@radicaltools/mcp 0.3.0 → 0.3.2

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 (59) hide show
  1. package/README.md +7 -5
  2. package/dist/{chunk-Z7THA3L5.js → chunk-KEIZXREX.js} +68 -35
  3. package/dist/{elkLayout-TAUBPPVN.js → elkLayout-MFJXDTJG.js} +1 -1
  4. package/dist/hub-catalogue/concern/concern-api-collections.radical +1136 -0
  5. package/dist/hub-catalogue/concern/concern-api-errors.radical +1180 -0
  6. package/dist/hub-catalogue/concern/concern-api-evolution.radical +449 -210
  7. package/dist/hub-catalogue/concern/concern-api-idempotency.radical +1218 -0
  8. package/dist/hub-catalogue/concern/concern-api-resource-design.radical +1102 -0
  9. package/dist/hub-catalogue/concern/concern-api-style-guide.radical +1210 -0
  10. package/dist/hub-catalogue/concern/concern-architecture-style.radical +287 -131
  11. package/dist/hub-catalogue/concern/concern-audit-trail.radical +1096 -0
  12. package/dist/hub-catalogue/concern/concern-authentication.radical +247 -37
  13. package/dist/hub-catalogue/concern/concern-authorization.radical +311 -89
  14. package/dist/hub-catalogue/concern/concern-availability.radical +287 -63
  15. package/dist/hub-catalogue/concern/concern-backend-stack.radical +300 -381
  16. package/dist/hub-catalogue/concern/concern-backup-recovery.radical +385 -129
  17. package/dist/hub-catalogue/concern/concern-caching.radical +1294 -0
  18. package/dist/hub-catalogue/concern/concern-capacity.radical +194 -81
  19. package/dist/hub-catalogue/concern/concern-code-documentation.radical +1397 -0
  20. package/dist/hub-catalogue/concern/concern-code-quality-gate.radical +1409 -0
  21. package/dist/hub-catalogue/concern/concern-code-review-branching.radical +1416 -0
  22. package/dist/hub-catalogue/concern/concern-code-style.radical +1058 -0
  23. package/dist/hub-catalogue/concern/concern-communication-style.radical +473 -167
  24. package/dist/hub-catalogue/concern/concern-data-classification.radical +970 -0
  25. package/dist/hub-catalogue/concern/concern-data-consistency.radical +339 -308
  26. package/dist/hub-catalogue/concern/concern-data-store.radical +480 -158
  27. package/dist/hub-catalogue/concern/concern-decomposition.radical +260 -85
  28. package/dist/hub-catalogue/concern/concern-definition-of-done.radical +1214 -0
  29. package/dist/hub-catalogue/concern/concern-delivery-metrics.radical +966 -0
  30. package/dist/hub-catalogue/concern/concern-dependency-hygiene.radical +1345 -0
  31. package/dist/hub-catalogue/concern/concern-deployment.radical +343 -92
  32. package/dist/hub-catalogue/concern/concern-encryption.radical +339 -76
  33. package/dist/hub-catalogue/concern/concern-error-handling-logging.radical +1197 -0
  34. package/dist/hub-catalogue/concern/concern-eu-dora.radical +1321 -0
  35. package/dist/hub-catalogue/concern/concern-frontend-stack.radical +467 -160
  36. package/dist/hub-catalogue/concern/concern-incident-management.radical +1204 -0
  37. package/dist/hub-catalogue/concern/concern-infrastructure.radical +1300 -268
  38. package/dist/hub-catalogue/concern/concern-integration-resilience.radical +88 -51
  39. package/dist/hub-catalogue/concern/concern-messaging.radical +173 -140
  40. package/dist/hub-catalogue/concern/concern-module-boundaries.radical +162 -159
  41. package/dist/hub-catalogue/concern/concern-observability.radical +224 -275
  42. package/dist/hub-catalogue/concern/concern-operational-readiness.radical +1249 -0
  43. package/dist/hub-catalogue/concern/concern-personal-data.radical +637 -122
  44. package/dist/hub-catalogue/concern/concern-quality-priorities.radical +1091 -0
  45. package/dist/hub-catalogue/concern/concern-rate-limiting.radical +433 -141
  46. package/dist/hub-catalogue/concern/concern-release-versioning.radical +1358 -0
  47. package/dist/hub-catalogue/concern/concern-retention.radical +1399 -0
  48. package/dist/hub-catalogue/concern/concern-secrets.radical +332 -74
  49. package/dist/hub-catalogue/concern/concern-secure-coding.radical +1379 -0
  50. package/dist/hub-catalogue/concern/concern-secure-development.radical +1245 -0
  51. package/dist/hub-catalogue/concern/concern-security-detection.radical +1153 -0
  52. package/dist/hub-catalogue/concern/concern-supply-chain.radical +257 -183
  53. package/dist/hub-catalogue/concern/concern-technical-debt.radical +1450 -0
  54. package/dist/hub-catalogue/concern/concern-technology-lifecycle.radical +1145 -0
  55. package/dist/hub-catalogue/concern/concern-tenant-isolation.radical +271 -137
  56. package/dist/hub-catalogue/concern/concern-test-strategy.radical +243 -224
  57. package/dist/hub-catalogue/concern/concern-threat-modelling.radical +1143 -0
  58. package/dist/index.js +1893 -468
  59. 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-KEIZXREX.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;
@@ -4961,181 +4966,13 @@ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
4961
4966
 
4962
4967
  // src/folderModel.ts
4963
4968
  init_define_RADICAL_BUILD();
4964
- import { mkdir as mkdir4, readdir as readdir2, realpath, stat as stat3 } from "fs/promises";
4965
- import { basename, resolve as resolve4 } from "path";
4969
+ import { mkdir as mkdir4, readFile as readFile5, readdir as readdir3, realpath, stat as stat4, writeFile as writeFile4 } from "fs/promises";
4970
+ import { basename as basename2, dirname as dirname6, isAbsolute, join as join7, relative as relative2, resolve as resolve5 } from "path";
4966
4971
  import { createHash } from "crypto";
4967
4972
 
4968
4973
  // ../../packages/common/src/ai/tools/index.ts
4969
4974
  init_define_RADICAL_BUILD();
4970
4975
 
4971
- // ../../packages/common/src/ai/tools/layoutTools.ts
4972
- init_define_RADICAL_BUILD();
4973
-
4974
- // ../../packages/common/src/ai/tools/types.ts
4975
- init_define_RADICAL_BUILD();
4976
- function fail(resultText) {
4977
- return { ok: false, resultText };
4978
- }
4979
- function sequenceStepCount(ctx) {
4980
- return Object.values(ctx.diagram.getSequences?.() ?? {}).reduce((n, q) => n + q.relationIds.length, 0);
4981
- }
4982
- var stepsGone = (n) => n > 0 ? ` and ${n} sequence step${n === 1 ? "" : "s"} along its relation${n === 1 ? "" : "s"}` : "";
4983
-
4984
- // ../../packages/common/src/ai/tools/layoutTools.ts
4985
- var AXIS_ENUM = ["horizontal", "vertical"];
4986
- function noCanvasLayout(tool, view) {
4987
- if (!view.kind || view.kind === "static") return null;
4988
- if (view.kind === "explore") return `${tool}: "${view.name}" is an explore view, laid out by Studio level by level from its start element; only static views have a canvas layout`;
4989
- return `${tool}: "${view.name}" is a ${view.kind} view; only static views have a canvas layout${view.kind === "dynamic" ? " (a dynamic view plays its sequence, drawn in order, with no positions of its own)" : ""}`;
4990
- }
4991
- function canvasFor(ctx, tool, raw, removing = false) {
4992
- if (raw === void 0) return { viewId: null };
4993
- if (typeof raw !== "string" || !raw) return { error: `${tool}: viewId must be a view id` };
4994
- const viewId = ctx.resolveId(raw);
4995
- const view = ctx.diagram.getViews?.()[viewId];
4996
- if (!view) return { error: `${tool}: unknown view id "${raw}"` };
4997
- const refused = removing ? null : noCanvasLayout(tool, view);
4998
- if (refused) return { error: refused };
4999
- return { viewId };
5000
- }
5001
- var describeConstraint = (c) => c.type === "grid" ? `${c.id} (grid of ${c.columns} columns: ${c.nodeIds.join(", ")})` : c.type === "pin" ? `${c.id} (pinned where they stand: ${c.nodeIds.join(", ")})` : `${c.id} (${c.axis === "horizontal" ? "row" : "column"}${c.ordered ? " in order" : ""}: ${c.nodeIds.join(", ")})`;
5002
- function buildLayoutToolDefs() {
5003
- return [
5004
- {
5005
- name: "smart_layout",
5006
- description: "Run Smart Layout and keep the new positions and container sizes. Without viewId it arranges the All elements canvas; with the id of a static view it arranges that view's own positions (a dynamic view plays its sequence and has no canvas layout, nor has a table, wiki or other kind); a view whose layout mode is a hierarchical nested tree is laid out as a tree, as Studio does. Alignments and grids hold; the canvas's pins (elements a Studio user dropped after a drag) are removed, since every element gets a new place. A large view gets as much work as one Smart Layout in Studio, the same layout, and the result says 'run it again for more' when more would help. Call it after adding or moving several nodes.",
5007
- inputSchema: {
5008
- type: "object",
5009
- properties: {
5010
- viewId: { type: "string", description: "A static view (real id or tempId); omit for All elements." },
5011
- around: { type: "array", items: { type: "string" }, description: "Tidy round these elements only (ids or tempIds): they and what they relate to move, every other element stays where it is. For an element just added among others that stand well." }
5012
- },
5013
- additionalProperties: false
5014
- }
5015
- },
5016
- {
5017
- name: "align_nodes",
5018
- description: "Keep two or more elements on one line on a canvas: a row (axis 'horizontal', equal centre y) or a column (axis 'vertical', equal centre x). Every later layout keeps it: drags and the live physics in Studio, Smart Layout. Without viewId it applies to the All elements canvas; with the id of a static view, to that view only (other kinds have no canvas). Elements hidden on the canvas are skipped until shown. Studio lines them up when it shows the canvas; smart_layout does too.",
5019
- inputSchema: {
5020
- type: "object",
5021
- properties: {
5022
- nodeIds: { type: "array", items: { type: "string" }, description: "Two or more node ids or tempIds; none inside another. With keepOrder, listed left to right (row) or top to bottom (column)." },
5023
- axis: { type: "string", enum: [...AXIS_ENUM], description: "'horizontal' = a row, 'vertical' = a column." },
5024
- keepOrder: { type: "boolean", description: "Also keep the elements in the order of nodeIds along the line; no layout may swap them." },
5025
- viewId: { type: "string", description: "A static view (real id or tempId); omit for All elements." }
5026
- },
5027
- required: ["nodeIds", "axis"],
5028
- additionalProperties: false
5029
- }
5030
- },
5031
- {
5032
- name: "grid_nodes",
5033
- description: "Keep elements in a grid on a canvas: `columns` columns, filled row by row in the order of nodeIds (left to right, then the next row). Every row stays a row and every column a column, in that order, through every later layout. Without viewId it applies to the All elements canvas; with the id of a static view, to that view only (other kinds have no canvas). Studio arranges them when it shows the canvas; smart_layout keeps the grid. Remove it with remove_alignment.",
5034
- inputSchema: {
5035
- type: "object",
5036
- properties: {
5037
- nodeIds: { type: "array", items: { type: "string" }, description: "Two or more node ids or tempIds, in reading order; none inside another." },
5038
- columns: { type: "number", description: "Columns of the grid. Defaults to the smallest that makes it about square (ceil of the square root of the count)." },
5039
- viewId: { type: "string", description: "A static view (real id or tempId); omit for All elements." }
5040
- },
5041
- required: ["nodeIds"],
5042
- additionalProperties: false
5043
- }
5044
- },
5045
- {
5046
- name: "remove_alignment",
5047
- description: "Stop keeping elements aligned on a canvas: remove one alignment or grid by id, or every alignment and grid whose elements are all among nodeIds. The positions stay as they are. The id of a canvas's pin (the elements a Studio user dropped after a drag, kept still by the live physics) unpins them all.",
5048
- inputSchema: {
5049
- type: "object",
5050
- properties: {
5051
- id: { type: "string", description: "Alignment id, as align_nodes returned it." },
5052
- nodeIds: { type: "array", items: { type: "string" }, description: "Removes the alignments made only of these elements." },
5053
- viewId: { type: "string", description: "The view (real id or tempId); omit for All elements. Also a view of another kind than static, to remove what was written there before." }
5054
- },
5055
- additionalProperties: false
5056
- }
5057
- }
5058
- ];
5059
- }
5060
- function buildAlignmentToolHandlers() {
5061
- return {
5062
- align_nodes: (rawInput, ctx) => {
5063
- const input = rawInput ?? {};
5064
- if (!ctx.diagram.addAlignment) return fail("align_nodes: alignments are not editable in this context");
5065
- if (input.keepOrder !== void 0 && typeof input.keepOrder !== "boolean") return fail("align_nodes: keepOrder must be true or false");
5066
- if (!Array.isArray(input.nodeIds) || input.nodeIds.some((id) => typeof id !== "string")) return fail("align_nodes: nodeIds must be an array of node ids");
5067
- if (!AXIS_ENUM.includes(input.axis)) return fail(`align_nodes: axis must be 'horizontal' or 'vertical'`);
5068
- const canvas2 = canvasFor(ctx, "align_nodes", input.viewId);
5069
- if ("error" in canvas2) return fail(canvas2.error);
5070
- const nodeIds = input.nodeIds.map((id) => ctx.resolveId(id));
5071
- const added = ctx.diagram.addAlignment(canvas2.viewId, input.axis, nodeIds, input.keepOrder === true);
5072
- if ("error" in added) return fail(`align_nodes: ${added.error}`);
5073
- const order = input.keepOrder === true ? ", in the order given" : "";
5074
- return { ok: true, resultText: `Aligned ${nodeIds.length} elements in a ${input.axis === "horizontal" ? "row" : "column"}${order}. Alignment ID: ${added.id}.`, updated: { views: 1 } };
5075
- },
5076
- grid_nodes: (rawInput, ctx) => {
5077
- const input = rawInput ?? {};
5078
- if (!ctx.diagram.addGrid) return fail("grid_nodes: grids are not editable in this context");
5079
- if (!Array.isArray(input.nodeIds) || input.nodeIds.some((id) => typeof id !== "string")) return fail("grid_nodes: nodeIds must be an array of node ids");
5080
- if (input.columns !== void 0 && (typeof input.columns !== "number" || !Number.isInteger(input.columns) || input.columns < 1)) return fail("grid_nodes: columns must be a whole number, at least 1");
5081
- const canvas2 = canvasFor(ctx, "grid_nodes", input.viewId);
5082
- if ("error" in canvas2) return fail(canvas2.error);
5083
- const nodeIds = input.nodeIds.map((id) => ctx.resolveId(id));
5084
- const columns = input.columns ?? defaultGridColumns(nodeIds.length);
5085
- const added = ctx.diagram.addGrid(canvas2.viewId, nodeIds, columns);
5086
- if ("error" in added) return fail(`grid_nodes: ${added.error}`);
5087
- return { ok: true, resultText: `Kept ${nodeIds.length} elements in a grid of ${columns} columns. Alignment ID: ${added.id}.`, updated: { views: 1 } };
5088
- },
5089
- remove_alignment: (rawInput, ctx) => {
5090
- const input = rawInput ?? {};
5091
- if (!ctx.diagram.getLayoutConstraints || !ctx.diagram.removeLayoutConstraints) return fail("remove_alignment: alignments are not editable in this context");
5092
- if (input.id === void 0 && input.nodeIds === void 0) return fail("remove_alignment: pass id or nodeIds");
5093
- if (input.id !== void 0 && (typeof input.id !== "string" || !input.id)) return fail("remove_alignment: id must be an alignment id");
5094
- if (input.nodeIds !== void 0 && (!Array.isArray(input.nodeIds) || input.nodeIds.some((id) => typeof id !== "string"))) return fail("remove_alignment: nodeIds must be an array of node ids");
5095
- const canvas2 = canvasFor(ctx, "remove_alignment", input.viewId, true);
5096
- if ("error" in canvas2) return fail(canvas2.error);
5097
- const among = input.nodeIds ? new Set(input.nodeIds.map((id) => ctx.resolveId(id))) : null;
5098
- const matches = ctx.diagram.getLayoutConstraints(canvas2.viewId).filter((c) => (input.id === void 0 ? c.type !== "pin" : c.id === input.id) && (!among || c.nodeIds.every((id) => among.has(id))));
5099
- if (!matches.length) {
5100
- const existing = ctx.diagram.getLayoutConstraints(canvas2.viewId);
5101
- return fail(`remove_alignment: no such alignment on this canvas.${existing.length ? ` It has: ${existing.map(describeConstraint).join("; ")}.` : " It has none."}`);
5102
- }
5103
- ctx.diagram.removeLayoutConstraints(canvas2.viewId, matches.map((c) => c.id));
5104
- return { ok: true, resultText: `Removed ${matches.map(describeConstraint).join("; ")}.`, updated: { views: 1 } };
5105
- }
5106
- };
5107
- }
5108
- function buildLayoutToolHandlers() {
5109
- return {
5110
- smart_layout: async (rawInput, ctx) => {
5111
- const input = rawInput ?? {};
5112
- if (!ctx.diagram.runLayout) return fail("smart_layout: layout is not available in this context");
5113
- let around;
5114
- if (input.around !== void 0) {
5115
- if (!Array.isArray(input.around) || !input.around.every((id) => typeof id === "string" && id)) return fail("smart_layout: around must be an array of node ids");
5116
- around = input.around.map((id) => ctx.resolveId(id));
5117
- const nodes = ctx.diagram.getNodes();
5118
- const unknown = around.filter((id) => !nodes[id]);
5119
- if (unknown.length) return fail(`smart_layout: unknown node id(s) ${unknown.join(", ")}`);
5120
- }
5121
- if (input.viewId !== void 0 && (typeof input.viewId !== "string" || !input.viewId)) return fail("smart_layout: viewId must be a view id");
5122
- let viewId;
5123
- if (typeof input.viewId === "string") {
5124
- viewId = ctx.resolveId(input.viewId);
5125
- const view = ctx.diagram.getViews?.()[viewId];
5126
- if (!view) return fail(`smart_layout: unknown view id "${input.viewId}"`);
5127
- const refused = noCanvasLayout("smart_layout", view);
5128
- if (refused) return fail(refused);
5129
- }
5130
- const outcome = await ctx.diagram.runLayout(viewId, around);
5131
- return { ok: outcome.ok, resultText: outcome.text };
5132
- }
5133
- };
5134
- }
5135
-
5136
- // ../../packages/common/src/ai/tools/metamodelTools.ts
5137
- init_define_RADICAL_BUILD();
5138
-
5139
4976
  // ../../packages/common/src/model.ts
5140
4977
  init_define_RADICAL_BUILD();
5141
4978
 
