glassbrain 0.1.4 → 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();
@@ -45,6 +45,55 @@ function addOrigin(list, origin) {
45
45
  function originsOfNode(n) {
46
46
  return n.origins?.length ? n.origins : n.origin ? [n.origin] : [];
47
47
  }
48
+ function indexModel(model) {
49
+ const parentOf = /* @__PURE__ */ new Map();
50
+ const childrenOf = /* @__PURE__ */ new Map();
51
+ for (const n of model.nodes) {
52
+ if (!n.parent) continue;
53
+ parentOf.set(n.id, n.parent);
54
+ const arr = childrenOf.get(n.parent);
55
+ arr ? arr.push(n.id) : childrenOf.set(n.parent, [n.id]);
56
+ }
57
+ const neighborsOf = /* @__PURE__ */ new Map();
58
+ for (const e of model.edges) {
59
+ for (const [a2, b] of [[e.source, e.target], [e.target, e.source]]) {
60
+ const arr = neighborsOf.get(a2);
61
+ arr ? arr.push(b) : neighborsOf.set(a2, [b]);
62
+ }
63
+ }
64
+ const depthMemo = /* @__PURE__ */ new Map();
65
+ const depthOf = (id, seen = /* @__PURE__ */ new Set()) => {
66
+ const hit = depthMemo.get(id);
67
+ if (hit != null) return hit;
68
+ seen.add(id);
69
+ const p = parentOf.get(id);
70
+ const d = p && !seen.has(p) ? depthOf(p, seen) + 1 : 1;
71
+ depthMemo.set(id, d);
72
+ return d;
73
+ };
74
+ const ancestorsOf = (id) => {
75
+ const out = [];
76
+ let p = parentOf.get(id);
77
+ while (p && !out.includes(p)) {
78
+ out.push(p);
79
+ p = parentOf.get(p);
80
+ }
81
+ return out;
82
+ };
83
+ const subtreeOf = (id) => {
84
+ const out = /* @__PURE__ */ new Set([id]);
85
+ const stack = [id];
86
+ while (stack.length) {
87
+ for (const c of childrenOf.get(stack.pop()) ?? []) {
88
+ if (out.has(c)) continue;
89
+ out.add(c);
90
+ stack.push(c);
91
+ }
92
+ }
93
+ return out;
94
+ };
95
+ return { parentOf, childrenOf, depthOf, ancestorsOf, subtreeOf, neighborsOf };
96
+ }
48
97
 
49
98
  // src/profile.ts
50
99
  function parsePhysical(origin, text) {
@@ -61,6 +110,7 @@ function parsePhysical(origin, text) {
61
110
  label: String(n.label ?? n.name ?? n.id),
62
111
  kind: typeof n.kind === "string" ? n.kind : void 0,
63
112
  parent: ref(n.parent),
113
+ order: typeof n.order === "number" && Number.isFinite(n.order) ? n.order : void 0,
64
114
  layer: typeof n.layer === "string" ? n.layer : void 0,
65
115
  // Marks carried by the data itself (e.g. a placeholder "with no content yet"). They are data, not derived: when the profile's
66
116
  // `placeholderFlags` recognizes one, it is drawn as skeleton.
@@ -81,43 +131,12 @@ function parsePhysical(origin, text) {
81
131
  function toPhysical(model) {
82
132
  const clean2 = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0 && v !== ""));
83
133
  return {
84
- 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 })),
85
136
  edges: model.edges.map((e) => clean2({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }))
86
137
  };
87
138
  }
88
139
  var DEFAULT_LAYER = { id: "default", label: "Graph", z: 0, structural: true };
89
- function validateStructure(model) {
90
- const out = [];
91
- const seen = /* @__PURE__ */ new Set();
92
- const dup = /* @__PURE__ */ new Set();
93
- for (const n of model.nodes) {
94
- if (seen.has(n.id)) dup.add(n.id);
95
- else seen.add(n.id);
96
- }
97
- for (const id of model.duplicateIds ?? []) dup.add(id);
98
- for (const id of dup) out.push({ kind: "duplicate", group: "Duplicate id", level: "warn", nodeId: id, message: `Duplicate node id: ${id} (defined more than once; the first one is kept)` });
99
- const seenEdge = /* @__PURE__ */ new Set();
100
- const dupEdge = /* @__PURE__ */ new Map();
101
- for (const e of model.edges) {
102
- const key = `${e.source}\0${e.target}\0${e.kind ?? ""}`;
103
- if (seenEdge.has(key)) dupEdge.set(key, e);
104
- else seenEdge.add(key);
105
- }
106
- for (const e of dupEdge.values()) {
107
- out.push({
108
- kind: "duplicate-edge",
109
- group: "Duplicate edge",
110
- level: "warn",
111
- edge: { source: e.source, target: e.target },
112
- message: `Duplicate edge: ${e.source} \u2192 ${e.target}${e.kind ? ` (${e.kind})` : ""} is defined more than once`
113
- });
114
- }
115
- for (const e of model.edges) {
116
- const miss = [!seen.has(e.source) && e.source, !seen.has(e.target) && e.target].filter(Boolean).join(" / ");
117
- if (miss) out.push({ kind: "dangling", group: "Dangling edge", level: "warn", edge: { source: e.source, target: e.target }, message: `Dangling edge: points to missing node ${miss}` });
118
- }
119
- return out;
120
- }
121
140
  function defineProfile(input) {
122
141
  const layers = input.layers?.length ? input.layers : [DEFAULT_LAYER];
123
142
  const fallbackLayer = layers[0].id;
@@ -224,7 +243,7 @@ var clean = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !==
224
243
  // adapters/graphify.ts
225
244
  var STRUCT = /* @__PURE__ */ new Set(["contains", "method"]);
226
245
  var NOTE = "rationale_for";
227
- 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);
228
247
  var base = (p) => p.split("/").pop() ?? p;
229
248
  function convertGraphify(d, name) {
230
249
  const raw = d.nodes.filter(isObj);
@@ -735,18 +754,18 @@ function gitSpec(spec, cwd) {
735
754
  throw new Error(`${rel || "."} does not exist at ${ref}`);
736
755
  }
737
756
  if (type === "blob") return { files: [{ path: path.basename(rel), text: git("show", `${ref}:./${rel}`) }], title, isDir: false };
738
- const names = git("ls-tree", "-r", "--name-only", ref, "--", rel || ".").split("\n").filter(Boolean);
757
+ const names2 = git("ls-tree", "-r", "--name-only", ref, "--", rel || ".").split("\n").filter(Boolean);
739
758
  const prefix = rel ? `${rel}/` : "";
740
- const files = names.map((n) => n.split(path.sep).join("/")).filter((n) => DATA.test(n) && !n.split("/").some((s) => s.startsWith(".") && !DOT_OK.has(s) || SKIP_DIR.has(s))).slice(0, MAX_FILES).map((n) => ({ path: n.startsWith(prefix) ? n.slice(prefix.length) : n, text: git("show", `${ref}:./${n}`) }));
759
+ const files = names2.map((n) => n.split(path.sep).join("/")).filter((n) => DATA.test(n) && !n.split("/").some((s) => s.startsWith(".") && !DOT_OK.has(s) || SKIP_DIR.has(s))).slice(0, MAX_FILES).map((n) => ({ path: n.startsWith(prefix) ? n.slice(prefix.length) : n, text: git("show", `${ref}:./${n}`) }));
741
760
  return { files, title, isDir: true };
742
761
  }
