glassbrain 0.2.0-alpha.2 → 0.2.0-alpha.4

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 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 };
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 };
16
16
  }
17
17
  function mergeSlices(slices) {
18
18
  const byId = /* @__PURE__ */ new Map();
@@ -94,6 +94,19 @@ function indexModel(model) {
94
94
  };
95
95
  return { parentOf, childrenOf, depthOf, ancestorsOf, subtreeOf, neighborsOf };
96
96
  }
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}`;
109
+ }
97
110
 
98
111
  // src/profile.ts
99
112
  function parsePhysical(origin, text) {
@@ -105,18 +118,29 @@ function parsePhysical(origin, text) {
105
118
  }
106
119
  if (!raw || typeof raw !== "object" || !("nodes" in raw) && !("edges" in raw)) return null;
107
120
  const ref = (v) => typeof v === "string" || typeof v === "number" ? String(v) : void 0;
108
- const nodes = (Array.isArray(raw.nodes) ? raw.nodes : []).filter((n) => n && typeof n === "object" && ref(n.id) !== void 0).map((n) => ({
109
- id: String(n.id),
110
- label: String(n.label ?? n.name ?? n.id),
111
- kind: typeof n.kind === "string" ? n.kind : void 0,
112
- parent: ref(n.parent),
113
- order: typeof n.order === "number" && Number.isFinite(n.order) ? n.order : void 0,
114
- layer: typeof n.layer === "string" ? n.layer : void 0,
115
- // Marks carried by the data itself (e.g. a placeholder "with no content yet"). They are data, not derived: when the profile's
116
- // `placeholderFlags` recognizes one, it is drawn as skeleton.
117
- ...Array.isArray(n.flags) ? { flags: n.flags.filter((f) => typeof f === "string") } : {},
118
- data: n
119
- }));
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
+ });
120
144
  const edges = (Array.isArray(raw.edges) ? raw.edges : []).filter((e) => e && typeof e === "object").map((e) => ({
121
145
  source: String(e.source ?? e.from),
122
146
  target: String(e.target ?? e.to),
@@ -132,7 +156,11 @@ function toPhysical(model) {
132
156
  const clean2 = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0 && v !== ""));
133
157
  return {
134
158
  // `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 })),
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
+ }),
136
164
  edges: model.edges.map((e) => clean2({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }))
137
165
  };
138
166
  }