@@ -5237,7 +5074,7 @@ function relationIndex(ctx) {
5237
5074
  if (own) return own;
5238
5075
  const cacheable = Object.isFrozen(ctx.relations) && Object.isFrozen(ctx.nodes);
5239
5076
  const cached = cacheable ? indexCache.get(ctx.relations) : void 0;
5240
- if (cached && cached.nodes === ctx.nodes) {
5077
+ if (cached && sameForChain(cached.nodes, ctx.nodes, "parentId")) {
5241
5078
  ctxIndex.set(ctx, cached.index);
5242
5079
  return cached.index;
5243
5080
  }
@@ -5370,8 +5207,15 @@ function ofTypes(way, n) {
5370
5207
  function followWay(node, way, ctx) {
5371
5208
  return way.via ? followVia(node, way.via, ctx).filter((n) => ofTypes(way, n)) : [];
5372
5209
  }
5210
+ function nodeList(nodes) {
5211
+ if (!Object.isFrozen(nodes)) return Object.values(nodes);
5212
+ let list = nodeLists.get(nodes);
5213
+ if (!list) nodeLists.set(nodes, list = Object.freeze(Object.values(nodes)));
5214
+ return list;
5215
+ }
5216
+ var nodeLists = /* @__PURE__ */ new WeakMap();
5373
5217
  function pipelineSource(view, ctx) {
5374
- const all = Object.values(ctx.nodes);
5218
+ const all = nodeList(ctx.nodes);
5375
5219
  if (!view || viewShowsEveryNode(view)) return all;
5376
5220
  const ids = new Set(view.nodeIds);
5377
5221
  return all.filter((n) => ids.has(n.id));
@@ -5462,16 +5306,136 @@ function viewShownNodes(view, nodes, relations) {
5462
5306
  const cacheable = Object.isFrozen(nodes) && Object.isFrozen(relations) && Object.isFrozen(view.nodeIds);
5463
5307
  if (cacheable) {
5464
5308
  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;
5309
+ 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
5310
  }
5467
- const shown = computeShownNodes(view, nodes, relations);
5311
+ let shown;
5312
+ if (view.originScope) {
5313
+ const [scoped, scopedRelations] = scopedTo(view.originScope, nodes, relations);
5314
+ shown = computeShownNodes(view, scoped, scopedRelations) ?? new Set(Object.keys(scoped));
5315
+ } else shown = computeShownNodes(view, nodes, relations);
5468
5316
  if (cacheable) shownCache.set(view.nodeIds, { nodes, relations, pipeline: view.pipeline, kind: view.kind, empty: view.empty, shown });
5469
5317
  return shown;
5470
5318
  }
5319
+ function scopedTo(scope, nodes, relations) {
5320
+ const inScope = (item) => !!item.origin && scope.includes(item.origin.slice(0, item.origin.lastIndexOf("@")));
5321
+ return [
5322
+ Object.fromEntries(Object.entries(nodes).filter(([, n]) => inScope(n))),
5323
+ Object.fromEntries(Object.entries(relations).filter(([, r]) => inScope(r)))
5324
+ ];
5325
+ }
5471
5326
  var shownCache = /* @__PURE__ */ new WeakMap();
5327
+ function chainKeys(pipeline) {
5328
+ if (!pipeline || typeof pipeline !== "object") return BASE_KEYS;
5329
+ const known = keysOfChain.get(pipeline);
5330
+ if (known) return known;
5331
+ const keys = new Set(BASE_KEYS.split(","));
5332
+ const walk = (v) => {
5333
+ if (Array.isArray(v)) {
5334
+ v.forEach(walk);
5335
+ return;
5336
+ }
5337
+ if (!v || typeof v !== "object") return;
5338
+ const o = v;
5339
+ if (o.kind === "text") for (const k of ["label", "description", "technology"]) keys.add(k);
5340
+ if (o.kind === "property" && typeof o.key === "string") keys.add(o.key);
5341
+ Object.values(o).forEach(walk);
5342
+ };
5343
+ walk(pipeline);
5344
+ const out = [...keys].join(",");
5345
+ keysOfChain.set(pipeline, out);
5346
+ return out;
5347
+ }
5348
+ var BASE_KEYS = "type,parentId";
5349
+ var keysOfChain = /* @__PURE__ */ new WeakMap();
5350
+ function sameForChain(a, b, keys) {
5351
+ if (a === b) return true;
5352
+ let byB = sameAnswers.get(a);
5353
+ if (!byB) sameAnswers.set(a, byB = /* @__PURE__ */ new WeakMap());
5354
+ let byKeys = byB.get(b);
5355
+ if (!byKeys) byB.set(b, byKeys = /* @__PURE__ */ new Map());
5356
+ const hit = byKeys.get(keys);
5357
+ if (hit !== void 0) return hit;
5358
+ const same3 = compareFor(a, b, keys.split(","));
5359
+ byKeys.set(keys, same3);
5360
+ return same3;
5361
+ }
5362
+ var sameAnswers = /* @__PURE__ */ new WeakMap();
5363
+ function compareFor(a, b, keys) {
5364
+ const listA = nodeList(a);
5365
+ const listB = nodeList(b);
5366
+ if (listA.length !== listB.length) return false;
5367
+ for (const y of listB) {
5368
+ const x = a[y.id];
5369
+ if (x === y) continue;
5370
+ if (!x || keys.some((k) => x[k] !== y[k])) return false;
5371
+ }
5372
+ return true;
5373
+ }
5374
+ function hash2(text2) {
5375
+ let a = 2166136261;
5376
+ let b = 16777619 ^ 1540483477;
5377
+ for (let i = 0; i < text2.length; i++) {
5378
+ const c = text2.charCodeAt(i);
5379
+ a = Math.imul(a ^ c, 16777619);
5380
+ b = Math.imul(b ^ c, 1540483477);
5381
+ }
5382
+ return [a >>> 0, b >>> 0];
5383
+ }
5384
+ var structures = /* @__PURE__ */ new WeakMap();
5385
+ function modelStructure(nodes, relations) {
5386
+ const known = structures.get(nodes)?.get(relations);
5387
+ if (known) return known;
5388
+ let n = 0, a = 0, b = 0, r = 0, c = 0, d = 0;
5389
+ for (const node of Object.values(nodes)) {
5390
+ const [x, y] = hash2(`${node.id}${node.type}${node.parentId ?? ""}`);
5391
+ a = a + x | 0;
5392
+ b = b + y | 0;
5393
+ n++;
5394
+ }
5395
+ for (const rel of Array.isArray(relations) ? relations : Object.values(relations)) {
5396
+ const [x, y] = hash2(`${rel.id}${rel.sourceId}${rel.targetId}${rel.relationType ?? ""}`);
5397
+ c = c + x | 0;
5398
+ d = d + y | 0;
5399
+ r++;
5400
+ }
5401
+ const out = `${n}.${a >>> 0}.${b >>> 0}:${r}.${c >>> 0}.${d >>> 0}`;
5402
+ if (Object.isFrozen(nodes) && Object.isFrozen(relations)) {
5403
+ let byRelations = structures.get(nodes);
5404
+ if (!byRelations) structures.set(nodes, byRelations = /* @__PURE__ */ new WeakMap());
5405
+ byRelations.set(relations, out);
5406
+ }
5407
+ return out;
5408
+ }
5409
+ var indexKeys = /* @__PURE__ */ new WeakMap();
5410
+ function viewIndexKey(view) {
5411
+ const known = indexKeys.get(view);
5412
+ if (known !== void 0) return known;
5413
+ const pipeline = pipelineOf(view);
5414
+ 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(".");
5415
+ indexKeys.set(view, key);
5416
+ return key;
5417
+ }
5418
+ var preset = null;
5419
+ function fromViewIndex(view, nodes, relations) {
5420
+ if (!preset || preset.off) return void 0;
5421
+ const key = viewIndexKey(view);
5422
+ const list = key ? preset.index.views[key] : void 0;
5423
+ if (!list) return void 0;
5424
+ const fits = preset.fits;
5425
+ if (!(fits && fits.relations === relations && sameForChain(fits.nodes, nodes, BASE_KEYS))) {
5426
+ if (!Object.isFrozen(nodes) || !Object.isFrozen(relations)) return void 0;
5427
+ if (modelStructure(nodes, relations) !== preset.index.structure) {
5428
+ preset.off = true;
5429
+ return void 0;
5430
+ }
5431
+ preset.fits = { nodes, relations };
5432
+ }
5433
+ const ids = preset.index.ids;
5434
+ return new Set(list.map((i) => ids[i]));
5435
+ }
5472
5436
  function computeShownNodes(view, nodes, relations) {
5473
5437
  if (pipelineOf(view)?.levels?.length && view.kind !== "dynamic") {
5474
- return new Set(runPipeline(view, { nodes, relations, metamodel: NO_METAMODEL }).nodes.map((n) => n.id));
5438
+ return fromViewIndex(view, nodes, relations) ?? new Set(runPipeline(view, { nodes, relations, metamodel: NO_METAMODEL }).nodes.map((n) => n.id));
5475
5439
  }
5476
5440
  if (viewShowsEveryNode(view)) return void 0;
5477
5441
  return new Set(view.nodeIds.filter((id) => id in nodes));
@@ -5579,28 +5543,28 @@ function documentMetamodel(stored, nodes) {
5579
5543
  const c4 = builtInC4Metamodel();
5580
5544
  return nodes?.some((n) => !c4.nodeTypes[n.type]) ? builtInGovernanceMetamodel() : c4;
5581
5545
  }
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");
5546
+ const preset2 = stored.id === "c4-builtin" ? builtInC4Metamodel() : stored.id === "c4-ddd-builtin" || stored.id === "c4-ddd-governance-builtin" ? builtInGovernanceMetamodel() : null;
5547
+ if (!preset2) return stored;
5548
+ const withViewpoints = withPresetViewpoints(preset2, stored);
5549
+ const extraNodeTypes = Object.entries(stored.nodeTypes ?? {}).filter(([id, def]) => !preset2.nodeTypes[id] && def && typeof def === "object");
5550
+ const extraRelationTypes = Object.entries(stored.relationTypes ?? {}).filter(([id, def]) => !preset2.relationTypes[id] && def && typeof def === "object");
5587
5551
  if (!extraNodeTypes.length && !extraRelationTypes.length) return withViewpoints;
5588
- const custom = forkPresetMetamodel({ ...withViewpoints, id: preset.id }) ?? withViewpoints;
5552
+ const custom = forkPresetMetamodel({ ...withViewpoints, id: preset2.id }) ?? withViewpoints;
5589
5553
  return {
5590
5554
  ...custom,
5591
5555
  nodeTypes: { ...custom.nodeTypes, ...Object.fromEntries(extraNodeTypes) },
5592
5556
  relationTypes: { ...custom.relationTypes, ...Object.fromEntries(extraRelationTypes) }
5593
5557
  };
5594
5558
  }
5595
- function withPresetViewpoints(preset, stored) {
5559
+ function withPresetViewpoints(preset2, stored) {
5596
5560
  const own = Array.isArray(stored.viewpoints) ? stored.viewpoints : [];
5597
5561
  const removed = new Set(Array.isArray(stored.removedViewpoints) ? stored.removedViewpoints : []);
5598
- if (!own.length && !removed.size) return preset;
5562
+ if (!own.length && !removed.size) return preset2;
5599
5563
  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));
5564
+ const fromPreset = (preset2.viewpoints ?? []).filter((v) => !removed.has(v.id)).map((v) => byId4.get(v.id) ?? v);
5565
+ const presetIds = new Set((preset2.viewpoints ?? []).map((v) => v.id));
5602
5566
  const viewpoints = [...fromPreset, ...own.filter((v) => !presetIds.has(v.id))];
5603
- return { ...preset, viewpoints, ...removed.size ? { removedViewpoints: [...removed] } : {} };
5567
+ return { ...preset2, viewpoints, ...removed.size ? { removedViewpoints: [...removed] } : {} };
5604
5568
  }
5605
5569
  var PRESET_IDS = /* @__PURE__ */ new Set(["c4-builtin", "c4-ddd-governance-builtin"]);
5606
5570
  function forkPresetMetamodel(mm) {
@@ -5608,7 +5572,10 @@ function forkPresetMetamodel(mm) {
5608
5572
  const copy = JSON.parse(JSON.stringify(mm));
5609
5573
  return { ...copy, id: `${mm.id.replace(/-builtin$/, "")}-custom`, name: `${mm.name} (custom)` };
5610
5574
  }
5611
- function descendantIds(id, nodes) {
5575
+ function childrenByParent(nodes) {
5576
+ const frozen = Object.isFrozen(nodes);
5577
+ const known = frozen ? childrenCache.get(nodes) : void 0;
5578
+ if (known) return known;
5612
5579
  const children2 = /* @__PURE__ */ new Map();
5613
5580
  for (const n of Object.values(nodes)) {
5614
5581
  if (!n.parentId) continue;
@@ -5616,6 +5583,12 @@ function descendantIds(id, nodes) {
5616
5583
  if (list) list.push(n.id);
5617
5584
  else children2.set(n.parentId, [n.id]);
5618
5585
  }
5586
+ if (frozen) childrenCache.set(nodes, children2);
5587
+ return children2;
5588
+ }
5589
+ var childrenCache = /* @__PURE__ */ new WeakMap();
5590
+ function descendantIds(id, nodes) {
5591
+ const children2 = childrenByParent(nodes);
5619
5592
  const out = [];
5620
5593
  const stack = [...children2.get(id) ?? []];
5621
5594
  while (stack.length) {
@@ -5663,6 +5636,79 @@ function materializeDefaults(node, mm) {
5663
5636
  if (p.default !== void 0 && node[p.key] === void 0) node[p.key] = p.default;
5664
5637
  }
5665
5638
  }
5639
+ function originOf(item) {
5640
+ return typeof item?.origin === "string" && item.origin ? item.origin : void 0;
5641
+ }
5642
+ function ownModel(data) {
5643
+ const own = (items) => Object.fromEntries(Object.entries(items).filter(([, item]) => !originOf(item)));
5644
+ const theirs = data.nodes.some((n) => originOf(n)) || data.relations.some((r) => originOf(r)) || (data.views ?? []).some((v) => originOf(v)) || (data.snapshots ?? []).some((s) => Object.values(s.nodes).some((n) => originOf(n)) || Object.values(s.relations).some((r) => originOf(r))) || (data.presentations ?? []).some((p) => p.slides.some((sl) => sl.modelSnapshot && (Object.values(sl.modelSnapshot.nodes).some((n) => originOf(n)) || Object.values(sl.modelSnapshot.relations).some((r) => originOf(r)))));
5645
+ if ("federation" in data) {
5646
+ const { federation: _fetched, ...rest } = data;
5647
+ return ownModel(rest);
5648
+ }
5649
+ if (!theirs) return data;
5650
+ return {
5651
+ ...data,
5652
+ nodes: data.nodes.filter((n) => !originOf(n)),
5653
+ relations: data.relations.filter((r) => !originOf(r)),
5654
+ ...data.views ? { views: data.views.filter((v) => !originOf(v)) } : {},
5655
+ ...data.snapshots ? { snapshots: data.snapshots.map((s) => ({ ...s, nodes: own(s.nodes), relations: own(s.relations) })) } : {},
5656
+ // A slide's own copy of the model, as a milestone.
5657
+ ...data.presentations ? { presentations: data.presentations.map((p) => ({ ...p, slides: p.slides.map((sl) => sl.modelSnapshot ? { ...sl, modelSnapshot: { ...sl.modelSnapshot, nodes: own(sl.modelSnapshot.nodes), relations: own(sl.modelSnapshot.relations) } } : sl) })) } : {}
5658
+ };
5659
+ }
5660
+ function viewRefusal(view) {
5661
+ const origin = originOf(view);
5662
+ return view && origin ? readOnlyError(`The view "${view.name}"`, origin).replace(/\.$/, ", or copy it into this model to change the copy.") : null;
5663
+ }
5664
+ function otherModelFolder(views, folder) {
5665
+ const root2 = normalizeViewFolder(folder).split("/")[0];
5666
+ if (!root2) return void 0;
5667
+ for (const view of Object.values(views)) {
5668
+ const origin = originOf(view);
5669
+ if (origin && originModel(origin) === root2) return origin;
5670
+ }
5671
+ return void 0;
5672
+ }
5673
+ function viewFolderRefusal(views, folder) {
5674
+ const origin = otherModelFolder(views, folder);
5675
+ return origin ? `The folder "${normalizeViewFolder(folder)}" holds the views of the model ${originModel(origin)} (${origin}), read-only: put the view in a folder of this model.` : null;
5676
+ }
5677
+ function originModel(origin) {
5678
+ const at = origin.lastIndexOf("@");
5679
+ return at > 0 ? origin.slice(0, at) : origin;
5680
+ }
5681
+ var LAYOUT_FIELDS = /* @__PURE__ */ new Set(["x", "y", "width", "height", "collapsed"]);
5682
+ function readOnlyError(what, origin) {
5683
+ return `${what} belongs to the model ${originModel(origin)} (${origin}): change it in that model's repository.`;
5684
+ }
5685
+ function nodeReadOnly(node) {
5686
+ const origin = originOf(node);
5687
+ return node && origin ? readOnlyError(`"${node.label}"`, origin) : null;
5688
+ }
5689
+ function relationReadOnly(state, rel) {
5690
+ const origin = originOf(rel);
5691
+ if (!rel || !origin) return null;
5692
+ const name = (id) => state.c4Nodes[id]?.label ?? id;
5693
+ return readOnlyError(`The relation "${name(rel.sourceId)}" \u2192 "${name(rel.targetId)}"`, origin);
5694
+ }
5695
+ function parentReadOnly(parent) {
5696
+ const origin = originOf(parent);
5697
+ return parent && origin ? `Cannot put anything inside "${parent.label}": it belongs to the model ${originModel(origin)} (${origin}).` : null;
5698
+ }
5699
+ function checkRemove(state, nodeIds, relationIds = []) {
5700
+ const removed = new Set(nodeIds.filter((id) => state.c4Nodes[id]).flatMap((id) => [id, ...descendantIds(id, state.c4Nodes)]));
5701
+ for (const id of removed) {
5702
+ const refused = nodeReadOnly(state.c4Nodes[id]);
5703
+ if (refused) return refused;
5704
+ }
5705
+ for (const rel of Object.values(state.c4Relations)) {
5706
+ if (!relationIds.includes(rel.id) && !removed.has(rel.sourceId) && !removed.has(rel.targetId)) continue;
5707
+ const refused = relationReadOnly(state, rel);
5708
+ if (refused) return refused;
5709
+ }
5710
+ return null;
5711
+ }
5666
5712
  function checkAddNode(state, node) {
5667
5713
  const mm = state.metamodel;
5668
5714
  const label = typeLabel3(mm, node.type);
@@ -5672,6 +5718,9 @@ function checkAddNode(state, node) {
5672
5718
  }
5673
5719
  const parent = node.parentId ? state.c4Nodes[node.parentId] : void 0;
5674
5720
  if (node.parentId && !parent) return `Cannot add ${label}: the element it was to go into no longer exists.`;
5721
+ const external = parentReadOnly(parent);
5722
+ if (external) return external;
5723
+ if (originOf(node)) return "An element's origin is set by radical federation, not by an edit.";
5675
5724
  if (!isPlacementAllowed(mm, node.type, parent, state.c4Nodes)) {
5676
5725
  return `Cannot place ${label} inside ${placementError(mm, node.type, parent, state.c4Nodes)}`;
5677
5726
  }
@@ -5695,6 +5744,13 @@ function insertNode(state, id, node) {
5695
5744
  function checkNodeUpdate(state, id, updates) {
5696
5745
  const existing = state.c4Nodes[id];
5697
5746
  if (!existing) return null;
5747
+ const record = existing;
5748
+ const changed = Object.entries(updates).filter(([key, value]) => record[key] !== value).map(([key]) => key);
5749
+ if (changed.some((key) => !LAYOUT_FIELDS.has(key))) {
5750
+ const external = nodeReadOnly(existing);
5751
+ if (external) return external;
5752
+ if (changed.includes("origin")) return "An element's origin is set by radical federation, not by an edit.";
5753
+ }
5698
5754
  if (!("parentId" in updates) && !("type" in updates) && !("kind" in updates)) return null;
5699
5755
  const newType = updates.type ?? existing.type;
5700
5756
  const newParentId = ("parentId" in updates ? updates.parentId : existing.parentId) ?? void 0;
@@ -5702,6 +5758,10 @@ function checkNodeUpdate(state, id, updates) {
5702
5758
  if ("parentId" in updates && newParentId && (newParentId === id || descendantIds(id, state.c4Nodes).includes(newParentId))) {
5703
5759
  return "Cannot move a node into itself or one of its descendants.";
5704
5760
  }
5761
+ if ("parentId" in updates && newParentId !== existing.parentId) {
5762
+ const external = parentReadOnly(parent);
5763
+ if (external) return external;
5764
+ }
5705
5765
  if (!isPlacementAllowed(state.metamodel, newType, parent, state.c4Nodes)) {
5706
5766
  return `Cannot move ${typeLabel3(state.metamodel, newType)} "${existing.label}" into ${placementError(state.metamodel, newType, parent, state.c4Nodes)}`;
5707
5767
  }
@@ -5758,6 +5818,12 @@ function checkReparent(state, ids, newParentId) {
5758
5818
  }
5759
5819
  const newParent = newParentId ? state.c4Nodes[newParentId] : void 0;
5760
5820
  if (newParentId && !newParent) return "Target parent no longer exists.";
5821
+ for (const n of nodes) {
5822
+ const external2 = nodeReadOnly(n);
5823
+ if (external2) return external2;
5824
+ }
5825
+ const external = parentReadOnly(newParent);
5826
+ if (external) return external;
5761
5827
  const moved = new Set(nodes.flatMap((n) => [n.id, ...descendantIds(n.id, state.c4Nodes)]));
5762
5828
  if (newParentId && moved.has(newParentId)) return "Cannot move a node into itself or one of its descendants.";
5763
5829
  if (newParent?.external && oldParentId !== newParentId) {
@@ -6122,6 +6188,7 @@ function metamodelWithoutNodeType(mm, typeId) {
6122
6188
  return next;
6123
6189
  }
6124
6190
  function checkAddRelation(state, rel) {
6191
+ if (originOf(rel)) return "A relation's origin is set by radical federation, not by an edit.";
6125
6192
  return relationRefusal(relationContext(state), rel);
6126
6193
  }
6127
6194
  var relationContext = (state) => ({ nodes: state.c4Nodes, relations: state.c4Relations, metamodel: state.metamodel });
@@ -6144,6 +6211,12 @@ function insertRelation(state, id, rel) {
6144
6211
  function checkPatchRelation(state, id, updates) {
6145
6212
  const rel = state.c4Relations[id];
6146
6213
  if (!rel) return null;
6214
+ const record = rel;
6215
+ if (Object.entries(updates).some(([key, value]) => record[key] !== value)) {
6216
+ const external = relationReadOnly(state, rel);
6217
+ if (external) return external;
6218
+ if ("origin" in updates && updates.origin !== rel.origin) return "A relation's origin is set by radical federation, not by an edit.";
6219
+ }
6147
6220
  const retyped = updates.relationType !== void 0 && updates.relationType !== rel.relationType;
6148
6221
  if (updates.sourceId === void 0 && updates.targetId === void 0 && !retyped) return null;
6149
6222
  return relationRefusal(relationContext(state), { ...rel, ...updates, relationType: retyped ? updates.relationType : void 0 }, id, rel.relationType);
@@ -6226,7 +6299,7 @@ function planViewGroups(state) {
6226
6299
  const groups = new Map(views.filter((v) => isViewGroup(v, state.metamodel)).map((v) => [v.id, v]));
6227
6300
  const members = /* @__PURE__ */ new Map();
6228
6301
  const refolder = [];
6229
- const rename = [];
6302
+ const rename2 = [];
6230
6303
  for (const v of views) {
6231
6304
  if (!v.partOf) continue;
6232
6305
  const group = groups.get(v.partOf);
@@ -6240,7 +6313,7 @@ function planViewGroups(state) {
6240
6313
  seen.add(node.id);
6241
6314
  members.set(v.partOf, seen);
6242
6315
  if ((v.folder ?? "") !== (group.folder ?? "")) refolder.push(v.id);
6243
- if (v.name !== subjectViewName(node, def)) rename.push(v.id);
6316
+ if (v.name !== subjectViewName(node, def)) rename2.push(v.id);
6244
6317
  }
6245
6318
  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
6319
  for (const group of groups.values()) {
@@ -6250,12 +6323,12 @@ function planViewGroups(state) {
6250
6323
  if (!node.external && canBeSubject(def, node) && !has.has(node.id)) add.push({ groupId: group.id, subjectId: node.id });
6251
6324
  }
6252
6325
  }
6253
- return { add, remove: remove2, refolder, unlist, rename };
6326
+ return { add, remove: remove2, refolder, unlist, rename: rename2 };
6254
6327
  }
6255
6328
  function syncViewGroups(state, newId) {
6256
- const { add, remove: remove2, refolder, unlist, rename } = planViewGroups(state);
6329
+ const { add, remove: remove2, refolder, unlist, rename: rename2 } = planViewGroups(state);
6257
6330
  for (const id of remove2) delete state.views[id];
6258
- for (const id of rename) {
6331
+ for (const id of rename2) {
6259
6332
  const view = state.views[id];
6260
6333
  const def = viewpointsOf(state.metamodel).find((t) => t.id === view.viewpoint);
6261
6334
  view.name = subjectViewName(state.c4Nodes[view.subject], def);
@@ -6286,7 +6359,7 @@ function syncViewGroups(state, newId) {
6286
6359
  else delete view.folder;
6287
6360
  }
6288
6361
  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;
6362
+ return add.length > 0 || remove2.length > 0 || refolder.length > 0 || unlist.length > 0 || rename2.length > 0;
6290
6363
  }
6291
6364
  function detachViewpoint(state, viewId) {
6292
6365
  const view = state.views[viewId];
@@ -6591,6 +6664,174 @@ function compareModels(before, after) {
6591
6664
  return { nodes: diff(before.nodes, after.nodes), relations: diff(before.relations, after.relations) };
6592
6665
  }
6593
6666
 
6667
+ // ../../packages/common/src/ai/tools/layoutTools.ts
6668
+ init_define_RADICAL_BUILD();
6669
+
6670
+ // ../../packages/common/src/ai/tools/types.ts
6671
+ init_define_RADICAL_BUILD();
6672
+ function fail(resultText) {
6673
+ return { ok: false, resultText };
6674
+ }
6675
+ function sequenceStepCount(ctx) {
6676
+ return Object.values(ctx.diagram.getSequences?.() ?? {}).reduce((n, q) => n + q.relationIds.length, 0);
6677
+ }
6678
+ var stepsGone = (n) => n > 0 ? ` and ${n} sequence step${n === 1 ? "" : "s"} along its relation${n === 1 ? "" : "s"}` : "";
6679
+
6680
+ // ../../packages/common/src/ai/tools/layoutTools.ts
6681
+ var AXIS_ENUM = ["horizontal", "vertical"];
6682
+ function noCanvasLayout(tool, view) {
6683
+ if (!view.kind || view.kind === "static") return null;
6684
+ if (view.kind === "explore") return `${tool}: "${view.name}" is an explore view, laid out by Studio level by level from its start element; only static views have a canvas layout`;
6685
+ return `${tool}: "${view.name}" is a ${view.kind} view; only static views have a canvas layout${view.kind === "dynamic" ? " (a dynamic view plays its sequence, drawn in order, with no positions of its own)" : ""}`;
6686
+ }
6687
+ function canvasFor(ctx, tool, raw, removing = false) {
6688
+ if (raw === void 0) return { viewId: null };
6689
+ if (typeof raw !== "string" || !raw) return { error: `${tool}: viewId must be a view id` };
6690
+ const viewId = ctx.resolveId(raw);
6691
+ const view = ctx.diagram.getViews?.()[viewId];
6692
+ if (!view) return { error: `${tool}: unknown view id "${raw}"` };
6693
+ const refused = removing ? null : noCanvasLayout(tool, view);
6694
+ if (refused) return { error: refused };
6695
+ return { viewId };
6696
+ }
6697
+ var describeConstraint = (c) => c.type === "grid" ? `${c.id} (grid of ${c.columns} columns: ${c.nodeIds.join(", ")})` : c.type === "pin" ? `${c.id} (pinned where they stand: ${c.nodeIds.join(", ")})` : `${c.id} (${c.axis === "horizontal" ? "row" : "column"}${c.ordered ? " in order" : ""}: ${c.nodeIds.join(", ")})`;
6698
+ function buildLayoutToolDefs() {
6699
+ return [
6700
+ {
6701
+ name: "smart_layout",
6702
+ description: "Run Smart Layout and keep the new positions and container sizes. Without viewId it arranges the All elements canvas; with the id of a static view it arranges that view's own positions (a dynamic view plays its sequence and has no canvas layout, nor has a table, wiki or other kind); a view whose layout mode is a hierarchical nested tree is laid out as a tree, as Studio does. Alignments and grids hold; the canvas's pins (elements a Studio user dropped after a drag) are removed, since every element gets a new place. A large view gets as much work as one Smart Layout in Studio, the same layout, and the result says 'run it again for more' when more would help. Call it after adding or moving several nodes.",
6703
+ inputSchema: {
6704
+ type: "object",
6705
+ properties: {
6706
+ viewId: { type: "string", description: "A static view (real id or tempId); omit for All elements." },
6707
+ around: { type: "array", items: { type: "string" }, description: "Tidy round these elements only (ids or tempIds): they and what they relate to move, every other element stays where it is. For an element just added among others that stand well." }
6708
+ },
6709
+ additionalProperties: false
6710
+ }
6711
+ },
6712
+ {
6713
+ name: "align_nodes",
6714
+ description: "Keep two or more elements on one line on a canvas: a row (axis 'horizontal', equal centre y) or a column (axis 'vertical', equal centre x). Every later layout keeps it: drags and the live physics in Studio, Smart Layout. Without viewId it applies to the All elements canvas; with the id of a static view, to that view only (other kinds have no canvas). Elements hidden on the canvas are skipped until shown. Studio lines them up when it shows the canvas; smart_layout does too.",
6715
+ inputSchema: {
6716
+ type: "object",
6717
+ properties: {
6718
+ nodeIds: { type: "array", items: { type: "string" }, description: "Two or more node ids or tempIds; none inside another. With keepOrder, listed left to right (row) or top to bottom (column)." },
6719
+ axis: { type: "string", enum: [...AXIS_ENUM], description: "'horizontal' = a row, 'vertical' = a column." },
6720
+ keepOrder: { type: "boolean", description: "Also keep the elements in the order of nodeIds along the line; no layout may swap them." },
6721
+ viewId: { type: "string", description: "A static view (real id or tempId); omit for All elements." }
6722
+ },
6723
+ required: ["nodeIds", "axis"],
6724
+ additionalProperties: false
6725
+ }
6726
+ },
6727
+ {
6728
+ name: "grid_nodes",
6729
+ description: "Keep elements in a grid on a canvas: `columns` columns, filled row by row in the order of nodeIds (left to right, then the next row). Every row stays a row and every column a column, in that order, through every later layout. Without viewId it applies to the All elements canvas; with the id of a static view, to that view only (other kinds have no canvas). Studio arranges them when it shows the canvas; smart_layout keeps the grid. Remove it with remove_alignment.",
6730
+ inputSchema: {
6731
+ type: "object",
6732
+ properties: {
6733
+ nodeIds: { type: "array", items: { type: "string" }, description: "Two or more node ids or tempIds, in reading order; none inside another." },
6734
+ columns: { type: "number", description: "Columns of the grid. Defaults to the smallest that makes it about square (ceil of the square root of the count)." },
6735
+ viewId: { type: "string", description: "A static view (real id or tempId); omit for All elements." }
6736
+ },
6737
+ required: ["nodeIds"],
6738
+ additionalProperties: false
6739
+ }
6740
+ },
6741
+ {
6742
+ name: "remove_alignment",
6743
+ description: "Stop keeping elements aligned on a canvas: remove one alignment or grid by id, or every alignment and grid whose elements are all among nodeIds. The positions stay as they are. The id of a canvas's pin (the elements a Studio user dropped after a drag, kept still by the live physics) unpins them all.",
6744
+ inputSchema: {
6745
+ type: "object",
6746
+ properties: {
6747
+ id: { type: "string", description: "Alignment id, as align_nodes returned it." },
6748
+ nodeIds: { type: "array", items: { type: "string" }, description: "Removes the alignments made only of these elements." },
6749
+ viewId: { type: "string", description: "The view (real id or tempId); omit for All elements. Also a view of another kind than static, to remove what was written there before." }
6750
+ },
6751
+ additionalProperties: false
6752
+ }
6753
+ }
6754
+ ];
6755
+ }
6756
+ function buildAlignmentToolHandlers() {
6757
+ return {
6758
+ align_nodes: (rawInput, ctx) => {
6759
+ const input = rawInput ?? {};
6760
+ if (!ctx.diagram.addAlignment) return fail("align_nodes: alignments are not editable in this context");
6761
+ if (input.keepOrder !== void 0 && typeof input.keepOrder !== "boolean") return fail("align_nodes: keepOrder must be true or false");
6762
+ if (!Array.isArray(input.nodeIds) || input.nodeIds.some((id) => typeof id !== "string")) return fail("align_nodes: nodeIds must be an array of node ids");
6763
+ if (!AXIS_ENUM.includes(input.axis)) return fail(`align_nodes: axis must be 'horizontal' or 'vertical'`);
6764
+ const canvas2 = canvasFor(ctx, "align_nodes", input.viewId);
6765
+ if ("error" in canvas2) return fail(canvas2.error);
6766
+ const nodeIds = input.nodeIds.map((id) => ctx.resolveId(id));
6767
+ const added = ctx.diagram.addAlignment(canvas2.viewId, input.axis, nodeIds, input.keepOrder === true);
6768
+ if ("error" in added) return fail(`align_nodes: ${added.error}`);
6769
+ const order = input.keepOrder === true ? ", in the order given" : "";
6770
+ return { ok: true, resultText: `Aligned ${nodeIds.length} elements in a ${input.axis === "horizontal" ? "row" : "column"}${order}. Alignment ID: ${added.id}.`, updated: { views: 1 } };
6771
+ },
6772
+ grid_nodes: (rawInput, ctx) => {
6773
+ const input = rawInput ?? {};
6774
+ if (!ctx.diagram.addGrid) return fail("grid_nodes: grids are not editable in this context");
6775
+ if (!Array.isArray(input.nodeIds) || input.nodeIds.some((id) => typeof id !== "string")) return fail("grid_nodes: nodeIds must be an array of node ids");
6776
+ if (input.columns !== void 0 && (typeof input.columns !== "number" || !Number.isInteger(input.columns) || input.columns < 1)) return fail("grid_nodes: columns must be a whole number, at least 1");
6777
+ const canvas2 = canvasFor(ctx, "grid_nodes", input.viewId);
6778
+ if ("error" in canvas2) return fail(canvas2.error);
6779
+ const nodeIds = input.nodeIds.map((id) => ctx.resolveId(id));
6780
+ const columns = input.columns ?? defaultGridColumns(nodeIds.length);
6781
+ const added = ctx.diagram.addGrid(canvas2.viewId, nodeIds, columns);
6782
+ if ("error" in added) return fail(`grid_nodes: ${added.error}`);
6783
+ return { ok: true, resultText: `Kept ${nodeIds.length} elements in a grid of ${columns} columns. Alignment ID: ${added.id}.`, updated: { views: 1 } };
6784
+ },
6785
+ remove_alignment: (rawInput, ctx) => {
6786
+ const input = rawInput ?? {};
6787
+ if (!ctx.diagram.getLayoutConstraints || !ctx.diagram.removeLayoutConstraints) return fail("remove_alignment: alignments are not editable in this context");
6788
+ if (input.id === void 0 && input.nodeIds === void 0) return fail("remove_alignment: pass id or nodeIds");
6789
+ if (input.id !== void 0 && (typeof input.id !== "string" || !input.id)) return fail("remove_alignment: id must be an alignment id");
6790
+ if (input.nodeIds !== void 0 && (!Array.isArray(input.nodeIds) || input.nodeIds.some((id) => typeof id !== "string"))) return fail("remove_alignment: nodeIds must be an array of node ids");
6791
+ const canvas2 = canvasFor(ctx, "remove_alignment", input.viewId, true);
6792
+ if ("error" in canvas2) return fail(canvas2.error);
6793
+ const among = input.nodeIds ? new Set(input.nodeIds.map((id) => ctx.resolveId(id))) : null;
6794
+ const matches = ctx.diagram.getLayoutConstraints(canvas2.viewId).filter((c) => (input.id === void 0 ? c.type !== "pin" : c.id === input.id) && (!among || c.nodeIds.every((id) => among.has(id))));
6795
+ if (!matches.length) {
6796
+ const existing = ctx.diagram.getLayoutConstraints(canvas2.viewId);
6797
+ return fail(`remove_alignment: no such alignment on this canvas.${existing.length ? ` It has: ${existing.map(describeConstraint).join("; ")}.` : " It has none."}`);
6798
+ }
6799
+ ctx.diagram.removeLayoutConstraints(canvas2.viewId, matches.map((c) => c.id));
6800
+ return { ok: true, resultText: `Removed ${matches.map(describeConstraint).join("; ")}.`, updated: { views: 1 } };
6801
+ }
6802
+ };
6803
+ }
6804
+ function buildLayoutToolHandlers() {
6805
+ return {
6806
+ smart_layout: async (rawInput, ctx) => {
6807
+ const input = rawInput ?? {};
6808
+ if (!ctx.diagram.runLayout) return fail("smart_layout: layout is not available in this context");
6809
+ let around;
6810
+ if (input.around !== void 0) {
6811
+ if (!Array.isArray(input.around) || !input.around.every((id) => typeof id === "string" && id)) return fail("smart_layout: around must be an array of node ids");
6812
+ around = input.around.map((id) => ctx.resolveId(id));
6813
+ const nodes = ctx.diagram.getNodes();
6814
+ const unknown = around.filter((id) => !nodes[id]);
6815
+ if (unknown.length) return fail(`smart_layout: unknown node id(s) ${unknown.join(", ")}`);
6816
+ }
6817
+ if (input.viewId !== void 0 && (typeof input.viewId !== "string" || !input.viewId)) return fail("smart_layout: viewId must be a view id");
6818
+ let viewId;
6819
+ if (typeof input.viewId === "string") {
6820
+ viewId = ctx.resolveId(input.viewId);
6821
+ const view = ctx.diagram.getViews?.()[viewId];
6822
+ if (!view) return fail(`smart_layout: unknown view id "${input.viewId}"`);
6823
+ const refused = noCanvasLayout("smart_layout", view);
6824
+ if (refused) return fail(refused);
6825
+ }
6826
+ const outcome = await ctx.diagram.runLayout(viewId, around);
6827
+ return { ok: outcome.ok, resultText: outcome.text };
6828
+ }
6829
+ };
6830
+ }
6831
+
6832
+ // ../../packages/common/src/ai/tools/metamodelTools.ts
6833
+ init_define_RADICAL_BUILD();
6834
+
6594
6835
  // ../../packages/common/src/ai/tools/viewTools.ts
6595
6836
  init_define_RADICAL_BUILD();
6596
6837
  var VIEW_KIND_ENUM = ["static", "table", "treemap", "matrix", "wiki", "warnier", "dynamic"];
@@ -7224,7 +7465,7 @@ function editable(current) {
7224
7465
  const mm = fork ?? JSON.parse(JSON.stringify(current));
7225
7466
  return { mm, note: fork ? ` The built-in metamodel was copied to the custom metamodel "${mm.name}" (${mm.id}).` : "" };
7226
7467
  }
7227
- function save(ctx, mm, text) {
7468
+ function save(ctx, mm, text2) {
7228
7469
  const before = Object.values(ctx.diagram.getViews?.() ?? {}).map((v) => ({ id: v.id, name: v.name, listed: v.nodeIds.length }));
7229
7470
  ctx.diagram.setMetamodel(mm);
7230
7471
  const after = ctx.diagram.getViews?.() ?? {};
@@ -7234,7 +7475,7 @@ function save(ctx, mm, text) {
7234
7475
  ...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
7476
  ...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
7477
  ];
7237
- return { ok: true, resultText: [text, ...notes].join(" "), ...gone.length ? { deleted: { views: gone.length } } : {} };
7478
+ return { ok: true, resultText: [text2, ...notes].join(" "), ...gone.length ? { deleted: { views: gone.length } } : {} };
7238
7479
  }
7239
7480
  function buildMetamodelToolHandlers() {
7240
7481
  return {
@@ -7689,23 +7930,24 @@ var SPECIAL = { \u0142: "l", \u0141: "l", \u00DF: "ss", \u00F8: "o", \u00D8: "o"
7689
7930
  function foldChar(c) {
7690
7931
  return SPECIAL[c] ?? c.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
7691
7932
  }
7692
- function foldText(text) {
7933
+ var ASCII = /^[\x00-\x7f]*$/;
7934
+ function foldText(text2) {
7935
+ if (ASCII.test(text2)) return text2.toLowerCase();
7693
7936
  let out = "";
7694
- for (const c of text) out += foldChar(c);
7937
+ for (const c of text2) out += foldChar(c);
7695
7938
  return out;
7696
7939
  }
7697
- function foldWithMap(text) {
7698
- let folded = "";
7940
+ function foldPositions(text2) {
7941
+ if (ASCII.test(text2)) return null;
7699
7942
  const at = [];
7700
7943
  let i = 0;
7701
- for (const c of text) {
7944
+ for (const c of text2) {
7702
7945
  const f = foldChar(c);
7703
7946
  for (let k = 0; k < f.length; k++) at.push(i);
7704
- folded += f;
7705
7947
  i += c.length;
7706
7948
  }
7707
7949
  at.push(i);
7708
- return { folded, at };
7950
+ return at;
7709
7951
  }
7710
7952
  function tokens(query) {
7711
7953
  return query.match(/[^\s"]+:"[^"]*"?|"[^"]*"?|\S+/g) ?? [];
@@ -7740,14 +7982,14 @@ function typesNamed(data, value) {
7740
7982
  }
7741
7983
  function parseSearch(query, data) {
7742
7984
  const out = { command: false, words: [], kinds: null, scope: null, types: null, properties: [] };
7743
- let text = query.trim();
7744
- if (text.startsWith(">")) {
7985
+ let text2 = query.trim();
7986
+ if (text2.startsWith(">")) {
7745
7987
  out.command = true;
7746
- text = text.slice(1);
7988
+ text2 = text2.slice(1);
7747
7989
  }
7748
7990
  const props = propertyNames(data.metamodel);
7749
7991
  const kinds = /* @__PURE__ */ new Set();
7750
- for (const token of tokens(text)) {
7992
+ for (const token of tokens(text2)) {
7751
7993
  if (out.command) {
7752
7994
  out.words.push(foldText(unquote(token)));
7753
7995
  continue;
@@ -7814,6 +8056,23 @@ function matchIn(folded, word) {
7814
8056
  function initials(folded) {
7815
8057
  return (folded.match(/[a-z0-9]+/g) ?? []).map((w) => w[0]).join("");
7816
8058
  }
8059
+ var FOLD_CACHE_MAX = 25e4;
8060
+ var folds = /* @__PURE__ */ new Map();
8061
+ var foldsMade = 0;
8062
+ function foldedOf(text2) {
8063
+ let f = folds.get(text2);
8064
+ if (!f) {
8065
+ if (folds.size >= FOLD_CACHE_MAX) folds.clear();
8066
+ f = { text: text2, folded: foldText(text2) };
8067
+ folds.set(text2, f);
8068
+ foldsMade++;
8069
+ }
8070
+ return f;
8071
+ }
8072
+ function positionsOf(f) {
8073
+ if (f.at === void 0) f.at = foldPositions(f.text);
8074
+ return f.at;
8075
+ }
7817
8076
  function matchFields(fields, words, foldedFields) {
7818
8077
  if (!words.length) return { score: 0, matches: [] };
7819
8078
  const matches = [];
@@ -7833,7 +8092,8 @@ function matchFields(fields, words, foldedFields) {
7833
8092
  return { score, matches };
7834
8093
  }
7835
8094
  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]);
8095
+ const at = positionsOf(f);
8096
+ const marks = ranges.map(([a, b]) => at ? [at[a], at[b - 1] + 1] : [a, b]).sort((x, y) => x[0] - y[0]);
7837
8097
  const out = [];
7838
8098
  for (const m of marks) {
7839
8099
  const last = out[out.length - 1];
@@ -7844,11 +8104,11 @@ function marksOf(f, ranges) {
7844
8104
  }
7845
8105
  var SNIPPET_BEFORE = 28;
7846
8106
  var SNIPPET_LENGTH = 90;
7847
- function snippetOf(text, f, ranges) {
8107
+ function snippetOf(text2, f, ranges) {
7848
8108
  const marks = marksOf(f, ranges);
7849
8109
  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;
8110
+ const flat2 = text2.replace(/\s+/g, " ");
8111
+ const shift = text2.slice(0, first).length - text2.slice(0, first).replace(/\s+/g, " ").length;
7852
8112
  const at = first - shift;
7853
8113
  let start = Math.max(0, at - SNIPPET_BEFORE);
7854
8114
  if (start > 0) {
@@ -7859,7 +8119,7 @@ function snippetOf(text, f, ranges) {
7859
8119
  const lead = start > 0 ? "\u2026" : "";
7860
8120
  const tail = end < flat2.length ? "\u2026" : "";
7861
8121
  const moved = (n) => {
7862
- const s = text.slice(0, n).length - text.slice(0, n).replace(/\s+/g, " ").length;
8122
+ const s = text2.slice(0, n).length - text2.slice(0, n).replace(/\s+/g, " ").length;
7863
8123
  return n - s - start + lead.length;
7864
8124
  };
7865
8125
  const shown = lead + flat2.slice(start, end) + tail;
@@ -7869,7 +8129,7 @@ function snippetOf(text, f, ranges) {
7869
8129
  };
7870
8130
  }
7871
8131
  function hitFor(fields, parsed, allowInitials) {
7872
- const folded = fields.map((f) => foldWithMap(f.text));
8132
+ const folded = fields.map((f) => foldedOf(f.text));
7873
8133
  const m = matchFields(fields, parsed.words, folded);
7874
8134
  let score = m?.score ?? 0;
7875
8135
  const matches = m?.matches ?? [];
@@ -7907,7 +8167,7 @@ function viewTypeName(view) {
7907
8167
  return VIEW_TYPE[view.kind ?? ""] ?? "Structure";
7908
8168
  }
7909
8169
  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"]);
8170
+ var BASE_KEYS2 = /* @__PURE__ */ new Set(["id", "type", "label", "description", "technology", "parentId", "collapsed", "external", "x", "y", "width", "height", "order", "pinned", "positions"]);
7911
8171
  function propertyFields(node, metamodel) {
7912
8172
  const values = node;
7913
8173
  const defs = metamodel?.nodeTypes[node.type]?.properties;
@@ -7922,7 +8182,7 @@ function propertyFields(node, metamodel) {
7922
8182
  return out;
7923
8183
  }
7924
8184
  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 });
8185
+ if (!BASE_KEYS2.has(key) && typeof v === "string" && v.trim()) out.push({ key, name: key, text: v });
7926
8186
  }
7927
8187
  return out;
7928
8188
  }
@@ -8094,7 +8354,7 @@ Boolean logic in WHERE:
8094
8354
  Supported node fields:
8095
8355
  - id, type, label, description, technology, parentId, external,
8096
8356
  plus any custom/governance property key for that node's type
8097
- (e.g. status, ears_type, category \u2014 see the metamodel context message)
8357
+ (e.g. status, ears_type, characteristic \u2014 see the metamodel context message)
8098
8358
 
8099
8359
  Supported relation fields:
8100
8360
  - id, sourceId, targetId, label, technology, relationType,
@@ -8381,7 +8641,7 @@ function getNodeField(node, field) {
8381
8641
  return node.parentId ?? null;
8382
8642
  case "external":
8383
8643
  return node.external ?? false;
8384
- // Custom/governance properties (ears_type, status, category, ...) ride as
8644
+ // Custom/governance properties (ears_type, status, characteristic, ...) ride as
8385
8645
  // extra own-keys on the node — fall through to a generic read instead of
8386
8646
  // rejecting any field not in the fixed list above.
8387
8647
  default:
@@ -8999,6 +9259,13 @@ function buildNodeToolHandlers() {
8999
9259
  if (typeof input.id !== "string" || !input.id) return fail("delete_node: id is required");
9000
9260
  const realId = ctx.resolveId(input.id);
9001
9261
  if (!(realId in ctx.diagram.getNodes())) return fail(`delete_node: unknown id "${input.id}"`);
9262
+ const refused = checkRemove({
9263
+ c4Nodes: ctx.diagram.getNodes(),
9264
+ c4Relations: ctx.diagram.getRelations(),
9265
+ views: ctx.diagram.getViews?.() ?? {},
9266
+ activeViewId: null
9267
+ }, [realId]);
9268
+ if (refused) return fail(`delete_node: ${refused}`);
9002
9269
  const steps = sequenceStepCount(ctx);
9003
9270
  ctx.diagram.removeNode(realId);
9004
9271
  return { ok: true, resultText: `Deleted node ${realId}${stepsGone(steps - sequenceStepCount(ctx))}.`, deleted: { nodes: 1 } };
@@ -9332,6 +9599,14 @@ function buildRelationToolHandlers() {
9332
9599
  ...effectiveType !== oldType && !effectiveType ? { relationType: void 0 } : {},
9333
9600
  ...Object.fromEntries([...cleared, ...removed].map((key) => [key, void 0]))
9334
9601
  };
9602
+ const refused = checkPatchRelation({
9603
+ c4Nodes: ctx.diagram.getNodes(),
9604
+ c4Relations: rels,
9605
+ views: ctx.diagram.getViews?.() ?? {},
9606
+ activeViewId: null,
9607
+ metamodel: mm
9608
+ }, realId, updates);
9609
+ if (refused) return fail(`update_relation: ${refused}`);
9335
9610
  ctx.diagram.updateRelation(realId, updates);
9336
9611
  const resultText = notes.length ? `Updated relation ${realId}. ${notes.join("; ")}` : `Updated relation ${realId}.`;
9337
9612
  return { ok: true, resultText, updated: { relations: 1 } };
@@ -9341,6 +9616,13 @@ function buildRelationToolHandlers() {
9341
9616
  if (typeof input.id !== "string" || !input.id) return fail("delete_relation: id is required");
9342
9617
  const realId = ctx.resolveId(input.id);
9343
9618
  if (!(realId in ctx.diagram.getRelations())) return fail(`delete_relation: unknown id "${input.id}"`);
9619
+ const refused = checkRemove({
9620
+ c4Nodes: ctx.diagram.getNodes(),
9621
+ c4Relations: ctx.diagram.getRelations(),
9622
+ views: ctx.diagram.getViews?.() ?? {},
9623
+ activeViewId: null
9624
+ }, [], [realId]);
9625
+ if (refused) return fail(`delete_relation: ${refused}`);
9344
9626
  const steps = sequenceStepCount(ctx);
9345
9627
  ctx.diagram.removeRelation(realId);
9346
9628
  return { ok: true, resultText: `Deleted relation ${realId}${stepsGone(steps - sequenceStepCount(ctx))}.`, deleted: { relations: 1 } };
@@ -9505,12 +9787,34 @@ var ASYNC = new Map(Object.entries(buildLayoutToolHandlers()));
9505
9787
  async function runTool(name, input, ctx) {
9506
9788
  const handler = ASYNC.get(name) ?? SYNC.get(name);
9507
9789
  if (!handler) return { ok: false, resultText: `Unknown tool "${name}"` };
9790
+ const refused = otherModelViewRefusal(name, input, ctx);
9791
+ if (refused) return { ok: false, resultText: `${name}: ${refused}` };
9508
9792
  try {
9509
9793
  return await handler(input, ctx);
9510
9794
  } catch (err) {
9511
9795
  return { ok: false, resultText: err.message };
9512
9796
  }
9513
9797
  }
9798
+ var VIEW_TOOLS = {
9799
+ update_view: "id",
9800
+ delete_view: "id",
9801
+ set_view_nodes: "viewId",
9802
+ smart_layout: "viewId",
9803
+ align_nodes: "viewId",
9804
+ grid_nodes: "viewId",
9805
+ remove_alignment: "viewId"
9806
+ };
9807
+ function otherModelViewRefusal(name, input, ctx) {
9808
+ const folder = (name === "create_view" || name === "update_view") && input && typeof input === "object" ? input.folder : void 0;
9809
+ if (typeof folder === "string") {
9810
+ const refused = viewFolderRefusal(ctx.diagram.getViews?.() ?? {}, folder);
9811
+ if (refused) return refused;
9812
+ }
9813
+ const field = VIEW_TOOLS[name];
9814
+ const raw = field && input && typeof input === "object" ? input[field] : void 0;
9815
+ if (typeof raw !== "string" || !raw) return null;
9816
+ return viewRefusal(ctx.diagram.getViews?.()[ctx.resolveId(raw)]);
9817
+ }
9514
9818
 
9515
9819
  // ../../packages/common/src/ai/modelFacade.ts
9516
9820
  init_define_RADICAL_BUILD();
@@ -9591,6 +9895,11 @@ function createModelFacade(data, options = {}) {
9591
9895
  syncGroups();
9592
9896
  },
9593
9897
  removeNode(id) {
9898
+ const refused = checkRemove(state, [id]);
9899
+ if (refused) {
9900
+ refuse(refused);
9901
+ return;
9902
+ }
9594
9903
  if (carried.snapshots?.length && state.c4Nodes[id]) {
9595
9904
  carried.snapshots = keepViewsInMilestones(carried.snapshots, state.views, /* @__PURE__ */ new Set([id, ...descendantIds(id, state.c4Nodes)]));
9596
9905
  }
@@ -9622,6 +9931,11 @@ function createModelFacade(data, options = {}) {
9622
9931
  patchRelation(state, id, updates);
9623
9932
  },
9624
9933
  removeRelation(id) {
9934
+ const refused = checkRemove(state, [], [id]);
9935
+ if (refused) {
9936
+ refuse(refused);
9937
+ return;
9938
+ }
9625
9939
  deleteRelation(state, id);
9626
9940
  },
9627
9941
  addView(name, opts) {
@@ -9728,13 +10042,15 @@ function createModelFacade(data, options = {}) {
9728
10042
  getMilestones: () => carried.snapshots ?? [],
9729
10043
  createMilestone(name) {
9730
10044
  const id = newId();
10045
+ const own = ownModel({ nodes: Object.values(state.c4Nodes), relations: Object.values(state.c4Relations) });
9731
10046
  const milestone = {
9732
10047
  id,
9733
10048
  name,
9734
10049
  timestamp: Date.now(),
9735
- nodes: clone(state.c4Nodes),
9736
- relations: clone(state.c4Relations),
9737
- sequences: clone(state.sequences)
10050
+ nodes: clone(Object.fromEntries(own.nodes.map((n) => [n.id, n]))),
10051
+ relations: clone(Object.fromEntries(own.relations.map((r) => [r.id, r]))),
10052
+ sequences: clone(state.sequences),
10053
+ ...carried.federation?.dependencies.length ? { otherModels: carried.federation.dependencies.map(({ name: name2, commit }) => ({ name: name2, commit })) } : {}
9738
10054
  };
9739
10055
  carried.snapshots = [...carried.snapshots ?? [], milestone];
9740
10056
  return id;
@@ -9915,6 +10231,116 @@ function buildContextMessage(nodes, relations, activeView, views) {
9915
10231
 
9916
10232
  // ../../packages/common/src/formats/mdFolder.ts
9917
10233
  init_define_RADICAL_BUILD();
10234
+
10235
+ // ../../packages/common/src/formats/checksMigration.ts
10236
+ init_define_RADICAL_BUILD();
10237
+ var CHECKED_TYPES = /* @__PURE__ */ new Set(["scenario", "fitness-fn"]);
10238
+ var OLD_KEYS = ["tests", "threshold"];
10239
+ var text = (v) => typeof v === "string" ? v.trim() : "";
10240
+ var needsMigration = (node) => CHECKED_TYPES.has(String(node.type)) && (OLD_KEYS.some((k) => k in node) || node.type === "fitness-fn" && "category" in node);
10241
+ var onlyTests = (metrics) => {
10242
+ const lines = metrics.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#"));
10243
+ return lines.length > 0 && lines.every((l) => /^test\(.*\)\s+passed$/.test(l));
10244
+ };
10245
+ function classify(next) {
10246
+ const category = text(next.category);
10247
+ delete next.category;
10248
+ if (category === "holistic" && !next.scope) next.scope = "holistic";
10249
+ if (category === "structural" && !next.characteristic) next.characteristic = "maintainability";
10250
+ if (!next.cadence && !next.invocation && onlyTests(text(next.metrics))) {
10251
+ next.cadence = "triggered";
10252
+ next.trigger = "pull-request";
10253
+ next.invocation = "automated";
10254
+ }
10255
+ }
10256
+ function migrateCheckFields(node) {
10257
+ if (!needsMigration(node)) return node;
10258
+ const next = { ...node };
10259
+ const tests = text(node.tests).split("\n").map((l) => l.trim()).filter(Boolean).map((line) => line.startsWith("#") ? line : `test(${line}) passed`);
10260
+ if (tests.length) next.metrics = [text(node.metrics), ...tests].filter(Boolean).join("\n");
10261
+ const threshold = text(node.threshold);
10262
+ if (threshold) {
10263
+ const description = text(node.description);
10264
+ next.description = description ? `${description}
10265
+
10266
+ Threshold: ${threshold}` : `Threshold: ${threshold}`;
10267
+ }
10268
+ for (const key of OLD_KEYS) delete next[key];
10269
+ if (node.type === "fitness-fn" && "category" in node) classify(next);
10270
+ return next;
10271
+ }
10272
+ function migrateNodeType(def) {
10273
+ return migrateCategory(migrateOldKeys(def));
10274
+ }
10275
+ function migrateCategory(def) {
10276
+ if (def.id !== "fitness-fn" || !def.properties?.some((p) => p.key === "category")) return def;
10277
+ const at = def.properties.findIndex((p) => p.key === "category");
10278
+ const kept = def.properties.filter((p) => p.key !== "category");
10279
+ const missing = FITNESS_CLASSIFICATION_PROPERTIES.filter((p) => !kept.some((k) => k.key === p.key));
10280
+ const properties = [...kept.slice(0, at), ...missing, ...kept.slice(at)];
10281
+ const wizard = def.wizard && {
10282
+ ...def.wizard,
10283
+ 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)
10284
+ };
10285
+ return { ...def, properties, ...wizard ? { wizard } : {} };
10286
+ }
10287
+ function migrateOldKeys(def) {
10288
+ if (!CHECKED_TYPES.has(def.id) || !def.properties?.some((p) => OLD_KEYS.includes(p.key))) return def;
10289
+ const at = def.properties.findIndex((p) => OLD_KEYS.includes(p.key));
10290
+ const kept = def.properties.filter((p) => !OLD_KEYS.includes(p.key));
10291
+ const missing = METRICS_PROPERTIES.filter((p) => !kept.some((k) => k.key === p.key));
10292
+ const properties = [...kept.slice(0, at), ...missing, ...kept.slice(at)];
10293
+ const wizard = def.wizard && {
10294
+ ...def.wizard,
10295
+ 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)
10296
+ };
10297
+ return { ...def, properties, ...wizard ? { wizard } : {} };
10298
+ }
10299
+ function migrateMetamodel(metamodel) {
10300
+ let changed = false;
10301
+ const nodeTypes = {};
10302
+ for (const [id, def] of Object.entries(metamodel.nodeTypes)) {
10303
+ nodeTypes[id] = migrateNodeType(def);
10304
+ if (nodeTypes[id] !== def) changed = true;
10305
+ }
10306
+ return changed ? { ...metamodel, nodeTypes } : metamodel;
10307
+ }
10308
+ var migrateRecord = (nodes) => {
10309
+ if (!Object.values(nodes).some((n) => needsMigration(n))) return nodes;
10310
+ return Object.fromEntries(Object.entries(nodes).map(([id, n]) => [id, migrateCheckFields(n)]));
10311
+ };
10312
+ function migrateChecks(data) {
10313
+ const nodes = data.nodes.some((n) => needsMigration(n)) ? data.nodes.map((n) => migrateCheckFields(n)) : data.nodes;
10314
+ const metamodel = data.metamodel ? migrateMetamodel(data.metamodel) : void 0;
10315
+ const snapshots = data.snapshots?.map((s) => {
10316
+ const next = migrateRecord(s.nodes);
10317
+ return next === s.nodes ? s : { ...s, nodes: next };
10318
+ });
10319
+ const presentations = data.presentations?.map((p) => {
10320
+ const slides = p.slides.map((slide2) => {
10321
+ if (!slide2.modelSnapshot) return slide2;
10322
+ const next = migrateRecord(slide2.modelSnapshot.nodes);
10323
+ return next === slide2.modelSnapshot.nodes ? slide2 : { ...slide2, modelSnapshot: { ...slide2.modelSnapshot, nodes: next } };
10324
+ });
10325
+ return slides.some((s, i) => s !== p.slides[i]) ? { ...p, slides } : p;
10326
+ });
10327
+ const hubTemplates = data.hubTemplates && Object.fromEntries(Object.entries(data.hubTemplates).map(([id, record]) => {
10328
+ const originals = Object.fromEntries(Object.entries(record.originalNodes).map(([nid, n]) => [nid, migrateCheckFields(n)]));
10329
+ return [id, Object.entries(originals).some(([nid, n]) => n !== record.originalNodes[nid]) ? { ...record, originalNodes: originals } : record];
10330
+ }));
10331
+ 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]);
10332
+ if (!changed) return data;
10333
+ return {
10334
+ ...data,
10335
+ nodes,
10336
+ ...metamodel ? { metamodel } : {},
10337
+ ...snapshots ? { snapshots } : {},
10338
+ ...presentations ? { presentations } : {},
10339
+ ...hubTemplates ? { hubTemplates } : {}
10340
+ };
10341
+ }
10342
+
10343
+ // ../../packages/common/src/formats/mdFolder.ts
9918
10344
  var MD_MANIFEST_FILE = "radical.md";
9919
10345
  var LAYOUT_FILE = "_layout.json";
9920
10346
  var RELATIONS_FILE = "relations.json";
@@ -10045,8 +10471,8 @@ function parseMarkdown(content) {
10045
10471
  const body = lines.slice(i).join("\n").trim();
10046
10472
  return { front, body };
10047
10473
  }
10048
- function slugify(text, fallback) {
10049
- const slug = text.toLowerCase().normalize("NFKD").replace(/[^\p{Letter}\p{Number}]+/gu, "-").replace(/^-+|-+$/g, "");
10474
+ function slugify(text2, fallback) {
10475
+ const slug = text2.toLowerCase().normalize("NFKD").replace(/[^\p{Letter}\p{Number}]+/gu, "-").replace(/^-+|-+$/g, "");
10050
10476
  return [...slug].slice(0, 60).join("") || fallback;
10051
10477
  }
10052
10478
  function allocateSlugs(claims) {
@@ -10072,7 +10498,8 @@ function allocateSlugs(claims) {
10072
10498
  function serializeToMdFolder(data, modelName) {
10073
10499
  return serializeToMdFolderWithPaths(data, modelName).files;
10074
10500
  }
10075
- function serializeToMdFolderWithPaths(data, modelName) {
10501
+ function serializeToMdFolderWithPaths(model, modelName) {
10502
+ const data = ownModel(model);
10076
10503
  const files = {};
10077
10504
  const nodePaths = {};
10078
10505
  const layout = { nodes: {} };
@@ -10231,7 +10658,7 @@ function deserializeFromMdFolder(files) {
10231
10658
  if (layout.defaultLayoutConstraints?.length) data.defaultLayoutConstraints = layout.defaultLayoutConstraints;
10232
10659
  if (layout.defaultEdgeStyle === "orthogonal") data.defaultEdgeStyle = layout.defaultEdgeStyle;
10233
10660
  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() } : {} };
10661
+ return { data: migrateChecks(data), ...typeof manifest === "string" && manifest.trim() ? { name: manifest.trim() } : {} };
10235
10662
  }
10236
10663
  function isMdFolderModelPath(path) {
10237
10664
  if (path === MD_MANIFEST_FILE || SIDECAR_FILES.has(path)) return true;
@@ -10748,6 +11175,93 @@ function forgetDeleted(merged, sides) {
10748
11175
  if (merged.defaultLayoutConstraints) merged.defaultLayoutConstraints = state.defaultLayoutConstraints ?? [];
10749
11176
  }
10750
11177
 
11178
+ // ../../packages/common/src/formats/modelCache.ts
11179
+ init_define_RADICAL_BUILD();
11180
+
11181
+ // ../../packages/common/src/formats/canvasSelection.ts
11182
+ init_define_RADICAL_BUILD();
11183
+ var STATE_DIR = ".state";
11184
+ var OLD_STATE_DIR = ".radical";
11185
+ var oldStatePath = (path) => path.startsWith(`${STATE_DIR}/`) ? `${OLD_STATE_DIR}/${path.slice(STATE_DIR.length + 1)}` : path;
11186
+ var SELECTION_FILE = `${STATE_DIR}/selection.json`;
11187
+ var SELECTION_GITIGNORE = `${STATE_DIR}/.gitignore`;
11188
+ var SELECTION_GITIGNORE_CONTENT = "*\n";
11189
+ var isIdList = (value) => Array.isArray(value) && value.every((id) => typeof id === "string" && id.length > 0);
11190
+ function parseSelection(text2) {
11191
+ let raw;
11192
+ try {
11193
+ raw = JSON.parse(text2);
11194
+ } catch {
11195
+ return null;
11196
+ }
11197
+ if (!raw || typeof raw !== "object") return null;
11198
+ const { version, updatedAt, viewId, nodeIds, relationIds } = raw;
11199
+ if (version !== 1 || typeof updatedAt !== "string" || !isIdList(nodeIds) || !isIdList(relationIds)) return null;
11200
+ if (viewId !== null && typeof viewId !== "string") return null;
11201
+ return { version, updatedAt, viewId, nodeIds, relationIds };
11202
+ }
11203
+
11204
+ // ../../packages/common/src/formats/modelCache.ts
11205
+ var MODEL_CACHE_DIR = `${STATE_DIR}/cache`;
11206
+ var MODEL_CACHE_FILE = `${MODEL_CACHE_DIR}/model.json`;
11207
+ var MODEL_CACHE_NAMES = /* @__PURE__ */ new Set(["model.json", "changes.json", "views.json"]);
11208
+ var MODEL_CACHE_VERSION = 2;
11209
+ function parse(text2) {
11210
+ if (!text2) return null;
11211
+ try {
11212
+ const json = JSON.parse(text2);
11213
+ return json && typeof json === "object" ? json : null;
11214
+ } catch {
11215
+ return null;
11216
+ }
11217
+ }
11218
+ var encoder = new TextEncoder();
11219
+ var decoder = new TextDecoder();
11220
+ function readFiles(files) {
11221
+ if (!files || typeof files !== "object") return null;
11222
+ for (const entry of Object.values(files)) {
11223
+ if (!entry || typeof entry.stamp !== "string" || typeof entry.content !== "string") return null;
11224
+ entry.content = decoder.decode(encoder.encode(entry.content));
11225
+ }
11226
+ return files;
11227
+ }
11228
+ function readModelCache(model, changes) {
11229
+ const json = parse(model);
11230
+ if (!json || json.format !== "radical-model-cache" || json.version !== MODEL_CACHE_VERSION || typeof json.id !== "string") return null;
11231
+ const base = readFiles(json.files);
11232
+ if (!base) return null;
11233
+ const files = { ...base };
11234
+ const delta = parse(changes);
11235
+ if (delta && delta.format === "radical-model-cache-changes" && delta.version === MODEL_CACHE_VERSION && delta.base === json.id && Array.isArray(delta.removed)) {
11236
+ const changed = readFiles(delta.files);
11237
+ if (changed) {
11238
+ Object.assign(files, changed);
11239
+ for (const path of delta.removed) delete files[path];
11240
+ }
11241
+ }
11242
+ return { id: json.id, base, files };
11243
+ }
11244
+ function writeModelCache(files, id) {
11245
+ const json = { format: "radical-model-cache", version: MODEL_CACHE_VERSION, id, files };
11246
+ return ascii(JSON.stringify(json));
11247
+ }
11248
+ function writeModelCacheChanges(baseId, base, files) {
11249
+ const changed = {};
11250
+ for (const [path, entry] of Object.entries(files)) if (base[path]?.stamp !== entry.stamp) changed[path] = entry;
11251
+ const removed = Object.keys(base).filter((path) => !(path in files));
11252
+ const json = { format: "radical-model-cache-changes", version: MODEL_CACHE_VERSION, base: baseId, files: changed, removed };
11253
+ return ascii(JSON.stringify(json));
11254
+ }
11255
+ function modelCacheChangeCount(base, files) {
11256
+ let n = 0;
11257
+ for (const [path, entry] of Object.entries(files)) if (base[path]?.stamp !== entry.stamp) n++;
11258
+ for (const path of Object.keys(base)) if (!(path in files)) n++;
11259
+ return n;
11260
+ }
11261
+ function ascii(text2) {
11262
+ return text2.replace(/[\u007f-￿]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
11263
+ }
11264
+
10751
11265
  // ../../packages/common/src/formats/mdFolderSync.ts
10752
11266
  var mergeMdFolderFiles = (base, ours, theirs) => {
10753
11267
  for (const [path, content] of Object.entries(theirs)) {
@@ -10769,9 +11283,35 @@ var mergeMdFolderFiles = (base, ours, theirs) => {
10769
11283
  return null;
10770
11284
  }
10771
11285
  };
11286
+ var READ_AT_ONCE = 32;
11287
+ async function readEach(paths, read) {
11288
+ const out = new Array(paths.length);
11289
+ let next = 0;
11290
+ const worker = async () => {
11291
+ while (next < paths.length) {
11292
+ const i = next++;
11293
+ out[i] = await read(paths[i]);
11294
+ }
11295
+ };
11296
+ await Promise.all(Array.from({ length: Math.min(READ_AT_ONCE, paths.length) }, worker));
11297
+ return out;
11298
+ }
11299
+ var CACHE_STALE_MAX = 50;
11300
+ var CACHE_STALE_SHARE = 0.01;
11301
+ function newCacheId() {
11302
+ return globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
11303
+ }
10772
11304
  var MdFolderSession = class {
10773
- constructor(storage) {
11305
+ /** `writeCache: false`: read the folder's cache when there is one, never
11306
+ * write it (the CLI, which exits as soon as it is done; Studio and the
11307
+ * MCP server keep it). `openFromCache`: the session's first read takes
11308
+ * the folder as its cache has it, without listing the files, and lists
11309
+ * them right after; `verified` says whether they differed (Studio, which
11310
+ * then loads the folder afresh; never the MCP server, which must see the
11311
+ * files as they are on every call). */
11312
+ constructor(storage, options = {}) {
10774
11313
  this.storage = storage;
11314
+ this.options = options;
10775
11315
  /** Called with the changed paths whenever `poll` or a refused `write`
10776
11316
  * finds edits made outside the app. */
10777
11317
  this.onExternalChange = null;
@@ -10782,6 +11322,17 @@ var MdFolderSession = class {
10782
11322
  this.observed = {};
10783
11323
  this.tail = Promise.resolve();
10784
11324
  this.running = 0;
11325
+ /** model.json as last read or written: its id and files, which
11326
+ * changes.json is made against. */
11327
+ this.cache = null;
11328
+ this.verification = Promise.resolve({ stale: false, changed: [] });
11329
+ this.cacheWrite = Promise.resolve();
11330
+ }
11331
+ /** Whether the files differed from the cache a first read took the folder
11332
+ * from (`openFromCache`), and which: resolves once they are listed, at
11333
+ * once for a read that listed them. */
11334
+ verified() {
11335
+ return this.verification;
10785
11336
  }
10786
11337
  /** Read every model file and make that the baseline. */
10787
11338
  readAll() {
@@ -10812,7 +11363,7 @@ var MdFolderSession = class {
10812
11363
  });
10813
11364
  }
10814
11365
  async writeLocked(files, merge) {
10815
- if (!this.loaded) await this.loadBaseline();
11366
+ if (!this.loaded) await this.loadBaseline(false);
10816
11367
  files = keepMdFolderPaths(this.baselineFiles(), files);
10817
11368
  const stamps = await this.storage.list();
10818
11369
  const conflict = await this.changedSince(stamps);
@@ -10841,6 +11392,7 @@ var MdFolderSession = class {
10841
11392
  this.baseline.delete(path);
10842
11393
  }
10843
11394
  this.observed = this.baselineStamps();
11395
+ this.keepCache();
10844
11396
  if (merged) this.onExternalChange?.(merged.changed);
10845
11397
  return merged ? { ok: true, merged } : { ok: true };
10846
11398
  }
@@ -10858,37 +11410,127 @@ var MdFolderSession = class {
10858
11410
  return changed;
10859
11411
  });
10860
11412
  }
10861
- async loadBaseline() {
11413
+ /** `rebuildCache`: write the cache again when it is out of date (not
11414
+ * for a write, which changes the folder at once). */
11415
+ async loadBaseline(rebuildCache = true) {
11416
+ const cached = await this.readCache();
11417
+ if (cached && this.options.openFromCache && !this.loaded && rebuildCache) {
11418
+ this.baseline = new Map(Object.entries(cached.files).map(([path, { content, stamp }]) => [path, { content, stamp }]));
11419
+ this.observed = this.baselineStamps();
11420
+ this.loaded = true;
11421
+ this.cache = cached;
11422
+ this.verification = this.verifyLater();
11423
+ return;
11424
+ }
10862
11425
  const stamps = await this.storage.list();
11426
+ const paths = Object.keys(stamps);
11427
+ const known = cached?.files;
11428
+ const toRead = known ? paths.filter((path) => known[path]?.stamp !== stamps[path]) : paths;
11429
+ const contents = await readEach(toRead, (path) => this.storage.read(path));
11430
+ const read = new Map(toRead.map((path, i) => [path, contents[i]]));
10863
11431
  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
- }
11432
+ for (const path of paths) baseline.set(path, { content: read.get(path) ?? known[path].content, stamp: stamps[path] });
10867
11433
  this.baseline = baseline;
10868
11434
  this.observed = stamps;
10869
11435
  this.loaded = true;
11436
+ this.cache = cached;
11437
+ this.verification = Promise.resolve({ stale: false, changed: [] });
11438
+ const gone = known ? Object.keys(known).filter((path) => !(path in stamps)).length : 0;
11439
+ if (rebuildCache && (!cached || toRead.length + gone > 0)) this.keepCache();
11440
+ }
11441
+ /** model.json, with changes.json applied when it was made for it. */
11442
+ async readCache() {
11443
+ if (!this.storage.readCache) return null;
11444
+ const [model, changes] = await Promise.all([
11445
+ this.storage.readCache("model.json").catch(() => null),
11446
+ this.storage.readCache("changes.json").catch(() => null)
11447
+ ]);
11448
+ return readModelCache(model, changes);
11449
+ }
11450
+ /** Lists the files after an open from the cache: those that differ are
11451
+ * read into the baseline's place for them by the next read. */
11452
+ verifyLater() {
11453
+ const run = this.tail.then(async () => {
11454
+ this.running++;
11455
+ try {
11456
+ const stamps = await this.storage.list();
11457
+ const changed = await this.changedSince(stamps);
11458
+ this.observed = stamps;
11459
+ this.keepCache();
11460
+ return { stale: changed.length > 0, changed };
11461
+ } catch {
11462
+ return { stale: true, changed: [] };
11463
+ } finally {
11464
+ this.running--;
11465
+ }
11466
+ });
11467
+ this.tail = run.catch(() => {
11468
+ });
11469
+ return run;
11470
+ }
11471
+ /** Brings the cache up to the baseline: changes.json, or model.json
11472
+ * again when it is missing or more files differ from it than it can
11473
+ * stand (written after the operation running, so it waits for neither).
11474
+ * Only for a model's folder: a folder of other files is left alone. */
11475
+ keepCache() {
11476
+ if (this.options.writeCache === false || !this.storage.writeCache) return;
11477
+ if (!isValidMdFolderManifest(this.baseline.get(MD_MANIFEST_FILE)?.content)) return;
11478
+ const run = this.tail.then(async () => {
11479
+ this.running++;
11480
+ try {
11481
+ const files = {};
11482
+ for (const [path, entry] of this.baseline) files[path] = { stamp: entry.stamp, content: entry.content };
11483
+ const cache = this.cache;
11484
+ if (cache && modelCacheChangeCount(cache.base, files) <= Math.max(CACHE_STALE_MAX, this.baseline.size * CACHE_STALE_SHARE)) {
11485
+ await this.storage.writeCache("changes.json", writeModelCacheChanges(cache.id, cache.base, files));
11486
+ return;
11487
+ }
11488
+ const id = newCacheId();
11489
+ await this.storage.writeCache("model.json", writeModelCache(files, id));
11490
+ this.cache = { id, base: files };
11491
+ } catch {
11492
+ } finally {
11493
+ this.running--;
11494
+ }
11495
+ });
11496
+ this.tail = run;
11497
+ this.cacheWrite = run;
11498
+ }
11499
+ /** Resolves once the cache is written as far as the session has gone. */
11500
+ cacheWritten() {
11501
+ return this.cacheWrite;
11502
+ }
11503
+ /** A file of the folder's cache other than its files' (views.json), or
11504
+ * null. */
11505
+ readCacheFile(name) {
11506
+ return this.storage.readCache ? this.storage.readCache(name).catch(() => null) : Promise.resolve(null);
11507
+ }
11508
+ /** Writes one; false when the folder keeps no cache. */
11509
+ async writeCacheFile(name, content) {
11510
+ if (this.options.writeCache === false || !this.storage.writeCache) return false;
11511
+ try {
11512
+ await this.storage.writeCache(name, content);
11513
+ return true;
11514
+ } catch {
11515
+ return false;
11516
+ }
10870
11517
  }
10871
11518
  /** Paths whose content on disk differs from the baseline: added, removed,
10872
11519
  * or rewritten with different content. A file whose stamp moved but whose
10873
11520
  * content didn't (touched, saved unchanged) just gets its stamp updated. */
10874
11521
  async changedSince(stamps) {
10875
11522
  const changed = [];
10876
- for (const [path, stamp] of Object.entries(stamps)) {
11523
+ const moved = Object.keys(stamps).filter((path) => {
10877
11524
  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
- }
11525
+ if (!known) changed.push(path);
11526
+ return !!known && known.stamp !== stamps[path];
11527
+ });
11528
+ const contents = await readEach(moved, (path) => this.storage.read(path).catch(() => void 0));
11529
+ moved.forEach((path, i) => {
11530
+ const known = this.baseline.get(path);
11531
+ if (contents[i] === known.content) known.stamp = stamps[path];
11532
+ else changed.push(path);
11533
+ });
10892
11534
  for (const path of this.baseline.keys()) {
10893
11535
  if (!(path in stamps)) changed.push(path);
10894
11536
  }
@@ -10903,12 +11545,11 @@ var MdFolderSession = class {
10903
11545
  /** The model files as they are on disk now. */
10904
11546
  async readFiles(stamps) {
10905
11547
  const files = {};
10906
- for (const path of Object.keys(stamps)) {
10907
- try {
10908
- files[path] = await this.storage.read(path);
10909
- } catch {
10910
- }
10911
- }
11548
+ const paths = Object.keys(stamps);
11549
+ const contents = await readEach(paths, (path) => this.storage.read(path).catch(() => void 0));
11550
+ paths.forEach((path, i) => {
11551
+ if (contents[i] !== void 0) files[path] = contents[i];
11552
+ });
10912
11553
  return files;
10913
11554
  }
10914
11555
  baselineStamps() {
@@ -10937,40 +11578,56 @@ function sameStamps(a, b) {
10937
11578
  // ../../packages/node-files/src/diskFolderStorage.ts
10938
11579
  init_define_RADICAL_BUILD();
10939
11580
  import { randomUUID } from "crypto";
10940
- import { lstat as lstat2, mkdir as mkdir2, readFile as readFile2, readdir, rm, stat, writeFile as writeFile2 } from "fs/promises";
10941
- import { dirname as dirname2, join as join2, resolve as resolve2, sep } from "path";
10942
-
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
- }
11581
+ import { lstat as lstat2, mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rename, rm, stat as stat2, writeFile as writeFile2 } from "fs/promises";
11582
+ import { dirname as dirname4, join as join3, resolve as resolve3, sep } from "path";
10963
11583
 
10964
11584
  // ../../packages/node-files/src/selectionFile.ts
10965
11585
  init_define_RADICAL_BUILD();
10966
- import { lstat, mkdir, readFile, writeFile } from "fs/promises";
10967
- import { join, resolve } from "path";
11586
+ import { lstat, mkdir, readFile as readFile2, writeFile } from "fs/promises";
11587
+ import { dirname as dirname3, join as join2, resolve as resolve2 } from "path";
10968
11588
 
10969
11589
  // ../../packages/common/src/formats/forgeRunStatus.ts
10970
11590
  init_define_RADICAL_BUILD();
10971
11591
 
10972
11592
  // ../../packages/common/src/ai/forge/prompts.ts
10973
11593
  init_define_RADICAL_BUILD();
11594
+
11595
+ // ../../packages/common/src/check/sensors.ts
11596
+ init_define_RADICAL_BUILD();
11597
+ var SENSOR_NAMES = ["command", "json", "playwright"];
11598
+ function commandWords(line) {
11599
+ const words = [];
11600
+ let word = "";
11601
+ let quote2 = null;
11602
+ let started = false;
11603
+ for (const ch of line) {
11604
+ if (quote2) {
11605
+ if (ch === quote2) quote2 = null;
11606
+ else word += ch;
11607
+ } else if (ch === '"' || ch === "'") {
11608
+ quote2 = ch;
11609
+ started = true;
11610
+ } else if (/\s/.test(ch)) {
11611
+ if (started || word) words.push(word);
11612
+ word = "";
11613
+ started = false;
11614
+ } else {
11615
+ word += ch;
11616
+ }
11617
+ }
11618
+ if (started || word) words.push(word);
11619
+ return words;
11620
+ }
11621
+ function parseMeasure(text2) {
11622
+ if (typeof text2 !== "string") return [];
11623
+ return text2.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#")).map((raw) => {
11624
+ const [sensor = "", ...args] = commandWords(raw);
11625
+ return { raw, sensor, args };
11626
+ });
11627
+ }
11628
+ var isSensorName = (name) => SENSOR_NAMES.includes(name);
11629
+
11630
+ // ../../packages/common/src/ai/forge/prompts.ts
10974
11631
  var PRIMARY_TYPE_IDS_FOR_STAGE = {
10975
11632
  requirements: ["requirement"],
10976
11633
  domain: ["domain", "entity"],
@@ -11180,7 +11837,7 @@ function stageTask(stageId, descBlock, need) {
11180
11837
  "relations between them. This is the last stage: the behavior and quality",
11181
11838
  "spec is already fully formed, so let the architecture follow from it rather",
11182
11839
  "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",
11840
+ "condition, a scenario implying an async flow, or a set of screens implying a",
11184
11841
  "separate admin front-end should visibly shape how you decompose the system.",
11185
11842
  "Link each element to the requirement(s) it satisfies with a `satisfies`",
11186
11843
  "relation, AND link each existing `fitness-fn` node to whichever new element(s)",
@@ -11207,7 +11864,23 @@ function stageTask(stageId, descBlock, need) {
11207
11864
  "Task: propose fitness functions (`fitness-fn` nodes) that constrain the",
11208
11865
  "requirements already in the model \u2014 measurable guardrails for things like",
11209
11866
  "latency, availability, coupling, security posture, or delivery flow implied",
11210
- "by the description. Set `category` and a concrete `threshold` for each. No",
11867
+ "by the description. Classify each: `characteristic`, the ISO/IEC 25010",
11868
+ `quality it protects (${FITNESS_CHARACTERISTICS.join(", ")}); \`scope\`,`,
11869
+ "`atomic` (one part in one context: a unit test, a linter rule) or `holistic`",
11870
+ "(several parts together: latency under load); `cadence`, `triggered` with the",
11871
+ `\`trigger\` it runs on (${FITNESS_TRIGGERS.join(", ")}), \`continual\` (measured`,
11872
+ "all the time, in production) or `temporal` with `every` (when it falls due,",
11873
+ "e.g. `90d`); and `invocation`, `automated` or `manual` (a person reviews it;",
11874
+ "its metrics line is then `review(<name>) passed`). For an automated one, set",
11875
+ "`measure` only when you know which sensor of radical sense measures it",
11876
+ `(${SENSOR_NAMES.map((n) => `\`${n}\``).join(", ")}): one line per measurement, the sensor and its`,
11877
+ "arguments (`playwright tests/load.spec.ts --label env=staging`); otherwise",
11878
+ "leave it empty. In `metrics` put one condition",
11879
+ "per line that says when it passes: a measured value and its threshold, with",
11880
+ "the metric named as a sensor would report it",
11881
+ "(`checkout.latency.p95{env=prod} <= 300 ms`, `deps.cycles == 0`). Name no",
11882
+ "test there: the repository binds its tests in .radical/radical.json. Put what",
11883
+ "the conditions cannot say in the description. No",
11211
11884
  "systems/containers exist yet (C4 runs later, once this spec is settled), so",
11212
11885
  "link each fitness function to the requirement(s) it constrains with a",
11213
11886
  "`traces-to` relation FROM the requirement TO the fitness function (the",
@@ -11335,8 +12008,8 @@ function stageTask(stageId, descBlock, need) {
11335
12008
  " domain model's term everywhere), a scenario whose Given/When/Then",
11336
12009
  " contradicts a transition or the order of a process, a step, screen or",
11337
12010
  " 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.",
12011
+ " screen or element carries out, a fitness function whose conditions",
12012
+ " contradict a requirement, a relation that points the wrong way.",
11340
12013
  "3. Propose each fix as the smallest change, one finding per proposal, following",
11341
12014
  " the refinement rule below. Everything you change goes to the user first.",
11342
12015
  "",
@@ -11348,7 +12021,7 @@ function stageTask(stageId, descBlock, need) {
11348
12021
  }
11349
12022
 
11350
12023
  // ../../packages/common/src/formats/forgeRunStatus.ts
11351
- var FORGE_RUN_FILE = `${SELECTION_DIR}/forge-run.json`;
12024
+ var FORGE_RUN_FILE = `${STATE_DIR}/forge-run.json`;
11352
12025
  var FORGE_RUN_STALE_MS = 30 * 60 * 1e3;
11353
12026
  function serializeForgeRun(status, now4 = /* @__PURE__ */ new Date()) {
11354
12027
  const out = { version: 1, ...status, updatedAt: now4.toISOString() };
@@ -11363,6 +12036,87 @@ init_define_RADICAL_BUILD();
11363
12036
  // ../../packages/common/src/check/rules.ts
11364
12037
  init_define_RADICAL_BUILD();
11365
12038
 
12039
+ // ../../packages/common/src/repositoryMapping.ts
12040
+ init_define_RADICAL_BUILD();
12041
+ var REPOSITORY_FILE = ".radical/radical.json";
12042
+ var strings = (v) => typeof v === "string" ? [v] : Array.isArray(v) && v.every((x) => typeof x === "string") ? v : null;
12043
+ function parseRepositoryFile(text2, file = REPOSITORY_FILE) {
12044
+ let raw;
12045
+ try {
12046
+ raw = JSON.parse(text2);
12047
+ } catch (error) {
12048
+ throw new Error(`${file}: ${error.message}`);
12049
+ }
12050
+ const list = (key) => {
12051
+ const value = raw?.[key] ?? [];
12052
+ if (!Array.isArray(value)) throw new Error(`${file}: "${key}" is no list`);
12053
+ return value;
12054
+ };
12055
+ const name = (e) => typeof e?.name === "string" ? { name: e.name } : {};
12056
+ const settings = (key, lists) => {
12057
+ const value = raw?.[key];
12058
+ if (value === void 0) return void 0;
12059
+ if (!value || typeof value !== "object") throw new Error(`${file}: "${key}" is no object`);
12060
+ const out = {};
12061
+ for (const list2 of lists) {
12062
+ const v = value[list2];
12063
+ if (v === void 0) continue;
12064
+ const got = strings(v);
12065
+ if (!got) throw new Error(`${file}: "${key}.${list2}" is no list`);
12066
+ out[list2] = got;
12067
+ }
12068
+ return out;
12069
+ };
12070
+ const tests = settings("tests", ["include", "exclude"]);
12071
+ const ci = settings("ci", ["artifacts"]);
12072
+ return {
12073
+ ...tests ? { tests } : {},
12074
+ ...ci ? { ci } : {},
12075
+ implements: list("implements").map((e, i) => {
12076
+ const paths = strings(e?.paths);
12077
+ if (typeof e?.element !== "string" || !e.element || !paths) throw new Error(`${file}: implements[${i}] needs "element" (an id) and "paths" (a list of folders)`);
12078
+ return { element: e.element, ...name(e), paths };
12079
+ }),
12080
+ verifies: list("verifies").map((e, i) => {
12081
+ const tests2 = strings(e?.tests);
12082
+ if (typeof e?.element !== "string" || !e.element || !tests2) throw new Error(`${file}: verifies[${i}] needs "element" (an id) and "tests" (a list of test ids)`);
12083
+ return { element: e.element, ...name(e), tests: tests2 };
12084
+ })
12085
+ };
12086
+ }
12087
+ function serializeRepositoryFile(file) {
12088
+ const head = (m) => `"element": ${JSON.stringify(m.element)}${m.name !== void 0 ? `, "name": ${JSON.stringify(m.name)}` : ""}`;
12089
+ const implemented = file.implements.map((m) => ` { ${head(m)}, "paths": [${m.paths.map((p) => JSON.stringify(p)).join(", ")}] }`);
12090
+ const verified = file.verifies.map((v) => ` { ${head(v)}, "tests": [${v.tests.length ? `
12091
+ ${v.tests.map((t) => ` ${JSON.stringify(t)}`).join(",\n")}
12092
+ ` : ""}] }`);
12093
+ const section = (key, lines) => ` "${key}": [${lines.length ? `
12094
+ ${lines.join(",\n")}
12095
+ ` : ""}]`;
12096
+ const inline = (v) => `{ ${Object.entries(v).map(([k, list]) => `${JSON.stringify(k)}: [${list.map((x) => JSON.stringify(x)).join(", ")}]`).join(", ")} }`;
12097
+ const settings = [
12098
+ ...file.tests ? [` "tests": ${inline(file.tests)}`] : [],
12099
+ ...file.ci ? [` "ci": ${inline(file.ci)}`] : []
12100
+ ];
12101
+ return `{
12102
+ ${[...settings, section("implements", implemented), ...file.verifies.length ? [section("verifies", verified)] : []].join(",\n")}
12103
+ }
12104
+ `;
12105
+ }
12106
+ function testsBoundTo(verifies, id) {
12107
+ return verifies.find((v) => v.element === id)?.tests ?? [];
12108
+ }
12109
+ function builtIn(mapped, id, parentOf) {
12110
+ const byElement = new Map(mapped.map((m) => [m.element, m.paths]));
12111
+ const seen = /* @__PURE__ */ new Set();
12112
+ for (let at = id; at && !seen.has(at); at = parentOf(at)) {
12113
+ seen.add(at);
12114
+ const paths = byElement.get(at);
12115
+ if (paths) return { paths, from: at };
12116
+ }
12117
+ return null;
12118
+ }
12119
+
11366
12120
  // ../../packages/common/src/check/evidence.ts
11367
12121
  init_define_RADICAL_BUILD();
11368
12122
 
@@ -11370,9 +12124,9 @@ init_define_RADICAL_BUILD();
11370
12124
  init_define_RADICAL_BUILD();
11371
12125
  var SEPARATOR = /\s+›\s+/;
11372
12126
  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) => {
12127
+ function parseTestIds(text2) {
12128
+ if (typeof text2 !== "string") return [];
12129
+ return text2.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#")).map((raw) => {
11376
12130
  const [file, ...title] = raw.split(SEPARATOR);
11377
12131
  return { raw, file: normalize(file), title };
11378
12132
  });
@@ -11405,16 +12159,182 @@ function globMatch(glob, file) {
11405
12159
  return glob.startsWith("**") ? normalize(file) : m[1];
11406
12160
  }
11407
12161
 
12162
+ // ../../packages/common/src/check/metrics.ts
12163
+ init_define_RADICAL_BUILD();
12164
+ var TEST_LINE = /^test\((.+)\)(?:\s+passed)?$/;
12165
+ var REVIEW_LINE = /^review\((.+)\)\s+passed$/i;
12166
+ var REVIEW_METRIC = "review";
12167
+ var METRIC_LINE = /^([A-Za-z_][\w.:/-]*)\s*(?:\{([^}]*)\})?\s*(<=|>=|==|!=|=|<|>)\s*(-?\d+(?:\.\d+)?(?:e-?\d+)?)\s*(\S+)?$/i;
12168
+ var BASELINE_LINE = /^([A-Za-z_][\w.:/-]*)\s*(?:\{([^}]*)\})?\s*(<=|>=|==|!=|=|<|>)\s*baseline(?:\s*([+-])\s*(\d+(?:\.\d+)?(?:e-?\d+)?)\s*(%|[^\s%]+)?)?$/i;
12169
+ function parseLabels(text2) {
12170
+ const labels = {};
12171
+ for (const part of text2.split(",").map((p) => p.trim()).filter(Boolean)) {
12172
+ const m = /^([\w.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^"',]*))$/.exec(part);
12173
+ if (!m) return `"${part}" is no label (name=value)`;
12174
+ labels[m[1]] = (m[2] ?? m[3] ?? m[4]).trim();
12175
+ }
12176
+ return labels;
12177
+ }
12178
+ function parseCondition(line) {
12179
+ const raw = line.trim();
12180
+ const test = TEST_LINE.exec(raw);
12181
+ if (test) {
12182
+ const [id] = parseTestIds(test[1]);
12183
+ return id ? { kind: "test", raw, id } : { kind: "invalid", raw, problem: "test() names no test" };
12184
+ }
12185
+ const review = REVIEW_LINE.exec(raw);
12186
+ if (review) return { kind: "metric", raw, metric: REVIEW_METRIC, labels: { name: review[1].trim() }, op: "==", value: 1 };
12187
+ const b = BASELINE_LINE.exec(raw);
12188
+ if (b) {
12189
+ const labels2 = b[2] === void 0 ? {} : parseLabels(b[2]);
12190
+ if (typeof labels2 === "string") return { kind: "invalid", raw, problem: labels2 };
12191
+ if (b[4] && !b[6]) return { kind: "invalid", raw, problem: "a margin on the baseline needs % or a unit (`baseline + 20%`, `baseline + 500 ms`)" };
12192
+ 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 };
12193
+ return { kind: "metric", raw, metric: b[1], labels: labels2, op: b[3] === "=" ? "==" : b[3], value: Number.NaN, baseline };
12194
+ }
12195
+ const m = METRIC_LINE.exec(raw);
12196
+ 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]`" };
12197
+ const labels = m[2] === void 0 ? {} : parseLabels(m[2]);
12198
+ if (typeof labels === "string") return { kind: "invalid", raw, problem: labels };
12199
+ return { kind: "metric", raw, metric: m[1], labels, op: m[3] === "=" ? "==" : m[3], value: Number(m[4]), ...m[5] ? { unit: m[5] } : {} };
12200
+ }
12201
+ function parseConditions(text2) {
12202
+ if (typeof text2 !== "string") return [];
12203
+ return text2.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#")).map(parseCondition);
12204
+ }
12205
+ function parseCombine(text2) {
12206
+ const t = typeof text2 === "string" ? text2.trim().toLowerCase() : "";
12207
+ if (!t || t === "all") return { kind: "all" };
12208
+ if (t === "any") return { kind: "any" };
12209
+ const m = /^at\s+least\s+(\d+)$/.exec(t);
12210
+ return m && Number(m[1]) > 0 ? { kind: "at-least", n: Number(m[1]) } : null;
12211
+ }
12212
+ var AGE_UNITS = { s: 1e3, m: 6e4, min: 6e4, h: 36e5, d: 864e5, w: 7 * 864e5 };
12213
+ function parseMaxAge(text2) {
12214
+ const t = typeof text2 === "string" ? text2.trim().toLowerCase() : "";
12215
+ if (!t) return void 0;
12216
+ const m = /^(\d+(?:\.\d+)?)\s*(s|min|m|h|d|w)$/.exec(t);
12217
+ return m ? Number(m[1]) * AGE_UNITS[m[2]] : null;
12218
+ }
12219
+ var UNIT_FAMILIES = [
12220
+ { ns: 1e-9, us: 1e-6, "\xB5s": 1e-6, ms: 1e-3, s: 1, min: 60, h: 3600, d: 86400 },
12221
+ { b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12, kib: 1024, mib: 1024 ** 2, gib: 1024 ** 3, tib: 1024 ** 4 }
12222
+ ];
12223
+ function convertUnit(value, from, to) {
12224
+ if (from === to) return value;
12225
+ const f = from.toLowerCase();
12226
+ const t = to.toLowerCase();
12227
+ if (f === t) return value;
12228
+ const family = UNIT_FAMILIES.find((u) => u[f] !== void 0 && u[t] !== void 0);
12229
+ return family ? value * family[f] / family[t] : null;
12230
+ }
12231
+ var COMPARE = {
12232
+ "<": (a, b) => a < b,
12233
+ "<=": (a, b) => a <= b,
12234
+ ">": (a, b) => a > b,
12235
+ ">=": (a, b) => a >= b,
12236
+ "==": (a, b) => a === b,
12237
+ "!=": (a, b) => a !== b
12238
+ };
12239
+ function latestMeasurement(condition, measurements) {
12240
+ let latest;
12241
+ for (const m of measurements) {
12242
+ if (m.metric !== condition.metric) continue;
12243
+ if (Object.entries(condition.labels).some(([k, v]) => m.labels[k] !== v)) continue;
12244
+ if (!latest || Date.parse(m.at) > Date.parse(latest.at)) latest = m;
12245
+ }
12246
+ return latest;
12247
+ }
12248
+ var DAY = 864e5;
12249
+ 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`;
12250
+ var BASELINE_RUNS = 7;
12251
+ function baselineOf(condition, baseline, unit) {
12252
+ 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);
12253
+ if (!values.length) return void 0;
12254
+ const mid = Math.floor(values.length / 2);
12255
+ return { median: values.length % 2 ? values[mid] : (values[mid - 1] + values[mid]) / 2, runs: values.length };
12256
+ }
12257
+ var round = (n) => Math.round(n * 100) / 100;
12258
+ function evaluateMetric(condition, measurements, maxAge, now4, baseline = []) {
12259
+ const measurement = latestMeasurement(condition, measurements);
12260
+ if (!measurement) return { outcome: "not-run" };
12261
+ const age = now4 - Date.parse(measurement.at);
12262
+ if (condition.baseline) {
12263
+ if (maxAge !== void 0 && age > maxAge) return { outcome: "stale", measurement, detail: `measured ${formatAge(age)} ago` };
12264
+ const unit = measurement.unit;
12265
+ const base = baselineOf(condition, baseline, unit);
12266
+ if (!base) return { outcome: "not-run", measurement, detail: "no baseline to compare with" };
12267
+ const { sign, by, percent } = condition.baseline;
12268
+ let margin = percent ? base.median * by / 100 : by;
12269
+ if (!percent && condition.baseline.unit && unit) {
12270
+ const converted = convertUnit(by, condition.baseline.unit, unit);
12271
+ if (converted === null) return { outcome: "invalid", measurement, detail: `the measurement is in ${unit}, which ${condition.baseline.unit} does not convert to` };
12272
+ margin = converted;
12273
+ }
12274
+ const limit = base.median + sign * margin;
12275
+ const outcome = COMPARE[condition.op](measurement.value, limit) ? "passed" : "failed";
12276
+ return { outcome, measurement, detail: `baseline ${round(base.median)}${unit ? ` ${unit}` : ""}, the median of ${base.runs}; limit ${round(limit)}${unit ? ` ${unit}` : ""}` };
12277
+ }
12278
+ let value = measurement.value;
12279
+ if (condition.unit && measurement.unit) {
12280
+ const converted = convertUnit(measurement.value, measurement.unit, condition.unit);
12281
+ if (converted === null) return { outcome: "invalid", measurement, detail: `the measurement is in ${measurement.unit}, which does not convert to ${condition.unit}` };
12282
+ value = converted;
12283
+ }
12284
+ if (maxAge !== void 0 && age > maxAge) return { outcome: "stale", measurement, detail: `measured ${formatAge(age)} ago` };
12285
+ return { outcome: COMPARE[condition.op](value, condition.value) ? "passed" : "failed", measurement };
12286
+ }
12287
+
11408
12288
  // ../../packages/common/src/check/evidence.ts
11409
12289
  var TESTED_TYPES = ["scenario", "fitness-fn"];
11410
- var testIdsOf = (node) => parseTestIds(node.tests);
12290
+ var BOUND_TESTS = "boundTests";
12291
+ function withBoundTests(nodes, verifies) {
12292
+ if (!verifies?.length) return nodes;
12293
+ const bound = /* @__PURE__ */ new Map();
12294
+ for (const v of verifies) bound.set(v.element, [...bound.get(v.element) ?? [], ...v.tests]);
12295
+ return nodes.map((n) => bound.has(n.id) ? { ...n, [BOUND_TESTS]: bound.get(n.id) } : n);
12296
+ }
12297
+ var conditionsOf = (node) => {
12298
+ const bound = node[BOUND_TESTS];
12299
+ return [
12300
+ ...parseConditions(node.metrics),
12301
+ ...Array.isArray(bound) ? bound.map((id) => parseCondition(`test(${id}) passed`)) : []
12302
+ ];
12303
+ };
12304
+ var testIdsOf = (node) => conditionsOf(node).flatMap((c) => c.kind === "test" ? [c.id] : []);
12305
+ var testOutcome = (id, model) => {
12306
+ const { fileSeen, matches } = findTests(id, model.tests ?? []);
12307
+ return matches.length ? outcomeOf(matches) : fileSeen ? "not-found" : "not-run";
12308
+ };
11411
12309
  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" };
12310
+ return testIdsOf(node).map((id) => ({ id, outcome: testOutcome(id, model) }));
12311
+ }
12312
+ function conditionResults(node, model, element) {
12313
+ const maxAge = parseMaxAge(node.max_age) ?? void 0;
12314
+ const now4 = model.now ?? Date.now();
12315
+ return conditionsOf(node).map((c) => {
12316
+ if (c.kind === "invalid") return { condition: c.raw, outcome: "invalid", detail: c.problem };
12317
+ if (c.kind === "test") return { condition: c.raw, test: c.id.raw, outcome: testOutcome(c.id, model) };
12318
+ const metric = element ? { ...c, labels: { ...c.labels, [ELEMENT_LABEL]: element.id } } : c;
12319
+ const e = evaluateMetric(metric, model.measurements ?? [], maxAge, now4, model.baseline ?? []);
12320
+ return { condition: c.raw, outcome: e.outcome, ...e.measurement ? { measurement: e.measurement } : {}, ...e.detail ? { detail: e.detail } : {} };
11416
12321
  });
11417
12322
  }
12323
+ var ELEMENT_LABEL = "element";
12324
+ function appliedElements(model, ff) {
12325
+ const seen = /* @__PURE__ */ new Set();
12326
+ return linkedNodes(model, ff.id, "implements", "target", "adr").flatMap((adr) => linkedNodes(model, adr.id, "constrains", "target")).filter((n) => !seen.has(n.id) && !!seen.add(n.id));
12327
+ }
12328
+ function measuredElements(model, ff) {
12329
+ if (ff.type !== "fitness-fn") return [];
12330
+ const metrics = new Set(conditionsOf(ff).flatMap((c) => c.kind === "metric" ? [c.metric] : []));
12331
+ const perElement = (model.measurements ?? []).some((m) => metrics.has(m.metric) && ELEMENT_LABEL in m.labels);
12332
+ return perElement ? appliedElements(model, ff).filter((n) => !originOf(n)) : [];
12333
+ }
12334
+ function elementConditions(node, model, element) {
12335
+ const metricLines = new Set(conditionsOf(node).flatMap((c) => c.kind === "metric" ? [c.raw] : []));
12336
+ return conditionResults(node, model, element).filter((r) => metricLines.has(r.condition));
12337
+ }
11418
12338
  function linkedNodes(model, id, relationType, end, type) {
11419
12339
  return Object.values(model.relations).filter((r) => r.relationType === relationType && (end === "source" ? r.targetId : r.sourceId) === id).map((r) => model.nodes[end === "source" ? r.sourceId : r.targetId]).filter((n) => !!n && (!type || n.type === type));
11420
12340
  }
@@ -11565,7 +12485,8 @@ function buildConceptInsert(concept, options) {
11565
12485
  const offsetX = corner.x - (bounded ? minX : 0);
11566
12486
  const offsetY = corner.y - (bounded ? minY : 0);
11567
12487
  const nodes = {};
11568
- for (const raw of templated.nodes) {
12488
+ for (const node of templated.nodes) {
12489
+ const raw = migrateCheckFields(node);
11569
12490
  const oldId = raw.id;
11570
12491
  const id = idMap.get(oldId);
11571
12492
  const type = raw.type ?? "component";
@@ -11641,7 +12562,7 @@ function templateRecord(concept, paramValues, maps) {
11641
12562
  for (const origNode of concept.nodes) {
11642
12563
  const id = maps.node.get(origNode.id);
11643
12564
  if (!id) continue;
11644
- originalNodes[id] = origNode;
12565
+ originalNodes[id] = migrateCheckFields(origNode);
11645
12566
  const perNodeParams = origNode.templateParams;
11646
12567
  if (perNodeParams?.length) nodeParamsMap[id] = perNodeParams;
11647
12568
  }
@@ -11900,6 +12821,7 @@ function unlinked(model, type, relation, end, otherTypes) {
11900
12821
  }
11901
12822
  var quote = (n) => `"${n.label}"`;
11902
12823
  var TYPE_NAME = { scenario: "Scenario", "fitness-fn": "Fitness function" };
12824
+ var TYPE_LABEL = (node) => TYPE_NAME[node.type] ?? node.type.charAt(0).toUpperCase() + node.type.slice(1);
11903
12825
  var affectedBy = (model, node) => node.type === "scenario" ? linkedNodes(model, node.id, "verifies", "target", "requirement") : linkedNodes(model, node.id, "implements", "target", "adr");
11904
12826
  function brokenWith(model, node) {
11905
12827
  const affected = affectedBy(model, node);
@@ -11917,6 +12839,77 @@ function testRule(outcome, message) {
11917
12839
  }));
11918
12840
  };
11919
12841
  }
12842
+ var runsOn = (node, trigger) => {
12843
+ if (!trigger || node.type !== "fitness-fn") return true;
12844
+ const cadence = prop2(node, "cadence");
12845
+ if (!cadence) return true;
12846
+ return cadence === "triggered" && prop2(node, "trigger") === trigger;
12847
+ };
12848
+ function metricRule(outcome, message) {
12849
+ return (model) => {
12850
+ if (!model.measurements) return [];
12851
+ return Object.values(model.nodes).filter((n) => TESTED_TYPES.includes(n.type)).filter((n) => outcome !== "not-run" || runsOn(n, model.trigger)).flatMap((node) => {
12852
+ const seen = (r) => {
12853
+ const m = r.measurement;
12854
+ return m ? ` (${m.value}${m.unit ? ` ${m.unit}` : ""} from ${m.source}, ${formatAge((model.now ?? Date.now()) - Date.parse(m.at))} ago)` : "";
12855
+ };
12856
+ const elements = measuredElements(model, node);
12857
+ if (elements.length) {
12858
+ const origin = originOf(node);
12859
+ return elements.flatMap((element) => elementConditions(node, model, element).filter((r) => r.outcome === outcome).map((r) => ({
12860
+ nodeId: origin ? element.id : node.id,
12861
+ message: `${message(node, r.condition, seen(r), r.detail).replace(/\.$/, "")} for ${TYPE_NAME[element.type] ?? element.type} ${quote(element)}${origin ? ` (a fitness function of ${origin})` : ""}.`,
12862
+ ...origin ? { relatedIds: [node.id] } : outcome === "failed" ? { relatedIds: [element.id] } : {}
12863
+ })));
12864
+ }
12865
+ const metricLines = new Set(conditionsOf(node).filter((c) => c.kind === "metric").map((c) => c.raw));
12866
+ return conditionResults(node, model).filter((r) => r.outcome === outcome && metricLines.has(r.condition)).map((r) => {
12867
+ const related = outcome === "failed" ? affectedBy(model, node).map((n) => n.id) : [];
12868
+ return { nodeId: node.id, message: message(node, r.condition, seen(r), r.detail), ...related.length ? { relatedIds: related } : {} };
12869
+ });
12870
+ });
12871
+ };
12872
+ }
12873
+ function verifiedHere(model, scenario) {
12874
+ const mapped = model.repository?.implements;
12875
+ if (!mapped?.length || originOf(scenario)) return false;
12876
+ return linkedNodes(model, scenario.id, "verifies", "target", "requirement").some((req) => linkedNodes(model, req.id, "satisfies", "source").some((el) => builtIn(mapped, el.id, (id) => model.nodes[id]?.parentId)));
12877
+ }
12878
+ function repositoryMapping(model) {
12879
+ const mapping = model.repository;
12880
+ if (!mapping) return [];
12881
+ return mapping.implements.flatMap((entry) => {
12882
+ const node = model.nodes[entry.element];
12883
+ if (!node) return [{ message: `${mapping.file}: ${entry.name ? `"${entry.name}" (${entry.element})` : entry.element} is no element of the model.` }];
12884
+ const on = originOf(node) ? {} : { nodeId: node.id };
12885
+ const found = [];
12886
+ if (entry.name !== void 0 && entry.name !== node.label) found.push({ ...on, message: `${mapping.file}: ${entry.element} is named "${entry.name}"; the model calls it ${quote(node)}.` });
12887
+ for (const path of entry.missing) found.push({ ...on, message: `${mapping.file}: ${quote(node)} is built in ${path}, which the repository does not have.` });
12888
+ return found;
12889
+ }).concat((mapping.verifies ?? []).flatMap((entry) => {
12890
+ const node = model.nodes[entry.element];
12891
+ if (!node) return [{ message: `${mapping.file}: tests bound to ${entry.name ? `"${entry.name}" (${entry.element})` : entry.element}, which is no element of the model.` }];
12892
+ const on = originOf(node) ? {} : { nodeId: node.id };
12893
+ const found = [];
12894
+ if (!TESTED_TYPES.includes(node.type)) found.push({ ...on, message: `${mapping.file}: tests bound to ${node.type} ${quote(node)}; only a scenario or a fitness function is checked by tests.` });
12895
+ if (entry.name !== void 0 && entry.name !== node.label) found.push({ ...on, message: `${mapping.file}: ${entry.element} is named "${entry.name}"; the model calls it ${quote(node)}.` });
12896
+ return found;
12897
+ }));
12898
+ }
12899
+ function invalidChecks(model) {
12900
+ return Object.values(model.nodes).filter((n) => TESTED_TYPES.includes(n.type)).flatMap((node) => {
12901
+ const what = `${TYPE_NAME[node.type]} ${quote(node)}`;
12902
+ const found = conditionsOf(node).flatMap((c) => c.kind === "invalid" ? [{ nodeId: node.id, message: `${what}: "${c.raw}" cannot be read: ${c.problem}.` }] : []);
12903
+ if (model.measurements) {
12904
+ for (const r of conditionResults(node, model)) {
12905
+ if (r.outcome === "invalid" && r.measurement) found.push({ nodeId: node.id, message: `${what}: "${r.condition}" cannot be evaluated: ${r.detail}.` });
12906
+ }
12907
+ }
12908
+ if (!parseCombine(prop2(node, "combine"))) found.push({ nodeId: node.id, message: `${what}: combine "${prop2(node, "combine")}" is none of all, any, at least N.` });
12909
+ 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.` });
12910
+ return found;
12911
+ });
12912
+ }
11920
12913
  var CHECK_RULES = [
11921
12914
  {
11922
12915
  id: "metamodel",
@@ -12048,25 +13041,99 @@ var CHECK_RULES = [
12048
13041
  }))
12049
13042
  },
12050
13043
  {
12051
- id: "fitness-fn-without-threshold",
12052
- description: "Every fitness function states its threshold or success criteria.",
13044
+ id: "scenario-without-metrics",
13045
+ description: "Every scenario has what checks it: tests the repository's .radical/radical.json binds to it, or metric conditions (property `metrics`, one per line: `<metric>{<labels>} <op> <number> [unit]`). One the repository must verify is scenario-not-verified-here's.",
12053
13046
  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.` }))
13047
+ dimension: "traceability",
13048
+ run: (model) => nodesOf(model, "scenario").filter((n) => !conditionsOf(n).length && !verifiedHere(model, n)).map((n) => ({ nodeId: n.id, message: `Scenario ${quote(n)} names no check.` }))
13049
+ },
13050
+ {
13051
+ id: "scenario-not-verified-here",
13052
+ description: "With the repository's .radical/radical.json (the CLI): every scenario of a requirement an element the repository builds satisfies has tests the file binds to it, or metric conditions.",
13053
+ severity: "warning",
13054
+ dimension: "traceability",
13055
+ run: (model) => nodesOf(model, "scenario").filter((n) => !conditionsOf(n).length && verifiedHere(model, n)).map((n) => ({ nodeId: n.id, message: `Scenario ${quote(n)} is this repository's to verify (an element it builds satisfies its requirement), and ${model.repository.file} binds no test to it: radical verify ${n.id} --test "<file> \u203A <title>".` }))
12056
13056
  },
12057
13057
  {
12058
- id: "scenario-without-tests",
12059
- description: "Every scenario names the automated tests that run it (property `tests`, one `file \u203A title` per line).",
13058
+ id: "model-names-tests",
13059
+ description: "A scenario or fitness function names no test in its Metrics: the repository binds its tests in .radical/radical.json (radical setup moves them there). A test named in Metrics still counts.",
12060
13060
  severity: "warning",
12061
13061
  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.` }))
13062
+ run: (model) => Object.values(model.nodes).filter((n) => TESTED_TYPES.includes(n.type) && !originOf(n)).flatMap((n) => {
13063
+ const named = parseConditions(n.metrics).filter((c) => c.kind === "test").length;
13064
+ return named ? [{ nodeId: n.id, message: `${TYPE_NAME[n.type]} ${quote(n)} names ${named} test${named === 1 ? "" : "s"} in its Metrics; ${named === 1 ? "it belongs" : "they belong"} in .radical/radical.json (radical setup moves them).` }] : [];
13065
+ })
13066
+ },
13067
+ {
13068
+ id: "fitness-fn-without-metrics",
13069
+ description: "Every fitness function states what checks it and when it passes (property `metrics`, one condition per line).",
13070
+ severity: "warning",
13071
+ dimension: "decisions",
13072
+ 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
13073
  },
12064
13074
  {
12065
- id: "fitness-fn-without-tests",
12066
- description: "Every fitness function names the automated checks that run it (property `tests`).",
13075
+ id: "fitness-fn-unclassified",
13076
+ 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
13077
  severity: "warning",
12068
13078
  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.` }))
13079
+ run: (model) => nodesOf(model, "fitness-fn").flatMap((n) => {
13080
+ const missing = ["characteristic", "scope", "cadence"].filter((k) => !prop2(n, k));
13081
+ if (prop2(n, "cadence") === "triggered" && !prop2(n, "trigger")) missing.push("trigger");
13082
+ if (prop2(n, "cadence") === "temporal" && !prop2(n, "every")) missing.push("every");
13083
+ if (!prop2(n, "invocation")) missing.push("invocation");
13084
+ return missing.length ? [{ nodeId: n.id, message: `Fitness function ${quote(n)} states no ${missing.join(", ")}.` }] : [];
13085
+ })
13086
+ },
13087
+ {
13088
+ id: "fitness-fn-measure-invalid",
13089
+ description: `Every line of a fitness function's \`measure\` names a sensor of radical sense (${SENSOR_NAMES.join(", ")}) or, run by the CLI, one of the repository's .radical/sensors/sensors.json.`,
13090
+ severity: "error",
13091
+ dimension: "completeness",
13092
+ run: (model) => model.sensors === void 0 ? [] : nodesOf(model, "fitness-fn").flatMap((n) => parseMeasure(n.measure).filter((line) => !isSensorName(line.sensor) && !model.sensors?.names.includes(line.sensor)).map((line) => ({
13093
+ nodeId: n.id,
13094
+ message: `Fitness function ${quote(n)}: measure "${line.raw}" names no sensor; radical sense has ${SENSOR_NAMES.join(", ")}, ${model.sensors ? `${model.sensors.file} ${model.sensors.names.length ? model.sensors.names.join(", ") : "none"}` : "and the repository has no .radical/sensors/sensors.json"}.`
13095
+ })))
13096
+ },
13097
+ {
13098
+ id: "repository-mapping",
13099
+ description: "With the repository's .radical/radical.json (the CLI): each entry names an element of the model, its own or another model's of the federation, under the element's name, with paths the repository has; tests are bound to scenarios and fitness functions.",
13100
+ severity: "warning",
13101
+ dimension: "traceability",
13102
+ run: repositoryMapping
13103
+ },
13104
+ {
13105
+ id: "repository-settings-in-model",
13106
+ description: `The model's check.json holds the model's rules and goals; the repository's test files (test-unbound's include and exclude) and CI's artifacts belong in .radical/radical.json ("tests", "ci"). Those in check.json are still read.`,
13107
+ severity: "warning",
13108
+ dimension: "completeness",
13109
+ run: (model) => (model.settingsInModel ?? []).map((what) => ({
13110
+ path: "check.json",
13111
+ message: `check.json holds the repository's ${what}; ${what.startsWith("ci") ? 'they belong in .radical/radical.json ("ci": { "artifacts": [...] })' : 'it belongs in .radical/radical.json ("tests": { "include": [...], "exclude": [...] })'}.`
13112
+ }))
13113
+ },
13114
+ {
13115
+ id: "description-path-missing",
13116
+ description: "With the repository (the CLI): a path from the repository's root an element's description names (apps/cli/src/sense.ts) is in the repository; one that is gone tells of code that moved.",
13117
+ severity: "warning",
13118
+ dimension: "consistency",
13119
+ run: (model) => Object.entries(model.missingPaths ?? {}).flatMap(([id, paths]) => {
13120
+ const node = model.nodes[id];
13121
+ return node && paths.length ? [{ nodeId: id, message: `${TYPE_LABEL(node)} ${quote(node)} names ${paths.join(", ")}, which the repository does not have.` }] : [];
13122
+ })
13123
+ },
13124
+ {
13125
+ id: "measure-with-arguments",
13126
+ description: `A fitness function's measure lines name sensors only: an adapter's arguments (files, options of the repository) belong to a sensor of .radical/sensors/sensors.json ({ "adapter": "playwright", "args": [...] }). A line with arguments still runs.`,
13127
+ severity: "warning",
13128
+ dimension: "completeness",
13129
+ run: (model) => nodesOf(model, "fitness-fn").flatMap((n) => parseMeasure(n.measure).filter((line) => line.args.length > 0).map((line) => ({ nodeId: n.id, message: `Fitness function ${quote(n)}: measure "${line.raw}" has the repository's arguments; name a sensor of .radical/sensors/sensors.json that holds them ({ "adapter": "${line.sensor}", "args": [...] }).` })))
13130
+ },
13131
+ {
13132
+ id: "metric-invalid",
13133
+ 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.",
13134
+ severity: "error",
13135
+ dimension: "completeness",
13136
+ run: invalidChecks
12070
13137
  },
12071
13138
  {
12072
13139
  id: "test-failed",
@@ -12082,7 +13149,7 @@ var CHECK_RULES = [
12082
13149
  severity: "error",
12083
13150
  dimension: "tests",
12084
13151
  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)}`)
13152
+ 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
13153
  },
12087
13154
  {
12088
13155
  id: "test-skipped",
@@ -12100,6 +13167,30 @@ var CHECK_RULES = [
12100
13167
  readsReports: true,
12101
13168
  run: testRule("not-run", (node, id) => `${TYPE_NAME[node.type]} ${quote(node)}: no report has the file of test ${id}.`)
12102
13169
  },
13170
+ {
13171
+ id: "metric-failed",
13172
+ description: "With measurements: every metric condition a scenario or fitness function states holds for the latest measurement it matches.",
13173
+ severity: "error",
13174
+ dimension: "tests",
13175
+ readsMeasurements: true,
13176
+ run: metricRule("failed", (node, condition, seen, why) => `${TYPE_NAME[node.type]} ${quote(node)}: ${condition} does not hold${seen}${why ? `; ${why}` : ""}.`)
13177
+ },
13178
+ {
13179
+ id: "metric-stale",
13180
+ description: "With measurements: the latest measurement each metric condition matches is no older than the element's max_age (a stale one never passes).",
13181
+ severity: "warning",
13182
+ dimension: "tests",
13183
+ readsMeasurements: true,
13184
+ run: metricRule("stale", (node, condition, seen) => `${TYPE_NAME[node.type]} ${quote(node)}: ${condition} has only a stale measurement${seen}.`)
13185
+ },
13186
+ {
13187
+ id: "metric-not-measured",
13188
+ description: "With measurements: a measurement matches every metric condition a scenario or fitness function states.",
13189
+ severity: "warning",
13190
+ dimension: "tests",
13191
+ readsMeasurements: true,
13192
+ 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}.`)
13193
+ },
12103
13194
  {
12104
13195
  id: "test-unbound",
12105
13196
  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 +13262,21 @@ var CHECK_METRICS = [
12171
13262
  byRule("elements-valid", "Elements the metamodel allows", "Elements no metamodel issue points at.", "consistency", "metamodel", (m) => Object.values(m.nodes)),
12172
13263
  byRule("requirements-complete", "Complete requirements", "Requirements with an action and every field their EARS type reads.", "completeness", "requirement-incomplete", (m) => nodesOf(m, "requirement")),
12173
13264
  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
13265
  byRule("needs-with-requirement", "Needs with a requirement", "Needs at least one requirement derives from.", "traceability", "need-without-requirement", (m) => nodesOf(m, "need")),
12176
13266
  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
13267
  byRule("requirements-satisfied", "Requirements satisfied", "Requirements an element of the architecture satisfies.", "traceability", "requirement-unsatisfied", (m) => nodesOf(m, "requirement")),
12178
13268
  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
13269
  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")),
13270
+ 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
13271
  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
13272
  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")),
13273
+ 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
13274
  {
12185
13275
  id: "requirements-verified",
12186
13276
  label: "Requirements verified",
12187
13277
  dimension: "behaviour",
12188
13278
  tests: true,
12189
- description: "Requirements whose scenarios all name tests that passed.",
13279
+ description: "Requirements whose scenarios all passed their checks.",
12190
13280
  measure: (ctx) => withStatus(nodesOf(ctx.model, "requirement"), ["verified"], ctx)
12191
13281
  },
12192
13282
  {
@@ -12194,7 +13284,7 @@ var CHECK_METRICS = [
12194
13284
  label: "Scenarios passing",
12195
13285
  dimension: "behaviour",
12196
13286
  tests: true,
12197
- description: "Scenarios whose tests all passed.",
13287
+ description: "Scenarios whose checks passed.",
12198
13288
  measure: (ctx) => withStatus(nodesOf(ctx.model, "scenario"), ["passed"], ctx)
12199
13289
  },
12200
13290
  {
@@ -12202,7 +13292,7 @@ var CHECK_METRICS = [
12202
13292
  label: "Accepted ADRs verified",
12203
13293
  dimension: "fitness",
12204
13294
  tests: true,
12205
- description: "Accepted ADRs whose fitness functions all name checks that passed.",
13295
+ description: "Accepted ADRs whose fitness functions all passed their checks.",
12206
13296
  measure: (ctx) => withStatus(acceptedAdrs(ctx.model), ["verified"], ctx)
12207
13297
  },
12208
13298
  {
@@ -12210,7 +13300,7 @@ var CHECK_METRICS = [
12210
13300
  label: "Fitness functions passing",
12211
13301
  dimension: "fitness",
12212
13302
  tests: true,
12213
- description: "Fitness functions whose checks all passed.",
13303
+ description: "Fitness functions whose checks passed.",
12214
13304
  measure: (ctx) => withStatus(nodesOf(ctx.model, "fitness-fn"), ["passed"], ctx)
12215
13305
  },
12216
13306
  {
@@ -12243,7 +13333,11 @@ var METRIC_IDS = new Set(CHECK_METRICS.map((m) => m.id));
12243
13333
 
12244
13334
  // ../../packages/common/src/check/files.ts
12245
13335
  init_define_RADICAL_BUILD();
12246
- var TEST_RESULTS_FILE = `${SELECTION_DIR}/test-results.json`;
13336
+ var TEST_RESULTS_FILE = `${STATE_DIR}/test-results.json`;
13337
+ var MEASUREMENTS_FILE = `${STATE_DIR}/measurements.json`;
13338
+
13339
+ // ../../packages/common/src/check/reviews.ts
13340
+ init_define_RADICAL_BUILD();
12247
13341
 
12248
13342
  // ../../packages/common/src/check/format.ts
12249
13343
  init_define_RADICAL_BUILD();
@@ -12266,21 +13360,131 @@ var ALL_RULES = [...FOLDER_RULES, ...CHECK_RULES, GOAL_RULE];
12266
13360
  var RULE_IDS = new Set(ALL_RULES.map((r) => r.id));
12267
13361
  var DEFAULT_SEVERITY = new Map(ALL_RULES.map((r) => [r.id, r.severity]));
12268
13362
 
13363
+ // ../../packages/common/src/federation.ts
13364
+ init_define_RADICAL_BUILD();
13365
+ var FEDERATION_FILE = `${STATE_DIR}/federation.json`;
13366
+ function parseFederationFile(text2) {
13367
+ if (!text2) return null;
13368
+ try {
13369
+ const raw = JSON.parse(text2);
13370
+ if (raw.version !== 2 || !Array.isArray(raw.nodes) || !Array.isArray(raw.relations) || !Array.isArray(raw.dependencies)) return null;
13371
+ return { notes: [], name: "", fetchedAt: "", ...raw };
13372
+ } catch {
13373
+ return null;
13374
+ }
13375
+ }
13376
+ function withOtherModels(data, file) {
13377
+ if (!file) return data;
13378
+ if (!file.nodes.length && !file.relations.length && !file.views?.length) return { ...data, federation: file };
13379
+ const ownNodes = new Set(data.nodes.map((n) => n.id));
13380
+ const ownRelations = new Set(data.relations.map((r) => r.id));
13381
+ const nodes = file.nodes.filter((n) => !ownNodes.has(n.id) && originOf(n)).map((n) => {
13382
+ const at = data.defaultPositions?.[n.id];
13383
+ return at ? { ...n, x: at.x, y: at.y, ...at.width ? { width: at.width } : {}, ...at.height ? { height: at.height } : {} } : n;
13384
+ });
13385
+ const all = /* @__PURE__ */ new Set([...ownNodes, ...nodes.map((n) => n.id)]);
13386
+ const relations = file.relations.filter((r) => !ownRelations.has(r.id) && originOf(r) && all.has(r.sourceId) && all.has(r.targetId));
13387
+ const ownViews = new Set((data.views ?? []).map((v) => v.id));
13388
+ const dependsOn = new Map(file.dependencies.map((d) => [d.name, d.dependsOn ?? []]));
13389
+ const scopeOf = (name) => {
13390
+ const scope = /* @__PURE__ */ new Set();
13391
+ const walk = (n) => {
13392
+ if (scope.has(n)) return;
13393
+ scope.add(n);
13394
+ for (const d of dependsOn.get(n) ?? []) walk(d);
13395
+ };
13396
+ walk(name);
13397
+ return [...scope];
13398
+ };
13399
+ const views = (file.views ?? []).filter((v) => !ownViews.has(v.id) && originOf(v)).map((v) => {
13400
+ const model = originModel(v.origin);
13401
+ return { ...v, folder: normalizeViewFolder(v.folder ? `${model}/${v.folder}` : model), originScope: scopeOf(model) };
13402
+ });
13403
+ return {
13404
+ ...data,
13405
+ nodes: [...data.nodes, ...nodes],
13406
+ relations: [...data.relations, ...relations],
13407
+ ...views.length ? { views: [...data.views ?? [], ...views] } : {},
13408
+ federation: file
13409
+ };
13410
+ }
13411
+
13412
+ // ../../packages/node-files/src/repositoryLayout.ts
13413
+ init_define_RADICAL_BUILD();
13414
+ import { readFile, readdir, stat } from "fs/promises";
13415
+ import { basename, dirname as dirname2, join, resolve } from "path";
13416
+ var RADICAL_DIR = ".radical";
13417
+ var MODEL_FOLDER = `${RADICAL_DIR}/model`;
13418
+ var OLD_MODEL_FOLDER = "architecture";
13419
+ var SENSORS_FILE = `${RADICAL_DIR}/sensors/sensors.json`;
13420
+ var CRUCIBLE_FILE = `${RADICAL_DIR}/crucible/crucible.json`;
13421
+ var CRUCIBLE_FINDINGS = `${RADICAL_DIR}/crucible/findings`;
13422
+ var CRUCIBLE_ROUNDS = `${RADICAL_DIR}/crucible/rounds`;
13423
+ var REVIEWS_FILE2 = `${RADICAL_DIR}/reviews.json`;
13424
+ var OLD_REVIEWS_FILE = `${MODEL_FOLDER}/reviews.json`;
13425
+ var MODEL_STATE = `${MODEL_FOLDER}/.state`;
13426
+ var OLD_MODEL_STATE = `${OLD_MODEL_FOLDER}/.radical`;
13427
+ var isFile = (path) => stat(path).then((s) => s.isFile(), () => false);
13428
+ var exists = (path) => stat(path).then(() => true, () => false);
13429
+ var isModel = (folder) => isFile(join(folder, MD_MANIFEST_FILE));
13430
+ async function upwards(from) {
13431
+ const dirs = [];
13432
+ for (let dir = resolve(from); ; dir = dirname2(dir)) {
13433
+ dirs.push(dir);
13434
+ if (await exists(join(dir, ".git")) || dirname2(dir) === dir) return dirs;
13435
+ }
13436
+ }
13437
+ async function repositoryRoot(from) {
13438
+ const top = (await upwards(from)).at(-1);
13439
+ return await exists(join(top, ".git")) ? top : null;
13440
+ }
13441
+ async function findModelFolder(cwd) {
13442
+ if (await isModel(cwd)) return resolve(cwd);
13443
+ const dirs = await upwards(cwd);
13444
+ for (const dir of dirs) if (await isModel(join(dir, MODEL_FOLDER))) return join(dir, MODEL_FOLDER);
13445
+ const old = join(dirs.at(-1), OLD_MODEL_FOLDER);
13446
+ return await isModel(old) ? old : null;
13447
+ }
13448
+ async function findRepositoryFile(from, file, oldFile) {
13449
+ for (const dir of await upwards(from)) {
13450
+ if (await isFile(join(dir, file))) return { path: join(dir, file), root: dir, old: false };
13451
+ if (await isFile(join(dir, oldFile))) return { path: join(dir, oldFile), root: dir, old: true };
13452
+ }
13453
+ return null;
13454
+ }
13455
+ function repositoryFileRoot(file) {
13456
+ for (let dir = dirname2(resolve(file)); dirname2(dir) !== dir; dir = dirname2(dir)) {
13457
+ if (basename(dir) === RADICAL_DIR) return dirname2(dir);
13458
+ }
13459
+ return dirname2(resolve(file));
13460
+ }
13461
+ async function mappingRoot(folder) {
13462
+ const at = resolve(folder);
13463
+ return await repositoryRoot(at) ?? (basename(dirname2(at)) === RADICAL_DIR ? dirname2(dirname2(at)) : dirname2(at));
13464
+ }
13465
+ async function readRepositoryMapping(from) {
13466
+ const found = await findRepositoryFile(from, REPOSITORY_FILE, REPOSITORY_FILE);
13467
+ if (!found) return null;
13468
+ return { file: found.path, root: repositoryFileRoot(found.path), ...parseRepositoryFile(await readFile(found.path, "utf8"), found.path) };
13469
+ }
13470
+
12269
13471
  // ../../packages/node-files/src/selectionFile.ts
12270
- async function selectionDir(root2, create) {
12271
- const dir = join(resolve(root2), SELECTION_DIR);
13472
+ async function selectionDir(root2, create, name = STATE_DIR) {
13473
+ const dir = join2(resolve2(root2), name);
12272
13474
  try {
12273
- if ((await lstat(dir)).isSymbolicLink()) throw new Error(`symlink in model path: ${SELECTION_DIR}`);
13475
+ if ((await lstat(dir)).isSymbolicLink()) throw new Error(`symlink in model path: ${name}`);
12274
13476
  } catch (error) {
12275
13477
  if (error.code !== "ENOENT") throw error;
12276
13478
  if (!create) return null;
12277
- await mkdir(dir);
13479
+ await mkdir(dir).catch((e) => {
13480
+ if (e.code !== "EEXIST") throw e;
13481
+ });
12278
13482
  }
12279
13483
  return dir;
12280
13484
  }
12281
13485
  async function editorStateDir(root2) {
12282
13486
  const dir = await selectionDir(root2, true);
12283
- const ignore = join(resolve(root2), SELECTION_GITIGNORE);
13487
+ const ignore = join2(resolve2(root2), SELECTION_GITIGNORE);
12284
13488
  try {
12285
13489
  await lstat(ignore);
12286
13490
  } catch {
@@ -12290,17 +13494,18 @@ async function editorStateDir(root2) {
12290
13494
  }
12291
13495
  async function writeEditorStateFile(root2, path, content) {
12292
13496
  await editorStateDir(root2);
12293
- const file = join(resolve(root2), path);
13497
+ const file = join2(resolve2(root2), path);
12294
13498
  if (await lstat(file).then((s) => s.isSymbolicLink(), () => false)) throw new Error(`symlink in model path: ${path}`);
12295
13499
  await writeFile(file, content, "utf-8");
12296
13500
  }
12297
13501
  async function readEditorStateFile(root2, path) {
12298
- if (!await selectionDir(root2, false)) return null;
12299
- try {
12300
- return await readFile(join(resolve(root2), path), "utf-8");
12301
- } catch {
12302
- return null;
13502
+ if (await selectionDir(root2, false)) {
13503
+ const text2 = await readFile2(join2(resolve2(root2), path), "utf-8").catch(() => null);
13504
+ if (text2 !== null) return text2;
12303
13505
  }
13506
+ const old = oldStatePath(path);
13507
+ if (old === path || !await selectionDir(root2, false, OLD_STATE_DIR)) return null;
13508
+ return readFile2(join2(resolve2(root2), old), "utf-8").catch(() => null);
12304
13509
  }
12305
13510
  async function writeForgeRunFile(root2, content) {
12306
13511
  await writeEditorStateFile(root2, FORGE_RUN_FILE, content);
@@ -12311,8 +13516,8 @@ var WRITE_LOCK = "write.lock";
12311
13516
  var LOCK_WAIT_MS = 15e3;
12312
13517
  var LOCK_STALE_MS = 15e3;
12313
13518
  var LOCK_UNREAD_MS = 1e3;
12314
- function staleLock(text, age) {
12315
- const [pid, since] = text.trim().split(" ").map(Number);
13519
+ function staleLock(text2, age) {
13520
+ const [pid, since] = text2.trim().split(" ").map(Number);
12316
13521
  if (!Number.isFinite(pid) || !Number.isFinite(since)) return age > LOCK_UNREAD_MS;
12317
13522
  if (Date.now() - since > LOCK_STALE_MS) return true;
12318
13523
  if (pid === process.pid) return false;
@@ -12326,13 +13531,13 @@ function staleLock(text, age) {
12326
13531
  var sleep = (ms) => new Promise((done) => setTimeout(done, ms));
12327
13532
  var READ_ONLY = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EROFS"]);
12328
13533
  async function takeWriteTurn(base, forRead = false) {
12329
- if (forRead && !await lstat2(join2(base, SELECTION_DIR)).then(() => true, () => false)) return async () => {
13534
+ if (forRead && !await lstat2(join3(base, STATE_DIR)).then(() => true, () => false)) return async () => {
12330
13535
  };
12331
13536
  try {
12332
13537
  return await takeTurn(base, forRead);
12333
13538
  } catch (error) {
12334
13539
  if (!forRead || !READ_ONLY.has(error.code ?? "")) throw error;
12335
- await waitForWriter(join2(base, SELECTION_DIR, WRITE_LOCK));
13540
+ await waitForWriter(join3(base, STATE_DIR, WRITE_LOCK));
12336
13541
  return async () => {
12337
13542
  };
12338
13543
  }
@@ -12340,15 +13545,15 @@ async function takeWriteTurn(base, forRead = false) {
12340
13545
  async function waitForWriter(file) {
12341
13546
  const deadline = Date.now() + LOCK_WAIT_MS;
12342
13547
  for (; ; ) {
12343
- const held = await readFile2(file, "utf-8").catch(() => null);
12344
- const age = await stat(file).then((s) => Date.now() - s.mtimeMs, () => 0);
13548
+ const held = await readFile3(file, "utf-8").catch(() => null);
13549
+ const age = await stat2(file).then((s) => Date.now() - s.mtimeMs, () => 0);
12345
13550
  if (held === null || staleLock(held, age) || Date.now() > deadline) return;
12346
13551
  await sleep(10 + Math.random() * 30);
12347
13552
  }
12348
13553
  }
12349
13554
  async function takeTurn(base, forRead = false) {
12350
- const file = join2(await editorStateDir(base), WRITE_LOCK);
12351
- if (await lstat2(file).then((s) => s.isSymbolicLink(), () => false)) throw new Error(`symlink in model path: .radical/${WRITE_LOCK}`);
13555
+ const file = join3(await editorStateDir(base), WRITE_LOCK);
13556
+ if (await lstat2(file).then((s) => s.isSymbolicLink(), () => false)) throw new Error(`symlink in model path: ${STATE_DIR}/${WRITE_LOCK}`);
12352
13557
  const mine = `${process.pid} ${Date.now()} ${randomUUID()}
12353
13558
  `;
12354
13559
  const deadline = Date.now() + LOCK_WAIT_MS;
@@ -12356,35 +13561,35 @@ async function takeTurn(base, forRead = false) {
12356
13561
  try {
12357
13562
  await writeFile2(file, mine, { encoding: "utf-8", flag: "wx" });
12358
13563
  return async () => {
12359
- if (await readFile2(file, "utf-8").catch(() => null) === mine) await rm(file, { force: true });
13564
+ if (await readFile3(file, "utf-8").catch(() => null) === mine) await rm(file, { force: true });
12360
13565
  };
12361
13566
  } catch (error) {
12362
13567
  if (error.code !== "EEXIST") throw error;
12363
13568
  }
12364
- const held = await readFile2(file, "utf-8").catch(() => null);
12365
- const age = await stat(file).then((s) => Date.now() - s.mtimeMs, () => 0);
13569
+ const held = await readFile3(file, "utf-8").catch(() => null);
13570
+ const age = await stat2(file).then((s) => Date.now() - s.mtimeMs, () => 0);
12366
13571
  if (held !== null && staleLock(held, age)) {
12367
- if (await readFile2(file, "utf-8").catch(() => null) === held) await rm(file, { force: true });
13572
+ if (await readFile3(file, "utf-8").catch(() => null) === held) await rm(file, { force: true });
12368
13573
  continue;
12369
13574
  }
12370
13575
  if (Date.now() > deadline) {
12371
- throw new Error(`Another program has been writing this model folder for ${LOCK_WAIT_MS / 1e3} s (.radical/${WRITE_LOCK}); ${forRead ? "the folder was not read" : "nothing was written"}. Try again.`);
13576
+ throw new Error(`Another program has been writing this model folder for ${LOCK_WAIT_MS / 1e3} s (${STATE_DIR}/${WRITE_LOCK}); ${forRead ? "the folder was not read" : "nothing was written"}. Try again.`);
12372
13577
  }
12373
13578
  await sleep(10 + Math.random() * 30);
12374
13579
  }
12375
13580
  }
12376
13581
  function diskFolderStorage(root2) {
12377
- const base = resolve2(root2);
13582
+ const base = resolve3(root2);
12378
13583
  const stampOf = (s) => `${s.mtimeMs}:${s.size}`;
12379
13584
  async function inside(rel) {
12380
- const abs = resolve2(base, rel);
13585
+ const abs = resolve3(base, rel);
12381
13586
  if (!abs.startsWith(base + sep)) throw new Error(`path outside the model folder: ${rel}`);
12382
13587
  if (!isMdFolderModelPath(rel) || rel.includes("\\") || rel.split("/").some((part) => !part || part === "." || part === "..")) {
12383
13588
  throw new Error(`not a model file: ${rel}`);
12384
13589
  }
12385
13590
  let current = base;
12386
13591
  for (const part of rel.split("/")) {
12387
- current = resolve2(current, part);
13592
+ current = resolve3(current, part);
12388
13593
  try {
12389
13594
  if ((await lstat2(current)).isSymbolicLink()) throw new Error(`symlink in model path: ${rel}`);
12390
13595
  } catch (error) {
@@ -12394,43 +13599,67 @@ function diskFolderStorage(root2) {
12394
13599
  return abs;
12395
13600
  }
12396
13601
  return {
13602
+ readCache: (name) => MODEL_CACHE_NAMES.has(name) ? readEditorStateFile(base, `${MODEL_CACHE_DIR}/${name}`) : Promise.resolve(null),
13603
+ async writeCache(name, content) {
13604
+ if (!MODEL_CACHE_NAMES.has(name)) throw new Error(`not a cache file: ${name}`);
13605
+ await editorStateDir(base);
13606
+ const dir = join3(base, MODEL_CACHE_DIR);
13607
+ if (await lstat2(dir).then((s) => s.isSymbolicLink(), () => false)) throw new Error(`symlink in model path: ${MODEL_CACHE_DIR}`);
13608
+ await mkdir2(dir, { recursive: true });
13609
+ for (const name2 of await readdir2(dir)) {
13610
+ if (!name2.endsWith(".part")) continue;
13611
+ const left = join3(dir, name2);
13612
+ if (await stat2(left).then((st) => Date.now() - st.mtimeMs > 6e4, () => false)) await rm(left, { force: true });
13613
+ }
13614
+ const file = join3(dir, name);
13615
+ const part = `${file}.${randomUUID()}.part`;
13616
+ await writeFile2(part, content, "utf-8");
13617
+ await rename(part, file);
13618
+ },
12397
13619
  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
- }
13620
+ const files = [];
13621
+ const add = (rel) => {
13622
+ files.push(rel);
12405
13623
  };
12406
13624
  const walk = async (rel) => {
12407
- const entries = await readdir(await inside(`${rel}/_index.md`).then(dirname2), { withFileTypes: true });
13625
+ const entries = await readdir2(await inside(`${rel}/_index.md`).then(dirname4), { withFileTypes: true });
12408
13626
  for (const entry of entries) {
12409
13627
  if (entry.name.startsWith(".")) continue;
12410
13628
  const child = `${rel}/${entry.name}`;
12411
13629
  if (entry.isDirectory()) await walk(child);
12412
- else if (entry.isFile() && isMdFolderModelPath(child)) await add(child);
13630
+ else if (entry.isFile() && isMdFolderModelPath(child)) add(child);
12413
13631
  else if (entry.isSymbolicLink()) throw new Error(`symlink in model path: ${child}`);
12414
13632
  }
12415
13633
  };
12416
- const top = await readdir(base, { withFileTypes: true });
13634
+ const top = await readdir2(base, { withFileTypes: true });
12417
13635
  for (const entry of top) {
12418
- if (entry.isFile() && isMdFolderModelPath(entry.name)) await add(entry.name);
13636
+ if (entry.isFile() && isMdFolderModelPath(entry.name)) add(entry.name);
12419
13637
  else if (entry.isDirectory() && entry.name === "nodes") await walk("nodes");
12420
13638
  else if (entry.isSymbolicLink() && (entry.name === "nodes" || isMdFolderModelPath(entry.name))) {
12421
13639
  throw new Error(`symlink in model path: ${entry.name}`);
12422
13640
  }
12423
13641
  }
13642
+ const found = await readEach(files, async (rel) => {
13643
+ try {
13644
+ return stampOf(await stat2(await inside(rel)));
13645
+ } catch (error) {
13646
+ if (error.code !== "ENOENT") throw error;
13647
+ }
13648
+ });
13649
+ const stamps = {};
13650
+ files.forEach((rel, i) => {
13651
+ if (found[i] !== void 0) stamps[rel] = found[i];
13652
+ });
12424
13653
  return stamps;
12425
13654
  },
12426
13655
  // Decoded as the browser decodes a file: without a byte-order mark.
12427
- read: async (rel) => stripBom(await readFile2(await inside(rel), "utf-8")),
13656
+ read: async (rel) => stripBom(await readFile3(await inside(rel), "utf-8")),
12428
13657
  async write(rel, content) {
12429
13658
  const abs = await inside(rel);
12430
- await mkdir2(dirname2(abs), { recursive: true });
13659
+ await mkdir2(dirname4(abs), { recursive: true });
12431
13660
  await inside(rel);
12432
13661
  await writeFile2(abs, content, "utf-8");
12433
- return stampOf(await stat(abs));
13662
+ return stampOf(await stat2(abs));
12434
13663
  },
12435
13664
  remove: async (rel) => rm(await inside(rel), { force: true }),
12436
13665
  lock: (forRead) => takeWriteTurn(base, forRead)
@@ -12440,8 +13669,8 @@ function diskFolderStorage(root2) {
12440
13669
  // ../../packages/node-files/src/gitModel.ts
12441
13670
  init_define_RADICAL_BUILD();
12442
13671
  import { execFile, spawn } from "child_process";
12443
- import { readFile as readFile3, stat as stat2 } from "fs/promises";
12444
- import { join as join3 } from "path";
13672
+ import { readFile as readFile4, stat as stat3 } from "fs/promises";
13673
+ import { join as join4 } from "path";
12445
13674
  import { promisify } from "util";
12446
13675
 
12447
13676
  // ../../packages/common/src/modelChanges.ts
@@ -12530,6 +13759,7 @@ function formatModelChanges(report, before, after) {
12530
13759
  field(" ", `${c.field} now`, value(c.after));
12531
13760
  } else lines.push(` ${c.field}: ${value(c.before)} \u2192 ${value(c.after)}`);
12532
13761
  }
13762
+ if (change.tests) lines.push(` tests (.radical/radical.json): ${change.tests.length ? "" : "none bound"}`, ...change.tests.map((t) => ` ${t}`));
12533
13763
  if (change.related.length) {
12534
13764
  lines.push(" relations:");
12535
13765
  for (const r of change.related.slice(0, MAX_RELATED)) {
@@ -12560,7 +13790,7 @@ function formatModelChanges(report, before, after) {
12560
13790
 
12561
13791
  // ../../packages/common/src/formats/modelBase.ts
12562
13792
  init_define_RADICAL_BUILD();
12563
- var MODEL_BASE_FILE = `${SELECTION_DIR}/base.json`;
13793
+ var MODEL_BASE_FILE = `${STATE_DIR}/base.json`;
12564
13794
  var BASE_OLD_MS = 24 * 60 * 60 * 1e3;
12565
13795
  function serializeModelBase(base, now4 = /* @__PURE__ */ new Date()) {
12566
13796
  const out = {
@@ -12577,10 +13807,10 @@ function serializeModelBase(base, now4 = /* @__PURE__ */ new Date()) {
12577
13807
  `;
12578
13808
  }
12579
13809
  var isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
12580
- function parseModelBase(text) {
13810
+ function parseModelBase(text2) {
12581
13811
  let raw;
12582
13812
  try {
12583
- raw = JSON.parse(text);
13813
+ raw = JSON.parse(text2);
12584
13814
  } catch {
12585
13815
  return null;
12586
13816
  }
@@ -12600,7 +13830,9 @@ function parseModelBase(text) {
12600
13830
  described,
12601
13831
  branch,
12602
13832
  savedAt,
12603
- nodes,
13833
+ // A base saved before `metrics` reads as the model now does, or every
13834
+ // scenario and fitness function would count as changed on the branch.
13835
+ nodes: nodes.map((n) => migrateCheckFields(n)),
12604
13836
  relations
12605
13837
  };
12606
13838
  }
@@ -12660,7 +13892,7 @@ async function readModelAtCommit(folder, commit, from) {
12660
13892
  return Object.fromEntries(blobs.map((blob, i) => [blob.path, contents[i]]));
12661
13893
  }
12662
13894
  function catFiles(cwd, shas) {
12663
- return new Promise((resolve5, reject) => {
13895
+ return new Promise((resolve6, reject) => {
12664
13896
  const child = spawn("git", ["cat-file", "--batch"], { cwd, windowsHide: true });
12665
13897
  const chunks = [];
12666
13898
  let stderr = "";
@@ -12688,7 +13920,7 @@ function catFiles(cwd, shas) {
12688
13920
  contents.push(stripBom(out.subarray(start, start + Number(size)).toString("utf8")));
12689
13921
  at = start + Number(size) + 1;
12690
13922
  }
12691
- resolve5(contents);
13923
+ resolve6(contents);
12692
13924
  });
12693
13925
  child.stdin.end(shas.join("\n") + "\n");
12694
13926
  });
@@ -12702,12 +13934,12 @@ async function renamedFrom(folder, commit) {
12702
13934
  if (fields[i].startsWith("R") && fields[i + 2] === manifest && fields[i + 1].endsWith("/radical.md")) return fields[i + 1].slice(0, -"/radical.md".length);
12703
13935
  }
12704
13936
  const top = await git(folder, ["rev-parse", "--show-toplevel"]);
12705
- const now4 = await readFile3(join3(folder, "radical.md"), "utf8").catch(() => null);
13937
+ const now4 = await readFile4(join4(folder, "radical.md"), "utf8").catch(() => null);
12706
13938
  if (now4 === null) return null;
12707
13939
  const then = (await git(folder, ["ls-tree", "-r", "-z", "--name-only", "--full-name", commit, "--", ":/"])).split("\0").filter((path) => path.endsWith("/radical.md") && path !== manifest);
12708
13940
  const gone = [];
12709
13941
  for (const path of then) {
12710
- if (await stat2(join3(top, path)).then(() => true, () => false)) continue;
13942
+ if (await stat3(join4(top, path)).then(() => true, () => false)) continue;
12711
13943
  if (stripBom(await gitOk(folder, ["show", `${commit}:${path}`]) ?? "") === stripBom(now4).trim()) gone.push(path.slice(0, -"/radical.md".length));
12712
13944
  }
12713
13945
  return gone.length === 1 ? gone[0] : null;
@@ -12727,21 +13959,27 @@ async function modelChangesSince(folder, current, since, options = {}) {
12727
13959
  const before = { nodes: byId2(old.nodes), relations: byId2(old.relations) };
12728
13960
  const after = { nodes: byId2(current.nodes), relations: byId2(current.relations) };
12729
13961
  const report = modelChangeReport(before, after);
13962
+ const mapping = await readRepositoryMapping(folder).catch(() => null);
13963
+ if (mapping) {
13964
+ for (const change of [...report.elements.added, ...report.elements.changed, ...report.elements.removed]) {
13965
+ if (change.type === "scenario" || change.type === "fitness-fn") change.tests = testsBoundTo(mapping.verifies, change.id);
13966
+ }
13967
+ }
12730
13968
  const short = base.commit.slice(0, 7);
12731
13969
  const where = base.commit.startsWith(base.described) ? short : `${base.described} (${short})`;
12732
13970
  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).` : [
13971
+ 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
13972
  `Model changes since ${where}, uncommitted edits included; elements and relations only, views and layout left out.`,
12735
13973
  `${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
13974
  "",
12737
13975
  formatModelChanges(report, before, after)
12738
13976
  ].join("\n");
12739
- return { base, report, text };
13977
+ return { base, report, text: text2 };
12740
13978
  }
12741
13979
 
12742
13980
  // ../../packages/common/src/formats/agentActivity.ts
12743
13981
  init_define_RADICAL_BUILD();
12744
- var AGENT_ACTIVITY_FILE = `${SELECTION_DIR}/agent-activity.json`;
13982
+ var AGENT_ACTIVITY_FILE = `${STATE_DIR}/agent-activity.json`;
12745
13983
  var AGENT_ACTIVE_MS = 15e3;
12746
13984
  function serializeAgentActivity(client, now4 = Date.now(), radical) {
12747
13985
  const out = { version: 1, ...client ? { client } : {}, ...radical ? { radical } : {}, until: now4 + AGENT_ACTIVE_MS };
@@ -13718,11 +14956,11 @@ var ADVANCE = {
13718
14956
  }
13719
14957
  };
13720
14958
  var OTHER_ADVANCE = 600;
13721
- var tableMeasure = (text, fontSize, italic) => {
14959
+ var tableMeasure = (text2, fontSize, italic) => {
13722
14960
  const sized = ADVANCE[fontSize < 11 ? 10 : 12];
13723
14961
  const table = italic ? sized.italic : sized.upright;
13724
14962
  let w = 0;
13725
- for (const ch of text) {
14963
+ for (const ch of text2) {
13726
14964
  const c = ch.codePointAt(0);
13727
14965
  w += c >= 32 && c < 127 ? table[c - 32] : c >= 11904 ? 1e3 : OTHER_ADVANCE;
13728
14966
  }
@@ -13730,7 +14968,7 @@ var tableMeasure = (text, fontSize, italic) => {
13730
14968
  };
13731
14969
  var measured = /* @__PURE__ */ new Map();
13732
14970
  var canvas;
13733
- var measureText = (text, fontSize, italic) => {
14971
+ var measureText = (text2, fontSize, italic) => {
13734
14972
  if (canvas === void 0) {
13735
14973
  const Canvas = globalThis.OffscreenCanvas;
13736
14974
  try {
@@ -13739,14 +14977,14 @@ var measureText = (text, fontSize, italic) => {
13739
14977
  canvas = null;
13740
14978
  }
13741
14979
  }
13742
- if (!canvas) return tableMeasure(text, fontSize, italic);
14980
+ if (!canvas) return tableMeasure(text2, fontSize, italic);
13743
14981
  const font = labelFont(fontSize, italic);
13744
- const key = `${font}|${text}`;
14982
+ const key = `${font}|${text2}`;
13745
14983
  let w = measured.get(key);
13746
14984
  if (w === void 0) {
13747
14985
  if (measured.size > 2e4) measured.clear();
13748
14986
  canvas.font = font;
13749
- w = canvas.measureText(text).width;
14987
+ w = canvas.measureText(text2).width;
13750
14988
  measured.set(key, w);
13751
14989
  }
13752
14990
  return w;
@@ -13801,7 +15039,7 @@ function relationLabelLines(r, nodes) {
13801
15039
  const lines = [];
13802
15040
  const name = r.label || (r.relationType === "transition" ? nodes ? transitionLabel(r, nodes) : "" : r.typeName ?? r.relationType);
13803
15041
  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 });
15042
+ 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
15043
  if (r.technology) lines.push({ text: `[${r.technology}]`, fontSize: RELATION_LABEL_BOX.techFontSize, maxRows: 1, italic: true, nowrap: true });
13806
15044
  return lines;
13807
15045
  }
@@ -14546,7 +15784,7 @@ function boxOf(nodes, positions, id) {
14546
15784
  height: p?.height ?? n.height
14547
15785
  };
14548
15786
  }
14549
- function childrenByParent(nodes) {
15787
+ function childrenByParent2(nodes) {
14550
15788
  const byParent = /* @__PURE__ */ new Map();
14551
15789
  for (const n of Object.values(nodes)) {
14552
15790
  if (!n.parentId || !nodes[n.parentId]) continue;
@@ -14599,7 +15837,7 @@ function finalize(nodes, positions, separate, gaps) {
14599
15837
  const gapsOf = (ids) => gaps && gaps.size > 0 ? (i, j) => gaps.get(pairKey(ids[i], ids[j])) : void 0;
14600
15838
  const out = {};
14601
15839
  for (const id of Object.keys(nodes)) out[id] = boxOf(nodes, positions, id);
14602
- const byParent = childrenByParent(nodes);
15840
+ const byParent = childrenByParent2(nodes);
14603
15841
  const parentIds = [...byParent.keys()].sort((a, b) => depthOf(nodes, b) - depthOf(nodes, a));
14604
15842
  for (const pid of parentIds) {
14605
15843
  const childIds = byParent.get(pid);
@@ -14925,7 +16163,7 @@ function enforceAlignments(nodes, positions, alignments, fixed = /* @__PURE__ */
14925
16163
  }
14926
16164
  separate(byParent.get(void 0) ?? [], ROOT_GAP);
14927
16165
  };
14928
- for (let round = 0; round < MAX_ROUNDS; round++) {
16166
+ for (let round2 = 0; round2 < MAX_ROUNDS; round2++) {
14929
16167
  snap3();
14930
16168
  tidy();
14931
16169
  if (alignmentError(nodes, boxes, alignments) <= TOLERANCE) break;
@@ -14939,7 +16177,22 @@ function enforceAlignments(nodes, positions, alignments, fixed = /* @__PURE__ */
14939
16177
 
14940
16178
  // ../../packages/layout/src/liveColaEngine.ts
14941
16179
  init_define_RADICAL_BUILD();
16180
+ var import_webcola2 = __toESM(require_dist(), 1);
16181
+
16182
+ // ../../packages/layout/src/webcolaHeap.ts
16183
+ init_define_RADICAL_BUILD();
14942
16184
  var import_webcola = __toESM(require_dist(), 1);
16185
+ function mergePairs(lessThan) {
16186
+ const subheaps = this.subheaps;
16187
+ if (subheaps.length === 0) return new import_webcola.PairingHeap(null);
16188
+ if (subheaps.length === 1) return subheaps[0];
16189
+ const pairs = [];
16190
+ while (subheaps.length >= 2) pairs.push(subheaps.pop().merge(subheaps.pop(), lessThan));
16191
+ let rest = subheaps.length === 1 ? subheaps[0] : new import_webcola.PairingHeap(null);
16192
+ for (let i = pairs.length - 1; i >= 0; i--) rest = pairs[i].merge(rest, lessThan);
16193
+ return rest;
16194
+ }
16195
+ import_webcola.PairingHeap.prototype.mergePairs = mergePairs;
14943
16196
 
14944
16197
  // ../../node_modules/d3-dispatch/src/index.js
14945
16198
  init_define_RADICAL_BUILD();
@@ -16539,7 +17792,7 @@ var LiveColaEngine = class {
16539
17792
  const frame2 = this.frameOf(g);
16540
17793
  return frame2 ? [[g.c4id, frame2]] : [];
16541
17794
  }));
16542
- for (const leaf of this.leavesOf(nodeId)) import_webcola.Layout.dragStart(leaf);
17795
+ for (const leaf of this.leavesOf(nodeId)) import_webcola2.Layout.dragStart(leaf);
16543
17796
  this.calm = this.calmDrag(nodeId, withIds, abs ?? { x: rfX, y: rfY }, { x: 0, y: 0 });
16544
17797
  this.offLinesAtGrab = new Set(this.groupAlignments.filter((a) => this.offLine(a)).map(groupLineKey));
16545
17798
  this.followedInDrag = /* @__PURE__ */ new Set();
@@ -16555,13 +17808,13 @@ var LiveColaEngine = class {
16555
17808
  for (const leaf of this.leavesOf(nodeId)) leaf.fixed = (leaf.fixed ?? 0) & ~PINNED;
16556
17809
  const cn = this.idToNode.get(nodeId);
16557
17810
  if (cn) {
16558
- import_webcola.Layout.dragStart(cn);
17811
+ import_webcola2.Layout.dragStart(cn);
16559
17812
  } else {
16560
17813
  const leaves = this.groupLeaves(nodeId);
16561
17814
  this._dragStartPositions.clear();
16562
17815
  for (const leaf of leaves) {
16563
17816
  this._dragStartPositions.set(leaf.c4id, { x: leaf.x, y: leaf.y });
16564
- import_webcola.Layout.dragStart(leaf);
17817
+ import_webcola2.Layout.dragStart(leaf);
16565
17818
  }
16566
17819
  }
16567
17820
  }
@@ -16576,7 +17829,7 @@ var LiveColaEngine = class {
16576
17829
  this.unfreeze();
16577
17830
  for (const id of [this.calm.id, ...this.calm.with]) {
16578
17831
  for (const leaf of this.leavesOf(id)) {
16579
- import_webcola.Layout.dragEnd(leaf);
17832
+ import_webcola2.Layout.dragEnd(leaf);
16580
17833
  leaf.fixed = (leaf.fixed ?? 0) & ~PINNED;
16581
17834
  }
16582
17835
  }
@@ -16599,7 +17852,7 @@ var LiveColaEngine = class {
16599
17852
  const cn = this.idToNode.get(nodeId);
16600
17853
  if (cn) {
16601
17854
  const abs2 = this.rfToAbsCenter(nodeId, rfX, rfY, cn.realWidth, cn.realHeight);
16602
- import_webcola.Layout.drag(cn, abs2);
17855
+ import_webcola2.Layout.drag(cn, abs2);
16603
17856
  } else {
16604
17857
  const g = this.idToGroup.get(nodeId);
16605
17858
  if (g) {
@@ -16626,7 +17879,7 @@ var LiveColaEngine = class {
16626
17879
  for (const leaf of this.groupLeaves(nodeId)) {
16627
17880
  const sp = this._dragStartPositions.get(leaf.c4id);
16628
17881
  if (sp) {
16629
- import_webcola.Layout.drag(leaf, { x: sp.x + dx, y: sp.y + dy });
17882
+ import_webcola2.Layout.drag(leaf, { x: sp.x + dx, y: sp.y + dy });
16630
17883
  }
16631
17884
  }
16632
17885
  }
@@ -16644,7 +17897,7 @@ var LiveColaEngine = class {
16644
17897
  this.calm = null;
16645
17898
  if (calm && !calm.moving) {
16646
17899
  this.framesAtGrab.clear();
16647
- for (const leaf of this.leavesOf(calm.id)) import_webcola.Layout.dragEnd(leaf);
17900
+ for (const leaf of this.leavesOf(calm.id)) import_webcola2.Layout.dragEnd(leaf);
16648
17901
  this.applyPins();
16649
17902
  return;
16650
17903
  }
@@ -16680,10 +17933,10 @@ var LiveColaEngine = class {
16680
17933
  held[1][i] = cn.py;
16681
17934
  }
16682
17935
  }
16683
- import_webcola.Layout.dragEnd(cn);
17936
+ import_webcola2.Layout.dragEnd(cn);
16684
17937
  } else {
16685
17938
  for (const leaf of this.groupLeaves(nodeId)) {
16686
- import_webcola.Layout.dragEnd(leaf);
17939
+ import_webcola2.Layout.dragEnd(leaf);
16687
17940
  }
16688
17941
  this._dragStartPositions.clear();
16689
17942
  }
@@ -16848,10 +18101,10 @@ var LiveColaEngine = class {
16848
18101
  refreshBounds() {
16849
18102
  for (const cn of this.colaNodes) {
16850
18103
  ;
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);
18104
+ 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
18105
  }
16853
18106
  for (const g of this.colaGroups) {
16854
- if (!g.parent) (0, import_webcola.computeGroupBounds)(g);
18107
+ if (!g.parent) (0, import_webcola2.computeGroupBounds)(g);
16855
18108
  }
16856
18109
  }
16857
18110
  /** An element's box as the canvas draws it: a leaf from its top-left at
@@ -17110,7 +18363,7 @@ var LiveColaEngine = class {
17110
18363
  const kids = this.childrenOf.get(level) ?? [];
17111
18364
  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
18365
  const stuck = /* @__PURE__ */ new Set();
17113
- for (let round = 0; round <= kids.length; round++) {
18366
+ for (let round2 = 0; round2 <= kids.length; round2++) {
17114
18367
  let stray;
17115
18368
  for (const t of moved) {
17116
18369
  const T = this.boxOf(t);
@@ -17292,7 +18545,7 @@ var LiveColaEngine = class {
17292
18545
  return p;
17293
18546
  };
17294
18547
  const visibleNodes = Object.values(nodes).filter((n) => isVisible(n, nodes) && !frameIds.has(n.id));
17295
- if (visibleNodes.length === 0) {
18548
+ if (visibleNodes.length === 0 || visibleNodes.length > CANVAS_MAX_ELEMENTS) {
17296
18549
  this.cola = null;
17297
18550
  this.seedPositions.clear();
17298
18551
  return;
@@ -17457,7 +18710,7 @@ var LiveColaEngine = class {
17457
18710
  this.childrenOf.set(level, list);
17458
18711
  }
17459
18712
  const d3Context = { dispatch: dispatch_default, timer, drag: drag_default, event: null };
17460
- const layout = (0, import_webcola.d3adaptor)(d3Context);
18713
+ const layout = (0, import_webcola2.d3adaptor)(d3Context);
17461
18714
  layout.nodes(this.colaNodes).links(colaLinks).groups(this.colaGroups).size([1800, 1200]).avoidOverlaps(true).handleDisconnected(false).linkDistance((link2) => {
17462
18715
  const s = link2.source;
17463
18716
  const t = link2.target;
@@ -18019,16 +19272,18 @@ function computeViewCollapsedSet(viewFilter, allNodes) {
18019
19272
  const result = /* @__PURE__ */ new Set();
18020
19273
  if (!viewFilter) return result;
18021
19274
  const parentHasViewChild = /* @__PURE__ */ new Set();
19275
+ const parents = /* @__PURE__ */ new Set();
18022
19276
  for (const n of Object.values(allNodes)) {
18023
- if (n.parentId && viewFilter.has(n.id)) parentHasViewChild.add(n.parentId);
19277
+ if (!n.parentId) continue;
19278
+ parents.add(n.parentId);
19279
+ if (viewFilter.has(n.id)) parentHasViewChild.add(n.parentId);
18024
19280
  }
18025
19281
  for (const [id, n] of Object.entries(allNodes)) {
18026
19282
  if (!viewFilter.has(id)) continue;
18027
19283
  if (!isContainerType(n.type)) continue;
18028
19284
  if (n.collapsed) continue;
18029
19285
  if (parentHasViewChild.has(id)) continue;
18030
- const hasChildInModel = Object.values(allNodes).some((c) => c.parentId === id);
18031
- if (hasChildInModel) result.add(id);
19286
+ if (parents.has(id)) result.add(id);
18032
19287
  }
18033
19288
  return result;
18034
19289
  }
@@ -19619,7 +20874,7 @@ function yieldToUI() {
19619
20874
  if (_sched != null && typeof _sched.yield === "function") {
19620
20875
  return _sched.yield();
19621
20876
  }
19622
- return new Promise((resolve5) => setTimeout(resolve5, 0));
20877
+ return new Promise((resolve6) => setTimeout(resolve6, 0));
19623
20878
  }
19624
20879
  function projectPositions(nodes, positions) {
19625
20880
  const out = {};
@@ -19698,7 +20953,7 @@ function unchangedResult(nodes, relations, style = "curved") {
19698
20953
  }
19699
20954
  async function runSmartLayoutELKPhase(inputNodes, inputRelations, metamodel, onProgress) {
19700
20955
  const { nodes, relations } = projectToVisibleGraph(inputNodes, inputRelations);
19701
- const { applyElkLayout } = await import("./elkLayout-TAUBPPVN.js");
20956
+ const { applyElkLayout } = await import("./elkLayout-MFJXDTJG.js");
19702
20957
  const depth2 = maxContainmentDepth(metamodel);
19703
20958
  const mmDirection = depth2 >= 2 ? "RIGHT" : "DOWN";
19704
20959
  const engines = [
@@ -21978,7 +23233,7 @@ function tidyOnce(inputNodes, inputRelations, options, spent) {
21978
23233
  const level = (ds) => ds.every((m) => Math.abs(m.d - ds[0].d) < 0.01);
21979
23234
  const shift = (a, id, d) => l.moveBy(id, a.axis === "x" ? d : 0, a.axis === "y" ? d : 0);
21980
23235
  const repair = (follow) => {
21981
- for (let round = 0; round < 3; round++) {
23236
+ for (let round2 = 0; round2 < 3; round2++) {
21982
23237
  let off = false;
21983
23238
  for (const a of alignments) {
21984
23239
  const ds = offsets(a);
@@ -22292,7 +23547,7 @@ function tidyOnce(inputNodes, inputRelations, options, spent) {
22292
23547
  }
22293
23548
  stale = null;
22294
23549
  improve();
22295
- for (let round = 0; round < 3; round++) {
23550
+ for (let round2 = 0; round2 < 3; round2++) {
22296
23551
  const done = steps.length;
22297
23552
  gather(true);
22298
23553
  if (steps.length === done || outOfTime()) break;
@@ -22329,7 +23584,7 @@ function same2(a, b) {
22329
23584
  init_define_RADICAL_BUILD();
22330
23585
  import { mkdir as mkdir3, writeFile as writeFile3 } from "fs/promises";
22331
23586
  import { existsSync } from "fs";
22332
- import { dirname as dirname3, join as join5, resolve as resolve3 } from "path";
23587
+ import { dirname as dirname5, join as join6, resolve as resolve4 } from "path";
22333
23588
  import { fileURLToPath as fileURLToPath2 } from "url";
22334
23589
 
22335
23590
  // ../../packages/common/src/ai/forge/index.ts
@@ -22481,10 +23736,10 @@ function formatClarificationAnswers(questions, answers) {
22481
23736
  for (const q of questions) {
22482
23737
  if (q.id === CONCERNS_QUESTION_ID || q.id.startsWith(CONCERN_QUESTION_PREFIX)) continue;
22483
23738
  const a = answers[q.id];
22484
- const text = Array.isArray(a) ? a.join(", ") : (a ?? "").trim();
22485
- if (!text) continue;
23739
+ const text2 = Array.isArray(a) ? a.join(", ") : (a ?? "").trim();
23740
+ if (!text2) continue;
22486
23741
  lines.push(`Q: ${q.question}
22487
- A: ${text}`);
23742
+ A: ${text2}`);
22488
23743
  }
22489
23744
  return lines.join("\n\n");
22490
23745
  }
@@ -22497,8 +23752,8 @@ init_define_RADICAL_BUILD();
22497
23752
  var WIREFRAME_WIDTH = 400;
22498
23753
  var WIREFRAME_HEIGHT = 300;
22499
23754
  var MAX_WIREFRAME_CHARS = 2e4;
22500
- function sanitizeWireframeSvg(text) {
22501
- const match = text.match(/<svg[\s\S]*?<\/svg>/i);
23755
+ function sanitizeWireframeSvg(text2) {
23756
+ const match = text2.match(/<svg[\s\S]*?<\/svg>/i);
22502
23757
  if (!match) return null;
22503
23758
  let svg = match[0];
22504
23759
  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, "");
@@ -22919,9 +24174,9 @@ var clone2 = (value) => JSON.parse(JSON.stringify(value));
22919
24174
  function snapshotOf(model) {
22920
24175
  return { nodes: clone2(model.getNodes()), relations: clone2(model.getRelations()) };
22921
24176
  }
22922
- var LAYOUT_FIELDS = /* @__PURE__ */ new Set(["x", "y", "width", "height", "collapsed"]);
24177
+ var LAYOUT_FIELDS2 = /* @__PURE__ */ new Set(["x", "y", "width", "height", "collapsed"]);
22923
24178
  function changedFields2(before, after) {
22924
- const keys = [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].filter((k) => !LAYOUT_FIELDS.has(k));
24179
+ const keys = [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].filter((k) => !LAYOUT_FIELDS2.has(k));
22925
24180
  const value = (o, k) => o[k];
22926
24181
  return keys.filter((k) => !sameModelValue(value(before, k), value(after, k))).sort();
22927
24182
  }
@@ -23014,7 +24269,7 @@ function describeRefinement(r) {
23014
24269
  }
23015
24270
  var CHECK_RULES_AFTER = {
23016
24271
  requirements: ["requirement-incomplete", "requirement-without-origin", "need-without-requirement"],
23017
- fitness: ["fitness-fn-without-threshold"],
24272
+ fitness: ["fitness-fn-without-metrics", "metric-invalid"],
23018
24273
  scenarios: ["requirement-without-scenario", "scenario-verifies-nothing"],
23019
24274
  c4: ["requirement-unsatisfied", "fitness-fn-unlinked"]
23020
24275
  };
@@ -23254,9 +24509,9 @@ init_define_RADICAL_BUILD();
23254
24509
  function slugify2(label) {
23255
24510
  return label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "feature";
23256
24511
  }
23257
- function indentBlock(text, spaces) {
24512
+ function indentBlock(text2, spaces) {
23258
24513
  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");
24514
+ return text2.replace(/\r\n/g, "\n").split("\n").map((line) => line.trim() ? pad + line.trim() : "").filter(Boolean).join("\n");
23260
24515
  }
23261
24516
  function scenarioSteps(scenario) {
23262
24517
  const given = String(scenario.given ?? "").trim();
@@ -23319,8 +24574,8 @@ function buildGherkinFiles(nodes, relations) {
23319
24574
 
23320
24575
  // ../../packages/common/src/hubFormat.ts
23321
24576
  init_define_RADICAL_BUILD();
23322
- var PREVIEW_KEYS = ["ears_type", "priority", "status", "category", "trigger"];
23323
- var SEARCH_KEYS = ["label", "description", "trigger", "action", "threshold", "decision"];
24577
+ var PREVIEW_KEYS = ["ears_type", "priority", "status", "characteristic", "trigger"];
24578
+ var SEARCH_KEYS = ["label", "description", "trigger", "action", "metrics", "threshold", "decision"];
23324
24579
  var SEARCH_TEXT_MAX = 600;
23325
24580
  function searchTextOf(nodes) {
23326
24581
  const parts = [];
@@ -23330,8 +24585,8 @@ function searchTextOf(nodes) {
23330
24585
  if (typeof v === "string" && v.trim()) parts.push(v.replace(/\{\{[A-Z0-9_]+\}\}/g, " ").replace(/\s+/g, " ").trim());
23331
24586
  }
23332
24587
  }
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;
24588
+ const text2 = [...new Set(parts)].join(" \xB7 ");
24589
+ return text2.length > SEARCH_TEXT_MAX ? `${text2.slice(0, SEARCH_TEXT_MAX).replace(/\s+\S*$/, "")}\u2026` : text2;
23335
24590
  }
23336
24591
  function conceptFile(meta) {
23337
24592
  return `${meta.category}/${meta.id}.radical`;
@@ -23363,14 +24618,14 @@ function summarize(doc, file = conceptFile(doc.hub)) {
23363
24618
  // ../../packages/hub-catalogue/src/catalogue.ts
23364
24619
  init_define_RADICAL_BUILD();
23365
24620
  import { readdirSync, readFileSync, statSync } from "fs";
23366
- import { join as join4, relative } from "path";
24621
+ import { join as join5, relative } from "path";
23367
24622
  import { fileURLToPath } from "url";
23368
24623
  var CATALOGUE_DIR = fileURLToPath(new URL("../catalogue", import.meta.url));
23369
24624
  function readCatalogue(dir = CATALOGUE_DIR) {
23370
24625
  const out = [];
23371
24626
  const walk = (d) => {
23372
24627
  for (const name of readdirSync(d).sort()) {
23373
- const p = join4(d, name);
24628
+ const p = join5(d, name);
23374
24629
  if (statSync(p).isDirectory()) walk(p);
23375
24630
  else if (name.endsWith(".radical")) {
23376
24631
  out.push({ file: relative(dir, p).split("\\").join("/"), doc: JSON.parse(readFileSync(p, "utf8")) });
@@ -23594,7 +24849,7 @@ var FORGE_TOOL_DEFS = [
23594
24849
  var FORGE_TOOLS = new Set(FORGE_TOOL_DEFS.map((tool) => tool.name));
23595
24850
  var FORGE_READ_ONLY = /* @__PURE__ */ new Set(["forge_clarify"]);
23596
24851
  function catalogueDir() {
23597
- const bundled = join5(dirname3(fileURLToPath2(import.meta.url)), "hub-catalogue");
24852
+ const bundled = join6(dirname5(fileURLToPath2(import.meta.url)), "hub-catalogue");
23598
24853
  return existsSync(bundled) ? bundled : CATALOGUE_DIR;
23599
24854
  }
23600
24855
  var MAX_CONTEXT_CHARS = 6e4;
@@ -24076,14 +25331,14 @@ var Forge = class {
24076
25331
  });
24077
25332
  if (!trial.ok) return fail2(`forge_propose_refinement: ${trial.text} Fix the proposal before you ask the user.`);
24078
25333
  const proposalId = `p${state.proposals + 1}`;
24079
- const text = [
25334
+ const text2 = [
24080
25335
  `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
25336
  "",
24082
25337
  formatProposal(proposal, lines),
24083
25338
  "",
24084
25339
  `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
25340
  ].join("\n");
24086
- return ok(text, { readOnly: true, commit: () => {
25341
+ return ok(text2, { readOnly: true, commit: () => {
24087
25342
  state.pending = { id: proposalId, proposal };
24088
25343
  state.proposals++;
24089
25344
  } });
@@ -24246,9 +25501,9 @@ Then call forge_wireframe again with mockupId "${id}" and the svg.`, { readOnly:
24246
25501
  if (!files.length) {
24247
25502
  lines.push("No Gherkin scenarios in the model, so there are no .feature files.");
24248
25503
  } else if (typeof args.gherkinDir === "string" && args.gherkinDir) {
24249
- const dir = resolve3(args.gherkinDir);
25504
+ const dir = resolve4(args.gherkinDir);
24250
25505
  await mkdir3(dir, { recursive: true });
24251
- for (const file of files) await writeFile3(join5(dir, file.filename), file.content);
25506
+ for (const file of files) await writeFile3(join6(dir, file.filename), file.content);
24252
25507
  lines.push(`Wrote ${files.length} .feature files to ${dir}:`, ...files.map((f) => `- ${f.filename}`));
24253
25508
  } else {
24254
25509
  lines.push(`${files.length} .feature files (pass gherkinDir to write them):`);
@@ -24291,7 +25546,7 @@ Then call forge_wireframe again with mockupId "${id}" and the svg.`, { readOnly:
24291
25546
 
24292
25547
  // src/folderModel.ts
24293
25548
  var EXCLUDED_TOOLS = /* @__PURE__ */ new Set(["set_active_view", "focus_node", "reset_diagram"]);
24294
- var READ_ONLY2 = /* @__PURE__ */ new Set(["get_model_summary", "get_selection", "get_issues", "get_changes", "search_model", "list_milestones", "compare_milestones"]);
25549
+ var READ_ONLY2 = /* @__PURE__ */ new Set(["get_model_summary", "get_selection", "get_issues", "get_changes", "get_implementation", "get_verification", "search_model", "list_milestones", "compare_milestones"]);
24295
25550
  var SERVER_TOOL_DEFS = [
24296
25551
  {
24297
25552
  name: "get_model_summary",
@@ -24310,7 +25565,7 @@ var SERVER_TOOL_DEFS = [
24310
25565
  },
24311
25566
  {
24312
25567
  name: "get_changes",
24313
- description: "What changed in the model since its version in git: the elements and relations added, removed and changed, uncommitted edits included, each changed field with its old and new value, and each element with its place in the model and its relations (the component that satisfies a requirement, the ADRs that constrain it, the scenarios and the tests they name). Only the model is compared; views, positions, sizes and folding are left out. Call it when you are asked to implement what was changed in the model, and again before you report the work as done. It writes no model file; without since it saves the base to .radical/base.json, for Studio to show the same changes.",
25568
+ description: "What changed in the model since its version in git: the elements and relations added, removed and changed, uncommitted edits included, each changed field with its old and new value, and each element with its place in the model and its relations (the component that satisfies a requirement, the ADRs that constrain it, the scenarios and the tests they name). Only the model is compared; views, positions, sizes and folding are left out. Call it when you are asked to implement what was changed in the model, and again before you report the work as done. It writes no model file; without since it saves the base to .state/base.json, for Studio to show the same changes.",
24314
25569
  inputSchema: {
24315
25570
  type: "object",
24316
25571
  properties: {
@@ -24318,8 +25573,55 @@ var SERVER_TOOL_DEFS = [
24318
25573
  },
24319
25574
  additionalProperties: false
24320
25575
  }
25576
+ },
25577
+ {
25578
+ name: "get_implementation",
25579
+ description: "Where the repository builds the model's elements, from its .radical/radical.json (folders from the repository's root). With id: the element's folders, its own or those of its nearest ancestor with an entry, named. Without: every entry, and the C4 elements of this model (systems, containers, components, databases, web apps, queues; not external ones) built nowhere the file says. Call it to find the code of an element before you change it, and before you map the repository with set_implementation.",
25580
+ inputSchema: {
25581
+ type: "object",
25582
+ properties: { id: { type: "string", description: "The element (an id or a tempId). Omit it for the whole mapping." } },
25583
+ additionalProperties: false
25584
+ }
25585
+ },
25586
+ {
25587
+ name: "set_implementation",
25588
+ description: "Says where the repository builds an element of the model, in its .radical/radical.json, which the repository's sensors, radical check and Studio's element card read: paths, folders from the repository's root, replace its entry; remove: true takes the entry out. Map the containers, and the components that have folders of their own: one without an entry is built where its parent is. Look at the repository's folders first; radical check warns about an entry that drifts from the model or the repository. It changes no model file.",
25589
+ inputSchema: {
25590
+ type: "object",
25591
+ properties: {
25592
+ id: { type: "string", description: "The element (an id or a tempId), this model's or another's of its federation." },
25593
+ paths: { type: "array", items: { type: "string" }, description: `The folders that build it, from the repository's root (e.g. "apps/cli"; "." for the whole repository).` },
25594
+ remove: { type: "boolean", description: "Take the element's entry out instead." }
25595
+ },
25596
+ required: ["id"],
25597
+ additionalProperties: false
25598
+ }
25599
+ },
25600
+ {
25601
+ name: "get_verification",
25602
+ description: `Which of the repository's tests check the model's scenarios and fitness functions, from its .radical/radical.json ("verifies"; test ids as Vitest and Playwright print them, from the repository's root). With id: the tests bound to that scenario or fitness function. Without: every entry, and the scenarios this repository must verify (an element it builds satisfies their requirement) that have no test bound and no metric condition. Tests are never named in the model: bind them with set_verification when you write them.`,
25603
+ inputSchema: {
25604
+ type: "object",
25605
+ properties: { id: { type: "string", description: "The scenario or fitness function (an id or a tempId). Omit it for every entry." } },
25606
+ additionalProperties: false
25607
+ }
25608
+ },
25609
+ {
25610
+ name: "set_verification",
25611
+ description: `Binds tests of the repository to a scenario or fitness function of the model, in its .radical/radical.json, which radical check, the Inspector and Studio read: it passes when every test bound to it passed and its metric conditions hold. tests (ids as "<file> \u203A <describe> \u203A <title>", or "<file>" for every test in it, from the repository's root) replace its tests; remove: true takes the entry out. Call it for each test you write for a scenario. It changes no model file.`,
25612
+ inputSchema: {
25613
+ type: "object",
25614
+ properties: {
25615
+ id: { type: "string", description: "The scenario or fitness function (an id or a tempId)." },
25616
+ tests: { type: "array", items: { type: "string" }, description: "The tests that check it." },
25617
+ remove: { type: "boolean", description: "Take its entry out instead." }
25618
+ },
25619
+ required: ["id"],
25620
+ additionalProperties: false
25621
+ }
24321
25622
  }
24322
25623
  ];
25624
+ var BUILT_TYPES = /* @__PURE__ */ new Set(["system", "container", "component", "database", "webapp", "queue"]);
24323
25625
  var READ_ONLY_TOOLS = /* @__PURE__ */ new Set([...READ_ONLY2, ...FORGE_READ_ONLY]);
24324
25626
  var buildTools = (metamodel) => [
24325
25627
  ...SERVER_TOOL_DEFS,
@@ -24363,11 +25665,11 @@ function checkData(data) {
24363
25665
  }
24364
25666
  }
24365
25667
  }
24366
- async function startIfEmpty(path, preset) {
25668
+ async function startIfEmpty(path, preset2) {
24367
25669
  await mkdir4(path, { recursive: true });
24368
- if (!(await readdir2(path)).every((name) => name.startsWith("."))) return;
25670
+ if (!(await readdir3(path)).every((name) => name.startsWith("."))) return;
24369
25671
  const session = new MdFolderSession(diskFolderStorage(path));
24370
- const created = await session.write(serializeToMdFolder({ nodes: [], relations: [], metamodel: PRESETS[preset]() }, basename(path)));
25672
+ const created = await session.write(serializeToMdFolder({ nodes: [], relations: [], metamodel: PRESETS[preset2]() }, basename2(path)));
24371
25673
  if (!created.ok) throw new Error(`Could not start a model in ${path}: it changed while being written`);
24372
25674
  }
24373
25675
  var byId3 = (items) => Object.fromEntries(items.map((item) => [item.id, item]));
@@ -24451,8 +25753,8 @@ function settleViewFolds(before, after) {
24451
25753
  }
24452
25754
  }
24453
25755
  var FolderModel = class _FolderModel {
24454
- constructor(folder, preset, metamodel) {
24455
- this.preset = preset;
25756
+ constructor(folder, preset2, metamodel) {
25757
+ this.preset = preset2;
24456
25758
  this.tempIds = /* @__PURE__ */ new Map();
24457
25759
  this.forge = new Forge();
24458
25760
  this.tail = Promise.resolve();
@@ -24519,16 +25821,18 @@ var FolderModel = class _FolderModel {
24519
25821
  * Save as folder writes one. */
24520
25822
  static async open(folder, options = {}) {
24521
25823
  if (!folder) throw new Error("--folder is required");
24522
- const path = resolve4(folder);
24523
- const preset = options.metamodel ?? "radical";
24524
- await startIfEmpty(path, preset);
25824
+ const path = resolve5(folder);
25825
+ const preset2 = options.metamodel ?? "radical";
25826
+ await startIfEmpty(path, preset2);
24525
25827
  const canonical2 = await realpath(path);
24526
- if (!(await stat3(canonical2)).isDirectory()) throw new Error(`Not a directory: ${folder}`);
24527
- const files = await new MdFolderSession(diskFolderStorage(canonical2)).readAll();
25828
+ if (!(await stat4(canonical2)).isDirectory()) throw new Error(`Not a directory: ${folder}`);
25829
+ const opening = new MdFolderSession(diskFolderStorage(canonical2));
25830
+ const files = await opening.readAll();
25831
+ await opening.cacheWritten();
24528
25832
  checkFiles(files);
24529
25833
  const data = deserializeFromMdFolder(files).data;
24530
25834
  checkData(data);
24531
- return new _FolderModel(canonical2, preset, createModelFacade(data).getMetamodel?.());
25835
+ return new _FolderModel(canonical2, preset2, createModelFacade(data).getMetamodel?.());
24532
25836
  }
24533
25837
  /** Writes where the agent's Forge run stands for Studio to show. A failed
24534
25838
  * write never fails the call: the status is a convenience. */
@@ -24547,7 +25851,7 @@ var FolderModel = class _FolderModel {
24547
25851
  try {
24548
25852
  if (!mayReplaceWithForgeBase(await readEditorStateFile(this.folder, MODEL_BASE_FILE))) return "";
24549
25853
  await writeEditorStateFile(this.folder, MODEL_BASE_FILE, content);
24550
- return "\n\nSaved the model as it was before this run to .radical/base.json (no base from git): Studio's Changes on branch shows what the run changes.";
25854
+ return "\n\nSaved the model as it was before this run to .state/base.json (no base from git): Studio's Changes on branch shows what the run changes.";
24551
25855
  } catch {
24552
25856
  return "";
24553
25857
  }
@@ -24576,8 +25880,9 @@ var FolderModel = class _FolderModel {
24576
25880
  await startIfEmpty(this.folder, this.preset);
24577
25881
  const session = new MdFolderSession(diskFolderStorage(this.folder));
24578
25882
  const before = await session.readAll();
25883
+ await session.cacheWritten();
24579
25884
  checkFiles(before);
24580
- const data = deserializeFromMdFolder(before).data;
25885
+ const data = withOtherModels(deserializeFromMdFolder(before).data, parseFederationFile(await readEditorStateFile(this.folder, FEDERATION_FILE)));
24581
25886
  checkData(data);
24582
25887
  if (data.views) {
24583
25888
  const nodes = byId3(data.nodes);
@@ -24599,16 +25904,128 @@ var FolderModel = class _FolderModel {
24599
25904
  }
24600
25905
  /** The canvas selection Studio wrote into the folder, resolved against
24601
25906
  * the model as it is now. */
25907
+ /** get_verification and set_verification: the tests the repository's
25908
+ * .radical/radical.json binds (ADR Tests are bound outside the model). */
25909
+ async verification(name, input, data) {
25910
+ const { id, tests, remove: remove2 } = input ?? {};
25911
+ const nodes = new Map(data.nodes.map((n) => [n.id, n]));
25912
+ const named = (n) => `${n.type} "${n.label}" (${n.id})`;
25913
+ const file = join7(await mappingRoot(this.folder), REPOSITORY_FILE);
25914
+ let repository;
25915
+ try {
25916
+ repository = await readFile5(file, "utf8").then((text2) => parseRepositoryFile(text2), (error) => {
25917
+ if (error.code === "ENOENT") return { implements: [], verifies: [] };
25918
+ throw error;
25919
+ });
25920
+ } catch (error) {
25921
+ return { ok: false, text: `${name}: ${error.message}` };
25922
+ }
25923
+ if (id !== void 0 && typeof id !== "string") return { ok: false, text: `${name}: id must be a scenario's or fitness function's id` };
25924
+ const node = typeof id === "string" ? nodes.get(this.tempIds.get(id) ?? id) : void 0;
25925
+ if (id !== void 0 && !node) return { ok: false, text: `${name}: no element ${id} in the model` };
25926
+ if (node && node.type !== "scenario" && node.type !== "fitness-fn") return { ok: false, text: `${name}: ${named(node)} is no scenario or fitness function; only those are checked by tests` };
25927
+ if (name === "get_verification") {
25928
+ if (node) {
25929
+ const bound = testsBoundTo(repository.verifies, node.id);
25930
+ return { ok: true, text: bound.length ? `${named(node)} is checked by:
25931
+ ${bound.map((t) => `- ${t}`).join("\n")}` : `${REPOSITORY_FILE} binds no test to ${named(node)}: bind its tests with set_verification.` };
25932
+ }
25933
+ const model = {
25934
+ nodes: Object.fromEntries(withBoundTests(data.nodes, repository.verifies).map((n) => [n.id, n])),
25935
+ relations: Object.fromEntries(data.relations.map((r) => [r.id, r])),
25936
+ metamodel: documentMetamodel(data.metamodel, data.nodes),
25937
+ repository: { file: REPOSITORY_FILE, implements: repository.implements.map((m) => ({ ...m, missing: [] })), verifies: repository.verifies }
25938
+ };
25939
+ const unverified = Object.values(model.nodes).filter((n) => n.type === "scenario" && !conditionsOf(n).length && verifiedHere(model, n));
25940
+ return { ok: true, text: JSON.stringify({
25941
+ file: REPOSITORY_FILE,
25942
+ verifies: repository.verifies.map((v) => ({ ...v, ...nodes.has(v.element) ? {} : { unknown: "no element of the model has this id" } })),
25943
+ toVerify: unverified.map((n) => ({ id: n.id, label: n.label }))
25944
+ }, null, 2) };
25945
+ }
25946
+ if (!node) return { ok: false, text: "set_verification: id is required" };
25947
+ const at = repository.verifies.findIndex((v) => v.element === node.id);
25948
+ if (remove2 === true) {
25949
+ if (at < 0) return { ok: true, text: `${REPOSITORY_FILE} has no entry for ${named(node)}.` };
25950
+ repository.verifies.splice(at, 1);
25951
+ } else {
25952
+ if (!Array.isArray(tests) || !tests.length || !tests.every((t) => typeof t === "string" && t.trim())) {
25953
+ return { ok: false, text: 'set_verification: tests must be a list of test ids ("<file> \u203A <title>"), or remove: true' };
25954
+ }
25955
+ const entry = { element: node.id, name: node.label, tests: [...new Set(tests.map((t) => t.trim()))] };
25956
+ if (at < 0) repository.verifies.push(entry);
25957
+ else repository.verifies[at] = entry;
25958
+ }
25959
+ await mkdir4(dirname6(file), { recursive: true });
25960
+ await writeFile4(file, serializeRepositoryFile(repository));
25961
+ return { ok: true, text: remove2 === true ? `Took ${named(node)} out of ${REPOSITORY_FILE}.` : `${named(node)} is checked by ${testsBoundTo(repository.verifies, node.id).length} test(s) (${REPOSITORY_FILE}).` };
25962
+ }
25963
+ /** get_implementation and set_implementation: the repository's
25964
+ * .radical/radical.json (ADR The repository maps the model to its code). */
25965
+ async implementation(name, input, data) {
25966
+ const { id, paths, remove: remove2 } = input ?? {};
25967
+ const nodes = new Map(data.nodes.map((n) => [n.id, n]));
25968
+ const parentOf = (at2) => nodes.get(at2)?.parentId;
25969
+ const named = (n) => `${n.type} "${n.label}" (${n.id})`;
25970
+ const root2 = await mappingRoot(this.folder);
25971
+ const file = join7(root2, REPOSITORY_FILE);
25972
+ let repository;
25973
+ try {
25974
+ repository = await readFile5(file, "utf8").then((text2) => parseRepositoryFile(text2), (error) => {
25975
+ if (error.code === "ENOENT") return { implements: [], verifies: [] };
25976
+ throw error;
25977
+ });
25978
+ } catch (error) {
25979
+ return { ok: false, text: `${name}: ${error.message}` };
25980
+ }
25981
+ const mapped = repository.implements;
25982
+ if (id !== void 0 && typeof id !== "string") return { ok: false, text: `${name}: id must be an element's id` };
25983
+ const node = typeof id === "string" ? nodes.get(this.tempIds.get(id) ?? id) : void 0;
25984
+ if (id !== void 0 && !node) return { ok: false, text: `${name}: no element ${id} in the model` };
25985
+ if (name === "get_implementation") {
25986
+ if (node) {
25987
+ const found = builtIn(mapped, node.id, parentOf);
25988
+ return { ok: true, text: found ? `${named(node)} is built in ${found.paths.join(", ")}${found.from === node.id ? "" : `, as ${named(nodes.get(found.from))} is`}.` : `${named(node)} is built nowhere ${REPOSITORY_FILE} says: map it with set_implementation.` };
25989
+ }
25990
+ const nowhere = data.nodes.filter((n) => BUILT_TYPES.has(n.type) && !originOf(n) && !n.external && !builtIn(mapped, n.id, parentOf));
25991
+ return { ok: true, text: JSON.stringify({
25992
+ file: REPOSITORY_FILE,
25993
+ implements: mapped.map((m) => ({ ...m, ...nodes.has(m.element) ? {} : { unknown: "no element of the model has this id" } })),
25994
+ builtNowhere: nowhere.map((n) => ({ id: n.id, type: n.type, label: n.label, parentId: n.parentId ?? null }))
25995
+ }, null, 2) };
25996
+ }
25997
+ if (!node) return { ok: false, text: "set_implementation: id is required" };
25998
+ const at = mapped.findIndex((m) => m.element === node.id);
25999
+ if (remove2 === true) {
26000
+ if (at < 0) return { ok: true, text: `${REPOSITORY_FILE} has no entry for ${named(node)}.` };
26001
+ mapped.splice(at, 1);
26002
+ await writeFile4(file, serializeRepositoryFile(repository));
26003
+ return { ok: true, text: `Took ${named(node)} out of ${REPOSITORY_FILE}.` };
26004
+ }
26005
+ if (!Array.isArray(paths) || !paths.length || !paths.every((p) => typeof p === "string" && p.trim())) {
26006
+ return { ok: false, text: "set_implementation: paths must be a list of folders from the repository's root, or remove: true" };
26007
+ }
26008
+ const clean = paths.map((p) => relative2(root2, resolve5(root2, p)).split("\\").join("/") || ".");
26009
+ const outside = clean.filter((p) => p.startsWith("..") || isAbsolute(p));
26010
+ if (outside.length) return { ok: false, text: `set_implementation: ${outside.join(", ")} ${outside.length === 1 ? "is" : "are"} outside the repository` };
26011
+ const entry = { element: node.id, name: node.label, paths: clean };
26012
+ if (at < 0) mapped.push(entry);
26013
+ else mapped[at] = entry;
26014
+ await mkdir4(dirname6(file), { recursive: true });
26015
+ await writeFile4(file, serializeRepositoryFile(repository));
26016
+ const missing = (await Promise.all(clean.map(async (p) => await stat4(join7(root2, p)).then(() => true, () => false) ? null : p))).filter((p) => p !== null);
26017
+ return { ok: true, text: `${named(node)} is built in ${clean.join(", ")} (${REPOSITORY_FILE}).${missing.length ? ` Not in the repository yet: ${missing.join(", ")}; radical check warns until they are.` : ""}` };
26018
+ }
24602
26019
  async selection(facade) {
24603
- const text = await readEditorStateFile(this.folder, SELECTION_FILE);
24604
- if (text === null) {
26020
+ const text2 = await readEditorStateFile(this.folder, SELECTION_FILE);
26021
+ if (text2 === null) {
24605
26022
  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
26023
  }
24607
- const selection2 = parseSelection(text);
26024
+ const selection2 = parseSelection(text2);
24608
26025
  if (!selection2) {
24609
26026
  const version = (() => {
24610
26027
  try {
24611
- return JSON.parse(text).version;
26028
+ return JSON.parse(text2).version;
24612
26029
  } catch {
24613
26030
  return void 0;
24614
26031
  }
@@ -24694,14 +26111,16 @@ ${buildMetamodelMessage(metamodel2)}` };
24694
26111
  if (name === "get_issues") {
24695
26112
  const mm = facade.getMetamodel?.();
24696
26113
  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") };
26114
+ const text2 = issues.length ? issues.map(formatIssue).join("\n") : "No issues: the model follows its metamodel.";
26115
+ return { ok: true, text: [text2, ...this.openConcerns(data, mm)].join("\n") };
24699
26116
  }
24700
26117
  if (name === "get_selection") return { ok: true, text: await this.selection(facade) };
26118
+ if (name === "get_implementation" || name === "set_implementation") return await this.implementation(name, input, data);
26119
+ if (name === "get_verification" || name === "set_verification") return await this.verification(name, input, data);
24701
26120
  if (name === "get_changes") {
24702
26121
  const { since } = input ?? {};
24703
26122
  if (since !== void 0 && typeof since !== "string") return { ok: false, text: "get_changes: since must be a git branch, tag or commit" };
24704
- return { ok: true, text: (await modelChangesSince(this.folder, data, since, { saveBase: since === void 0 })).text };
26123
+ return { ok: true, text: (await modelChangesSince(this.folder, ownModel(data), since, { saveBase: since === void 0 })).text };
24705
26124
  }
24706
26125
  priorTempIds = new Map(this.tempIds);
24707
26126
  const ctx = {
@@ -24724,7 +26143,7 @@ ${buildMetamodelMessage(metamodel2)}` };
24724
26143
  this.restoreTempIds(priorTempIds);
24725
26144
  return { ok: false, text: facade.lastError ?? result.resultText };
24726
26145
  }
24727
- const forgeBase = name === "forge_start" ? forgeModelBase(data.nodes, data.relations) : null;
26146
+ const forgeBase = name === "forge_start" ? forgeModelBase(ownModel(data).nodes, ownModel(data).relations) : null;
24728
26147
  if (READ_ONLY2.has(name) || result.readOnly) {
24729
26148
  result.commit?.();
24730
26149
  if (FORGE_TOOLS.has(name)) await this.writeForgeStatus();
@@ -24791,7 +26210,7 @@ ${buildMetamodelMessage(metamodel2)}` };
24791
26210
  if (!result.candidates.length) return { ok: false, text: "Smart Layout: no candidate produced a result." };
24792
26211
  if (result.keptCurrent) {
24793
26212
  if (view && !Object.keys(view.positions ?? {}).length) {
24794
- view.positions = viewCanvasPositions(view, nodes, positionsOf(nodes), viewDrawnIds(view, nodes, byId3(changed.relations)));
26213
+ view.positions = viewCanvasPositions(view, nodes, positionsOf2(nodes), viewDrawnIds(view, nodes, byId3(changed.relations)));
24795
26214
  return { ok: true, changed, text: `Smart Layout (${view.name}): nothing left to tidy; the view keeps its places.` };
24796
26215
  }
24797
26216
  const where = view ? ` (${view.name})` : "";
@@ -24806,7 +26225,7 @@ ${buildMetamodelMessage(metamodel2)}` };
24806
26225
  else changed.defaultLayoutConstraints = changed.defaultLayoutConstraints?.filter((c) => c.type !== "pin");
24807
26226
  }
24808
26227
  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)));
26228
+ if (view) view.positions = viewCanvasPositions(view, nodes, positionsOf2(nodes), viewDrawnIds(view, nodes, byId3(changed.relations)));
24810
26229
  const before = result.baseline;
24811
26230
  const after = result.winner.metrics;
24812
26231
  const tidied = result.tidy;
@@ -24826,7 +26245,7 @@ ${buildMetamodelMessage(metamodel2)}` };
24826
26245
  const unpinned = pinnedNodeIds(constraints).length;
24827
26246
  view.layoutConstraints = view.layoutConstraints?.filter((c) => c.type !== "pin");
24828
26247
  applyAlignments(nodes, viewLayoutInput(view, nodes, byId3(changed.relations), constraints));
24829
- view.positions = viewCanvasPositions(view, nodes, positionsOf(nodes), viewDrawnIds(view, nodes, byId3(changed.relations)));
26248
+ view.positions = viewCanvasPositions(view, nodes, positionsOf2(nodes), viewDrawnIds(view, nodes, byId3(changed.relations)));
24830
26249
  return {
24831
26250
  ok: true,
24832
26251
  changed,
@@ -24856,6 +26275,7 @@ ${buildMetamodelMessage(metamodel2)}` };
24856
26275
  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
26276
  if (!paths.length) return { ok: true, text: `${resultText} No files changed.${warned}` };
24858
26277
  const write = await session.write(next, mergeMdFolderFiles);
26278
+ await session.cacheWritten();
24859
26279
  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
26280
  await this.markAgentWriting();
24861
26281
  const notices = write.merged ? mergeNotices(write.merged, { ours: "by this call", theirs: "in the folder meanwhile" }) : [];
@@ -24877,14 +26297,16 @@ ${buildMetamodelMessage(metamodel2)}` };
24877
26297
  for (const [temp, real] of previous) this.tempIds.set(temp, real);
24878
26298
  }
24879
26299
  };
24880
- function positionsOf(nodes) {
26300
+ function positionsOf2(nodes) {
24881
26301
  return Object.fromEntries(Object.values(nodes).map((node) => [node.id, { x: node.x, y: node.y, width: node.width, height: node.height }]));
24882
26302
  }
24883
26303
 
24884
26304
  // src/index.ts
24885
- var USAGE = `Usage: radical-mcp --folder <model-folder> [--metamodel ${Object.keys(PRESETS).join("|")}]
26305
+ var USAGE = `Usage: radical-mcp [--folder <model-folder>] [--metamodel ${Object.keys(PRESETS).join("|")}]
24886
26306
  --folder the Markdown model folder, absolute or relative to the working directory;
24887
- a missing or empty folder becomes a new model
26307
+ a missing or empty folder becomes a new model. Without it: the
26308
+ working directory when it is a model folder, else the
26309
+ repository's .radical/model (or architecture/ of the old layout)
24888
26310
  --metamodel the metamodel of a new model (default: radical)
24889
26311
  --version print the version`;
24890
26312
  function parseArgs(args) {
@@ -24896,7 +26318,7 @@ function parseArgs(args) {
24896
26318
  }
24897
26319
  const folder = values.get("--folder");
24898
26320
  const metamodel = values.get("--metamodel");
24899
- if (!folder || metamodel !== void 0 && !(metamodel in PRESETS)) throw new Error(USAGE);
26321
+ if (metamodel !== void 0 && !(metamodel in PRESETS)) throw new Error(USAGE);
24900
26322
  return { folder, metamodel };
24901
26323
  }
24902
26324
  var INSTRUCTIONS = [
@@ -24957,7 +26379,10 @@ async function main() {
24957
26379
  `);
24958
26380
  return;
24959
26381
  }
24960
- const { folder, metamodel } = parseArgs(args);
26382
+ const { folder: named, metamodel } = parseArgs(args);
26383
+ const folder = named ?? await findModelFolder(process.cwd());
26384
+ if (!folder) throw new Error(`No model folder here or in .radical/model of the repository.
26385
+ ${USAGE}`);
24961
26386
  const model = await FolderModel.open(folder, { metamodel });
24962
26387
  const server = new McpServer({ name: "radical-folder", version: displayVersion() }, { instructions: INSTRUCTIONS });
24963
26388
  const registered = /* @__PURE__ */ new Map();