glassbrain 0.2.0-alpha.5 → 0.2.0-alpha.7

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.
@@ -15,6 +15,10 @@ function buildModel(nodes, edges, errors = []) {
15
15
  return { nodes, edges, errors, index };
16
16
  }
17
17
  function mergeSlices(slices) {
18
+ if (slices.some((s) => s.declarations?.length) || slices.every((s) => !s.nodes.length)) return composeTrees(slices);
19
+ return mergeRuntimeSlices(slices);
20
+ }
21
+ function mergeRuntimeSlices(slices) {
18
22
  const byId = /* @__PURE__ */ new Map();
19
23
  const edges = [];
20
24
  const errors = [];
@@ -94,18 +98,177 @@ function indexModel(model) {
94
98
  };
95
99
  return { parentOf, childrenOf, depthOf, ancestorsOf, subtreeOf, neighborsOf };
96
100
  }
97
- function encodeParent(parent, order) {
98
- if (!parent) return null;
99
- if (order === void 0) return `${parent}@-1`;
100
- if (!Number.isFinite(order) || order <= 0) throw new Error("order must be finite and positive");
101
- const text = String(order);
102
- if (!/[eE]/.test(text)) return `${parent}@${text}`;
103
- const [mantissa, exponent] = text.toLowerCase().split("e");
104
- const [whole, fraction = ""] = mantissa.split(".");
105
- const digits = whole + fraction;
106
- const at = whole.length + Number(exponent);
107
- const decimal = at <= 0 ? `0.${"0".repeat(-at)}${digits}` : at >= digits.length ? digits + "0".repeat(at - digits.length) : `${digits.slice(0, at)}.${digits.slice(at)}`;
108
- return `${parent}@${decimal}`;
101
+
102
+ // src/tree.ts
103
+ var object = (x) => !!x && typeof x === "object" && !Array.isArray(x);
104
+ var ref = (x) => typeof x === "string" || typeof x === "number" ? String(x) : void 0;
105
+ var stable = (x) => JSON.stringify(x, function(_key, value) {
106
+ return object(value) ? Object.fromEntries(Object.keys(value).sort().map((k) => [k, value[k]])) : value;
107
+ });
108
+ function treeDeclarations(raw, origin) {
109
+ const declarations = [];
110
+ const rootIds = [];
111
+ const problems = [];
112
+ const stack = (Array.isArray(raw) ? raw : []).map((node, i) => ({ node, path: `nodes[${i}]`, top: true })).reverse();
113
+ if (raw !== void 0 && !Array.isArray(raw)) problems.push("nodes must be an array");
114
+ while (stack.length) {
115
+ const { node, path: path3, top } = stack.pop();
116
+ if (!object(node) || ref(node.id) === void 0) {
117
+ problems.push(`${path3}: expected a node with id`);
118
+ continue;
119
+ }
120
+ const id = ref(node.id);
121
+ if (!id.trim()) problems.push(`${path3}.id: expected a non-empty identity`);
122
+ if (top) rootIds.push(id);
123
+ const { children, ...fields } = node;
124
+ if ("parent" in node || "order" in node) problems.push(`${path3}: parent/order are not supported; nest nodes in children`);
125
+ if ("unordered" in node && typeof node.unordered !== "boolean") problems.push(`${path3}.unordered must be a boolean`);
126
+ const declaration = { id, fields: { ...fields, id }, path: `${origin}:${path3}` };
127
+ if ("children" in node) {
128
+ if (!Array.isArray(children)) problems.push(`${path3}.children must be an array`);
129
+ else {
130
+ declaration.children = children.filter(object).map((n) => ref(n.id)).filter((id2) => id2 !== void 0);
131
+ for (let i = children.length - 1; i >= 0; i--) stack.push({ node: children[i], path: `${path3}.children[${i}]`, top: false });
132
+ }
133
+ }
134
+ declarations.push(declaration);
135
+ }
136
+ return { declarations, rootIds, ...problems.length ? { error: problems.slice(0, 20).join("; ") } : {} };
137
+ }
138
+ function treeNodes(declarations = []) {
139
+ const placements = /* @__PURE__ */ new Map();
140
+ for (const d of declarations) d.children?.forEach((id, i) => placements.set(id, { parent: d.id, order: i + 1 }));
141
+ return declarations.map(({ id, fields }) => ({
142
+ id,
143
+ ...placements.get(id),
144
+ label: String(fields.label ?? fields.name ?? id),
145
+ ...typeof fields.kind === "string" ? { kind: fields.kind } : {},
146
+ ...Array.isArray(fields.flags) ? { flags: fields.flags.filter((f) => typeof f === "string") } : {},
147
+ data: fields
148
+ }));
149
+ }
150
+ function composeTrees(input) {
151
+ const slices = [...input].sort((a2, b) => a2.origin < b.origin ? -1 : a2.origin > b.origin ? 1 : 0);
152
+ const errors = [];
153
+ const records = /* @__PURE__ */ new Map();
154
+ const roots = [];
155
+ for (const slice of slices) {
156
+ if (slice.error) errors.push({ origin: slice.origin, code: "schema", message: slice.error });
157
+ if (!slice.declarations && slice.nodes.length) {
158
+ errors.push({ origin: slice.origin, code: "schema", message: "Cannot compose flat runtime slices with native children fragments." });
159
+ continue;
160
+ }
161
+ roots.push(...slice.rootIds ?? []);
162
+ for (const d of slice.declarations ?? []) {
163
+ let r = records.get(d.id);
164
+ if (!r) {
165
+ r = { fields: /* @__PURE__ */ Object.create(null), locations: /* @__PURE__ */ new Map(), origins: [] };
166
+ records.set(d.id, r);
167
+ }
168
+ if (!r.origins.includes(slice.origin)) r.origins.push(slice.origin);
169
+ for (const [field, value] of [...Object.entries(d.fields), ...d.children === void 0 ? [] : [["children", d.children]]]) {
170
+ const previous = field === "children" ? r.children : r.fields[field];
171
+ if (r.locations.has(field) && stable(previous) !== stable(value)) {
172
+ errors.push({
173
+ origin: slice.origin,
174
+ node: d.id,
175
+ code: field === "children" ? "children-conflict" : "field-conflict",
176
+ message: `"${d.id}".${field}: ${r.locations.get(field)} = ${stable(previous)} conflicts with ${d.path} = ${stable(value)}; provide one consistent value (lists are not combined).`
177
+ });
178
+ } else if (!r.locations.has(field)) {
179
+ if (field === "children") r.children = value;
180
+ else r.fields[field] = value;
181
+ r.locations.set(field, d.path);
182
+ }
183
+ }
184
+ }
185
+ }
186
+ const parents = /* @__PURE__ */ new Map();
187
+ const positions = /* @__PURE__ */ new Map();
188
+ for (const [id, r] of records) {
189
+ const seen = /* @__PURE__ */ new Set();
190
+ for (const [i, child] of (r.children ?? []).entries()) {
191
+ if (seen.has(child)) errors.push({ origin: r.origins[0], node: id, code: "children-conflict", message: `${r.locations.get("children")}: "${child}" occurs twice in children of "${id}".` });
192
+ seen.add(child);
193
+ const old = parents.get(child);
194
+ if (old !== void 0 && old !== id) {
195
+ errors.push({ origin: r.origins[0], node: child, code: "parent-error", message: `"${child}" has two parents: "${old}" (${records.get(old).locations.get("children")}) and "${id}" (${r.locations.get("children")}). Keep one placement.` });
196
+ } else {
197
+ parents.set(child, id);
198
+ positions.set(child, i + 1);
199
+ }
200
+ }
201
+ }
202
+ const done = /* @__PURE__ */ new Set();
203
+ for (const id of records.keys()) {
204
+ const chain = [], at = /* @__PURE__ */ new Map();
205
+ let cur = id;
206
+ while (cur !== void 0 && !done.has(cur)) {
207
+ if (at.has(cur)) {
208
+ const loop = [...chain.slice(at.get(cur)), cur];
209
+ errors.push({ origin: records.get(cur).origins[0], node: cur, code: "parent-error", message: `parent cycle: ${loop.join(" \u2192 ")}. Remove one children placement.` });
210
+ parents.delete(cur);
211
+ positions.delete(cur);
212
+ break;
213
+ }
214
+ at.set(cur, chain.length);
215
+ chain.push(cur);
216
+ cur = parents.get(cur);
217
+ }
218
+ chain.forEach((x) => done.add(x));
219
+ }
220
+ const orderedRoots = [.../* @__PURE__ */ new Set([...roots, ...records.keys()])].filter((id) => !parents.has(id));
221
+ const ordered = [], visited = /* @__PURE__ */ new Set(), stack = [...orderedRoots].reverse();
222
+ while (stack.length) {
223
+ const id = stack.pop();
224
+ if (visited.has(id) || !records.has(id)) continue;
225
+ visited.add(id);
226
+ ordered.push(id);
227
+ const kids = records.get(id).children ?? [];
228
+ for (let i = kids.length - 1; i >= 0; i--) if (parents.get(kids[i]) === id) stack.push(kids[i]);
229
+ }
230
+ const rootRanks = new Map(orderedRoots.map((id, i) => [id, i + 1]));
231
+ const nodes = ordered.map((id) => {
232
+ const r = records.get(id);
233
+ const n = treeNodes([{ id, fields: r.fields, path: "" }])[0];
234
+ return { ...n, parent: parents.get(id), order: positions.get(id) ?? rootRanks.get(id), origin: r.origins[0], origins: r.origins };
235
+ });
236
+ return buildModel(nodes, slices.flatMap((s) => s.edges), errors);
237
+ }
238
+ function serializeTree(model) {
239
+ if (model.errors.length || model.duplicateIds?.length) throw new Error("Cannot export a graph with unresolved input conflicts");
240
+ const records = /* @__PURE__ */ new Map();
241
+ const groups = /* @__PURE__ */ new Map();
242
+ for (const n of model.nodes) {
243
+ if (records.has(n.id)) throw new Error(`Duplicate id: ${n.id}`);
244
+ if (n.parent && !model.index.has(n.parent)) throw new Error(`Missing parent: ${n.parent}`);
245
+ const { parent: _parent, order: _order, layer: _layer, children: _children, ...data } = n.data ?? {};
246
+ records.set(n.id, Object.fromEntries(Object.entries({ ...data, id: n.id, label: n.label, kind: n.kind }).filter(([, v]) => v !== void 0)));
247
+ const group = groups.get(n.parent) ?? [];
248
+ group.push(n);
249
+ groups.set(n.parent, group);
250
+ }
251
+ for (const list of groups.values()) list.sort((a2, b) => (a2.order ?? Infinity) - (b.order ?? Infinity));
252
+ const roots = groups.get(void 0) ?? [];
253
+ const visited = /* @__PURE__ */ new Set(), stack = [...roots];
254
+ while (stack.length) {
255
+ const n = stack.pop();
256
+ if (visited.has(n.id)) throw new Error(`Parent cycle: ${n.id}`);
257
+ visited.add(n.id);
258
+ const kids = groups.get(n.id);
259
+ if (kids?.length) {
260
+ const record = records.get(n.id);
261
+ if (!("unordered" in record) && kids.every((k) => k.order === void 0)) record.unordered = true;
262
+ record.children = kids.map((k) => records.get(k.id));
263
+ stack.push(...kids);
264
+ }
265
+ }
266
+ if (visited.size !== model.nodes.length) throw new Error("Parent cycle: no rooted forest can be exported");
267
+ for (const e of model.edges) if (!records.has(e.source) || !records.has(e.target)) throw new Error(`Dangling edge: ${e.source} \u2192 ${e.target}`);
268
+ return {
269
+ nodes: roots.map((n) => records.get(n.id)),
270
+ edges: model.edges.map((e) => Object.fromEntries(Object.entries({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }).filter(([, v]) => v !== void 0)))
271
+ };
109
272
  }
110
273
 
111
274
  // src/profile.ts
@@ -117,30 +280,6 @@ function parsePhysical(origin, text) {
117
280
  return { origin, title: origin, nodes: [], edges: [], error: e instanceof Error ? e.message : String(e) };
118
281
  }
119
282
  if (!raw || typeof raw !== "object" || !("nodes" in raw) && !("edges" in raw)) return null;
120
- const ref = (v) => typeof v === "string" || typeof v === "number" ? String(v) : void 0;
121
- const parentOf = (v) => {
122
- const rawParent = ref(v);
123
- const at = rawParent?.lastIndexOf("@") ?? -1;
124
- const tail = at > 0 ? rawParent.slice(at + 1) : "";
125
- if (!/^(-1|\d+(\.\d+)?)$/.test(tail)) return { parent: rawParent, order: void 0 };
126
- const order = tail === "-1" ? void 0 : Number(tail);
127
- return { parent: rawParent.slice(0, at), order: order !== void 0 && order > 0 ? order : void 0 };
128
- };
129
- const nodes = (Array.isArray(raw.nodes) ? raw.nodes : []).filter((n) => n && typeof n === "object" && ref(n.id) !== void 0).map((n) => {
130
- const { parent, order } = parentOf(n.parent);
131
- return {
132
- id: String(n.id),
133
- label: String(n.label ?? n.name ?? n.id),
134
- kind: typeof n.kind === "string" ? n.kind : void 0,
135
- parent,
136
- order,
137
- layer: typeof n.layer === "string" ? n.layer : void 0,
138
- // Marks carried by the data itself (e.g. a placeholder "with no content yet"). They are data, not derived: when the profile's
139
- // `placeholderFlags` recognizes one, it is drawn as skeleton.
140
- ...Array.isArray(n.flags) ? { flags: n.flags.filter((f) => typeof f === "string") } : {},
141
- data: n
142
- };
143
- });
144
283
  const edges = (Array.isArray(raw.edges) ? raw.edges : []).filter((e) => e && typeof e === "object").map((e) => ({
145
284
  source: String(e.source ?? e.from),
146
285
  target: String(e.target ?? e.to),
@@ -150,21 +289,16 @@ function parsePhysical(origin, text) {
150
289
  // The whole record, like nodes' `data`: fields the library does not know survive a round trip (convert, toPhysical).
151
290
  data: e
152
291
  }));
153
- return { origin, title: String(raw.name ?? raw.title ?? origin), nodes, edges };
292
+ const parsed = treeDeclarations(raw.nodes, origin);
293
+ return { origin, title: String(raw.name ?? raw.title ?? origin), nodes: treeNodes(parsed.declarations), edges, ...parsed };
154
294
  }
155
295
  function toPhysical(model) {
156
- const clean2 = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0 && v !== ""));
157
- return {
158
- // `layer` is derived, never written: a file that gains it would freeze a view decision into the data.
159
- // `parent` is always written, `null` for a root, and carries the order: `"<id>@<order|-1>"`. `order` is never a field of its own.
160
- nodes: model.nodes.map((n) => {
161
- const { order: _order, layer: _layer, ...data } = n.data ?? {};
162
- return clean2({ ...data, id: n.id, label: n.label, kind: n.kind, parent: encodeParent(n.parent, n.order) });
163
- }),
164
- edges: model.edges.map((e) => clean2({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }))
165
- };
296
+ return serializeTree(model);
166
297
  }
