@radicaltools/mcp 0.3.1 → 0.3.3

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.
package/dist/index.js CHANGED
@@ -85,7 +85,7 @@ import {
85
85
  viewShowsEveryNode,
86
86
  wikiDepthOf,
87
87
  withCanvasPositions
88
- } from "./chunk-2SZDTOYJ.js";
88
+ } from "./chunk-DRPYDYRL.js";
89
89
 
90
90
  // ../../node_modules/webcola/dist/src/powergraph.js
91
91
  var require_powergraph = __commonJS({
@@ -4966,181 +4966,13 @@ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
4966
4966
 
4967
4967
  // src/folderModel.ts
4968
4968
  init_define_RADICAL_BUILD();
4969
- import { mkdir as mkdir4, readdir as readdir2, realpath, stat as stat3 } from "fs/promises";
4970
- 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";
4971
4971
  import { createHash } from "crypto";
4972
4972
 
4973
4973
  // ../../packages/common/src/ai/tools/index.ts
4974
4974
  init_define_RADICAL_BUILD();
4975
4975
 
4976
- // ../../packages/common/src/ai/tools/layoutTools.ts
4977
- init_define_RADICAL_BUILD();
4978
-
4979
- // ../../packages/common/src/ai/tools/types.ts
4980
- init_define_RADICAL_BUILD();
4981
- function fail(resultText) {
4982
- return { ok: false, resultText };
4983
- }
4984
- function sequenceStepCount(ctx) {
4985
- return Object.values(ctx.diagram.getSequences?.() ?? {}).reduce((n, q) => n + q.relationIds.length, 0);
4986
- }
4987
- var stepsGone = (n) => n > 0 ? ` and ${n} sequence step${n === 1 ? "" : "s"} along its relation${n === 1 ? "" : "s"}` : "";
4988
-
4989
- // ../../packages/common/src/ai/tools/layoutTools.ts
4990
- var AXIS_ENUM = ["horizontal", "vertical"];
4991
- function noCanvasLayout(tool, view) {
4992
- if (!view.kind || view.kind === "static") return null;
4993
- 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`;
4994
- 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)" : ""}`;
4995
- }
4996
- function canvasFor(ctx, tool, raw, removing = false) {
4997
- if (raw === void 0) return { viewId: null };
4998
- if (typeof raw !== "string" || !raw) return { error: `${tool}: viewId must be a view id` };
4999
- const viewId = ctx.resolveId(raw);
5000
- const view = ctx.diagram.getViews?.()[viewId];
5001
- if (!view) return { error: `${tool}: unknown view id "${raw}"` };
5002
- const refused = removing ? null : noCanvasLayout(tool, view);
5003
- if (refused) return { error: refused };
5004
- return { viewId };
5005
- }
5006
- 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(", ")})`;
5007
- function buildLayoutToolDefs() {
5008
- return [
5009
- {
5010
- name: "smart_layout",
5011
- 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.",
5012
- inputSchema: {
5013
- type: "object",
5014
- properties: {
5015
- viewId: { type: "string", description: "A static view (real id or tempId); omit for All elements." },
5016
- 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." }
5017
- },
5018
- additionalProperties: false
5019
- }
5020
- },
5021
- {
5022
- name: "align_nodes",
5023
- 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.",
5024
- inputSchema: {
5025
- type: "object",
5026
- properties: {
5027
- 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)." },
5028
- axis: { type: "string", enum: [...AXIS_ENUM], description: "'horizontal' = a row, 'vertical' = a column." },
5029
- keepOrder: { type: "boolean", description: "Also keep the elements in the order of nodeIds along the line; no layout may swap them." },
5030
- viewId: { type: "string", description: "A static view (real id or tempId); omit for All elements." }
5031
- },
5032
- required: ["nodeIds", "axis"],
5033
- additionalProperties: false
5034
- }
5035
- },
5036
- {
5037
- name: "grid_nodes",
5038
- 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.",
5039
- inputSchema: {
5040
- type: "object",
5041
- properties: {
5042
- nodeIds: { type: "array", items: { type: "string" }, description: "Two or more node ids or tempIds, in reading order; none inside another." },
5043
- 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)." },
5044
- viewId: { type: "string", description: "A static view (real id or tempId); omit for All elements." }
5045
- },
5046
- required: ["nodeIds"],
5047
- additionalProperties: false
5048
- }
5049
- },
5050
- {
5051
- name: "remove_alignment",
5052
- 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.",
5053
- inputSchema: {
5054
- type: "object",
5055
- properties: {
5056
- id: { type: "string", description: "Alignment id, as align_nodes returned it." },
5057
- nodeIds: { type: "array", items: { type: "string" }, description: "Removes the alignments made only of these elements." },
5058
- 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." }
5059
- },
5060
- additionalProperties: false
5061
- }
5062
- }
5063
- ];
5064
- }
5065
- function buildAlignmentToolHandlers() {
5066
- return {
5067
- align_nodes: (rawInput, ctx) => {
5068
- const input = rawInput ?? {};
5069
- if (!ctx.diagram.addAlignment) return fail("align_nodes: alignments are not editable in this context");
5070
- if (input.keepOrder !== void 0 && typeof input.keepOrder !== "boolean") return fail("align_nodes: keepOrder must be true or false");
5071
- if (!Array.isArray(input.nodeIds) || input.nodeIds.some((id) => typeof id !== "string")) return fail("align_nodes: nodeIds must be an array of node ids");
5072
- if (!AXIS_ENUM.includes(input.axis)) return fail(`align_nodes: axis must be 'horizontal' or 'vertical'`);
5073
- const canvas2 = canvasFor(ctx, "align_nodes", input.viewId);
5074
- if ("error" in canvas2) return fail(canvas2.error);
5075
- const nodeIds = input.nodeIds.map((id) => ctx.resolveId(id));
5076
- const added = ctx.diagram.addAlignment(canvas2.viewId, input.axis, nodeIds, input.keepOrder === true);
5077
- if ("error" in added) return fail(`align_nodes: ${added.error}`);
5078
- const order = input.keepOrder === true ? ", in the order given" : "";
5079
- return { ok: true, resultText: `Aligned ${nodeIds.length} elements in a ${input.axis === "horizontal" ? "row" : "column"}${order}. Alignment ID: ${added.id}.`, updated: { views: 1 } };
5080
- },
5081
- grid_nodes: (rawInput, ctx) => {
5082
- const input = rawInput ?? {};
5083
- if (!ctx.diagram.addGrid) return fail("grid_nodes: grids are not editable in this context");
5084
- if (!Array.isArray(input.nodeIds) || input.nodeIds.some((id) => typeof id !== "string")) return fail("grid_nodes: nodeIds must be an array of node ids");
5085
- 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");
5086
- const canvas2 = canvasFor(ctx, "grid_nodes", input.viewId);
5087
- if ("error" in canvas2) return fail(canvas2.error);
5088
- const nodeIds = input.nodeIds.map((id) => ctx.resolveId(id));
5089
- const columns = input.columns ?? defaultGridColumns(nodeIds.length);
5090
- const added = ctx.diagram.addGrid(canvas2.viewId, nodeIds, columns);
5091
- if ("error" in added) return fail(`grid_nodes: ${added.error}`);
5092
- return { ok: true, resultText: `Kept ${nodeIds.length} elements in a grid of ${columns} columns. Alignment ID: ${added.id}.`, updated: { views: 1 } };
5093
- },
5094
- remove_alignment: (rawInput, ctx) => {
5095
- const input = rawInput ?? {};
5096
- if (!ctx.diagram.getLayoutConstraints || !ctx.diagram.removeLayoutConstraints) return fail("remove_alignment: alignments are not editable in this context");
5097
- if (input.id === void 0 && input.nodeIds === void 0) return fail("remove_alignment: pass id or nodeIds");
5098
- if (input.id !== void 0 && (typeof input.id !== "string" || !input.id)) return fail("remove_alignment: id must be an alignment id");
5099
- 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");
5100
- const canvas2 = canvasFor(ctx, "remove_alignment", input.viewId, true);
5101
- if ("error" in canvas2) return fail(canvas2.error);
5102
- const among = input.nodeIds ? new Set(input.nodeIds.map((id) => ctx.resolveId(id))) : null;
5103
- 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))));
5104
- if (!matches.length) {
5105
- const existing = ctx.diagram.getLayoutConstraints(canvas2.viewId);
5106
- return fail(`remove_alignment: no such alignment on this canvas.${existing.length ? ` It has: ${existing.map(describeConstraint).join("; ")}.` : " It has none."}`);
5107
- }
5108
- ctx.diagram.removeLayoutConstraints(canvas2.viewId, matches.map((c) => c.id));
5109
- return { ok: true, resultText: `Removed ${matches.map(describeConstraint).join("; ")}.`, updated: { views: 1 } };
5110
- }
5111
- };
5112
- }
5113
- function buildLayoutToolHandlers() {
5114
- return {
5115
- smart_layout: async (rawInput, ctx) => {
5116
- const input = rawInput ?? {};
5117
- if (!ctx.diagram.runLayout) return fail("smart_layout: layout is not available in this context");
5118
- let around;
5119
- if (input.around !== void 0) {
5120
- 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");
5121
- around = input.around.map((id) => ctx.resolveId(id));
5122
- const nodes = ctx.diagram.getNodes();
5123
- const unknown = around.filter((id) => !nodes[id]);
5124
- if (unknown.length) return fail(`smart_layout: unknown node id(s) ${unknown.join(", ")}`);
5125
- }
5126
- if (input.viewId !== void 0 && (typeof input.viewId !== "string" || !input.viewId)) return fail("smart_layout: viewId must be a view id");
5127
- let viewId;
5128
- if (typeof input.viewId === "string") {
5129
- viewId = ctx.resolveId(input.viewId);
5130
- const view = ctx.diagram.getViews?.()[viewId];
5131
- if (!view) return fail(`smart_layout: unknown view id "${input.viewId}"`);
5132
- const refused = noCanvasLayout("smart_layout", view);
5133
- if (refused) return fail(refused);
5134
- }
5135
- const outcome = await ctx.diagram.runLayout(viewId, around);
5136
- return { ok: outcome.ok, resultText: outcome.text };
5137
- }
5138
- };
5139
- }
5140
-
5141
- // ../../packages/common/src/ai/tools/metamodelTools.ts
5142
- init_define_RADICAL_BUILD();
5143
-
5144
4976
  // ../../packages/common/src/model.ts
5145
4977
  init_define_RADICAL_BUILD();
5146
4978
 
@@ -5476,10 +5308,21 @@ function viewShownNodes(view, nodes, relations) {
5476
5308
  const hit = shownCache.get(view.nodeIds);
5477
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;
5478
5310
  }
5479
- 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);
5480
5316
  if (cacheable) shownCache.set(view.nodeIds, { nodes, relations, pipeline: view.pipeline, kind: view.kind, empty: view.empty, shown });
5481
5317
  return shown;
5482
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
+ }
5483
5326
  var shownCache = /* @__PURE__ */ new WeakMap();
5484
5327
  function chainKeys(pipeline) {
5485
5328
  if (!pipeline || typeof pipeline !== "object") return BASE_KEYS;
@@ -5793,6 +5636,79 @@ function materializeDefaults(node, mm) {
5793
5636
  if (p.default !== void 0 && node[p.key] === void 0) node[p.key] = p.default;
5794
5637
  }
5795
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
+ }
5796
5712
  function checkAddNode(state, node) {
5797
5713
  const mm = state.metamodel;
5798
5714
  const label = typeLabel3(mm, node.type);
@@ -5802,6 +5718,9 @@ function checkAddNode(state, node) {
5802
5718
  }
5803
5719
  const parent = node.parentId ? state.c4Nodes[node.parentId] : void 0;
5804
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.";
5805
5724
  if (!isPlacementAllowed(mm, node.type, parent, state.c4Nodes)) {
5806
5725
  return `Cannot place ${label} inside ${placementError(mm, node.type, parent, state.c4Nodes)}`;
5807
5726
  }
@@ -5825,6 +5744,13 @@ function insertNode(state, id, node) {
5825
5744
  function checkNodeUpdate(state, id, updates) {
5826
5745
  const existing = state.c4Nodes[id];
5827
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
+ }
5828
5754
  if (!("parentId" in updates) && !("type" in updates) && !("kind" in updates)) return null;
5829
5755
  const newType = updates.type ?? existing.type;
5830
5756
  const newParentId = ("parentId" in updates ? updates.parentId : existing.parentId) ?? void 0;
@@ -5832,6 +5758,10 @@ function checkNodeUpdate(state, id, updates) {
5832
5758
  if ("parentId" in updates && newParentId && (newParentId === id || descendantIds(id, state.c4Nodes).includes(newParentId))) {
5833
5759
  return "Cannot move a node into itself or one of its descendants.";
5834
5760
  }
5761
+ if ("parentId" in updates && newParentId !== existing.parentId) {
5762
+ const external = parentReadOnly(parent);
5763
+ if (external) return external;
5764
+ }
5835
5765
  if (!isPlacementAllowed(state.metamodel, newType, parent, state.c4Nodes)) {
5836
5766
  return `Cannot move ${typeLabel3(state.metamodel, newType)} "${existing.label}" into ${placementError(state.metamodel, newType, parent, state.c4Nodes)}`;
5837
5767
  }
@@ -5888,6 +5818,12 @@ function checkReparent(state, ids, newParentId) {
5888
5818
  }
5889
5819
  const newParent = newParentId ? state.c4Nodes[newParentId] : void 0;
5890
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;
5891
5827
  const moved = new Set(nodes.flatMap((n) => [n.id, ...descendantIds(n.id, state.c4Nodes)]));
5892
5828
  if (newParentId && moved.has(newParentId)) return "Cannot move a node into itself or one of its descendants.";
5893
5829
  if (newParent?.external && oldParentId !== newParentId) {
@@ -6252,6 +6188,7 @@ function metamodelWithoutNodeType(mm, typeId) {
6252
6188
  return next;
6253
6189
  }
6254
6190
  function checkAddRelation(state, rel) {
6191
+ if (originOf(rel)) return "A relation's origin is set by radical federation, not by an edit.";
6255
6192
  return relationRefusal(relationContext(state), rel);
6256
6193
  }
6257
6194
  var relationContext = (state) => ({ nodes: state.c4Nodes, relations: state.c4Relations, metamodel: state.metamodel });
@@ -6274,6 +6211,12 @@ function insertRelation(state, id, rel) {
6274
6211
  function checkPatchRelation(state, id, updates) {
6275
6212
  const rel = state.c4Relations[id];
6276
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
+ }
6277
6220
  const retyped = updates.relationType !== void 0 && updates.relationType !== rel.relationType;
6278
6221
  if (updates.sourceId === void 0 && updates.targetId === void 0 && !retyped) return null;
6279
6222
  return relationRefusal(relationContext(state), { ...rel, ...updates, relationType: retyped ? updates.relationType : void 0 }, id, rel.relationType);
@@ -6704,23 +6647,191 @@ function modelValue(value) {
6704
6647
  if (Array.isArray(value) && !value.length) return null;
6705
6648
  return value;
6706
6649
  }
6707
- var sameModelValue = (a, b) => JSON.stringify(modelValue(a)) === JSON.stringify(modelValue(b));
6708
- var sameValue = sameModelValue;
6709
- function changedFields(before, after) {
6710
- const a = before;
6711
- const b = after;
6712
- const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
6713
- return [...keys].filter((key) => !LAYOUT_KEYS.has(key) && !sameValue(a[key], b[key])).sort();
6650
+ var sameModelValue = (a, b) => JSON.stringify(modelValue(a)) === JSON.stringify(modelValue(b));
6651
+ var sameValue = sameModelValue;
6652
+ function changedFields(before, after) {
6653
+ const a = before;
6654
+ const b = after;
6655
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
6656
+ return [...keys].filter((key) => !LAYOUT_KEYS.has(key) && !sameValue(a[key], b[key])).sort();
6657
+ }
6658
+ function compareModels(before, after) {
6659
+ const diff = (from, to) => ({
6660
+ added: Object.keys(to).filter((id) => !(id in from)),
6661
+ removed: Object.keys(from).filter((id) => !(id in to)),
6662
+ changed: Object.keys(to).filter((id) => id in from && from[id] !== to[id]).map((id) => ({ id, fields: changedFields(from[id], to[id]) })).filter((change) => change.fields.length > 0)
6663
+ });
6664
+ return { nodes: diff(before.nodes, after.nodes), relations: diff(before.relations, after.relations) };
6665
+ }
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
+ };
6714
6803
  }
6715
- function compareModels(before, after) {
6716
- const diff = (from, to) => ({
6717
- added: Object.keys(to).filter((id) => !(id in from)),
6718
- removed: Object.keys(from).filter((id) => !(id in to)),
6719
- changed: Object.keys(to).filter((id) => id in from && from[id] !== to[id]).map((id) => ({ id, fields: changedFields(from[id], to[id]) })).filter((change) => change.fields.length > 0)
6720
- });
6721
- return { nodes: diff(before.nodes, after.nodes), relations: diff(before.relations, after.relations) };
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
+ };
6722
6830
  }
6723
6831
 
6832
+ // ../../packages/common/src/ai/tools/metamodelTools.ts
6833
+ init_define_RADICAL_BUILD();
6834
+
6724
6835
  // ../../packages/common/src/ai/tools/viewTools.ts
6725
6836
  init_define_RADICAL_BUILD();
6726
6837
  var VIEW_KIND_ENUM = ["static", "table", "treemap", "matrix", "wiki", "warnier", "dynamic"];
@@ -9148,6 +9259,13 @@ function buildNodeToolHandlers() {
9148
9259
  if (typeof input.id !== "string" || !input.id) return fail("delete_node: id is required");
9149
9260
  const realId = ctx.resolveId(input.id);
9150
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}`);
9151
9269
  const steps = sequenceStepCount(ctx);
