glassbrain 0.2.0-alpha.1 → 0.2.0-alpha.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.
@@ -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,9 @@ 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
+ // `parent` is always written, `null` for a root: dropping it (it was `undefined`) made every export invalid in 0.2.
136
+ nodes: model.nodes.map((n) => clean2({ ...n.data, id: n.id, label: n.label, kind: n.kind, parent: n.parent ?? null, order: n.order })),
134
137
  edges: model.edges.map((e) => clean2({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }))
135
138
  };
136
139
  }
@@ -241,7 +244,7 @@ var clean = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !==
241
244
  // adapters/graphify.ts
242
245
  var STRUCT = /* @__PURE__ */ new Set(["contains", "method"]);
243
246
  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);
247
+ 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
248
  var base = (p) => p.split("/").pop() ?? p;
246
249
  function convertGraphify(d, name) {
247
250
  const raw = d.nodes.filter(isObj);
@@ -315,7 +318,18 @@ function convertGraphify(d, name) {
315
318
  var score = (l) => typeof l.confidence_score === "number" ? l.confidence_score : typeof l.weight === "number" ? Math.min(1, l.weight) : void 0;
316
319
  var groupLabel = (t) => ({ concept: "Concepts", rationale: "Rationale", document: "Documents" })[t] ?? t;
317
320
  var PROFILE = {
318
- nodePalette: { symbol: "#6366f1", concept: "#e63b7a", rationale: "#f59e0b", document: "#0891b2", paper: "#0891b2", image: "#16a34a" },
321
+ // The adapter invents these three while building the folder / file boxes, so it must colour them too.
322
+ nodePalette: {
323
+ symbol: "#6366f1",
324
+ concept: "#e63b7a",
325
+ rationale: "#f59e0b",
326
+ document: "#0891b2",
327
+ paper: "#0891b2",
328
+ image: "#16a34a",
329
+ folder: "#94a3b8",
330
+ file: "#64748b",
331
+ group: "#a855f7"
332
+ },
319
333
  edgePalette: {
320
334
  calls: "#6366f1",
321
335
  imports: "#94a3b8",
@@ -530,7 +544,8 @@ var obsidian = {
530
544
  return {
531
545
  sources,
532
546
  profile: {
533
- nodePalette: autoPalette(kinds),
547
+ // `folder` is invented by the walk, not present in frontmatter kinds: colour it here.
548
+ nodePalette: { ...autoPalette(kinds), folder: "#94a3b8" },
534
549
  edgePalette: { link: "#94a3b8" },
535
550
  kindLabels: { folder: "Folder", note: "Note", link: "link" },
536
551
  detail: { line: [{ key: "path", label: "File" }], list: [{ key: "tags", label: "Tags" }] },
@@ -621,7 +636,10 @@ var PROFILE2 = {
621
636
  source: "#64748b",
622
637
  screen: "#0891b2",
623
638
  component: "#6366f1",
624
- token: "#f59e0b"
639
+ token: "#f59e0b",
640
+ layer: "#a855f7",
641
+ folder: "#94a3b8",
642
+ file: "#64748b"
625
643
  },
626
644
  edgePalette: {
627
645
  imports: "#94a3b8",
@@ -758,9 +776,23 @@ function gitSpec(spec, cwd) {
758
776
  return { files, title, isDir: true };
759
777
  }
760
778
  var META = /* @__PURE__ */ new Set(["_profile.json", "_layout.json"]);
779
+ function mergeProfile(base2, over) {
780
+ const pal = (a2, b) => ({ ...a2 && typeof a2 === "object" ? a2 : {}, ...b && typeof b === "object" ? b : {} });
781
+ return {
782
+ ...base2,
783
+ ...over,
784
+ nodePalette: pal(base2.nodePalette, over.nodePalette),
785
+ edgePalette: pal(base2.edgePalette, over.edgePalette),
786
+ kindLabels: pal(base2.kindLabels, over.kindLabels)
787
+ };
788
+ }
761
789
  var natural = (a2, b) => a2.localeCompare(b, void 0, { numeric: true });
762
790
  function load(spec, opts = {}) {
763
791
  const tree2 = readSpec(spec, opts.cwd);
792
+ if (!tree2.isDir) {
793
+ const beside = path.join(path.dirname(path.resolve(opts.cwd ?? process.cwd(), spec)), "_profile.json");
794
+ if (fs.existsSync(beside)) tree2.files.push({ path: "_profile.json", text: fs.readFileSync(beside, "utf8") });
795
+ }
764
796
  const metaErrors = [];
765
797
  const meta = (name) => {
766
798
  const f = tree2.files.find((x) => x.path === name);
@@ -772,6 +804,16 @@ function load(spec, opts = {}) {
772
804
  return null;
773
805
  }
774
806
  };
807
+ const bundled = () => {
808
+ if (tree2.isDir || tree2.files.length !== 1) return null;
809
+ try {
810
+ const d = JSON.parse(tree2.files[0].text);
811
+ return d && typeof d === "object" && d.profile && typeof d.profile === "object" ? d.profile : null;
812
+ } catch {
813
+ return null;
814
+ }
815
+ };
816
+ const explicit = meta("_profile.json") ?? bundled();
775
817
  const data = tree2.files.filter((f) => !META.has(f.path));
776
818
  const isJson = (f) => /\.json$/i.test(f.path);
777
819
  const dirs = [...new Set(data.filter((f) => f.path.includes("/")).map((f) => f.path.split("/")[0]))].sort(natural);
@@ -792,7 +834,9 @@ function load(spec, opts = {}) {
792
834
  return {
793
835
  title: tree2.title,
794
836
  versions,
795
- profile: meta("_profile.json") ?? suggested,
837
+ // A `_profile.json` that only carries demo metadata used to *replace* the adapter's profile, taking its palette
838
+ // with it: a converted graph then drew every kind as skeleton. Explicit keys win; the adapter fills the rest.
839
+ profile: explicit && suggested ? mergeProfile(suggested, explicit) : explicit ?? suggested,
796
840
  layouts: meta("_layout.json"),
797
841
  format,
798
842
  metaErrors,
@@ -980,12 +1024,69 @@ function diffModels(before, after, opts = {}) {
980
1024
  };
981
1025
  }
982
1026
 
1027
+ // src/layers.ts
1028
+ var MAX_DERIVED_LAYERS = 8;
1029
+ var EMPTY = { layers: [], layerOf: /* @__PURE__ */ new Map() };
1030
+ function orderedChildren(children, id) {
1031
+ const kids = children.get(id) ?? [];
1032
+ if (kids.length < 2) return null;
1033
+ const withOrder = kids.filter((n) => typeof n.order === "number" && Number.isFinite(n.order));
1034
+ if (withOrder.length !== kids.length) return null;
1035
+ const seen = /* @__PURE__ */ new Set();
1036
+ for (const k of withOrder) {
1037
+ if (seen.has(k.order)) return null;
1038
+ seen.add(k.order);
1039
+ }
1040
+ return [...kids].sort((a2, b) => a2.order - b.order);
1041
+ }
1042
+ function childrenMap(model) {
1043
+ const out = /* @__PURE__ */ new Map();
1044
+ for (const n of model.nodes) {
1045
+ if (!n.parent || !model.index.has(n.parent)) continue;
1046
+ const arr = out.get(n.parent);
1047
+ arr ? arr.push(n) : out.set(n.parent, [n]);
1048
+ }
1049
+ return out;
1050
+ }
1051
+ function deriveLayers(model, colors = [], force = false) {
1052
+ if (!model.nodes.length) return EMPTY;
1053
+ const children = childrenMap(model);
1054
+ const roots = model.nodes.filter((n) => !n.parent || !model.index.has(n.parent));
1055
+ let ordered = null;
1056
+ let anchor;
1057
+ if (roots.length === 1) {
1058
+ anchor = roots[0];
1059
+ ordered = orderedChildren(children, anchor.id);
1060
+ if (!ordered && force) ordered = children.get(anchor.id) ?? null;
1061
+ } else if (force && roots.length > 1) {
1062
+ ordered = roots;
1063
+ }
1064
+ if (!ordered || ordered.length < 2 || ordered.length > MAX_DERIVED_LAYERS) return EMPTY;
1065
+ const layers = ordered.map((n, i) => ({
1066
+ id: n.id,
1067
+ label: n.label || n.id,
1068
+ z: i,
1069
+ ...colors[i] ? { color: colors[i] } : {}
1070
+ }));
1071
+ const layerOf = /* @__PURE__ */ new Map();
1072
+ for (const [i, layer] of ordered.entries()) {
1073
+ const stack = [layer.id];
1074
+ while (stack.length) {
1075
+ const id = stack.pop();
1076
+ layerOf.set(id, layers[i].id);
1077
+ for (const k of children.get(id) ?? []) stack.push(k.id);
1078
+ }
1079
+ }
1080
+ if (anchor) layerOf.set(anchor.id, layers[0].id);
1081
+ return { layers, layerOf, anchor: anchor?.id };
1082
+ }
1083
+
983
1084
  // schema/graph.schema.json
984
1085
  var graph_schema_default = {
985
1086
  $schema: "https://json-schema.org/draft/2020-12/schema",
986
1087
  $id: "https://unpkg.com/glassbrain/schema/graph.schema.json",
987
1088
  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.",
1089
+ 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
1090
  type: "object",
990
1091
  anyOf: [{ required: ["nodes"] }, { required: ["edges"] }],
991
1092
  properties: {
@@ -1003,14 +1104,14 @@ var graph_schema_default = {
1003
1104
  $defs: {
1004
1105
  node: {
1005
1106
  type: "object",
1006
- required: ["id"],
1107
+ required: ["id", "parent"],
1007
1108
  properties: {
1008
1109
  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
1110
  label: { type: "string", description: "Display name. Falls back to `name`, then `id`." },
1010
1111
  name: { type: "string", description: "Alias of `label`." },
1011
1112
  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." },
1113
+ 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." },
1114
+ 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
1115
  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
1116
  description: { type: "string", description: "Markdown shown in the detail panel. `[text](node:<id>)` links jump to another node." }
1016
1117
  },
@@ -1041,57 +1142,129 @@ var profile_schema_default = {
1041
1142
  $schema: "https://json-schema.org/draft/2020-12/schema",
1042
1143
  $id: "https://unpkg.com/glassbrain/schema/profile.schema.json",
1043
1144
  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.",
1145
+ 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
1146
  type: "object",
1046
1147
  properties: {
1047
- layers: {
1148
+ nodePalette: {
1149
+ $ref: "#/$defs/colors",
1150
+ description: "Node kind \u2192 color. Kinds not listed are skeleton."
1151
+ },
1152
+ edgePalette: {
1153
+ $ref: "#/$defs/colors",
1154
+ description: "Edge kind \u2192 color."
1155
+ },
1156
+ nodeSize: {
1157
+ $ref: "#/$defs/numbers",
1158
+ description: "Node kind \u2192 size multiplier (1 = default)."
1159
+ },
1160
+ edgeWidth: {
1161
+ $ref: "#/$defs/numbers",
1162
+ description: "Edge kind \u2192 width multiplier."
1163
+ },
1164
+ placeholderFlags: {
1048
1165
  type: "array",
1049
- description: "Layers for the 2.5D plane view. One default layer if omitted.",
1050
1166
  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." }
1167
+ type: "string"
1168
+ },
1169
+ description: "Nodes with any of these flags are drawn as placeholders (declared, not yet filled)."
1170
+ },
1171
+ kindLabels: {
1172
+ $ref: "#/$defs/strings",
1173
+ description: "Kind \u2192 human-readable name (nodes and edges share this map)."
1174
+ },
1175
+ edgeLabels: {
1176
+ $ref: "#/$defs/strings",
1177
+ description: "Same as kindLabels, for edge kinds; merged into it."
1178
+ },
1179
+ appearance: {
1180
+ type: "object",
1181
+ description: "View defaults only. Layers themselves are derived from the graph: a run of ordered siblings is one layer.",
1182
+ properties: {
1183
+ defaultLayers: {
1184
+ type: "boolean",
1185
+ description: "Open with the layer (2.5D plane) view on when the graph has ordered siblings. Default false."
1186
+ },
1187
+ layerColors: {
1188
+ type: "array",
1189
+ items: {
1190
+ type: "string"
1191
+ },
1192
+ description: "Hue per layer, in order. Defaults to the theme's palette."
1059
1193
  }
1060
1194
  }
1061
1195
  },
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." },
1196
+ style: {
1197
+ type: "array",
1198
+ description: "Extra cytoscape style rules, appended after the base style."
1199
+ },
1070
1200
  detail: {
1071
1201
  type: "object",
1072
1202
  description: "Detail panel field tables.",
1073
1203
  properties: {
1074
- line: { $ref: "#/$defs/fields" },
1075
- list: { $ref: "#/$defs/fields" },
1076
- skip: { type: "array", items: { type: "string" } },
1077
- flagNotes: { $ref: "#/$defs/strings" }
1204
+ line: {
1205
+ $ref: "#/$defs/fields"
1206
+ },
1207
+ list: {
1208
+ $ref: "#/$defs/fields"
1209
+ },
1210
+ skip: {
1211
+ type: "array",
1212
+ items: {
1213
+ type: "string"
1214
+ }
1215
+ },
1216
+ flagNotes: {
1217
+ $ref: "#/$defs/strings"
1218
+ }
1078
1219
  }
1079
1220
  },
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." }
1221
+ rootLabel: {
1222
+ type: "string"
1223
+ },
1224
+ diffIgnore: {
1225
+ type: "array",
1226
+ items: {
1227
+ type: "string"
1228
+ },
1229
+ 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."
1230
+ }
1083
1231
  },
1084
1232
  additionalProperties: true,
1085
1233
  $defs: {
1086
- colors: { type: "object", additionalProperties: { type: "string" } },
1087
- numbers: { type: "object", additionalProperties: { type: "number" } },
1088
- strings: { type: "object", additionalProperties: { type: "string" } },
1234
+ colors: {
1235
+ type: "object",
1236
+ additionalProperties: {
1237
+ type: "string"
1238
+ }
1239
+ },
1240
+ numbers: {
1241
+ type: "object",
1242
+ additionalProperties: {
1243
+ type: "number"
1244
+ }
1245
+ },
1246
+ strings: {
1247
+ type: "object",
1248
+ additionalProperties: {
1249
+ type: "string"
1250
+ }
1251
+ },
1089
1252
  fields: {
1090
1253
  type: "array",
1091
1254
  items: {
1092
1255
  type: "object",
1093
- required: ["key", "label"],
1094
- properties: { key: { type: "string" }, label: { type: "string" } }
1256
+ required: [
1257
+ "key",
1258
+ "label"
1259
+ ],
1260
+ properties: {
1261
+ key: {
1262
+ type: "string"
1263
+ },
1264
+ label: {
1265
+ type: "string"
1266
+ }
1267
+ }
1095
1268
  }
1096
1269
  }
1097
1270
  }
@@ -1112,7 +1285,8 @@ var KNOWN = /* @__PURE__ */ new Set([
1112
1285
  "anyOf",
1113
1286
  "$ref",
1114
1287
  "minimum",
1115
- "maximum"
1288
+ "maximum",
1289
+ "exclusiveMinimum"
1116
1290
  ]);
1117
1291
  var typeOf = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v === "number" ? Number.isInteger(v) ? "integer" : "number" : typeof v;
1118
1292
  var fits = (v, t) => {
@@ -1153,6 +1327,7 @@ function checkSchema(root, value, limit = 50) {
1153
1327
  if (typeof v === "number") {
1154
1328
  if (s.minimum != null && v < s.minimum) out2.push({ path: path3, message: `must be \u2265 ${s.minimum}` });
1155
1329
  if (s.maximum != null && v > s.maximum) out2.push({ path: path3, message: `must be \u2264 ${s.maximum}` });
1330
+ if (s.exclusiveMinimum != null && v <= s.exclusiveMinimum) out2.push({ path: path3, message: `must be > ${s.exclusiveMinimum}` });
1156
1331
  }
1157
1332
  };
1158
1333
  const out = [];
@@ -1161,6 +1336,9 @@ function checkSchema(root, value, limit = 50) {
1161
1336
  }
1162
1337
 
1163
1338
  // cli/checks.ts
1339
+ var ISOMORPHISM_TAU = 0.85;
1340
+ var WIDE_INFO = 5;
1341
+ var WIDE_WARN = 10;
1164
1342
  var MAX_NAMES = 4;
1165
1343
  var MIN_SAMPLE = 10;
1166
1344
  var names = (xs) => `${xs.slice(0, MAX_NAMES).join(", ")}${xs.length > MAX_NAMES ? ` and ${xs.length - MAX_NAMES} more` : ""}`;
@@ -1168,27 +1346,51 @@ var misplacedField = {
1168
1346
  code: "misplaced-field",
1169
1347
  level: "error",
1170
1348
  run: ({ model }) => {
1171
- const reserved = ["id", "label", "kind", "parent", "layer", "description"];
1349
+ const reserved = ["id", "label", "kind", "parent", "order", "description"];
1172
1350
  const out = [];
1173
1351
  for (const n of model.nodes) {
1174
1352
  const nested = n.data?.data;
1175
1353
  if (!nested || typeof nested !== "object" || Array.isArray(nested)) continue;
1176
1354
  const found = reserved.filter((k) => k in nested);
1177
1355
  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` });
1356
+ out.push({
1357
+ node: n.id,
1358
+ message: `"${n.id}" keeps ${found.map((k) => `"${k}"`).join(", ")} under "data"; only top-level fields are read`,
1359
+ fix: `move ${found.length > 1 ? "them" : "it"} up one level, next to "id":
1360
+ - { "id": "${n.id}", "data": { ${found.map((k) => `"${k}": \u2026`).join(", ")} } }
1361
+ + { "id": "${n.id}", ${found.map((k) => `"${k}": \u2026`).join(", ")} }`
1362
+ });
1179
1363
  }
1180
1364
  return out;
1181
1365
  }
1182
1366
  };
1183
- var missingParent = {
1184
- code: "missing-parent",
1367
+ var layerField = {
1368
+ code: "layer-field",
1185
1369
  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` }))
1370
+ run: ({ model }) => model.nodes.filter((n) => n.data && typeof n.data === "object" && "layer" in n.data).map((n) => ({
1371
+ node: n.id,
1372
+ message: `"${n.id}" still carries "layer": layers are not written any more, they are derived from "order"`,
1373
+ fix: `delete the field. To make the graph read as floors, give one node's children "order" instead:
1374
+ - { "id": "${n.id}", "parent": "\u2026", "layer": "${n.layer}" }
1375
+ + { "id": "${n.id}", "parent": "\u2026", "order": 2 }`
1376
+ }))
1377
+ };
1378
+ var unknownParent = {
1379
+ code: "unknown-parent",
1380
+ level: "error",
1381
+ run: ({ model, index: index2, labelOf }) => model.nodes.filter((n) => n.parent && !index2.has(n.parent)).map((n) => ({
1382
+ node: n.id,
1383
+ message: `"${n.id}" sits inside "${n.parent}", which does not exist`,
1384
+ fix: `point it at a node that exists (one of: ${[...index2.keys()].slice(0, 3).map((id) => `"${id}"`).join(", ")}), or add "${n.parent}":
1385
+ - "parent": "${n.parent}"
1386
+ + "parent": "${[...index2.keys()][0] ?? "EXISTING_ID"}"
1387
+ ("parent": null also works, but it makes another top-level tree, which validate warns about.)`
1388
+ }))
1187
1389
  };
1188
1390
  var parentCycle = {
1189
1391
  code: "parent-cycle",
1190
1392
  level: "error",
1191
- run: ({ model, index }) => {
1393
+ run: ({ model, index: index2 }) => {
1192
1394
  const out = [];
1193
1395
  const done = /* @__PURE__ */ new Set();
1194
1396
  for (const start of model.nodes) {
@@ -1201,41 +1403,68 @@ var parentCycle = {
1201
1403
  if (seen !== void 0) {
1202
1404
  const loop = path3.slice(seen);
1203
1405
  loop.forEach((id) => done.add(id));
1204
- out.push({ node: cur, message: `parent cycle: ${[...loop, cur].join(" \u2192 ")}` });
1406
+ out.push({
1407
+ node: cur,
1408
+ message: `parent cycle: ${[...loop, cur].join(" \u2192 ")}`,
1409
+ fix: `a node cannot sit inside itself. Pick the one that should be the top of the loop and give it "parent": null:
1410
+ - { "id": "${loop[0]}", "parent": "${cur}" }
1411
+ + { "id": "${loop[0]}", "parent": null }`
1412
+ });
1205
1413
  break;
1206
1414
  }
1207
1415
  at.set(cur, path3.length);
1208
1416
  path3.push(cur);
1209
- const parent = index.get(cur)?.parent;
1210
- cur = parent && index.has(parent) ? parent : void 0;
1417
+ const parent = index2.get(cur)?.parent;
1418
+ cur = parent && index2.has(parent) ? parent : void 0;
1211
1419
  }
1212
1420
  for (const id of path3) done.add(id);
1213
1421
  }
1214
1422
  return out;
1215
1423
  }
1216
1424
  };
1217
- var unknownLayer = {
1218
- code: "unknown-layer",
1425
+ var orderMixed = {
1426
+ code: "order-mixed",
1219
1427
  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(", ")})` }));
1428
+ run: ({ children }) => {
1429
+ const out = [];
1430
+ for (const [parent, kids] of children) {
1431
+ const withOrder = kids.filter((k) => typeof k.order === "number").length;
1432
+ if (withOrder === 0 || withOrder === kids.length) continue;
1433
+ const missing = kids.filter((k) => typeof k.order !== "number").slice(0, 3);
1434
+ const next = Math.max(0, ...kids.map((k) => typeof k.order === "number" ? k.order : 0)) + 1;
1435
+ out.push({
1436
+ node: parent,
1437
+ message: `${withOrder} of ${kids.length} children of "${parent}" have "order"; a numbered list numbers every item`,
1438
+ fix: `give the rest an order, or take them all away (then the order is whatever the layout finds):
1439
+ ${missing.map((k, i) => ` - { "id": "${k.id}", "parent": "${parent}" }
1440
+ + { "id": "${k.id}", "parent": "${parent}", "order": ${next + i} }`).join("\n")}`
1441
+ });
1442
+ }
1443
+ return out;
1224
1444
  }
1225
1445
  };
1226
- var crossLayerParent = {
1227
- code: "cross-layer-parent",
1446
+ var orderDuplicate = {
1447
+ code: "order-duplicate",
1228
1448
  level: "error",
1229
- run: ({ model, index, layerOf }) => {
1449
+ run: ({ children }) => {
1230
1450
  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
- });
1451
+ for (const [parent, kids] of children) {
1452
+ const seen = /* @__PURE__ */ new Map();
1453
+ for (const k of kids) {
1454
+ if (typeof k.order !== "number") continue;
1455
+ const arr = seen.get(k.order);
1456
+ arr ? arr.push(k) : seen.set(k.order, [k]);
1457
+ }
1458
+ for (const [value, same] of seen) {
1459
+ if (same.length < 2) continue;
1460
+ out.push({
1461
+ node: parent,
1462
+ message: `"${parent}" has ${same.length} children at order ${value} (${names(same.map((n) => n.id))}); two items cannot share a place`,
1463
+ fix: `spread them. Fractions are allowed, so nothing else has to move:
1464
+ ${same.slice(1).map((k, i) => ` - { "id": "${k.id}", "order": ${value} }
1465
+ + { "id": "${k.id}", "order": ${value + (i + 1) / 10} }`).join("\n")}`
1466
+ });
1467
+ }
1239
1468
  }
1240
1469
  return out;
1241
1470
  }
@@ -1243,19 +1472,27 @@ var crossLayerParent = {
1243
1472
  var conflictingDefinition = {
1244
1473
  code: "conflicting-definition",
1245
1474
  level: "error",
1246
- run: ({ model, index, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1475
+ run: ({ model, index: index2, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1247
1476
  node: id,
1248
- message: `"${id}" is defined differently in ${names(index.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`
1477
+ message: `"${id}" is defined differently in ${names(index2.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`,
1478
+ fix: `one id is one thing. Either make the copies identical, or give one a new id and point its edges at that:
1479
+ ${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
1480
  }))
1250
1481
  };
1251
1482
  var danglingEdge = {
1252
1483
  code: "dangling-edge",
1253
1484
  level: "error",
1254
- run: ({ model, index }) => {
1485
+ run: ({ model, index: index2, labelOf }) => {
1255
1486
  const out = [];
1256
1487
  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}` });
1488
+ const missing = [!index2.has(e.source) && e.source, !index2.has(e.target) && e.target].filter(Boolean).join(" / ");
1489
+ if (!missing) continue;
1490
+ out.push({
1491
+ message: `edge ${e.source} \u2192 ${e.target}${e.kind ? ` (${e.kind})` : ""} points at the missing node ${missing}`,
1492
+ fix: `an edge can only join nodes that exist. Add the node, or repoint the edge:
1493
+ - { "source": "${e.source}", "target": "${e.target}" }
1494
+ + { "source": "${index2.has(e.source) ? e.source : labelOf(e.target) || e.source}", "target": "${index2.has(e.target) ? e.target : "EXISTING_ID"}" }`
1495
+ });
1259
1496
  }
1260
1497
  return out;
1261
1498
  }
@@ -1273,7 +1510,11 @@ var duplicateEdge = {
1273
1510
  for (const [key, count2] of times) {
1274
1511
  if (count2 < 2) continue;
1275
1512
  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` });
1513
+ out.push({
1514
+ message: `edge ${source} \u2192 ${target}${kind ? ` (${kind})` : ""} is written ${count2} times; it is drawn once`,
1515
+ fix: `delete ${count2 - 1} of the copies; the file should hold this line once:
1516
+ { "source": "${source}", "target": "${target}"${kind ? `, "kind": "${kind}"` : ""} }`
1517
+ });
1277
1518
  }
1278
1519
  return out;
1279
1520
  }
@@ -1281,26 +1522,144 @@ var duplicateEdge = {
1281
1522
  var multipleRoots = {
1282
1523
  code: "multiple-roots",
1283
1524
  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]);
1525
+ run: ({ model }) => {
1526
+ const roots = model.nodes.filter((n) => n.parent == null);
1527
+ if (roots.length < 2) return [];
1528
+ return [{
1529
+ message: `${roots.length} top-level nodes (${names(roots.map((n) => n.label || n.id))}); it reads as ${roots.length} separate trees, not one`,
1530
+ fix: `one file, one tree: add a root and hang them under it. A root is a real node, so give it a label:
1531
+ + { "id": "root", "label": "${model.nodes.find((n) => !n.parent)?.label ?? "Overview"}", "kind": "overview", "parent": null }
1532
+ ${roots.slice(0, 3).map((n, i) => `- { "id": "${n.id}", "parent": null }
1533
+ + { "id": "${n.id}", "parent": "root", "order": ${i + 1} }`).join("\n ")}
1534
+ (ordered children of one root also become the layer view.) Or split the file in two, one tree each.`
1535
+ }];
1536
+ }
1537
+ };
1538
+ var noHierarchy = {
1539
+ code: "no-hierarchy",
1540
+ level: "warn",
1541
+ run: ({ model }) => {
1542
+ if (!model.nodes.length || model.nodes.some((n) => n.parent)) return [];
1543
+ return [{
1544
+ message: `${model.nodes.length} nodes and no parent anywhere: flat, so there is no outline to read`,
1545
+ fix: `give every node a parent (or null for the one root). If the ids carry the folders, grouping by prefix is enough:
1546
+ - { "id": "flask/app.py", "parent": null }
1547
+ + { "id": "flask/app.py", "parent": "flask" }
1548
+ or run: glassbrain restructure <path>`
1549
+ }];
1550
+ }
1551
+ };
1552
+ function isomorphism(model, children, heightOf) {
1553
+ let logSum = 0;
1554
+ let parents = 0;
1555
+ const uneven = [];
1556
+ for (const [id, kids] of children) {
1557
+ if (kids.length < 2) continue;
1558
+ const count2 = /* @__PURE__ */ new Map();
1559
+ for (const k of kids) {
1560
+ const h = heightOf(k.id);
1561
+ count2.set(h, (count2.get(h) ?? 0) + 1);
1292
1562
  }
1563
+ const q = Math.max(...count2.values()) / kids.length;
1564
+ logSum += Math.log(q);
1565
+ parents++;
1566
+ if (q < 1) uneven.push({ id, q, kids: kids.length });
1567
+ }
1568
+ uneven.sort((a2, b) => a2.q - b.q || b.kids - a2.kids);
1569
+ return { score: parents ? Math.exp(logSum / parents) : 1, parents, uneven };
1570
+ }
1571
+ function unevenFix(ctx, worst) {
1572
+ const kids = [...ctx.children.get(worst.id) ?? []].sort((a2, b) => ctx.heightOf(a2.id) - ctx.heightOf(b.id));
1573
+ const short = kids[0];
1574
+ const deep = kids[kids.length - 1];
1575
+ const m = ctx.heightOf(deep.id);
1576
+ const shallow = ctx.heightOf(short.id);
1577
+ const leaf = ctx.children.get(short.id)?.length ? "" : " (it is a leaf: it needs a child, or the deep branch needs one less level)";
1578
+ return [
1579
+ `same parent, same depth. Under "${ctx.labelOf(worst.id)}" (${worst.kids} children, ${Math.round(worst.q * 100)}% are ${m} deep):`,
1580
+ ` \u2717 ${worst.id}`,
1581
+ ` \u251C\u2500 ${short.id} ${shallow} deep${leaf}`,
1582
+ ` \u2514\u2500 ${deep.id} ${m} deep`,
1583
+ ` \u2713 both ${m} deep: give ${short.id} one more real level, or lift ${deep.id}'s children up one level.`,
1584
+ ` Do not invent an empty group just to pad the depth \u2014 move the branch instead.`,
1585
+ `or let the tool do all of them: glassbrain restructure <path>`
1586
+ ].join("\n");
1587
+ }
1588
+ var unevenBranches = {
1589
+ code: "uneven-branches",
1590
+ level: "warn",
1591
+ run: (ctx) => {
1592
+ const { score: score2, parents, uneven } = isomorphism(ctx.model, ctx.children, ctx.heightOf);
1593
+ if (!parents || score2 >= 1) return [];
1594
+ const worst = uneven[0];
1595
+ const level = score2 < ISOMORPHISM_TAU && uneven.length >= 2 ? "warn" : "info";
1596
+ 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`;
1597
+ return [{
1598
+ level,
1599
+ message: worst ? `${line}; worst: ${ctx.labelOf(worst.id)} (${worst.kids} children)` : line,
1600
+ fix: worst ? unevenFix(ctx, worst) : void 0,
1601
+ ...worst ? { node: worst.id } : {}
1602
+ }];
1603
+ }
1604
+ };
1605
+ var wideNode = {
1606
+ code: "wide-node",
1607
+ level: "warn",
1608
+ run: ({ children, labelOf, layers }) => {
1293
1609
  const out = [];
1294
- for (const [layer, nodes] of tops) {
1295
- if (nodes.length < 2) continue;
1610
+ for (const [id, kids] of children) {
1611
+ const n = kids.length;
1612
+ if (n <= WIDE_INFO) continue;
1613
+ const level = n > WIDE_WARN ? "warn" : "info";
1614
+ const isAnchor = layers.anchor === id;
1615
+ const what = isAnchor ? `${n} layers` : `${n} children`;
1296
1616
  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`
1617
+ level,
1618
+ node: id,
1619
+ message: `"${labelOf(id)}" holds ${what}; ${isAnchor ? "2\u20134 layers read best" : `more than ${WIDE_INFO} wants another level of grouping`}`,
1620
+ fix: isAnchor ? `fewer floors, or group the extras under one of them:
1621
+ ${kids.slice(4, 6).map((k, i) => `- { "id": "${k.id}", "parent": "${id}", "order": ${5 + i} }
1622
+ + { "id": "more", "parent": "${id}", "order": 5 }
1623
+ + { "id": "${k.id}", "parent": "more", "order": ${i + 1} }`).join("\n ")}` : `add one grouping node between:
1624
+ - { "id": "${kids[0].id}", "parent": "${id}" }
1625
+ + { "id": "${id}/group", "parent": "${id}" }
1626
+ + { "id": "${kids[0].id}", "parent": "${id}/group" }`
1299
1627
  });
1300
1628
  }
1301
1629
  return out;
1302
1630
  }
1303
1631
  };
1632
+ var uncoloredKind = {
1633
+ code: "uncolored-kind",
1634
+ level: "error",
1635
+ run: ({ model, profile }) => {
1636
+ const used = [...new Set(model.nodes.map((n) => n.kind).filter((k) => !!k))];
1637
+ const missing = used.filter((k) => !(k in profile.nodePalette));
1638
+ if (!missing.length) return [];
1639
+ const shown = missing.slice(0, 5);
1640
+ const palette = Object.fromEntries(shown.map((k, i) => [k, ["#6366f1", "#f59e0b", "#10b981", "#ef4444", "#8b5cf6"][i % 5]]));
1641
+ return [{
1642
+ message: `${missing.length} node kind${missing.length > 1 ? "s are" : " is"} not in nodePalette, so ${missing.length > 1 ? "they are" : "it is"} drawn as skeleton: ${names(missing)}`,
1643
+ fix: `add one colour per kind to _profile.json (one entry per kind, not per node):
1644
+ { "nodePalette": ${JSON.stringify(palette)} }
1645
+ ${missing.length > shown.length ? ` \u2026 and ${missing.length - shown.length} more; every kind in the data needs an entry.
1646
+ ` : ""} Colors that land closer than 10 in Lab distance read as one kind (validate notes it).`
1647
+ }];
1648
+ }
1649
+ };
1650
+ var singleKind = {
1651
+ code: "single-kind",
1652
+ level: "warn",
1653
+ run: ({ model }) => {
1654
+ const used = new Set(model.nodes.map((n) => n.kind).filter(Boolean));
1655
+ if (used.size !== 1 || model.nodes.length < MIN_SAMPLE) return [];
1656
+ return [{
1657
+ message: `every node has kind "${[...used][0]}"; a single kind tells the reader nothing about what differs`,
1658
+ fix: `split it by what the node is for. The palette only shows differences it has a colour for:
1659
+ { "nodePalette": { "${[...used][0]}": "#6366f1", "concept": "#f59e0b", "person": "#10b981" } }`
1660
+ }];
1661
+ }
1662
+ };
1304
1663
  var preferFewerKinds = {
1305
1664
  code: "prefer-fewer-kinds",
1306
1665
  level: "info",
@@ -1311,7 +1670,10 @@ var preferFewerKinds = {
1311
1670
  if (!kinds || total < MIN_SAMPLE) return;
1312
1671
  const average = total / kinds;
1313
1672
  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` });
1673
+ out.push({
1674
+ message: `${space} kinds: ${kinds} (${average.toFixed(1)} per kind); 8 kinds or 5 per kind reads better`,
1675
+ 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.`
1676
+ });
1315
1677
  }
1316
1678
  };
1317
1679
  spread("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
@@ -1327,32 +1689,13 @@ var loneKind = {
1327
1689
  const lone = (space, counts, total) => {
1328
1690
  if (total < MIN_SAMPLE) return;
1329
1691
  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)}` });
1692
+ 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
1693
  };
1332
1694
  lone("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1333
1695
  lone("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1334
1696
  return out;
1335
1697
  }
1336
1698
  };
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
1699
  var lowCoverage = {
1357
1700
  code: "low-coverage",
1358
1701
  level: "info",
@@ -1361,40 +1704,58 @@ var lowCoverage = {
1361
1704
  if (leaves.length < 20) return [];
1362
1705
  const described = leaves.filter((n) => typeof n.data?.description === "string" && n.data.description.trim()).length;
1363
1706
  if (described / leaves.length >= 0.5) return [];
1364
- return [{ message: `${leaves.length - described} of ${leaves.length} leaf nodes have no description` }];
1707
+ return [{
1708
+ message: `${leaves.length - described} of ${leaves.length} leaf nodes have no description`,
1709
+ fix: `a leaf is what the reader clicks to understand something; half of them open empty.
1710
+ { "id": "${leaves.find((n) => !(typeof n.data?.description === "string" && n.data.description.trim()))?.id ?? "leaf"}", "description": "one sentence on what this is" }`
1711
+ }];
1365
1712
  }
1366
1713
  };
1367
1714
  var colorsContrast = {
1368
1715
  code: "colors-contrast",
1369
1716
  level: "info",
1370
1717
  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` }];
1718
+ const colors = Object.entries(profile.nodePalette).map(([kind, hex]) => ({ kind, lab: hexLab(hex) }));
1719
+ const usable = colors.filter((c) => c.lab !== null);
1720
+ if (usable.length < 6) return [];
1721
+ let worst = { a: "", b: "", d: Infinity };
1722
+ for (let i = 0; i < usable.length; i++) {
1723
+ for (let j = i + 1; j < usable.length; j++) {
1724
+ const d = deltaE(usable[i].lab, usable[j].lab);
1725
+ if (d < worst.d) worst = { a: usable[i].kind, b: usable[j].kind, d };
1726
+ }
1727
+ }
1728
+ if (worst.d >= 10) return [];
1729
+ return [{
1730
+ message: `"${worst.a}" and "${worst.b}" are ${worst.d.toFixed(1)} apart in color (under 10 reads as the same kind)`,
1731
+ fix: `push them apart in lightness, not just hue:
1732
+ "${worst.a}": darker \u2192 e.g. #4338ca
1733
+ "${worst.b}": lighter \u2192 e.g. #a5b4fc`
1734
+ }];
1376
1735
  }
1377
1736
  };
1378
1737
  var rules = [
1379
1738
  misplacedField,
1380
- missingParent,
1739
+ layerField,
1740
+ unknownParent,
1381
1741
  parentCycle,
1382
- unknownLayer,
1383
- crossLayerParent,
1742
+ orderMixed,
1743
+ orderDuplicate,
1384
1744
  conflictingDefinition,
1385
1745
  danglingEdge,
1386
1746
  duplicateEdge,
1387
1747
  multipleRoots,
1748
+ noHierarchy,
1749
+ unevenBranches,
1750
+ wideNode,
1751
+ uncoloredKind,
1752
+ singleKind,
1388
1753
  preferFewerKinds,
1389
1754
  loneKind,
1390
- preferFewerLayers,
1391
- flatParent,
1392
1755
  lowCoverage,
1393
1756
  colorsContrast
1394
1757
  ];
1395
- var RANK = { error: 0, warn: 1, info: 2 };
1396
1758
  function checkGraph(model, profile, opts) {
1397
- const fallbackLayer = profile.layers[0].id;
1398
1759
  const children = /* @__PURE__ */ new Map();
1399
1760
  for (const n of model.nodes) {
1400
1761
  if (!n.parent || !model.index.has(n.parent)) continue;
@@ -1402,40 +1763,73 @@ function checkGraph(model, profile, opts) {
1402
1763
  if (arr) arr.push(n);
1403
1764
  else children.set(n.parent, [n]);
1404
1765
  }
1766
+ const heightMemo = /* @__PURE__ */ new Map();
1767
+ const heightOf = (id, seen = /* @__PURE__ */ new Set()) => {
1768
+ const hit = heightMemo.get(id);
1769
+ if (hit != null) return hit;
1770
+ if (seen.has(id)) return 0;
1771
+ seen.add(id);
1772
+ let h = 0;
1773
+ for (const k of children.get(id) ?? []) h = Math.max(h, heightOf(k.id, seen) + 1);
1774
+ heightMemo.set(id, h);
1775
+ return h;
1776
+ };
1405
1777
  const ctx = {
1406
1778
  model,
1407
1779
  profile,
1408
1780
  where: opts.where,
1409
1781
  index: model.index,
1410
1782
  children,
1411
- layerOf: (n) => n.layer ?? fallbackLayer,
1783
+ layers: deriveLayers(model),
1412
1784
  labelOf: (id) => model.index.get(id)?.label ?? id,
1785
+ heightOf: (id) => heightOf(id),
1413
1786
  sameFileDuplicates: opts.sameFileDuplicates ?? /* @__PURE__ */ new Set()
1414
1787
  };
1415
1788
  const out = rules.flatMap((rule) => rule.run(ctx).map((issue) => ({
1416
- level: rule.level,
1789
+ level: issue.level ?? rule.level,
1417
1790
  code: rule.code,
1418
1791
  where: opts.where,
1419
1792
  message: issue.message,
1420
- ...issue.node !== void 0 ? { node: issue.node } : {},
1421
- ...issue.layer !== void 0 ? { layer: issue.layer } : {}
1793
+ ...issue.fix !== void 0 ? { fix: issue.fix } : {},
1794
+ ...issue.node !== void 0 ? { node: issue.node } : {}
1422
1795
  })));
1423
- return out.sort((a2, b) => RANK[a2.level] - RANK[b.level]);
1796
+ return out;
1424
1797
  }
1425
1798
  function structureOf(model) {
1426
- const index = indexModel(model);
1799
+ const index2 = indexModel(model);
1427
1800
  let depth = 0;
1428
1801
  let parented = 0;
1429
1802
  for (const n of model.nodes) {
1430
1803
  if (n.parent && model.index.has(n.parent)) parented++;
1431
- depth = Math.max(depth, index.depthOf(n.id));
1804
+ depth = Math.max(depth, index2.depthOf(n.id));
1432
1805
  }
1806
+ const children = /* @__PURE__ */ new Map();
1807
+ for (const n of model.nodes) {
1808
+ if (!n.parent || !model.index.has(n.parent)) continue;
1809
+ const arr = children.get(n.parent);
1810
+ arr ? arr.push(n) : children.set(n.parent, [n]);
1811
+ }
1812
+ const heightMemo = /* @__PURE__ */ new Map();
1813
+ const heightOf = (id, seen = /* @__PURE__ */ new Set()) => {
1814
+ const hit = heightMemo.get(id);
1815
+ if (hit != null) return hit;
1816
+ if (seen.has(id)) return 0;
1817
+ seen.add(id);
1818
+ let h = 0;
1819
+ for (const k of children.get(id) ?? []) h = Math.max(h, heightOf(k.id, seen) + 1);
1820
+ heightMemo.set(id, h);
1821
+ return h;
1822
+ };
1823
+ const derived = deriveLayers(model);
1433
1824
  return {
1434
1825
  nodes: model.nodes.length,
1435
1826
  edges: model.edges.length,
1436
1827
  roots: model.nodes.filter((n) => !n.parent).length,
1437
1828
  depth,
1438
- parented
1829
+ parented,
1830
+ layers: derived.layers.length,
1831
+ isomorphism: +isomorphism(model, children, (id) => heightOf(id)).score.toFixed(2),
1832
+ ordered: derived.layers.length > 0 || [...children.keys()].some((id) => orderedChildren(children, id) !== null)
1439
1833
  };
1440
1834
  }
1441
1835
  function countsBy(values) {
@@ -1443,42 +1837,61 @@ function countsBy(values) {
1443
1837
  for (const v of values) if (v) out.set(v, (out.get(v) ?? 0) + 1);
1444
1838
  return out;
1445
1839
  }
1446
- function hexGray(value) {
1840
+ function hexLab(value) {
1447
1841
  const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(value.trim());
1448
1842
  if (!m) return null;
1449
1843
  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;
1844
+ 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);
1845
+ const [x, y, z] = [
1846
+ (r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047,
1847
+ r * 0.2126 + g * 0.7152 + b * 0.0722,
1848
+ (r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883
1849
+ ].map((v) => v > 8856e-6 ? v ** (1 / 3) : 7.787 * v + 16 / 116);
1850
+ return [116 * y - 16, 500 * (x - y), 200 * (y - z)];
1851
+ }
1852
+ function deltaE(a2, b) {
1853
+ return Math.hypot(a2[0] - b[0], a2[1] - b[1], a2[2] - b[2]);
1465
1854
  }
1466
1855
 
1467
1856
  // cli/model.ts
1468
1857
  function profileFromJson(id, json) {
1469
1858
  if (!json) return defineProfile({ id });
1470
- const { demo: _demo, diffIgnore: _ignore, edgeLabels = {}, ...rest } = json;
1859
+ const { demo: _demo, diffIgnore: _ignore, edgeLabels = {}, layers: _layers, singleRoot: _single, ...rest } = json;
1471
1860
  return defineProfile({ id, ...rest, kindLabels: { ...rest.kindLabels, ...edgeLabels } });
1472
1861
  }
1862
+ function profileOf(l) {
1863
+ const json = l.profile;
1864
+ const base2 = profileFromJson("cli", json);
1865
+ const latest = l.versions[l.versions.length - 1];
1866
+ if (!latest) return base2;
1867
+ return derivedProfile(base2, latest.sources, json, false);
1868
+ }
1869
+ function derivedProfile(base2, sources, json, force) {
1870
+ const first = parseSources(sources, base2);
1871
+ const colors = json?.appearance?.layerColors;
1872
+ const derived = deriveLayers(first, Array.isArray(colors) ? colors : [], force);
1873
+ if (derived.layers.length < 2) return base2;
1874
+ return defineProfile({ ...base2, layers: derived.layers, layerOf: (n) => derived.layerOf.get(n.id) ?? derived.layers[0].id });
1875
+ }
1473
1876
  var modelOf = (v, profile) => parseSources(v.sources, profile);
1474
- var RANK2 = { error: 0, warn: 1, info: 2 };
1877
+ var RANK = { error: 0, warn: 1, info: 2 };
1475
1878
  function validate(loaded) {
1476
1879
  const out = [];
1477
- const profile = profileFromJson("cli", loaded.profile);
1880
+ const profile = profileOf(loaded);
1478
1881
  if (loaded.profile) {
1479
1882
  for (const e of checkSchema(profile_schema_default, loaded.profile)) out.push({ level: "error", code: "schema", where: "_profile.json", message: `${e.path}: ${e.message}` });
1883
+ const retired = ["layers", "singleRoot"].filter((k) => k in loaded.profile);
1884
+ if (retired.length) out.push({
1885
+ level: "warn",
1886
+ code: "profile-retired",
1887
+ where: "_profile.json",
1888
+ message: `${retired.map((k) => `"${k}"`).join(" and ")} no longer configure anything: layers are derived from "order"`,
1889
+ fix: `delete ${retired.length > 1 ? "them" : "it"} from _profile.json. To open the page with the plane view on, write:
1890
+ { "appearance": { "defaultLayers": true } }`
1891
+ });
1480
1892
  }
1481
1893
  for (const e of loaded.metaErrors) out.push({ level: "error", code: "schema", where: e.file, message: e.message });
1894
+ const latest = loaded.raw[loaded.raw.length - 1]?.version;
1482
1895
  for (const { version, files } of loaded.raw) {
1483
1896
  const prefix = loaded.versions.length > 1 ? `${version}/` : "";
1484
1897
  const notJson = /* @__PURE__ */ new Set();
@@ -1499,6 +1912,18 @@ function validate(loaded) {
1499
1912
  continue;
1500
1913
  }
1501
1914
  for (const e of checkSchema(graph_schema_default, doc)) out.push({ level: "error", code: "schema", where: prefix + f.path, message: `${e.path}: ${e.message}` });
1915
+ const bare = (Array.isArray(doc.nodes) ? doc.nodes : []).filter((n) => !!n && typeof n === "object" && !("parent" in n));
1916
+ if (bare.length) out.push({
1917
+ level: "error",
1918
+ code: "missing-parent",
1919
+ where: prefix + f.path,
1920
+ 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`,
1921
+ fix: `add the field. The top of the tree is null; everything else names its container:
1922
+ - { "id": "${String(bare[0].id)}" }
1923
+ + { "id": "${String(bare[0].id)}", "parent": null }
1924
+ - { "id": "child" }
1925
+ + { "id": "child", "parent": "${String(bare[0].id)}" }`
1926
+ });
1502
1927
  const seen = /* @__PURE__ */ new Map();
1503
1928
  for (const id of idsIn(doc)) seen.set(id, (seen.get(id) ?? 0) + 1);
1504
1929
  for (const [id, count2] of seen) {
@@ -1511,10 +1936,10 @@ function validate(loaded) {
1511
1936
  const v = loaded.versions.find((x) => x.name === version);
1512
1937
  const model = modelOf(v, profile);
1513
1938
  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 }));
1939
+ if (version === latest) out.push(...checkGraph(model, profile, { where: prefix || loaded.title, sameFileDuplicates }));
1515
1940
  if (!model.nodes.length) out.push({ level: "warn", code: "empty", where: prefix || loaded.title, message: "No nodes found" });
1516
1941
  }
1517
- return out.sort((a2, b) => RANK2[a2.level] - RANK2[b.level]);
1942
+ return out.sort((a2, b) => RANK[a2.level] - RANK[b.level]);
1518
1943
  }
1519
1944
  function idsIn(doc) {
1520
1945
  const nodes = doc.nodes;
@@ -1588,9 +2013,9 @@ var one = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1588
2013
  var MAX_SIBLINGS = 12;
1589
2014
  var MAX_LINES = 200;
1590
2015
  var MAX_EDGES = 6;
1591
- function tree(model, profile, opts) {
1592
- const fallbackLayer = profile.layers[0].id;
1593
- const layerOf = (n) => n.layer ?? fallbackLayer;
2016
+ function tree(model, opts) {
2017
+ const derived = deriveLayers(model);
2018
+ const layerOf = (n) => derived.layerOf.get(n.id);
1594
2019
  const labelOf = (id) => model.index.get(id)?.label ?? id;
1595
2020
  const depth = Math.max(1, opts.depth ?? 3);
1596
2021
  const perNode = Math.max(1, opts.perNode ?? MAX_SIBLINGS);
@@ -1624,7 +2049,9 @@ function tree(model, profile, opts) {
1624
2049
  for (const n of model.nodes) measure(n.id);
1625
2050
  const bySize = (a2, b) => (size.get(b.id) ?? 1) - (size.get(a2.id) ?? 1) || labelOf(a2.id).localeCompare(labelOf(b.id));
1626
2051
  const sorted = /* @__PURE__ */ new Map();
1627
- for (const [id, list] of kids) sorted.set(id, [...list].sort(bySize));
2052
+ for (const [id, list] of kids) {
2053
+ sorted.set(id, orderedChildren(kids, id) ?? [...list].sort(bySize));
2054
+ }
1628
2055
  const outgoing = /* @__PURE__ */ new Map();
1629
2056
  for (const e of model.edges) {
1630
2057
  if (!model.index.has(e.source) || !model.index.has(e.target)) continue;
@@ -1649,16 +2076,18 @@ function tree(model, profile, opts) {
1649
2076
  if (collapsed && tall > 0) bits.push(`${tall} deep`);
1650
2077
  if (edges.length) bits.push(edgeText(edges));
1651
2078
  const label = `${labelOf(node.id)}${broken(node) ? " (parent missing)" : ""}`;
2079
+ const orderTag = typeof node.order === "number" ? `[${node.order}] ` : "";
1652
2080
  entries.push({
1653
2081
  id: node.id,
1654
2082
  label,
1655
2083
  depth: level,
1656
2084
  layer: layerOf(node),
2085
+ ...typeof node.order === "number" ? { order: node.order } : {},
1657
2086
  nodes: inside,
1658
2087
  deep: tall,
1659
2088
  collapsed,
1660
2089
  edges,
1661
- text: `${prefix}${connector}${label}${bits.length ? ` ${bits.join(" \xB7 ")}` : ""}`
2090
+ text: `${prefix}${connector}${orderTag}${label}${bits.length ? ` ${bits.join(" \xB7 ")}` : ""}`
1662
2091
  });
1663
2092
  if (!canExpand) return;
1664
2093
  const shown = list.slice(0, perNode);
@@ -1681,7 +2110,7 @@ function tree(model, profile, opts) {
1681
2110
  }
1682
2111
  };
1683
2112
  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}`;
2113
+ 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
2114
  const roots = model.nodes.filter((n) => !n.parent || broken(n));
1686
2115
  if (opts.path) {
1687
2116
  const start = model.index.get(opts.path);
@@ -1732,37 +2161,264 @@ function treeText(result) {
1732
2161
  return lines.join("\n");
1733
2162
  }
1734
2163
 
2164
+ // cli/restructure.ts
2165
+ function index(nodes) {
2166
+ const byId = new Map(nodes.map((n) => [n.id, n]));
2167
+ const children = /* @__PURE__ */ new Map();
2168
+ for (const n of nodes) {
2169
+ if (!n.parent || !byId.has(n.parent)) {
2170
+ n.parent = null;
2171
+ continue;
2172
+ }
2173
+ const arr = children.get(n.parent);
2174
+ arr ? arr.push(n.id) : children.set(n.parent, [n.id]);
2175
+ }
2176
+ const depth = /* @__PURE__ */ new Map();
2177
+ const walk2 = (id, seen) => {
2178
+ const hit = depth.get(id);
2179
+ if (hit != null) return hit;
2180
+ if (seen.has(id)) return 0;
2181
+ seen.add(id);
2182
+ const p = byId.get(id)?.parent;
2183
+ const d = p ? walk2(p, seen) + 1 : 0;
2184
+ depth.set(id, d);
2185
+ return d;
2186
+ };
2187
+ for (const n of nodes) walk2(n.id, /* @__PURE__ */ new Set());
2188
+ return { byId, children, depth };
2189
+ }
2190
+ function scoreOf(ctx) {
2191
+ const height = /* @__PURE__ */ new Map();
2192
+ const h = (id, seen = /* @__PURE__ */ new Set()) => {
2193
+ const hit = height.get(id);
2194
+ if (hit != null) return hit;
2195
+ if (seen.has(id)) return 0;
2196
+ seen.add(id);
2197
+ let v = 0;
2198
+ for (const k of ctx.children.get(id) ?? []) v = Math.max(v, h(k, seen) + 1);
2199
+ height.set(id, v);
2200
+ return v;
2201
+ };
2202
+ const nodeList = [...ctx.byId.values()];
2203
+ const model = { nodes: nodeList, edges: [], errors: [], index: ctx.byId };
2204
+ const kids = new Map([...ctx.children].map(([id, ids]) => [id, ids.map((k) => ctx.byId.get(k))]));
2205
+ return isomorphism(model, kids, (id) => h(id)).score;
2206
+ }
2207
+ function adoptFlat(nodes, byId, created, moves) {
2208
+ if (nodes.some((n) => n.parent)) return;
2209
+ const pathOf = (n) => {
2210
+ const sf = n.data.source_file;
2211
+ if (typeof sf === "string" && sf.includes("/")) return sf;
2212
+ if (n.id.includes("/")) return n.id.split("#")[0];
2213
+ return null;
2214
+ };
2215
+ if (!nodes.some((n) => pathOf(n))) return;
2216
+ const dirs = /* @__PURE__ */ new Map();
2217
+ const mkdir = (dir) => {
2218
+ if (!dir) return null;
2219
+ const hit = dirs.get(dir);
2220
+ if (hit) return hit;
2221
+ const parentDir = dir.includes("/") ? dir.slice(0, dir.lastIndexOf("/")) : "";
2222
+ const parent = mkdir(parentDir);
2223
+ const id = `dir:${dir}`;
2224
+ dirs.set(dir, id);
2225
+ created.push({ id, label: dir.slice(dir.lastIndexOf("/") + 1) || dir, kind: "folder", parent });
2226
+ byId.set(id, { id, label: dir.slice(dir.lastIndexOf("/") + 1) || dir, kind: "folder", parent, data: {} });
2227
+ return id;
2228
+ };
2229
+ for (const n of nodes) {
2230
+ const path3 = pathOf(n);
2231
+ if (!path3) continue;
2232
+ const slash = path3.lastIndexOf("/");
2233
+ const dir = slash < 0 ? "" : path3.slice(0, slash);
2234
+ const fileId = `file:${path3}`;
2235
+ if (!dirs.has(fileId)) {
2236
+ const parent = mkdir(dir);
2237
+ const fileLabel = path3.slice(slash + 1);
2238
+ created.push({ id: fileId, label: fileLabel, kind: "file", parent });
2239
+ byId.set(fileId, { id: fileId, label: fileLabel, kind: "file", parent, data: {} });
2240
+ dirs.set(fileId, fileId);
2241
+ }
2242
+ const before = n.parent;
2243
+ n.parent = fileId;
2244
+ moves.push({ id: n.id, from: before, to: fileId, why: `${path3}` });
2245
+ }
2246
+ }
2247
+ function attachByKind(ctx, wraps, moves) {
2248
+ const per = /* @__PURE__ */ new Map();
2249
+ for (const n of ctx.byId.values()) {
2250
+ if (!n.kind) continue;
2251
+ const hist = per.get(n.kind) ?? /* @__PURE__ */ new Map();
2252
+ const d = ctx.depth.get(n.id) ?? 0;
2253
+ hist.set(d, (hist.get(d) ?? 0) + 1);
2254
+ per.set(n.kind, hist);
2255
+ }
2256
+ const modal = /* @__PURE__ */ new Map();
2257
+ for (const [kind, hist] of per) {
2258
+ const total = [...hist.values()].reduce((a2, b) => a2 + b, 0);
2259
+ let best = 0;
2260
+ let bestCount = -1;
2261
+ for (const [d, c] of hist) if (c > bestCount || c === bestCount && d < best) {
2262
+ best = d;
2263
+ bestCount = c;
2264
+ }
2265
+ if (total >= 3 && bestCount / total >= 0.6) modal.set(kind, best);
2266
+ }
2267
+ const limit = Math.max(4, Math.floor(ctx.byId.size * 0.2));
2268
+ let changes = 0;
2269
+ for (const n of [...ctx.byId.values()]) {
2270
+ if (changes >= limit) break;
2271
+ if (!n.kind || !n.parent) continue;
2272
+ const target = modal.get(n.kind);
2273
+ if (target == null) continue;
2274
+ const here2 = ctx.depth.get(n.id) ?? 0;
2275
+ if (here2 === target) continue;
2276
+ if (here2 > target) {
2277
+ let up = n.parent;
2278
+ while (up && (ctx.depth.get(up) ?? 0) > target - 1) up = ctx.byId.get(up)?.parent ?? null;
2279
+ if (!up || up === n.parent || (ctx.depth.get(up) ?? 0) !== target - 1) continue;
2280
+ moves.push({ id: n.id, from: n.parent, to: up, why: `kind "${n.kind}" sits at depth ${target}` });
2281
+ n.parent = up;
2282
+ changes++;
2283
+ }
2284
+ }
2285
+ const rebuilt = index([...ctx.byId.values()]);
2286
+ ctx.children = rebuilt.children;
2287
+ ctx.depth = rebuilt.depth;
2288
+ }
2289
+ function ladderOf(ctx) {
2290
+ const per = /* @__PURE__ */ new Map();
2291
+ for (const n of ctx.byId.values()) {
2292
+ if (!n.kind) continue;
2293
+ const d = ctx.depth.get(n.id) ?? 0;
2294
+ const hist = per.get(n.kind) ?? /* @__PURE__ */ new Map();
2295
+ hist.set(d, (hist.get(d) ?? 0) + 1);
2296
+ per.set(n.kind, hist);
2297
+ }
2298
+ return [...per].map(([kind, hist]) => {
2299
+ const [depth, count2] = [...hist].sort((a2, b) => b[1] - a2[1] || a2[0] - b[0])[0];
2300
+ return { kind, depth, count: count2 };
2301
+ }).sort((a2, b) => a2.depth - b.depth || a2.kind.localeCompare(b.kind));
2302
+ }
2303
+ function singleRoot(ctx, created, moves) {
2304
+ const roots = [...ctx.byId.values()].filter((n) => !n.parent);
2305
+ if (roots.length < 2) return;
2306
+ const levels = /* @__PURE__ */ new Map();
2307
+ const tall = (id2, seen = /* @__PURE__ */ new Set()) => {
2308
+ const hit = levels.get(id2);
2309
+ if (hit != null) return hit;
2310
+ if (seen.has(id2)) return 0;
2311
+ seen.add(id2);
2312
+ let h = 0;
2313
+ for (const k of ctx.children.get(id2) ?? []) h = Math.max(h, tall(k, seen) + 1);
2314
+ levels.set(id2, h);
2315
+ return h;
2316
+ };
2317
+ const heights = roots.map((r) => tall(r.id));
2318
+ if (Math.max(...heights) - Math.min(...heights) > 1) return;
2319
+ let id = "root";
2320
+ for (let i = 2; ctx.byId.has(id); i++) id = `root-${i}`;
2321
+ const root = { id, label: "Overview", kind: "overview", parent: null, seq: -1, data: {} };
2322
+ ctx.byId.set(id, root);
2323
+ created.push({ id, label: "Overview", kind: "overview", parent: null });
2324
+ roots.forEach((n, i) => {
2325
+ moves.push({ id: n.id, from: null, to: id, why: "single root" });
2326
+ n.parent = id;
2327
+ n.order = i + 1;
2328
+ });
2329
+ const re = index([...ctx.byId.values()]);
2330
+ ctx.children = re.children;
2331
+ ctx.depth = re.depth;
2332
+ }
2333
+ function numberSiblings(ctx) {
2334
+ for (const [, kids] of ctx.children) {
2335
+ if (kids.length < 2) {
2336
+ for (const k of kids) delete ctx.byId.get(k).order;
2337
+ continue;
2338
+ }
2339
+ 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));
2340
+ list.forEach((n, i) => {
2341
+ n.order = i + 1;
2342
+ });
2343
+ }
2344
+ }
2345
+ function restructure(nodes, edges) {
2346
+ const ctx = index(nodes);
2347
+ const before = scoreOf(ctx);
2348
+ const beforeFlat = !nodes.some((n) => n.parent);
2349
+ const created = [];
2350
+ const moves = [];
2351
+ const wraps = [];
2352
+ let note;
2353
+ adoptFlat([...ctx.byId.values()], ctx.byId, created, moves);
2354
+ if (!edges.length && !nodes.some((n) => n.parent)) note = "no parent anywhere and no path to build one from: give the nodes parents first";
2355
+ const re = index([...ctx.byId.values()]);
2356
+ ctx.children = re.children;
2357
+ ctx.depth = re.depth;
2358
+ const inferred = ladderOf(ctx);
2359
+ attachByKind(ctx, wraps, moves);
2360
+ singleRoot(ctx, created, moves);
2361
+ numberSiblings(ctx);
2362
+ const after = scoreOf(ctx);
2363
+ return { nodes: [...ctx.byId.values()], edges, moves, wraps, created, before, beforeFlat, after, ladder: inferred, note };
2364
+ }
2365
+ function planText(r, title) {
2366
+ const L = [];
2367
+ L.push(`${title}: isomorphism ${r.beforeFlat ? "flat" : r.before.toFixed(2)} \u2192 ${r.after.toFixed(2)}`);
2368
+ if (r.note) L.push(`note: ${r.note}`);
2369
+ if (r.ladder.length) L.push(`kinds \u2192 depth: ${r.ladder.map((l) => `${l.kind} ${l.depth} (${l.count})`).join(" \xB7 ")}`);
2370
+ 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" : ""})`);
2371
+ if (r.moves.length) L.push(`moved ${r.moves.length} node${r.moves.length > 1 ? "s" : ""}${r.wraps.length ? ` (${r.wraps.length} wrapped)` : ""}:`);
2372
+ for (const m of r.moves.slice(0, 8)) L.push(` ${m.id}: ${m.from ?? "(top)"} \u2192 ${m.to ?? "(top)"} ${m.why}`);
2373
+ if (r.moves.length > 8) L.push(` \u2026 ${r.moves.length - 8} more (--json)`);
2374
+ if (!r.moves.length && !r.created.length) L.push("nothing to move: the shape already matches the kinds");
2375
+ return L.join("\n");
2376
+ }
2377
+
1735
2378
  // cli/glassbrain.ts
1736
2379
  var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, written as plain JSON.
1737
2380
 
1738
2381
  [ THE THREE AXES ]
1739
2382
  Different things. Do not use one where another belongs.
1740
2383
  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 ])
2384
+ parent containment \u2014 what sits inside what; every node has one
2385
+ order position among siblings \u2014 turns a set into a numbered list
1743
2386
 
1744
2387
  [ DATA ]
1745
2388
  Two arrays. The \`//\` notes are not part of the file: strip them and it is valid JSON
1746
2389
  (if validate says \`not JSON\`, a note survived the copy).
1747
2390
 
1748
2391
  { "nodes": [
1749
- { "id": "src", "label": "src", "kind": "folder" }, // required, stable, not a counter
2392
+ { "id": "src", "label": "src", "kind": "folder",
2393
+ "parent": null }, // the root: parent is null
1750
2394
  { "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" } ],
2395
+ "parent": "src", "order": 1, // inside src, first
2396
+ "description": "Checks the password, then opens a session.", // markdown
2397
+ "owner": "auth" }, // any other field: kept, shown
2398
+ { "id": "src/db.ts", "label": "db.ts", "kind": "file",
2399
+ "parent": "src", "order": 2 } ],
1755
2400
  "edges": [
1756
2401
  { "source": "src/login.ts", "target": "src/db.ts", "kind": "uses" } ] }
1757
2402
 
1758
- \`parent\` is read only as a top-level field. Nested (\`data.parent\`) it is shown and
2403
+ \`parent\` is required on every node: a node id, or null for the root. One root per
2404
+ file. It is read only as a top-level field; nested (\`data.parent\`) it is shown and
1759
2405
  nothing else. \`kind\` gives the color; \`description\` is what the panel says.
1760
2406
 
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)
2407
+ ORDER a numbered list, or no list at all
2408
+ The children of one parent either all carry \`order\` or none does, and no two
2409
+ share a number \u2014 a list is numbered, or it is a set. Values are floats, so 3.5
2410
+ inserts between 3 and 4. The layout reads them clockwise from the top.
2411
+ A root whose children are numbered opens the layer view: one floor per child.
2412
+ Without order the layer button stays grey and can still force the floors
2413
+ open (document order, view only). There is no layer field.
2414
+
2415
+ SHAPE how a graph reads (validate measures each)
2416
+ 2\u20135 children per node; more than 10 is a wall (wide-node)
2417
+ children of one parent the same depth; 1.00 is perfect (uneven-branches)
2418
+ every kind used 5+ times, at most 8 node kinds (prefer-fewer-kinds)
2419
+ describe the leaves; under half described is noted (low-coverage)
2420
+ kind is optional; without it every node is drawn the same gray
2421
+ kind is optional; without it every node is drawn the same gray
1766
2422
 
1767
2423
  Full schema: ${schema}
1768
2424
 
@@ -1770,7 +2426,7 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
1770
2426
  A folder is a graph. Passes are optional; one numbered folder each.
1771
2427
 
1772
2428
  kg/
1773
- \u251C\u2500\u2500 _profile.json colors and layers, shared by every pass (see [ APPEARANCE ])
2429
+ \u251C\u2500\u2500 _profile.json colors, shared by every pass (see [ APPEARANCE ])
1774
2430
  \u251C\u2500\u2500 1-skeleton/graph.json a graph (see [ DATA ])
1775
2431
  \u251C\u2500\u2500 2-filled/graph.json each pass is the whole graph: copy the last, edit the copy
1776
2432
  \u2514\u2500\u2500 3-linked/graph.json then validate, and diff against the pass before
@@ -1782,20 +2438,17 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
1782
2438
  [ APPEARANCE ]
1783
2439
  kg/_profile.json, shared by every pass. Everything in it is optional.
1784
2440
 
1785
- COLORS one entry per kind you use; unlisted kinds stay neutral.
2441
+ COLORS one entry per kind you use. A kind without an entry is drawn as skeleton \u2014
2442
+ every uncoloured kind looks the same, so validate reports it as an error.
1786
2443
  { "nodePalette": { "file": "#6366f1", "folder": "#94a3b8" },
1787
2444
  "edgePalette": { "uses": "#2563eb" } }
1788
- Colors that land in one brightness band read alike (validate notes it).
2445
+ Ten kinds is already a lot; one with no colour is invisible.
2446
+ Colors closer than 10 in Lab distance read as one kind (validate notes it).
1789
2447
 
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).
2448
+ VIEW only the opening state; the page has the switches.
2449
+ { "appearance": { "defaultLayers": true } }
2450
+ Open with the 2.5D floors on. Without it the page opens flat and the layer
2451
+ control turns them on. A graph with no ordered root has one floor.
1799
2452
 
1800
2453
  Full schema: ${schema.replace("graph.schema", "profile.schema")}
1801
2454
 
@@ -1803,8 +2456,13 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
1803
2456
  Always validate before handing over; a page is only written for a graph with no errors.
1804
2457
 
1805
2458
  glassbrain <path> write one html page, print its path (passes play as steps)
2459
+ glassbrain view <path> the same page, spelled out (a path is required)
1806
2460
  glassbrain validate <path> errors, warnings, info; exit 1 on errors
1807
2461
  glassbrain tree <path> the containment tree as text
2462
+ glassbrain restructure <path> raise the shape score: re-hang and renumber; writes a
2463
+ new folder with graph.json and _profile.json (a pass,
2464
+ or <name>.restructured/ for one file). It colours the
2465
+ kinds it invents. --dry-run prints the plan only.
1808
2466
  glassbrain diff <old> <new> only what changed between two graphs
1809
2467
  glassbrain diff <git-ref> <path> the same graph at an earlier commit (default HEAD)
1810
2468
  glassbrain convert <path> [out-dir] write any supported format as glassbrain JSON
@@ -1812,20 +2470,23 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
1812
2470
  <path> is a file, a folder, or <git-ref>:<path> (HEAD~1:kg/graph.json). Graphify,
1813
2471
  Understand-Anything, memory.jsonl and markdown folders are read as-is.
1814
2472
 
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
2473
+ validate speaks in three levels, and every line carries its repair:
2474
+ error broken schema, a missing/unknown parent, a cycle, a duplicate id,
2475
+ mixed or duplicate order, an edge to a missing node
2476
+ warn discouraged several roots in one file, one relation written twice,
2477
+ a node with more than 10 children, branches uneven in two
2478
+ or more places (one place is only info)
2479
+ info distribution kinds, order notes, empty leaves, color contrast
1820
2480
  exit codes: 0 clean \xB7 1 errors (--strict: warnings too) \xB7 2 usage.
1821
2481
  It always ends with the structure and the tree command for that graph.
1822
2482
 
1823
2483
  [ OPTIONS ]
1824
- --json machine-readable output (validate, tree, diff)
2484
+ --json machine-readable output (validate, tree, diff, restructure)
1825
2485
  --strict warnings fail too (validate, view)
1826
2486
  --depth <n> tree: levels to expand (default 3)
1827
2487
  --path <id> tree: one node, its ancestors and its subtree
1828
2488
  --orphans tree: only nodes with no parent
2489
+ --dry-run restructure: print the plan, write nothing
1829
2490
  --out <file.html> write the page here instead of a temp file (view, diff)
1830
2491
  --open / --no-open open the browser or not (diff opens only in a terminal)
1831
2492
  --exit-code exit 1 when anything changed (diff)
@@ -1833,16 +2494,10 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
1833
2494
  --ignore <a,b> fields that do not count as a change (diff)
1834
2495
  --format <id> force a format: native, graphify, understand-anything, memory, obsidian
1835
2496
  -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
2497
  `;
1843
2498
  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"];
2499
+ var SWITCHES = /* @__PURE__ */ new Set(["open", "json", "all", "exit-code", "strict", "help", "version", "orphans", "dry-run"]);
2500
+ var COMMANDS = ["view", "diff", "validate", "convert", "tree", "restructure"];
1846
2501
  function parseArgs(argv) {
1847
2502
  const pos = [];
1848
2503
  const flags = {};
@@ -1896,7 +2551,10 @@ var tally = (found) => ({
1896
2551
  info: found.filter((f) => f.level === "info").length
1897
2552
  });
1898
2553
  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}`);
2554
+ for (const f of found.slice(0, limit)) {
2555
+ console.log(`${TAG[f.level]} ${f.code} ${f.where} ${f.message}`);
2556
+ if (f.fix) console.log(f.fix.split("\n").map((l) => ` ${l}`).join("\n"));
2557
+ }
1900
2558
  if (found.length > limit) console.log(`\u2026 ${found.length - limit} more (--json)`);
1901
2559
  }
1902
2560
  var slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "graph";
@@ -1909,7 +2567,7 @@ function openFile(file) {
1909
2567
  }
1910
2568
  }
1911
2569
  var nodesOf = (l) => {
1912
- const profile = profileFromJson("cli", l.profile);
2570
+ const profile = profileOf(l);
1913
2571
  return l.versions.map((v) => modelOf(v, profile));
1914
2572
  };
1915
2573
  function notes(l, models) {
@@ -1960,7 +2618,7 @@ function runDiff(a2) {
1960
2618
  const before = load(oldSpec, { format });
1961
2619
  const after = load(newSpec, { format });
1962
2620
  const profileJson = after.profile ?? before.profile;
1963
- const profile = profileFromJson("cli", profileJson);
2621
+ const profile = profileOf(after);
1964
2622
  const pick = (l) => l.versions[l.versions.length - 1];
1965
2623
  const vb = pick(before);
1966
2624
  const va = pick(after);
@@ -2022,7 +2680,7 @@ function runValidate(a2) {
2022
2680
  if (found.length) console.log("");
2023
2681
  printFindings(found);
2024
2682
  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`);
2683
+ 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
2684
  console.log(`tree: glassbrain tree ${a2.pos[0]} --depth=3`);
2027
2685
  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
2686
  `);
@@ -2038,7 +2696,7 @@ function runTree(a2) {
2038
2696
  notes(l, models);
2039
2697
  const latest = models[models.length - 1];
2040
2698
  const version = l.versions[l.versions.length - 1].name;
2041
- const result = tree(latest, profileFromJson("cli", l.profile), {
2699
+ const result = tree(latest, {
2042
2700
  title: l.versions.length > 1 ? `${l.title}/${version}` : l.title,
2043
2701
  depth,
2044
2702
  path: typeof a2.flags.path === "string" ? a2.flags.path : void 0,
@@ -2050,13 +2708,84 @@ function runTree(a2) {
2050
2708
  console.log(treeText(result));
2051
2709
  }
2052
2710
  }
2711
+ function runRestructure(a2) {
2712
+ if (a2.pos.length !== 1) fail("restructure needs exactly one <path>");
2713
+ const l = load(a2.pos[0], { format: a2.flags.format });
2714
+ const models = nodesOf(l);
2715
+ notes(l, models);
2716
+ const latest = models[models.length - 1];
2717
+ const phys = toPhysical(latest);
2718
+ const nodes = phys.nodes.map((n, seq) => ({
2719
+ id: String(n.id),
2720
+ label: String(n.label ?? n.id),
2721
+ kind: typeof n.kind === "string" ? n.kind : void 0,
2722
+ parent: n.parent === void 0 || n.parent === null ? null : String(n.parent),
2723
+ order: typeof n.order === "number" ? n.order : void 0,
2724
+ seq,
2725
+ data: n
2726
+ }));
2727
+ const edges = phys.edges.map((e) => ({
2728
+ source: String(e.source),
2729
+ target: String(e.target),
2730
+ ...typeof e.kind === "string" ? { kind: e.kind } : {},
2731
+ ...typeof e.label === "string" ? { label: e.label } : {},
2732
+ ...typeof e.weight === "number" ? { weight: e.weight } : {},
2733
+ data: e
2734
+ }));
2735
+ const plan = restructure(nodes, edges);
2736
+ if (a2.flags.json) {
2737
+ 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));
2738
+ if (a2.flags["dry-run"]) return;
2739
+ } else {
2740
+ console.log(planText(plan, l.title));
2741
+ if (a2.flags["dry-run"]) {
2742
+ console.log("\n(dry run: nothing written. Drop --dry-run to write a new pass.)");
2743
+ return;
2744
+ }
2745
+ }
2746
+ const outNodes = plan.nodes.map((p) => {
2747
+ const { parent: _p, order: _o, ...rest } = p.data ?? {};
2748
+ return {
2749
+ ...rest,
2750
+ id: p.id,
2751
+ label: p.label,
2752
+ ...p.kind ? { kind: p.kind } : {},
2753
+ parent: p.parent,
2754
+ ...p.order !== void 0 ? { order: p.order } : {}
2755
+ };
2756
+ });
2757
+ const graph = { name: l.title, nodes: outNodes, edges: phys.edges };
2758
+ const abs = path2.resolve(a2.pos[0]);
2759
+ const dir = fs2.existsSync(abs) && fs2.statSync(abs).isDirectory() ? abs : path2.dirname(abs);
2760
+ 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) : [];
2761
+ const palette = {};
2762
+ const known = { folder: "#94a3b8", file: "#64748b", overview: "#a855f7", group: "#a855f7" };
2763
+ const wheel = ["#6366f1", "#f59e0b", "#10b981", "#ef4444", "#8b5cf6", "#06b6d4"];
2764
+ let wi = 0;
2765
+ for (const k of new Set(plan.nodes.map((n) => n.kind))) {
2766
+ if (k) palette[k] = known[k] ?? wheel[wi++ % wheel.length];
2767
+ }
2768
+ const srcProfile = l.profile ?? {};
2769
+ const outProfile = {
2770
+ ...srcProfile,
2771
+ nodePalette: { ...palette, ...srcProfile.nodePalette ?? {} }
2772
+ };
2773
+ const passDir = l.versions.length > 1 || passes.length ? path2.join(dir, `${(passes.length ? Math.max(...passes) : 0) + 1}-restructured`) : path2.join(dir, `${path2.basename(abs, ".json") || "graph"}.restructured`);
2774
+ fs2.mkdirSync(passDir, { recursive: true });
2775
+ fs2.writeFileSync(path2.join(passDir, "_profile.json"), `${JSON.stringify(outProfile, null, 1)}
2776
+ `);
2777
+ const file = path2.join(passDir, "graph.json");
2778
+ fs2.writeFileSync(file, `${JSON.stringify(graph, null, 1)}
2779
+ `);
2780
+ console.log(`
2781
+ wrote ${file}`);
2782
+ console.log(`next: glassbrain diff ${a2.pos[0]} ${file}`);
2783
+ }
2053
2784
  function runConvert(a2) {
2054
2785
  if (a2.pos.length < 1 || a2.pos.length > 2) fail("convert needs <path> [out-dir]");
2055
2786
  const l = load(a2.pos[0], { format: a2.flags.format });
2056
2787
  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])) } }));
2788
+ const graphs = l.versions.map((v, i) => ({ name: v.name, graph: { name: v.name, ...toPhysical(models[i]) } }));
2060
2789
  const outDir = a2.pos[1];
2061
2790
  if (!outDir) {
2062
2791
  if (graphs.length > 1) fail("several versions: give an out-dir");
@@ -2080,11 +2809,14 @@ var a = parseArgs(process.argv.slice(2));
2080
2809
  if (a.flags.version) {
2081
2810
  const pkg = JSON.parse(fs2.readFileSync(path2.join(here, "../../package.json"), "utf8"));
2082
2811
  console.log(pkg.version);
2083
- } else if (a.flags.help || a.cmd === "view" && !a.pos.length) {
2812
+ } else if (a.flags.help) {
2813
+ process.stdout.write(HELP(path2.join(here, "../../schema/graph.schema.json")));
2814
+ } else if (a.cmd === "view" && !a.pos.length) {
2815
+ if (process.argv.slice(2).includes("view")) fail("view needs exactly one <path>");
2084
2816
  process.stdout.write(HELP(path2.join(here, "../../schema/graph.schema.json")));
2085
2817
  } else {
2086
2818
  try {
2087
- ({ view, diff: runDiff, validate: runValidate, convert: runConvert, tree: runTree })[a.cmd](a);
2819
+ ({ view, diff: runDiff, validate: runValidate, convert: runConvert, tree: runTree, restructure: runRestructure })[a.cmd](a);
2088
2820
  } catch (e) {
2089
2821
  fail(e.message, 2);
2090
2822
  }