@@ -317,7 +345,18 @@ function convertGraphify(d, name) {
317
345
  var score = (l) => typeof l.confidence_score === "number" ? l.confidence_score : typeof l.weight === "number" ? Math.min(1, l.weight) : void 0;
318
346
  var groupLabel = (t) => ({ concept: "Concepts", rationale: "Rationale", document: "Documents" })[t] ?? t;
319
347
  var PROFILE = {
320
- nodePalette: { symbol: "#6366f1", concept: "#e63b7a", rationale: "#f59e0b", document: "#0891b2", paper: "#0891b2", image: "#16a34a" },
348
+ // The adapter invents these three while building the folder / file boxes, so it must colour them too.
349
+ nodePalette: {
350
+ symbol: "#6366f1",
351
+ concept: "#e63b7a",
352
+ rationale: "#f59e0b",
353
+ document: "#0891b2",
354
+ paper: "#0891b2",
355
+ image: "#16a34a",
356
+ folder: "#94a3b8",
357
+ file: "#64748b",
358
+ group: "#a855f7"
359
+ },
321
360
  edgePalette: {
322
361
  calls: "#6366f1",
323
362
  imports: "#94a3b8",
@@ -532,7 +571,8 @@ var obsidian = {
532
571
  return {
533
572
  sources,
534
573
  profile: {
535
- nodePalette: autoPalette(kinds),
574
+ // `folder` is invented by the walk, not present in frontmatter kinds: colour it here.
575
+ nodePalette: { ...autoPalette(kinds), folder: "#94a3b8" },
536
576
  edgePalette: { link: "#94a3b8" },
537
577
  kindLabels: { folder: "Folder", note: "Note", link: "link" },
538
578
  detail: { line: [{ key: "path", label: "File" }], list: [{ key: "tags", label: "Tags" }] },
@@ -623,7 +663,10 @@ var PROFILE2 = {
623
663
  source: "#64748b",
624
664
  screen: "#0891b2",
625
665
  component: "#6366f1",
626
- token: "#f59e0b"
666
+ token: "#f59e0b",
667
+ layer: "#a855f7",
668
+ folder: "#94a3b8",
669
+ file: "#64748b"
627
670
  },
628
671
  edgePalette: {
629
672
  imports: "#94a3b8",
@@ -725,7 +768,7 @@ function walk(root) {
725
768
  if (out.length >= MAX_FILES) throw new Error(`More than ${MAX_FILES} data files under ${root} \u2014 point at a smaller folder`);
726
769
  const p = path.join(dir, e.name);
727
770
  if (e.isDirectory()) {
728
- if (SKIP_DIR.has(e.name) || e.name.startsWith(".") && !DOT_OK.has(e.name)) continue;
771
+ if (e.name.endsWith(".restructured") || SKIP_DIR.has(e.name) || e.name.startsWith(".") && !DOT_OK.has(e.name)) continue;
729
772
  go(p);
730
773
  } else if (DATA.test(e.name)) {
731
774
  out.push({ path: path.relative(root, p).split(path.sep).join("/"), text: fs.readFileSync(p, "utf8") });
@@ -760,9 +803,27 @@ function gitSpec(spec, cwd) {
760
803
  return { files, title, isDir: true };
761
804
  }
762
805
  var META = /* @__PURE__ */ new Set(["_profile.json", "_layout.json"]);
806
+ function mergeProfile(base2, over) {
807
+ const pal = (a2, b) => ({ ...a2 && typeof a2 === "object" ? a2 : {}, ...b && typeof b === "object" ? b : {} });
808
+ return {
809
+ ...base2,
810
+ ...over,
811
+ nodePalette: pal(base2.nodePalette, over.nodePalette),
812
+ edgePalette: pal(base2.edgePalette, over.edgePalette),
813
+ kindLabels: pal(base2.kindLabels, over.kindLabels)
814
+ };
815
+ }
763
816
  var natural = (a2, b) => a2.localeCompare(b, void 0, { numeric: true });
764
817
  function load(spec, opts = {}) {
765
818
  const tree2 = readSpec(spec, opts.cwd);
819
+ const abs = path.resolve(opts.cwd ?? process.cwd(), spec);
820
+ if (fs.existsSync(abs) && !tree2.files.some((f) => f.path === "_profile.json")) {
821
+ const dir = tree2.isDir ? abs : path.dirname(abs);
822
+ const candidates = [path.join(dir, "_profile.json")];
823
+ if (/^\d+-/.test(path.basename(dir))) candidates.push(path.join(path.dirname(dir), "_profile.json"));
824
+ const file = candidates.find((p) => fs.existsSync(p));
825
+ if (file) tree2.files.push({ path: "_profile.json", text: fs.readFileSync(file, "utf8") });
826
+ }
766
827
  const metaErrors = [];
767
828
  const meta = (name) => {
768
829
  const f = tree2.files.find((x) => x.path === name);
@@ -774,7 +835,17 @@ function load(spec, opts = {}) {
774
835
  return null;
775
836
  }
776
837
  };
777
- const data = tree2.files.filter((f) => !META.has(f.path));
838
+ const bundled = () => {
839
+ if (tree2.isDir) return null;
840
+ try {
841
+ const d = JSON.parse(tree2.files[0].text);
842
+ return d && typeof d === "object" && d.profile && typeof d.profile === "object" ? d.profile : null;
843
+ } catch {
844
+ return null;
845
+ }
846
+ };
847
+ const explicit = bundled() ?? meta("_profile.json");
848
+ const data = tree2.files.filter((f) => !META.has(path.posix.basename(f.path)));
778
849
  const isJson = (f) => /\.json$/i.test(f.path);
779
850
  const dirs = [...new Set(data.filter((f) => f.path.includes("/")).map((f) => f.path.split("/")[0]))].sort(natural);
780
851
  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)));
@@ -794,7 +865,9 @@ function load(spec, opts = {}) {
794
865
  return {
795
866
  title: tree2.title,
796
867
  versions,
797
- profile: meta("_profile.json") ?? suggested,
868
+ // A `_profile.json` that only carries demo metadata used to *replace* the adapter's profile, taking its palette
869
+ // with it: a converted graph then drew every kind as skeleton. Explicit keys win; the adapter fills the rest.
870
+ profile: explicit && suggested ? mergeProfile(suggested, explicit) : explicit ?? suggested,
798
871
  layouts: meta("_layout.json"),
799
872
  format,
800
873
  metaErrors,
@@ -983,7 +1056,6 @@ function diffModels(before, after, opts = {}) {
983
1056
  }
984
1057
 
985
1058
  // src/layers.ts
986
- var MAX_DERIVED_LAYERS = 8;
987
1059
  var EMPTY = { layers: [], layerOf: /* @__PURE__ */ new Map() };
988
1060
  function orderedChildren(children, id) {
989
1061
  const kids = children.get(id) ?? [];
@@ -1006,14 +1078,20 @@ function childrenMap(model) {
1006
1078
  }
1007
1079
  return out;
1008
1080
  }
1009
- function deriveLayers(model, colors = []) {
1081
+ function deriveLayers(model, colors = [], force = false) {
1010
1082
  if (!model.nodes.length) return EMPTY;
1011
1083
  const children = childrenMap(model);
1012
1084
  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;
1085
+ let ordered = null;
1086
+ let anchor;
1087
+ if (roots.length === 1) {
1088
+ anchor = roots[0];
1089
+ ordered = orderedChildren(children, anchor.id);
1090
+ if (!ordered && force) ordered = children.get(anchor.id) ?? null;
1091
+ } else if (force && roots.length > 1) {
1092
+ ordered = roots;
1093
+ }
1094
+ if (!ordered || ordered.length < 2) return EMPTY;
1017
1095
  const layers = ordered.map((n, i) => ({
1018
1096
  id: n.id,
1019
1097
  label: n.label || n.id,
@@ -1029,8 +1107,8 @@ function deriveLayers(model, colors = []) {
1029
1107
  for (const k of children.get(id) ?? []) stack.push(k.id);
1030
1108
  }
1031
1109
  }
1032
- layerOf.set(anchor.id, layers[0].id);
1033
- return { layers, layerOf, anchor: anchor.id };
1110
+ if (anchor) layerOf.set(anchor.id, layers[0].id);
1111
+ return { layers, layerOf, anchor: anchor?.id };
1034
1112
  }
1035
1113
 
1036
1114
  // schema/graph.schema.json
@@ -1038,7 +1116,7 @@ var graph_schema_default = {
1038
1116
  $schema: "https://json-schema.org/draft/2020-12/schema",
1039
1117
  $id: "https://unpkg.com/glassbrain/schema/graph.schema.json",
1040
1118
  title: "glassbrain graph",
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.",
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.',
1042
1120
  type: "object",
1043
1121
  anyOf: [{ required: ["nodes"] }, { required: ["edges"] }],
1044
1122
  properties: {
@@ -1058,12 +1136,11 @@ var graph_schema_default = {
1058
1136
  type: "object",
1059
1137
  required: ["id", "parent"],
1060
1138
  properties: {
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." },
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)." },
1062
1140
  label: { type: "string", description: "Display name. Falls back to `name`, then `id`." },
1063
1141
  name: { type: "string", description: "Alias of `label`." },
1064
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." },
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." },
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.' },
1067
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." },
1068
1145
  description: { type: "string", description: "Markdown shown in the detail panel. `[text](node:<id>)` links jump to another node." }
1069
1146
  },
@@ -1238,7 +1315,8 @@ var KNOWN = /* @__PURE__ */ new Set([
1238
1315
  "$ref",
1239
1316
  "minimum",
1240
1317
  "maximum",
1241
- "exclusiveMinimum"
1318
+ "exclusiveMinimum",
1319
+ "pattern"
1242
1320
  ]);
1243
1321
  var typeOf = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v === "number" ? Number.isInteger(v) ? "integer" : "number" : typeof v;
1244
1322
  var fits = (v, t) => {
@@ -1258,6 +1336,9 @@ function checkSchema(root, value, limit = 50) {
1258
1336
  return;
1259
1337
  }
1260
1338
  }
1339
+ if (typeof v === "string" && typeof s.pattern === "string" && !new RegExp(s.pattern).test(v)) {
1340
+ out2.push({ path: path3, message: `does not match ${s.pattern}` });
1341
+ }
1261
1342
  if (s.anyOf && !s.anyOf.some((alt) => {
1262
1343
  const e = [];
1263
1344
  walk2(alt, v, path3, e);
@@ -1287,18 +1368,234 @@ function checkSchema(root, value, limit = 50) {
1287
1368
  return out;
1288
1369
  }
1289
1370
 
1371
+ // cli/shape.ts
1372
+ var rounded = (x) => +x.toFixed(6);
1373
+ function analyzeShape(nodes) {
1374
+ const byId = new Map(nodes.map((n) => [n.id, n]));
1375
+ const children = /* @__PURE__ */ new Map();
1376
+ for (const n of nodes)
1377
+ if (n.parent && byId.has(n.parent)) {
1378
+ const xs = children.get(n.parent) ?? [];
1379
+ xs.push(n.id);
1380
+ children.set(n.parent, xs);
1381
+ }
1382
+ const shapes = [];
1383
+ const intern = /* @__PURE__ */ new Map();
1384
+ const nodeShape = /* @__PURE__ */ new Map();
1385
+ const active = /* @__PURE__ */ new Set();
1386
+ const compile = (id) => {
1387
+ const hit = nodeShape.get(id);
1388
+ if (hit !== void 0)
1389
+ return hit;
1390
+ if (active.has(id))
1391
+ throw new Error("parent cycle: repair containment before measuring shape");
1392
+ active.add(id);
1393
+ const hist = /* @__PURE__ */ new Map();
1394
+ for (const k of children.get(id) ?? []) {
1395
+ const s2 = compile(k);
1396
+ hist.set(s2, (hist.get(s2) ?? 0) + 1);
1397
+ }
1398
+ active.delete(id);
1399
+ const entries = [...hist].sort((a2, b) => a2[0] - b[0]);
1400
+ const kind = byId.get(id)?.kind;
1401
+ const key = JSON.stringify([kind ?? null, entries]);
1402
+ let s = intern.get(key);
1403
+ if (s === void 0) {
1404
+ s = shapes.length;
1405
+ intern.set(key, s);
1406
+ shapes.push({ key: s, kind, count: (children.get(id) ?? []).length, typed: !!kind && [...hist.keys()].every((k) => shapes[k].typed), children: hist });
1407
+ }
1408
+ nodeShape.set(id, s);
1409
+ return s;
1410
+ };
1411
+ const pending = new Map(nodes.map((n) => [n.id, (children.get(n.id) ?? []).length]));
1412
+ const queue = nodes.filter((n) => pending.get(n.id) === 0).map((n) => n.id);
1413
+ for (let at = 0; at < queue.length; at++) {
1414
+ const id = queue[at];
1415
+ compile(id);
1416
+ const p = byId.get(id)?.parent;
1417
+ if (p && pending.has(p)) {
1418
+ const left = pending.get(p) - 1;
1419
+ pending.set(p, left);
1420
+ if (!left)
1421
+ queue.push(p);
1422
+ }
1423
+ }
1424
+ if (nodeShape.size !== byId.size)
1425
+ return { branches: [], peak: 0, assessed: 0, unassessed: children.size, distance: () => 0 };
1426
+ const cache = /* @__PURE__ */ new Map();
1427
+ const kernel = (a2, b, depth = 0) => {
1428
+ if (a2 === b)
1429
+ return 1;
1430
+ const x = shapes[a2], y = shapes[b];
1431
+ if (x.kind !== y.kind)
1432
+ return 0;
1433
+ if (depth >= 16)
1434
+ return 1;
1435
+ const key = `${Math.min(a2, b)}:${Math.max(a2, b)}:${depth}`;
1436
+ const hit = cache.get(key);
1437
+ if (hit !== void 0)
1438
+ return hit;
1439
+ const dot = (u, v) => {
1440
+ let sum = 0;
1441
+ for (const [i, ni] of u.children)
1442
+ for (const [j, nj] of v.children)
1443
+ sum += ni * nj * kernel(i, j, depth + 1);
1444
+ return sum / (u.count * v.count);
1445
+ };
1446
+ const c = !x.count && !y.count ? 1 : !x.count || !y.count ? 0 : dot(x, y) / Math.sqrt(dot(x, x) * dot(y, y));
1447
+ const k = Math.min(1, 0.5 + 0.5 * c);
1448
+ cache.set(key, k);
1449
+ return k;
1450
+ };
1451
+ const quantityCache = /* @__PURE__ */ new Map();
1452
+ const quantities = (id) => {
1453
+ const hit = quantityCache.get(id);
1454
+ if (hit)
1455
+ return hit;
1456
+ const out = [];
1457
+ let level = /* @__PURE__ */ new Map([[id, 1]]);
1458
+ for (let d = 0; d < 16; d++) {
1459
+ let total = 0, sum = 0;
1460
+ const next = /* @__PURE__ */ new Map();
1461
+ for (const [s, n] of level) {
1462
+ total += n;
1463
+ sum += n * Math.log2(1 + shapes[s].count);
1464
+ for (const [c, k] of shapes[s].children)
1465
+ next.set(c, (next.get(c) ?? 0) + n * k);
1466
+ }
1467
+ out.push(total ? sum / total : 0);
1468
+ level = next;
1469
+ }
1470
+ quantityCache.set(id, out);
1471
+ return out;
1472
+ };
1473
+ const distanceCache = /* @__PURE__ */ new Map();
1474
+ const shapeDistance = (i, j) => {
1475
+ if (i === j)
1476
+ return 0;
1477
+ const key = `${Math.min(i, j)}:${Math.max(i, j)}`;
1478
+ const hit = distanceCache.get(key);
1479
+ if (hit !== void 0)
1480
+ return hit;
1481
+ const x = quantities(i), y = quantities(j);
1482
+ let size = 0;
1483
+ for (let d = 0; d < 16; d++)
1484
+ size += 2 ** (-d - 1) * (1 - Math.exp(-Math.abs(x[d] - y[d])));
1485
+ const value = 0.85 * Math.sqrt(Math.max(0, 1 - kernel(i, j))) + 0.15 * size;
1486
+ if (shapes[i].count || shapes[j].count)
1487
+ distanceCache.set(key, value);
1488
+ return value;
1489
+ };
1490
+ const distance = (a2, b) => {
1491
+ const i = nodeShape.get(a2), j = nodeShape.get(b);
1492
+ return i === void 0 || j === void 0 ? 0 : shapeDistance(i, j);
1493
+ };
1494
+ const enter = /* @__PURE__ */ new Map(), leave = /* @__PURE__ */ new Map();
1495
+ let tick = 0;
1496
+ const stack = nodes.filter((n) => !n.parent || !byId.has(n.parent)).map((n) => [n.id, false]);
1497
+ while (stack.length) {
1498
+ const [id, done] = stack.pop();
1499
+ if (done) {
1500
+ leave.set(id, tick++);
1501
+ continue;
1502
+ }
1503
+ enter.set(id, tick++);
1504
+ stack.push([id, true]);
1505
+ for (const child of children.get(id) ?? []) stack.push([child, false]);
1506
+ }
1507
+ const contains = (a2, b) => enter.get(a2) <= enter.get(b) && leave.get(a2) >= leave.get(b);
1508
+ const forks = [...children.keys()].filter((id) => {
1509
+ const shape = shapes[nodeShape.get(id)];
1510
+ return shape.count >= 3 && shape.typed;
1511
+ });
1512
+ const templateSupport = (id) => {
1513
+ const own = nodeShape.get(id);
1514
+ if (!shapes[own].typed || shapes[own].count < 3) return 1;
1515
+ let support = 1;
1516
+ for (const other of forks) {
1517
+ if (contains(id, other) || contains(other, id)) continue;
1518
+ const candidate = nodeShape.get(other);
1519
+ if (shapes[own].kind !== shapes[candidate].kind) continue;
1520
+ const near = Math.max(0, 1 - (shapeDistance(own, candidate) / 0.12) ** 2);
1521
+ support += near * near;
1522
+ }
1523
+ return support;
1524
+ };
1525
+ const branches = [];
1526
+ for (const [parent, kids] of children) {
1527
+ const groups = /* @__PURE__ */ new Map();
1528
+ for (const id of kids) {
1529
+ const s = nodeShape.get(id);
1530
+ const xs = groups.get(s) ?? [];
1531
+ xs.push(id);
1532
+ groups.set(s, xs);
1533
+ }
1534
+ const gs = [...groups.values()];
1535
+ let sum = 0, sq = 0;
1536
+ const low = [], high = [];
1537
+ const keep = (p) => {
1538
+ if (low.length < 6 || p.distance < low[low.length - 1].distance) {
1539
+ low.push(p);
1540
+ low.sort((a2, b) => a2.distance - b.distance);
1541
+ if (low.length > 6)
1542
+ low.pop();
1543
+ }
1544
+ if (high.length < 6 || p.distance > high[0].distance) {
1545
+ high.push(p);
1546
+ high.sort((a2, b) => a2.distance - b.distance);
1547
+ if (high.length > 6)
1548
+ high.shift();
1549
+ }
1550
+ };
1551
+ for (let i = 0; i < gs.length; i++) {
1552
+ if (gs[i].length > 1)
1553
+ keep({ a: gs[i][0], b: gs[i][1], distance: 0 });
1554
+ for (let j = i + 1; j < gs.length; j++) {
1555
+ const d = distance(gs[i][0], gs[j][0]), weight = gs[i].length * gs[j].length;
1556
+ sum += weight * d;
1557
+ sq += weight * d * d;
1558
+ keep({ a: gs[i][0], b: gs[j][0], distance: rounded(d) });
1559
+ }
1560
+ }
1561
+ const total = kids.length * (kids.length - 1) / 2, mean = total ? sum / total : 0;
1562
+ const dispersion = Math.sqrt(Math.max(0, (total ? sq / total : 0) - mean * mean));
1563
+ const support = templateSupport(parent);
1564
+ const pairs = [...new Map([...low, ...high].map((p) => [`${p.a}\0${p.b}`, p])).values()];
1565
+ pairs.sort((a2, b) => a2.distance - b.distance || a2.a.localeCompare(b.a) || a2.b.localeCompare(b.b));
1566
+ const assessed = kids.length >= 3 && shapes[nodeShape.get(parent)].typed;
1567
+ branches.push({
1568
+ parent,
1569
+ children: kids,
1570
+ meanDistance: rounded(mean),
1571
+ dispersion: rounded(dispersion),
1572
+ support: rounded(support),
1573
+ score: assessed ? rounded(dispersion / support) : 0,
1574
+ assessed,
1575
+ closest: pairs[0],
1576
+ pairs: pairs.length > 12 ? [...pairs.slice(0, 6), ...pairs.slice(-6)] : pairs
1577
+ });
1578
+ }
1579
+ return {
1580
+ branches,
1581
+ peak: Math.max(0, ...branches.map((b) => b.score)),
1582
+ assessed: branches.filter((b) => b.assessed).length,
1583
+ unassessed: branches.filter((b) => !b.assessed).length,
1584
+ distance
1585
+ };
1586
+ }
1587
+
1290
1588
  // cli/checks.ts
1291
- var ISOMORPHISM_TAU = 0.85;
1292
1589
  var WIDE_INFO = 5;
1293
1590
  var WIDE_WARN = 10;
1294
1591
  var MAX_NAMES = 4;
1295
1592
  var MIN_SAMPLE = 10;
1296
1593
  var names = (xs) => `${xs.slice(0, MAX_NAMES).join(", ")}${xs.length > MAX_NAMES ? ` and ${xs.length - MAX_NAMES} more` : ""}`;
1297
1594
  var misplacedField = {
1298
- code: "misplaced-field",
1595
+ code: "schema",
1299
1596
  level: "error",
1300
1597
  run: ({ model }) => {
1301
- const reserved = ["id", "label", "kind", "parent", "order", "description"];
1598
+ const reserved = ["id", "label", "kind", "parent", "description"];
1302
1599
  const out = [];
1303
1600
  for (const n of model.nodes) {
1304
1601
  const nested = n.data?.data;
@@ -1317,32 +1614,32 @@ var misplacedField = {
1317
1614
  }
1318
1615
  };
1319
1616
  var layerField = {
1320
- code: "layer-field",
1617
+ code: "schema",
1321
1618
  level: "error",
1322
1619
  run: ({ model }) => model.nodes.filter((n) => n.data && typeof n.data === "object" && "layer" in n.data).map((n) => ({
1323
1620
  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 }`
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" }`
1328
1625
  }))
1329
1626
  };
1330
1627
  var unknownParent = {
1331
- code: "unknown-parent",
1628
+ code: "parent-error",
1332
1629
  level: "error",
1333
- run: ({ model, index: index2, labelOf }) => model.nodes.filter((n) => n.parent && !index2.has(n.parent)).map((n) => ({
1630
+ run: ({ model, index, labelOf }) => model.nodes.filter((n) => n.parent && !index.has(n.parent)).map((n) => ({
1334
1631
  node: n.id,
1335
1632
  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.)`
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.)`
1340
1637
  }))
1341
1638
  };
1342
1639
  var parentCycle = {
1343
- code: "parent-cycle",
1640
+ code: "parent-error",
1344
1641
  level: "error",
1345
- run: ({ model, index: index2 }) => {
1642
+ run: ({ model, index }) => {
1346
1643
  const out = [];
1347
1644
  const done = /* @__PURE__ */ new Set();
1348
1645
  for (const start of model.nodes) {
@@ -1359,15 +1656,15 @@ var parentCycle = {
1359
1656
  node: cur,
1360
1657
  message: `parent cycle: ${[...loop, cur].join(" \u2192 ")}`,
1361
1658
  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}" }
1659
+ - { "id": "${loop[0]}", "parent": "${cur}@-1" }
1363
1660
  + { "id": "${loop[0]}", "parent": null }`
1364
1661
  });
1365
1662
  break;
1366
1663
  }
1367
1664
  at.set(cur, path3.length);
1368
1665
  path3.push(cur);
1369
- const parent = index2.get(cur)?.parent;
1370
- cur = parent && index2.has(parent) ? parent : void 0;
1666
+ const parent = index.get(cur)?.parent;
1667
+ cur = parent && index.has(parent) ? parent : void 0;
1371
1668
  }
1372
1669
  for (const id of path3) done.add(id);
1373
1670
  }
@@ -1375,7 +1672,7 @@ var parentCycle = {
1375
1672
  }
1376
1673
  };
1377
1674
  var orderMixed = {
1378
- code: "order-mixed",
1675
+ code: "order-error",
1379
1676
  level: "error",
1380
1677
  run: ({ children }) => {
1381
1678
  const out = [];
@@ -1386,17 +1683,17 @@ var orderMixed = {
1386
1683
  const next = Math.max(0, ...kids.map((k) => typeof k.order === "number" ? k.order : 0)) + 1;
1387
1684
  out.push({
1388
1685
  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")}`
1686
+ message: `${withOrder} of ${kids.length} children of "${parent}" are numbered; a sibling set is numbered or explicitly unordered ("@-1")`,
1687
+ fix: `give the rest an order, or mark them all unordered with "@-1":
1688
+ ${missing.map((k, i) => ` - { "id": "${k.id}", "parent": "${parent}@-1" }
1689
+ + { "id": "${k.id}", "parent": "${parent}@${next + i}" }`).join("\n")}`
1393
1690
  });
1394
1691
  }
1395
1692
  return out;
1396
1693
  }
1397
1694
  };
1398
1695
  var orderDuplicate = {
1399
- code: "order-duplicate",
1696
+ code: "order-error",
1400
1697
  level: "error",
1401
1698
  run: ({ children }) => {
1402
1699
  const out = [];
@@ -1413,8 +1710,8 @@ var orderDuplicate = {
1413
1710
  node: parent,
1414
1711
  message: `"${parent}" has ${same.length} children at order ${value} (${names(same.map((n) => n.id))}); two items cannot share a place`,
1415
1712
  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")}`
1713
+ ${same.slice(1).map((k, i) => ` - { "id": "${k.id}", "parent": "${parent}@${value}" }
1714
+ + { "id": "${k.id}", "parent": "${parent}@${value + (i + 1) / 10}" }`).join("\n")}`
1418
1715
  });
1419
1716
  }
1420
1717
  }
@@ -1422,28 +1719,28 @@ ${same.slice(1).map((k, i) => ` - { "id": "${k.id}", "order": ${value} }
1422
1719
  }
1423
1720
  };
1424
1721
  var conflictingDefinition = {
1425
- code: "conflicting-definition",
1722
+ code: "duplicate-id",
1426
1723
  level: "error",
1427
- run: ({ model, index: index2, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1724
+ run: ({ model, index, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1428
1725
  node: id,
1429
- message: `"${id}" is defined differently in ${names(index2.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`,
1726
+ message: `"${id}" is defined differently in ${names(index.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`,
1430
1727
  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.`
1728
+ ${names(index.get(id)?.origins ?? [])} \u2014 keep one definition of "${id}", or rename the other to "${id}-2" and update every edge that meant it.`
1432
1729
  }))
1433
1730
  };
1434
1731
  var danglingEdge = {
1435
1732
  code: "dangling-edge",
1436
1733
  level: "error",
1437
- run: ({ model, index: index2, labelOf }) => {
1734
+ run: ({ model, index, labelOf }) => {
1438
1735
  const out = [];
1439
1736
  for (const e of model.edges) {
1440
- const missing = [!index2.has(e.source) && e.source, !index2.has(e.target) && e.target].filter(Boolean).join(" / ");
1737
+ const missing = [!index.has(e.source) && e.source, !index.has(e.target) && e.target].filter(Boolean).join(" / ");
1441
1738
  if (!missing) continue;
1442
1739
  out.push({
1443
1740
  message: `edge ${e.source} \u2192 ${e.target}${e.kind ? ` (${e.kind})` : ""} points at the missing node ${missing}`,
1444
1741
  fix: `an edge can only join nodes that exist. Add the node, or repoint the edge:
1445
1742
  - { "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"}" }`
1743
+ + { "source": "${index.has(e.source) ? e.source : labelOf(e.target) || e.source}", "target": "${index.has(e.target) ? e.target : "EXISTING_ID"}" }`
1447
1744
  });
1448
1745
  }
1449
1746
  return out;
@@ -1471,88 +1768,17 @@ var duplicateEdge = {
1471
1768
  return out;
1472
1769
  }
1473
1770
  };
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
- }
1771
+ var unevenKinds = {
1772
+ code: "bad-structure",
1773
+ level: "info",
1774
+ run: ({ model }) => analyzeShape(model.nodes).branches.filter((b) => b.score >= 0.2).sort((a2, b) => b.score - a2.score).map((b) => ({
1775
+ node: b.parent,
1776
+ level: b.children.length > WIDE_WARN ? "error" : b.score >= 0.4 ? "warn" : "info",
1777
+ 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)})`,
1778
+ fix: `inspect this branch: glassbrain tree <path> --path "${b.parent}"
1779
+ closest compared pair: ${b.closest?.a} / ${b.closest?.b} (distance ${b.closest?.distance}). Differences can be intentional.
1780
+ glassbrain restructure <path> --dry-run --json shows grouping suggestions; no content is deleted.`
1781
+ }))
1556
1782
  };
1557
1783
  var wideNode = {
1558
1784
  code: "wide-node",
@@ -1568,21 +1794,47 @@ var wideNode = {
1568
1794
  out.push({
1569
1795
  level,
1570
1796
  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" }`
1797
+ message: `"${labelOf(id)}" holds ${what}; ${isAnchor ? "review whether each floor is a major section" : "review whether this is one natural collection"}`,
1798
+ fix: `inspect membership and depth: glassbrain tree <path> --path "${id}"
1799
+ glassbrain restructure <path> --dry-run shows candidate groups and their ids.
1800
+ 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." : ""}`
1579
1801
  });
1580
1802
  }
1581
1803
  return out;
1582
1804
  }
1583
1805
  };
1584
- var preferFewerKinds = {
1585
- code: "prefer-fewer-kinds",
1806
+ var uncoloredKind = {
1807
+ code: "uncolored-kind",
1808
+ level: "error",
1809
+ run: ({ model, profile }) => {
1810
+ const used = [...new Set(model.nodes.map((n) => n.kind).filter((k) => !!k))];
1811
+ const missing = used.filter((k) => !(k in profile.nodePalette));
1812
+ if (!missing.length) return [];
1813
+ const shown = missing.slice(0, 5);
1814
+ const palette = Object.fromEntries(shown.map((k, i) => [k, ["#6366f1", "#f59e0b", "#10b981", "#ef4444", "#8b5cf6"][i % 5]]));
1815
+ return [{
1816
+ message: `${missing.length} node kind${missing.length > 1 ? "s are" : " is"} not in nodePalette, so ${missing.length > 1 ? "they are" : "it is"} drawn as skeleton: ${names(missing)}`,
1817
+ fix: `add one colour per kind to _profile.json (one entry per kind, not per node):
1818
+ { "nodePalette": ${JSON.stringify(palette)} }
1819
+ ${missing.length > shown.length ? ` \u2026 and ${missing.length - shown.length} more; every kind in the data needs an entry.
1820
+ ` : ""} Colors that land closer than 10 in Lab distance read as one kind (lint notes it).`
1821
+ }];
1822
+ }
1823
+ };
1824
+ var singleKind = {
1825
+ code: "single-kind",
1826
+ level: "info",
1827
+ run: ({ model }) => {
1828
+ const used = new Set(model.nodes.map((n) => n.kind).filter(Boolean));
1829
+ if (used.size !== 1 || model.nodes.length < MIN_SAMPLE) return [];
1830
+ return [{
1831
+ message: `every node has kind "${[...used][0]}"; check whether this is one natural category`,
1832
+ fix: `keep one kind for genuinely similar things. Introduce another only when it expresses a useful distinction; counts alone do not justify it.`
1833
+ }];
1834
+ }
1835
+ };
1836
+ var kindNote = {
1837
+ code: "kind-note",
1586
1838
  level: "info",
1587
1839
  run: ({ model }) => {
1588
1840
  const out = [];
@@ -1592,33 +1844,25 @@ var preferFewerKinds = {
1592
1844
  const average = total / kinds;
1593
1845
  if (kinds > 10 || average < 5) {
1594
1846
  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.`
1847
+ message: `${space} kinds: ${kinds} (${average.toFixed(1)} per kind); around 8 colors and repeated kinds are easier to scan, but counts are advisory`,
1848
+ fix: `inspect whether kinds express distinct meanings. Preserve precise relation kinds and meaningful rare categories; merge only synonyms.`
1597
1849
  });
1598
1850
  }
1599
1851
  };
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
1852
  const lone = (space, counts, total) => {
1611
1853
  if (total < MIN_SAMPLE) return;
1612
1854
  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.` });
1855
+ 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.` });
1614
1856
  };
1857
+ spread("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1858
+ spread("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1615
1859
  lone("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1616
1860
  lone("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1617
1861
  return out;
1618
1862
  }
1619
1863
  };
1620
1864
  var lowCoverage = {
1621
- code: "low-coverage",
1865
+ code: "coverage-note",
1622
1866
  level: "info",
1623
1867
  run: ({ model, children }) => {
1624
1868
  const leaves = model.nodes.filter((n) => !children.has(n.id));
@@ -1632,8 +1876,8 @@ var lowCoverage = {
1632
1876
  }];
1633
1877
  }
1634
1878
  };
1635
- var colorsContrast = {
1636
- code: "colors-contrast",
1879
+ var colorNote = {
1880
+ code: "color-note",
1637
1881
  level: "info",
1638
1882
  run: ({ profile }) => {
1639
1883
  const colors = Object.entries(profile.nodePalette).map(([kind, hex]) => ({ kind, lab: hexLab(hex) }));
@@ -1655,6 +1899,22 @@ var colorsContrast = {
1655
1899
  }];
1656
1900
  }
1657
1901
  };
1902
+ var orderHint = {
1903
+ code: "order-hint",
1904
+ level: "info",
1905
+ run: ({ model, children }) => {
1906
+ const roots = model.nodes.filter((n) => !n.parent);
1907
+ if (roots.length !== 1) return [];
1908
+ const root = roots[0];
1909
+ const kids = children.get(root.id) ?? [];
1910
+ if (kids.length < 2 || kids.some((k) => typeof k.order === "number")) return [];
1911
+ return [{
1912
+ node: root.id,
1913
+ message: `"${root.label || root.id}" has ${kids.length} unordered children; it opens flat, with optional floors`,
1914
+ 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.`
1915
+ }];
1916
+ }
1917
+ };
1658
1918
  var rules = [
1659
1919
  misplacedField,
1660
1920
  layerField,
@@ -1665,14 +1925,14 @@ var rules = [
1665
1925
  conflictingDefinition,
1666
1926
  danglingEdge,
1667
1927
  duplicateEdge,
1668
- multipleRoots,
1669
- noHierarchy,
1670
- unevenBranches,
1928
+ unevenKinds,
1671
1929
  wideNode,
1672
- preferFewerKinds,
1673
- loneKind,
1930
+ uncoloredKind,
1931
+ singleKind,
1932
+ kindNote,
1933
+ colorNote,
1674
1934
  lowCoverage,
1675
- colorsContrast
1935
+ orderHint
1676
1936
  ];
1677
1937
  function checkGraph(model, profile, opts) {
1678
1938
  const children = /* @__PURE__ */ new Map();
@@ -1682,17 +1942,6 @@ function checkGraph(model, profile, opts) {
1682
1942
  if (arr) arr.push(n);
1683
1943
  else children.set(n.parent, [n]);
1684
1944
  }
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
1945
  const ctx = {
1697
1946
  model,
1698
1947
  profile,
@@ -1701,7 +1950,6 @@ function checkGraph(model, profile, opts) {
1701
1950
  children,
1702
1951
  layers: deriveLayers(model),
1703
1952
  labelOf: (id) => model.index.get(id)?.label ?? id,
1704
- heightOf: (id) => heightOf(id),
1705
1953
  sameFileDuplicates: opts.sameFileDuplicates ?? /* @__PURE__ */ new Set()
1706
1954
  };
1707
1955
  const out = rules.flatMap((rule) => rule.run(ctx).map((issue) => ({
@@ -1715,12 +1963,12 @@ function checkGraph(model, profile, opts) {
1715
1963
  return out;
1716
1964
  }
1717
1965
  function structureOf(model) {
1718
- const index2 = indexModel(model);
1966
+ const index = indexModel(model);
1719
1967
  let depth = 0;
1720
1968
  let parented = 0;
1721
1969
  for (const n of model.nodes) {
1722
1970
  if (n.parent && model.index.has(n.parent)) parented++;
1723
- depth = Math.max(depth, index2.depthOf(n.id));
1971
+ depth = Math.max(depth, index.depthOf(n.id));
1724
1972
  }
1725
1973
  const children = /* @__PURE__ */ new Map();
1726
1974
  for (const n of model.nodes) {
@@ -1728,18 +1976,8 @@ function structureOf(model) {
1728
1976
  const arr = children.get(n.parent);
1729
1977
  arr ? arr.push(n) : children.set(n.parent, [n]);
1730
1978
  }
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
1979
  const derived = deriveLayers(model);
1980
+ const analysis = analyzeShape(model.nodes);
1743
1981
  return {
1744
1982
  nodes: model.nodes.length,
1745
1983
  edges: model.edges.length,
@@ -1747,7 +1985,8 @@ function structureOf(model) {
1747
1985
  depth,
1748
1986
  parented,
1749
1987
  layers: derived.layers.length,
1750
- isomorphism: +isomorphism(model, children, (id) => heightOf(id)).score.toFixed(2),
1988
+ regularity: +(1 - analysis.peak).toFixed(3),
1989
+ shape: { peak: analysis.peak, assessed: analysis.assessed, unassessed: analysis.unassessed, branches: analysis.branches },
1751
1990
  ordered: derived.layers.length > 0 || [...children.keys()].some((id) => orderedChildren(children, id) !== null)
1752
1991
  };
1753
1992
  }
@@ -1783,18 +2022,18 @@ function profileOf(l) {
1783
2022
  const base2 = profileFromJson("cli", json);
1784
2023
  const latest = l.versions[l.versions.length - 1];
1785
2024
  if (!latest) return base2;
1786
- return derivedProfile(base2, latest.sources, json);
2025
+ return derivedProfile(base2, latest.sources, json, false);
1787
2026
  }
1788
- function derivedProfile(base2, sources, json) {
2027
+ function derivedProfile(base2, sources, json, force) {
1789
2028
  const first = parseSources(sources, base2);
1790
2029
  const colors = json?.appearance?.layerColors;
1791
- const derived = deriveLayers(first, Array.isArray(colors) ? colors : []);
2030
+ const derived = deriveLayers(first, Array.isArray(colors) ? colors : [], force);
1792
2031
  if (derived.layers.length < 2) return base2;
1793
2032
  return defineProfile({ ...base2, layers: derived.layers, layerOf: (n) => derived.layerOf.get(n.id) ?? derived.layers[0].id });
1794
2033
  }
1795
2034
  var modelOf = (v, profile) => parseSources(v.sources, profile);
1796
2035
  var RANK = { error: 0, warn: 1, info: 2 };
1797
- function validate(loaded) {
2036
+ function lint(loaded) {
1798
2037
  const out = [];
1799
2038
  const profile = profileOf(loaded);
1800
2039
  if (loaded.profile) {
@@ -1802,11 +2041,10 @@ function validate(loaded) {
1802
2041
  const retired = ["layers", "singleRoot"].filter((k) => k in loaded.profile);
1803
2042
  if (retired.length) out.push({
1804
2043
  level: "warn",
1805
- code: "profile-retired",
2044
+ code: "schema",
1806
2045
  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 } }`
2046
+ message: `${retired.map((k) => `"${k}"`).join(" and ")} no longer configure anything: layers come from the order in "parent"`,
2047
+ 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.`
1810
2048
  });
1811
2049
  }
1812
2050
  for (const e of loaded.metaErrors) out.push({ level: "error", code: "schema", where: e.file, message: e.message });
@@ -1823,32 +2061,61 @@ function validate(loaded) {
1823
2061
  doc = JSON.parse(f.text);
1824
2062
  } catch (e) {
1825
2063
  notJson.add(f.path);
1826
- out.push({ level: "error", code: "not-json", where: prefix + f.path, message: `not JSON: ${e.message}` });
2064
+ out.push({ level: "error", code: "schema", where: prefix + f.path, message: `not JSON: ${e.message}` });
1827
2065
  continue;
1828
2066
  }
1829
2067
  if (!doc || typeof doc !== "object" || !("nodes" in doc) && !("edges" in doc)) {
1830
- out.push({ level: "warn", code: "not-a-graph", where: prefix + f.path, message: 'not a graph (no "nodes" or "edges"), skipped' });
2068
+ out.push({ level: "warn", code: "schema", where: prefix + f.path, message: 'not a graph (no "nodes" or "edges"), skipped' });
1831
2069
  continue;
1832
2070
  }
1833
2071
  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));
2072
+ const rawNodes = (Array.isArray(doc.nodes) ? doc.nodes : []).filter((n) => !!n && typeof n === "object");
2073
+ const bare = rawNodes.filter((n) => !("parent" in n));
1835
2074
  if (bare.length) out.push({
1836
2075
  level: "error",
1837
- code: "missing-parent",
2076
+ code: "parent-error",
1838
2077
  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:
2078
+ 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>"`,
2079
+ fix: `add the field. The top of the tree is null; everything else names its container and its place:
1841
2080
  - { "id": "${String(bare[0].id)}" }
1842
2081
  + { "id": "${String(bare[0].id)}", "parent": null }
1843
2082
  - { "id": "child" }
1844
- + { "id": "child", "parent": "${String(bare[0].id)}" }`
2083
+ + { "id": "child", "parent": "${String(bare[0].id)}@-1" }`
2084
+ });
2085
+ const malformed = rawNodes.filter((n) => "parent" in n && typeof n.parent === "string" && !parentParts(n.parent));
2086
+ if (malformed.length) {
2087
+ const sample = malformed[0];
2088
+ const value = String(sample.parent);
2089
+ const at = value.lastIndexOf("@");
2090
+ const id = at > 0 ? value.slice(0, at) : value;
2091
+ out.push({
2092
+ level: "error",
2093
+ code: "parent-error",
2094
+ where: prefix + f.path,
2095
+ 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>"`,
2096
+ fix: `write the container's id, then "@", then a positive number (-1 = explicitly unordered):
2097
+ - { "id": "${String(sample.id)}", "parent": ${JSON.stringify(value)} }
2098
+ + { "id": "${String(sample.id)}", "parent": "${id}@-1" }`
2099
+ });
2100
+ }
2101
+ const roots = rawNodes.filter((n) => n.parent === null);
2102
+ if (roots.length > 1) out.push({
2103
+ level: "error",
2104
+ code: "parent-error",
2105
+ where: prefix + f.path,
2106
+ 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`,
2107
+ fix: `one file is one tree. Add a root and hang the others under it (numbered children open the floors):
2108
+ + { "id": "overview", "label": "Overview", "parent": null }
2109
+ ${roots.slice(0, 3).map((n, i) => `- { "id": "${String(n.id)}", "parent": null }
2110
+ + { "id": "${String(n.id)}", "parent": "overview@${i + 1}" }`).join("\n ")}
2111
+ or split the file: one file per tree.`
1845
2112
  });
1846
2113
  const seen = /* @__PURE__ */ new Map();
1847
2114
  for (const id of idsIn(doc)) seen.set(id, (seen.get(id) ?? 0) + 1);
1848
2115
  for (const [id, count2] of seen) {
1849
2116
  if (count2 < 2) continue;
1850
2117
  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` });
2118
+ 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` });
1852
2119
  }
1853
2120
  }
1854
2121
  }
@@ -1856,10 +2123,17 @@ function validate(loaded) {
1856
2123
  const model = modelOf(v, profile);
1857
2124
  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
2125
  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" });
2126
+ if (!model.nodes.length) out.push({ level: "warn", code: "schema", where: prefix || loaded.title, message: "No nodes found" });
1860
2127
  }
1861
2128
  return out.sort((a2, b) => RANK[a2.level] - RANK[b.level]);
1862
2129
  }
2130
+ var ORDER_TAIL = /^(-1|\d+(\.\d+)?)$/;
2131
+ function parentParts(raw) {
2132
+ const at = raw.lastIndexOf("@");
2133
+ if (at < 1) return null;
2134
+ const order = raw.slice(at + 1);
2135
+ return ORDER_TAIL.test(order) && (order === "-1" || Number.isFinite(Number(order)) && Number(order) > 0) ? { id: raw.slice(0, at), order } : null;
2136
+ }
1863
2137
  function idsIn(doc) {
1864
2138
  const nodes = doc.nodes;
1865
2139
  if (!Array.isArray(nodes)) return [];
@@ -1934,6 +2208,7 @@ var MAX_LINES = 200;
1934
2208
  var MAX_EDGES = 6;
1935
2209
  function tree(model, opts) {
1936
2210
  const derived = deriveLayers(model);
2211
+ const evidence = new Map(analyzeShape(model.nodes).branches.map((b) => [b.parent, b]));
1937
2212
  const layerOf = (n) => derived.layerOf.get(n.id);
1938
2213
  const labelOf = (id) => model.index.get(id)?.label ?? id;
1939
2214
  const depth = Math.max(1, opts.depth ?? 3);
@@ -1991,6 +2266,8 @@ function tree(model, opts) {
1991
2266
  const tall = height.get(node.id) ?? 0;
1992
2267
  const edges = collapsed ? [] : outgoing.get(node.id) ?? [];
1993
2268
  const bits = [];
2269
+ const assessment = evidence.get(node.id);
2270
+ if (assessment) bits.push(`${list.length} ${list.length === 1 ? "child" : "children"} \xB7 ${assessment.assessed ? `pressure ${assessment.score.toFixed(3)}` : "unassessed"}`);
1994
2271
  if (inside > 0) bits.push(one(inside, "node"));
1995
2272
  if (collapsed && tall > 0) bits.push(`${tall} deep`);
1996
2273
  if (edges.length) bits.push(edgeText(edges));
@@ -2006,7 +2283,7 @@ function tree(model, opts) {
2006
2283
  deep: tall,
2007
2284
  collapsed,
2008
2285
  edges,
2009
- text: `${prefix}${connector}${orderTag}${label}${bits.length ? ` ${bits.join(" \xB7 ")}` : ""}`
2286
+ text: `${prefix}${connector}${orderTag}${label}${labelOf(node.id) !== node.id ? ` [${node.id}]` : ""}${bits.length ? ` ${bits.join(" \xB7 ")}` : ""}`
2010
2287
  });
2011
2288
  if (!canExpand) return;
2012
2289
  const shown = list.slice(0, perNode);
@@ -2029,7 +2306,7 @@ function tree(model, opts) {
2029
2306
  }
2030
2307
  };
2031
2308
  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)}`;
2309
+ 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`;
2033
2310
  const roots = model.nodes.filter((n) => !n.parent || broken(n));
2034
2311
  if (opts.path) {
2035
2312
  const start = model.index.get(opts.path);
@@ -2081,304 +2358,267 @@ function treeText(result) {
2081
2358
  }
2082
2359
 
2083
2360
  // cli/restructure.ts
2084
- function index(nodes) {
2361
+ function restructure(input, edges, opts = {}) {
2362
+ const nodes = input.map((n) => ({ ...n, data: { ...n.data } }));
2085
2363
  const byId = new Map(nodes.map((n) => [n.id, n]));
2086
- const children = /* @__PURE__ */ new Map();
2364
+ if (byId.size !== nodes.length)
2365
+ throw new Error("duplicate ids: resolve them before restructure");
2366
+ const done = /* @__PURE__ */ new Set();
2087
2367
  for (const n of nodes) {
2088
- if (!n.parent || !byId.has(n.parent)) {
2089
- n.parent = null;
2090
- continue;
2368
+ const seen = /* @__PURE__ */ new Set();
2369
+ let cur = n;
2370
+ while (cur && !done.has(cur.id)) {
2371
+ if (seen.has(cur.id))
2372
+ throw new Error("parent cycle: repair it before restructure");
2373
+ seen.add(cur.id);
2374
+ if (cur.parent && !byId.has(cur.parent))
2375
+ throw new Error(`unknown parent ${cur.parent}: repair it before restructure`);
2376
+ cur = cur.parent ? byId.get(cur.parent) : void 0;
2091
2377
  }
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;
2378
+ for (const id of seen)
2379
+ done.add(id);
2380
+ }
2381
+ for (const e of edges)
2382
+ if (!byId.has(e.source) || !byId.has(e.target))
2383
+ throw new Error("dangling edge: repair endpoints before restructure");
2384
+ const before = analyzeShape(nodes).peak, beforeFlat = !nodes.some((n) => n.parent);
2385
+ const created = [], moves = [], orders = [];
2386
+ const unique = (base2) => {
2387
+ let id = base2, i = 2;
2388
+ while (byId.has(id))
2389
+ id = `${base2}-${i++}`;
2390
+ return id;
2120
2391
  };
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;
2392
+ const add = (label, kind, parent, base2 = "group") => {
2393
+ const n = { id: unique(base2), label, kind, parent, data: {} };
2394
+ nodes.push(n);
2395
+ byId.set(n.id, n);
2396
+ created.push({ id: n.id, label, kind, parent });
2397
+ return n;
2133
2398
  };
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;
2399
+ const move = (n, parent, why) => {
2400
+ moves.push({ id: n.id, from: n.parent, to: parent, why });
2401
+ n.parent = parent;
2147
2402
  };
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++;
2403
+ if (beforeFlat) {
2404
+ const paths = /* @__PURE__ */ new Map();
2405
+ const ensure = (p, isFile = false) => {
2406
+ const key = `${isFile ? "f" : "d"}:${p}`;
2407
+ const found = paths.get(key);
2408
+ if (found)
2409
+ return found;
2410
+ const slash = p.lastIndexOf("/");
2411
+ const parent = slash > 0 ? ensure(p.slice(0, slash)).id : null;
2412
+ const n = add(p.slice(slash + 1) || p, isFile ? "file" : "folder", parent, isFile ? "file" : "folder");
2413
+ paths.set(key, n);
2414
+ return n;
2415
+ };
2416
+ for (const n of [...input]) {
2417
+ const raw = typeof n.data.source_file === "string" ? n.data.source_file : n.id.includes("/") ? n.id.split("#")[0] : null;
2418
+ if (raw && raw.includes("/"))
2419
+ move(byId.get(n.id), ensure(raw, true).id, "explicit source path");
2202
2420
  }
2203
2421
  }
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;
2422
+ const roots = nodes.filter((n) => !n.parent);
2423
+ if (roots.length > 1) {
2424
+ const root = add(opts.title?.trim() || "Overview", "overview", null, "root");
2425
+ for (const n of roots)
2426
+ move(n, root.id, "one root");
2427
+ }
2428
+ const analysis = analyzeShape(nodes);
2429
+ const suggestions = [];
2430
+ for (const b of analysis.branches) {
2431
+ if (b.score < 0.2 || !b.closest || b.children.length < 3)
2256
2432
  continue;
2433
+ const seen = /* @__PURE__ */ new Set();
2434
+ const ordered = b.children.map((id) => byId.get(id)).sort((a2, b2) => (a2.order ?? a2.seq ?? 0) - (b2.order ?? b2.seq ?? 0));
2435
+ for (const seed of b.pairs.slice(0, 6)) {
2436
+ const members = [seed.a, seed.b];
2437
+ for (const id of b.children) {
2438
+ if (!members.includes(id) && members.every((m) => analysis.distance(m, id) <= seed.distance + 0.12)) members.push(id);
2439
+ }
2440
+ if (members.length === b.children.length) continue;
2441
+ const key = [...members].sort().join("\0");
2442
+ if (seen.has(key)) continue;
2443
+ seen.add(key);
2444
+ let within = 0, outside = Infinity;
2445
+ for (const m of members) for (const id of b.children) {
2446
+ const d = analysis.distance(m, id);
2447
+ if (members.includes(id)) within = Math.max(within, d);
2448
+ else outside = Math.min(outside, d);
2449
+ }
2450
+ if (outside - within < 0.15) continue;
2451
+ const indices = ordered.map((n, i) => members.includes(n.id) ? i : -1).filter((i) => i >= 0);
2452
+ if (ordered.every((n) => n.order !== void 0) && Math.max(...indices) - Math.min(...indices) + 1 !== members.length) continue;
2453
+ suggestions.push({
2454
+ parent: b.parent,
2455
+ members: ordered.filter((n) => members.includes(n.id)).map((n) => n.id),
2456
+ within: +within.toFixed(6),
2457
+ outside: +outside.toFixed(6),
2458
+ cost: { created: 1, moved: members.length },
2459
+ reason: "This sibling set is structurally closer within than to every outsider. Inspect the named nodes in tree; group only if their meanings belong together."
2460
+ });
2257
2461
  }
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) => {
2462
+ }
2463
+ if (opts.group) {
2464
+ const picked = opts.group.map((id) => byId.get(id));
2465
+ if (picked.length < 2 || picked.some((n) => !n) || new Set(opts.group).size !== picked.length)
2466
+ throw new Error("--group needs two or more distinct existing sibling ids");
2467
+ const members = picked, parent = members[0].parent;
2468
+ if (!parent || members.some((n) => n.parent !== parent))
2469
+ throw new Error("--group members must have the same parent");
2470
+ const siblings = nodes.filter((n) => n.parent === parent).sort((a2, b) => (a2.order ?? a2.seq ?? 0) - (b.order ?? b.seq ?? 0));
2471
+ if (members.length === siblings.length)
2472
+ throw new Error("grouping every sibling adds no distinction");
2473
+ const numbered = siblings.every((n) => n.order !== void 0);
2474
+ const indices = siblings.map((n, i) => opts.group.includes(n.id) ? i : -1).filter((i) => i >= 0);
2475
+ if (numbered && Math.max(...indices) - Math.min(...indices) + 1 !== members.length)
2476
+ throw new Error("ordered group members must be consecutive");
2477
+ const label = siblings.filter((n) => opts.group.includes(n.id)).map((n) => n.label || n.id).join(" & ");
2478
+ const group = add(label, "group", parent);
2479
+ if (numbered)
2480
+ group.order = Math.min(...members.map((n) => n.order));
2481
+ for (const n of members)
2482
+ move(n, group.id, "explicit --group selection");
2483
+ }
2484
+ const children = /* @__PURE__ */ new Map();
2485
+ for (const n of nodes)
2486
+ if (n.parent) {
2487
+ const xs = children.get(n.parent) ?? [];
2488
+ xs.push(n);
2489
+ children.set(n.parent, xs);
2490
+ }
2491
+ for (const kids of children.values()) {
2492
+ const values = kids.filter((n) => n.order !== void 0).map((n) => n.order);
2493
+ if (!values.length)
2494
+ continue;
2495
+ if (values.length === kids.length && new Set(values).size === values.length && values.every((n) => Number.isFinite(n) && n > 0))
2496
+ continue;
2497
+ kids.sort((a2, b) => (a2.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || (a2.seq ?? 0) - (b.seq ?? 0));
2498
+ kids.forEach((n, i) => {
2499
+ if (n.order !== i + 1)
2500
+ orders.push({ id: n.id, from: n.order ?? null, to: i + 1 });
2260
2501
  n.order = i + 1;
2261
2502
  });
2262
2503
  }
2504
+ const after = analyzeShape(nodes).peak;
2505
+ return {
2506
+ nodes,
2507
+ edges,
2508
+ moves,
2509
+ created,
2510
+ removed: [],
2511
+ wraps: created.filter((n) => n.kind === "group").map((n) => n.id),
2512
+ before,
2513
+ after,
2514
+ beforeFlat,
2515
+ ladder: [],
2516
+ orders,
2517
+ suggestions,
2518
+ note: "Structure pressure is not correctness. No original node or relation was removed. Group suggestions require --group; lower pressure after grouping is not proof of improvement."
2519
+ };
2263
2520
  }
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");
2521
+ function planText(r, title, inputPath = "<path>") {
2522
+ const lines = [`${title}: structure pressure ${r.before.toFixed(3)} \u2192 ${r.after.toFixed(3)}`, r.note ?? "", `created ${r.created.length}; moved ${r.moves.length}; renumbered ${r.orders.length}; removed 0`];
2523
+ for (const m of r.moves.slice(0, 12))
2524
+ lines.push(` ${m.id}: ${m.from ?? "(root)"} \u2192 ${m.to} (${m.why})`);
2525
+ for (const s of r.suggestions)
2526
+ lines.push(`suggest group ${s.members.join(",")} under ${s.parent}: within ${s.within.toFixed(3)}, outside ${s.outside.toFixed(3)}; cost +1 node, ${s.members.length} moves.
2527
+ inspect with tree; apply with glassbrain restructure ${inputPath} --group ${s.members.join(",")}`);
2528
+ return lines.filter(Boolean).join("\n");
2529
+ }
2530
+ function planNodesOf(model) {
2531
+ return model.nodes.map((n, seq) => ({
2532
+ id: n.id,
2533
+ label: n.label,
2534
+ kind: n.kind,
2535
+ parent: n.parent ?? null,
2536
+ 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,
2537
+ seq,
2538
+ data: n.data ?? {}
2539
+ }));
2540
+ }
2541
+ function graphOf(plan, name, edges) {
2542
+ return {
2543
+ name,
2544
+ nodes: plan.nodes.map((p) => {
2545
+ const { parent: _p, order: _o, layer: _layer, ...rest } = p.data ?? {};
2546
+ return {
2547
+ ...rest,
2548
+ id: p.id,
2549
+ label: p.label,
2550
+ ...p.kind ? { kind: p.kind } : {},
2551
+ parent: encodeParent(p.parent, p.order)
2552
+ };
2553
+ }),
2554
+ edges
2555
+ };
2295
2556
  }
2296
2557
 
2297
2558
  // 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
2559
+ var HELP = (schema) => `glassbrain: open, diff and lint a knowledge graph, written as plain JSON.
2305
2560
 
2306
2561
  [ DATA ]
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 } ],
2562
+ JSON with two arrays, \`nodes\` and \`edges\`. The parent structure helps readability.
2563
+ { "nodes": [
2564
+ { "id": "start", "label": "Start", "kind": "folder","parent": null }, // the root: parent is null
2565
+ { "id": "login", "label": "Login", "kind": "file", "parent": "start@1", // first child
2566
+ "description": "Checks the password, then opens a session.", // markdown
2567
+ "owner": "auth" }, // any other field: kept, shown
2568
+ { "id": "db", "label": "DB", "kind": "file", "parent": "start@2" } ], // second child
2319
2569
  "edges": [
2320
- { "source": "src/login.ts", "target": "src/db.ts", "kind": "uses" } ] }
2321
-
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.
2570
+ { "source": "login", "target": "db", "kind": "uses" } ] }
2325
2571
 
2326
- ORDER a numbered list, or no list at all
2327
- The children of one parent either all carry \`order\` or none does, and no two
2328
- share a number \u2014 a list is numbered, or it is a set. Values are floats, so 3.5
2329
- inserts between 3 and 4. The layout reads them clockwise from the top.
2330
- A root whose children are numbered opens the layer view: one floor per child.
2331
- There is no layer field. Nothing to configure: write order, see floors.
2332
-
2333
- SHAPE how a graph reads (validate measures each)
2334
- 2\u20135 children per node; more than 10 is a wall (wide-node)
2335
- children of one parent the same depth; 1.00 is perfect (uneven-branches)
2336
- every kind used 5+ times, at most 8 node kinds (prefer-fewer-kinds)
2337
- describe the leaves; under half described is noted (low-coverage)
2338
- kind is optional; without it every node is drawn the same gray
2339
- kind is optional; without it every node is drawn the same gray
2572
+ GUIDELINES
2573
+ * \`parent\` is required on EVERY node: null for the only root, otherwise "<id>@<order>".
2574
+ * \`@order\` sorts siblings: use distinct positive numbers; decimals are allowed.
2575
+ * Use \`@-1\` only to force an unordered group; all siblings must then use @-1.
2576
+ * Parent structure helps readability. Prefer fewer than 5 children; keep natural collections. Consider deeper grouping if crowded.
2577
+ * Keep kinds few and consistent (around 8 or fewer).
2578
+ * Keep depth and detail meaningful. Lint flags structural imbalance as \`bad-structure\`.
2579
+ * Put supporting details in descriptions. Extra fields are kept and shown.
2340
2580
 
2341
2581
  Full schema: ${schema}
2342
2582
 
2343
2583
  [ STRUCTURE ]
2344
- A folder is a graph. Passes are optional; one numbered folder each.
2584
+ * For most cases, one graph is enough. Just write one, unless the task calls for more. *
2585
+
2586
+ But you can keep multiple ones. Use them for staged workflows, diffs, or version control.
2587
+ One folder per pass; folder names set the order. For example:
2345
2588
 
2346
2589
  kg/
2347
2590
  \u251C\u2500\u2500 _profile.json colors, shared by every pass (see [ APPEARANCE ])
2348
2591
  \u251C\u2500\u2500 1-skeleton/graph.json a graph (see [ DATA ])
2349
2592
  \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
2593
+ \u2514\u2500\u2500 3-linked/graph.json then lint, and diff against the pass before
2351
2594
 
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.
2595
+ Inside a pass, JSON at any depth merges by id; split by area only when a file gets too big to write.
2355
2596
 
2356
2597
  [ APPEARANCE ]
2357
- kg/_profile.json, shared by every pass. Everything in it is optional.
2598
+ kg/_profile.json, shared by every pass, also when opening a pass file directly.
2599
+ A local pass profile overrides it; an exported bundle carries its own profile.
2358
2600
 
2359
- COLORS one entry per kind you use; unlisted kinds stay neutral.
2601
+ COLORS one entry per kind you use. A kind without an entry is drawn as skeleton \u2014
2602
+ every uncoloured kind looks the same, so lint reports it as an error.
2360
2603
  { "nodePalette": { "file": "#6366f1", "folder": "#94a3b8" },
2361
2604
  "edgePalette": { "uses": "#2563eb" } }
2362
- Colors closer than 10 in Lab distance read as one kind (validate notes it).
2605
+ Colors closer than 10 in Lab distance read as one kind (lint notes it).
2363
2606
 
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.
2607
+ VIEW set { "appearance": { "defaultLayers": true } } to open in layers.
2608
+ Only sets the opening state; use the page switches to change it.
2368
2609
 
2369
2610
  Full schema: ${schema.replace("graph.schema", "profile.schema")}
2370
2611
 
2371
2612
  [ COMMANDS ]
2372
- Always validate before handing over; a page is only written for a graph with no errors.
2613
+ * Always lint before handing over; view refuses graphs with errors. *
2373
2614
 
2374
2615
  glassbrain <path> write one html page, print its path (passes play as steps)
2375
2616
  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.
2617
+ glassbrain lint <path> Lint errors, warnings, info; exit 1 on errors.
2618
+ Always lint before handing over.
2619
+ glassbrain tree <path> log the containment tree as text
2620
+ glassbrain restructure <path> preserve content; repair containment and order, suggest groups;
2621
+ write graph.json and _profile.json in a new folder
2382
2622
  glassbrain diff <old> <new> only what changed between two graphs
2383
2623
  glassbrain diff <git-ref> <path> the same graph at an earlier commit (default HEAD)
2384
2624
  glassbrain convert <path> [out-dir] write any supported format as glassbrain JSON
@@ -2386,22 +2626,14 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
2386
2626
  <path> is a file, a folder, or <git-ref>:<path> (HEAD~1:kg/graph.json). Graphify,
2387
2627
  Understand-Anything, memory.jsonl and markdown folders are read as-is.
2388
2628
 
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.
2398
2629
 
2399
2630
  [ OPTIONS ]
2400
- --json machine-readable output (validate, tree, diff, restructure)
2401
- --strict warnings fail too (validate, view)
2631
+ --json machine-readable output (lint, tree, diff, restructure)
2632
+ --strict warnings fail too (lint, view)
2402
2633
  --depth <n> tree: levels to expand (default 3)
2403
2634
  --path <id> tree: one node, its ancestors and its subtree
2404
2635
  --orphans tree: only nodes with no parent
2636
+ --group <a,b> restructure: explicitly group selected siblings
2405
2637
  --dry-run restructure: print the plan, write nothing
2406
2638
  --out <file.html> write the page here instead of a temp file (view, diff)
2407
2639
  --open / --no-open open the browser or not (diff opens only in a terminal)
@@ -2411,9 +2643,10 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
2411
2643
  --format <id> force a format: native, graphify, understand-anything, memory, obsidian
2412
2644
  -h, --help / -v, --version this help / the version
2413
2645
  `;
2414
- var VALUED = /* @__PURE__ */ new Set(["out", "format", "ignore", "depth", "path"]);
2646
+ var VALUED = /* @__PURE__ */ new Set(["out", "format", "ignore", "depth", "path", "group"]);
2415
2647
  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"];
2648
+ var COMMANDS = ["view", "diff", "lint", "convert", "tree", "restructure"];
2649
+ var ALIASES = { validate: "lint", "re-structure": "restructure" };
2417
2650
  function parseArgs(argv) {
2418
2651
  const pos = [];
2419
2652
  const flags = {};
@@ -2437,7 +2670,8 @@ function parseArgs(argv) {
2437
2670
  } else if (a2.startsWith("-") && a2 !== "-") fail(`unknown option ${a2} (see glassbrain --help)`);
2438
2671
  else pos.push(a2);
2439
2672
  }
2440
- const cmd = COMMANDS.includes(pos[0]) ? pos.shift() : "view";
2673
+ const name = Object.hasOwn(ALIASES, pos[0]) ? ALIASES[pos[0]] : pos[0];
2674
+ const cmd = COMMANDS.includes(name) ? (pos.shift(), name) : "view";
2441
2675
  if (cmd === "view" && pos.length > 1 && !fs2.existsSync(pos[0]) && /^[a-z]+$/.test(pos[0])) fail(`unknown command ${pos[0]} (commands: ${COMMANDS.join(", ")})`);
2442
2676
  return { cmd, pos, flags };
2443
2677
  }
@@ -2497,18 +2731,20 @@ function notes(l, models) {
2497
2731
  });
2498
2732
  }
2499
2733
  var summaryOf = (l, m) => `${l.title}: ${l.versions.length > 1 ? `${l.versions.length} versions, latest ` : ""}${count(m.nodes.length, "node")}, ${count(m.edges.length, "edge")}${l.format !== "native" ? ` (read as ${l.format})` : ""}`;
2734
+ var shellArg = (s) => "'" + s.replace(/'/g, `'"'"'`) + "'";
2735
+ var findingsAt = (l, input) => lint(l).map((f) => ({ ...f, ...f.fix ? { fix: f.fix.replaceAll("<path>", shellArg(input)) } : {} }));
2500
2736
  function view(a2) {
2501
2737
  if (a2.pos.length !== 1) fail("view needs exactly one <path>");
2502
2738
  const l = load(a2.pos[0], { format: a2.flags.format });
2503
2739
  const models = nodesOf(l);
2504
2740
  notes(l, models);
2505
- const found = validate(l);
2741
+ const found = findingsAt(l, a2.pos[0]);
2506
2742
  const n = tally(found);
2507
2743
  if (n.error || a2.flags.strict && n.warn) {
2508
2744
  console.log(summaryOf(l, models[models.length - 1]));
2509
2745
  printFindings(found);
2510
2746
  console.log(`
2511
- ${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \u2014 page not written. Fix them, then validate again.`);
2747
+ ${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \u2014 page not written. Fix them, then lint again.`);
2512
2748
  process.exitCode = 1;
2513
2749
  return;
2514
2750
  }
@@ -2517,7 +2753,7 @@ ${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \u2014 page not writ
2517
2753
  console.log(file);
2518
2754
  if (n.warn) {
2519
2755
  printFindings(found.filter((f) => f.level === "warn"));
2520
- console.log(`${count(n.warn, "warning")} (not blocking; \`glassbrain validate\` has the details)`);
2756
+ console.log(`${count(n.warn, "warning")} (not blocking; \`glassbrain lint\` has the details)`);
2521
2757
  }
2522
2758
  if (a2.flags.open !== false) openFile(file);
2523
2759
  }
@@ -2571,10 +2807,10 @@ ${file}`);
2571
2807
  if (file && wantOpen) openFile(file);
2572
2808
  if (a2.flags["exit-code"] && changed) process.exitCode = 1;
2573
2809
  }
2574
- function runValidate(a2) {
2575
- if (a2.pos.length !== 1) fail("validate needs exactly one <path>");
2810
+ function runLint(a2) {
2811
+ if (a2.pos.length !== 1) fail("lint needs exactly one <path>");
2576
2812
  const l = load(a2.pos[0], { format: a2.flags.format });
2577
- const found = validate(l);
2813
+ const found = findingsAt(l, a2.pos[0]);
2578
2814
  const models = nodesOf(l);
2579
2815
  const latest = models[models.length - 1];
2580
2816
  const n = tally(found);
@@ -2596,8 +2832,8 @@ function runValidate(a2) {
2596
2832
  if (found.length) console.log("");
2597
2833
  printFindings(found);
2598
2834
  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`);
2835
+ 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 structure pressure ${structure.shape.peak.toFixed(3)} \xB7 ${structure.shape.assessed} assessed / ${structure.shape.unassessed} unassessed`);
2836
+ console.log(`tree: glassbrain tree ${shellArg(a2.pos[0])} --depth=3`);
2601
2837
  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` : ""}
2602
2838
  `);
2603
2839
  }
@@ -2627,19 +2863,14 @@ function runTree(a2) {
2627
2863
  function runRestructure(a2) {
2628
2864
  if (a2.pos.length !== 1) fail("restructure needs exactly one <path>");
2629
2865
  const l = load(a2.pos[0], { format: a2.flags.format });
2866
+ const blockers = lint(l).filter((f) => f.code === "duplicate-id" || f.code === "dangling-edge");
2867
+ if (blockers.length) fail(`repair identity/relation errors before restructure: ${blockers.map((f) => f.message).join("; ")}`, 1);
2630
2868
  const models = nodesOf(l);
2631
2869
  notes(l, models);
2632
2870
  const latest = models[models.length - 1];
2871
+ if (latest.errors.length) fail("repair parse errors before restructure", 1);
2633
2872
  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
- }));
2873
+ const nodes = planNodesOf(latest);
2643
2874
  const edges = phys.edges.map((e) => ({
2644
2875
  source: String(e.source),
2645
2876
  target: String(e.target),
@@ -2648,48 +2879,60 @@ function runRestructure(a2) {
2648
2879
  ...typeof e.weight === "number" ? { weight: e.weight } : {},
2649
2880
  data: e
2650
2881
  }));
2651
- const plan = restructure(nodes, edges);
2882
+ const ownName = (() => {
2883
+ if (l.raw.length !== 1 || l.raw[0].files.length !== 1) return null;
2884
+ try {
2885
+ const d = JSON.parse(l.raw[0].files[0].text);
2886
+ const n = typeof d.name === "string" ? d.name : typeof d.title === "string" ? d.title : null;
2887
+ return n?.trim() || null;
2888
+ } catch {
2889
+ return null;
2890
+ }
2891
+ })();
2892
+ const absIn = path2.resolve(a2.pos[0]);
2893
+ const isDir = fs2.existsSync(absIn) && fs2.statSync(absIn).isDirectory();
2894
+ const base2 = l.title.replace(/\.json$/i, "").split("/").pop() || "Overview";
2895
+ const fallback = !isDir && /^(graph|data|index|nodes|kg)$/i.test(base2) ? path2.basename(path2.dirname(absIn)) : base2;
2896
+ const plan = restructure(nodes, edges, { title: ownName ?? fallback, group: typeof a2.flags.group === "string" ? a2.flags.group.split(",") : void 0 });
2652
2897
  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));
2898
+ console.log(JSON.stringify({ before: plan.before, beforeFlat: plan.beforeFlat, after: plan.after, moves: plan.moves, wraps: plan.wraps, created: plan.created, removed: plan.removed, ladder: plan.ladder, suggestions: plan.suggestions, orders: plan.orders, note: plan.note }, null, 1));
2654
2899
  if (a2.flags["dry-run"]) return;
2655
2900
  } else {
2656
- console.log(planText(plan, l.title));
2901
+ console.log(planText(plan, l.title, shellArg(a2.pos[0])));
2657
2902
  if (a2.flags["dry-run"]) {
2658
2903
  console.log("\n(dry run: nothing written. Drop --dry-run to write a new pass.)");
2659
2904
  return;
2660
2905
  }
2661
2906
  }
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 };
2907
+ const graph = graphOf(plan, l.title, phys.edges);
2674
2908
  const abs = path2.resolve(a2.pos[0]);
2675
2909
  const dir = fs2.existsSync(abs) && fs2.statSync(abs).isDirectory() ? abs : path2.dirname(abs);
2676
2910
  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)}
2911
+ const palette = {};
2912
+ const known = { folder: "#94a3b8", file: "#64748b", overview: "#a855f7", group: "#a855f7" };
2913
+ const wheel = ["#6366f1", "#f59e0b", "#10b981", "#ef4444", "#8b5cf6", "#06b6d4"];
2914
+ let wi = 0;
2915
+ for (const k of new Set(plan.nodes.map((n) => n.kind))) {
2916
+ if (k) palette[k] = known[k] ?? wheel[wi++ % wheel.length];
2917
+ }
2918
+ const srcProfile = l.profile ?? {};
2919
+ const outProfile = {
2920
+ ...srcProfile,
2921
+ nodePalette: { ...palette, ...srcProfile.nodePalette ?? {} }
2922
+ };
2923
+ const passDir = l.versions.length > 1 || passes.length ? path2.join(dir, `${(passes.length ? Math.max(...passes) : 0) + 1}-restructured`) : path2.join(dir, `${path2.basename(abs, ".json") || "graph"}.restructured`);
2924
+ if (fs2.existsSync(path2.join(passDir, "graph.json"))) fail(`output already exists: ${passDir}; use a fresh input location or review the existing pass`);
2925
+ fs2.mkdirSync(passDir, { recursive: true });
2926
+ fs2.writeFileSync(path2.join(passDir, "_profile.json"), `${JSON.stringify(outProfile, null, 1)}
2683
2927
  `);
2684
- file = path2.join(passDir, "graph.json");
2685
- } else {
2686
- file = path2.join(dir, `${path2.basename(abs, ".json") || "graph"}.restructured.json`);
2687
- }
2928
+ const file = path2.join(passDir, "graph.json");
2688
2929
  fs2.writeFileSync(file, `${JSON.stringify(graph, null, 1)}
2689
2930
  `);
2690
- console.log(`
2931
+ if (!a2.flags.json) {
2932
+ console.log(`
2691
2933
  wrote ${file}`);
2692
- console.log(`next: glassbrain diff ${a2.pos[0]} ${file}`);
2934
+ console.log(`next: glassbrain diff ${a2.pos[0]} ${file}`);
2935
+ }
2693
2936
  }
2694
2937
  function runConvert(a2) {
2695
2938
  if (a2.pos.length < 1 || a2.pos.length > 2) fail("convert needs <path> [out-dir]");
@@ -2726,7 +2969,7 @@ if (a.flags.version) {
2726
2969
  process.stdout.write(HELP(path2.join(here, "../../schema/graph.schema.json")));
2727
2970
  } else {
2728
2971
  try {
2729
- ({ view, diff: runDiff, validate: runValidate, convert: runConvert, tree: runTree, restructure: runRestructure })[a.cmd](a);
2972
+ ({ view, diff: runDiff, lint: runLint, convert: runConvert, tree: runTree, restructure: runRestructure })[a.cmd](a);
2730
2973
  } catch (e) {
2731
2974
  fail(e.message, 2);
2732
2975
  }