9152
9270
  ctx.diagram.removeNode(realId);
9153
9271
  return { ok: true, resultText: `Deleted node ${realId}${stepsGone(steps - sequenceStepCount(ctx))}.`, deleted: { nodes: 1 } };
@@ -9481,6 +9599,14 @@ function buildRelationToolHandlers() {
9481
9599
  ...effectiveType !== oldType && !effectiveType ? { relationType: void 0 } : {},
9482
9600
  ...Object.fromEntries([...cleared, ...removed].map((key) => [key, void 0]))
9483
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}`);
9484
9610
  ctx.diagram.updateRelation(realId, updates);
9485
9611
  const resultText = notes.length ? `Updated relation ${realId}. ${notes.join("; ")}` : `Updated relation ${realId}.`;
9486
9612
  return { ok: true, resultText, updated: { relations: 1 } };
@@ -9490,6 +9616,13 @@ function buildRelationToolHandlers() {
9490
9616
  if (typeof input.id !== "string" || !input.id) return fail("delete_relation: id is required");
9491
9617
  const realId = ctx.resolveId(input.id);
9492
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}`);
9493
9626
  const steps = sequenceStepCount(ctx);
9494
9627
  ctx.diagram.removeRelation(realId);
9495
9628
  return { ok: true, resultText: `Deleted relation ${realId}${stepsGone(steps - sequenceStepCount(ctx))}.`, deleted: { relations: 1 } };