167
298
  var DEFAULT_LAYER = { id: "default", label: "Graph", z: 0, structural: true };
299
+ function kindTable(...entries) {
300
+ return Object.assign(/* @__PURE__ */ Object.create(null), ...entries);
301
+ }
168
302
  function defineProfile(input) {
169
303
  const layers = input.layers?.length ? input.layers : [DEFAULT_LAYER];
170
304
  const fallbackLayer = layers[0].id;
@@ -174,15 +308,15 @@ function defineProfile(input) {
174
308
  merge: input.merge ?? mergeSlices,
175
309
  layers,
176
310
  layerOf: input.layerOf ?? ((n) => n.layer ?? fallbackLayer),
177
- nodePalette: input.nodePalette ?? {},
178
- edgePalette: input.edgePalette ?? {},
179
- nodeSize: input.nodeSize ?? {},
180
- edgeWidth: input.edgeWidth ?? {},
311
+ nodePalette: kindTable(input.nodePalette),
312
+ edgePalette: kindTable(input.edgePalette),
313
+ nodeSize: kindTable(input.nodeSize),
314
+ edgeWidth: kindTable(input.edgeWidth),
181
315
  placeholderFlags: input.placeholderFlags ?? [],
182
316
  style: input.style ?? [],
183
317
  nodeClass: input.nodeClass ?? (() => ""),
184
318
  edgeClass: input.edgeClass ?? ((e) => e.kind ?? ""),
185
- kindLabels: input.kindLabels ?? {},
319
+ kindLabels: kindTable(input.kindLabels),
186
320
  detail: input.detail ?? {},
187
321
  validate: input.validate ?? (() => []),
188
322
  layoutEdge: input.layoutEdge ?? (() => false),
@@ -723,12 +857,36 @@ function adapt(files, only) {
723
857
  const out = pick.convert(files);
724
858
  const skipped = pick === MARKDOWN ? [] : files.filter((f) => /\.jsonl?$/i.test(f.path) && !pick.detect([f])).map((f) => f.path);
725
859
  return {
726
- sources: out.sources.map((s) => ({ origin: s.origin, text: JSON.stringify(s.graph) })),
860
+ sources: treeSources(out),
727
861
  profile: out.profile,
728
862
  adapter: pick,
729
863
  skipped
730
864
  };
731
865
  }
866
+ function treeSources(out) {
867
+ const children = /* @__PURE__ */ new Map();
868
+ for (const s of out.sources) for (const n of s.graph.nodes) {
869
+ if (!n.parent) continue;
870
+ const kids = children.get(n.parent) ?? /* @__PURE__ */ new Map();
871
+ kids.set(n.id, typeof n.order === "number" ? n.order : void 0);
872
+ children.set(n.parent, kids);
873
+ }
874
+ const written = /* @__PURE__ */ new Set();
875
+ return out.sources.map((s) => ({ origin: s.origin, text: JSON.stringify({
876
+ ...s.graph,
877
+ nodes: s.graph.nodes.map((n) => {
878
+ const { parent: _parent, order: _order, layer: _layer, ...fields } = n;
879
+ const kids = children.get(n.id);
880
+ if (!kids || written.has(n.id)) return fields;
881
+ written.add(n.id);
882
+ return {
883
+ ...fields,
884
+ ...fields.unordered === void 0 && [...kids.values()].every((v) => v === void 0) ? { unordered: true } : {},
885
+ children: [...kids].sort((a2, b) => (a2[1] ?? Infinity) - (b[1] ?? Infinity)).map(([id]) => ({ id }))
886
+ };
887
+ })
888
+ }) }));
889
+ }
732
890
  var isNativeGraph = (f) => {
733
891
  if (!/\.json$/i.test(f.path)) return false;
734
892
  try {
@@ -781,25 +939,25 @@ function walk(root) {
781
939
  function gitSpec(spec, cwd) {
782
940
  const m = /^([^:]+):(.*)$/.exec(spec);
783
941
  if (!m || /^[a-zA-Z]$/.test(m[1])) return null;
784
- const [, ref, rel0] = m;
942
+ const [, ref2, rel0] = m;
785
943
  const git = (...args) => execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 1 << 30, stdio: ["ignore", "pipe", "pipe"] });
786
944
  try {
787
- git("rev-parse", "--verify", "--quiet", `${ref}^{commit}`);
945
+ git("rev-parse", "--verify", "--quiet", `${ref2}^{commit}`);
788
946
  } catch {
789
947
  return null;
790
948
  }
791
949
  const rel = rel0.replace(/^\.?\/*/, "").replace(/\/+$/, "");
792
- const title = `${path.basename(rel || cwd)} @ ${ref}`;
950
+ const title = `${path.basename(rel || cwd)} @ ${ref2}`;
793
951
  let type;
794
952
  try {
795
- type = git("cat-file", "-t", `${ref}:./${rel}`).trim();
953
+ type = git("cat-file", "-t", `${ref2}:./${rel}`).trim();
796
954
  } catch {
797
- throw new Error(`${rel || "."} does not exist at ${ref}`);
955
+ throw new Error(`${rel || "."} does not exist at ${ref2}`);
798
956
  }
799
- if (type === "blob") return { files: [{ path: path.basename(rel), text: git("show", `${ref}:./${rel}`) }], title, isDir: false };
800
- const names2 = git("ls-tree", "-r", "--name-only", ref, "--", rel || ".").split("\n").filter(Boolean);
957
+ if (type === "blob") return { files: [{ path: path.basename(rel), text: git("show", `${ref2}:./${rel}`) }], title, isDir: false };
958
+ const names2 = git("ls-tree", "-r", "--name-only", ref2, "--", rel || ".").split("\n").filter(Boolean);
801
959
  const prefix = rel ? `${rel}/` : "";
802
- 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}`) }));
960
+ 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", `${ref2}:./${n}`) }));
803
961
  return { files, title, isDir: true };
804
962
  }
805
963
  var META = /* @__PURE__ */ new Set(["_profile.json", "_layout.json"]);
@@ -829,7 +987,12 @@ function load(spec, opts = {}) {
829
987
  const f = tree2.files.find((x) => x.path === name);
830
988
  if (!f) return null;
831
989
  try {
832
- return JSON.parse(f.text);
990
+ const value = JSON.parse(f.text);
991
+ if (name === "_profile.json" && (!value || typeof value !== "object" || Array.isArray(value))) {
992
+ metaErrors.push({ file: name, message: "expected a profile object" });
993
+ return null;
994
+ }
995
+ return value;
833
996
  } catch (e) {
834
997
  metaErrors.push({ file: name, message: `not JSON: ${e.message}` });
835
998
  return null;
@@ -860,7 +1023,7 @@ function load(spec, opts = {}) {
860
1023
  suggested ??= r.profile;
861
1024
  }
862
1025
  ignored.push(...r.skipped.map((p) => versioned ? `${g.name}/${p}` : p));
863
- return { name: g.name, sources: r.sources };
1026
+ return { name: g.name, sources: r.sources, format: r.adapter?.id ?? "native" };
864
1027
  });
865
1028
  return {
866
1029
  title: tree2.title,
@@ -885,7 +1048,7 @@ var DIFF_FLAG = {
885
1048
  merged: "gb-merged"
886
1049
  };
887
1050
  var KEPT_FLAG = "gb-kept";
888
- var stable = (v, ignore) => {
1051
+ var stable2 = (v, ignore) => {
889
1052
  const walk2 = (x) => {
890
1053
  if (Array.isArray(x)) return x.map(walk2);
891
1054
  if (x && typeof x === "object") {
@@ -903,7 +1066,7 @@ function changedFields(a2, b, ignore) {
903
1066
  const ob = b ?? {};
904
1067
  const keys = new Set([...Object.keys(oa), ...Object.keys(ob)].filter((k) => !ignore.has(k)));
905
1068
  const out = [];
906
- for (const k of keys) if (stable(oa[k], ignore) !== stable(ob[k], ignore)) out.push(k);
1069
+ for (const k of keys) if (stable2(oa[k], ignore) !== stable2(ob[k], ignore)) out.push(k);
907
1070
  return out.sort();
908
1071
  }
909
1072
  var EDIT_CAP = 512;
@@ -938,7 +1101,7 @@ function editDistance(a2, b) {
938
1101
  return prev[m] + over;
939
1102
  }
940
1103
  function changeAmount(a2, b, fields, ignore) {
941
- const pick = (n) => fields.map((k) => stable((n.data ?? {})[k], ignore)).join("\0");
1104
+ const pick = (n) => fields.map((k) => stable2((n.data ?? {})[k], ignore)).join("\0");
942
1105
  return editDistance(pick(a2), pick(b)) + editDistance(a2.label ?? "", b.label ?? "");
943
1106
  }
944
1107
  var edgeKey = (e) => `${e.source} ${e.target} ${e.kind ?? ""}`;
@@ -961,8 +1124,30 @@ function diffModels(before, after, opts = {}) {
961
1124
  const b = afterByKey.get(k);
962
1125
  if (b) resolve.set(list[0].id, b.id);
963
1126
  }
964
- const ref = (id) => id === void 0 ? void 0 : resolve.get(id) ?? id;
1127
+ const ref2 = (id) => id === void 0 ? void 0 : resolve.get(id) ?? id;
965
1128
  const consumed = new Set(resolve.keys());
1129
+ const reordered = /* @__PURE__ */ new Set();
1130
+ if (!ignore.has("position")) {
1131
+ const groups = /* @__PURE__ */ new Map();
1132
+ for (const a2 of before.nodes) {
1133
+ const id = resolve.get(a2.id), b = id ? after.index.get(id) : void 0;
1134
+ if (!b || ref2(a2.parent) !== b.parent) continue;
1135
+ if (a2.parent && before.index.get(a2.parent)?.data?.unordered === true || b.parent && after.index.get(b.parent)?.data?.unordered === true) continue;
1136
+ const p = b.parent;
1137
+ const g = groups.get(p) ?? { old: [], next: [] };
1138
+ g.old.push(a2);
1139
+ g.next.push(b);
1140
+ groups.set(p, g);
1141
+ }
1142
+ for (const g of groups.values()) {
1143
+ g.old.sort((a2, b) => (a2.order ?? Infinity) - (b.order ?? Infinity));
1144
+ const ranks = new Map(after.nodes.map((n, i) => [n.id, i]));
1145
+ g.next.sort((a2, b) => (a2.order ?? ranks.get(a2.id)) - (b.order ?? ranks.get(b.id)));
1146
+ g.old.forEach((a2, i) => {
1147
+ if (resolve.get(a2.id) !== g.next[i].id) reordered.add(g.next[i].id);
1148
+ });
1149
+ }
1150
+ }
966
1151
  const changes = [];
967
1152
  const prevData = /* @__PURE__ */ new Map();
968
1153
  const moved = /* @__PURE__ */ new Map();
@@ -974,8 +1159,13 @@ function diffModels(before, after, opts = {}) {
974
1159
  flag = DIFF_FLAG.added;
975
1160
  changes.push({ kind: "added", id: b.id });
976
1161
  } else {
977
- const fields = changedFields(a2.data, b.data, ignore);
978
- const aParent = ref(a2.parent) ?? null;
1162
+ const own = (n) => {
1163
+ const { children: _children, parent: _parent, order: _order, ...data } = n.data ?? {};
1164
+ return { ...data, kind: n.kind };
1165
+ };
1166
+ const fields = changedFields(own(a2), own(b), ignore);
1167
+ if (reordered.has(b.id)) fields.push("position");
1168
+ const aParent = ref2(a2.parent) ?? null;
979
1169
  if (aParent !== (b.parent ?? null)) {
980
1170
  flag = DIFF_FLAG.moved;
981
1171
  changes.push({
@@ -1012,7 +1202,7 @@ function diffModels(before, after, opts = {}) {
1012
1202
  const merged = !!to && after.index.has(to);
1013
1203
  const kind = merged ? "merged" : "removed";
1014
1204
  changes.push({ kind, id: a2.id, pairId: merged ? to : void 0 });
1015
- const parent = ref(a2.parent);
1205
+ const parent = ref2(a2.parent);
1016
1206
  nodes.push({
1017
1207
  ...withFlag(a2, DIFF_FLAG[kind]),
1018
1208
  parent: parent && (unionIds.has(parent) || !consumed.has(a2.parent)) ? parent : void 0
@@ -1022,7 +1212,7 @@ function diffModels(before, after, opts = {}) {
1022
1212
  const afterEdges = new Map(after.edges.map((e) => [edgeKey(e), e]));
1023
1213
  const beforeEdges = new Map(
1024
1214
  before.edges.map((e) => {
1025
- const r = { ...e, source: ref(e.source), target: ref(e.target) };
1215
+ const r = { ...e, source: ref2(e.source), target: ref2(e.target) };
1026
1216
  return [edgeKey(r), r];
1027
1217
  })
1028
1218
  );
@@ -1057,7 +1247,8 @@ function diffModels(before, after, opts = {}) {
1057
1247
 
1058
1248
  // src/layers.ts
1059
1249
  var EMPTY = { layers: [], layerOf: /* @__PURE__ */ new Map() };
1060
- function orderedChildren(children, id) {
1250
+ function orderedChildren(children, id, unordered = false) {
1251
+ if (unordered) return null;
1061
1252
  const kids = children.get(id) ?? [];
1062
1253
  if (kids.length < 2) return null;
1063
1254
  const withOrder = kids.filter((n) => typeof n.order === "number" && Number.isFinite(n.order));
@@ -1086,10 +1277,10 @@ function deriveLayers(model, colors = [], force = false) {
1086
1277
  let anchor;
1087
1278
  if (roots.length === 1) {
1088
1279
  anchor = roots[0];
1089
- ordered = orderedChildren(children, anchor.id);
1280
+ ordered = orderedChildren(children, anchor.id, anchor.data?.unordered === true);
1090
1281
  if (!ordered && force) ordered = children.get(anchor.id) ?? null;
1091
- } else if (force && roots.length > 1) {
1092
- ordered = roots;
1282
+ } else if (roots.length > 1 && (force || roots.every((n) => n.order !== void 0))) {
1283
+ ordered = [...roots].sort((a2, b) => (a2.order ?? Infinity) - (b.order ?? Infinity));
1093
1284
  }
1094
1285
  if (!ordered || ordered.length < 2) return EMPTY;
1095
1286
  const layers = ordered.map((n, i) => ({
@@ -1116,50 +1307,152 @@ var graph_schema_default = {
1116
1307
  $schema: "https://json-schema.org/draft/2020-12/schema",
1117
1308
  $id: "https://unpkg.com/glassbrain/schema/graph.schema.json",
1118
1309
  title: "glassbrain graph",
1119
- 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`: null for the root, otherwise `"<id>@<order>"` where `order` is a positive number or -1 for explicitly unordered. Several files in one folder are merged into one graph (same id = same node). Unknown fields are kept and shown in the detail panel.',
1310
+ description: "An ordered forest of node fragments plus semantic edges. Nest nodes in children; array order is reading order. Same id means the same node: absent fields are filled, equal values are accepted, conflicting values are errors. Children declarations must have identical direct child id sequences. Top-level fragments acquire a parent wherever another node contains their id. Each node has at most one parent; cycles are invalid.",
1120
1311
  type: "object",
1121
- anyOf: [{ required: ["nodes"] }, { required: ["edges"] }],
1312
+ anyOf: [
1313
+ {
1314
+ required: [
1315
+ "nodes"
1316
+ ]
1317
+ },
1318
+ {
1319
+ required: [
1320
+ "edges"
1321
+ ]
1322
+ }
1323
+ ],
1122
1324
  properties: {
1123
- name: { type: "string", description: "Title of this file (shown as its source name)." },
1124
- title: { type: "string", description: "Alias of `name`." },
1325
+ name: {
1326
+ type: "string",
1327
+ description: "Title of this file (shown as its source name)."
1328
+ },
1329
+ title: {
1330
+ type: "string",
1331
+ description: "Alias of `name`."
1332
+ },
1125
1333
  nodes: {
1126
1334
  type: "array",
1127
- items: { $ref: "#/$defs/node" }
1335
+ items: {
1336
+ $ref: "#/$defs/node"
1337
+ }
1128
1338
  },
1129
1339
  edges: {
1130
1340
  type: "array",
1131
- items: { $ref: "#/$defs/edge" }
1341
+ items: {
1342
+ $ref: "#/$defs/edge"
1343
+ }
1132
1344
  }
1133
1345
  },
1134
1346
  $defs: {
1135
1347
  node: {
1136
1348
  type: "object",
1137
- required: ["id", "parent"],
1349
+ required: [
1350
+ "id"
1351
+ ],
1138
1352
  properties: {
1139
- id: { type: ["string", "number"], pattern: "^[^\\s@]{1,80}$", description: "Stable identity. Keep it the same across versions: that is how a diff knows it is the same thing. No `@` and no whitespace, at most 80 characters; prefer a short code (`a-z0-9_`, under 20)." },
1140
- label: { type: "string", description: "Display name. Falls back to `name`, then `id`." },
1141
- name: { type: "string", description: "Alias of `label`." },
1142
- 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." },
1143
- parent: { type: ["string", "null"], pattern: "^[^\\s@]{1,80}@(-1|[1-9]\\d*(\\.\\d+)?|0\\.\\d*[1-9]\\d*)$", description: '`"<id>@<order>"`: the id of the node this one sits inside, then its position among the siblings (1, 2, 3\u2026; 3.5 inserts between 3 and 4), or -1 for explicitly unordered. null for the root. Required: the only source of structure, and the layout, the layers and the outline are all built from it.' },
1144
- 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." },
1145
- description: { type: "string", description: "Markdown shown in the detail panel. `[text](node:<id>)` links jump to another node." }
1353
+ id: {
1354
+ type: [
1355
+ "string",
1356
+ "number"
1357
+ ],
1358
+ pattern: "\\S",
1359
+ description: "Non-empty stable identity. Keep it the same across versions: that is how a diff knows it is the same thing. Prefer a short code."
1360
+ },
1361
+ label: {
1362
+ type: "string",
1363
+ description: "Display name. Falls back to `name`, then `id`."
1364
+ },
1365
+ name: {
1366
+ type: "string",
1367
+ description: "Alias of `label`."
1368
+ },
1369
+ kind: {
1370
+ type: "string",
1371
+ description: "What sort of thing this is. Colors come from the profile's `nodePalette[kind]`; kinds not in the palette are drawn as skeleton."
1372
+ },
1373
+ flags: {
1374
+ type: "array",
1375
+ items: {
1376
+ type: "string"
1377
+ },
1378
+ description: "Boolean markers; each becomes a CSS-like class. A flag listed in the profile's `placeholderFlags` draws the node as a placeholder."
1379
+ },
1380
+ description: {
1381
+ type: "string",
1382
+ description: "Markdown shown in the detail panel. `[text](node:<id>)` links jump to another node."
1383
+ },
1384
+ children: {
1385
+ type: "array",
1386
+ items: {
1387
+ $ref: "#/$defs/node"
1388
+ },
1389
+ description: "Ordered direct children. Omitted means unspecified; [] explicitly declares no children. Multiple declarations must name the same ids in the same order; child fields are composed independently by id."
1390
+ },
1391
+ unordered: { type: "boolean" },
1392
+ parent: false,
1393
+ order: false,
1394
+ layer: false
1146
1395
  },
1147
1396
  additionalProperties: true
1148
1397
  },
1149
1398
  edge: {
1150
1399
  type: "object",
1151
1400
  anyOf: [
1152
- { required: ["source", "target"] },
1153
- { required: ["from", "to"] }
1401
+ {
1402
+ required: [
1403
+ "source",
1404
+ "target"
1405
+ ]
1406
+ },
1407
+ {
1408
+ required: [
1409
+ "from",
1410
+ "to"
1411
+ ]
1412
+ }
1154
1413
  ],
1155
1414
  properties: {
1156
- source: { type: ["string", "number"], description: "Node id the edge starts at." },
1157
- target: { type: ["string", "number"], description: "Node id the edge points to." },
1158
- from: { type: ["string", "number"], description: "Alias of `source`." },
1159
- to: { type: ["string", "number"], description: "Alias of `target`." },
1160
- kind: { type: "string", description: "Relation type. Colors come from the profile's `edgePalette[kind]`. An edge is identified by its two ends plus its kind." },
1161
- label: { type: "string" },
1162
- weight: { type: "number", minimum: 0, maximum: 1, description: "0\u20131 (confidence, strength\u2026); drives line width." }
1415
+ source: {
1416
+ type: [
1417
+ "string",
1418
+ "number"
1419
+ ],
1420
+ description: "Node id the edge starts at."
1421
+ },
1422
+ target: {
1423
+ type: [
1424
+ "string",
1425
+ "number"
1426
+ ],
1427
+ description: "Node id the edge points to."
1428
+ },
1429
+ from: {
1430
+ type: [
1431
+ "string",
1432
+ "number"
1433
+ ],
1434
+ description: "Alias of `source`."
1435
+ },
1436
+ to: {
1437
+ type: [
1438
+ "string",
1439
+ "number"
1440
+ ],
1441
+ description: "Alias of `target`."
1442
+ },
1443
+ kind: {
1444
+ type: "string",
1445
+ description: "Relation type. Colors come from the profile's `edgePalette[kind]`. An edge is identified by its two ends plus its kind."
1446
+ },
1447
+ label: {
1448
+ type: "string"
1449
+ },
1450
+ weight: {
1451
+ type: "number",
1452
+ minimum: 0,
1453
+ maximum: 1,
1454
+ description: "0\u20131 (confidence, strength\u2026); drives line width."
1455
+ }
1163
1456
  },
1164
1457
  additionalProperties: true
1165
1458
  }
@@ -1171,7 +1464,7 @@ var profile_schema_default = {
1171
1464
  $schema: "https://json-schema.org/draft/2020-12/schema",
1172
1465
  $id: "https://unpkg.com/glassbrain/schema/profile.schema.json",
1173
1466
  title: "glassbrain profile (_profile.json)",
1174
- 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.",
1467
+ 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 the order of children in the graph. Parsers, merge and domain validation are code and live in a TypeScript profile instead.",
1175
1468
  type: "object",
1176
1469
  properties: {
1177
1470
  nodePalette: {
@@ -1211,7 +1504,7 @@ var profile_schema_default = {
1211
1504
  properties: {
1212
1505
  defaultLayers: {
1213
1506
  type: "boolean",
1214
- description: "Open with the layer (2.5D plane) view on when the graph has ordered siblings. Default false."
1507
+ description: "Open with the layer (2.5D plane) view on when the graph has ordered siblings. By default, opens layered when the graph has two or more floors."
1215
1508
  },
1216
1509
  layerColors: {
1217
1510
  type: "array",
@@ -1327,6 +1620,11 @@ function checkSchema(root, value, limit = 50) {
1327
1620
  const resolve = (s) => s.$ref ? root.$defs[s.$ref.replace("#/$defs/", "")] : s;
1328
1621
  const walk2 = (s0, v, path3, out2) => {
1329
1622
  if (out2.length >= limit) return;
1623
+ if (s0 === false) {
1624
+ out2.push({ path: path3, message: "retired field; use children" });
1625
+ return;
1626
+ }
1627
+ if (s0 === true) return;
1330
1628
  const s = resolve(s0);
1331
1629
  for (const k of Object.keys(s)) if (!KNOWN.has(k)) throw new Error(`schema-check: unsupported keyword "${k}"`);
1332
1630
  if (s.type) {
@@ -1349,10 +1647,10 @@ function checkSchema(root, value, limit = 50) {
1349
1647
  }
1350
1648
  if (typeOf(v) === "object") {
1351
1649
  const o = v;
1352
- for (const r of s.required ?? []) if (!(r in o)) out2.push({ path: path3, message: `missing "${r}"` });
1650
+ for (const r of s.required ?? []) if (!Object.hasOwn(o, r)) out2.push({ path: path3, message: `missing "${r}"` });
1353
1651
  for (const [k, val] of Object.entries(o)) {
1354
- const sub = s.properties?.[k] ?? (typeof s.additionalProperties === "object" ? s.additionalProperties : null);
1355
- if (sub) walk2(sub, val, `${path3}.${k}`, out2);
1652
+ const sub = s.properties && Object.hasOwn(s.properties, k) ? s.properties[k] : typeof s.additionalProperties === "object" ? s.additionalProperties : null;
1653
+ if (sub !== null && sub !== void 0) walk2(sub, val, `${path3}.${k}`, out2);
1356
1654
  else if (s.additionalProperties === false) out2.push({ path: path3, message: `unknown field "${k}"` });
1357
1655
  }
1358
1656
  }
@@ -1368,6 +1666,36 @@ function checkSchema(root, value, limit = 50) {
1368
1666
  return out;
1369
1667
  }
1370
1668
 
1669
+ // src/kinds.ts
1670
+ function kindDistribution(items) {
1671
+ const counts = /* @__PURE__ */ new Map();
1672
+ for (const item of items) if (item.kind) counts.set(item.kind, (counts.get(item.kind) ?? 0) + 1);
1673
+ const sizes = [...counts].map(([kind, count2]) => ({ kind, count: count2 })).sort((a2, b) => b.count - a2.count || a2.kind.localeCompare(b.kind));
1674
+ const typed = sizes.reduce((sum, row) => sum + row.count, 0);
1675
+ const effective = sizes.reduce((sum, row) => sum + Math.sqrt(row.count / typed), 0) ** 2;
1676
+ const fragmentation = typed > 1 ? effective / Math.log(typed) : 0;
1677
+ return {
1678
+ total: items.length,
1679
+ typed,
1680
+ missing: items.length - typed,
1681
+ count: sizes.length,
1682
+ sizes,
1683
+ effective,
1684
+ fragmentation,
1685
+ reason: typed >= 10 && fragmentation > 2 ? "too fragmented" : null
1686
+ };
1687
+ }
1688
+ function kindHeading(space, d) {
1689
+ return `${space} kinds: ${d.count}${d.reason ? ` (${d.reason})` : ""}`;
1690
+ }
1691
+ function kindSummary(space, d, labels = {}) {
1692
+ return [
1693
+ kindHeading(space, d),
1694
+ ...d.sizes.map((row) => `${Object.hasOwn(labels, row.kind) ? labels[row.kind] : row.kind} ${row.count}/${d.total}`),
1695
+ ...d.missing ? [`(no kind) ${d.missing}/${d.total}`] : []
1696
+ ].join(" | ");
1697
+ }
1698
+
1371
1699
  // cli/shape.ts
1372
1700
  var rounded = (x) => +x.toFixed(6);
1373
1701
  function analyzeShape(nodes) {
@@ -1586,16 +1914,14 @@ function analyzeShape(nodes) {
1586
1914
  }
1587
1915
 
1588
1916
  // cli/checks.ts
1589
- var WIDE_INFO = 5;
1590
- var WIDE_WARN = 10;
1917
+ var WIDE_WARN = 5;
1591
1918
  var MAX_NAMES = 4;
1592
- var MIN_SAMPLE = 10;
1593
1919
  var names = (xs) => `${xs.slice(0, MAX_NAMES).join(", ")}${xs.length > MAX_NAMES ? ` and ${xs.length - MAX_NAMES} more` : ""}`;
1594
1920
  var misplacedField = {
1595
1921
  code: "schema",
1596
1922
  level: "error",
1597
1923
  run: ({ model }) => {
1598
- const reserved = ["id", "label", "kind", "parent", "description"];
1924
+ const reserved = ["id", "label", "kind", "children", "description"];
1599
1925
  const out = [];
1600
1926
  for (const n of model.nodes) {
1601
1927
  const nested = n.data?.data;
@@ -1618,10 +1944,8 @@ var layerField = {
1618
1944
  level: "error",
1619
1945
  run: ({ model }) => model.nodes.filter((n) => n.data && typeof n.data === "object" && "layer" in n.data).map((n) => ({
1620
1946
  node: n.id,
1621
- message: `"${n.id}" still carries "layer": layers are not written any more, they come from the order in "parent"`,
1622
- fix: `delete the field. To make the graph read as floors, number one node's children in "parent" instead:
1623
- - { "id": "${n.id}", "parent": "\u2026@-1", "layer": "${n.layer}" }
1624
- + { "id": "${n.id}", "parent": "\u2026@2" }`
1947
+ message: `"${n.id}" still carries "layer": layers are not written any more, they come from children`,
1948
+ fix: `delete "layer" and put the node in its container's children array.`
1625
1949
  }))
1626
1950
  };
1627
1951
  var unknownParent = {
@@ -1630,10 +1954,7 @@ var unknownParent = {
1630
1954
  run: ({ model, index, labelOf }) => model.nodes.filter((n) => n.parent && !index.has(n.parent)).map((n) => ({
1631
1955
  node: n.id,
1632
1956
  message: `"${n.id}" sits inside "${n.parent}", which does not exist`,
1633
- fix: `point it at a node that exists (one of: ${[...index.keys()].slice(0, 3).map((id) => `"${id}"`).join(", ")}), or add "${n.parent}":
1634
- - "parent": "${n.parent}@-1"
1635
- + "parent": "${[...index.keys()][0] ?? "EXISTING_ID"}@-1"
1636
- ("parent": null also works, but a file has one root: a second null is a parent-error.)`
1957
+ fix: `add the missing container "${n.parent}" and nest "${n.id}" in its children, or move "${n.id}" to nodes.`
1637
1958
  }))
1638
1959
  };
1639
1960
  var parentCycle = {
@@ -1655,9 +1976,7 @@ var parentCycle = {
1655
1976
  out.push({
1656
1977
  node: cur,
1657
1978
  message: `parent cycle: ${[...loop, cur].join(" \u2192 ")}`,
1658
- fix: `a node cannot sit inside itself. Pick the one that should be the top of the loop and give it "parent": null:
1659
- - { "id": "${loop[0]}", "parent": "${cur}@-1" }
1660
- + { "id": "${loop[0]}", "parent": null }`
1979
+ fix: `remove one children placement in this cycle; a node cannot contain itself.`
1661
1980
  });
1662
1981
  break;
1663
1982
  }
@@ -1676,60 +1995,13 @@ var reservedContains = {
1676
1995
  level: "error",
1677
1996
  run: ({ model }) => model.edges.some((e) => e.kind === "contains") ? [{
1678
1997
  message: 'edge kind "contains" is reserved for the parent structure',
1679
- fix: "express containment with the child node's parent field and remove the redundant edge. If this is another relationship, give its kind a distinct name and update edgePalette."
1998
+ fix: "express containment with a children array and remove the redundant edge. If this is another relationship, give its kind a distinct name and update edgePalette."
1680
1999
  }] : []
1681
2000
  };
1682
- var orderMixed = {
1683
- code: "order-error",
1684
- level: "error",
1685
- run: ({ children }) => {
1686
- const out = [];
1687
- for (const [parent, kids] of children) {
1688
- const withOrder = kids.filter((k) => typeof k.order === "number").length;
1689
- if (withOrder === 0 || withOrder === kids.length) continue;
1690
- const missing = kids.filter((k) => typeof k.order !== "number").slice(0, 3);
1691
- const next = Math.max(0, ...kids.map((k) => typeof k.order === "number" ? k.order : 0)) + 1;
1692
- out.push({
1693
- node: parent,
1694
- message: `${withOrder} of ${kids.length} children of "${parent}" are numbered; a sibling set is numbered or explicitly unordered ("@-1")`,
1695
- fix: `give the rest an order, or mark them all unordered with "@-1":
1696
- ${missing.map((k, i) => ` - { "id": "${k.id}", "parent": "${parent}@-1" }
1697
- + { "id": "${k.id}", "parent": "${parent}@${next + i}" }`).join("\n")}`
1698
- });
1699
- }
1700
- return out;
1701
- }
1702
- };
1703
- var orderDuplicate = {
1704
- code: "order-error",
1705
- level: "error",
1706
- run: ({ children }) => {
1707
- const out = [];
1708
- for (const [parent, kids] of children) {
1709
- const seen = /* @__PURE__ */ new Map();
1710
- for (const k of kids) {
1711
- if (typeof k.order !== "number") continue;
1712
- const arr = seen.get(k.order);
1713
- arr ? arr.push(k) : seen.set(k.order, [k]);
1714
- }
1715
- for (const [value, same] of seen) {
1716
- if (same.length < 2) continue;
1717
- out.push({
1718
- node: parent,
1719
- message: `"${parent}" has ${same.length} children at order ${value} (${names(same.map((n) => n.id))}); two items cannot share a place`,
1720
- fix: `spread them. Fractions are allowed, so nothing else has to move:
1721
- ${same.slice(1).map((k, i) => ` - { "id": "${k.id}", "parent": "${parent}@${value}" }
1722
- + { "id": "${k.id}", "parent": "${parent}@${value + (i + 1) / 10}" }`).join("\n")}`
1723
- });
1724
- }
1725
- }
1726
- return out;
1727
- }
1728
- };
1729
2001
  var conflictingDefinition = {
1730
2002
  code: "duplicate-id",
1731
2003
  level: "error",
1732
- run: ({ model, index, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
2004
+ run: ({ model, index }) => (model.duplicateIds ?? []).map((id) => ({
1733
2005
  node: id,
1734
2006
  message: `"${id}" is defined differently in ${names(index.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`,
1735
2007
  fix: `one id is one thing. Either make the copies identical, or give one a new id and point its edges at that:
@@ -1778,10 +2050,9 @@ var duplicateEdge = {
1778
2050
  };
1779
2051
  var unevenKinds = {
1780
2052
  code: "bad-structure",
1781
- level: "info",
2053
+ level: "warn",
1782
2054
  run: ({ model }) => analyzeShape(model.nodes).branches.filter((b) => b.score >= 0.2).sort((a2, b) => b.score - a2.score).map((b) => ({
1783
2055
  node: b.parent,
1784
- level: b.children.length > WIDE_WARN ? "error" : b.score >= 0.4 ? "warn" : "info",
1785
2056
  message: `"${b.parent}": ${b.children.length} children with uneven structural relationships (structure pressure ${b.score.toFixed(3)}, dispersion ${b.dispersion.toFixed(3)}, effective template support ${b.support.toFixed(2)})`,
1786
2057
  fix: `inspect this branch: glassbrain tree <path> --path "${b.parent}"
1787
2058
  closest compared pair: ${b.closest?.a} / ${b.closest?.b} (distance ${b.closest?.distance}). Differences can be intentional.
@@ -1795,17 +2066,15 @@ var wideNode = {
1795
2066
  const out = [];
1796
2067
  for (const [id, kids] of children) {
1797
2068
  const n = kids.length;
1798
- if (n <= WIDE_INFO) continue;
1799
- const level = n > WIDE_WARN ? "warn" : "info";
2069
+ if (n <= WIDE_WARN) continue;
1800
2070
  const isAnchor = layers.anchor === id;
1801
2071
  const what = isAnchor ? `${n} layers` : `${n} children`;
1802
2072
  out.push({
1803
- level,
1804
2073
  node: id,
1805
2074
  message: `"${labelOf(id)}" holds ${what}; ${isAnchor ? "review whether each floor is a major section" : "review whether this is one natural collection"}`,
1806
2075
  fix: `inspect membership and depth: glassbrain tree <path> --path "${id}"
1807
2076
  glassbrain restructure <path> --dry-run shows candidate groups and their ids.
1808
- Prefer fewer than 5 children per group; this is guidance, not a quota. Keep a natural collection together; add a named group only when it explains membership.${isAnchor ? "\n Each numbered root child becomes a floor. Use @-1 for an unordered collection; reserve numbered root children for major sections." : ""}`
2077
+ Prefer fewer than 5 children per group; this is guidance, not a quota. Keep a natural collection together; add a named group only when it explains membership.${isAnchor ? "\n Each root child can be shown as a floor; use the view switch to read them together." : ""}`
1809
2078
  });
1810
2079
  }
1811
2080
  return out;
@@ -1813,10 +2082,10 @@ var wideNode = {
1813
2082
  };
1814
2083
  var uncoloredKind = {
1815
2084
  code: "uncolored-kind",
1816
- level: "error",
2085
+ level: "warn",
1817
2086
  run: ({ model, profile }) => {
1818
2087
  const used = [...new Set(model.nodes.map((n) => n.kind).filter((k) => !!k))];
1819
- const missing = used.filter((k) => !(k in profile.nodePalette));
2088
+ const missing = used.filter((k) => !Object.hasOwn(profile.nodePalette, k));
1820
2089
  if (!missing.length) return [];
1821
2090
  const shown = missing.slice(0, 5);
1822
2091
  const palette = Object.fromEntries(shown.map((k, i) => [k, ["#6366f1", "#f59e0b", "#10b981", "#ef4444", "#8b5cf6"][i % 5]]));
@@ -1829,45 +2098,16 @@ ${missing.length > shown.length ? ` \u2026 and ${missing.length - shown.length}
1829
2098
  }];
1830
2099
  }
1831
2100
  };
1832
- var singleKind = {
1833
- code: "single-kind",
1834
- level: "info",
1835
- run: ({ model }) => {
1836
- const used = new Set(model.nodes.map((n) => n.kind).filter(Boolean));
1837
- if (used.size !== 1 || model.nodes.length < MIN_SAMPLE) return [];
1838
- return [{
1839
- message: `every node has kind "${[...used][0]}"; check whether this is one natural category`,
1840
- fix: `keep one kind for genuinely similar things. Introduce another only when it expresses a useful distinction; counts alone do not justify it.`
1841
- }];
1842
- }
1843
- };
1844
2101
  var kindNote = {
1845
2102
  code: "kind-note",
1846
- level: "info",
1847
- run: ({ model }) => {
1848
- const out = [];
1849
- const spread = (space, counts, total) => {
1850
- const kinds = counts.size;
1851
- if (!kinds || total < MIN_SAMPLE) return;
1852
- const average = total / kinds;
1853
- if (kinds > 10 || average < 5) {
1854
- out.push({
1855
- message: `${space} kinds: ${kinds} (${average.toFixed(1)} per kind); around 8 colors and repeated kinds are easier to scan, but counts are advisory`,
1856
- fix: `inspect whether kinds express distinct meanings. Preserve precise relation kinds and meaningful rare categories; merge only synonyms.`
1857
- });
1858
- }
1859
- };
1860
- const lone = (space, counts, total) => {
1861
- if (total < MIN_SAMPLE) return;
1862
- const once = [...counts].filter(([, c]) => c === 1).map(([k]) => k);
1863
- if (once.length) out.push({ message: `${once.length} ${space} kind${once.length > 1 ? "s" : ""} used once: ${names(once)}`, fix: `keep a rare kind when its meaning is distinct; do not add instances merely to meet a count.` });
1864
- };
1865
- spread("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1866
- spread("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1867
- lone("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1868
- lone("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1869
- return out;
1870
- }
2103
+ level: "warn",
2104
+ run: ({ model }) => ["node", "edge"].flatMap((space) => {
2105
+ const d = kindDistribution(space === "node" ? model.nodes : model.edges);
2106
+ return d.reason ? [{
2107
+ message: `${kindHeading(space, d)}; ${d.typed} typed ${space}s`,
2108
+ fix: "review the vocabulary as a whole; merge synonymous kinds and keep meaningful distinctions, including rare ones. Do not add instances just to satisfy a count."
2109
+ }] : [];
2110
+ })
1871
2111
  };
1872
2112
  var lowCoverage = {
1873
2113
  code: "coverage-note",
@@ -1907,41 +2147,21 @@ var colorNote = {
1907
2147
  }];
1908
2148
  }
1909
2149
  };
1910
- var orderHint = {
1911
- code: "order-hint",
1912
- level: "info",
1913
- run: ({ model, children }) => {
1914
- const roots = model.nodes.filter((n) => !n.parent);
1915
- if (roots.length !== 1) return [];
1916
- const root = roots[0];
1917
- const kids = children.get(root.id) ?? [];
1918
- if (kids.length < 2 || kids.some((k) => typeof k.order === "number")) return [];
1919
- return [{
1920
- node: root.id,
1921
- message: `"${root.label || root.id}" has ${kids.length} unordered children; it opens flat, with optional floors`,
1922
- fix: `keep @-1 for a collection. Number the root children only when they are major sections worth separate floors; view can also preview floors without changing the data.`
1923
- }];
1924
- }
1925
- };
1926
2150
  var rules = [
1927
2151
  misplacedField,
1928
2152
  layerField,
1929
2153
  unknownParent,
1930
2154
  parentCycle,
1931
2155
  reservedContains,
1932
- orderMixed,
1933
- orderDuplicate,
1934
2156
  conflictingDefinition,
1935
2157
  danglingEdge,
1936
2158
  duplicateEdge,
1937
2159
  unevenKinds,
1938
2160
  wideNode,
1939
2161
  uncoloredKind,
1940
- singleKind,
1941
2162
  kindNote,
1942
2163
  colorNote,
1943
- lowCoverage,
1944
- orderHint
2164
+ lowCoverage
1945
2165
  ];
1946
2166
  function checkGraph(model, profile, opts) {
1947
2167
  const children = /* @__PURE__ */ new Map();
@@ -1958,10 +2178,11 @@ function checkGraph(model, profile, opts) {
1958
2178
  index: model.index,
1959
2179
  children,
1960
2180
  layers: deriveLayers(model),
1961
- labelOf: (id) => model.index.get(id)?.label ?? id,
1962
- sameFileDuplicates: opts.sameFileDuplicates ?? /* @__PURE__ */ new Set()
2181
+ labelOf: (id) => model.index.get(id)?.label ?? id
1963
2182
  };
1964
- const out = rules.flatMap((rule) => rule.run(ctx).map((issue) => ({
2183
+ const invalidStructure = unknownParent.run(ctx).length > 0 || parentCycle.run(ctx).length > 0;
2184
+ const applicable = opts.quality === false ? rules.filter((rule) => rule.level === "error") : rules;
2185
+ const out = applicable.filter((rule) => !invalidStructure || rule !== unevenKinds).flatMap((rule) => rule.run(ctx).map((issue) => ({
1965
2186
  level: issue.level ?? rule.level,
1966
2187
  code: rule.code,
1967
2188
  where: opts.where,
@@ -1986,7 +2207,12 @@ function structureOf(model) {
1986
2207
  arr ? arr.push(n) : children.set(n.parent, [n]);
1987
2208
  }
1988
2209
  const derived = deriveLayers(model);
1989
- const analysis = analyzeShape(model.nodes);
2210
+ let analysis;
2211
+ try {
2212
+ analysis = analyzeShape(model.nodes);
2213
+ } catch {
2214
+ analysis = analyzeShape([]);
2215
+ }
1990
2216
  return {
1991
2217
  nodes: model.nodes.length,
1992
2218
  edges: model.edges.length,
@@ -1996,14 +2222,9 @@ function structureOf(model) {
1996
2222
  layers: derived.layers.length,
1997
2223
  regularity: +(1 - analysis.peak).toFixed(3),
1998
2224
  shape: { peak: analysis.peak, assessed: analysis.assessed, unassessed: analysis.unassessed, branches: analysis.branches },
1999
- ordered: derived.layers.length > 0 || [...children.keys()].some((id) => orderedChildren(children, id) !== null)
2225
+ ordered: derived.layers.length > 0 || [...children.keys()].some((id) => orderedChildren(children, id, model.index.get(id)?.data?.unordered === true) !== null)
2000
2226
  };
2001
2227
  }
2002
- function countsBy(values) {
2003
- const out = /* @__PURE__ */ new Map();
2004
- for (const v of values) if (v) out.set(v, (out.get(v) ?? 0) + 1);
2005
- return out;
2006
- }
2007
2228
  function hexLab(value) {
2008
2229
  const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(value.trim());
2009
2230
  if (!m) return null;
@@ -2022,9 +2243,10 @@ function deltaE(a2, b) {
2022
2243
 
2023
2244
  // cli/model.ts
2024
2245
  function profileFromJson(id, json) {
2025
- if (!json) return defineProfile({ id });
2026
- const { demo: _demo, diffIgnore: _ignore, edgeLabels = {}, layers: _layers, singleRoot: _single, ...rest } = json;
2027
- return defineProfile({ id, ...rest, kindLabels: { ...rest.kindLabels, ...edgeLabels } });
2246
+ if (!json || checkSchema(profile_schema_default, json, 1).length) return defineProfile({ id });
2247
+ const fields = Object.fromEntries(Object.entries(json).filter(([key]) => Object.hasOwn(profile_schema_default.properties, key)));
2248
+ const kindLabels = { ...json.kindLabels, ...json.edgeLabels };
2249
+ return defineProfile({ id, ...fields, kindLabels });
2028
2250
  }
2029
2251
  function profileOf(l) {
2030
2252
  const json = l.profile;
@@ -2042,112 +2264,61 @@ function derivedProfile(base2, sources, json, force) {
2042
2264
  }
2043
2265
  var modelOf = (v, profile) => parseSources(v.sources, profile);
2044
2266
  var RANK = { error: 0, warn: 1, info: 2 };
2045
- function lint(loaded) {
2267
+ function inspectProfile(json) {
2268
+ if (!json) return [];
2269
+ const out = checkSchema(profile_schema_default, json).map((e) => ({ level: "error", code: "schema", where: "_profile.json", message: `${e.path}: ${e.message}` }));
2270
+ if (typeof json !== "object" || Array.isArray(json)) return out;
2271
+ const retired = ["layers", "singleRoot"].filter((k) => k in json);
2272
+ if (retired.length) out.push({
2273
+ level: "warn",
2274
+ code: "schema",
2275
+ where: "_profile.json",
2276
+ message: `${retired.map((k) => `"${k}"`).join(" and ")} no longer configure anything: layers come from the ordered children structure`,
2277
+ fix: 'delete the retired keys from _profile.json. Use "appearance": { "defaultLayers": false } to open flat.'
2278
+ });
2279
+ return out;
2280
+ }
2281
+ function inspectGraph(model, profile, sources, opts) {
2046
2282
  const out = [];
2047
- const profile = profileOf(loaded);
2048
- if (loaded.profile) {
2049
- for (const e of checkSchema(profile_schema_default, loaded.profile)) out.push({ level: "error", code: "schema", where: "_profile.json", message: `${e.path}: ${e.message}` });
2050
- const retired = ["layers", "singleRoot"].filter((k) => k in loaded.profile);
2051
- if (retired.length) out.push({
2052
- level: "warn",
2053
- code: "schema",
2054
- where: "_profile.json",
2055
- message: `${retired.map((k) => `"${k}"`).join(" and ")} no longer configure anything: layers come from the order in "parent"`,
2056
- fix: `delete ${retired.length > 1 ? "them" : "it"} from _profile.json. The page opens on the floors when the graph has them; write "appearance": { "defaultLayers": false } to open flat.`
2057
- });
2283
+ const prefix = opts.prefix ?? "";
2284
+ const notJson = /* @__PURE__ */ new Set();
2285
+ if (opts.native !== false) for (const f of sources) {
2286
+ let doc;
2287
+ try {
2288
+ doc = JSON.parse(f.text);
2289
+ } catch (e) {
2290
+ notJson.add(f.origin);
2291
+ out.push({ level: "error", code: "schema", where: prefix + f.origin, message: `not JSON: ${e.message}` });
2292
+ continue;
2293
+ }
2294
+ if (!doc || typeof doc !== "object" || !("nodes" in doc) && !("edges" in doc)) {
2295
+ out.push({ level: "warn", code: "schema", where: prefix + f.origin, message: 'not a graph (no "nodes" or "edges"), skipped' });
2296
+ continue;
2297
+ }
2298
+ for (const e of checkSchema(graph_schema_default, doc)) out.push({ level: "error", code: "schema", where: prefix + f.origin, message: `${e.path}: ${e.message}` });
2058
2299
  }
2300
+ for (const e of model.errors) if (!notJson.has(e.origin)) out.push({ level: "error", code: e.code ?? "schema", where: prefix + e.origin, message: e.message, node: e.node });
2301
+ out.push(...checkGraph(model, profile, { where: opts.where, quality: opts.quality }));
2302
+ if (!model.nodes.length) out.push({ level: "warn", code: "schema", where: opts.where, message: "No nodes found" });
2303
+ return out.sort((a2, b) => RANK[a2.level] - RANK[b.level]);
2304
+ }
2305
+ function lint(loaded) {
2306
+ const out = inspectProfile(loaded.profile);
2307
+ const profile = profileOf(loaded);
2059
2308
  for (const e of loaded.metaErrors) out.push({ level: "error", code: "schema", where: e.file, message: e.message });
2060
2309
  const latest = loaded.raw[loaded.raw.length - 1]?.version;
2061
2310
  for (const { version, files } of loaded.raw) {
2062
2311
  const prefix = loaded.versions.length > 1 ? `${version}/` : "";
2063
- const notJson = /* @__PURE__ */ new Set();
2064
- const sameFileDuplicates = /* @__PURE__ */ new Set();
2065
- if (loaded.format === "native") {
2066
- for (const f of files) {
2067
- if (!/\.json$/i.test(f.path)) continue;
2068
- let doc;
2069
- try {
2070
- doc = JSON.parse(f.text);
2071
- } catch (e) {
2072
- notJson.add(f.path);
2073
- out.push({ level: "error", code: "schema", where: prefix + f.path, message: `not JSON: ${e.message}` });
2074
- continue;
2075
- }
2076
- if (!doc || typeof doc !== "object" || !("nodes" in doc) && !("edges" in doc)) {
2077
- out.push({ level: "warn", code: "schema", where: prefix + f.path, message: 'not a graph (no "nodes" or "edges"), skipped' });
2078
- continue;
2079
- }
2080
- for (const e of checkSchema(graph_schema_default, doc)) out.push({ level: "error", code: "schema", where: prefix + f.path, message: `${e.path}: ${e.message}` });
2081
- const rawNodes = (Array.isArray(doc.nodes) ? doc.nodes : []).filter((n) => !!n && typeof n === "object");
2082
- const bare = rawNodes.filter((n) => !("parent" in n));
2083
- if (bare.length) out.push({
2084
- level: "error",
2085
- code: "parent-error",
2086
- where: prefix + f.path,
2087
- 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: null for the root, otherwise "<id>@<order>"`,
2088
- fix: `add the field. The top of the tree is null; everything else names its container and its place:
2089
- - { "id": "${String(bare[0].id)}" }
2090
- + { "id": "${String(bare[0].id)}", "parent": null }
2091
- - { "id": "child" }
2092
- + { "id": "child", "parent": "${String(bare[0].id)}@-1" }`
2093
- });
2094
- const malformed = rawNodes.filter((n) => "parent" in n && typeof n.parent === "string" && !parentParts(n.parent));
2095
- if (malformed.length) {
2096
- const sample = malformed[0];
2097
- const value = String(sample.parent);
2098
- const at = value.lastIndexOf("@");
2099
- const id = at > 0 ? value.slice(0, at) : value;
2100
- out.push({
2101
- level: "error",
2102
- code: "parent-error",
2103
- where: prefix + f.path,
2104
- message: `${malformed.length} node${malformed.length > 1 ? "s" : ""} with a malformed "parent" (${malformed.slice(0, 3).map((n) => `"${String(n.parent)}"`).join(", ")}${malformed.length > 3 ? ` and ${malformed.length - 3} more` : ""}); it is "<id>@<order>"`,
2105
- fix: `write the container's id, then "@", then a positive number (-1 = explicitly unordered):
2106
- - { "id": "${String(sample.id)}", "parent": ${JSON.stringify(value)} }
2107
- + { "id": "${String(sample.id)}", "parent": "${id}@-1" }`
2108
- });
2109
- }
2110
- const roots = rawNodes.filter((n) => n.parent === null);
2111
- if (roots.length > 1) out.push({
2112
- level: "error",
2113
- code: "parent-error",
2114
- where: prefix + f.path,
2115
- message: `${roots.length} nodes with "parent": null (${roots.slice(0, 3).map((n) => `"${String(n.id)}"`).join(", ")}${roots.length > 3 ? ` and ${roots.length - 3} more` : ""}); a file has one root`,
2116
- fix: `one file is one tree. Add a root and hang the others under it (numbered children open the floors):
2117
- + { "id": "overview", "label": "Overview", "parent": null }
2118
- ${roots.slice(0, 3).map((n, i) => `- { "id": "${String(n.id)}", "parent": null }
2119
- + { "id": "${String(n.id)}", "parent": "overview@${i + 1}" }`).join("\n ")}
2120
- or split the file: one file per tree.`
2121
- });
2122
- const seen = /* @__PURE__ */ new Map();
2123
- for (const id of idsIn(doc)) seen.set(id, (seen.get(id) ?? 0) + 1);
2124
- for (const [id, count2] of seen) {
2125
- if (count2 < 2) continue;
2126
- sameFileDuplicates.add(id);
2127
- out.push({ level: "error", code: "duplicate-id", where: prefix + f.path, message: `id "${id}" appears ${count2} times in this file; the first one is kept` });
2128
- }
2129
- }
2130
- }
2131
2312
  const v = loaded.versions.find((x) => x.name === version);
2132
- const model = modelOf(v, profile);
2133
- for (const e of model.errors) if (!notJson.has(e.origin)) out.push({ level: "error", code: "schema", where: prefix + e.origin, message: e.message });
2134
- if (version === latest) out.push(...checkGraph(model, profile, { where: prefix || loaded.title, sameFileDuplicates }));
2135
- if (!model.nodes.length) out.push({ level: "warn", code: "schema", where: prefix || loaded.title, message: "No nodes found" });
2313
+ out.push(...inspectGraph(
2314
+ modelOf(v, profile),
2315
+ profile,
2316
+ files.filter((f) => /\.json$/i.test(f.path)).map((f) => ({ origin: f.path, text: f.text })),
2317
+ { where: prefix || loaded.title, prefix, native: (v.format ?? loaded.format) === "native", quality: version === latest }
2318
+ ));
2136
2319
  }
2137
2320
  return out.sort((a2, b) => RANK[a2.level] - RANK[b.level]);
2138
2321
  }
2139
- var ORDER_TAIL = /^(-1|\d+(\.\d+)?)$/;
2140
- function parentParts(raw) {
2141
- const at = raw.lastIndexOf("@");
2142
- if (at < 1) return null;
2143
- const order = raw.slice(at + 1);
2144
- return ORDER_TAIL.test(order) && (order === "-1" || Number.isFinite(Number(order)) && Number(order) > 0) ? { id: raw.slice(0, at), order } : null;
2145
- }
2146
- function idsIn(doc) {
2147
- const nodes = doc.nodes;
2148
- if (!Array.isArray(nodes)) return [];
2149
- return nodes.filter((n) => !!n && typeof n === "object" && "id" in n && n.id != null).map((n) => String(n.id));
2150
- }
2151
2322
  var ignoreOf = (profile, extra = []) => [.../* @__PURE__ */ new Set([...Array.isArray(profile?.diffIgnore) ? profile.diffIgnore : [], ...extra])];
2152
2323
  function diff(before, after, labels, ignore = []) {
2153
2324
  const delta = diffModels(before, after, { labels, ignore });
@@ -2253,7 +2424,7 @@ function tree(model, opts) {
2253
2424
  const bySize = (a2, b) => (size.get(b.id) ?? 1) - (size.get(a2.id) ?? 1) || labelOf(a2.id).localeCompare(labelOf(b.id));
2254
2425
  const sorted = /* @__PURE__ */ new Map();
2255
2426
  for (const [id, list] of kids) {
2256
- sorted.set(id, orderedChildren(kids, id) ?? [...list].sort(bySize));
2427
+ sorted.set(id, orderedChildren(kids, id, model.index.get(id)?.data?.unordered === true) ?? [...list].sort(bySize));
2257
2428
  }
2258
2429
  const outgoing = /* @__PURE__ */ new Map();
2259
2430
  for (const e of model.edges) {
@@ -2281,13 +2452,14 @@ function tree(model, opts) {
2281
2452
  if (collapsed && tall > 0) bits.push(`${tall} deep`);
2282
2453
  if (edges.length) bits.push(edgeText(edges));
2283
2454
  const label = `${labelOf(node.id)}${broken(node) ? " (parent missing)" : ""}`;
2284
- const orderTag = typeof node.order === "number" ? `[${node.order}] ` : "";
2455
+ const order = node.parent && model.index.get(node.parent)?.data?.unordered === true ? void 0 : node.order;
2456
+ const orderTag = typeof order === "number" ? `[${order}] ` : "";
2285
2457
  entries.push({
2286
2458
  id: node.id,
2287
2459
  label,
2288
2460
  depth: level,
2289
2461
  layer: layerOf(node),
2290
- ...typeof node.order === "number" ? { order: node.order } : {},
2462
+ ...typeof order === "number" ? { order } : {},
2291
2463
  nodes: inside,
2292
2464
  deep: tall,
2293
2465
  collapsed,
@@ -2316,6 +2488,10 @@ function tree(model, opts) {
2316
2488
  };
2317
2489
  const structure = structureOf(model);
2318
2490
  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 structure pressure ${structure.shape.peak.toFixed(3)} \xB7 ${structure.shape.assessed} assessed / ${structure.shape.unassessed} unassessed`;
2491
+ const kinds = { nodes: kindDistribution(model.nodes), edges: kindDistribution(model.edges) };
2492
+ header += `
2493
+ ${kindSummary("node", kinds.nodes, opts.kindLabels)}
2494
+ ${kindSummary("edge", kinds.edges, opts.kindLabels)}`;
2319
2495
  const roots = model.nodes.filter((n) => !n.parent || broken(n));
2320
2496
  if (opts.path) {
2321
2497
  const start = model.index.get(opts.path);
@@ -2358,7 +2534,7 @@ path: ${[...chain, labelOf(start.id)].join(" \u203A ")}`;
2358
2534
  }
2359
2535
  }
2360
2536
  const more = Math.max(0, entries.length - maxLines);
2361
- return { header, entries: more ? entries.slice(0, maxLines) : entries, more };
2537
+ return { header, kinds, entries: more ? entries.slice(0, maxLines) : entries, more };
2362
2538
  }
2363
2539
  function treeText(result) {
2364
2540
  const lines = [result.header, ...result.entries.map((e) => e.text)];
@@ -2458,7 +2634,7 @@ function restructure(input, edges, opts = {}) {
2458
2634
  }
2459
2635
  if (outside - within < 0.15) continue;
2460
2636
  const indices = ordered.map((n, i) => members.includes(n.id) ? i : -1).filter((i) => i >= 0);
2461
- if (ordered.every((n) => n.order !== void 0) && Math.max(...indices) - Math.min(...indices) + 1 !== members.length) continue;
2637
+ if (byId.get(b.parent)?.data.unordered !== true && ordered.every((n) => n.order !== void 0) && Math.max(...indices) - Math.min(...indices) + 1 !== members.length) continue;
2462
2638
  suggestions.push({
2463
2639
  parent: b.parent,
2464
2640
  members: ordered.filter((n) => members.includes(n.id)).map((n) => n.id),
@@ -2479,12 +2655,14 @@ function restructure(input, edges, opts = {}) {
2479
2655
  const siblings = nodes.filter((n) => n.parent === parent).sort((a2, b) => (a2.order ?? a2.seq ?? 0) - (b.order ?? b.seq ?? 0));
2480
2656
  if (members.length === siblings.length)
2481
2657
  throw new Error("grouping every sibling adds no distinction");
2482
- const numbered = siblings.every((n) => n.order !== void 0);
2658
+ const unordered = byId.get(parent)?.data.unordered === true;
2659
+ const numbered = !unordered && siblings.every((n) => n.order !== void 0);
2483
2660
  const indices = siblings.map((n, i) => opts.group.includes(n.id) ? i : -1).filter((i) => i >= 0);
2484
2661
  if (numbered && Math.max(...indices) - Math.min(...indices) + 1 !== members.length)
2485
2662
  throw new Error("ordered group members must be consecutive");
2486
2663
  const label = siblings.filter((n) => opts.group.includes(n.id)).map((n) => n.label || n.id).join(" & ");
2487
2664
  const group = add(label, "group", parent);
2665
+ if (unordered) group.data.unordered = true;
2488
2666
  if (numbered)
2489
2667
  group.order = Math.min(...members.map((n) => n.order));
2490
2668
  for (const n of members)
@@ -2542,48 +2720,34 @@ function planNodesOf(model) {
2542
2720
  label: n.label,
2543
2721
  kind: n.kind,
2544
2722
  parent: n.parent ?? null,
2545
- order: typeof n.order === "number" ? n.order : typeof n.data?.order === "number" && Number.isFinite(n.data.order) && n.data.order > 0 ? n.data.order : void 0,
2723
+ order: n.order,
2546
2724
  seq,
2547
2725
  data: n.data ?? {}
2548
2726
  }));
2549
2727
  }
2550
2728
  function graphOf(plan, name, edges) {
2551
- return {
2552
- name,
2553
- nodes: plan.nodes.map((p) => {
2554
- const { parent: _p, order: _o, layer: _layer, ...rest } = p.data ?? {};
2555
- return {
2556
- ...rest,
2557
- id: p.id,
2558
- label: p.label,
2559
- ...p.kind ? { kind: p.kind } : {},
2560
- parent: encodeParent(p.parent, p.order)
2561
- };
2562
- }),
2563
- edges
2564
- };
2729
+ const model = buildModel(plan.nodes.map((p) => ({ ...p, parent: p.parent ?? void 0 })), []);
2730
+ return { name, nodes: toPhysical(model).nodes, edges };
2565
2731
  }
2566
2732
 
2567
2733
  // cli/glassbrain.ts
2568
2734
  var HELP = (schema) => `glassbrain: open, diff and lint a knowledge graph, written as plain JSON.
2569
2735
 
2570
2736
  [ DATA ]
2571
- JSON with two arrays, \`nodes\` and \`edges\`. The parent structure helps readability.
2737
+ JSON with two arrays, \`nodes\` and \`edges\`. The children structure helps readability.
2572
2738
  { "nodes": [
2573
- { "id": "start", "label": "Start", "kind": "folder","parent": null }, // the root: parent is null
2574
- { "id": "login", "label": "Login", "kind": "file", "parent": "start@1", // first child
2739
+ { "id": "start", "label": "Start", "kind": "folder", "children": [ // the root
2740
+ { "id": "login", "label": "Login", "kind": "file", // first child
2575
2741
  "description": "Checks the password, then opens a session.", // markdown
2576
2742
  "owner": "auth" }, // any other field: kept, shown
2577
- { "id": "db", "label": "DB", "kind": "file", "parent": "start@2" } ], // second child
2743
+ { "id": "db", "label": "DB", "kind": "file" } ] } ], // second child
2578
2744
  "edges": [
2579
2745
  { "source": "login", "target": "db", "kind": "uses" } ] }
2580
2746
 
2581
2747
  GUIDELINES
2582
- * \`parent\` is required on EVERY node: null for the only root, otherwise "<id>@<order>".
2583
- * \`@order\` sorts siblings: use distinct positive numbers; decimals are allowed.
2584
- * Use \`@-1\` only to force an unordered group; all siblings must then use @-1.
2585
- * Parent structure helps readability. Prefer fewer than 5 children; keep natural collections. Consider deeper grouping if crowded.
2586
- * Keep kinds few and consistent (around 8 or fewer).
2748
+ * \`id\` identifies a node; nest it in \`children\` in reading order. Recommend \`kind\` for its category.
2749
+ * Children structure helps readability. Prefer fewer than 5 children; keep natural collections. Consider deeper grouping if crowded.
2750
+ * Reuse consistent node and edge kinds; check their distributions with tree.
2587
2751
  * Keep depth and detail meaningful. Lint flags structural imbalance as \`bad-structure\`.
2588
2752
  * Put supporting details in descriptions. Extra fields are kept and shown.
2589
2753
 
@@ -2601,14 +2765,14 @@ var HELP = (schema) => `glassbrain: open, diff and lint a knowledge graph, writt
2601
2765
  \u251C\u2500\u2500 2-filled/graph.json each pass is the whole graph: copy the last, edit the copy
2602
2766
  \u2514\u2500\u2500 3-linked/graph.json then lint, and diff against the pass before
2603
2767
 
2604
- Inside a pass, JSON at any depth merges by id; split by area only when a file gets too big to write.
2768
+ Inside a pass, same ids fill absent fields; conflicting values or child-id sequences error. Split by area when needed.
2605
2769
 
2606
2770
  [ APPEARANCE ]
2607
2771
  kg/_profile.json, shared by every pass, also when opening a pass file directly.
2608
2772
  A local pass profile overrides it; an exported bundle carries its own profile.
2609
2773
 
2610
2774
  COLORS one entry per kind you use. A kind without an entry is drawn as skeleton \u2014
2611
- every uncoloured kind looks the same, so lint reports it as an error.
2775
+ every uncoloured kind looks the same, so lint reports it as a warning.
2612
2776
  { "nodePalette": { "file": "#6366f1", "folder": "#94a3b8" },
2613
2777
  "edgePalette": { "uses": "#2563eb" } }
2614
2778
  Colors closer than 10 in Lab distance read as one kind (lint notes it).
@@ -2626,7 +2790,7 @@ var HELP = (schema) => `glassbrain: open, diff and lint a knowledge graph, writt
2626
2790
  glassbrain lint <path> Lint errors, warnings, info; exit 1 on errors.
2627
2791
  Always lint before handing over.
2628
2792
  glassbrain tree <path> log the containment tree as text
2629
- glassbrain restructure <path> preserve content; repair containment and order, suggest groups;
2793
+ glassbrain restructure <path> preserve content; repair containment, preserve reading order, suggest groups;
2630
2794
  write graph.json and _profile.json in a new folder
2631
2795
  glassbrain diff <old> <new> only what changed between two graphs
2632
2796
  glassbrain diff <git-ref> <path> the same graph at an earlier commit (default HEAD)
@@ -2792,6 +2956,7 @@ function runDiff(a2) {
2792
2956
  const ma = modelOf(va, profile);
2793
2957
  notes(before, []);
2794
2958
  notes(after, []);
2959
+ if (mb.errors.length || ma.errors.length || mb.duplicateIds?.length || ma.duplicateIds?.length) fail("repair input conflicts before diff", 1);
2795
2960
  const ignore = ignoreOf(profileJson, typeof a2.flags.ignore === "string" ? a2.flags.ignore.split(",").map((s) => s.trim()).filter(Boolean) : []);
2796
2961
  const { summary } = diff(mb, ma, labels, ignore);
2797
2962
  const labelOf = (id) => ma.index.get(id)?.label ?? mb.index.get(id)?.label ?? id;
@@ -2856,15 +3021,17 @@ function runTree(a2) {
2856
3021
  const models = nodesOf(l);
2857
3022
  notes(l, models);
2858
3023
  const latest = models[models.length - 1];
3024
+ if (latest.errors.length) fail(latest.errors.map((e) => `${e.origin}: ${e.message}`).join("\n"), 1);
2859
3025
  const version = l.versions[l.versions.length - 1].name;
2860
3026
  const result = tree(latest, {
3027
+ kindLabels: profileOf(l).kindLabels,
2861
3028
  title: l.versions.length > 1 ? `${l.title}/${version}` : l.title,
2862
3029
  depth,
2863
3030
  path: typeof a2.flags.path === "string" ? a2.flags.path : void 0,
2864
3031
  orphans: a2.flags.orphans === true
2865
3032
  });
2866
3033
  if (a2.flags.json) {
2867
- console.log(JSON.stringify({ title: l.title, ...structureOf(latest), entries: result.entries, more: result.more }, null, 1));
3034
+ console.log(JSON.stringify({ title: l.title, ...structureOf(latest), kinds: result.kinds, entries: result.entries, more: result.more }, null, 1));
2868
3035
  } else {
2869
3036
  console.log(treeText(result));
2870
3037
  }
@@ -2872,7 +3039,7 @@ function runTree(a2) {
2872
3039
  function runRestructure(a2) {
2873
3040
  if (a2.pos.length !== 1) fail("restructure needs exactly one <path>");
2874
3041
  const l = load(a2.pos[0], { format: a2.flags.format });
2875
- const blockers = lint(l).filter((f) => f.code === "duplicate-id" || f.code === "dangling-edge");
3042
+ const blockers = lint(l).filter((f) => ["duplicate-id", "dangling-edge", "field-conflict", "children-conflict"].includes(f.code));
2876
3043
  if (blockers.length) fail(`repair identity/relation errors before restructure: ${blockers.map((f) => f.message).join("; ")}`, 1);
2877
3044
  const models = nodesOf(l);
2878
3045
  notes(l, models);
@@ -2917,8 +3084,8 @@ function runRestructure(a2) {
2917
3084
  const abs = path2.resolve(a2.pos[0]);
2918
3085
  const dir = fs2.existsSync(abs) && fs2.statSync(abs).isDirectory() ? abs : path2.dirname(abs);
2919
3086
  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) : [];
2920
- const palette = {};
2921
- const known = { folder: "#94a3b8", file: "#64748b", overview: "#a855f7", group: "#a855f7" };
3087
+ const palette = kindTable();
3088
+ const known = kindTable({ folder: "#94a3b8", file: "#64748b", overview: "#a855f7", group: "#a855f7" });
2922
3089
  const wheel = ["#6366f1", "#f59e0b", "#10b981", "#ef4444", "#8b5cf6", "#06b6d4"];
2923
3090
  let wi = 0;
2924
3091
  for (const k of new Set(plan.nodes.map((n) => n.kind))) {
@@ -2947,13 +3114,18 @@ function runConvert(a2) {
2947
3114
  if (a2.pos.length < 1 || a2.pos.length > 2) fail("convert needs <path> [out-dir]");
2948
3115
  const l = load(a2.pos[0], { format: a2.flags.format });
2949
3116
  const models = nodesOf(l);
2950
- const graphs = l.versions.map((v, i) => ({ name: v.name, graph: { name: v.name, ...toPhysical(models[i]) } }));
3117
+ const graphs = l.versions.map((v, i) => ({ name: v.name, graph: { name: v.name, ...l.profile ? { profile: l.profile } : {}, ...toPhysical(models[i]) } }));
2951
3118
  const outDir = a2.pos[1];
2952
3119
  if (!outDir) {
2953
3120
  if (graphs.length > 1) fail("several versions: give an out-dir");
2954
3121
  console.log(JSON.stringify(graphs[0].graph, null, 1));
2955
3122
  return;
2956
3123
  }
3124
+ const outputs = graphs.map((g) => path2.join(outDir, ...graphs.length > 1 ? [g.name] : [], "graph.json"));
3125
+ if (l.profile) outputs.push(path2.join(outDir, "_profile.json"));
3126
+ if (l.layouts) outputs.push(path2.join(outDir, "_layout.json"));
3127
+ const existing = outputs.find((file) => fs2.existsSync(file));
3128
+ if (existing) fail(`output already exists: ${existing}; choose a fresh output directory`);
2957
3129
  fs2.mkdirSync(outDir, { recursive: true });
2958
3130
  for (const g of graphs) {
2959
3131
  const dir = graphs.length > 1 ? path2.join(outDir, g.name) : outDir;