glassbrain 0.2.0-alpha.1 → 0.2.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,9 +10,9 @@ import { fileURLToPath } from "node:url";
10
10
 
11
11
  // src/model.ts
12
12
  function buildModel(nodes, edges, errors = []) {
13
- const index = /* @__PURE__ */ new Map();
14
- for (const n of nodes) if (!index.has(n.id)) index.set(n.id, n);
15
- return { nodes, edges, errors, index };
13
+ const index2 = /* @__PURE__ */ new Map();
14
+ for (const n of nodes) if (!index2.has(n.id)) index2.set(n.id, n);
15
+ return { nodes, edges, errors, index: index2 };
16
16
  }
17
17
  function mergeSlices(slices) {
18
18
  const byId = /* @__PURE__ */ new Map();
@@ -110,6 +110,7 @@ function parsePhysical(origin, text) {
110
110
  label: String(n.label ?? n.name ?? n.id),
111
111
  kind: typeof n.kind === "string" ? n.kind : void 0,
112
112
  parent: ref(n.parent),
113
+ order: typeof n.order === "number" && Number.isFinite(n.order) ? n.order : void 0,
113
114
  layer: typeof n.layer === "string" ? n.layer : void 0,
114
115
  // Marks carried by the data itself (e.g. a placeholder "with no content yet"). They are data, not derived: when the profile's
115
116
  // `placeholderFlags` recognizes one, it is drawn as skeleton.
@@ -130,7 +131,8 @@ function parsePhysical(origin, text) {
130
131
  function toPhysical(model) {
131
132
  const clean2 = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0 && v !== ""));
132
133
  return {
133
- nodes: model.nodes.map((n) => clean2({ ...n.data, id: n.id, label: n.label, kind: n.kind, parent: n.parent, layer: n.layer })),
134
+ // `layer` is derived, never written: a file that gains it would freeze a view decision into the data.
135
+ nodes: model.nodes.map((n) => clean2({ ...n.data, id: n.id, label: n.label, kind: n.kind, parent: n.parent, order: n.order })),
134
136
  edges: model.edges.map((e) => clean2({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }))
135
137
  };
136
138
  }
@@ -241,7 +243,7 @@ var clean = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !==
241
243
  // adapters/graphify.ts
242
244
  var STRUCT = /* @__PURE__ */ new Set(["contains", "method"]);
243
245
  var NOTE = "rationale_for";
244
- var looksLike = (d) => isObj(d) && Array.isArray(d.nodes) && Array.isArray(d.links ?? d.edges) && (d.nodes.length === 0 || d.nodes.some((n) => isObj(n) && ("file_type" in n || "source_file" in n))) && !("layers" in d && "project" in d);
246
+ var looksLike = (d) => isObj(d) && Array.isArray(d.nodes) && Array.isArray(d.links ?? d.edges) && (Array.isArray(d.links) || d.nodes.some((n) => isObj(n) && "file_type" in n)) && !("layers" in d && "project" in d);
245
247
  var base = (p) => p.split("/").pop() ?? p;
246
248
  function convertGraphify(d, name) {
247
249
  const raw = d.nodes.filter(isObj);
@@ -980,12 +982,63 @@ function diffModels(before, after, opts = {}) {
980
982
  };
981
983
  }
982
984
 
985
+ // src/layers.ts
986
+ var MAX_DERIVED_LAYERS = 8;
987
+ var EMPTY = { layers: [], layerOf: /* @__PURE__ */ new Map() };
988
+ function orderedChildren(children, id) {
989
+ const kids = children.get(id) ?? [];
990
+ if (kids.length < 2) return null;
991
+ const withOrder = kids.filter((n) => typeof n.order === "number" && Number.isFinite(n.order));
992
+ if (withOrder.length !== kids.length) return null;
993
+ const seen = /* @__PURE__ */ new Set();
994
+ for (const k of withOrder) {
995
+ if (seen.has(k.order)) return null;
996
+ seen.add(k.order);
997
+ }
998
+ return [...kids].sort((a2, b) => a2.order - b.order);
999
+ }
1000
+ function childrenMap(model) {
1001
+ const out = /* @__PURE__ */ new Map();
1002
+ for (const n of model.nodes) {
1003
+ if (!n.parent || !model.index.has(n.parent)) continue;
1004
+ const arr = out.get(n.parent);
1005
+ arr ? arr.push(n) : out.set(n.parent, [n]);
1006
+ }
1007
+ return out;
1008
+ }
1009
+ function deriveLayers(model, colors = []) {
1010
+ if (!model.nodes.length) return EMPTY;
1011
+ const children = childrenMap(model);
1012
+ const roots = model.nodes.filter((n) => !n.parent || !model.index.has(n.parent));
1013
+ if (roots.length !== 1) return EMPTY;
1014
+ const anchor = roots[0];
1015
+ const ordered = orderedChildren(children, anchor.id);
1016
+ if (!ordered || ordered.length > MAX_DERIVED_LAYERS) return EMPTY;
1017
+ const layers = ordered.map((n, i) => ({
1018
+ id: n.id,
1019
+ label: n.label || n.id,
1020
+ z: i,
1021
+ ...colors[i] ? { color: colors[i] } : {}
1022
+ }));
1023
+ const layerOf = /* @__PURE__ */ new Map();
1024
+ for (const [i, layer] of ordered.entries()) {
1025
+ const stack = [layer.id];
1026
+ while (stack.length) {
1027
+ const id = stack.pop();
1028
+ layerOf.set(id, layers[i].id);
1029
+ for (const k of children.get(id) ?? []) stack.push(k.id);
1030
+ }
1031
+ }
1032
+ layerOf.set(anchor.id, layers[0].id);
1033
+ return { layers, layerOf, anchor: anchor.id };
1034
+ }
1035
+
983
1036
  // schema/graph.schema.json
984
1037
  var graph_schema_default = {
985
1038
  $schema: "https://json-schema.org/draft/2020-12/schema",
986
1039
  $id: "https://unpkg.com/glassbrain/schema/graph.schema.json",
987
1040
  title: "glassbrain graph",
988
- description: "One file of a glassbrain knowledge graph. A graph is nodes plus edges; structure comes from `parent` (containment), not from edges. Several files in one folder are merged into one graph (same id = same node). Unknown fields are kept and shown in the detail panel.",
1041
+ description: "One file of a glassbrain knowledge graph. A graph is nodes plus edges; structure comes from `parent` (containment), not from edges. Every node carries `parent`: a node id, or null for the root. Several files in one folder are merged into one graph (same id = same node). Unknown fields are kept and shown in the detail panel.",
989
1042
  type: "object",
990
1043
  anyOf: [{ required: ["nodes"] }, { required: ["edges"] }],
991
1044
  properties: {
@@ -1003,14 +1056,14 @@ var graph_schema_default = {
1003
1056
  $defs: {
1004
1057
  node: {
1005
1058
  type: "object",
1006
- required: ["id"],
1059
+ required: ["id", "parent"],
1007
1060
  properties: {
1008
1061
  id: { type: ["string", "number"], description: "Stable identity. Keep it the same across versions: that is how a diff knows it is the same thing." },
1009
1062
  label: { type: "string", description: "Display name. Falls back to `name`, then `id`." },
1010
1063
  name: { type: "string", description: "Alias of `label`." },
1011
1064
  kind: { type: "string", description: "What sort of thing this is. Colors come from the profile's `nodePalette[kind]`; kinds not in the palette are drawn as skeleton." },
1012
- parent: { type: "string", description: "Id of the node this one sits inside. This is the only source of structure: the layout is built from it." },
1013
- layer: { type: "string", description: "Layer id (for the 2.5D plane view). Defaults to the profile's first layer." },
1065
+ parent: { type: ["string", "null"], description: "Id of the node this one sits inside; null for the root. Required: the only source of structure, and the layout, the layers and the outline are all built from it." },
1066
+ order: { type: "number", exclusiveMinimum: 0, description: "Position among its siblings (1, 2, 3\u2026; 3.5 inserts between 3 and 4). Either every child of a parent has one or none does, and no two siblings share one." },
1014
1067
  flags: { type: "array", items: { type: "string" }, description: "Boolean markers; each becomes a CSS-like class. A flag listed in the profile's `placeholderFlags` draws the node as a placeholder." },
1015
1068
  description: { type: "string", description: "Markdown shown in the detail panel. `[text](node:<id>)` links jump to another node." }
1016
1069
  },
@@ -1041,57 +1094,129 @@ var profile_schema_default = {
1041
1094
  $schema: "https://json-schema.org/draft/2020-12/schema",
1042
1095
  $id: "https://unpkg.com/glassbrain/schema/profile.schema.json",
1043
1096
  title: "glassbrain profile (_profile.json)",
1044
- description: "The declarative part of a glassbrain profile, as a `_profile.json` next to the graph files. Everything is optional: with no profile a graph still renders (kinds without a color are drawn as skeleton). Parsers, merge and domain validation are code and live in a TypeScript profile instead.",
1097
+ description: "The declarative part of a glassbrain profile, as a `_profile.json` next to the graph files. Everything is optional: with no profile a graph still renders (kinds without a color are drawn as skeleton). Layers are not configured here: they are derived from `order` in the graph. Parsers, merge and domain validation are code and live in a TypeScript profile instead.",
1045
1098
  type: "object",
1046
1099
  properties: {
1047
- layers: {
1100
+ nodePalette: {
1101
+ $ref: "#/$defs/colors",
1102
+ description: "Node kind \u2192 color. Kinds not listed are skeleton."
1103
+ },
1104
+ edgePalette: {
1105
+ $ref: "#/$defs/colors",
1106
+ description: "Edge kind \u2192 color."
1107
+ },
1108
+ nodeSize: {
1109
+ $ref: "#/$defs/numbers",
1110
+ description: "Node kind \u2192 size multiplier (1 = default)."
1111
+ },
1112
+ edgeWidth: {
1113
+ $ref: "#/$defs/numbers",
1114
+ description: "Edge kind \u2192 width multiplier."
1115
+ },
1116
+ placeholderFlags: {
1048
1117
  type: "array",
1049
- description: "Layers for the 2.5D plane view. One default layer if omitted.",
1050
1118
  items: {
1051
- type: "object",
1052
- required: ["id", "label"],
1053
- properties: {
1054
- id: { type: "string" },
1055
- label: { type: "string" },
1056
- z: { type: "number", description: "Plane order: 0 is the bottom." },
1057
- color: { type: "string", description: "Hue of the plane." },
1058
- structural: { type: "boolean", description: "false = placed around the main structure instead of taking part in it." }
1119
+ type: "string"
1120
+ },
1121
+ description: "Nodes with any of these flags are drawn as placeholders (declared, not yet filled)."
1122
+ },
1123
+ kindLabels: {
1124
+ $ref: "#/$defs/strings",
1125
+ description: "Kind \u2192 human-readable name (nodes and edges share this map)."
1126
+ },
1127
+ edgeLabels: {
1128
+ $ref: "#/$defs/strings",
1129
+ description: "Same as kindLabels, for edge kinds; merged into it."
1130
+ },
1131
+ appearance: {
1132
+ type: "object",
1133
+ description: "View defaults only. Layers themselves are derived from the graph: a run of ordered siblings is one layer.",
1134
+ properties: {
1135
+ defaultLayers: {
1136
+ type: "boolean",
1137
+ description: "Open with the layer (2.5D plane) view on when the graph has ordered siblings. Default false."
1138
+ },
1139
+ layerColors: {
1140
+ type: "array",
1141
+ items: {
1142
+ type: "string"
1143
+ },
1144
+ description: "Hue per layer, in order. Defaults to the theme's palette."
1059
1145
  }
1060
1146
  }
1061
1147
  },
1062
- nodePalette: { $ref: "#/$defs/colors", description: "Node kind \u2192 color. Kinds not listed are skeleton." },
1063
- edgePalette: { $ref: "#/$defs/colors", description: "Edge kind \u2192 color." },
1064
- nodeSize: { $ref: "#/$defs/numbers", description: "Node kind \u2192 size multiplier (1 = default)." },
1065
- edgeWidth: { $ref: "#/$defs/numbers", description: "Edge kind \u2192 width multiplier." },
1066
- placeholderFlags: { type: "array", items: { type: "string" }, description: "Nodes with any of these flags are drawn as placeholders (declared, not yet filled)." },
1067
- kindLabels: { $ref: "#/$defs/strings", description: "Kind \u2192 human-readable name (nodes and edges share this map)." },
1068
- edgeLabels: { $ref: "#/$defs/strings", description: "Same as kindLabels, for edge kinds; merged into it." },
1069
- style: { type: "array", description: "Extra cytoscape style rules, appended after the base style." },
1148
+ style: {
1149
+ type: "array",
1150
+ description: "Extra cytoscape style rules, appended after the base style."
1151
+ },
1070
1152
  detail: {
1071
1153
  type: "object",
1072
1154
  description: "Detail panel field tables.",
1073
1155
  properties: {
1074
- line: { $ref: "#/$defs/fields" },
1075
- list: { $ref: "#/$defs/fields" },
1076
- skip: { type: "array", items: { type: "string" } },
1077
- flagNotes: { $ref: "#/$defs/strings" }
1156
+ line: {
1157
+ $ref: "#/$defs/fields"
1158
+ },
1159
+ list: {
1160
+ $ref: "#/$defs/fields"
1161
+ },
1162
+ skip: {
1163
+ type: "array",
1164
+ items: {
1165
+ type: "string"
1166
+ }
1167
+ },
1168
+ flagNotes: {
1169
+ $ref: "#/$defs/strings"
1170
+ }
1078
1171
  }
1079
1172
  },
1080
- singleRoot: { type: "boolean", description: "Wrap several top-level nodes in one root box (default true)." },
1081
- rootLabel: { type: "string" },
1082
- diffIgnore: { type: "array", items: { type: "string" }, description: "Node fields that do not count as a change when diffing (fields every rebuild rewrites, e.g. cluster ids or line numbers). Used by the glassbrain CLI." }
1173
+ rootLabel: {
1174
+ type: "string"
1175
+ },
1176
+ diffIgnore: {
1177
+ type: "array",
1178
+ items: {
1179
+ type: "string"
1180
+ },
1181
+ description: "Node fields that do not count as a change when diffing (fields every rebuild rewrites, e.g. cluster ids or line numbers). Used by the glassbrain CLI."
1182
+ }
1083
1183
  },
1084
1184
  additionalProperties: true,
1085
1185
  $defs: {
1086
- colors: { type: "object", additionalProperties: { type: "string" } },
1087
- numbers: { type: "object", additionalProperties: { type: "number" } },
1088
- strings: { type: "object", additionalProperties: { type: "string" } },
1186
+ colors: {
1187
+ type: "object",
1188
+ additionalProperties: {
1189
+ type: "string"
1190
+ }
1191
+ },
1192
+ numbers: {
1193
+ type: "object",
1194
+ additionalProperties: {
1195
+ type: "number"
1196
+ }
1197
+ },
1198
+ strings: {
1199
+ type: "object",
1200
+ additionalProperties: {
1201
+ type: "string"
1202
+ }
1203
+ },
1089
1204
  fields: {
1090
1205
  type: "array",
1091
1206
  items: {
1092
1207
  type: "object",
1093
- required: ["key", "label"],
1094
- properties: { key: { type: "string" }, label: { type: "string" } }
1208
+ required: [
1209
+ "key",
1210
+ "label"
1211
+ ],
1212
+ properties: {
1213
+ key: {
1214
+ type: "string"
1215
+ },
1216
+ label: {
1217
+ type: "string"
1218
+ }
1219
+ }
1095
1220
  }
1096
1221
  }
1097
1222
  }
@@ -1112,7 +1237,8 @@ var KNOWN = /* @__PURE__ */ new Set([
1112
1237
  "anyOf",
1113
1238
  "$ref",
1114
1239
  "minimum",
1115
- "maximum"
1240
+ "maximum",
1241
+ "exclusiveMinimum"
1116
1242
  ]);
1117
1243
  var typeOf = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v === "number" ? Number.isInteger(v) ? "integer" : "number" : typeof v;
1118
1244
  var fits = (v, t) => {
@@ -1153,6 +1279,7 @@ function checkSchema(root, value, limit = 50) {
1153
1279
  if (typeof v === "number") {
1154
1280
  if (s.minimum != null && v < s.minimum) out2.push({ path: path3, message: `must be \u2265 ${s.minimum}` });
1155
1281
  if (s.maximum != null && v > s.maximum) out2.push({ path: path3, message: `must be \u2264 ${s.maximum}` });
1282
+ if (s.exclusiveMinimum != null && v <= s.exclusiveMinimum) out2.push({ path: path3, message: `must be > ${s.exclusiveMinimum}` });
1156
1283
  }
1157
1284
  };
1158
1285
  const out = [];
@@ -1161,6 +1288,9 @@ function checkSchema(root, value, limit = 50) {
1161
1288
  }
1162
1289
 
1163
1290
  // cli/checks.ts
1291
+ var ISOMORPHISM_TAU = 0.85;
1292
+ var WIDE_INFO = 5;
1293
+ var WIDE_WARN = 10;
1164
1294
  var MAX_NAMES = 4;
1165
1295
  var MIN_SAMPLE = 10;
1166
1296
  var names = (xs) => `${xs.slice(0, MAX_NAMES).join(", ")}${xs.length > MAX_NAMES ? ` and ${xs.length - MAX_NAMES} more` : ""}`;
@@ -1168,27 +1298,51 @@ var misplacedField = {
1168
1298
  code: "misplaced-field",
1169
1299
  level: "error",
1170
1300
  run: ({ model }) => {
1171
- const reserved = ["id", "label", "kind", "parent", "layer", "description"];
1301
+ const reserved = ["id", "label", "kind", "parent", "order", "description"];
1172
1302
  const out = [];
1173
1303
  for (const n of model.nodes) {
1174
1304
  const nested = n.data?.data;
1175
1305
  if (!nested || typeof nested !== "object" || Array.isArray(nested)) continue;
1176
1306
  const found = reserved.filter((k) => k in nested);
1177
1307
  if (!found.length) continue;
1178
- out.push({ node: n.id, message: `"${n.id}" keeps ${found.map((k) => `"${k}"`).join(", ")} under "data"; only top-level fields are read` });
1308
+ out.push({
1309
+ node: n.id,
1310
+ message: `"${n.id}" keeps ${found.map((k) => `"${k}"`).join(", ")} under "data"; only top-level fields are read`,
1311
+ fix: `move ${found.length > 1 ? "them" : "it"} up one level, next to "id":
1312
+ - { "id": "${n.id}", "data": { ${found.map((k) => `"${k}": \u2026`).join(", ")} } }
1313
+ + { "id": "${n.id}", ${found.map((k) => `"${k}": \u2026`).join(", ")} }`
1314
+ });
1179
1315
  }
1180
1316
  return out;
1181
1317
  }
1182
1318
  };
1183
- var missingParent = {
1184
- code: "missing-parent",
1319
+ var layerField = {
1320
+ code: "layer-field",
1321
+ level: "error",
1322
+ run: ({ model }) => model.nodes.filter((n) => n.data && typeof n.data === "object" && "layer" in n.data).map((n) => ({
1323
+ node: n.id,
1324
+ message: `"${n.id}" still carries "layer": layers are not written any more, they are derived from "order"`,
1325
+ fix: `delete the field. To make the graph read as floors, give one node's children "order" instead:
1326
+ - { "id": "${n.id}", "parent": "\u2026", "layer": "${n.layer}" }
1327
+ + { "id": "${n.id}", "parent": "\u2026", "order": 2 }`
1328
+ }))
1329
+ };
1330
+ var unknownParent = {
1331
+ code: "unknown-parent",
1185
1332
  level: "error",
1186
- run: ({ model, index }) => model.nodes.filter((n) => n.parent && !index.has(n.parent)).map((n) => ({ node: n.id, message: `"${n.id}" sits inside "${n.parent}", which does not exist` }))
1333
+ run: ({ model, index: index2, labelOf }) => model.nodes.filter((n) => n.parent && !index2.has(n.parent)).map((n) => ({
1334
+ node: n.id,
1335
+ message: `"${n.id}" sits inside "${n.parent}", which does not exist`,
1336
+ fix: `point it at a node that exists (one of: ${[...index2.keys()].slice(0, 3).map((id) => `"${id}"`).join(", ")}), or add "${n.parent}":
1337
+ - "parent": "${n.parent}"
1338
+ + "parent": "${[...index2.keys()][0] ?? "EXISTING_ID"}"
1339
+ ("parent": null also works, but it makes another top-level tree, which validate warns about.)`
1340
+ }))
1187
1341
  };
1188
1342
  var parentCycle = {
1189
1343
  code: "parent-cycle",
1190
1344
  level: "error",
1191
- run: ({ model, index }) => {
1345
+ run: ({ model, index: index2 }) => {
1192
1346
  const out = [];
1193
1347
  const done = /* @__PURE__ */ new Set();
1194
1348
  for (const start of model.nodes) {
@@ -1201,41 +1355,68 @@ var parentCycle = {
1201
1355
  if (seen !== void 0) {
1202
1356
  const loop = path3.slice(seen);
1203
1357
  loop.forEach((id) => done.add(id));
1204
- out.push({ node: cur, message: `parent cycle: ${[...loop, cur].join(" \u2192 ")}` });
1358
+ out.push({
1359
+ node: cur,
1360
+ message: `parent cycle: ${[...loop, cur].join(" \u2192 ")}`,
1361
+ fix: `a node cannot sit inside itself. Pick the one that should be the top of the loop and give it "parent": null:
1362
+ - { "id": "${loop[0]}", "parent": "${cur}" }
1363
+ + { "id": "${loop[0]}", "parent": null }`
1364
+ });
1205
1365
  break;
1206
1366
  }
1207
1367
  at.set(cur, path3.length);
1208
1368
  path3.push(cur);
1209
- const parent = index.get(cur)?.parent;
1210
- cur = parent && index.has(parent) ? parent : void 0;
1369
+ const parent = index2.get(cur)?.parent;
1370
+ cur = parent && index2.has(parent) ? parent : void 0;
1211
1371
  }
1212
1372
  for (const id of path3) done.add(id);
1213
1373
  }
1214
1374
  return out;
1215
1375
  }
1216
1376
  };
1217
- var unknownLayer = {
1218
- code: "unknown-layer",
1377
+ var orderMixed = {
1378
+ code: "order-mixed",
1219
1379
  level: "error",
1220
- run: ({ model, profile }) => {
1221
- const declared = profile.layers.map((l) => l.id);
1222
- const known = new Set(declared);
1223
- return model.nodes.filter((n) => n.layer && !known.has(n.layer)).map((n) => ({ node: n.id, layer: n.layer, message: `layer "${n.layer}" is not declared (declared: ${declared.join(", ")})` }));
1380
+ run: ({ children }) => {
1381
+ const out = [];
1382
+ for (const [parent, kids] of children) {
1383
+ const withOrder = kids.filter((k) => typeof k.order === "number").length;
1384
+ if (withOrder === 0 || withOrder === kids.length) continue;
1385
+ const missing = kids.filter((k) => typeof k.order !== "number").slice(0, 3);
1386
+ const next = Math.max(0, ...kids.map((k) => typeof k.order === "number" ? k.order : 0)) + 1;
1387
+ out.push({
1388
+ node: parent,
1389
+ message: `${withOrder} of ${kids.length} children of "${parent}" have "order"; a numbered list numbers every item`,
1390
+ fix: `give the rest an order, or take them all away (then the order is whatever the layout finds):
1391
+ ${missing.map((k, i) => ` - { "id": "${k.id}", "parent": "${parent}" }
1392
+ + { "id": "${k.id}", "parent": "${parent}", "order": ${next + i} }`).join("\n")}`
1393
+ });
1394
+ }
1395
+ return out;
1224
1396
  }
1225
1397
  };
1226
- var crossLayerParent = {
1227
- code: "cross-layer-parent",
1398
+ var orderDuplicate = {
1399
+ code: "order-duplicate",
1228
1400
  level: "error",
1229
- run: ({ model, index, layerOf }) => {
1401
+ run: ({ children }) => {
1230
1402
  const out = [];
1231
- for (const n of model.nodes) {
1232
- const parent = n.parent ? index.get(n.parent) : void 0;
1233
- if (!parent || layerOf(parent) === layerOf(n)) continue;
1234
- out.push({
1235
- node: n.id,
1236
- layer: layerOf(n),
1237
- message: `"${n.id}" is on layer "${layerOf(n)}" but its parent "${parent.id}" is on "${layerOf(parent)}"; each layer is its own tree, layers connect by edges only`
1238
- });
1403
+ for (const [parent, kids] of children) {
1404
+ const seen = /* @__PURE__ */ new Map();
1405
+ for (const k of kids) {
1406
+ if (typeof k.order !== "number") continue;
1407
+ const arr = seen.get(k.order);
1408
+ arr ? arr.push(k) : seen.set(k.order, [k]);
1409
+ }
1410
+ for (const [value, same] of seen) {
1411
+ if (same.length < 2) continue;
1412
+ out.push({
1413
+ node: parent,
1414
+ message: `"${parent}" has ${same.length} children at order ${value} (${names(same.map((n) => n.id))}); two items cannot share a place`,
1415
+ fix: `spread them. Fractions are allowed, so nothing else has to move:
1416
+ ${same.slice(1).map((k, i) => ` - { "id": "${k.id}", "order": ${value} }
1417
+ + { "id": "${k.id}", "order": ${value + (i + 1) / 10} }`).join("\n")}`
1418
+ });
1419
+ }
1239
1420
  }
1240
1421
  return out;
1241
1422
  }
@@ -1243,19 +1424,27 @@ var crossLayerParent = {
1243
1424
  var conflictingDefinition = {
1244
1425
  code: "conflicting-definition",
1245
1426
  level: "error",
1246
- run: ({ model, index, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1427
+ run: ({ model, index: index2, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1247
1428
  node: id,
1248
- message: `"${id}" is defined differently in ${names(index.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`
1429
+ message: `"${id}" is defined differently in ${names(index2.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`,
1430
+ fix: `one id is one thing. Either make the copies identical, or give one a new id and point its edges at that:
1431
+ ${names(index2.get(id)?.origins ?? [])} \u2014 keep one definition of "${id}", or rename the other to "${id}-2" and update every edge that meant it.`
1249
1432
  }))
1250
1433
  };
1251
1434
  var danglingEdge = {
1252
1435
  code: "dangling-edge",
1253
1436
  level: "error",
1254
- run: ({ model, index }) => {
1437
+ run: ({ model, index: index2, labelOf }) => {
1255
1438
  const out = [];
1256
1439
  for (const e of model.edges) {
1257
- const missing = [!index.has(e.source) && e.source, !index.has(e.target) && e.target].filter(Boolean).join(" / ");
1258
- if (missing) out.push({ message: `edge ${e.source} \u2192 ${e.target}${e.kind ? ` (${e.kind})` : ""} points at the missing node ${missing}` });
1440
+ const missing = [!index2.has(e.source) && e.source, !index2.has(e.target) && e.target].filter(Boolean).join(" / ");
1441
+ if (!missing) continue;
1442
+ out.push({
1443
+ message: `edge ${e.source} \u2192 ${e.target}${e.kind ? ` (${e.kind})` : ""} points at the missing node ${missing}`,
1444
+ fix: `an edge can only join nodes that exist. Add the node, or repoint the edge:
1445
+ - { "source": "${e.source}", "target": "${e.target}" }
1446
+ + { "source": "${index2.has(e.source) ? e.source : labelOf(e.target) || e.source}", "target": "${index2.has(e.target) ? e.target : "EXISTING_ID"}" }`
1447
+ });
1259
1448
  }
1260
1449
  return out;
1261
1450
  }
@@ -1273,7 +1462,11 @@ var duplicateEdge = {
1273
1462
  for (const [key, count2] of times) {
1274
1463
  if (count2 < 2) continue;
1275
1464
  const [source, target, kind] = key.split("\0");
1276
- out.push({ message: `edge ${source} \u2192 ${target}${kind ? ` (${kind})` : ""} is written ${count2} times; it is drawn once` });
1465
+ out.push({
1466
+ message: `edge ${source} \u2192 ${target}${kind ? ` (${kind})` : ""} is written ${count2} times; it is drawn once`,
1467
+ fix: `delete ${count2 - 1} of the copies; the file should hold this line once:
1468
+ { "source": "${source}", "target": "${target}"${kind ? `, "kind": "${kind}"` : ""} }`
1469
+ });
1277
1470
  }
1278
1471
  return out;
1279
1472
  }
@@ -1281,21 +1474,108 @@ var duplicateEdge = {
1281
1474
  var multipleRoots = {
1282
1475
  code: "multiple-roots",
1283
1476
  level: "warn",
1284
- run: ({ model, layerOf }) => {
1285
- const tops = /* @__PURE__ */ new Map();
1286
- for (const n of model.nodes) {
1287
- if (n.parent) continue;
1288
- const layer = layerOf(n);
1289
- const arr = tops.get(layer);
1290
- if (arr) arr.push(n);
1291
- else tops.set(layer, [n]);
1477
+ run: ({ model }) => {
1478
+ const roots = model.nodes.filter((n) => n.parent == null);
1479
+ if (roots.length < 2) return [];
1480
+ return [{
1481
+ message: `${roots.length} top-level nodes (${names(roots.map((n) => n.label || n.id))}); it reads as ${roots.length} separate trees, not one`,
1482
+ fix: `one file, one tree: add a root and hang them under it. A root is a real node, so give it a label:
1483
+ + { "id": "root", "label": "${model.nodes.find((n) => !n.parent)?.label ?? "Overview"}", "kind": "overview", "parent": null }
1484
+ ${roots.slice(0, 3).map((n, i) => `- { "id": "${n.id}", "parent": null }
1485
+ + { "id": "${n.id}", "parent": "root", "order": ${i + 1} }`).join("\n ")}
1486
+ (ordered children of one root also become the layer view.) Or split the file in two, one tree each.`
1487
+ }];
1488
+ }
1489
+ };
1490
+ var noHierarchy = {
1491
+ code: "no-hierarchy",
1492
+ level: "warn",
1493
+ run: ({ model }) => {
1494
+ if (!model.nodes.length || model.nodes.some((n) => n.parent)) return [];
1495
+ return [{
1496
+ message: `${model.nodes.length} nodes and no parent anywhere: flat, so there is no outline to read`,
1497
+ fix: `give every node a parent (or null for the one root). If the ids carry the folders, grouping by prefix is enough:
1498
+ - { "id": "flask/app.py", "parent": null }
1499
+ + { "id": "flask/app.py", "parent": "flask" }
1500
+ or run: glassbrain restructure <path>`
1501
+ }];
1502
+ }
1503
+ };
1504
+ function isomorphism(model, children, heightOf) {
1505
+ let logSum = 0;
1506
+ let parents = 0;
1507
+ const uneven = [];
1508
+ for (const [id, kids] of children) {
1509
+ if (kids.length < 2) continue;
1510
+ const count2 = /* @__PURE__ */ new Map();
1511
+ for (const k of kids) {
1512
+ const h = heightOf(k.id);
1513
+ count2.set(h, (count2.get(h) ?? 0) + 1);
1292
1514
  }
1515
+ const q = Math.max(...count2.values()) / kids.length;
1516
+ logSum += Math.log(q);
1517
+ parents++;
1518
+ if (q < 1) uneven.push({ id, q, kids: kids.length });
1519
+ }
1520
+ uneven.sort((a2, b) => a2.q - b.q || b.kids - a2.kids);
1521
+ return { score: parents ? Math.exp(logSum / parents) : 1, parents, uneven };
1522
+ }
1523
+ function unevenFix(ctx, worst) {
1524
+ const kids = [...ctx.children.get(worst.id) ?? []].sort((a2, b) => ctx.heightOf(a2.id) - ctx.heightOf(b.id));
1525
+ const short = kids[0];
1526
+ const deep = kids[kids.length - 1];
1527
+ const m = ctx.heightOf(deep.id);
1528
+ const shallow = ctx.heightOf(short.id);
1529
+ const leaf = ctx.children.get(short.id)?.length ? "" : " (it is a leaf: it needs a child, or the deep branch needs one less level)";
1530
+ return [
1531
+ `same parent, same depth. Under "${ctx.labelOf(worst.id)}" (${worst.kids} children, ${Math.round(worst.q * 100)}% are ${m} deep):`,
1532
+ ` \u2717 ${worst.id}`,
1533
+ ` \u251C\u2500 ${short.id} ${shallow} deep${leaf}`,
1534
+ ` \u2514\u2500 ${deep.id} ${m} deep`,
1535
+ ` \u2713 both ${m} deep: give ${short.id} one more real level, or lift ${deep.id}'s children up one level.`,
1536
+ ` Do not invent an empty group just to pad the depth \u2014 move the branch instead.`,
1537
+ `or let the tool do all of them: glassbrain restructure <path>`
1538
+ ].join("\n");
1539
+ }
1540
+ var unevenBranches = {
1541
+ code: "uneven-branches",
1542
+ level: "warn",
1543
+ run: (ctx) => {
1544
+ const { score: score2, parents, uneven } = isomorphism(ctx.model, ctx.children, ctx.heightOf);
1545
+ if (!parents || score2 >= 1) return [];
1546
+ const worst = uneven[0];
1547
+ const level = score2 < ISOMORPHISM_TAU && uneven.length >= 2 ? "warn" : "info";
1548
+ const line = `isomorphism ${score2.toFixed(2)} of 1.00${level === "warn" ? ` (threshold ${ISOMORPHISM_TAU})` : ""}: ${uneven.length} of ${parents} parents ${uneven.length === 1 ? "has" : "have"} branches of different depth`;
1549
+ return [{
1550
+ level,
1551
+ message: worst ? `${line}; worst: ${ctx.labelOf(worst.id)} (${worst.kids} children)` : line,
1552
+ fix: worst ? unevenFix(ctx, worst) : void 0,
1553
+ ...worst ? { node: worst.id } : {}
1554
+ }];
1555
+ }
1556
+ };
1557
+ var wideNode = {
1558
+ code: "wide-node",
1559
+ level: "warn",
1560
+ run: ({ children, labelOf, layers }) => {
1293
1561
  const out = [];
1294
- for (const [layer, nodes] of tops) {
1295
- if (nodes.length < 2) continue;
1562
+ for (const [id, kids] of children) {
1563
+ const n = kids.length;
1564
+ if (n <= WIDE_INFO) continue;
1565
+ const level = n > WIDE_WARN ? "warn" : "info";
1566
+ const isAnchor = layers.anchor === id;
1567
+ const what = isAnchor ? `${n} layers` : `${n} children`;
1296
1568
  out.push({
1297
- layer,
1298
- message: `layer "${layer}" has ${nodes.length} top-level nodes (${names(nodes.map((n) => n.label || n.id))}); it reads as ${nodes.length} separate trees, not one`
1569
+ level,
1570
+ node: id,
1571
+ message: `"${labelOf(id)}" holds ${what}; ${isAnchor ? "2\u20134 layers read best" : `more than ${WIDE_INFO} wants another level of grouping`}`,
1572
+ fix: isAnchor ? `fewer floors, or group the extras under one of them:
1573
+ ${kids.slice(4, 6).map((k, i) => `- { "id": "${k.id}", "parent": "${id}", "order": ${5 + i} }
1574
+ + { "id": "more", "parent": "${id}", "order": 5 }
1575
+ + { "id": "${k.id}", "parent": "more", "order": ${i + 1} }`).join("\n ")}` : `add one grouping node between:
1576
+ - { "id": "${kids[0].id}", "parent": "${id}" }
1577
+ + { "id": "${id}/group", "parent": "${id}" }
1578
+ + { "id": "${kids[0].id}", "parent": "${id}/group" }`
1299
1579
  });
1300
1580
  }
1301
1581
  return out;
@@ -1311,7 +1591,10 @@ var preferFewerKinds = {
1311
1591
  if (!kinds || total < MIN_SAMPLE) return;
1312
1592
  const average = total / kinds;
1313
1593
  if (kinds > 10 || average < 5) {
1314
- out.push({ message: `${space} kinds: ${kinds} (${average.toFixed(1)} per kind); 10 kinds or 5 per kind reads better` });
1594
+ out.push({
1595
+ message: `${space} kinds: ${kinds} (${average.toFixed(1)} per kind); 8 kinds or 5 per kind reads better`,
1596
+ fix: `merge the look-alikes into one kind and keep the difference in the label or the description. The palette only has room for a handful.`
1597
+ });
1315
1598
  }
1316
1599
  };
1317
1600
  spread("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
@@ -1327,32 +1610,13 @@ var loneKind = {
1327
1610
  const lone = (space, counts, total) => {
1328
1611
  if (total < MIN_SAMPLE) return;
1329
1612
  const once = [...counts].filter(([, c]) => c === 1).map(([k]) => k);
1330
- if (once.length) out.push({ message: `${once.length} ${space} kind${once.length > 1 ? "s" : ""} used once: ${names(once)}` });
1613
+ if (once.length) out.push({ message: `${once.length} ${space} kind${once.length > 1 ? "s" : ""} used once: ${names(once)}`, fix: `fold ${once.length > 1 ? "them" : "it"} into a kind that is already used, or use ${once.length > 1 ? "them" : "it"} more.` });
1331
1614
  };
1332
1615
  lone("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1333
1616
  lone("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1334
1617
  return out;
1335
1618
  }
1336
1619
  };
1337
- var preferFewerLayers = {
1338
- code: "prefer-fewer-layers",
1339
- level: "info",
1340
- run: ({ model, layerOf }) => {
1341
- const perLayer = /* @__PURE__ */ new Map();
1342
- for (const n of model.nodes) perLayer.set(layerOf(n), (perLayer.get(layerOf(n)) ?? 0) + 1);
1343
- const used = perLayer.size;
1344
- const smallest = Math.min(...perLayer.values());
1345
- if (used <= 5 && !(used > 3 && smallest < 3)) return [];
1346
- return [{
1347
- message: `${used} layers in use${used > 3 ? `, the smallest holds ${smallest}` : ""}; 2\u20135 is what a reader can hold, fewer when a layer holds almost nothing`
1348
- }];
1349
- }
1350
- };
1351
- var flatParent = {
1352
- code: "flat-parent",
1353
- level: "info",
1354
- run: ({ children, labelOf }) => [...children].filter(([, kids]) => kids.length > 30).slice(0, 3).map(([id, kids]) => ({ node: id, message: `"${labelOf(id)}" holds ${kids.length} children; one more level of grouping reads better` }))
1355
- };
1356
1620
  var lowCoverage = {
1357
1621
  code: "low-coverage",
1358
1622
  level: "info",
@@ -1361,40 +1625,56 @@ var lowCoverage = {
1361
1625
  if (leaves.length < 20) return [];
1362
1626
  const described = leaves.filter((n) => typeof n.data?.description === "string" && n.data.description.trim()).length;
1363
1627
  if (described / leaves.length >= 0.5) return [];
1364
- return [{ message: `${leaves.length - described} of ${leaves.length} leaf nodes have no description` }];
1628
+ return [{
1629
+ message: `${leaves.length - described} of ${leaves.length} leaf nodes have no description`,
1630
+ fix: `a leaf is what the reader clicks to understand something; half of them open empty.
1631
+ { "id": "${leaves.find((n) => !(typeof n.data?.description === "string" && n.data.description.trim()))?.id ?? "leaf"}", "description": "one sentence on what this is" }`
1632
+ }];
1365
1633
  }
1366
1634
  };
1367
1635
  var colorsContrast = {
1368
1636
  code: "colors-contrast",
1369
1637
  level: "info",
1370
1638
  run: ({ profile }) => {
1371
- const grays = Object.values(profile.nodePalette).map(hexGray).filter((g) => g !== null);
1372
- if (grays.length < 4) return [];
1373
- const e = entropy(grays);
1374
- if (e >= 0.6) return [];
1375
- return [{ message: `${grays.length} kind colors sit in few brightness bands (entropy ${e.toFixed(2)} < 0.60); neighboring kinds will read alike` }];
1639
+ const colors = Object.entries(profile.nodePalette).map(([kind, hex]) => ({ kind, lab: hexLab(hex) }));
1640
+ const usable = colors.filter((c) => c.lab !== null);
1641
+ if (usable.length < 6) return [];
1642
+ let worst = { a: "", b: "", d: Infinity };
1643
+ for (let i = 0; i < usable.length; i++) {
1644
+ for (let j = i + 1; j < usable.length; j++) {
1645
+ const d = deltaE(usable[i].lab, usable[j].lab);
1646
+ if (d < worst.d) worst = { a: usable[i].kind, b: usable[j].kind, d };
1647
+ }
1648
+ }
1649
+ if (worst.d >= 10) return [];
1650
+ return [{
1651
+ message: `"${worst.a}" and "${worst.b}" are ${worst.d.toFixed(1)} apart in color (under 10 reads as the same kind)`,
1652
+ fix: `push them apart in lightness, not just hue:
1653
+ "${worst.a}": darker \u2192 e.g. #4338ca
1654
+ "${worst.b}": lighter \u2192 e.g. #a5b4fc`
1655
+ }];
1376
1656
  }
1377
1657
  };
1378
1658
  var rules = [
1379
1659
  misplacedField,
1380
- missingParent,
1660
+ layerField,
1661
+ unknownParent,
1381
1662
  parentCycle,
1382
- unknownLayer,
1383
- crossLayerParent,
1663
+ orderMixed,
1664
+ orderDuplicate,
1384
1665
  conflictingDefinition,
1385
1666
  danglingEdge,
1386
1667
  duplicateEdge,
1387
1668
  multipleRoots,
1669
+ noHierarchy,
1670
+ unevenBranches,
1671
+ wideNode,
1388
1672
  preferFewerKinds,
1389
1673
  loneKind,
1390
- preferFewerLayers,
1391
- flatParent,
1392
1674
  lowCoverage,
1393
1675
  colorsContrast
1394
1676
  ];
1395
- var RANK = { error: 0, warn: 1, info: 2 };
1396
1677
  function checkGraph(model, profile, opts) {
1397
- const fallbackLayer = profile.layers[0].id;
1398
1678
  const children = /* @__PURE__ */ new Map();
1399
1679
  for (const n of model.nodes) {
1400
1680
  if (!n.parent || !model.index.has(n.parent)) continue;
@@ -1402,40 +1682,73 @@ function checkGraph(model, profile, opts) {
1402
1682
  if (arr) arr.push(n);
1403
1683
  else children.set(n.parent, [n]);
1404
1684
  }
1685
+ const heightMemo = /* @__PURE__ */ new Map();
1686
+ const heightOf = (id, seen = /* @__PURE__ */ new Set()) => {
1687
+ const hit = heightMemo.get(id);
1688
+ if (hit != null) return hit;
1689
+ if (seen.has(id)) return 0;
1690
+ seen.add(id);
1691
+ let h = 0;
1692
+ for (const k of children.get(id) ?? []) h = Math.max(h, heightOf(k.id, seen) + 1);
1693
+ heightMemo.set(id, h);
1694
+ return h;
1695
+ };
1405
1696
  const ctx = {
1406
1697
  model,
1407
1698
  profile,
1408
1699
  where: opts.where,
1409
1700
  index: model.index,
1410
1701
  children,
1411
- layerOf: (n) => n.layer ?? fallbackLayer,
1702
+ layers: deriveLayers(model),
1412
1703
  labelOf: (id) => model.index.get(id)?.label ?? id,
1704
+ heightOf: (id) => heightOf(id),
1413
1705
  sameFileDuplicates: opts.sameFileDuplicates ?? /* @__PURE__ */ new Set()
1414
1706
  };
1415
1707
  const out = rules.flatMap((rule) => rule.run(ctx).map((issue) => ({
1416
- level: rule.level,
1708
+ level: issue.level ?? rule.level,
1417
1709
  code: rule.code,
1418
1710
  where: opts.where,
1419
1711
  message: issue.message,
1420
- ...issue.node !== void 0 ? { node: issue.node } : {},
1421
- ...issue.layer !== void 0 ? { layer: issue.layer } : {}
1712
+ ...issue.fix !== void 0 ? { fix: issue.fix } : {},
1713
+ ...issue.node !== void 0 ? { node: issue.node } : {}
1422
1714
  })));
1423
- return out.sort((a2, b) => RANK[a2.level] - RANK[b.level]);
1715
+ return out;
1424
1716
  }
1425
1717
  function structureOf(model) {
1426
- const index = indexModel(model);
1718
+ const index2 = indexModel(model);
1427
1719
  let depth = 0;
1428
1720
  let parented = 0;
1429
1721
  for (const n of model.nodes) {
1430
1722
  if (n.parent && model.index.has(n.parent)) parented++;
1431
- depth = Math.max(depth, index.depthOf(n.id));
1723
+ depth = Math.max(depth, index2.depthOf(n.id));
1724
+ }
1725
+ const children = /* @__PURE__ */ new Map();
1726
+ for (const n of model.nodes) {
1727
+ if (!n.parent || !model.index.has(n.parent)) continue;
1728
+ const arr = children.get(n.parent);
1729
+ arr ? arr.push(n) : children.set(n.parent, [n]);
1432
1730
  }
1731
+ const heightMemo = /* @__PURE__ */ new Map();
1732
+ const heightOf = (id, seen = /* @__PURE__ */ new Set()) => {
1733
+ const hit = heightMemo.get(id);
1734
+ if (hit != null) return hit;
1735
+ if (seen.has(id)) return 0;
1736
+ seen.add(id);
1737
+ let h = 0;
1738
+ for (const k of children.get(id) ?? []) h = Math.max(h, heightOf(k.id, seen) + 1);
1739
+ heightMemo.set(id, h);
1740
+ return h;
1741
+ };
1742
+ const derived = deriveLayers(model);
1433
1743
  return {
1434
1744
  nodes: model.nodes.length,
1435
1745
  edges: model.edges.length,
1436
1746
  roots: model.nodes.filter((n) => !n.parent).length,
1437
1747
  depth,
1438
- parented
1748
+ parented,
1749
+ layers: derived.layers.length,
1750
+ isomorphism: +isomorphism(model, children, (id) => heightOf(id)).score.toFixed(2),
1751
+ ordered: derived.layers.length > 0 || [...children.keys()].some((id) => orderedChildren(children, id) !== null)
1439
1752
  };
1440
1753
  }
1441
1754
  function countsBy(values) {
@@ -1443,42 +1756,61 @@ function countsBy(values) {
1443
1756
  for (const v of values) if (v) out.set(v, (out.get(v) ?? 0) + 1);
1444
1757
  return out;
1445
1758
  }
1446
- function hexGray(value) {
1759
+ function hexLab(value) {
1447
1760
  const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(value.trim());
1448
1761
  if (!m) return null;
1449
1762
  const hex = m[1].length === 3 ? [...m[1]].map((c) => c + c).join("") : m[1];
1450
- const r = parseInt(hex.slice(0, 2), 16);
1451
- const g = parseInt(hex.slice(2, 4), 16);
1452
- const b = parseInt(hex.slice(4, 6), 16);
1453
- return 0.299 * r + 0.587 * g + 0.114 * b;
1454
- }
1455
- function entropy(values) {
1456
- const bins = new Array(16).fill(0);
1457
- for (const v of values) bins[Math.min(15, Math.max(0, Math.floor(v / 16)))]++;
1458
- let sum = 0;
1459
- for (const count2 of bins) if (count2) {
1460
- const p = count2 / values.length;
1461
- sum -= p * Math.log2(p);
1462
- }
1463
- const max = Math.log2(Math.min(16, values.length));
1464
- return max ? sum / max : 0;
1763
+ const [r, g, b] = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
1764
+ const [x, y, z] = [
1765
+ (r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047,
1766
+ r * 0.2126 + g * 0.7152 + b * 0.0722,
1767
+ (r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883
1768
+ ].map((v) => v > 8856e-6 ? v ** (1 / 3) : 7.787 * v + 16 / 116);
1769
+ return [116 * y - 16, 500 * (x - y), 200 * (y - z)];
1770
+ }
1771
+ function deltaE(a2, b) {
1772
+ return Math.hypot(a2[0] - b[0], a2[1] - b[1], a2[2] - b[2]);
1465
1773
  }
1466
1774
 
1467
1775
  // cli/model.ts
1468
1776
  function profileFromJson(id, json) {
1469
1777
  if (!json) return defineProfile({ id });
1470
- const { demo: _demo, diffIgnore: _ignore, edgeLabels = {}, ...rest } = json;
1778
+ const { demo: _demo, diffIgnore: _ignore, edgeLabels = {}, layers: _layers, singleRoot: _single, ...rest } = json;
1471
1779
  return defineProfile({ id, ...rest, kindLabels: { ...rest.kindLabels, ...edgeLabels } });
1472
1780
  }
1781
+ function profileOf(l) {
1782
+ const json = l.profile;
1783
+ const base2 = profileFromJson("cli", json);
1784
+ const latest = l.versions[l.versions.length - 1];
1785
+ if (!latest) return base2;
1786
+ return derivedProfile(base2, latest.sources, json);
1787
+ }
1788
+ function derivedProfile(base2, sources, json) {
1789
+ const first = parseSources(sources, base2);
1790
+ const colors = json?.appearance?.layerColors;
1791
+ const derived = deriveLayers(first, Array.isArray(colors) ? colors : []);
1792
+ if (derived.layers.length < 2) return base2;
1793
+ return defineProfile({ ...base2, layers: derived.layers, layerOf: (n) => derived.layerOf.get(n.id) ?? derived.layers[0].id });
1794
+ }
1473
1795
  var modelOf = (v, profile) => parseSources(v.sources, profile);
1474
- var RANK2 = { error: 0, warn: 1, info: 2 };
1796
+ var RANK = { error: 0, warn: 1, info: 2 };
1475
1797
  function validate(loaded) {
1476
1798
  const out = [];
1477
- const profile = profileFromJson("cli", loaded.profile);
1799
+ const profile = profileOf(loaded);
1478
1800
  if (loaded.profile) {
1479
1801
  for (const e of checkSchema(profile_schema_default, loaded.profile)) out.push({ level: "error", code: "schema", where: "_profile.json", message: `${e.path}: ${e.message}` });
1802
+ const retired = ["layers", "singleRoot"].filter((k) => k in loaded.profile);
1803
+ if (retired.length) out.push({
1804
+ level: "warn",
1805
+ code: "profile-retired",
1806
+ where: "_profile.json",
1807
+ message: `${retired.map((k) => `"${k}"`).join(" and ")} no longer configure anything: layers are derived from "order"`,
1808
+ fix: `delete ${retired.length > 1 ? "them" : "it"} from _profile.json. To open the page with the plane view on, write:
1809
+ { "appearance": { "defaultLayers": true } }`
1810
+ });
1480
1811
  }
1481
1812
  for (const e of loaded.metaErrors) out.push({ level: "error", code: "schema", where: e.file, message: e.message });
1813
+ const latest = loaded.raw[loaded.raw.length - 1]?.version;
1482
1814
  for (const { version, files } of loaded.raw) {
1483
1815
  const prefix = loaded.versions.length > 1 ? `${version}/` : "";
1484
1816
  const notJson = /* @__PURE__ */ new Set();
@@ -1499,6 +1831,18 @@ function validate(loaded) {
1499
1831
  continue;
1500
1832
  }
1501
1833
  for (const e of checkSchema(graph_schema_default, doc)) out.push({ level: "error", code: "schema", where: prefix + f.path, message: `${e.path}: ${e.message}` });
1834
+ const bare = (Array.isArray(doc.nodes) ? doc.nodes : []).filter((n) => !!n && typeof n === "object" && !("parent" in n));
1835
+ if (bare.length) out.push({
1836
+ level: "error",
1837
+ code: "missing-parent",
1838
+ where: prefix + f.path,
1839
+ message: `${bare.length} node${bare.length > 1 ? "s" : ""} without "parent" (${bare.slice(0, 3).map((n) => `"${String(n.id)}"`).join(", ")}${bare.length > 3 ? ` and ${bare.length - 3} more` : ""}); every node has one: an id, or null for the root`,
1840
+ fix: `add the field. The top of the tree is null; everything else names its container:
1841
+ - { "id": "${String(bare[0].id)}" }
1842
+ + { "id": "${String(bare[0].id)}", "parent": null }
1843
+ - { "id": "child" }
1844
+ + { "id": "child", "parent": "${String(bare[0].id)}" }`
1845
+ });
1502
1846
  const seen = /* @__PURE__ */ new Map();
1503
1847
  for (const id of idsIn(doc)) seen.set(id, (seen.get(id) ?? 0) + 1);
1504
1848
  for (const [id, count2] of seen) {
@@ -1511,10 +1855,10 @@ function validate(loaded) {
1511
1855
  const v = loaded.versions.find((x) => x.name === version);
1512
1856
  const model = modelOf(v, profile);
1513
1857
  for (const e of model.errors) if (!notJson.has(e.origin)) out.push({ level: "error", code: "schema", where: prefix + e.origin, message: e.message });
1514
- out.push(...checkGraph(model, profile, { where: prefix || loaded.title, sameFileDuplicates }));
1858
+ if (version === latest) out.push(...checkGraph(model, profile, { where: prefix || loaded.title, sameFileDuplicates }));
1515
1859
  if (!model.nodes.length) out.push({ level: "warn", code: "empty", where: prefix || loaded.title, message: "No nodes found" });
1516
1860
  }
1517
- return out.sort((a2, b) => RANK2[a2.level] - RANK2[b.level]);
1861
+ return out.sort((a2, b) => RANK[a2.level] - RANK[b.level]);
1518
1862
  }
1519
1863
  function idsIn(doc) {
1520
1864
  const nodes = doc.nodes;
@@ -1588,9 +1932,9 @@ var one = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1588
1932
  var MAX_SIBLINGS = 12;
1589
1933
  var MAX_LINES = 200;
1590
1934
  var MAX_EDGES = 6;
1591
- function tree(model, profile, opts) {
1592
- const fallbackLayer = profile.layers[0].id;
1593
- const layerOf = (n) => n.layer ?? fallbackLayer;
1935
+ function tree(model, opts) {
1936
+ const derived = deriveLayers(model);
1937
+ const layerOf = (n) => derived.layerOf.get(n.id);
1594
1938
  const labelOf = (id) => model.index.get(id)?.label ?? id;
1595
1939
  const depth = Math.max(1, opts.depth ?? 3);
1596
1940
  const perNode = Math.max(1, opts.perNode ?? MAX_SIBLINGS);
@@ -1624,7 +1968,9 @@ function tree(model, profile, opts) {
1624
1968
  for (const n of model.nodes) measure(n.id);
1625
1969
  const bySize = (a2, b) => (size.get(b.id) ?? 1) - (size.get(a2.id) ?? 1) || labelOf(a2.id).localeCompare(labelOf(b.id));
1626
1970
  const sorted = /* @__PURE__ */ new Map();
1627
- for (const [id, list] of kids) sorted.set(id, [...list].sort(bySize));
1971
+ for (const [id, list] of kids) {
1972
+ sorted.set(id, orderedChildren(kids, id) ?? [...list].sort(bySize));
1973
+ }
1628
1974
  const outgoing = /* @__PURE__ */ new Map();
1629
1975
  for (const e of model.edges) {
1630
1976
  if (!model.index.has(e.source) || !model.index.has(e.target)) continue;
@@ -1649,16 +1995,18 @@ function tree(model, profile, opts) {
1649
1995
  if (collapsed && tall > 0) bits.push(`${tall} deep`);
1650
1996
  if (edges.length) bits.push(edgeText(edges));
1651
1997
  const label = `${labelOf(node.id)}${broken(node) ? " (parent missing)" : ""}`;
1998
+ const orderTag = typeof node.order === "number" ? `[${node.order}] ` : "";
1652
1999
  entries.push({
1653
2000
  id: node.id,
1654
2001
  label,
1655
2002
  depth: level,
1656
2003
  layer: layerOf(node),
2004
+ ...typeof node.order === "number" ? { order: node.order } : {},
1657
2005
  nodes: inside,
1658
2006
  deep: tall,
1659
2007
  collapsed,
1660
2008
  edges,
1661
- text: `${prefix}${connector}${label}${bits.length ? ` ${bits.join(" \xB7 ")}` : ""}`
2009
+ text: `${prefix}${connector}${orderTag}${label}${bits.length ? ` ${bits.join(" \xB7 ")}` : ""}`
1662
2010
  });
1663
2011
  if (!canExpand) return;
1664
2012
  const shown = list.slice(0, perNode);
@@ -1681,7 +2029,7 @@ function tree(model, profile, opts) {
1681
2029
  }
1682
2030
  };
1683
2031
  const structure = structureOf(model);
1684
- let header = `${opts.title} ${one(structure.nodes, "node")} \xB7 ${one(structure.edges, "edge")} \xB7 ${one(structure.roots, "root")} \xB7 depth ${structure.depth}`;
2032
+ let header = `${opts.title} ${one(structure.nodes, "node")} \xB7 ${one(structure.edges, "edge")} \xB7 ${one(structure.roots, "root")} \xB7 depth ${structure.depth}${structure.layers ? ` \xB7 ${one(structure.layers, "layer")}` : ""} \xB7 isomorphism ${structure.isomorphism.toFixed(2)}`;
1685
2033
  const roots = model.nodes.filter((n) => !n.parent || broken(n));
1686
2034
  if (opts.path) {
1687
2035
  const start = model.index.get(opts.path);
@@ -1732,37 +2080,263 @@ function treeText(result) {
1732
2080
  return lines.join("\n");
1733
2081
  }
1734
2082
 
2083
+ // cli/restructure.ts
2084
+ function index(nodes) {
2085
+ const byId = new Map(nodes.map((n) => [n.id, n]));
2086
+ const children = /* @__PURE__ */ new Map();
2087
+ for (const n of nodes) {
2088
+ if (!n.parent || !byId.has(n.parent)) {
2089
+ n.parent = null;
2090
+ continue;
2091
+ }
2092
+ const arr = children.get(n.parent);
2093
+ arr ? arr.push(n.id) : children.set(n.parent, [n.id]);
2094
+ }
2095
+ const depth = /* @__PURE__ */ new Map();
2096
+ const walk2 = (id, seen) => {
2097
+ const hit = depth.get(id);
2098
+ if (hit != null) return hit;
2099
+ if (seen.has(id)) return 0;
2100
+ seen.add(id);
2101
+ const p = byId.get(id)?.parent;
2102
+ const d = p ? walk2(p, seen) + 1 : 0;
2103
+ depth.set(id, d);
2104
+ return d;
2105
+ };
2106
+ for (const n of nodes) walk2(n.id, /* @__PURE__ */ new Set());
2107
+ return { byId, children, depth };
2108
+ }
2109
+ function scoreOf(ctx) {
2110
+ const height = /* @__PURE__ */ new Map();
2111
+ const h = (id, seen = /* @__PURE__ */ new Set()) => {
2112
+ const hit = height.get(id);
2113
+ if (hit != null) return hit;
2114
+ if (seen.has(id)) return 0;
2115
+ seen.add(id);
2116
+ let v = 0;
2117
+ for (const k of ctx.children.get(id) ?? []) v = Math.max(v, h(k, seen) + 1);
2118
+ height.set(id, v);
2119
+ return v;
2120
+ };
2121
+ const nodeList = [...ctx.byId.values()];
2122
+ const model = { nodes: nodeList, edges: [], errors: [], index: ctx.byId };
2123
+ const kids = new Map([...ctx.children].map(([id, ids]) => [id, ids.map((k) => ctx.byId.get(k))]));
2124
+ return isomorphism(model, kids, (id) => h(id)).score;
2125
+ }
2126
+ function adoptFlat(nodes, byId, created, moves) {
2127
+ if (nodes.some((n) => n.parent)) return;
2128
+ const pathOf = (n) => {
2129
+ const sf = n.data.source_file;
2130
+ if (typeof sf === "string" && sf.includes("/")) return sf;
2131
+ if (n.id.includes("/")) return n.id.split("#")[0];
2132
+ return null;
2133
+ };
2134
+ if (!nodes.some((n) => pathOf(n))) return;
2135
+ const dirs = /* @__PURE__ */ new Map();
2136
+ const mkdir = (dir) => {
2137
+ if (!dir) return null;
2138
+ const hit = dirs.get(dir);
2139
+ if (hit) return hit;
2140
+ const parentDir = dir.includes("/") ? dir.slice(0, dir.lastIndexOf("/")) : "";
2141
+ const parent = mkdir(parentDir);
2142
+ const id = `dir:${dir}`;
2143
+ dirs.set(dir, id);
2144
+ created.push({ id, label: dir.slice(dir.lastIndexOf("/") + 1) || dir, kind: "folder", parent });
2145
+ byId.set(id, { id, label: dir.slice(dir.lastIndexOf("/") + 1) || dir, kind: "folder", parent, data: {} });
2146
+ return id;
2147
+ };
2148
+ for (const n of nodes) {
2149
+ const path3 = pathOf(n);
2150
+ if (!path3) continue;
2151
+ const slash = path3.lastIndexOf("/");
2152
+ const dir = slash < 0 ? "" : path3.slice(0, slash);
2153
+ const fileId = `file:${path3}`;
2154
+ if (!dirs.has(fileId)) {
2155
+ const parent = mkdir(dir);
2156
+ const fileLabel = path3.slice(slash + 1);
2157
+ created.push({ id: fileId, label: fileLabel, kind: "file", parent });
2158
+ byId.set(fileId, { id: fileId, label: fileLabel, kind: "file", parent, data: {} });
2159
+ dirs.set(fileId, fileId);
2160
+ }
2161
+ const before = n.parent;
2162
+ n.parent = fileId;
2163
+ moves.push({ id: n.id, from: before, to: fileId, why: `${path3}` });
2164
+ }
2165
+ }
2166
+ function attachByKind(ctx, wraps, moves) {
2167
+ const per = /* @__PURE__ */ new Map();
2168
+ for (const n of ctx.byId.values()) {
2169
+ if (!n.kind) continue;
2170
+ const hist = per.get(n.kind) ?? /* @__PURE__ */ new Map();
2171
+ const d = ctx.depth.get(n.id) ?? 0;
2172
+ hist.set(d, (hist.get(d) ?? 0) + 1);
2173
+ per.set(n.kind, hist);
2174
+ }
2175
+ const modal = /* @__PURE__ */ new Map();
2176
+ for (const [kind, hist] of per) {
2177
+ const total = [...hist.values()].reduce((a2, b) => a2 + b, 0);
2178
+ let best = 0;
2179
+ let bestCount = -1;
2180
+ for (const [d, c] of hist) if (c > bestCount || c === bestCount && d < best) {
2181
+ best = d;
2182
+ bestCount = c;
2183
+ }
2184
+ if (total >= 3 && bestCount / total >= 0.6) modal.set(kind, best);
2185
+ }
2186
+ const limit = Math.max(4, Math.floor(ctx.byId.size * 0.2));
2187
+ let changes = 0;
2188
+ for (const n of [...ctx.byId.values()]) {
2189
+ if (changes >= limit) break;
2190
+ if (!n.kind || !n.parent) continue;
2191
+ const target = modal.get(n.kind);
2192
+ if (target == null) continue;
2193
+ const here2 = ctx.depth.get(n.id) ?? 0;
2194
+ if (here2 === target) continue;
2195
+ if (here2 > target) {
2196
+ let up = n.parent;
2197
+ while (up && (ctx.depth.get(up) ?? 0) > target - 1) up = ctx.byId.get(up)?.parent ?? null;
2198
+ if (!up || up === n.parent || (ctx.depth.get(up) ?? 0) !== target - 1) continue;
2199
+ moves.push({ id: n.id, from: n.parent, to: up, why: `kind "${n.kind}" sits at depth ${target}` });
2200
+ n.parent = up;
2201
+ changes++;
2202
+ }
2203
+ }
2204
+ const rebuilt = index([...ctx.byId.values()]);
2205
+ ctx.children = rebuilt.children;
2206
+ ctx.depth = rebuilt.depth;
2207
+ }
2208
+ function ladderOf(ctx) {
2209
+ const per = /* @__PURE__ */ new Map();
2210
+ for (const n of ctx.byId.values()) {
2211
+ if (!n.kind) continue;
2212
+ const d = ctx.depth.get(n.id) ?? 0;
2213
+ const hist = per.get(n.kind) ?? /* @__PURE__ */ new Map();
2214
+ hist.set(d, (hist.get(d) ?? 0) + 1);
2215
+ per.set(n.kind, hist);
2216
+ }
2217
+ return [...per].map(([kind, hist]) => {
2218
+ const [depth, count2] = [...hist].sort((a2, b) => b[1] - a2[1] || a2[0] - b[0])[0];
2219
+ return { kind, depth, count: count2 };
2220
+ }).sort((a2, b) => a2.depth - b.depth || a2.kind.localeCompare(b.kind));
2221
+ }
2222
+ function singleRoot(ctx, created, moves) {
2223
+ const roots = [...ctx.byId.values()].filter((n) => !n.parent);
2224
+ if (roots.length < 2) return;
2225
+ const levels = /* @__PURE__ */ new Map();
2226
+ const tall = (id2, seen = /* @__PURE__ */ new Set()) => {
2227
+ const hit = levels.get(id2);
2228
+ if (hit != null) return hit;
2229
+ if (seen.has(id2)) return 0;
2230
+ seen.add(id2);
2231
+ let h = 0;
2232
+ for (const k of ctx.children.get(id2) ?? []) h = Math.max(h, tall(k, seen) + 1);
2233
+ levels.set(id2, h);
2234
+ return h;
2235
+ };
2236
+ const heights = roots.map((r) => tall(r.id));
2237
+ if (Math.max(...heights) - Math.min(...heights) > 1) return;
2238
+ let id = "root";
2239
+ for (let i = 2; ctx.byId.has(id); i++) id = `root-${i}`;
2240
+ const root = { id, label: "Overview", kind: "overview", parent: null, seq: -1, data: {} };
2241
+ ctx.byId.set(id, root);
2242
+ created.push({ id, label: "Overview", kind: "overview", parent: null });
2243
+ roots.forEach((n, i) => {
2244
+ moves.push({ id: n.id, from: null, to: id, why: "single root" });
2245
+ n.parent = id;
2246
+ n.order = i + 1;
2247
+ });
2248
+ const re = index([...ctx.byId.values()]);
2249
+ ctx.children = re.children;
2250
+ ctx.depth = re.depth;
2251
+ }
2252
+ function numberSiblings(ctx) {
2253
+ for (const [, kids] of ctx.children) {
2254
+ if (kids.length < 2) {
2255
+ for (const k of kids) delete ctx.byId.get(k).order;
2256
+ continue;
2257
+ }
2258
+ const list = kids.map((id) => ctx.byId.get(id)).sort((a2, b) => (a2.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || (a2.seq ?? Number.MAX_SAFE_INTEGER) - (b.seq ?? Number.MAX_SAFE_INTEGER) || a2.label.localeCompare(b.label));
2259
+ list.forEach((n, i) => {
2260
+ n.order = i + 1;
2261
+ });
2262
+ }
2263
+ }
2264
+ function restructure(nodes, edges) {
2265
+ const ctx = index(nodes);
2266
+ const before = scoreOf(ctx);
2267
+ const beforeFlat = !nodes.some((n) => n.parent);
2268
+ const created = [];
2269
+ const moves = [];
2270
+ const wraps = [];
2271
+ let note;
2272
+ adoptFlat([...ctx.byId.values()], ctx.byId, created, moves);
2273
+ if (!edges.length && !nodes.some((n) => n.parent)) note = "no parent anywhere and no path to build one from: give the nodes parents first";
2274
+ const re = index([...ctx.byId.values()]);
2275
+ ctx.children = re.children;
2276
+ ctx.depth = re.depth;
2277
+ const inferred = ladderOf(ctx);
2278
+ attachByKind(ctx, wraps, moves);
2279
+ singleRoot(ctx, created, moves);
2280
+ numberSiblings(ctx);
2281
+ const after = scoreOf(ctx);
2282
+ return { nodes: [...ctx.byId.values()], edges, moves, wraps, created, before, beforeFlat, after, ladder: inferred, note };
2283
+ }
2284
+ function planText(r, title) {
2285
+ const L = [];
2286
+ L.push(`${title}: isomorphism ${r.beforeFlat ? "flat" : r.before.toFixed(2)} \u2192 ${r.after.toFixed(2)}`);
2287
+ if (r.note) L.push(`note: ${r.note}`);
2288
+ if (r.ladder.length) L.push(`kinds \u2192 depth: ${r.ladder.map((l) => `${l.kind} ${l.depth} (${l.count})`).join(" \xB7 ")}`);
2289
+ if (r.created.length) L.push(`created ${r.created.length} container${r.created.length > 1 ? "s" : ""} (${r.created.slice(0, 4).map((c) => c.id).join(", ")}${r.created.length > 4 ? " \u2026" : ""})`);
2290
+ if (r.moves.length) L.push(`moved ${r.moves.length} node${r.moves.length > 1 ? "s" : ""}${r.wraps.length ? ` (${r.wraps.length} wrapped)` : ""}:`);
2291
+ for (const m of r.moves.slice(0, 8)) L.push(` ${m.id}: ${m.from ?? "(top)"} \u2192 ${m.to ?? "(top)"} ${m.why}`);
2292
+ if (r.moves.length > 8) L.push(` \u2026 ${r.moves.length - 8} more (--json)`);
2293
+ if (!r.moves.length && !r.created.length) L.push("nothing to move: the shape already matches the kinds");
2294
+ return L.join("\n");
2295
+ }
2296
+
1735
2297
  // cli/glassbrain.ts
1736
2298
  var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, written as plain JSON.
1737
2299
 
1738
2300
  [ THE THREE AXES ]
1739
2301
  Different things. Do not use one where another belongs.
1740
2302
  pass a snapshot in time \u2014 one folder per pass (1-skeleton/, 2-filled/)
1741
- parent containment \u2014 what sits inside what (see [ DATA ])
1742
- layer a plane in 2.5D \u2014 levels or parallel bands (see [ APPEARANCE ])
2303
+ parent containment \u2014 what sits inside what; every node has one
2304
+ order position among siblings \u2014 turns a set into a numbered list
1743
2305
 
1744
2306
  [ DATA ]
1745
2307
  Two arrays. The \`//\` notes are not part of the file: strip them and it is valid JSON
1746
2308
  (if validate says \`not JSON\`, a note survived the copy).
1747
2309
 
1748
2310
  { "nodes": [
1749
- { "id": "src", "label": "src", "kind": "folder" }, // required, stable, not a counter
2311
+ { "id": "src", "label": "src", "kind": "folder",
2312
+ "parent": null }, // the root: parent is null
1750
2313
  { "id": "src/login.ts", "label": "login.ts", "kind": "file",
1751
- "parent": "src", // top level: what it sits inside
1752
- "description": "Checks the password, then opens a session.", // markdown, from the source
1753
- "owner": "auth" }, // any other field: kept, shown
1754
- { "id": "src/db.ts", "label": "db.ts", "kind": "file", "parent": "src" } ],
2314
+ "parent": "src", "order": 1, // inside src, first
2315
+ "description": "Checks the password, then opens a session.", // markdown
2316
+ "owner": "auth" }, // any other field: kept, shown
2317
+ { "id": "src/db.ts", "label": "db.ts", "kind": "file",
2318
+ "parent": "src", "order": 2 } ],
1755
2319
  "edges": [
1756
2320
  { "source": "src/login.ts", "target": "src/db.ts", "kind": "uses" } ] }
1757
2321
 
1758
- \`parent\` is read only as a top-level field. Nested (\`data.parent\`) it is shown and
2322
+ \`parent\` is required on every node: a node id, or null for the root. One root per
2323
+ file. It is read only as a top-level field; nested (\`data.parent\`) it is shown and
1759
2324
  nothing else. \`kind\` gives the color; \`description\` is what the panel says.
1760
2325
 
1761
- SHAPE how a graph reads (validate names what is off)
1762
- one root per layer, every other node has a parent (warn: multiple-roots)
1763
- at most 8 node kinds and 10 edge kinds, each used 5+ (info: prefer-fewer-kinds)
1764
- a container with more than 30 children wants a level (info: flat-parent)
1765
- describe the leaves; under half described is noted (info: low-coverage)
2326
+ ORDER a numbered list, or no list at all
2327
+ The children of one parent either all carry \`order\` or none does, and no two
2328
+ share a number \u2014 a list is numbered, or it is a set. Values are floats, so 3.5
2329
+ inserts between 3 and 4. The layout reads them clockwise from the top.
2330
+ A root whose children are numbered opens the layer view: one floor per child.
2331
+ There is no layer field. Nothing to configure: write order, see floors.
2332
+
2333
+ SHAPE how a graph reads (validate measures each)
2334
+ 2\u20135 children per node; more than 10 is a wall (wide-node)
2335
+ children of one parent the same depth; 1.00 is perfect (uneven-branches)
2336
+ every kind used 5+ times, at most 8 node kinds (prefer-fewer-kinds)
2337
+ describe the leaves; under half described is noted (low-coverage)
2338
+ kind is optional; without it every node is drawn the same gray
2339
+ kind is optional; without it every node is drawn the same gray
1766
2340
 
1767
2341
  Full schema: ${schema}
1768
2342
 
@@ -1770,7 +2344,7 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
1770
2344
  A folder is a graph. Passes are optional; one numbered folder each.
1771
2345
 
1772
2346
  kg/
1773
- \u251C\u2500\u2500 _profile.json colors and layers, shared by every pass (see [ APPEARANCE ])
2347
+ \u251C\u2500\u2500 _profile.json colors, shared by every pass (see [ APPEARANCE ])
1774
2348
  \u251C\u2500\u2500 1-skeleton/graph.json a graph (see [ DATA ])
1775
2349
  \u251C\u2500\u2500 2-filled/graph.json each pass is the whole graph: copy the last, edit the copy
1776
2350
  \u2514\u2500\u2500 3-linked/graph.json then validate, and diff against the pass before
@@ -1785,17 +2359,12 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
1785
2359
  COLORS one entry per kind you use; unlisted kinds stay neutral.
1786
2360
  { "nodePalette": { "file": "#6366f1", "folder": "#94a3b8" },
1787
2361
  "edgePalette": { "uses": "#2563eb" } }
1788
- Colors that land in one brightness band read alike (validate notes it).
2362
+ Colors closer than 10 in Lab distance read as one kind (validate notes it).
1789
2363
 
1790
- LAYERS planes, not folders: \`parent\` is "sits inside", \`layer\` is "belongs to another
1791
- level of the same picture".
1792
- A node joins one with "layer"; missing means the first. 2-5 planes:
1793
- a code graph 1 data \xB7 2 API \xB7 3 interface
1794
- a topic graph 1 background \xB7 2 the thing \xB7 3 readings of it
1795
- Fewer when a plane holds one or two nodes; more than 5 stops being an outline.
1796
- { "layers": [ { "id": "api", "label": "API", "z": 0 },
1797
- { "id": "ui", "label": "UI", "z": 1 } ] }
1798
- Each plane is its own tree: a node's parent must be on the same layer (error).
2364
+ VIEW only the opening state; the page has the switches.
2365
+ { "appearance": { "defaultLayers": true } }
2366
+ Open with the 2.5D floors on. Without it the page opens flat and the layer
2367
+ control turns them on. A graph with no ordered root has one floor.
1799
2368
 
1800
2369
  Full schema: ${schema.replace("graph.schema", "profile.schema")}
1801
2370
 
@@ -1803,8 +2372,13 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
1803
2372
  Always validate before handing over; a page is only written for a graph with no errors.
1804
2373
 
1805
2374
  glassbrain <path> write one html page, print its path (passes play as steps)
2375
+ glassbrain view <path> the same page, spelled out (a path is required)
1806
2376
  glassbrain validate <path> errors, warnings, info; exit 1 on errors
1807
2377
  glassbrain tree <path> the containment tree as text
2378
+ glassbrain restructure <path> raise the shape score: re-hang and renumber; writes a
2379
+ new pass (a single file gets <name>.restructured.json).
2380
+ A flat graph gets a tree from source_file or ids with '/'.
2381
+ --dry-run prints the plan and writes nothing.
1808
2382
  glassbrain diff <old> <new> only what changed between two graphs
1809
2383
  glassbrain diff <git-ref> <path> the same graph at an earlier commit (default HEAD)
1810
2384
  glassbrain convert <path> [out-dir] write any supported format as glassbrain JSON
@@ -1812,20 +2386,23 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
1812
2386
  <path> is a file, a folder, or <git-ref>:<path> (HEAD~1:kg/graph.json). Graphify,
1813
2387
  Understand-Anything, memory.jsonl and markdown folders are read as-is.
1814
2388
 
1815
- validate speaks in three levels:
1816
- error broken schema, an id twice, a parent missing / on another layer / in a
1817
- cycle, an edge to a missing node, two files defining one id apart
1818
- warn discouraged several roots in one layer, one relation written twice
1819
- info distribution kinds, flat parents, empty leaves, layer count, color contrast
2389
+ validate speaks in three levels, and every line carries its repair:
2390
+ error broken schema, a missing/unknown parent, a cycle, a duplicate id,
2391
+ mixed or duplicate order, an edge to a missing node
2392
+ warn discouraged several roots in one file, one relation written twice,
2393
+ a node with more than 10 children, branches uneven in two
2394
+ or more places (one place is only info)
2395
+ info distribution kinds, order notes, empty leaves, color contrast
1820
2396
  exit codes: 0 clean \xB7 1 errors (--strict: warnings too) \xB7 2 usage.
1821
2397
  It always ends with the structure and the tree command for that graph.
1822
2398
 
1823
2399
  [ OPTIONS ]
1824
- --json machine-readable output (validate, tree, diff)
2400
+ --json machine-readable output (validate, tree, diff, restructure)
1825
2401
  --strict warnings fail too (validate, view)
1826
2402
  --depth <n> tree: levels to expand (default 3)
1827
2403
  --path <id> tree: one node, its ancestors and its subtree
1828
2404
  --orphans tree: only nodes with no parent
2405
+ --dry-run restructure: print the plan, write nothing
1829
2406
  --out <file.html> write the page here instead of a temp file (view, diff)
1830
2407
  --open / --no-open open the browser or not (diff opens only in a terminal)
1831
2408
  --exit-code exit 1 when anything changed (diff)
@@ -1833,16 +2410,10 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
1833
2410
  --ignore <a,b> fields that do not count as a change (diff)
1834
2411
  --format <id> force a format: native, graphify, understand-anything, memory, obsidian
1835
2412
  -h, --help / -v, --version this help / the version
1836
-
1837
- [ SKILLS ]
1838
- Optional fixed workflows (a codebase, docs into features):
1839
- https://github.com/voidixyn/glassbrain/tree/main/skills
1840
- npx skills add voidixyn/glassbrain
1841
- Help alone is enough to write, validate and read a graph.
1842
2413
  `;
1843
2414
  var VALUED = /* @__PURE__ */ new Set(["out", "format", "ignore", "depth", "path"]);
1844
- var SWITCHES = /* @__PURE__ */ new Set(["open", "json", "all", "exit-code", "strict", "help", "version", "orphans"]);
1845
- var COMMANDS = ["view", "diff", "validate", "convert", "tree"];
2415
+ var SWITCHES = /* @__PURE__ */ new Set(["open", "json", "all", "exit-code", "strict", "help", "version", "orphans", "dry-run"]);
2416
+ var COMMANDS = ["view", "diff", "validate", "convert", "tree", "restructure"];
1846
2417
  function parseArgs(argv) {
1847
2418
  const pos = [];
1848
2419
  const flags = {};
@@ -1896,7 +2467,10 @@ var tally = (found) => ({
1896
2467
  info: found.filter((f) => f.level === "info").length
1897
2468
  });
1898
2469
  function printFindings(found, limit = 40) {
1899
- for (const f of found.slice(0, limit)) console.log(`${TAG[f.level]} ${f.code} ${f.where} ${f.message}`);
2470
+ for (const f of found.slice(0, limit)) {
2471
+ console.log(`${TAG[f.level]} ${f.code} ${f.where} ${f.message}`);
2472
+ if (f.fix) console.log(f.fix.split("\n").map((l) => ` ${l}`).join("\n"));
2473
+ }
1900
2474
  if (found.length > limit) console.log(`\u2026 ${found.length - limit} more (--json)`);
1901
2475
  }
1902
2476
  var slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "graph";
@@ -1909,7 +2483,7 @@ function openFile(file) {
1909
2483
  }
1910
2484
  }
1911
2485
  var nodesOf = (l) => {
1912
- const profile = profileFromJson("cli", l.profile);
2486
+ const profile = profileOf(l);
1913
2487
  return l.versions.map((v) => modelOf(v, profile));
1914
2488
  };
1915
2489
  function notes(l, models) {
@@ -1960,7 +2534,7 @@ function runDiff(a2) {
1960
2534
  const before = load(oldSpec, { format });
1961
2535
  const after = load(newSpec, { format });
1962
2536
  const profileJson = after.profile ?? before.profile;
1963
- const profile = profileFromJson("cli", profileJson);
2537
+ const profile = profileOf(after);
1964
2538
  const pick = (l) => l.versions[l.versions.length - 1];
1965
2539
  const vb = pick(before);
1966
2540
  const va = pick(after);
@@ -2022,7 +2596,7 @@ function runValidate(a2) {
2022
2596
  if (found.length) console.log("");
2023
2597
  printFindings(found);
2024
2598
  console.log(`${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \xB7 ${count(n.info, "info")}`);
2025
- console.log(`structure: ${count(structure.roots, "root")} \xB7 depth ${structure.depth} \xB7 ${structure.parented}/${structure.nodes} parented`);
2599
+ console.log(`structure: ${count(structure.roots, "root")} \xB7 depth ${structure.depth}${structure.layers ? ` \xB7 ${count(structure.layers, "layer")}` : ""} \xB7 ${structure.parented}/${structure.nodes} parented \xB7 isomorphism ${structure.isomorphism.toFixed(2)}`);
2026
2600
  console.log(`tree: glassbrain tree ${a2.pos[0]} --depth=3`);
2027
2601
  if (l.ignored.length) process.stderr.write(`note: not read: ${l.ignored.slice(0, 5).join(", ")}${l.ignored.length > 5 ? ` and ${l.ignored.length - 5} more` : ""}
2028
2602
  `);
@@ -2038,7 +2612,7 @@ function runTree(a2) {
2038
2612
  notes(l, models);
2039
2613
  const latest = models[models.length - 1];
2040
2614
  const version = l.versions[l.versions.length - 1].name;
2041
- const result = tree(latest, profileFromJson("cli", l.profile), {
2615
+ const result = tree(latest, {
2042
2616
  title: l.versions.length > 1 ? `${l.title}/${version}` : l.title,
2043
2617
  depth,
2044
2618
  path: typeof a2.flags.path === "string" ? a2.flags.path : void 0,
@@ -2050,13 +2624,78 @@ function runTree(a2) {
2050
2624
  console.log(treeText(result));
2051
2625
  }
2052
2626
  }
2627
+ function runRestructure(a2) {
2628
+ if (a2.pos.length !== 1) fail("restructure needs exactly one <path>");
2629
+ const l = load(a2.pos[0], { format: a2.flags.format });
2630
+ const models = nodesOf(l);
2631
+ notes(l, models);
2632
+ const latest = models[models.length - 1];
2633
+ const phys = toPhysical(latest);
2634
+ const nodes = phys.nodes.map((n, seq) => ({
2635
+ id: String(n.id),
2636
+ label: String(n.label ?? n.id),
2637
+ kind: typeof n.kind === "string" ? n.kind : void 0,
2638
+ parent: n.parent === void 0 || n.parent === null ? null : String(n.parent),
2639
+ order: typeof n.order === "number" ? n.order : void 0,
2640
+ seq,
2641
+ data: n
2642
+ }));
2643
+ const edges = phys.edges.map((e) => ({
2644
+ source: String(e.source),
2645
+ target: String(e.target),
2646
+ ...typeof e.kind === "string" ? { kind: e.kind } : {},
2647
+ ...typeof e.label === "string" ? { label: e.label } : {},
2648
+ ...typeof e.weight === "number" ? { weight: e.weight } : {},
2649
+ data: e
2650
+ }));
2651
+ const plan = restructure(nodes, edges);
2652
+ if (a2.flags.json) {
2653
+ console.log(JSON.stringify({ before: plan.before, beforeFlat: plan.beforeFlat, after: plan.after, moves: plan.moves, wraps: plan.wraps, created: plan.created, ladder: plan.ladder, note: plan.note }, null, 1));
2654
+ if (a2.flags["dry-run"]) return;
2655
+ } else {
2656
+ console.log(planText(plan, l.title));
2657
+ if (a2.flags["dry-run"]) {
2658
+ console.log("\n(dry run: nothing written. Drop --dry-run to write a new pass.)");
2659
+ return;
2660
+ }
2661
+ }
2662
+ const outNodes = plan.nodes.map((p) => {
2663
+ const { parent: _p, order: _o, ...rest } = p.data ?? {};
2664
+ return {
2665
+ ...rest,
2666
+ id: p.id,
2667
+ label: p.label,
2668
+ ...p.kind ? { kind: p.kind } : {},
2669
+ parent: p.parent,
2670
+ ...p.order !== void 0 ? { order: p.order } : {}
2671
+ };
2672
+ });
2673
+ const graph = { name: l.title, nodes: outNodes, edges: phys.edges };
2674
+ const abs = path2.resolve(a2.pos[0]);
2675
+ const dir = fs2.existsSync(abs) && fs2.statSync(abs).isDirectory() ? abs : path2.dirname(abs);
2676
+ const passes = fs2.existsSync(dir) ? fs2.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => /^(\d+)-/.exec(e.name)?.[1]).filter(Boolean).map(Number) : [];
2677
+ let file;
2678
+ if (l.versions.length > 1 || passes.length) {
2679
+ const next = (passes.length ? Math.max(...passes) : 0) + 1;
2680
+ const passDir = path2.join(dir, `${next}-restructured`);
2681
+ fs2.mkdirSync(passDir, { recursive: true });
2682
+ if (l.profile) fs2.writeFileSync(path2.join(passDir, "_profile.json"), `${JSON.stringify(l.profile, null, 1)}
2683
+ `);
2684
+ file = path2.join(passDir, "graph.json");
2685
+ } else {
2686
+ file = path2.join(dir, `${path2.basename(abs, ".json") || "graph"}.restructured.json`);
2687
+ }
2688
+ fs2.writeFileSync(file, `${JSON.stringify(graph, null, 1)}
2689
+ `);
2690
+ console.log(`
2691
+ wrote ${file}`);
2692
+ console.log(`next: glassbrain diff ${a2.pos[0]} ${file}`);
2693
+ }
2053
2694
  function runConvert(a2) {
2054
2695
  if (a2.pos.length < 1 || a2.pos.length > 2) fail("convert needs <path> [out-dir]");
2055
2696
  const l = load(a2.pos[0], { format: a2.flags.format });
2056
2697
  const models = nodesOf(l);
2057
- const declared = Array.isArray(l.profile?.layers) && l.profile.layers.length > 0;
2058
- const strip = (g) => declared ? g : { ...g, nodes: g.nodes.map(({ layer: _l, ...n }) => n) };
2059
- const graphs = l.versions.map((v, i) => ({ name: v.name, graph: { name: v.name, ...strip(toPhysical(models[i])) } }));
2698
+ const graphs = l.versions.map((v, i) => ({ name: v.name, graph: { name: v.name, ...toPhysical(models[i]) } }));
2060
2699
  const outDir = a2.pos[1];
2061
2700
  if (!outDir) {
2062
2701
  if (graphs.length > 1) fail("several versions: give an out-dir");
@@ -2080,11 +2719,14 @@ var a = parseArgs(process.argv.slice(2));
2080
2719
  if (a.flags.version) {
2081
2720
  const pkg = JSON.parse(fs2.readFileSync(path2.join(here, "../../package.json"), "utf8"));
2082
2721
  console.log(pkg.version);
2083
- } else if (a.flags.help || a.cmd === "view" && !a.pos.length) {
2722
+ } else if (a.flags.help) {
2723
+ process.stdout.write(HELP(path2.join(here, "../../schema/graph.schema.json")));
2724
+ } else if (a.cmd === "view" && !a.pos.length) {
2725
+ if (process.argv.slice(2).includes("view")) fail("view needs exactly one <path>");
2084
2726
  process.stdout.write(HELP(path2.join(here, "../../schema/graph.schema.json")));
2085
2727
  } else {
2086
2728
  try {
2087
- ({ view, diff: runDiff, validate: runValidate, convert: runConvert, tree: runTree })[a.cmd](a);
2729
+ ({ view, diff: runDiff, validate: runValidate, convert: runConvert, tree: runTree, restructure: runRestructure })[a.cmd](a);
2088
2730
  } catch (e) {
2089
2731
  fail(e.message, 2);
2090
2732
  }