@@ -9654,12 +9787,34 @@ var ASYNC = new Map(Object.entries(buildLayoutToolHandlers()));
9654
9787
  async function runTool(name, input, ctx) {
9655
9788
  const handler = ASYNC.get(name) ?? SYNC.get(name);
9656
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}` };
9657
9792
  try {
9658
9793
  return await handler(input, ctx);
9659
9794
  } catch (err) {
9660
9795
  return { ok: false, resultText: err.message };
9661
9796
  }
9662
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
+ }
9663
9818
 
9664
9819
  // ../../packages/common/src/ai/modelFacade.ts
9665
9820
  init_define_RADICAL_BUILD();
@@ -9740,6 +9895,11 @@ function createModelFacade(data, options = {}) {
9740
9895
  syncGroups();
9741
9896
  },
9742
9897
  removeNode(id) {
9898
+ const refused = checkRemove(state, [id]);
9899
+ if (refused) {
9900
+ refuse(refused);
9901
+ return;
9902
+ }
9743
9903
  if (carried.snapshots?.length && state.c4Nodes[id]) {
9744
9904
  carried.snapshots = keepViewsInMilestones(carried.snapshots, state.views, /* @__PURE__ */ new Set([id, ...descendantIds(id, state.c4Nodes)]));
9745
9905
  }
@@ -9771,6 +9931,11 @@ function createModelFacade(data, options = {}) {
9771
9931
  patchRelation(state, id, updates);
9772
9932
  },
9773
9933
  removeRelation(id) {
9934
+ const refused = checkRemove(state, [], [id]);
9935
+ if (refused) {
9936
+ refuse(refused);
9937
+ return;
9938
+ }
9774
9939
  deleteRelation(state, id);
9775
9940
  },
9776
9941
  addView(name, opts) {
@@ -9877,13 +10042,15 @@ function createModelFacade(data, options = {}) {
9877
10042
  getMilestones: () => carried.snapshots ?? [],
9878
10043
  createMilestone(name) {
9879
10044
  const id = newId();
10045
+ const own = ownModel({ nodes: Object.values(state.c4Nodes), relations: Object.values(state.c4Relations) });
9880
10046
  const milestone = {
9881
10047
  id,
9882
10048
  name,
9883
10049
  timestamp: Date.now(),
9884
- nodes: clone(state.c4Nodes),
9885
- relations: clone(state.c4Relations),
9886
- 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 })) } : {}
9887
10054
  };
9888
10055
  carried.snapshots = [...carried.snapshots ?? [], milestone];
9889
10056
  return id;
@@ -10331,7 +10498,8 @@ function allocateSlugs(claims) {
10331
10498
  function serializeToMdFolder(data, modelName) {
10332
10499
  return serializeToMdFolderWithPaths(data, modelName).files;
10333
10500
  }
10334
- function serializeToMdFolderWithPaths(data, modelName) {
10501
+ function serializeToMdFolderWithPaths(model, modelName) {
10502
+ const data = ownModel(model);
10335
10503
  const files = {};
10336
10504
  const nodePaths = {};
10337
10505
  const layout = { nodes: {} };
@@ -11012,9 +11180,11 @@ init_define_RADICAL_BUILD();
11012
11180
 
11013
11181
  // ../../packages/common/src/formats/canvasSelection.ts
11014
11182
  init_define_RADICAL_BUILD();
11015
- var SELECTION_DIR = ".radical";
11016
- var SELECTION_FILE = `${SELECTION_DIR}/selection.json`;
11017
- var SELECTION_GITIGNORE = `${SELECTION_DIR}/.gitignore`;
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`;
11018
11188
  var SELECTION_GITIGNORE_CONTENT = "*\n";