743
762
  var META = /* @__PURE__ */ new Set(["_profile.json", "_layout.json"]);
744
763
  var natural = (a2, b) => a2.localeCompare(b, void 0, { numeric: true });
745
764
  function load(spec, opts = {}) {
746
- const tree = readSpec(spec, opts.cwd);
765
+ const tree2 = readSpec(spec, opts.cwd);
747
766
  const metaErrors = [];
748
767
  const meta = (name) => {
749
- const f = tree.files.find((x) => x.path === name);
768
+ const f = tree2.files.find((x) => x.path === name);
750
769
  if (!f) return null;
751
770
  try {
752
771
  return JSON.parse(f.text);
@@ -755,12 +774,12 @@ function load(spec, opts = {}) {
755
774
  return null;
756
775
  }
757
776
  };
758
- const data = tree.files.filter((f) => !META.has(f.path));
777
+ const data = tree2.files.filter((f) => !META.has(f.path));
759
778
  const isJson = (f) => /\.json$/i.test(f.path);
760
779
  const dirs = [...new Set(data.filter((f) => f.path.includes("/")).map((f) => f.path.split("/")[0]))].sort(natural);
761
- const versioned = tree.isDir && !opts.format && dirs.length >= 2 && !dirs.some((d) => DOT_OK.has(d)) && !data.some((f) => !f.path.includes("/") && isJson(f)) && dirs.every((d) => data.some((f) => f.path.startsWith(`${d}/`) && isJson(f)));
780
+ const versioned = tree2.isDir && !opts.format && dirs.length >= 2 && !dirs.some((d) => DOT_OK.has(d)) && !data.some((f) => !f.path.includes("/") && isJson(f)) && dirs.every((d) => data.some((f) => f.path.startsWith(`${d}/`) && isJson(f)));
762
781
  const ignored = versioned ? data.filter((f) => !isJson(f)).map((f) => f.path) : [];
763
- const groups = versioned ? dirs.map((d) => ({ name: d, files: data.filter((f) => f.path.startsWith(`${d}/`) && isJson(f)).map((f) => ({ ...f, path: f.path.slice(d.length + 1) })) })) : [{ name: tree.title, files: data }];
782
+ const groups = versioned ? dirs.map((d) => ({ name: d, files: data.filter((f) => f.path.startsWith(`${d}/`) && isJson(f)).map((f) => ({ ...f, path: f.path.slice(d.length + 1) })) })) : [{ name: tree2.title, files: data }];
764
783
  let suggested = null;
765
784
  let format = "native";
766
785
  const versions = groups.map((g) => {
@@ -773,7 +792,7 @@ function load(spec, opts = {}) {
773
792
  return { name: g.name, sources: r.sources };
774
793
  });
775
794
  return {
776
- title: tree.title,
795
+ title: tree2.title,
777
796
  versions,
778
797
  profile: meta("_profile.json") ?? suggested,
779
798
  layouts: meta("_layout.json"),
@@ -963,12 +982,63 @@ function diffModels(before, after, opts = {}) {
963
982
  };
964
983
  }
965
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
+
966
1036
  // schema/graph.schema.json
967
1037
  var graph_schema_default = {
968
1038
  $schema: "https://json-schema.org/draft/2020-12/schema",
969
1039
  $id: "https://unpkg.com/glassbrain/schema/graph.schema.json",
970
1040
  title: "glassbrain graph",
971
- 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.",
972
1042
  type: "object",
973
1043
  anyOf: [{ required: ["nodes"] }, { required: ["edges"] }],
974
1044
  properties: {
@@ -986,14 +1056,14 @@ var graph_schema_default = {
986
1056
  $defs: {
987
1057
  node: {
988
1058
  type: "object",
989
- required: ["id"],
1059
+ required: ["id", "parent"],
990
1060
  properties: {
991
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." },
992
1062
  label: { type: "string", description: "Display name. Falls back to `name`, then `id`." },
993
1063
  name: { type: "string", description: "Alias of `label`." },
994
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." },
995
- 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." },
996
- 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." },
997
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." },
998
1068
  description: { type: "string", description: "Markdown shown in the detail panel. `[text](node:<id>)` links jump to another node." }
999
1069
  },
@@ -1024,57 +1094,129 @@ var profile_schema_default = {
1024
1094
  $schema: "https://json-schema.org/draft/2020-12/schema",
1025
1095
  $id: "https://unpkg.com/glassbrain/schema/profile.schema.json",
1026
1096
  title: "glassbrain profile (_profile.json)",
1027
- 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.",
1028
1098
  type: "object",
1029
1099
  properties: {
1030
- 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: {
1031
1117
  type: "array",
1032
- description: "Layers for the 2.5D plane view. One default layer if omitted.",
1033
1118
  items: {
1034
- type: "object",
1035
- required: ["id", "label"],
1036
- properties: {
1037
- id: { type: "string" },
1038
- label: { type: "string" },
1039
- z: { type: "number", description: "Plane order: 0 is the bottom." },
1040
- color: { type: "string", description: "Hue of the plane." },
1041
- 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."
1042
1145
  }
1043
1146
  }
1044
1147
  },
1045
- nodePalette: { $ref: "#/$defs/colors", description: "Node kind \u2192 color. Kinds not listed are skeleton." },
1046
- edgePalette: { $ref: "#/$defs/colors", description: "Edge kind \u2192 color." },
1047
- nodeSize: { $ref: "#/$defs/numbers", description: "Node kind \u2192 size multiplier (1 = default)." },
1048
- edgeWidth: { $ref: "#/$defs/numbers", description: "Edge kind \u2192 width multiplier." },
1049
- placeholderFlags: { type: "array", items: { type: "string" }, description: "Nodes with any of these flags are drawn as placeholders (declared, not yet filled)." },
1050
- kindLabels: { $ref: "#/$defs/strings", description: "Kind \u2192 human-readable name (nodes and edges share this map)." },
1051
- edgeLabels: { $ref: "#/$defs/strings", description: "Same as kindLabels, for edge kinds; merged into it." },
1052
- 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
+ },
1053
1152
  detail: {
1054
1153
  type: "object",
1055
1154
  description: "Detail panel field tables.",
1056
1155
  properties: {
1057
- line: { $ref: "#/$defs/fields" },
1058
- list: { $ref: "#/$defs/fields" },
1059
- skip: { type: "array", items: { type: "string" } },
1060
- 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
+ }
1061
1171
  }
1062
1172
  },
1063
- singleRoot: { type: "boolean", description: "Wrap several top-level nodes in one root box (default true)." },
1064
- rootLabel: { type: "string" },
1065
- 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
+ }
1066
1183
  },
1067
1184
  additionalProperties: true,
1068
1185
  $defs: {
1069
- colors: { type: "object", additionalProperties: { type: "string" } },
1070
- numbers: { type: "object", additionalProperties: { type: "number" } },
1071
- 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
+ },
1072
1204
  fields: {
1073
1205
  type: "array",
1074
1206
  items: {
1075
1207
  type: "object",
1076
- required: ["key", "label"],
1077
- 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
+ }
1078
1220
  }
1079
1221
  }
1080
1222
  }
@@ -1095,7 +1237,8 @@ var KNOWN = /* @__PURE__ */ new Set([
1095
1237
  "anyOf",
1096
1238
  "$ref",
1097
1239
  "minimum",
1098
- "maximum"
1240
+ "maximum",
1241
+ "exclusiveMinimum"
1099
1242
  ]);
1100
1243
  var typeOf = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v === "number" ? Number.isInteger(v) ? "integer" : "number" : typeof v;
1101
1244
  var fits = (v, t) => {
@@ -1136,6 +1279,7 @@ function checkSchema(root, value, limit = 50) {
1136
1279
  if (typeof v === "number") {
1137
1280
  if (s.minimum != null && v < s.minimum) out2.push({ path: path3, message: `must be \u2265 ${s.minimum}` });
1138
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}` });
1139
1283
  }
1140
1284
  };
1141
1285
  const out = [];
@@ -1143,23 +1287,534 @@ function checkSchema(root, value, limit = 50) {
1143
1287
  return out;
1144
1288
  }
1145
1289
 
1290
+ // cli/checks.ts
1291
+ var ISOMORPHISM_TAU = 0.85;
1292
+ var WIDE_INFO = 5;
1293
+ var WIDE_WARN = 10;
1294
+ var MAX_NAMES = 4;
1295
+ var MIN_SAMPLE = 10;
1296
+ var names = (xs) => `${xs.slice(0, MAX_NAMES).join(", ")}${xs.length > MAX_NAMES ? ` and ${xs.length - MAX_NAMES} more` : ""}`;
1297
+ var misplacedField = {
1298
+ code: "misplaced-field",
1299
+ level: "error",
1300
+ run: ({ model }) => {
1301
+ const reserved = ["id", "label", "kind", "parent", "order", "description"];
1302
+ const out = [];
1303
+ for (const n of model.nodes) {
1304
+ const nested = n.data?.data;
1305
+ if (!nested || typeof nested !== "object" || Array.isArray(nested)) continue;
1306
+ const found = reserved.filter((k) => k in nested);
1307
+ if (!found.length) continue;
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
+ });
1315
+ }
1316
+ return out;
1317
+ }
1318
+ };
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",
1332
+ level: "error",
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
+ }))
1341
+ };
1342
+ var parentCycle = {
1343
+ code: "parent-cycle",
1344
+ level: "error",
1345
+ run: ({ model, index: index2 }) => {
1346
+ const out = [];
1347
+ const done = /* @__PURE__ */ new Set();
1348
+ for (const start of model.nodes) {
1349
+ if (done.has(start.id)) continue;
1350
+ const path3 = [];
1351
+ const at = /* @__PURE__ */ new Map();
1352
+ let cur = start.id;
1353
+ while (cur && !done.has(cur)) {
1354
+ const seen = at.get(cur);
1355
+ if (seen !== void 0) {
1356
+ const loop = path3.slice(seen);
1357
+ loop.forEach((id) => done.add(id));
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
+ });
1365
+ break;
1366
+ }
1367
+ at.set(cur, path3.length);
1368
+ path3.push(cur);
1369
+ const parent = index2.get(cur)?.parent;
1370
+ cur = parent && index2.has(parent) ? parent : void 0;
1371
+ }
1372
+ for (const id of path3) done.add(id);
1373
+ }
1374
+ return out;
1375
+ }
1376
+ };
1377
+ var orderMixed = {
1378
+ code: "order-mixed",
1379
+ level: "error",
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;
1396
+ }
1397
+ };
1398
+ var orderDuplicate = {
1399
+ code: "order-duplicate",
1400
+ level: "error",
1401
+ run: ({ children }) => {
1402
+ const out = [];
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
+ }
1420
+ }
1421
+ return out;
1422
+ }
1423
+ };
1424
+ var conflictingDefinition = {
1425
+ code: "conflicting-definition",
1426
+ level: "error",
1427
+ run: ({ model, index: index2, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1428
+ node: id,
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.`
1432
+ }))
1433
+ };
1434
+ var danglingEdge = {
1435
+ code: "dangling-edge",
1436
+ level: "error",
1437
+ run: ({ model, index: index2, labelOf }) => {
1438
+ const out = [];
1439
+ for (const e of model.edges) {
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
+ });
1448
+ }
1449
+ return out;
1450
+ }
1451
+ };
1452
+ var duplicateEdge = {
1453
+ code: "duplicate-edge",
1454
+ level: "warn",
1455
+ run: ({ model }) => {
1456
+ const times = /* @__PURE__ */ new Map();
1457
+ for (const e of model.edges) {
1458
+ const key = `${e.source}\0${e.target}\0${e.kind ?? ""}`;
1459
+ times.set(key, (times.get(key) ?? 0) + 1);
1460
+ }
1461
+ const out = [];
1462
+ for (const [key, count2] of times) {
1463
+ if (count2 < 2) continue;
1464
+ const [source, target, kind] = key.split("\0");
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
+ });
1470
+ }
1471
+ return out;
1472
+ }
1473
+ };
1474
+ var multipleRoots = {
1475
+ code: "multiple-roots",
1476
+ level: "warn",
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);
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 }) => {
1561
+ const out = [];
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`;
1568
+ out.push({
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" }`
1579
+ });
1580
+ }
1581
+ return out;
1582
+ }
1583
+ };
1584
+ var preferFewerKinds = {
1585
+ code: "prefer-fewer-kinds",
1586
+ level: "info",
1587
+ run: ({ model }) => {
1588
+ const out = [];
1589
+ const spread = (space, counts, total) => {
1590
+ const kinds = counts.size;
1591
+ if (!kinds || total < MIN_SAMPLE) return;
1592
+ const average = total / kinds;
1593
+ if (kinds > 10 || average < 5) {
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
+ });
1598
+ }
1599
+ };
1600
+ spread("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1601
+ spread("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1602
+ return out;
1603
+ }
1604
+ };
1605
+ var loneKind = {
1606
+ code: "lone-kind",
1607
+ level: "info",
1608
+ run: ({ model }) => {
1609
+ const out = [];
1610
+ const lone = (space, counts, total) => {
1611
+ if (total < MIN_SAMPLE) return;
1612
+ const once = [...counts].filter(([, c]) => c === 1).map(([k]) => k);
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.` });
1614
+ };
1615
+ lone("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1616
+ lone("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1617
+ return out;
1618
+ }
1619
+ };
1620
+ var lowCoverage = {
1621
+ code: "low-coverage",
1622
+ level: "info",
1623
+ run: ({ model, children }) => {
1624
+ const leaves = model.nodes.filter((n) => !children.has(n.id));
1625
+ if (leaves.length < 20) return [];
1626
+ const described = leaves.filter((n) => typeof n.data?.description === "string" && n.data.description.trim()).length;
1627
+ if (described / leaves.length >= 0.5) return [];
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
+ }];
1633
+ }
1634
+ };
1635
+ var colorsContrast = {
1636
+ code: "colors-contrast",
1637
+ level: "info",
1638
+ run: ({ profile }) => {
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
+ }];
1656
+ }
1657
+ };
1658
+ var rules = [
1659
+ misplacedField,
1660
+ layerField,
1661
+ unknownParent,
1662
+ parentCycle,
1663
+ orderMixed,
1664
+ orderDuplicate,
1665
+ conflictingDefinition,
1666
+ danglingEdge,
1667
+ duplicateEdge,
1668
+ multipleRoots,
1669
+ noHierarchy,
1670
+ unevenBranches,
1671
+ wideNode,
1672
+ preferFewerKinds,
1673
+ loneKind,
1674
+ lowCoverage,
1675
+ colorsContrast
1676
+ ];
1677
+ function checkGraph(model, profile, opts) {
1678
+ const children = /* @__PURE__ */ new Map();
1679
+ for (const n of model.nodes) {
1680
+ if (!n.parent || !model.index.has(n.parent)) continue;
1681
+ const arr = children.get(n.parent);
1682
+ if (arr) arr.push(n);
1683
+ else children.set(n.parent, [n]);
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
+ };
1696
+ const ctx = {
1697
+ model,
1698
+ profile,
1699
+ where: opts.where,
1700
+ index: model.index,
1701
+ children,
1702
+ layers: deriveLayers(model),
1703
+ labelOf: (id) => model.index.get(id)?.label ?? id,
1704
+ heightOf: (id) => heightOf(id),
1705
+ sameFileDuplicates: opts.sameFileDuplicates ?? /* @__PURE__ */ new Set()
1706
+ };
1707
+ const out = rules.flatMap((rule) => rule.run(ctx).map((issue) => ({
1708
+ level: issue.level ?? rule.level,
1709
+ code: rule.code,
1710
+ where: opts.where,
1711
+ message: issue.message,
1712
+ ...issue.fix !== void 0 ? { fix: issue.fix } : {},
1713
+ ...issue.node !== void 0 ? { node: issue.node } : {}
1714
+ })));
1715
+ return out;
1716
+ }
1717
+ function structureOf(model) {
1718
+ const index2 = indexModel(model);
1719
+ let depth = 0;
1720
+ let parented = 0;
1721
+ for (const n of model.nodes) {
1722
+ if (n.parent && model.index.has(n.parent)) parented++;
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]);
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);
1743
+ return {
1744
+ nodes: model.nodes.length,
1745
+ edges: model.edges.length,
1746
+ roots: model.nodes.filter((n) => !n.parent).length,
1747
+ depth,
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)
1752
+ };
1753
+ }
1754
+ function countsBy(values) {
1755
+ const out = /* @__PURE__ */ new Map();
1756
+ for (const v of values) if (v) out.set(v, (out.get(v) ?? 0) + 1);
1757
+ return out;
1758
+ }
1759
+ function hexLab(value) {
1760
+ const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(value.trim());
1761
+ if (!m) return null;
1762
+ const hex = m[1].length === 3 ? [...m[1]].map((c) => c + c).join("") : m[1];
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]);
1773
+ }
1774
+
1146
1775
  // cli/model.ts
1147
1776
  function profileFromJson(id, json) {
1148
1777
  if (!json) return defineProfile({ id });
1149
- const { demo: _demo, diffIgnore: _ignore, edgeLabels = {}, ...rest } = json;
1778
+ const { demo: _demo, diffIgnore: _ignore, edgeLabels = {}, layers: _layers, singleRoot: _single, ...rest } = json;
1150
1779
  return defineProfile({ id, ...rest, kindLabels: { ...rest.kindLabels, ...edgeLabels } });
1151
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
+ }
1152
1795
  var modelOf = (v, profile) => parseSources(v.sources, profile);
1796
+ var RANK = { error: 0, warn: 1, info: 2 };
1153
1797
  function validate(loaded) {
1154
1798
  const out = [];
1155
- const profile = profileFromJson("cli", loaded.profile);
1799
+ const profile = profileOf(loaded);
1156
1800
  if (loaded.profile) {
1157
- for (const e of checkSchema(profile_schema_default, loaded.profile)) out.push({ level: "error", where: "_profile.json", message: `${e.path}: ${e.message}` });
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
+ });
1158
1811
  }
1159
- for (const e of loaded.metaErrors) out.push({ level: "error", where: e.file, message: e.message });
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;
1160
1814
  for (const { version, files } of loaded.raw) {
1161
1815
  const prefix = loaded.versions.length > 1 ? `${version}/` : "";
1162
1816
  const notJson = /* @__PURE__ */ new Set();
1817
+ const sameFileDuplicates = /* @__PURE__ */ new Set();
1163
1818
  if (loaded.format === "native") {
1164
1819
  for (const f of files) {
1165
1820
  if (!/\.json$/i.test(f.path)) continue;
@@ -1168,45 +1823,47 @@ function validate(loaded) {
1168
1823
  doc = JSON.parse(f.text);
1169
1824
  } catch (e) {
1170
1825
  notJson.add(f.path);
1171
- out.push({ level: "error", where: prefix + f.path, message: `not JSON: ${e.message}` });
1826
+ out.push({ level: "error", code: "not-json", where: prefix + f.path, message: `not JSON: ${e.message}` });
1172
1827
  continue;
1173
1828
  }
1174
1829
  if (!doc || typeof doc !== "object" || !("nodes" in doc) && !("edges" in doc)) {
1175
- out.push({ level: "warn", where: prefix + f.path, message: 'not a graph (no "nodes" or "edges"), skipped' });
1830
+ out.push({ level: "warn", code: "not-a-graph", where: prefix + f.path, message: 'not a graph (no "nodes" or "edges"), skipped' });
1176
1831
  continue;
1177
1832
  }
1178
- for (const e of checkSchema(graph_schema_default, doc)) out.push({ level: "error", where: prefix + f.path, message: `${e.path}: ${e.message}` });
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
+ });
1846
+ const seen = /* @__PURE__ */ new Map();
1847
+ for (const id of idsIn(doc)) seen.set(id, (seen.get(id) ?? 0) + 1);
1848
+ for (const [id, count2] of seen) {
1849
+ if (count2 < 2) continue;
1850
+ sameFileDuplicates.add(id);
1851
+ out.push({ level: "error", code: "same-file-duplicate", where: prefix + f.path, message: `id "${id}" appears ${count2} times in this file; the first one is kept` });
1852
+ }
1179
1853
  }
1180
1854
  }
1181
1855
  const v = loaded.versions.find((x) => x.name === version);
1182
1856
  const model = modelOf(v, profile);
1183
- for (const e of model.errors) if (!notJson.has(e.origin)) out.push({ level: "error", where: prefix + e.origin, message: e.message });
1184
- for (const i of [...validateStructure(model), ...structure(model)]) out.push({ level: i.level, where: prefix || loaded.title, message: i.message });
1185
- if (!model.nodes.length) out.push({ level: "warn", where: prefix || loaded.title, message: "No nodes found" });
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 });
1858
+ if (version === latest) out.push(...checkGraph(model, profile, { where: prefix || loaded.title, sameFileDuplicates }));
1859
+ if (!model.nodes.length) out.push({ level: "warn", code: "empty", where: prefix || loaded.title, message: "No nodes found" });
1186
1860
  }
1187
- return out;
1861
+ return out.sort((a2, b) => RANK[a2.level] - RANK[b.level]);
1188
1862
  }
1189
- function structure(model) {
1190
- const out = [];
1191
- for (const n of model.nodes) {
1192
- if (n.parent && !model.index.has(n.parent)) {
1193
- out.push({ kind: "missing-parent", level: "warn", nodeId: n.id, message: `Missing parent: ${n.id} sits inside ${n.parent}, which does not exist (drawn at top level)` });
1194
- }
1195
- }
1196
- const reported = /* @__PURE__ */ new Set();
1197
- for (const n of model.nodes) {
1198
- const seen = [];
1199
- for (let p = n.id; p && !reported.has(p); p = model.index.get(p)?.parent) {
1200
- if (seen.includes(p)) {
1201
- const loop = seen.slice(seen.indexOf(p));
1202
- loop.forEach((x) => reported.add(x));
1203
- out.push({ kind: "parent-cycle", level: "error", nodeId: p, message: `Parent cycle: ${[...loop, p].join(" \u2192 ")}` });
1204
- break;
1205
- }
1206
- seen.push(p);
1207
- }
1208
- }
1209
- return out;
1863
+ function idsIn(doc) {
1864
+ const nodes = doc.nodes;
1865
+ if (!Array.isArray(nodes)) return [];
1866
+ return nodes.filter((n) => !!n && typeof n === "object" && "id" in n && n.id != null).map((n) => String(n.id));
1210
1867
  }
1211
1868
  var ignoreOf = (profile, extra = []) => [.../* @__PURE__ */ new Set([...Array.isArray(profile?.diffIgnore) ? profile.diffIgnore : [], ...extra])];
1212
1869
  function diff(before, after, labels, ignore = []) {
@@ -1270,90 +1927,493 @@ function diffText(s, labelOf, limit = 20) {
1270
1927
  return L.join("\n");
1271
1928
  }
1272
1929
 
1273
- // cli/glassbrain.ts
1274
- var HELP = (schema) => `glassbrain: open, diff and validate knowledge graphs, written as plain JSON.
1930
+ // cli/tree.ts
1931
+ var one = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1932
+ var MAX_SIBLINGS = 12;
1933
+ var MAX_LINES = 200;
1934
+ var MAX_EDGES = 6;
1935
+ function tree(model, opts) {
1936
+ const derived = deriveLayers(model);
1937
+ const layerOf = (n) => derived.layerOf.get(n.id);
1938
+ const labelOf = (id) => model.index.get(id)?.label ?? id;
1939
+ const depth = Math.max(1, opts.depth ?? 3);
1940
+ const perNode = Math.max(1, opts.perNode ?? MAX_SIBLINGS);
1941
+ const maxLines = Math.max(1, opts.maxLines ?? MAX_LINES);
1942
+ const kids = /* @__PURE__ */ new Map();
1943
+ for (const n of model.nodes) {
1944
+ if (!n.parent || !model.index.has(n.parent)) continue;
1945
+ const arr = kids.get(n.parent);
1946
+ if (arr) arr.push(n);
1947
+ else kids.set(n.parent, [n]);
1948
+ }
1949
+ const size = /* @__PURE__ */ new Map();
1950
+ const height = /* @__PURE__ */ new Map();
1951
+ const measuring = /* @__PURE__ */ new Set();
1952
+ const measure = (id) => {
1953
+ const hit = size.get(id);
1954
+ if (hit !== void 0) return hit;
1955
+ if (measuring.has(id)) return 1;
1956
+ measuring.add(id);
1957
+ let total = 1;
1958
+ let tall = 0;
1959
+ for (const k of kids.get(id) ?? []) {
1960
+ total += measure(k.id);
1961
+ tall = Math.max(tall, (height.get(k.id) ?? 0) + 1);
1962
+ }
1963
+ measuring.delete(id);
1964
+ size.set(id, total);
1965
+ height.set(id, tall);
1966
+ return total;
1967
+ };
1968
+ for (const n of model.nodes) measure(n.id);
1969
+ const bySize = (a2, b) => (size.get(b.id) ?? 1) - (size.get(a2.id) ?? 1) || labelOf(a2.id).localeCompare(labelOf(b.id));
1970
+ const sorted = /* @__PURE__ */ new Map();
1971
+ for (const [id, list] of kids) {
1972
+ sorted.set(id, orderedChildren(kids, id) ?? [...list].sort(bySize));
1973
+ }
1974
+ const outgoing = /* @__PURE__ */ new Map();
1975
+ for (const e of model.edges) {
1976
+ if (!model.index.has(e.source) || !model.index.has(e.target)) continue;
1977
+ const item = `${e.kind ?? "\u2192"}::${labelOf(e.target)}`;
1978
+ const arr = outgoing.get(e.source);
1979
+ if (arr) arr.push(item);
1980
+ else outgoing.set(e.source, [item]);
1981
+ }
1982
+ for (const list of outgoing.values()) list.sort();
1983
+ const entries = [];
1984
+ const edgeText = (all) => `(${all.slice(0, MAX_EDGES).join(", ")}${all.length > MAX_EDGES ? ` \u2026 ${all.length - MAX_EDGES} more` : ""})`;
1985
+ const broken = (n) => n.parent && !model.index.has(n.parent);
1986
+ const visit = (node, level, prefix, connector) => {
1987
+ const list = sorted.get(node.id) ?? [];
1988
+ const canExpand = level + 1 < depth && list.length > 0;
1989
+ const collapsed = list.length > 0 && !canExpand;
1990
+ const inside = (size.get(node.id) ?? 1) - 1;
1991
+ const tall = height.get(node.id) ?? 0;
1992
+ const edges = collapsed ? [] : outgoing.get(node.id) ?? [];
1993
+ const bits = [];
1994
+ if (inside > 0) bits.push(one(inside, "node"));
1995
+ if (collapsed && tall > 0) bits.push(`${tall} deep`);
1996
+ if (edges.length) bits.push(edgeText(edges));
1997
+ const label = `${labelOf(node.id)}${broken(node) ? " (parent missing)" : ""}`;
1998
+ const orderTag = typeof node.order === "number" ? `[${node.order}] ` : "";
1999
+ entries.push({
2000
+ id: node.id,
2001
+ label,
2002
+ depth: level,
2003
+ layer: layerOf(node),
2004
+ ...typeof node.order === "number" ? { order: node.order } : {},
2005
+ nodes: inside,
2006
+ deep: tall,
2007
+ collapsed,
2008
+ edges,
2009
+ text: `${prefix}${connector}${orderTag}${label}${bits.length ? ` ${bits.join(" \xB7 ")}` : ""}`
2010
+ });
2011
+ if (!canExpand) return;
2012
+ const shown = list.slice(0, perNode);
2013
+ const childPrefix = prefix + (level === 0 ? "" : connector.includes("\u2514") ? " " : "\u2502 ");
2014
+ shown.forEach((child, i) => {
2015
+ const last = i === shown.length - 1 && list.length <= perNode;
2016
+ visit(child, level + 1, childPrefix, last ? "\u2514\u2500 " : "\u251C\u2500 ");
2017
+ });
2018
+ if (list.length > perNode) {
2019
+ entries.push({
2020
+ id: null,
2021
+ label: `\u2026 ${list.length - perNode} more`,
2022
+ depth: level + 1,
2023
+ nodes: 0,
2024
+ deep: 0,
2025
+ collapsed: false,
2026
+ edges: [],
2027
+ text: `${childPrefix}\u2514\u2500 \u2026 ${list.length - perNode} more`
2028
+ });
2029
+ }
2030
+ };
2031
+ const structure = structureOf(model);
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)}`;
2033
+ const roots = model.nodes.filter((n) => !n.parent || broken(n));
2034
+ if (opts.path) {
2035
+ const start = model.index.get(opts.path);
2036
+ if (!start) throw new Error(`no node "${opts.path}" in ${opts.title}`);
2037
+ const chain = [];
2038
+ let up = start.parent;
2039
+ const seen = /* @__PURE__ */ new Set([start.id]);
2040
+ while (up && model.index.has(up) && !seen.has(up)) {
2041
+ seen.add(up);
2042
+ chain.unshift(labelOf(up));
2043
+ up = model.index.get(up)?.parent;
2044
+ }
2045
+ header += `
2046
+ path: ${[...chain, labelOf(start.id)].join(" \u203A ")}`;
2047
+ visit(start, 0, "", "");
2048
+ } else if (opts.orphans) {
2049
+ for (const n of roots.slice(0, perNode)) {
2050
+ const inside = (size.get(n.id) ?? 1) - 1;
2051
+ const label = `${labelOf(n.id)}${broken(n) ? " (parent missing)" : ""}`;
2052
+ entries.push({
2053
+ id: n.id,
2054
+ label,
2055
+ depth: 0,
2056
+ layer: layerOf(n),
2057
+ nodes: inside,
2058
+ deep: height.get(n.id) ?? 0,
2059
+ collapsed: true,
2060
+ edges: [],
2061
+ text: `${label}${inside ? ` ${one(inside, "node")}` : ""}`
2062
+ });
2063
+ }
2064
+ if (roots.length > perNode) {
2065
+ entries.push({ id: null, label: `\u2026 ${roots.length - perNode} more`, depth: 0, nodes: 0, deep: 0, collapsed: false, edges: [], text: `\u2026 ${roots.length - perNode} more` });
2066
+ }
2067
+ } else {
2068
+ const shown = roots.slice(0, perNode);
2069
+ shown.forEach((root) => visit(root, 0, "", ""));
2070
+ if (roots.length > perNode) {
2071
+ entries.push({ id: null, label: `\u2026 ${roots.length - perNode} more`, depth: 0, nodes: 0, deep: 0, collapsed: false, edges: [], text: `\u2026 ${roots.length - perNode} more roots` });
2072
+ }
2073
+ }
2074
+ const more = Math.max(0, entries.length - maxLines);
2075
+ return { header, entries: more ? entries.slice(0, maxLines) : entries, more };
2076
+ }
2077
+ function treeText(result) {
2078
+ const lines = [result.header, ...result.entries.map((e) => e.text)];
2079
+ if (result.more) lines.push(`\u2026 ${result.more} more lines (raise --depth, or narrow with --path <id>)`);
2080
+ return lines.join("\n");
2081
+ }
1275
2082
 
1276
- [ STRUCTURE ]
1277
- A folder is a graph; one folder per pass, the name sets the order.
1278
- kg/
1279
- \u251C\u2500\u2500 _profile.json shared by every pass ( see [ APPEARANCE ] )
1280
- \u251C\u2500\u2500 1-skeleton/graph.json each folder holds a graph ( see [ DATA ] )
1281
- \u251C\u2500\u2500 2-filled/graph.json
1282
- \u2514\u2500\u2500 3-linked/graph.json
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
+ }
1283
2296
 
1284
- Passes are optional. Use them for the step harness, diffs and version control.
1285
- JSON at any depth merges by id; split by area only when a file gets too big to write.
2297
+ // cli/glassbrain.ts
2298
+ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, written as plain JSON.
2299
+
2300
+ [ THE THREE AXES ]
2301
+ Different things. Do not use one where another belongs.
2302
+ pass a snapshot in time \u2014 one folder per pass (1-skeleton/, 2-filled/)
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
1286
2305
 
1287
2306
  [ DATA ]
1288
- Two arrays, \`nodes\` and \`edges\`.
1289
- { "nodes": [
1290
- { "id": "src", "label": "src", "kind": "folder" },
1291
- { "id": "src/login.ts", "label": "login.ts", "kind": "file", "parent": "src",
1292
- "description": "Checks the password, then opens a session. Markdown." },
1293
- { "id": "src/db.ts", "label": "db.ts", "kind": "file", "parent": "src" } ],
1294
- "edges": [
1295
- { "source": "src/login.ts", "target": "src/db.ts", "kind": "uses" } ] }
2307
+ Two arrays. The \`//\` notes are not part of the file: strip them and it is valid JSON
2308
+ (if validate says \`not JSON\`, a note survived the copy).
2309
+
2310
+ { "nodes": [
2311
+ { "id": "src", "label": "src", "kind": "folder",
2312
+ "parent": null }, // the root: parent is null
2313
+ { "id": "src/login.ts", "label": "login.ts", "kind": "file",
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 } ],
2319
+ "edges": [
2320
+ { "source": "src/login.ts", "target": "src/db.ts", "kind": "uses" } ] }
1296
2321
 
1297
- The parent structure helps readability. Start with a few meaningful groups and give every other node a parent.
1298
- Keep kinds few and consistent; put supporting detail in descriptions.
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
2324
+ nothing else. \`kind\` gives the color; \`description\` is what the panel says.
1299
2325
 
1300
- FIELDS
1301
- id stable across passes: a path or a slug, never a counter
1302
- label what is shown (defaults to id)
1303
- kind a word: folder, file, feature, decision
1304
- parent id of the node this sits inside
1305
- description markdown; [text](node:<id>) links to a node
1306
- flags e.g. ["stub"] for a node not filled in yet
1307
- layer which plane ( see [ APPEARANCE ] )
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.
1308
2332
 
1309
- Any other field is kept and shown in the detail panel.
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
1310
2340
 
1311
2341
  Full schema: ${schema}
1312
2342
 
2343
+ [ STRUCTURE ]
2344
+ A folder is a graph. Passes are optional; one numbered folder each.
2345
+
2346
+ kg/
2347
+ \u251C\u2500\u2500 _profile.json colors, shared by every pass (see [ APPEARANCE ])
2348
+ \u251C\u2500\u2500 1-skeleton/graph.json a graph (see [ DATA ])
2349
+ \u251C\u2500\u2500 2-filled/graph.json each pass is the whole graph: copy the last, edit the copy
2350
+ \u2514\u2500\u2500 3-linked/graph.json then validate, and diff against the pass before
2351
+
2352
+ Files inside one pass merge by id: the same node described twice is one node.
2353
+ Two files defining that id differently is an error, not a merge.
2354
+ Split by area only when a file gets too big to write.
2355
+
1313
2356
  [ APPEARANCE ]
1314
- kg/_profile.json, shared by every pass.
2357
+ kg/_profile.json, shared by every pass. Everything in it is optional.
1315
2358
 
1316
- COLORS give each kind you use a color; the rest stay grey.
1317
- { "nodePalette": { "file": "#6366f1", "function": "#10b981" },
1318
- "edgePalette": { "calls": "#2563eb" }, "placeholderFlags": ["stub"] }
1319
- "placeholderFlags" makes a flagged "stub" look unfinished.
2359
+ COLORS one entry per kind you use; unlisted kinds stay neutral.
2360
+ { "nodePalette": { "file": "#6366f1", "folder": "#94a3b8" },
2361
+ "edgePalette": { "uses": "#2563eb" } }
2362
+ Colors closer than 10 in Lab distance read as one kind (validate notes it).
1320
2363
 
1321
- LAYERS only for real planes: abstraction levels (contract vs implementation),
1322
- never grouping. A node picks one with "layer", else the first; "z" orders them.
1323
- { "layers": [ { "id": "api", "label": "API", "z": 0 },
1324
- { "id": "ui", "label": "UI", "z": 1 } ] }
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.
1325
2368
 
1326
2369
  Full schema: ${schema.replace("graph.schema", "profile.schema")}
1327
2370
 
1328
2371
  [ COMMANDS ]
1329
- Always: validate before handing over. Fix everything it reports.
2372
+ Always validate before handing over; a page is only written for a graph with no errors.
1330
2373
 
1331
- glassbrain <path> open it (passes play as steps); prints the path to hand over
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)
2376
+ glassbrain validate <path> errors, warnings, info; exit 1 on errors
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.
1332
2382
  glassbrain diff <old> <new> only what changed between two graphs
1333
- glassbrain diff <git-ref> <path> in a git repo, the same graph at an earlier commit, where
1334
- the history is the versions (default ref: HEAD)
1335
- glassbrain validate <path> schema and structure
2383
+ glassbrain diff <git-ref> <path> the same graph at an earlier commit (default HEAD)
1336
2384
  glassbrain convert <path> [out-dir] write any supported format as glassbrain JSON
1337
2385
 
1338
- <path> is a file, a folder, or <git-ref>:<path> (HEAD~1:kg/graph.json).
1339
- Also reads Graphify, Understand-Anything, memory.jsonl and markdown folders as-is.
2386
+ <path> is a file, a folder, or <git-ref>:<path> (HEAD~1:kg/graph.json). Graphify,
2387
+ Understand-Anything, memory.jsonl and markdown folders are read as-is.
2388
+
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
2396
+ exit codes: 0 clean \xB7 1 errors (--strict: warnings too) \xB7 2 usage.
2397
+ It always ends with the structure and the tree command for that graph.
1340
2398
 
1341
2399
  [ OPTIONS ]
1342
- --json machine-readable output (diff, validate)
1343
- --strict exit 1 on warnings too (validate)
2400
+ --json machine-readable output (validate, tree, diff, restructure)
2401
+ --strict warnings fail too (validate, view)
2402
+ --depth <n> tree: levels to expand (default 3)
2403
+ --path <id> tree: one node, its ancestors and its subtree
2404
+ --orphans tree: only nodes with no parent
2405
+ --dry-run restructure: print the plan, write nothing
2406
+ --out <file.html> write the page here instead of a temp file (view, diff)
2407
+ --open / --no-open open the browser or not (diff opens only in a terminal)
1344
2408
  --exit-code exit 1 when anything changed (diff)
1345
2409
  --all list every change, not the first 20 (diff)
1346
2410
  --ignore <a,b> fields that do not count as a change (diff)
1347
- --out <file.html> write the page here instead of a temp file (view, diff)
1348
- --open / --no-open open the browser or not (diff opens only in a terminal)
1349
2411
  --format <id> force a format: native, graphify, understand-anything, memory, obsidian
1350
2412
  -h, --help / -v, --version this help / the version
1351
-
1352
- More: https://github.com/voidixyn/glassbrain
1353
2413
  `;
1354
- var VALUED = /* @__PURE__ */ new Set(["out", "format", "ignore"]);
1355
- var SWITCHES = /* @__PURE__ */ new Set(["open", "json", "all", "exit-code", "strict", "help", "version"]);
1356
- var COMMANDS = ["view", "diff", "validate", "convert"];
2414
+ var VALUED = /* @__PURE__ */ new Set(["out", "format", "ignore", "depth", "path"]);
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"];
1357
2417
  function parseArgs(argv) {
1358
2418
  const pos = [];
1359
2419
  const flags = {};
@@ -1400,6 +2460,19 @@ function writePage(payload, out) {
1400
2460
  return file;
1401
2461
  }
1402
2462
  var count = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
2463
+ var TAG = { error: "error", warn: "warn ", info: "info " };
2464
+ var tally = (found) => ({
2465
+ error: found.filter((f) => f.level === "error").length,
2466
+ warn: found.filter((f) => f.level === "warn").length,
2467
+ info: found.filter((f) => f.level === "info").length
2468
+ });
2469
+ function printFindings(found, limit = 40) {
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
+ }
2474
+ if (found.length > limit) console.log(`\u2026 ${found.length - limit} more (--json)`);
2475
+ }
1403
2476
  var slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "graph";
1404
2477
  function openFile(file) {
1405
2478
  const [cmd, args] = process.platform === "darwin" ? ["open", [file]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", file]] : ["xdg-open", [file]];
@@ -1410,7 +2483,7 @@ function openFile(file) {
1410
2483
  }
1411
2484
  }
1412
2485
  var nodesOf = (l) => {
1413
- const profile = profileFromJson("cli", l.profile);
2486
+ const profile = profileOf(l);
1414
2487
  return l.versions.map((v) => modelOf(v, profile));
1415
2488
  };
1416
2489
  function notes(l, models) {
@@ -1429,9 +2502,23 @@ function view(a2) {
1429
2502
  const l = load(a2.pos[0], { format: a2.flags.format });
1430
2503
  const models = nodesOf(l);
1431
2504
  notes(l, models);
2505
+ const found = validate(l);
2506
+ const n = tally(found);
2507
+ if (n.error || a2.flags.strict && n.warn) {
2508
+ console.log(summaryOf(l, models[models.length - 1]));
2509
+ printFindings(found);
2510
+ console.log(`
2511
+ ${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \u2014 page not written. Fix them, then validate again.`);
2512
+ process.exitCode = 1;
2513
+ return;
2514
+ }
1432
2515
  const file = writePage({ title: l.title, profile: l.profile, versions: l.versions, layouts: l.layouts, start: { at: l.versions.length - 1, compare: false } }, a2.flags.out);
1433
2516
  console.log(summaryOf(l, models[models.length - 1]));
1434
2517
  console.log(file);
2518
+ if (n.warn) {
2519
+ printFindings(found.filter((f) => f.level === "warn"));
2520
+ console.log(`${count(n.warn, "warning")} (not blocking; \`glassbrain validate\` has the details)`);
2521
+ }
1435
2522
  if (a2.flags.open !== false) openFile(file);
1436
2523
  }
1437
2524
  function sides(pos) {
@@ -1447,7 +2534,7 @@ function runDiff(a2) {
1447
2534
  const before = load(oldSpec, { format });
1448
2535
  const after = load(newSpec, { format });
1449
2536
  const profileJson = after.profile ?? before.profile;
1450
- const profile = profileFromJson("cli", profileJson);
2537
+ const profile = profileOf(after);
1451
2538
  const pick = (l) => l.versions[l.versions.length - 1];
1452
2539
  const vb = pick(before);
1453
2540
  const va = pick(after);
@@ -1488,27 +2575,127 @@ function runValidate(a2) {
1488
2575
  if (a2.pos.length !== 1) fail("validate needs exactly one <path>");
1489
2576
  const l = load(a2.pos[0], { format: a2.flags.format });
1490
2577
  const found = validate(l);
1491
- const errors = found.filter((f) => f.level === "error").length;
1492
- const warns = found.length - errors;
1493
2578
  const models = nodesOf(l);
2579
+ const latest = models[models.length - 1];
2580
+ const n = tally(found);
2581
+ const structure = structureOf(latest);
2582
+ const failing = n.error > 0 || a2.flags.strict && n.warn > 0;
1494
2583
  if (a2.flags.json) {
1495
- console.log(JSON.stringify({ format: l.format, ignored: l.ignored, versions: l.versions.map((v, i) => ({ name: v.name, nodes: models[i].nodes.length, edges: models[i].edges.length })), errors, warnings: warns, issues: found }, null, 1));
2584
+ console.log(JSON.stringify({
2585
+ format: l.format,
2586
+ ignored: l.ignored,
2587
+ versions: l.versions.map((v, i) => ({ name: v.name, nodes: models[i].nodes.length, edges: models[i].edges.length })),
2588
+ errors: n.error,
2589
+ warnings: n.warn,
2590
+ infos: n.info,
2591
+ structure,
2592
+ issues: found
2593
+ }, null, 1));
1496
2594
  } else {
1497
- for (const f of found.slice(0, 200)) console.log(`${f.level === "error" ? "error" : "warn "} ${f.where} ${f.message}`);
1498
- if (found.length > 200) console.log(`\u2026 ${found.length - 200} more`);
2595
+ console.log(summaryOf(l, latest));
2596
+ if (found.length) console.log("");
2597
+ printFindings(found);
2598
+ console.log(`${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \xB7 ${count(n.info, "info")}`);
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)}`);
2600
+ console.log(`tree: glassbrain tree ${a2.pos[0]} --depth=3`);
1499
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` : ""}
1500
2602
  `);
1501
- console.log(`${found.length ? "\n" : ""}${summaryOf(l, models[models.length - 1])} \u2014 ${count(errors, "error")}, ${count(warns, "warning")}`);
1502
2603
  }
1503
- if (errors || a2.flags.strict && warns) process.exitCode = 1;
2604
+ if (failing) process.exitCode = 1;
2605
+ }
2606
+ function runTree(a2) {
2607
+ if (a2.pos.length !== 1) fail("tree needs exactly one <path>");
2608
+ const depth = a2.flags.depth === void 0 ? 3 : Number(a2.flags.depth);
2609
+ if (!Number.isInteger(depth) || depth < 1) fail("--depth needs a positive integer");
2610
+ const l = load(a2.pos[0], { format: a2.flags.format });
2611
+ const models = nodesOf(l);
2612
+ notes(l, models);
2613
+ const latest = models[models.length - 1];
2614
+ const version = l.versions[l.versions.length - 1].name;
2615
+ const result = tree(latest, {
2616
+ title: l.versions.length > 1 ? `${l.title}/${version}` : l.title,
2617
+ depth,
2618
+ path: typeof a2.flags.path === "string" ? a2.flags.path : void 0,
2619
+ orphans: a2.flags.orphans === true
2620
+ });
2621
+ if (a2.flags.json) {
2622
+ console.log(JSON.stringify({ title: l.title, ...structureOf(latest), entries: result.entries, more: result.more }, null, 1));
2623
+ } else {
2624
+ console.log(treeText(result));
2625
+ }
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}`);
1504
2693
  }
1505
2694
  function runConvert(a2) {
1506
2695
  if (a2.pos.length < 1 || a2.pos.length > 2) fail("convert needs <path> [out-dir]");
1507
2696
  const l = load(a2.pos[0], { format: a2.flags.format });
1508
2697
  const models = nodesOf(l);
1509
- const declared = Array.isArray(l.profile?.layers) && l.profile.layers.length > 0;
1510
- const strip = (g) => declared ? g : { ...g, nodes: g.nodes.map(({ layer: _l, ...n }) => n) };
1511
- 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]) } }));
1512
2699
  const outDir = a2.pos[1];
1513
2700
  if (!outDir) {
1514
2701
  if (graphs.length > 1) fail("several versions: give an out-dir");
@@ -1532,11 +2719,14 @@ var a = parseArgs(process.argv.slice(2));
1532
2719
  if (a.flags.version) {
1533
2720
  const pkg = JSON.parse(fs2.readFileSync(path2.join(here, "../../package.json"), "utf8"));
1534
2721
  console.log(pkg.version);
1535
- } 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>");
1536
2726
  process.stdout.write(HELP(path2.join(here, "../../schema/graph.schema.json")));
1537
2727
  } else {
1538
2728
  try {
1539
- ({ view, diff: runDiff, validate: runValidate, convert: runConvert })[a.cmd](a);
2729
+ ({ view, diff: runDiff, validate: runValidate, convert: runConvert, tree: runTree, restructure: runRestructure })[a.cmd](a);
1540
2730
  } catch (e) {
1541
2731
  fail(e.message, 2);
1542
2732
  }