11019
11189
  var isIdList = (value) => Array.isArray(value) && value.every((id) => typeof id === "string" && id.length > 0);
11020
11190
  function parseSelection(text2) {
@@ -11032,7 +11202,7 @@ function parseSelection(text2) {
11032
11202
  }
11033
11203
 
11034
11204
  // ../../packages/common/src/formats/modelCache.ts
11035
- var MODEL_CACHE_DIR = `${SELECTION_DIR}/cache`;
11205
+ var MODEL_CACHE_DIR = `${STATE_DIR}/cache`;
11036
11206
  var MODEL_CACHE_FILE = `${MODEL_CACHE_DIR}/model.json`;
11037
11207
  var MODEL_CACHE_NAMES = /* @__PURE__ */ new Set(["model.json", "changes.json", "views.json"]);
11038
11208
  var MODEL_CACHE_VERSION = 2;
@@ -11408,13 +11578,13 @@ function sameStamps(a, b) {
11408
11578
  // ../../packages/node-files/src/diskFolderStorage.ts
11409
11579
  init_define_RADICAL_BUILD();
11410
11580
  import { randomUUID } from "crypto";
11411
- import { lstat as lstat2, mkdir as mkdir2, readFile as readFile2, readdir, rename, rm, stat, writeFile as writeFile2 } from "fs/promises";
11412
- import { dirname as dirname2, join as join2, resolve as resolve2, sep } from "path";
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";
11413
11583
 
11414
11584
  // ../../packages/node-files/src/selectionFile.ts
11415
11585
  init_define_RADICAL_BUILD();
11416
- import { lstat, mkdir, readFile, writeFile } from "fs/promises";
11417
- 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";
11418
11588
 
11419
11589
  // ../../packages/common/src/formats/forgeRunStatus.ts
11420
11590
  init_define_RADICAL_BUILD();
@@ -11708,9 +11878,9 @@ function stageTask(stageId, descBlock, need) {
11708
11878
  "leave it empty. In `metrics` put one condition",
11709
11879
  "per line that says when it passes: a measured value and its threshold, with",
11710
11880
  "the metric named as a sensor would report it",
11711
- "(`checkout.latency.p95{env=prod} <= 300 ms`, `deps.cycles == 0`), or a test",
11712
- "that has to pass (`test(<file> \u203A <title>) passed`) where the description names",
11713
- "one. Put what the conditions cannot say in the description. No",
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",
11714
11884
  "systems/containers exist yet (C4 runs later, once this spec is settled), so",
11715
11885
  "link each fitness function to the requirement(s) it constrains with a",
11716
11886
  "`traces-to` relation FROM the requirement TO the fitness function (the",
@@ -11851,7 +12021,7 @@ function stageTask(stageId, descBlock, need) {
11851
12021
  }
11852
12022
 
11853
12023
  // ../../packages/common/src/formats/forgeRunStatus.ts
11854
- var FORGE_RUN_FILE = `${SELECTION_DIR}/forge-run.json`;
12024
+ var FORGE_RUN_FILE = `${STATE_DIR}/forge-run.json`;
11855
12025
  var FORGE_RUN_STALE_MS = 30 * 60 * 1e3;
11856
12026
  function serializeForgeRun(status, now4 = /* @__PURE__ */ new Date()) {
11857
12027
  const out = { version: 1, ...status, updatedAt: now4.toISOString() };
@@ -11866,6 +12036,87 @@ init_define_RADICAL_BUILD();
11866
12036
  // ../../packages/common/src/check/rules.ts
11867
12037
  init_define_RADICAL_BUILD();
11868
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
+
11869
12120
  // ../../packages/common/src/check/evidence.ts
11870
12121
  init_define_RADICAL_BUILD();
11871
12122
 
@@ -12036,7 +12287,20 @@ function evaluateMetric(condition, measurements, maxAge, now4, baseline = []) {
12036
12287
 
12037
12288
  // ../../packages/common/src/check/evidence.ts
12038
12289
  var TESTED_TYPES = ["scenario", "fitness-fn"];
12039
- var conditionsOf = (node) => parseConditions(node.metrics);
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
+ };
12040
12304
  var testIdsOf = (node) => conditionsOf(node).flatMap((c) => c.kind === "test" ? [c.id] : []);
12041
12305
  var testOutcome = (id, model) => {
12042
12306
  const { fileSeen, matches } = findTests(id, model.tests ?? []);
@@ -12045,16 +12309,32 @@ var testOutcome = (id, model) => {
12045
12309
  function testOutcomes(node, model) {
12046
12310
  return testIdsOf(node).map((id) => ({ id, outcome: testOutcome(id, model) }));
12047
12311
  }
12048
- function conditionResults(node, model) {
12312
+ function conditionResults(node, model, element) {
12049
12313
  const maxAge = parseMaxAge(node.max_age) ?? void 0;
12050
12314
  const now4 = model.now ?? Date.now();
12051
12315
  return conditionsOf(node).map((c) => {
12052
12316
  if (c.kind === "invalid") return { condition: c.raw, outcome: "invalid", detail: c.problem };
12053
12317
  if (c.kind === "test") return { condition: c.raw, test: c.id.raw, outcome: testOutcome(c.id, model) };
12054
- const e = evaluateMetric(c, model.measurements ?? [], maxAge, now4, model.baseline ?? []);
12318
+ const metric = element ? { ...c, labels: { ...c.labels, [ELEMENT_LABEL]: element.id } } : c;
12319
+ const e = evaluateMetric(metric, model.measurements ?? [], maxAge, now4, model.baseline ?? []);
12055
12320
  return { condition: c.raw, outcome: e.outcome, ...e.measurement ? { measurement: e.measurement } : {}, ...e.detail ? { detail: e.detail } : {} };
12056
12321
  });
12057
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
+ }
12058
12338
  function linkedNodes(model, id, relationType, end, type) {
12059
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));
12060
12340
  }
@@ -12541,6 +12821,7 @@ function unlinked(model, type, relation, end, otherTypes) {
12541
12821
  }
12542
12822
  var quote = (n) => `"${n.label}"`;
12543
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);
12544
12825
  var affectedBy = (model, node) => node.type === "scenario" ? linkedNodes(model, node.id, "verifies", "target", "requirement") : linkedNodes(model, node.id, "implements", "target", "adr");
12545
12826
  function brokenWith(model, node) {
12546
12827
  const affected = affectedBy(model, node);
@@ -12568,16 +12849,53 @@ function metricRule(outcome, message) {
12568
12849
  return (model) => {
12569
12850
  if (!model.measurements) return [];
12570
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
+ }
12571
12865
  const metricLines = new Set(conditionsOf(node).filter((c) => c.kind === "metric").map((c) => c.raw));
12572
12866
  return conditionResults(node, model).filter((r) => r.outcome === outcome && metricLines.has(r.condition)).map((r) => {
12573
- const m = r.measurement;
12574
- const seen = m ? ` (${m.value}${m.unit ? ` ${m.unit}` : ""} from ${m.source}, ${formatAge((model.now ?? Date.now()) - Date.parse(m.at))} ago)` : "";
12575
12867
  const related = outcome === "failed" ? affectedBy(model, node).map((n) => n.id) : [];
12576
- return { nodeId: node.id, message: message(node, r.condition, seen, r.detail), ...related.length ? { relatedIds: related } : {} };
12868
+ return { nodeId: node.id, message: message(node, r.condition, seen(r), r.detail), ...related.length ? { relatedIds: related } : {} };
12577
12869
  });
12578
12870
  });
12579
12871
  };
12580
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
+ }
12581
12899
  function invalidChecks(model) {
12582
12900
  return Object.values(model.nodes).filter((n) => TESTED_TYPES.includes(n.type)).flatMap((node) => {
12583
12901
  const what = `${TYPE_NAME[node.type]} ${quote(node)}`;
@@ -12724,10 +13042,27 @@ var CHECK_RULES = [
12724
13042
  },
12725
13043
  {
12726
13044
  id: "scenario-without-metrics",
12727
- description: "Every scenario states what checks it (property `metrics`, one condition per line: `test(<file> \u203A <title>) passed` or `<metric>{<labels>} <op> <number> [unit]`).",
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.",
13046
+ severity: "warning",
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>".` }))
13056
+ },
13057
+ {
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.",
12728
13060
  severity: "warning",
12729
13061
  dimension: "traceability",
12730
- run: (model) => nodesOf(model, "scenario").filter((n) => !conditionsOf(n).length).map((n) => ({ nodeId: n.id, message: `Scenario ${quote(n)} names no check.` }))
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
+ })
12731
13066
  },
12732
13067
  {
12733
13068
  id: "fitness-fn-without-metrics",
@@ -12751,10 +13086,47 @@ var CHECK_RULES = [
12751
13086
  },
12752
13087
  {
12753
13088
  id: "fitness-fn-measure-invalid",
12754
- description: `Every line of a fitness function's \`measure\` names a sensor of radical sense (${SENSOR_NAMES.join(", ")}).`,
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.`,
12755
13090
  severity: "error",
12756
13091
  dimension: "completeness",
12757
- run: (model) => nodesOf(model, "fitness-fn").flatMap((n) => parseMeasure(n.measure).filter((line) => !isSensorName(line.sensor)).map((line) => ({ nodeId: n.id, message: `Fitness function ${quote(n)}: measure "${line.raw}" names no sensor; radical sense has ${SENSOR_NAMES.join(", ")}.` })))
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": [...] }).` })))
12758
13130
  },
12759
13131
  {
12760
13132
  id: "metric-invalid",
@@ -12961,8 +13333,8 @@ var METRIC_IDS = new Set(CHECK_METRICS.map((m) => m.id));
12961
13333
 
12962
13334
  // ../../packages/common/src/check/files.ts
12963
13335
  init_define_RADICAL_BUILD();
12964
- var TEST_RESULTS_FILE = `${SELECTION_DIR}/test-results.json`;
12965
- var MEASUREMENTS_FILE = `${SELECTION_DIR}/measurements.json`;
13336
+ var TEST_RESULTS_FILE = `${STATE_DIR}/test-results.json`;
13337
+ var MEASUREMENTS_FILE = `${STATE_DIR}/measurements.json`;
12966
13338
 
12967
13339
  // ../../packages/common/src/check/reviews.ts
12968
13340
  init_define_RADICAL_BUILD();
@@ -12988,11 +13360,119 @@ var ALL_RULES = [...FOLDER_RULES, ...CHECK_RULES, GOAL_RULE];
12988
13360
  var RULE_IDS = new Set(ALL_RULES.map((r) => r.id));
12989
13361
  var DEFAULT_SEVERITY = new Map(ALL_RULES.map((r) => [r.id, r.severity]));
12990
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
+
12991
13471
  // ../../packages/node-files/src/selectionFile.ts
12992
- async function selectionDir(root2, create) {
12993
- const dir = join(resolve(root2), SELECTION_DIR);
13472
+ async function selectionDir(root2, create, name = STATE_DIR) {
13473
+ const dir = join2(resolve2(root2), name);
12994
13474
  try {
12995
- 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}`);
12996
13476
  } catch (error) {
12997
13477
  if (error.code !== "ENOENT") throw error;
12998
13478
  if (!create) return null;
@@ -13004,7 +13484,7 @@ async function selectionDir(root2, create) {
13004
13484
  }
13005
13485
  async function editorStateDir(root2) {
13006
13486
  const dir = await selectionDir(root2, true);
13007
- const ignore = join(resolve(root2), SELECTION_GITIGNORE);
13487
+ const ignore = join2(resolve2(root2), SELECTION_GITIGNORE);
13008
13488
  try {
13009
13489
  await lstat(ignore);
13010
13490
  } catch {
@@ -13014,17 +13494,18 @@ async function editorStateDir(root2) {
13014
13494
  }
13015
13495
  async function writeEditorStateFile(root2, path, content) {
13016
13496
  await editorStateDir(root2);
13017
- const file = join(resolve(root2), path);
13497
+ const file = join2(resolve2(root2), path);
13018
13498
  if (await lstat(file).then((s) => s.isSymbolicLink(), () => false)) throw new Error(`symlink in model path: ${path}`);
13019
13499
  await writeFile(file, content, "utf-8");
13020
13500
  }
13021
13501
  async function readEditorStateFile(root2, path) {
13022
- if (!await selectionDir(root2, false)) return null;
13023
- try {
13024
- return await readFile(join(resolve(root2), path), "utf-8");
13025
- } catch {
13026
- 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;
13027
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);
13028
13509
  }
13029
13510
  async function writeForgeRunFile(root2, content) {
13030
13511
  await writeEditorStateFile(root2, FORGE_RUN_FILE, content);
@@ -13050,13 +13531,13 @@ function staleLock(text2, age) {
13050
13531
  var sleep = (ms) => new Promise((done) => setTimeout(done, ms));
13051
13532
  var READ_ONLY = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EROFS"]);
13052
13533
  async function takeWriteTurn(base, forRead = false) {
13053
- 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 () => {
13054
13535
  };
13055
13536
  try {
13056
13537
  return await takeTurn(base, forRead);
13057
13538
  } catch (error) {
13058
13539
  if (!forRead || !READ_ONLY.has(error.code ?? "")) throw error;
13059
- await waitForWriter(join2(base, SELECTION_DIR, WRITE_LOCK));
13540
+ await waitForWriter(join3(base, STATE_DIR, WRITE_LOCK));
13060
13541
  return async () => {
13061
13542
  };
13062
13543
  }
@@ -13064,15 +13545,15 @@ async function takeWriteTurn(base, forRead = false) {
13064
13545
  async function waitForWriter(file) {
13065
13546
  const deadline = Date.now() + LOCK_WAIT_MS;
13066
13547
  for (; ; ) {
13067
- const held = await readFile2(file, "utf-8").catch(() => null);
13068
- 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);
13069
13550
  if (held === null || staleLock(held, age) || Date.now() > deadline) return;
13070
13551
  await sleep(10 + Math.random() * 30);
13071
13552
  }
13072
13553
  }
13073
13554
  async function takeTurn(base, forRead = false) {
13074
- const file = join2(await editorStateDir(base), WRITE_LOCK);
13075
- 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}`);
13076
13557
  const mine = `${process.pid} ${Date.now()} ${randomUUID()}
13077
13558
  `;
13078
13559
  const deadline = Date.now() + LOCK_WAIT_MS;
@@ -13080,35 +13561,35 @@ async function takeTurn(base, forRead = false) {
13080
13561
  try {
13081
13562
  await writeFile2(file, mine, { encoding: "utf-8", flag: "wx" });
13082
13563
  return async () => {
13083
- 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 });
13084
13565
  };
13085
13566
  } catch (error) {
13086
13567
  if (error.code !== "EEXIST") throw error;
13087
13568
  }
13088
- const held = await readFile2(file, "utf-8").catch(() => null);
13089
- 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);
13090
13571
  if (held !== null && staleLock(held, age)) {
13091
- 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 });
13092
13573
  continue;
13093
13574
  }
13094
13575
  if (Date.now() > deadline) {
13095
- 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.`);
13096
13577
  }
13097
13578
  await sleep(10 + Math.random() * 30);
13098
13579
  }
13099
13580
  }
13100
13581
  function diskFolderStorage(root2) {
13101
- const base = resolve2(root2);
13582
+ const base = resolve3(root2);
13102
13583
  const stampOf = (s) => `${s.mtimeMs}:${s.size}`;
13103
13584
  async function inside(rel) {
13104
- const abs = resolve2(base, rel);
13585
+ const abs = resolve3(base, rel);
13105
13586
  if (!abs.startsWith(base + sep)) throw new Error(`path outside the model folder: ${rel}`);
13106
13587
  if (!isMdFolderModelPath(rel) || rel.includes("\\") || rel.split("/").some((part) => !part || part === "." || part === "..")) {
13107
13588
  throw new Error(`not a model file: ${rel}`);
13108
13589
  }
13109
13590
  let current = base;
13110
13591
  for (const part of rel.split("/")) {
13111
- current = resolve2(current, part);
13592
+ current = resolve3(current, part);
13112
13593
  try {
13113
13594
  if ((await lstat2(current)).isSymbolicLink()) throw new Error(`symlink in model path: ${rel}`);
13114
13595
  } catch (error) {
@@ -13122,15 +13603,15 @@ function diskFolderStorage(root2) {
13122
13603
  async writeCache(name, content) {
13123
13604
  if (!MODEL_CACHE_NAMES.has(name)) throw new Error(`not a cache file: ${name}`);
13124
13605
  await editorStateDir(base);
13125
- const dir = join2(base, MODEL_CACHE_DIR);
13606
+ const dir = join3(base, MODEL_CACHE_DIR);
13126
13607
  if (await lstat2(dir).then((s) => s.isSymbolicLink(), () => false)) throw new Error(`symlink in model path: ${MODEL_CACHE_DIR}`);
13127
13608
  await mkdir2(dir, { recursive: true });
13128
- for (const name2 of await readdir(dir)) {
13609
+ for (const name2 of await readdir2(dir)) {
13129
13610
  if (!name2.endsWith(".part")) continue;
13130
- const left = join2(dir, name2);
13131
- if (await stat(left).then((st) => Date.now() - st.mtimeMs > 6e4, () => false)) await rm(left, { force: true });
13611
+ const left = join3(dir, name2);
13612
+ if (await stat2(left).then((st) => Date.now() - st.mtimeMs > 6e4, () => false)) await rm(left, { force: true });
13132
13613
  }
13133
- const file = join2(dir, name);
13614
+ const file = join3(dir, name);
13134
13615
  const part = `${file}.${randomUUID()}.part`;
13135
13616
  await writeFile2(part, content, "utf-8");
13136
13617
  await rename(part, file);
@@ -13141,7 +13622,7 @@ function diskFolderStorage(root2) {
13141
13622
  files.push(rel);
13142
13623
  };
13143
13624
  const walk = async (rel) => {
13144
- 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 });
13145
13626
  for (const entry of entries) {
13146
13627
  if (entry.name.startsWith(".")) continue;
13147
13628
  const child = `${rel}/${entry.name}`;
@@ -13150,7 +13631,7 @@ function diskFolderStorage(root2) {
13150
13631
  else if (entry.isSymbolicLink()) throw new Error(`symlink in model path: ${child}`);
13151
13632
  }
13152
13633
  };
13153
- const top = await readdir(base, { withFileTypes: true });
13634
+ const top = await readdir2(base, { withFileTypes: true });
13154
13635
  for (const entry of top) {
13155
13636
  if (entry.isFile() && isMdFolderModelPath(entry.name)) add(entry.name);
13156
13637
  else if (entry.isDirectory() && entry.name === "nodes") await walk("nodes");
@@ -13160,7 +13641,7 @@ function diskFolderStorage(root2) {
13160
13641
  }
13161
13642
  const found = await readEach(files, async (rel) => {
13162
13643
  try {
13163
- return stampOf(await stat(await inside(rel)));
13644
+ return stampOf(await stat2(await inside(rel)));
13164
13645
  } catch (error) {
13165
13646
  if (error.code !== "ENOENT") throw error;
13166
13647
  }
@@ -13172,13 +13653,13 @@ function diskFolderStorage(root2) {
13172
13653
  return stamps;
13173
13654
  },
13174
13655
  // Decoded as the browser decodes a file: without a byte-order mark.
13175
- read: async (rel) => stripBom(await readFile2(await inside(rel), "utf-8")),
13656
+ read: async (rel) => stripBom(await readFile3(await inside(rel), "utf-8")),
13176
13657
  async write(rel, content) {
13177
13658
  const abs = await inside(rel);
13178
- await mkdir2(dirname2(abs), { recursive: true });
13659
+ await mkdir2(dirname4(abs), { recursive: true });
13179
13660
  await inside(rel);
13180
13661
  await writeFile2(abs, content, "utf-8");
13181
- return stampOf(await stat(abs));
13662
+ return stampOf(await stat2(abs));
13182
13663
  },
13183
13664
  remove: async (rel) => rm(await inside(rel), { force: true }),
13184
13665
  lock: (forRead) => takeWriteTurn(base, forRead)
@@ -13188,8 +13669,8 @@ function diskFolderStorage(root2) {
13188
13669
  // ../../packages/node-files/src/gitModel.ts
13189
13670
  init_define_RADICAL_BUILD();
13190
13671
  import { execFile, spawn } from "child_process";
13191
- import { readFile as readFile3, stat as stat2 } from "fs/promises";
13192
- import { join as join3 } from "path";
13672
+ import { readFile as readFile4, stat as stat3 } from "fs/promises";
13673
+ import { join as join4 } from "path";
13193
13674
  import { promisify } from "util";
13194
13675
 
13195
13676
  // ../../packages/common/src/modelChanges.ts
@@ -13278,6 +13759,7 @@ function formatModelChanges(report, before, after) {
13278
13759
  field(" ", `${c.field} now`, value(c.after));
13279
13760
  } else lines.push(` ${c.field}: ${value(c.before)} \u2192 ${value(c.after)}`);
13280
13761
  }
13762
+ if (change.tests) lines.push(` tests (.radical/radical.json): ${change.tests.length ? "" : "none bound"}`, ...change.tests.map((t) => ` ${t}`));
13281
13763
  if (change.related.length) {
13282
13764
  lines.push(" relations:");
13283
13765
  for (const r of change.related.slice(0, MAX_RELATED)) {
@@ -13308,7 +13790,7 @@ function formatModelChanges(report, before, after) {
13308
13790
 
13309
13791
  // ../../packages/common/src/formats/modelBase.ts
13310
13792
  init_define_RADICAL_BUILD();
13311
- var MODEL_BASE_FILE = `${SELECTION_DIR}/base.json`;
13793
+ var MODEL_BASE_FILE = `${STATE_DIR}/base.json`;
13312
13794
  var BASE_OLD_MS = 24 * 60 * 60 * 1e3;
13313
13795
  function serializeModelBase(base, now4 = /* @__PURE__ */ new Date()) {
13314
13796
  const out = {
@@ -13410,7 +13892,7 @@ async function readModelAtCommit(folder, commit, from) {
13410
13892
  return Object.fromEntries(blobs.map((blob, i) => [blob.path, contents[i]]));
13411
13893
  }
13412
13894
  function catFiles(cwd, shas) {
13413
- return new Promise((resolve5, reject) => {
13895
+ return new Promise((resolve6, reject) => {
13414
13896
  const child = spawn("git", ["cat-file", "--batch"], { cwd, windowsHide: true });
13415
13897
  const chunks = [];
13416
13898
  let stderr = "";
@@ -13438,7 +13920,7 @@ function catFiles(cwd, shas) {
13438
13920
  contents.push(stripBom(out.subarray(start, start + Number(size)).toString("utf8")));
13439
13921
  at = start + Number(size) + 1;
13440
13922
  }
13441
- resolve5(contents);
13923
+ resolve6(contents);
13442
13924
  });
13443
13925
  child.stdin.end(shas.join("\n") + "\n");
13444
13926
  });
@@ -13452,12 +13934,12 @@ async function renamedFrom(folder, commit) {
13452
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);
13453
13935
  }
13454
13936
  const top = await git(folder, ["rev-parse", "--show-toplevel"]);
13455
- const now4 = await readFile3(join3(folder, "radical.md"), "utf8").catch(() => null);
13937
+ const now4 = await readFile4(join4(folder, "radical.md"), "utf8").catch(() => null);
13456
13938
  if (now4 === null) return null;
13457
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);
13458
13940
  const gone = [];
13459
13941
  for (const path of then) {
13460
- if (await stat2(join3(top, path)).then(() => true, () => false)) continue;
13942
+ if (await stat3(join4(top, path)).then(() => true, () => false)) continue;
13461
13943
  if (stripBom(await gitOk(folder, ["show", `${commit}:${path}`]) ?? "") === stripBom(now4).trim()) gone.push(path.slice(0, -"/radical.md".length));
13462
13944
  }
13463
13945
  return gone.length === 1 ? gone[0] : null;
@@ -13477,6 +13959,12 @@ async function modelChangesSince(folder, current, since, options = {}) {
13477
13959
  const before = { nodes: byId2(old.nodes), relations: byId2(old.relations) };
13478
13960
  const after = { nodes: byId2(current.nodes), relations: byId2(current.relations) };
13479
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
+ }
13480
13968
  const short = base.commit.slice(0, 7);
13481
13969
  const where = base.commit.startsWith(base.described) ? short : `${base.described} (${short})`;
13482
13970
  const count = (group, noun) => `${noun}: ${group.added.length} added, ${group.changed.length} changed, ${group.removed.length} removed`;
@@ -13491,7 +13979,7 @@ async function modelChangesSince(folder, current, since, options = {}) {
13491
13979
 
13492
13980
  // ../../packages/common/src/formats/agentActivity.ts
13493
13981
  init_define_RADICAL_BUILD();
13494
- var AGENT_ACTIVITY_FILE = `${SELECTION_DIR}/agent-activity.json`;
13982
+ var AGENT_ACTIVITY_FILE = `${STATE_DIR}/agent-activity.json`;
13495
13983
  var AGENT_ACTIVE_MS = 15e3;
13496
13984
  function serializeAgentActivity(client, now4 = Date.now(), radical) {
13497
13985
  const out = { version: 1, ...client ? { client } : {}, ...radical ? { radical } : {}, until: now4 + AGENT_ACTIVE_MS };
@@ -20386,7 +20874,7 @@ function yieldToUI() {
20386
20874
  if (_sched != null && typeof _sched.yield === "function") {
20387
20875
  return _sched.yield();
20388
20876
  }
20389
- return new Promise((resolve5) => setTimeout(resolve5, 0));
20877
+ return new Promise((resolve6) => setTimeout(resolve6, 0));
20390
20878
  }
20391
20879
  function projectPositions(nodes, positions) {
20392
20880
  const out = {};
@@ -20465,7 +20953,7 @@ function unchangedResult(nodes, relations, style = "curved") {
20465
20953
  }
20466
20954
  async function runSmartLayoutELKPhase(inputNodes, inputRelations, metamodel, onProgress) {
20467
20955
  const { nodes, relations } = projectToVisibleGraph(inputNodes, inputRelations);
20468
- const { applyElkLayout } = await import("./elkLayout-VYJDCCIT.js");
20956
+ const { applyElkLayout } = await import("./elkLayout-XPMSDPVA.js");
20469
20957
  const depth2 = maxContainmentDepth(metamodel);
20470
20958
  const mmDirection = depth2 >= 2 ? "RIGHT" : "DOWN";
20471
20959
  const engines = [
@@ -23096,7 +23584,7 @@ function same2(a, b) {
23096
23584
  init_define_RADICAL_BUILD();
23097
23585
  import { mkdir as mkdir3, writeFile as writeFile3 } from "fs/promises";
23098
23586
  import { existsSync } from "fs";
23099
- 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";
23100
23588
  import { fileURLToPath as fileURLToPath2 } from "url";
23101
23589
 
23102
23590
  // ../../packages/common/src/ai/forge/index.ts
@@ -23686,9 +24174,9 @@ var clone2 = (value) => JSON.parse(JSON.stringify(value));
23686
24174
  function snapshotOf(model) {
23687
24175
  return { nodes: clone2(model.getNodes()), relations: clone2(model.getRelations()) };
23688
24176
  }
23689
- var LAYOUT_FIELDS = /* @__PURE__ */ new Set(["x", "y", "width", "height", "collapsed"]);
24177
+ var LAYOUT_FIELDS2 = /* @__PURE__ */ new Set(["x", "y", "width", "height", "collapsed"]);
23690
24178
  function changedFields2(before, after) {
23691
- 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));
23692
24180
  const value = (o, k) => o[k];
23693
24181
  return keys.filter((k) => !sameModelValue(value(before, k), value(after, k))).sort();
23694
24182
  }
@@ -24130,14 +24618,14 @@ function summarize(doc, file = conceptFile(doc.hub)) {
24130
24618
  // ../../packages/hub-catalogue/src/catalogue.ts
24131
24619
  init_define_RADICAL_BUILD();
24132
24620
  import { readdirSync, readFileSync, statSync } from "fs";
24133
- import { join as join4, relative } from "path";
24621
+ import { join as join5, relative } from "path";
24134
24622
  import { fileURLToPath } from "url";
24135
24623
  var CATALOGUE_DIR = fileURLToPath(new URL("../catalogue", import.meta.url));
24136
24624
  function readCatalogue(dir = CATALOGUE_DIR) {
24137
24625
  const out = [];
24138
24626
  const walk = (d) => {
24139
24627
  for (const name of readdirSync(d).sort()) {
24140
- const p = join4(d, name);
24628
+ const p = join5(d, name);
24141
24629
  if (statSync(p).isDirectory()) walk(p);
24142
24630
  else if (name.endsWith(".radical")) {
24143
24631
  out.push({ file: relative(dir, p).split("\\").join("/"), doc: JSON.parse(readFileSync(p, "utf8")) });
@@ -24361,7 +24849,7 @@ var FORGE_TOOL_DEFS = [
24361
24849
  var FORGE_TOOLS = new Set(FORGE_TOOL_DEFS.map((tool) => tool.name));
24362
24850
  var FORGE_READ_ONLY = /* @__PURE__ */ new Set(["forge_clarify"]);
24363
24851
  function catalogueDir() {
24364
- const bundled = join5(dirname3(fileURLToPath2(import.meta.url)), "hub-catalogue");
24852
+ const bundled = join6(dirname5(fileURLToPath2(import.meta.url)), "hub-catalogue");
24365
24853
  return existsSync(bundled) ? bundled : CATALOGUE_DIR;
24366
24854
  }
24367
24855
  var MAX_CONTEXT_CHARS = 6e4;
@@ -25013,9 +25501,9 @@ Then call forge_wireframe again with mockupId "${id}" and the svg.`, { readOnly:
25013
25501
  if (!files.length) {
25014
25502
  lines.push("No Gherkin scenarios in the model, so there are no .feature files.");
25015
25503
  } else if (typeof args.gherkinDir === "string" && args.gherkinDir) {
25016
- const dir = resolve3(args.gherkinDir);
25504
+ const dir = resolve4(args.gherkinDir);
25017
25505
  await mkdir3(dir, { recursive: true });
25018
- 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);
25019
25507
  lines.push(`Wrote ${files.length} .feature files to ${dir}:`, ...files.map((f) => `- ${f.filename}`));
25020
25508
  } else {
25021
25509
  lines.push(`${files.length} .feature files (pass gherkinDir to write them):`);
@@ -25058,7 +25546,7 @@ Then call forge_wireframe again with mockupId "${id}" and the svg.`, { readOnly:
25058
25546
 
25059
25547
  // src/folderModel.ts
25060
25548
  var EXCLUDED_TOOLS = /* @__PURE__ */ new Set(["set_active_view", "focus_node", "reset_diagram"]);
25061
- 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"]);
25062
25550
  var SERVER_TOOL_DEFS = [
25063
25551
  {
25064
25552
  name: "get_model_summary",
@@ -25077,7 +25565,7 @@ var SERVER_TOOL_DEFS = [
25077
25565
  },
25078
25566
  {
25079
25567
  name: "get_changes",
25080
- 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.",
25081
25569
  inputSchema: {
25082
25570
  type: "object",
25083
25571
  properties: {
@@ -25085,8 +25573,55 @@ var SERVER_TOOL_DEFS = [
25085
25573
  },
25086
25574
  additionalProperties: false
25087
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
+ }
25088
25622
  }
25089
25623
  ];
25624
+ var BUILT_TYPES = /* @__PURE__ */ new Set(["system", "container", "component", "database", "webapp", "queue"]);
25090
25625
  var READ_ONLY_TOOLS = /* @__PURE__ */ new Set([...READ_ONLY2, ...FORGE_READ_ONLY]);
25091
25626
  var buildTools = (metamodel) => [
25092
25627
  ...SERVER_TOOL_DEFS,
@@ -25132,9 +25667,9 @@ function checkData(data) {
25132
25667
  }
25133
25668
  async function startIfEmpty(path, preset2) {
25134
25669
  await mkdir4(path, { recursive: true });
25135
- if (!(await readdir2(path)).every((name) => name.startsWith("."))) return;
25670
+ if (!(await readdir3(path)).every((name) => name.startsWith("."))) return;
25136
25671
  const session = new MdFolderSession(diskFolderStorage(path));
25137
- const created = await session.write(serializeToMdFolder({ nodes: [], relations: [], metamodel: PRESETS[preset2]() }, basename(path)));
25672
+ const created = await session.write(serializeToMdFolder({ nodes: [], relations: [], metamodel: PRESETS[preset2]() }, basename2(path)));
25138
25673
  if (!created.ok) throw new Error(`Could not start a model in ${path}: it changed while being written`);
25139
25674
  }
25140
25675
  var byId3 = (items) => Object.fromEntries(items.map((item) => [item.id, item]));
@@ -25286,11 +25821,11 @@ var FolderModel = class _FolderModel {
25286
25821
  * Save as folder writes one. */
25287
25822
  static async open(folder, options = {}) {
25288
25823
  if (!folder) throw new Error("--folder is required");
25289
- const path = resolve4(folder);
25824
+ const path = resolve5(folder);
25290
25825
  const preset2 = options.metamodel ?? "radical";
25291
25826
  await startIfEmpty(path, preset2);
25292
25827
  const canonical2 = await realpath(path);
25293
- if (!(await stat3(canonical2)).isDirectory()) throw new Error(`Not a directory: ${folder}`);
25828
+ if (!(await stat4(canonical2)).isDirectory()) throw new Error(`Not a directory: ${folder}`);
25294
25829
  const opening = new MdFolderSession(diskFolderStorage(canonical2));
25295
25830
  const files = await opening.readAll();
25296
25831
  await opening.cacheWritten();
@@ -25316,7 +25851,7 @@ var FolderModel = class _FolderModel {
25316
25851
  try {
25317
25852
  if (!mayReplaceWithForgeBase(await readEditorStateFile(this.folder, MODEL_BASE_FILE))) return "";
25318
25853
  await writeEditorStateFile(this.folder, MODEL_BASE_FILE, content);
25319
- 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.";
25320
25855
  } catch {
25321
25856
  return "";
25322
25857
  }
@@ -25347,7 +25882,7 @@ var FolderModel = class _FolderModel {
25347
25882
  const before = await session.readAll();
25348
25883
  await session.cacheWritten();
25349
25884
  checkFiles(before);
25350
- const data = deserializeFromMdFolder(before).data;
25885
+ const data = withOtherModels(deserializeFromMdFolder(before).data, parseFederationFile(await readEditorStateFile(this.folder, FEDERATION_FILE)));
25351
25886
  checkData(data);
25352
25887
  if (data.views) {
25353
25888
  const nodes = byId3(data.nodes);
@@ -25369,6 +25904,118 @@ var FolderModel = class _FolderModel {
25369
25904
  }
25370
25905
  /** The canvas selection Studio wrote into the folder, resolved against
25371
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
+ }
25372
26019
  async selection(facade) {
25373
26020
  const text2 = await readEditorStateFile(this.folder, SELECTION_FILE);
25374
26021
  if (text2 === null) {
@@ -25468,10 +26115,12 @@ ${buildMetamodelMessage(metamodel2)}` };
25468
26115
  return { ok: true, text: [text2, ...this.openConcerns(data, mm)].join("\n") };
25469
26116
  }
25470
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);
25471
26120
  if (name === "get_changes") {
25472
26121
  const { since } = input ?? {};
25473
26122
  if (since !== void 0 && typeof since !== "string") return { ok: false, text: "get_changes: since must be a git branch, tag or commit" };
25474
- 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 };
25475
26124
  }
25476
26125
  priorTempIds = new Map(this.tempIds);
25477
26126
  const ctx = {
@@ -25494,7 +26143,7 @@ ${buildMetamodelMessage(metamodel2)}` };
25494
26143
  this.restoreTempIds(priorTempIds);
25495
26144
  return { ok: false, text: facade.lastError ?? result.resultText };
25496
26145
  }
25497
- 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;
25498
26147
  if (READ_ONLY2.has(name) || result.readOnly) {
25499
26148
  result.commit?.();
25500
26149
  if (FORGE_TOOLS.has(name)) await this.writeForgeStatus();
@@ -25653,9 +26302,11 @@ function positionsOf2(nodes) {
25653
26302
  }
25654
26303
 
25655
26304
  // src/index.ts
25656
- 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("|")}]
25657
26306
  --folder the Markdown model folder, absolute or relative to the working directory;
25658
- 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)
25659
26310
  --metamodel the metamodel of a new model (default: radical)
25660
26311
  --version print the version`;
25661
26312
  function parseArgs(args) {
@@ -25667,7 +26318,7 @@ function parseArgs(args) {
25667
26318
  }
25668
26319
  const folder = values.get("--folder");
25669
26320
  const metamodel = values.get("--metamodel");
25670
- if (!folder || metamodel !== void 0 && !(metamodel in PRESETS)) throw new Error(USAGE);
26321
+ if (metamodel !== void 0 && !(metamodel in PRESETS)) throw new Error(USAGE);
25671
26322
  return { folder, metamodel };
25672
26323
  }
25673
26324
  var INSTRUCTIONS = [
@@ -25728,7 +26379,10 @@ async function main() {
25728
26379
  `);
25729
26380
  return;
25730
26381
  }
25731
- 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}`);
25732
26386
  const model = await FolderModel.open(folder, { metamodel });
25733
26387
  const server = new McpServer({ name: "radical-folder", version: displayVersion() }, { instructions: INSTRUCTIONS });
25734
26388
  const registered = /* @__PURE__ */ new Map();