glassbrain 0.2.0-alpha.3 → 0.2.0-alpha.5

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,8 +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
- // `parent` is always written, `null` for a root: dropping it (it was `undefined`) made every export invalid in 0.2.
136
- nodes: model.nodes.map((n) => clean2({ ...n.data, id: n.id, label: n.label, kind: n.kind, parent: n.parent ?? null, order: n.order })),
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
+ }),
137
164
  edges: model.edges.map((e) => clean2({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }))
138
165
  };
139
166
  }
@@ -741,7 +768,7 @@ function walk(root) {
741
768
  if (out.length >= MAX_FILES) throw new Error(`More than ${MAX_FILES} data files under ${root} \u2014 point at a smaller folder`);
742
769
  const p = path.join(dir, e.name);
743
770
  if (e.isDirectory()) {
744
- 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;
745
772
  go(p);
746
773
  } else if (DATA.test(e.name)) {
747
774
  out.push({ path: path.relative(root, p).split(path.sep).join("/"), text: fs.readFileSync(p, "utf8") });
@@ -789,9 +816,13 @@ function mergeProfile(base2, over) {
789
816
  var natural = (a2, b) => a2.localeCompare(b, void 0, { numeric: true });
790
817
  function load(spec, opts = {}) {
791
818
  const tree2 = readSpec(spec, opts.cwd);
792
- if (!tree2.isDir) {
793
- const beside = path.join(path.dirname(path.resolve(opts.cwd ?? process.cwd(), spec)), "_profile.json");
794
- if (fs.existsSync(beside)) tree2.files.push({ path: "_profile.json", text: fs.readFileSync(beside, "utf8") });
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") });
795
826
  }
796
827
  const metaErrors = [];
797
828
  const meta = (name) => {
@@ -805,7 +836,7 @@ function load(spec, opts = {}) {
805
836
  }
806
837
  };
807
838
  const bundled = () => {
808
- if (tree2.isDir || tree2.files.length !== 1) return null;
839
+ if (tree2.isDir) return null;
809
840
  try {
810
841
  const d = JSON.parse(tree2.files[0].text);
811
842
  return d && typeof d === "object" && d.profile && typeof d.profile === "object" ? d.profile : null;
@@ -813,8 +844,8 @@ function load(spec, opts = {}) {
813
844
  return null;
814
845
  }
815
846
  };
816
- const explicit = meta("_profile.json") ?? bundled();
817
- const data = tree2.files.filter((f) => !META.has(f.path));
847
+ const explicit = bundled() ?? meta("_profile.json");
848
+ const data = tree2.files.filter((f) => !META.has(path.posix.basename(f.path)));
818
849
  const isJson = (f) => /\.json$/i.test(f.path);
819
850
  const dirs = [...new Set(data.filter((f) => f.path.includes("/")).map((f) => f.path.split("/")[0]))].sort(natural);
820
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)));
@@ -1025,7 +1056,6 @@ function diffModels(before, after, opts = {}) {
1025
1056
  }
1026
1057
 
1027
1058
  // src/layers.ts
1028
- var MAX_DERIVED_LAYERS = 8;
1029
1059
  var EMPTY = { layers: [], layerOf: /* @__PURE__ */ new Map() };
1030
1060
  function orderedChildren(children, id) {
1031
1061
  const kids = children.get(id) ?? [];
@@ -1061,7 +1091,7 @@ function deriveLayers(model, colors = [], force = false) {
1061
1091
  } else if (force && roots.length > 1) {
1062
1092
  ordered = roots;
1063
1093
  }
1064
- if (!ordered || ordered.length < 2 || ordered.length > MAX_DERIVED_LAYERS) return EMPTY;
1094
+ if (!ordered || ordered.length < 2) return EMPTY;
1065
1095
  const layers = ordered.map((n, i) => ({
1066
1096
  id: n.id,
1067
1097
  label: n.label || n.id,
@@ -1086,7 +1116,7 @@ var graph_schema_default = {
1086
1116
  $schema: "https://json-schema.org/draft/2020-12/schema",
1087
1117
  $id: "https://unpkg.com/glassbrain/schema/graph.schema.json",
1088
1118
  title: "glassbrain graph",
1089
- description: "One file of a glassbrain knowledge graph. A graph is nodes plus edges; structure comes from `parent` (containment), not from edges. Every node carries `parent`: a node id, or null for the root. Several files in one folder are merged into one graph (same id = same node). Unknown fields are kept and shown in the detail panel.",
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.',
1090
1120
  type: "object",
1091
1121
  anyOf: [{ required: ["nodes"] }, { required: ["edges"] }],
1092
1122
  properties: {
@@ -1106,12 +1136,11 @@ var graph_schema_default = {
1106
1136
  type: "object",
1107
1137
  required: ["id", "parent"],
1108
1138
  properties: {
1109
- id: { type: ["string", "number"], description: "Stable identity. Keep it the same across versions: that is how a diff knows it is the same thing." },
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)." },
1110
1140
  label: { type: "string", description: "Display name. Falls back to `name`, then `id`." },
1111
1141
  name: { type: "string", description: "Alias of `label`." },
1112
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." },
1113
- parent: { type: ["string", "null"], description: "Id of the node this one sits inside; null for the root. Required: the only source of structure, and the layout, the layers and the outline are all built from it." },
1114
- order: { type: "number", exclusiveMinimum: 0, description: "Position among its siblings (1, 2, 3\u2026; 3.5 inserts between 3 and 4). Either every child of a parent has one or none does, and no two siblings share one." },
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.' },
1115
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." },
1116
1145
  description: { type: "string", description: "Markdown shown in the detail panel. `[text](node:<id>)` links jump to another node." }
1117
1146
  },
@@ -1286,7 +1315,8 @@ var KNOWN = /* @__PURE__ */ new Set([
1286
1315
  "$ref",
1287
1316
  "minimum",
1288
1317
  "maximum",
1289
- "exclusiveMinimum"
1318
+ "exclusiveMinimum",
1319
+ "pattern"
1290
1320
  ]);
1291
1321
  var typeOf = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v === "number" ? Number.isInteger(v) ? "integer" : "number" : typeof v;
1292
1322
  var fits = (v, t) => {
@@ -1306,6 +1336,9 @@ function checkSchema(root, value, limit = 50) {
1306
1336
  return;
1307
1337
  }
1308
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
+ }
1309
1342
  if (s.anyOf && !s.anyOf.some((alt) => {
1310
1343
  const e = [];
1311
1344
  walk2(alt, v, path3, e);
@@ -1335,18 +1368,234 @@ function checkSchema(root, value, limit = 50) {
1335
1368
  return out;
1336
1369
  }
1337
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
+
1338
1588
  // cli/checks.ts
1339
- var ISOMORPHISM_TAU = 0.85;
1340
1589
  var WIDE_INFO = 5;
1341
1590
  var WIDE_WARN = 10;
1342
1591
  var MAX_NAMES = 4;
1343
1592
  var MIN_SAMPLE = 10;
1344
1593
  var names = (xs) => `${xs.slice(0, MAX_NAMES).join(", ")}${xs.length > MAX_NAMES ? ` and ${xs.length - MAX_NAMES} more` : ""}`;
1345
1594
  var misplacedField = {
1346
- code: "misplaced-field",
1595
+ code: "schema",
1347
1596
  level: "error",
1348
1597
  run: ({ model }) => {
1349
- const reserved = ["id", "label", "kind", "parent", "order", "description"];
1598
+ const reserved = ["id", "label", "kind", "parent", "description"];
1350
1599
  const out = [];
1351
1600
  for (const n of model.nodes) {
1352
1601
  const nested = n.data?.data;
@@ -1365,32 +1614,32 @@ var misplacedField = {
1365
1614
  }
1366
1615
  };
1367
1616
  var layerField = {
1368
- code: "layer-field",
1617
+ code: "schema",
1369
1618
  level: "error",
1370
1619
  run: ({ model }) => model.nodes.filter((n) => n.data && typeof n.data === "object" && "layer" in n.data).map((n) => ({
1371
1620
  node: n.id,
1372
- message: `"${n.id}" still carries "layer": layers are not written any more, they are derived from "order"`,
1373
- fix: `delete the field. To make the graph read as floors, give one node's children "order" instead:
1374
- - { "id": "${n.id}", "parent": "\u2026", "layer": "${n.layer}" }
1375
- + { "id": "${n.id}", "parent": "\u2026", "order": 2 }`
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" }`
1376
1625
  }))
1377
1626
  };
1378
1627
  var unknownParent = {
1379
- code: "unknown-parent",
1628
+ code: "parent-error",
1380
1629
  level: "error",
1381
- 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) => ({
1382
1631
  node: n.id,
1383
1632
  message: `"${n.id}" sits inside "${n.parent}", which does not exist`,
1384
- fix: `point it at a node that exists (one of: ${[...index2.keys()].slice(0, 3).map((id) => `"${id}"`).join(", ")}), or add "${n.parent}":
1385
- - "parent": "${n.parent}"
1386
- + "parent": "${[...index2.keys()][0] ?? "EXISTING_ID"}"
1387
- ("parent": null also works, but it makes another top-level tree, which validate warns about.)`
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.)`
1388
1637
  }))
1389
1638
  };
1390
1639
  var parentCycle = {
1391
- code: "parent-cycle",
1640
+ code: "parent-error",
1392
1641
  level: "error",
1393
- run: ({ model, index: index2 }) => {
1642
+ run: ({ model, index }) => {
1394
1643
  const out = [];
1395
1644
  const done = /* @__PURE__ */ new Set();
1396
1645
  for (const start of model.nodes) {
@@ -1407,23 +1656,31 @@ var parentCycle = {
1407
1656
  node: cur,
1408
1657
  message: `parent cycle: ${[...loop, cur].join(" \u2192 ")}`,
1409
1658
  fix: `a node cannot sit inside itself. Pick the one that should be the top of the loop and give it "parent": null:
1410
- - { "id": "${loop[0]}", "parent": "${cur}" }
1659
+ - { "id": "${loop[0]}", "parent": "${cur}@-1" }
1411
1660
  + { "id": "${loop[0]}", "parent": null }`
1412
1661
  });
1413
1662
  break;
1414
1663
  }
1415
1664
  at.set(cur, path3.length);
1416
1665
  path3.push(cur);
1417
- const parent = index2.get(cur)?.parent;
1418
- cur = parent && index2.has(parent) ? parent : void 0;
1666
+ const parent = index.get(cur)?.parent;
1667
+ cur = parent && index.has(parent) ? parent : void 0;
1419
1668
  }
1420
1669
  for (const id of path3) done.add(id);
1421
1670
  }
1422
1671
  return out;
1423
1672
  }
1424
1673
  };
1674
+ var reservedContains = {
1675
+ code: "parent-error",
1676
+ level: "error",
1677
+ run: ({ model }) => model.edges.some((e) => e.kind === "contains") ? [{
1678
+ message: 'edge kind "contains" is reserved for the parent structure',
1679
+ fix: "express containment with the child node's parent field and remove the redundant edge. If this is another relationship, give its kind a distinct name and update edgePalette."
1680
+ }] : []
1681
+ };
1425
1682
  var orderMixed = {
1426
- code: "order-mixed",
1683
+ code: "order-error",
1427
1684
  level: "error",
1428
1685
  run: ({ children }) => {
1429
1686
  const out = [];
@@ -1434,17 +1691,17 @@ var orderMixed = {
1434
1691
  const next = Math.max(0, ...kids.map((k) => typeof k.order === "number" ? k.order : 0)) + 1;
1435
1692
  out.push({
1436
1693
  node: parent,
1437
- message: `${withOrder} of ${kids.length} children of "${parent}" have "order"; a numbered list numbers every item`,
1438
- fix: `give the rest an order, or take them all away (then the order is whatever the layout finds):
1439
- ${missing.map((k, i) => ` - { "id": "${k.id}", "parent": "${parent}" }
1440
- + { "id": "${k.id}", "parent": "${parent}", "order": ${next + i} }`).join("\n")}`
1694
+ message: `${withOrder} of ${kids.length} children of "${parent}" are numbered; a sibling set is numbered or explicitly unordered ("@-1")`,
1695
+ fix: `give the rest an order, or mark them all unordered with "@-1":
1696
+ ${missing.map((k, i) => ` - { "id": "${k.id}", "parent": "${parent}@-1" }
1697
+ + { "id": "${k.id}", "parent": "${parent}@${next + i}" }`).join("\n")}`
1441
1698
  });
1442
1699
  }
1443
1700
  return out;
1444
1701
  }
1445
1702
  };
1446
1703
  var orderDuplicate = {
1447
- code: "order-duplicate",
1704
+ code: "order-error",
1448
1705
  level: "error",
1449
1706
  run: ({ children }) => {
1450
1707
  const out = [];
@@ -1461,8 +1718,8 @@ var orderDuplicate = {
1461
1718
  node: parent,
1462
1719
  message: `"${parent}" has ${same.length} children at order ${value} (${names(same.map((n) => n.id))}); two items cannot share a place`,
1463
1720
  fix: `spread them. Fractions are allowed, so nothing else has to move:
1464
- ${same.slice(1).map((k, i) => ` - { "id": "${k.id}", "order": ${value} }
1465
- + { "id": "${k.id}", "order": ${value + (i + 1) / 10} }`).join("\n")}`
1721
+ ${same.slice(1).map((k, i) => ` - { "id": "${k.id}", "parent": "${parent}@${value}" }
1722
+ + { "id": "${k.id}", "parent": "${parent}@${value + (i + 1) / 10}" }`).join("\n")}`
1466
1723
  });
1467
1724
  }
1468
1725
  }
@@ -1470,28 +1727,28 @@ ${same.slice(1).map((k, i) => ` - { "id": "${k.id}", "order": ${value} }
1470
1727
  }
1471
1728
  };
1472
1729
  var conflictingDefinition = {
1473
- code: "conflicting-definition",
1730
+ code: "duplicate-id",
1474
1731
  level: "error",
1475
- run: ({ model, index: index2, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1732
+ run: ({ model, index, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1476
1733
  node: id,
1477
- message: `"${id}" is defined differently in ${names(index2.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`,
1734
+ message: `"${id}" is defined differently in ${names(index.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`,
1478
1735
  fix: `one id is one thing. Either make the copies identical, or give one a new id and point its edges at that:
1479
- ${names(index2.get(id)?.origins ?? [])} \u2014 keep one definition of "${id}", or rename the other to "${id}-2" and update every edge that meant it.`
1736
+ ${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.`
1480
1737
  }))
1481
1738
  };
1482
1739
  var danglingEdge = {
1483
1740
  code: "dangling-edge",
1484
1741
  level: "error",
1485
- run: ({ model, index: index2, labelOf }) => {
1742
+ run: ({ model, index, labelOf }) => {
1486
1743
  const out = [];
1487
1744
  for (const e of model.edges) {
1488
- const missing = [!index2.has(e.source) && e.source, !index2.has(e.target) && e.target].filter(Boolean).join(" / ");
1745
+ const missing = [!index.has(e.source) && e.source, !index.has(e.target) && e.target].filter(Boolean).join(" / ");
1489
1746
  if (!missing) continue;
1490
1747
  out.push({
1491
1748
  message: `edge ${e.source} \u2192 ${e.target}${e.kind ? ` (${e.kind})` : ""} points at the missing node ${missing}`,
1492
1749
  fix: `an edge can only join nodes that exist. Add the node, or repoint the edge:
1493
1750
  - { "source": "${e.source}", "target": "${e.target}" }
1494
- + { "source": "${index2.has(e.source) ? e.source : labelOf(e.target) || e.source}", "target": "${index2.has(e.target) ? e.target : "EXISTING_ID"}" }`
1751
+ + { "source": "${index.has(e.source) ? e.source : labelOf(e.target) || e.source}", "target": "${index.has(e.target) ? e.target : "EXISTING_ID"}" }`
1495
1752
  });
1496
1753
  }
1497
1754
  return out;
@@ -1519,88 +1776,17 @@ var duplicateEdge = {
1519
1776
  return out;
1520
1777
  }
1521
1778
  };
1522
- var multipleRoots = {
1523
- code: "multiple-roots",
1524
- level: "warn",
1525
- run: ({ model }) => {
1526
- const roots = model.nodes.filter((n) => n.parent == null);
1527
- if (roots.length < 2) return [];
1528
- return [{
1529
- message: `${roots.length} top-level nodes (${names(roots.map((n) => n.label || n.id))}); it reads as ${roots.length} separate trees, not one`,
1530
- fix: `one file, one tree: add a root and hang them under it. A root is a real node, so give it a label:
1531
- + { "id": "root", "label": "${model.nodes.find((n) => !n.parent)?.label ?? "Overview"}", "kind": "overview", "parent": null }
1532
- ${roots.slice(0, 3).map((n, i) => `- { "id": "${n.id}", "parent": null }
1533
- + { "id": "${n.id}", "parent": "root", "order": ${i + 1} }`).join("\n ")}
1534
- (ordered children of one root also become the layer view.) Or split the file in two, one tree each.`
1535
- }];
1536
- }
1537
- };
1538
- var noHierarchy = {
1539
- code: "no-hierarchy",
1540
- level: "warn",
1541
- run: ({ model }) => {
1542
- if (!model.nodes.length || model.nodes.some((n) => n.parent)) return [];
1543
- return [{
1544
- message: `${model.nodes.length} nodes and no parent anywhere: flat, so there is no outline to read`,
1545
- fix: `give every node a parent (or null for the one root). If the ids carry the folders, grouping by prefix is enough:
1546
- - { "id": "flask/app.py", "parent": null }
1547
- + { "id": "flask/app.py", "parent": "flask" }
1548
- or run: glassbrain restructure <path>`
1549
- }];
1550
- }
1551
- };
1552
- function isomorphism(model, children, heightOf) {
1553
- let logSum = 0;
1554
- let parents = 0;
1555
- const uneven = [];
1556
- for (const [id, kids] of children) {
1557
- if (kids.length < 2) continue;
1558
- const count2 = /* @__PURE__ */ new Map();
1559
- for (const k of kids) {
1560
- const h = heightOf(k.id);
1561
- count2.set(h, (count2.get(h) ?? 0) + 1);
1562
- }
1563
- const q = Math.max(...count2.values()) / kids.length;
1564
- logSum += Math.log(q);
1565
- parents++;
1566
- if (q < 1) uneven.push({ id, q, kids: kids.length });
1567
- }
1568
- uneven.sort((a2, b) => a2.q - b.q || b.kids - a2.kids);
1569
- return { score: parents ? Math.exp(logSum / parents) : 1, parents, uneven };
1570
- }
1571
- function unevenFix(ctx, worst) {
1572
- const kids = [...ctx.children.get(worst.id) ?? []].sort((a2, b) => ctx.heightOf(a2.id) - ctx.heightOf(b.id));
1573
- const short = kids[0];
1574
- const deep = kids[kids.length - 1];
1575
- const m = ctx.heightOf(deep.id);
1576
- const shallow = ctx.heightOf(short.id);
1577
- const leaf = ctx.children.get(short.id)?.length ? "" : " (it is a leaf: it needs a child, or the deep branch needs one less level)";
1578
- return [
1579
- `same parent, same depth. Under "${ctx.labelOf(worst.id)}" (${worst.kids} children, ${Math.round(worst.q * 100)}% are ${m} deep):`,
1580
- ` \u2717 ${worst.id}`,
1581
- ` \u251C\u2500 ${short.id} ${shallow} deep${leaf}`,
1582
- ` \u2514\u2500 ${deep.id} ${m} deep`,
1583
- ` \u2713 both ${m} deep: give ${short.id} one more real level, or lift ${deep.id}'s children up one level.`,
1584
- ` Do not invent an empty group just to pad the depth \u2014 move the branch instead.`,
1585
- `or let the tool do all of them: glassbrain restructure <path>`
1586
- ].join("\n");
1587
- }
1588
- var unevenBranches = {
1589
- code: "uneven-branches",
1590
- level: "warn",
1591
- run: (ctx) => {
1592
- const { score: score2, parents, uneven } = isomorphism(ctx.model, ctx.children, ctx.heightOf);
1593
- if (!parents || score2 >= 1) return [];
1594
- const worst = uneven[0];
1595
- const level = score2 < ISOMORPHISM_TAU && uneven.length >= 2 ? "warn" : "info";
1596
- const line = `isomorphism ${score2.toFixed(2)} of 1.00${level === "warn" ? ` (threshold ${ISOMORPHISM_TAU})` : ""}: ${uneven.length} of ${parents} parents ${uneven.length === 1 ? "has" : "have"} branches of different depth`;
1597
- return [{
1598
- level,
1599
- message: worst ? `${line}; worst: ${ctx.labelOf(worst.id)} (${worst.kids} children)` : line,
1600
- fix: worst ? unevenFix(ctx, worst) : void 0,
1601
- ...worst ? { node: worst.id } : {}
1602
- }];
1603
- }
1779
+ var unevenKinds = {
1780
+ code: "bad-structure",
1781
+ level: "info",
1782
+ run: ({ model }) => analyzeShape(model.nodes).branches.filter((b) => b.score >= 0.2).sort((a2, b) => b.score - a2.score).map((b) => ({
1783
+ node: b.parent,
1784
+ level: b.children.length > WIDE_WARN ? "error" : b.score >= 0.4 ? "warn" : "info",
1785
+ message: `"${b.parent}": ${b.children.length} children with uneven structural relationships (structure pressure ${b.score.toFixed(3)}, dispersion ${b.dispersion.toFixed(3)}, effective template support ${b.support.toFixed(2)})`,
1786
+ fix: `inspect this branch: glassbrain tree <path> --path "${b.parent}"
1787
+ closest compared pair: ${b.closest?.a} / ${b.closest?.b} (distance ${b.closest?.distance}). Differences can be intentional.
1788
+ glassbrain restructure <path> --dry-run --json shows grouping suggestions; no content is deleted.`
1789
+ }))
1604
1790
  };
1605
1791
  var wideNode = {
1606
1792
  code: "wide-node",
@@ -1616,14 +1802,10 @@ var wideNode = {
1616
1802
  out.push({
1617
1803
  level,
1618
1804
  node: id,
1619
- message: `"${labelOf(id)}" holds ${what}; ${isAnchor ? "2\u20134 layers read best" : `more than ${WIDE_INFO} wants another level of grouping`}`,
1620
- fix: isAnchor ? `fewer floors, or group the extras under one of them:
1621
- ${kids.slice(4, 6).map((k, i) => `- { "id": "${k.id}", "parent": "${id}", "order": ${5 + i} }
1622
- + { "id": "more", "parent": "${id}", "order": 5 }
1623
- + { "id": "${k.id}", "parent": "more", "order": ${i + 1} }`).join("\n ")}` : `add one grouping node between:
1624
- - { "id": "${kids[0].id}", "parent": "${id}" }
1625
- + { "id": "${id}/group", "parent": "${id}" }
1626
- + { "id": "${kids[0].id}", "parent": "${id}/group" }`
1805
+ message: `"${labelOf(id)}" holds ${what}; ${isAnchor ? "review whether each floor is a major section" : "review whether this is one natural collection"}`,
1806
+ fix: `inspect membership and depth: glassbrain tree <path> --path "${id}"
1807
+ glassbrain restructure <path> --dry-run shows candidate groups and their ids.
1808
+ Prefer fewer than 5 children per group; this is guidance, not a quota. Keep a natural collection together; add a named group only when it explains membership.${isAnchor ? "\n Each numbered root child becomes a floor. Use @-1 for an unordered collection; reserve numbered root children for major sections." : ""}`
1627
1809
  });
1628
1810
  }
1629
1811
  return out;
@@ -1643,25 +1825,24 @@ var uncoloredKind = {
1643
1825
  fix: `add one colour per kind to _profile.json (one entry per kind, not per node):
1644
1826
  { "nodePalette": ${JSON.stringify(palette)} }
1645
1827
  ${missing.length > shown.length ? ` \u2026 and ${missing.length - shown.length} more; every kind in the data needs an entry.
1646
- ` : ""} Colors that land closer than 10 in Lab distance read as one kind (validate notes it).`
1828
+ ` : ""} Colors that land closer than 10 in Lab distance read as one kind (lint notes it).`
1647
1829
  }];
1648
1830
  }
1649
1831
  };
1650
1832
  var singleKind = {
1651
1833
  code: "single-kind",
1652
- level: "warn",
1834
+ level: "info",
1653
1835
  run: ({ model }) => {
1654
1836
  const used = new Set(model.nodes.map((n) => n.kind).filter(Boolean));
1655
1837
  if (used.size !== 1 || model.nodes.length < MIN_SAMPLE) return [];
1656
1838
  return [{
1657
- message: `every node has kind "${[...used][0]}"; a single kind tells the reader nothing about what differs`,
1658
- fix: `split it by what the node is for. The palette only shows differences it has a colour for:
1659
- { "nodePalette": { "${[...used][0]}": "#6366f1", "concept": "#f59e0b", "person": "#10b981" } }`
1839
+ message: `every node has kind "${[...used][0]}"; check whether this is one natural category`,
1840
+ fix: `keep one kind for genuinely similar things. Introduce another only when it expresses a useful distinction; counts alone do not justify it.`
1660
1841
  }];
1661
1842
  }
1662
1843
  };
1663
- var preferFewerKinds = {
1664
- code: "prefer-fewer-kinds",
1844
+ var kindNote = {
1845
+ code: "kind-note",
1665
1846
  level: "info",
1666
1847
  run: ({ model }) => {
1667
1848
  const out = [];
@@ -1671,33 +1852,25 @@ var preferFewerKinds = {
1671
1852
  const average = total / kinds;
1672
1853
  if (kinds > 10 || average < 5) {
1673
1854
  out.push({
1674
- message: `${space} kinds: ${kinds} (${average.toFixed(1)} per kind); 8 kinds or 5 per kind reads better`,
1675
- fix: `merge the look-alikes into one kind and keep the difference in the label or the description. The palette only has room for a handful.`
1855
+ message: `${space} kinds: ${kinds} (${average.toFixed(1)} per kind); around 8 colors and repeated kinds are easier to scan, but counts are advisory`,
1856
+ fix: `inspect whether kinds express distinct meanings. Preserve precise relation kinds and meaningful rare categories; merge only synonyms.`
1676
1857
  });
1677
1858
  }
1678
1859
  };
1679
- spread("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1680
- spread("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1681
- return out;
1682
- }
1683
- };
1684
- var loneKind = {
1685
- code: "lone-kind",
1686
- level: "info",
1687
- run: ({ model }) => {
1688
- const out = [];
1689
1860
  const lone = (space, counts, total) => {
1690
1861
  if (total < MIN_SAMPLE) return;
1691
1862
  const once = [...counts].filter(([, c]) => c === 1).map(([k]) => k);
1692
- if (once.length) out.push({ message: `${once.length} ${space} kind${once.length > 1 ? "s" : ""} used once: ${names(once)}`, fix: `fold ${once.length > 1 ? "them" : "it"} into a kind that is already used, or use ${once.length > 1 ? "them" : "it"} more.` });
1863
+ if (once.length) out.push({ message: `${once.length} ${space} kind${once.length > 1 ? "s" : ""} used once: ${names(once)}`, fix: `keep a rare kind when its meaning is distinct; do not add instances merely to meet a count.` });
1693
1864
  };
1865
+ spread("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1866
+ spread("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1694
1867
  lone("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1695
1868
  lone("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1696
1869
  return out;
1697
1870
  }
1698
1871
  };
1699
1872
  var lowCoverage = {
1700
- code: "low-coverage",
1873
+ code: "coverage-note",
1701
1874
  level: "info",
1702
1875
  run: ({ model, children }) => {
1703
1876
  const leaves = model.nodes.filter((n) => !children.has(n.id));
@@ -1711,8 +1884,8 @@ var lowCoverage = {
1711
1884
  }];
1712
1885
  }
1713
1886
  };
1714
- var colorsContrast = {
1715
- code: "colors-contrast",
1887
+ var colorNote = {
1888
+ code: "color-note",
1716
1889
  level: "info",
1717
1890
  run: ({ profile }) => {
1718
1891
  const colors = Object.entries(profile.nodePalette).map(([kind, hex]) => ({ kind, lab: hexLab(hex) }));
@@ -1734,26 +1907,41 @@ var colorsContrast = {
1734
1907
  }];
1735
1908
  }
1736
1909
  };
1910
+ var orderHint = {
1911
+ code: "order-hint",
1912
+ level: "info",
1913
+ run: ({ model, children }) => {
1914
+ const roots = model.nodes.filter((n) => !n.parent);
1915
+ if (roots.length !== 1) return [];
1916
+ const root = roots[0];
1917
+ const kids = children.get(root.id) ?? [];
1918
+ if (kids.length < 2 || kids.some((k) => typeof k.order === "number")) return [];
1919
+ return [{
1920
+ node: root.id,
1921
+ message: `"${root.label || root.id}" has ${kids.length} unordered children; it opens flat, with optional floors`,
1922
+ fix: `keep @-1 for a collection. Number the root children only when they are major sections worth separate floors; view can also preview floors without changing the data.`
1923
+ }];
1924
+ }
1925
+ };
1737
1926
  var rules = [
1738
1927
  misplacedField,
1739
1928
  layerField,
1740
1929
  unknownParent,
1741
1930
  parentCycle,
1931
+ reservedContains,
1742
1932
  orderMixed,
1743
1933
  orderDuplicate,
1744
1934
  conflictingDefinition,
1745
1935
  danglingEdge,
1746
1936
  duplicateEdge,
1747
- multipleRoots,
1748
- noHierarchy,
1749
- unevenBranches,
1937
+ unevenKinds,
1750
1938
  wideNode,
1751
1939
  uncoloredKind,
1752
1940
  singleKind,
1753
- preferFewerKinds,
1754
- loneKind,
1941
+ kindNote,
1942
+ colorNote,
1755
1943
  lowCoverage,
1756
- colorsContrast
1944
+ orderHint
1757
1945
  ];
1758
1946
  function checkGraph(model, profile, opts) {
1759
1947
  const children = /* @__PURE__ */ new Map();
@@ -1763,17 +1951,6 @@ function checkGraph(model, profile, opts) {
1763
1951
  if (arr) arr.push(n);
1764
1952
  else children.set(n.parent, [n]);
1765
1953
  }
1766
- const heightMemo = /* @__PURE__ */ new Map();
1767
- const heightOf = (id, seen = /* @__PURE__ */ new Set()) => {
1768
- const hit = heightMemo.get(id);
1769
- if (hit != null) return hit;
1770
- if (seen.has(id)) return 0;
1771
- seen.add(id);
1772
- let h = 0;
1773
- for (const k of children.get(id) ?? []) h = Math.max(h, heightOf(k.id, seen) + 1);
1774
- heightMemo.set(id, h);
1775
- return h;
1776
- };
1777
1954
  const ctx = {
1778
1955
  model,
1779
1956
  profile,
@@ -1782,7 +1959,6 @@ function checkGraph(model, profile, opts) {
1782
1959
  children,
1783
1960
  layers: deriveLayers(model),
1784
1961
  labelOf: (id) => model.index.get(id)?.label ?? id,
1785
- heightOf: (id) => heightOf(id),
1786
1962
  sameFileDuplicates: opts.sameFileDuplicates ?? /* @__PURE__ */ new Set()
1787
1963
  };
1788
1964
  const out = rules.flatMap((rule) => rule.run(ctx).map((issue) => ({
@@ -1796,12 +1972,12 @@ function checkGraph(model, profile, opts) {
1796
1972
  return out;
1797
1973
  }
1798
1974
  function structureOf(model) {
1799
- const index2 = indexModel(model);
1975
+ const index = indexModel(model);
1800
1976
  let depth = 0;
1801
1977
  let parented = 0;
1802
1978
  for (const n of model.nodes) {
1803
1979
  if (n.parent && model.index.has(n.parent)) parented++;
1804
- depth = Math.max(depth, index2.depthOf(n.id));
1980
+ depth = Math.max(depth, index.depthOf(n.id));
1805
1981
  }
1806
1982
  const children = /* @__PURE__ */ new Map();
1807
1983
  for (const n of model.nodes) {
@@ -1809,18 +1985,8 @@ function structureOf(model) {
1809
1985
  const arr = children.get(n.parent);
1810
1986
  arr ? arr.push(n) : children.set(n.parent, [n]);
1811
1987
  }
1812
- const heightMemo = /* @__PURE__ */ new Map();
1813
- const heightOf = (id, seen = /* @__PURE__ */ new Set()) => {
1814
- const hit = heightMemo.get(id);
1815
- if (hit != null) return hit;
1816
- if (seen.has(id)) return 0;
1817
- seen.add(id);
1818
- let h = 0;
1819
- for (const k of children.get(id) ?? []) h = Math.max(h, heightOf(k.id, seen) + 1);
1820
- heightMemo.set(id, h);
1821
- return h;
1822
- };
1823
1988
  const derived = deriveLayers(model);
1989
+ const analysis = analyzeShape(model.nodes);
1824
1990
  return {
1825
1991
  nodes: model.nodes.length,
1826
1992
  edges: model.edges.length,
@@ -1828,7 +1994,8 @@ function structureOf(model) {
1828
1994
  depth,
1829
1995
  parented,
1830
1996
  layers: derived.layers.length,
1831
- isomorphism: +isomorphism(model, children, (id) => heightOf(id)).score.toFixed(2),
1997
+ regularity: +(1 - analysis.peak).toFixed(3),
1998
+ shape: { peak: analysis.peak, assessed: analysis.assessed, unassessed: analysis.unassessed, branches: analysis.branches },
1832
1999
  ordered: derived.layers.length > 0 || [...children.keys()].some((id) => orderedChildren(children, id) !== null)
1833
2000
  };
1834
2001
  }
@@ -1875,7 +2042,7 @@ function derivedProfile(base2, sources, json, force) {
1875
2042
  }
1876
2043
  var modelOf = (v, profile) => parseSources(v.sources, profile);
1877
2044
  var RANK = { error: 0, warn: 1, info: 2 };
1878
- function validate(loaded) {
2045
+ function lint(loaded) {
1879
2046
  const out = [];
1880
2047
  const profile = profileOf(loaded);
1881
2048
  if (loaded.profile) {
@@ -1883,11 +2050,10 @@ function validate(loaded) {
1883
2050
  const retired = ["layers", "singleRoot"].filter((k) => k in loaded.profile);
1884
2051
  if (retired.length) out.push({
1885
2052
  level: "warn",
1886
- code: "profile-retired",
2053
+ code: "schema",
1887
2054
  where: "_profile.json",
1888
- message: `${retired.map((k) => `"${k}"`).join(" and ")} no longer configure anything: layers are derived from "order"`,
1889
- fix: `delete ${retired.length > 1 ? "them" : "it"} from _profile.json. To open the page with the plane view on, write:
1890
- { "appearance": { "defaultLayers": true } }`
2055
+ message: `${retired.map((k) => `"${k}"`).join(" and ")} no longer configure anything: layers come from the order in "parent"`,
2056
+ fix: `delete ${retired.length > 1 ? "them" : "it"} from _profile.json. The page opens on the floors when the graph has them; write "appearance": { "defaultLayers": false } to open flat.`
1891
2057
  });
1892
2058
  }
1893
2059
  for (const e of loaded.metaErrors) out.push({ level: "error", code: "schema", where: e.file, message: e.message });
@@ -1904,32 +2070,61 @@ function validate(loaded) {
1904
2070
  doc = JSON.parse(f.text);
1905
2071
  } catch (e) {
1906
2072
  notJson.add(f.path);
1907
- out.push({ level: "error", code: "not-json", where: prefix + f.path, message: `not JSON: ${e.message}` });
2073
+ out.push({ level: "error", code: "schema", where: prefix + f.path, message: `not JSON: ${e.message}` });
1908
2074
  continue;
1909
2075
  }
1910
2076
  if (!doc || typeof doc !== "object" || !("nodes" in doc) && !("edges" in doc)) {
1911
- out.push({ level: "warn", code: "not-a-graph", where: prefix + f.path, message: 'not a graph (no "nodes" or "edges"), skipped' });
2077
+ out.push({ level: "warn", code: "schema", where: prefix + f.path, message: 'not a graph (no "nodes" or "edges"), skipped' });
1912
2078
  continue;
1913
2079
  }
1914
2080
  for (const e of checkSchema(graph_schema_default, doc)) out.push({ level: "error", code: "schema", where: prefix + f.path, message: `${e.path}: ${e.message}` });
1915
- const bare = (Array.isArray(doc.nodes) ? doc.nodes : []).filter((n) => !!n && typeof n === "object" && !("parent" in n));
2081
+ const rawNodes = (Array.isArray(doc.nodes) ? doc.nodes : []).filter((n) => !!n && typeof n === "object");
2082
+ const bare = rawNodes.filter((n) => !("parent" in n));
1916
2083
  if (bare.length) out.push({
1917
2084
  level: "error",
1918
- code: "missing-parent",
2085
+ code: "parent-error",
1919
2086
  where: prefix + f.path,
1920
- message: `${bare.length} node${bare.length > 1 ? "s" : ""} without "parent" (${bare.slice(0, 3).map((n) => `"${String(n.id)}"`).join(", ")}${bare.length > 3 ? ` and ${bare.length - 3} more` : ""}); every node has one: an id, or null for the root`,
1921
- fix: `add the field. The top of the tree is null; everything else names its container:
2087
+ message: `${bare.length} node${bare.length > 1 ? "s" : ""} without "parent" (${bare.slice(0, 3).map((n) => `"${String(n.id)}"`).join(", ")}${bare.length > 3 ? ` and ${bare.length - 3} more` : ""}); every node has one: null for the root, otherwise "<id>@<order>"`,
2088
+ fix: `add the field. The top of the tree is null; everything else names its container and its place:
1922
2089
  - { "id": "${String(bare[0].id)}" }
1923
2090
  + { "id": "${String(bare[0].id)}", "parent": null }
1924
2091
  - { "id": "child" }
1925
- + { "id": "child", "parent": "${String(bare[0].id)}" }`
2092
+ + { "id": "child", "parent": "${String(bare[0].id)}@-1" }`
2093
+ });
2094
+ const malformed = rawNodes.filter((n) => "parent" in n && typeof n.parent === "string" && !parentParts(n.parent));
2095
+ if (malformed.length) {
2096
+ const sample = malformed[0];
2097
+ const value = String(sample.parent);
2098
+ const at = value.lastIndexOf("@");
2099
+ const id = at > 0 ? value.slice(0, at) : value;
2100
+ out.push({
2101
+ level: "error",
2102
+ code: "parent-error",
2103
+ where: prefix + f.path,
2104
+ message: `${malformed.length} node${malformed.length > 1 ? "s" : ""} with a malformed "parent" (${malformed.slice(0, 3).map((n) => `"${String(n.parent)}"`).join(", ")}${malformed.length > 3 ? ` and ${malformed.length - 3} more` : ""}); it is "<id>@<order>"`,
2105
+ fix: `write the container's id, then "@", then a positive number (-1 = explicitly unordered):
2106
+ - { "id": "${String(sample.id)}", "parent": ${JSON.stringify(value)} }
2107
+ + { "id": "${String(sample.id)}", "parent": "${id}@-1" }`
2108
+ });
2109
+ }
2110
+ const roots = rawNodes.filter((n) => n.parent === null);
2111
+ if (roots.length > 1) out.push({
2112
+ level: "error",
2113
+ code: "parent-error",
2114
+ where: prefix + f.path,
2115
+ message: `${roots.length} nodes with "parent": null (${roots.slice(0, 3).map((n) => `"${String(n.id)}"`).join(", ")}${roots.length > 3 ? ` and ${roots.length - 3} more` : ""}); a file has one root`,
2116
+ fix: `one file is one tree. Add a root and hang the others under it (numbered children open the floors):
2117
+ + { "id": "overview", "label": "Overview", "parent": null }
2118
+ ${roots.slice(0, 3).map((n, i) => `- { "id": "${String(n.id)}", "parent": null }
2119
+ + { "id": "${String(n.id)}", "parent": "overview@${i + 1}" }`).join("\n ")}
2120
+ or split the file: one file per tree.`
1926
2121
  });
1927
2122
  const seen = /* @__PURE__ */ new Map();
1928
2123
  for (const id of idsIn(doc)) seen.set(id, (seen.get(id) ?? 0) + 1);
1929
2124
  for (const [id, count2] of seen) {
1930
2125
  if (count2 < 2) continue;
1931
2126
  sameFileDuplicates.add(id);
1932
- 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` });
2127
+ out.push({ level: "error", code: "duplicate-id", where: prefix + f.path, message: `id "${id}" appears ${count2} times in this file; the first one is kept` });
1933
2128
  }
1934
2129
  }
1935
2130
  }
@@ -1937,10 +2132,17 @@ function validate(loaded) {
1937
2132
  const model = modelOf(v, profile);
1938
2133
  for (const e of model.errors) if (!notJson.has(e.origin)) out.push({ level: "error", code: "schema", where: prefix + e.origin, message: e.message });
1939
2134
  if (version === latest) out.push(...checkGraph(model, profile, { where: prefix || loaded.title, sameFileDuplicates }));
1940
- if (!model.nodes.length) out.push({ level: "warn", code: "empty", where: prefix || loaded.title, message: "No nodes found" });
2135
+ if (!model.nodes.length) out.push({ level: "warn", code: "schema", where: prefix || loaded.title, message: "No nodes found" });
1941
2136
  }
1942
2137
  return out.sort((a2, b) => RANK[a2.level] - RANK[b.level]);
1943
2138
  }
2139
+ var ORDER_TAIL = /^(-1|\d+(\.\d+)?)$/;
2140
+ function parentParts(raw) {
2141
+ const at = raw.lastIndexOf("@");
2142
+ if (at < 1) return null;
2143
+ const order = raw.slice(at + 1);
2144
+ return ORDER_TAIL.test(order) && (order === "-1" || Number.isFinite(Number(order)) && Number(order) > 0) ? { id: raw.slice(0, at), order } : null;
2145
+ }
1944
2146
  function idsIn(doc) {
1945
2147
  const nodes = doc.nodes;
1946
2148
  if (!Array.isArray(nodes)) return [];
@@ -2015,6 +2217,7 @@ var MAX_LINES = 200;
2015
2217
  var MAX_EDGES = 6;
2016
2218
  function tree(model, opts) {
2017
2219
  const derived = deriveLayers(model);
2220
+ const evidence = new Map(analyzeShape(model.nodes).branches.map((b) => [b.parent, b]));
2018
2221
  const layerOf = (n) => derived.layerOf.get(n.id);
2019
2222
  const labelOf = (id) => model.index.get(id)?.label ?? id;
2020
2223
  const depth = Math.max(1, opts.depth ?? 3);
@@ -2072,6 +2275,8 @@ function tree(model, opts) {
2072
2275
  const tall = height.get(node.id) ?? 0;
2073
2276
  const edges = collapsed ? [] : outgoing.get(node.id) ?? [];
2074
2277
  const bits = [];
2278
+ const assessment = evidence.get(node.id);
2279
+ if (assessment) bits.push(`${list.length} ${list.length === 1 ? "child" : "children"} \xB7 ${assessment.assessed ? `pressure ${assessment.score.toFixed(3)}` : "unassessed"}`);
2075
2280
  if (inside > 0) bits.push(one(inside, "node"));
2076
2281
  if (collapsed && tall > 0) bits.push(`${tall} deep`);
2077
2282
  if (edges.length) bits.push(edgeText(edges));
@@ -2087,7 +2292,7 @@ function tree(model, opts) {
2087
2292
  deep: tall,
2088
2293
  collapsed,
2089
2294
  edges,
2090
- text: `${prefix}${connector}${orderTag}${label}${bits.length ? ` ${bits.join(" \xB7 ")}` : ""}`
2295
+ text: `${prefix}${connector}${orderTag}${label}${labelOf(node.id) !== node.id ? ` [${node.id}]` : ""}${bits.length ? ` ${bits.join(" \xB7 ")}` : ""}`
2091
2296
  });
2092
2297
  if (!canExpand) return;
2093
2298
  const shown = list.slice(0, perNode);
@@ -2110,7 +2315,7 @@ function tree(model, opts) {
2110
2315
  }
2111
2316
  };
2112
2317
  const structure = structureOf(model);
2113
- let header = `${opts.title} ${one(structure.nodes, "node")} \xB7 ${one(structure.edges, "edge")} \xB7 ${one(structure.roots, "root")} \xB7 depth ${structure.depth}${structure.layers ? ` \xB7 ${one(structure.layers, "layer")}` : ""} \xB7 isomorphism ${structure.isomorphism.toFixed(2)}`;
2318
+ 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`;
2114
2319
  const roots = model.nodes.filter((n) => !n.parent || broken(n));
2115
2320
  if (opts.path) {
2116
2321
  const start = model.index.get(opts.path);
@@ -2162,307 +2367,267 @@ function treeText(result) {
2162
2367
  }
2163
2368
 
2164
2369
  // cli/restructure.ts
2165
- function index(nodes) {
2370
+ function restructure(input, edges, opts = {}) {
2371
+ const nodes = input.map((n) => ({ ...n, data: { ...n.data } }));
2166
2372
  const byId = new Map(nodes.map((n) => [n.id, n]));
2167
- const children = /* @__PURE__ */ new Map();
2373
+ if (byId.size !== nodes.length)
2374
+ throw new Error("duplicate ids: resolve them before restructure");
2375
+ const done = /* @__PURE__ */ new Set();
2168
2376
  for (const n of nodes) {
2169
- if (!n.parent || !byId.has(n.parent)) {
2170
- n.parent = null;
2171
- continue;
2377
+ const seen = /* @__PURE__ */ new Set();
2378
+ let cur = n;
2379
+ while (cur && !done.has(cur.id)) {
2380
+ if (seen.has(cur.id))
2381
+ throw new Error("parent cycle: repair it before restructure");
2382
+ seen.add(cur.id);
2383
+ if (cur.parent && !byId.has(cur.parent))
2384
+ throw new Error(`unknown parent ${cur.parent}: repair it before restructure`);
2385
+ cur = cur.parent ? byId.get(cur.parent) : void 0;
2172
2386
  }
2173
- const arr = children.get(n.parent);
2174
- arr ? arr.push(n.id) : children.set(n.parent, [n.id]);
2175
- }
2176
- const depth = /* @__PURE__ */ new Map();
2177
- const walk2 = (id, seen) => {
2178
- const hit = depth.get(id);
2179
- if (hit != null) return hit;
2180
- if (seen.has(id)) return 0;
2181
- seen.add(id);
2182
- const p = byId.get(id)?.parent;
2183
- const d = p ? walk2(p, seen) + 1 : 0;
2184
- depth.set(id, d);
2185
- return d;
2186
- };
2187
- for (const n of nodes) walk2(n.id, /* @__PURE__ */ new Set());
2188
- return { byId, children, depth };
2189
- }
2190
- function scoreOf(ctx) {
2191
- const height = /* @__PURE__ */ new Map();
2192
- const h = (id, seen = /* @__PURE__ */ new Set()) => {
2193
- const hit = height.get(id);
2194
- if (hit != null) return hit;
2195
- if (seen.has(id)) return 0;
2196
- seen.add(id);
2197
- let v = 0;
2198
- for (const k of ctx.children.get(id) ?? []) v = Math.max(v, h(k, seen) + 1);
2199
- height.set(id, v);
2200
- return v;
2387
+ for (const id of seen)
2388
+ done.add(id);
2389
+ }
2390
+ for (const e of edges)
2391
+ if (!byId.has(e.source) || !byId.has(e.target))
2392
+ throw new Error("dangling edge: repair endpoints before restructure");
2393
+ const before = analyzeShape(nodes).peak, beforeFlat = !nodes.some((n) => n.parent);
2394
+ const created = [], moves = [], orders = [];
2395
+ const unique = (base2) => {
2396
+ let id = base2, i = 2;
2397
+ while (byId.has(id))
2398
+ id = `${base2}-${i++}`;
2399
+ return id;
2201
2400
  };
2202
- const nodeList = [...ctx.byId.values()];
2203
- const model = { nodes: nodeList, edges: [], errors: [], index: ctx.byId };
2204
- const kids = new Map([...ctx.children].map(([id, ids]) => [id, ids.map((k) => ctx.byId.get(k))]));
2205
- return isomorphism(model, kids, (id) => h(id)).score;
2206
- }
2207
- function adoptFlat(nodes, byId, created, moves) {
2208
- if (nodes.some((n) => n.parent)) return;
2209
- const pathOf = (n) => {
2210
- const sf = n.data.source_file;
2211
- if (typeof sf === "string" && sf.includes("/")) return sf;
2212
- if (n.id.includes("/")) return n.id.split("#")[0];
2213
- return null;
2401
+ const add = (label, kind, parent, base2 = "group") => {
2402
+ const n = { id: unique(base2), label, kind, parent, data: {} };
2403
+ nodes.push(n);
2404
+ byId.set(n.id, n);
2405
+ created.push({ id: n.id, label, kind, parent });
2406
+ return n;
2214
2407
  };
2215
- if (!nodes.some((n) => pathOf(n))) return;
2216
- const dirs = /* @__PURE__ */ new Map();
2217
- const mkdir = (dir) => {
2218
- if (!dir) return null;
2219
- const hit = dirs.get(dir);
2220
- if (hit) return hit;
2221
- const parentDir = dir.includes("/") ? dir.slice(0, dir.lastIndexOf("/")) : "";
2222
- const parent = mkdir(parentDir);
2223
- const id = `dir:${dir}`;
2224
- dirs.set(dir, id);
2225
- created.push({ id, label: dir.slice(dir.lastIndexOf("/") + 1) || dir, kind: "folder", parent });
2226
- byId.set(id, { id, label: dir.slice(dir.lastIndexOf("/") + 1) || dir, kind: "folder", parent, data: {} });
2227
- return id;
2408
+ const move = (n, parent, why) => {
2409
+ moves.push({ id: n.id, from: n.parent, to: parent, why });
2410
+ n.parent = parent;
2228
2411
  };
2229
- for (const n of nodes) {
2230
- const path3 = pathOf(n);
2231
- if (!path3) continue;
2232
- const slash = path3.lastIndexOf("/");
2233
- const dir = slash < 0 ? "" : path3.slice(0, slash);
2234
- const fileId = `file:${path3}`;
2235
- if (!dirs.has(fileId)) {
2236
- const parent = mkdir(dir);
2237
- const fileLabel = path3.slice(slash + 1);
2238
- created.push({ id: fileId, label: fileLabel, kind: "file", parent });
2239
- byId.set(fileId, { id: fileId, label: fileLabel, kind: "file", parent, data: {} });
2240
- dirs.set(fileId, fileId);
2241
- }
2242
- const before = n.parent;
2243
- n.parent = fileId;
2244
- moves.push({ id: n.id, from: before, to: fileId, why: `${path3}` });
2245
- }
2246
- }
2247
- function attachByKind(ctx, wraps, moves) {
2248
- const per = /* @__PURE__ */ new Map();
2249
- for (const n of ctx.byId.values()) {
2250
- if (!n.kind) continue;
2251
- const hist = per.get(n.kind) ?? /* @__PURE__ */ new Map();
2252
- const d = ctx.depth.get(n.id) ?? 0;
2253
- hist.set(d, (hist.get(d) ?? 0) + 1);
2254
- per.set(n.kind, hist);
2255
- }
2256
- const modal = /* @__PURE__ */ new Map();
2257
- for (const [kind, hist] of per) {
2258
- const total = [...hist.values()].reduce((a2, b) => a2 + b, 0);
2259
- let best = 0;
2260
- let bestCount = -1;
2261
- for (const [d, c] of hist) if (c > bestCount || c === bestCount && d < best) {
2262
- best = d;
2263
- bestCount = c;
2264
- }
2265
- if (total >= 3 && bestCount / total >= 0.6) modal.set(kind, best);
2266
- }
2267
- const limit = Math.max(4, Math.floor(ctx.byId.size * 0.2));
2268
- let changes = 0;
2269
- for (const n of [...ctx.byId.values()]) {
2270
- if (changes >= limit) break;
2271
- if (!n.kind || !n.parent) continue;
2272
- const target = modal.get(n.kind);
2273
- if (target == null) continue;
2274
- const here2 = ctx.depth.get(n.id) ?? 0;
2275
- if (here2 === target) continue;
2276
- if (here2 > target) {
2277
- let up = n.parent;
2278
- while (up && (ctx.depth.get(up) ?? 0) > target - 1) up = ctx.byId.get(up)?.parent ?? null;
2279
- if (!up || up === n.parent || (ctx.depth.get(up) ?? 0) !== target - 1) continue;
2280
- moves.push({ id: n.id, from: n.parent, to: up, why: `kind "${n.kind}" sits at depth ${target}` });
2281
- n.parent = up;
2282
- changes++;
2412
+ if (beforeFlat) {
2413
+ const paths = /* @__PURE__ */ new Map();
2414
+ const ensure = (p, isFile = false) => {
2415
+ const key = `${isFile ? "f" : "d"}:${p}`;
2416
+ const found = paths.get(key);
2417
+ if (found)
2418
+ return found;
2419
+ const slash = p.lastIndexOf("/");
2420
+ const parent = slash > 0 ? ensure(p.slice(0, slash)).id : null;
2421
+ const n = add(p.slice(slash + 1) || p, isFile ? "file" : "folder", parent, isFile ? "file" : "folder");
2422
+ paths.set(key, n);
2423
+ return n;
2424
+ };
2425
+ for (const n of [...input]) {
2426
+ const raw = typeof n.data.source_file === "string" ? n.data.source_file : n.id.includes("/") ? n.id.split("#")[0] : null;
2427
+ if (raw && raw.includes("/"))
2428
+ move(byId.get(n.id), ensure(raw, true).id, "explicit source path");
2283
2429
  }
2284
2430
  }
2285
- const rebuilt = index([...ctx.byId.values()]);
2286
- ctx.children = rebuilt.children;
2287
- ctx.depth = rebuilt.depth;
2288
- }
2289
- function ladderOf(ctx) {
2290
- const per = /* @__PURE__ */ new Map();
2291
- for (const n of ctx.byId.values()) {
2292
- if (!n.kind) continue;
2293
- const d = ctx.depth.get(n.id) ?? 0;
2294
- const hist = per.get(n.kind) ?? /* @__PURE__ */ new Map();
2295
- hist.set(d, (hist.get(d) ?? 0) + 1);
2296
- per.set(n.kind, hist);
2297
- }
2298
- return [...per].map(([kind, hist]) => {
2299
- const [depth, count2] = [...hist].sort((a2, b) => b[1] - a2[1] || a2[0] - b[0])[0];
2300
- return { kind, depth, count: count2 };
2301
- }).sort((a2, b) => a2.depth - b.depth || a2.kind.localeCompare(b.kind));
2302
- }
2303
- function singleRoot(ctx, created, moves) {
2304
- const roots = [...ctx.byId.values()].filter((n) => !n.parent);
2305
- if (roots.length < 2) return;
2306
- const levels = /* @__PURE__ */ new Map();
2307
- const tall = (id2, seen = /* @__PURE__ */ new Set()) => {
2308
- const hit = levels.get(id2);
2309
- if (hit != null) return hit;
2310
- if (seen.has(id2)) return 0;
2311
- seen.add(id2);
2312
- let h = 0;
2313
- for (const k of ctx.children.get(id2) ?? []) h = Math.max(h, tall(k, seen) + 1);
2314
- levels.set(id2, h);
2315
- return h;
2316
- };
2317
- const heights = roots.map((r) => tall(r.id));
2318
- if (Math.max(...heights) - Math.min(...heights) > 1) return;
2319
- let id = "root";
2320
- for (let i = 2; ctx.byId.has(id); i++) id = `root-${i}`;
2321
- const root = { id, label: "Overview", kind: "overview", parent: null, seq: -1, data: {} };
2322
- ctx.byId.set(id, root);
2323
- created.push({ id, label: "Overview", kind: "overview", parent: null });
2324
- roots.forEach((n, i) => {
2325
- moves.push({ id: n.id, from: null, to: id, why: "single root" });
2326
- n.parent = id;
2327
- n.order = i + 1;
2328
- });
2329
- const re = index([...ctx.byId.values()]);
2330
- ctx.children = re.children;
2331
- ctx.depth = re.depth;
2332
- }
2333
- function numberSiblings(ctx) {
2334
- for (const [, kids] of ctx.children) {
2335
- if (kids.length < 2) {
2336
- for (const k of kids) delete ctx.byId.get(k).order;
2431
+ const roots = nodes.filter((n) => !n.parent);
2432
+ if (roots.length > 1) {
2433
+ const root = add(opts.title?.trim() || "Overview", "overview", null, "root");
2434
+ for (const n of roots)
2435
+ move(n, root.id, "one root");
2436
+ }
2437
+ const analysis = analyzeShape(nodes);
2438
+ const suggestions = [];
2439
+ for (const b of analysis.branches) {
2440
+ if (b.score < 0.2 || !b.closest || b.children.length < 3)
2337
2441
  continue;
2442
+ const seen = /* @__PURE__ */ new Set();
2443
+ const ordered = b.children.map((id) => byId.get(id)).sort((a2, b2) => (a2.order ?? a2.seq ?? 0) - (b2.order ?? b2.seq ?? 0));
2444
+ for (const seed of b.pairs.slice(0, 6)) {
2445
+ const members = [seed.a, seed.b];
2446
+ for (const id of b.children) {
2447
+ if (!members.includes(id) && members.every((m) => analysis.distance(m, id) <= seed.distance + 0.12)) members.push(id);
2448
+ }
2449
+ if (members.length === b.children.length) continue;
2450
+ const key = [...members].sort().join("\0");
2451
+ if (seen.has(key)) continue;
2452
+ seen.add(key);
2453
+ let within = 0, outside = Infinity;
2454
+ for (const m of members) for (const id of b.children) {
2455
+ const d = analysis.distance(m, id);
2456
+ if (members.includes(id)) within = Math.max(within, d);
2457
+ else outside = Math.min(outside, d);
2458
+ }
2459
+ if (outside - within < 0.15) continue;
2460
+ const indices = ordered.map((n, i) => members.includes(n.id) ? i : -1).filter((i) => i >= 0);
2461
+ if (ordered.every((n) => n.order !== void 0) && Math.max(...indices) - Math.min(...indices) + 1 !== members.length) continue;
2462
+ suggestions.push({
2463
+ parent: b.parent,
2464
+ members: ordered.filter((n) => members.includes(n.id)).map((n) => n.id),
2465
+ within: +within.toFixed(6),
2466
+ outside: +outside.toFixed(6),
2467
+ cost: { created: 1, moved: members.length },
2468
+ 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."
2469
+ });
2470
+ }
2471
+ }
2472
+ if (opts.group) {
2473
+ const picked = opts.group.map((id) => byId.get(id));
2474
+ if (picked.length < 2 || picked.some((n) => !n) || new Set(opts.group).size !== picked.length)
2475
+ throw new Error("--group needs two or more distinct existing sibling ids");
2476
+ const members = picked, parent = members[0].parent;
2477
+ if (!parent || members.some((n) => n.parent !== parent))
2478
+ throw new Error("--group members must have the same parent");
2479
+ const siblings = nodes.filter((n) => n.parent === parent).sort((a2, b) => (a2.order ?? a2.seq ?? 0) - (b.order ?? b.seq ?? 0));
2480
+ if (members.length === siblings.length)
2481
+ throw new Error("grouping every sibling adds no distinction");
2482
+ const numbered = siblings.every((n) => n.order !== void 0);
2483
+ const indices = siblings.map((n, i) => opts.group.includes(n.id) ? i : -1).filter((i) => i >= 0);
2484
+ if (numbered && Math.max(...indices) - Math.min(...indices) + 1 !== members.length)
2485
+ throw new Error("ordered group members must be consecutive");
2486
+ const label = siblings.filter((n) => opts.group.includes(n.id)).map((n) => n.label || n.id).join(" & ");
2487
+ const group = add(label, "group", parent);
2488
+ if (numbered)
2489
+ group.order = Math.min(...members.map((n) => n.order));
2490
+ for (const n of members)
2491
+ move(n, group.id, "explicit --group selection");
2492
+ }
2493
+ const children = /* @__PURE__ */ new Map();
2494
+ for (const n of nodes)
2495
+ if (n.parent) {
2496
+ const xs = children.get(n.parent) ?? [];
2497
+ xs.push(n);
2498
+ children.set(n.parent, xs);
2338
2499
  }
2339
- const list = kids.map((id) => ctx.byId.get(id)).sort((a2, b) => (a2.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || (a2.seq ?? Number.MAX_SAFE_INTEGER) - (b.seq ?? Number.MAX_SAFE_INTEGER) || a2.label.localeCompare(b.label));
2340
- list.forEach((n, i) => {
2500
+ for (const kids of children.values()) {
2501
+ const values = kids.filter((n) => n.order !== void 0).map((n) => n.order);
2502
+ if (!values.length)
2503
+ continue;
2504
+ if (values.length === kids.length && new Set(values).size === values.length && values.every((n) => Number.isFinite(n) && n > 0))
2505
+ continue;
2506
+ kids.sort((a2, b) => (a2.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || (a2.seq ?? 0) - (b.seq ?? 0));
2507
+ kids.forEach((n, i) => {
2508
+ if (n.order !== i + 1)
2509
+ orders.push({ id: n.id, from: n.order ?? null, to: i + 1 });
2341
2510
  n.order = i + 1;
2342
2511
  });
2343
2512
  }
2513
+ const after = analyzeShape(nodes).peak;
2514
+ return {
2515
+ nodes,
2516
+ edges,
2517
+ moves,
2518
+ created,
2519
+ removed: [],
2520
+ wraps: created.filter((n) => n.kind === "group").map((n) => n.id),
2521
+ before,
2522
+ after,
2523
+ beforeFlat,
2524
+ ladder: [],
2525
+ orders,
2526
+ suggestions,
2527
+ 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."
2528
+ };
2344
2529
  }
2345
- function restructure(nodes, edges) {
2346
- const ctx = index(nodes);
2347
- const before = scoreOf(ctx);
2348
- const beforeFlat = !nodes.some((n) => n.parent);
2349
- const created = [];
2350
- const moves = [];
2351
- const wraps = [];
2352
- let note;
2353
- adoptFlat([...ctx.byId.values()], ctx.byId, created, moves);
2354
- if (!edges.length && !nodes.some((n) => n.parent)) note = "no parent anywhere and no path to build one from: give the nodes parents first";
2355
- const re = index([...ctx.byId.values()]);
2356
- ctx.children = re.children;
2357
- ctx.depth = re.depth;
2358
- const inferred = ladderOf(ctx);
2359
- attachByKind(ctx, wraps, moves);
2360
- singleRoot(ctx, created, moves);
2361
- numberSiblings(ctx);
2362
- const after = scoreOf(ctx);
2363
- return { nodes: [...ctx.byId.values()], edges, moves, wraps, created, before, beforeFlat, after, ladder: inferred, note };
2364
- }
2365
- function planText(r, title) {
2366
- const L = [];
2367
- L.push(`${title}: isomorphism ${r.beforeFlat ? "flat" : r.before.toFixed(2)} \u2192 ${r.after.toFixed(2)}`);
2368
- if (r.note) L.push(`note: ${r.note}`);
2369
- if (r.ladder.length) L.push(`kinds \u2192 depth: ${r.ladder.map((l) => `${l.kind} ${l.depth} (${l.count})`).join(" \xB7 ")}`);
2370
- if (r.created.length) L.push(`created ${r.created.length} container${r.created.length > 1 ? "s" : ""} (${r.created.slice(0, 4).map((c) => c.id).join(", ")}${r.created.length > 4 ? " \u2026" : ""})`);
2371
- if (r.moves.length) L.push(`moved ${r.moves.length} node${r.moves.length > 1 ? "s" : ""}${r.wraps.length ? ` (${r.wraps.length} wrapped)` : ""}:`);
2372
- for (const m of r.moves.slice(0, 8)) L.push(` ${m.id}: ${m.from ?? "(top)"} \u2192 ${m.to ?? "(top)"} ${m.why}`);
2373
- if (r.moves.length > 8) L.push(` \u2026 ${r.moves.length - 8} more (--json)`);
2374
- if (!r.moves.length && !r.created.length) L.push("nothing to move: the shape already matches the kinds");
2375
- return L.join("\n");
2530
+ function planText(r, title, inputPath = "<path>") {
2531
+ 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`];
2532
+ for (const m of r.moves.slice(0, 12))
2533
+ lines.push(` ${m.id}: ${m.from ?? "(root)"} \u2192 ${m.to} (${m.why})`);
2534
+ for (const s of r.suggestions)
2535
+ 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.
2536
+ inspect with tree; apply with glassbrain restructure ${inputPath} --group ${s.members.join(",")}`);
2537
+ return lines.filter(Boolean).join("\n");
2538
+ }
2539
+ function planNodesOf(model) {
2540
+ return model.nodes.map((n, seq) => ({
2541
+ id: n.id,
2542
+ label: n.label,
2543
+ kind: n.kind,
2544
+ parent: n.parent ?? null,
2545
+ order: typeof n.order === "number" ? n.order : typeof n.data?.order === "number" && Number.isFinite(n.data.order) && n.data.order > 0 ? n.data.order : void 0,
2546
+ seq,
2547
+ data: n.data ?? {}
2548
+ }));
2549
+ }
2550
+ function graphOf(plan, name, edges) {
2551
+ return {
2552
+ name,
2553
+ nodes: plan.nodes.map((p) => {
2554
+ const { parent: _p, order: _o, layer: _layer, ...rest } = p.data ?? {};
2555
+ return {
2556
+ ...rest,
2557
+ id: p.id,
2558
+ label: p.label,
2559
+ ...p.kind ? { kind: p.kind } : {},
2560
+ parent: encodeParent(p.parent, p.order)
2561
+ };
2562
+ }),
2563
+ edges
2564
+ };
2376
2565
  }
2377
2566
 
2378
2567
  // cli/glassbrain.ts
2379
- var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, written as plain JSON.
2380
-
2381
- [ THE THREE AXES ]
2382
- Different things. Do not use one where another belongs.
2383
- pass a snapshot in time \u2014 one folder per pass (1-skeleton/, 2-filled/)
2384
- parent containment \u2014 what sits inside what; every node has one
2385
- order position among siblings \u2014 turns a set into a numbered list
2568
+ var HELP = (schema) => `glassbrain: open, diff and lint a knowledge graph, written as plain JSON.
2386
2569
 
2387
2570
  [ DATA ]
2388
- Two arrays. The \`//\` notes are not part of the file: strip them and it is valid JSON
2389
- (if validate says \`not JSON\`, a note survived the copy).
2390
-
2391
- { "nodes": [
2392
- { "id": "src", "label": "src", "kind": "folder",
2393
- "parent": null }, // the root: parent is null
2394
- { "id": "src/login.ts", "label": "login.ts", "kind": "file",
2395
- "parent": "src", "order": 1, // inside src, first
2396
- "description": "Checks the password, then opens a session.", // markdown
2397
- "owner": "auth" }, // any other field: kept, shown
2398
- { "id": "src/db.ts", "label": "db.ts", "kind": "file",
2399
- "parent": "src", "order": 2 } ],
2571
+ JSON with two arrays, \`nodes\` and \`edges\`. The parent structure helps readability.
2572
+ { "nodes": [
2573
+ { "id": "start", "label": "Start", "kind": "folder","parent": null }, // the root: parent is null
2574
+ { "id": "login", "label": "Login", "kind": "file", "parent": "start@1", // first child
2575
+ "description": "Checks the password, then opens a session.", // markdown
2576
+ "owner": "auth" }, // any other field: kept, shown
2577
+ { "id": "db", "label": "DB", "kind": "file", "parent": "start@2" } ], // second child
2400
2578
  "edges": [
2401
- { "source": "src/login.ts", "target": "src/db.ts", "kind": "uses" } ] }
2579
+ { "source": "login", "target": "db", "kind": "uses" } ] }
2402
2580
 
2403
- \`parent\` is required on every node: a node id, or null for the root. One root per
2404
- file. It is read only as a top-level field; nested (\`data.parent\`) it is shown and
2405
- nothing else. \`kind\` gives the color; \`description\` is what the panel says.
2406
-
2407
- ORDER a numbered list, or no list at all
2408
- The children of one parent either all carry \`order\` or none does, and no two
2409
- share a number \u2014 a list is numbered, or it is a set. Values are floats, so 3.5
2410
- inserts between 3 and 4. The layout reads them clockwise from the top.
2411
- A root whose children are numbered opens the layer view: one floor per child.
2412
- Without order the layer button stays grey and can still force the floors
2413
- open (document order, view only). There is no layer field.
2414
-
2415
- SHAPE how a graph reads (validate measures each)
2416
- 2\u20135 children per node; more than 10 is a wall (wide-node)
2417
- children of one parent the same depth; 1.00 is perfect (uneven-branches)
2418
- every kind used 5+ times, at most 8 node kinds (prefer-fewer-kinds)
2419
- describe the leaves; under half described is noted (low-coverage)
2420
- kind is optional; without it every node is drawn the same gray
2421
- kind is optional; without it every node is drawn the same gray
2581
+ GUIDELINES
2582
+ * \`parent\` is required on EVERY node: null for the only root, otherwise "<id>@<order>".
2583
+ * \`@order\` sorts siblings: use distinct positive numbers; decimals are allowed.
2584
+ * Use \`@-1\` only to force an unordered group; all siblings must then use @-1.
2585
+ * Parent structure helps readability. Prefer fewer than 5 children; keep natural collections. Consider deeper grouping if crowded.
2586
+ * Keep kinds few and consistent (around 8 or fewer).
2587
+ * Keep depth and detail meaningful. Lint flags structural imbalance as \`bad-structure\`.
2588
+ * Put supporting details in descriptions. Extra fields are kept and shown.
2422
2589
 
2423
2590
  Full schema: ${schema}
2424
2591
 
2425
2592
  [ STRUCTURE ]
2426
- A folder is a graph. Passes are optional; one numbered folder each.
2593
+ * For most cases, one graph is enough. Just write one, unless the task calls for more. *
2594
+
2595
+ But you can keep multiple ones. Use them for staged workflows, diffs, or version control.
2596
+ One folder per pass; folder names set the order. For example:
2427
2597
 
2428
2598
  kg/
2429
2599
  \u251C\u2500\u2500 _profile.json colors, shared by every pass (see [ APPEARANCE ])
2430
2600
  \u251C\u2500\u2500 1-skeleton/graph.json a graph (see [ DATA ])
2431
2601
  \u251C\u2500\u2500 2-filled/graph.json each pass is the whole graph: copy the last, edit the copy
2432
- \u2514\u2500\u2500 3-linked/graph.json then validate, and diff against the pass before
2602
+ \u2514\u2500\u2500 3-linked/graph.json then lint, and diff against the pass before
2433
2603
 
2434
- Files inside one pass merge by id: the same node described twice is one node.
2435
- Two files defining that id differently is an error, not a merge.
2436
- Split by area only when a file gets too big to write.
2604
+ Inside a pass, JSON at any depth merges by id; split by area only when a file gets too big to write.
2437
2605
 
2438
2606
  [ APPEARANCE ]
2439
- kg/_profile.json, shared by every pass. Everything in it is optional.
2607
+ kg/_profile.json, shared by every pass, also when opening a pass file directly.
2608
+ A local pass profile overrides it; an exported bundle carries its own profile.
2440
2609
 
2441
2610
  COLORS one entry per kind you use. A kind without an entry is drawn as skeleton \u2014
2442
- every uncoloured kind looks the same, so validate reports it as an error.
2611
+ every uncoloured kind looks the same, so lint reports it as an error.
2443
2612
  { "nodePalette": { "file": "#6366f1", "folder": "#94a3b8" },
2444
2613
  "edgePalette": { "uses": "#2563eb" } }
2445
- Ten kinds is already a lot; one with no colour is invisible.
2446
- Colors closer than 10 in Lab distance read as one kind (validate notes it).
2614
+ Colors closer than 10 in Lab distance read as one kind (lint notes it).
2447
2615
 
2448
- VIEW only the opening state; the page has the switches.
2449
- { "appearance": { "defaultLayers": true } }
2450
- Open with the 2.5D floors on. Without it the page opens flat and the layer
2451
- control turns them on. A graph with no ordered root has one floor.
2616
+ VIEW set { "appearance": { "defaultLayers": true } } to open in layers.
2617
+ Only sets the opening state; use the page switches to change it.
2452
2618
 
2453
2619
  Full schema: ${schema.replace("graph.schema", "profile.schema")}
2454
2620
 
2455
2621
  [ COMMANDS ]
2456
- Always validate before handing over; a page is only written for a graph with no errors.
2622
+ * Always lint before handing over; view refuses graphs with errors. *
2457
2623
 
2458
2624
  glassbrain <path> write one html page, print its path (passes play as steps)
2459
2625
  glassbrain view <path> the same page, spelled out (a path is required)
2460
- glassbrain validate <path> errors, warnings, info; exit 1 on errors
2461
- glassbrain tree <path> the containment tree as text
2462
- glassbrain restructure <path> raise the shape score: re-hang and renumber; writes a
2463
- new folder with graph.json and _profile.json (a pass,
2464
- or <name>.restructured/ for one file). It colours the
2465
- kinds it invents. --dry-run prints the plan only.
2626
+ glassbrain lint <path> Lint errors, warnings, info; exit 1 on errors.
2627
+ Always lint before handing over.
2628
+ glassbrain tree <path> log the containment tree as text
2629
+ glassbrain restructure <path> preserve content; repair containment and order, suggest groups;
2630
+ write graph.json and _profile.json in a new folder
2466
2631
  glassbrain diff <old> <new> only what changed between two graphs
2467
2632
  glassbrain diff <git-ref> <path> the same graph at an earlier commit (default HEAD)
2468
2633
  glassbrain convert <path> [out-dir] write any supported format as glassbrain JSON
@@ -2470,22 +2635,14 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
2470
2635
  <path> is a file, a folder, or <git-ref>:<path> (HEAD~1:kg/graph.json). Graphify,
2471
2636
  Understand-Anything, memory.jsonl and markdown folders are read as-is.
2472
2637
 
2473
- validate speaks in three levels, and every line carries its repair:
2474
- error broken schema, a missing/unknown parent, a cycle, a duplicate id,
2475
- mixed or duplicate order, an edge to a missing node
2476
- warn discouraged several roots in one file, one relation written twice,
2477
- a node with more than 10 children, branches uneven in two
2478
- or more places (one place is only info)
2479
- info distribution kinds, order notes, empty leaves, color contrast
2480
- exit codes: 0 clean \xB7 1 errors (--strict: warnings too) \xB7 2 usage.
2481
- It always ends with the structure and the tree command for that graph.
2482
2638
 
2483
2639
  [ OPTIONS ]
2484
- --json machine-readable output (validate, tree, diff, restructure)
2485
- --strict warnings fail too (validate, view)
2640
+ --json machine-readable output (lint, tree, diff, restructure)
2641
+ --strict warnings fail too (lint, view)
2486
2642
  --depth <n> tree: levels to expand (default 3)
2487
2643
  --path <id> tree: one node, its ancestors and its subtree
2488
2644
  --orphans tree: only nodes with no parent
2645
+ --group <a,b> restructure: explicitly group selected siblings
2489
2646
  --dry-run restructure: print the plan, write nothing
2490
2647
  --out <file.html> write the page here instead of a temp file (view, diff)
2491
2648
  --open / --no-open open the browser or not (diff opens only in a terminal)
@@ -2495,9 +2652,10 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
2495
2652
  --format <id> force a format: native, graphify, understand-anything, memory, obsidian
2496
2653
  -h, --help / -v, --version this help / the version
2497
2654
  `;
2498
- var VALUED = /* @__PURE__ */ new Set(["out", "format", "ignore", "depth", "path"]);
2655
+ var VALUED = /* @__PURE__ */ new Set(["out", "format", "ignore", "depth", "path", "group"]);
2499
2656
  var SWITCHES = /* @__PURE__ */ new Set(["open", "json", "all", "exit-code", "strict", "help", "version", "orphans", "dry-run"]);
2500
- var COMMANDS = ["view", "diff", "validate", "convert", "tree", "restructure"];
2657
+ var COMMANDS = ["view", "diff", "lint", "convert", "tree", "restructure"];
2658
+ var ALIASES = { validate: "lint", "re-structure": "restructure" };
2501
2659
  function parseArgs(argv) {
2502
2660
  const pos = [];
2503
2661
  const flags = {};
@@ -2521,7 +2679,8 @@ function parseArgs(argv) {
2521
2679
  } else if (a2.startsWith("-") && a2 !== "-") fail(`unknown option ${a2} (see glassbrain --help)`);
2522
2680
  else pos.push(a2);
2523
2681
  }
2524
- const cmd = COMMANDS.includes(pos[0]) ? pos.shift() : "view";
2682
+ const name = Object.hasOwn(ALIASES, pos[0]) ? ALIASES[pos[0]] : pos[0];
2683
+ const cmd = COMMANDS.includes(name) ? (pos.shift(), name) : "view";
2525
2684
  if (cmd === "view" && pos.length > 1 && !fs2.existsSync(pos[0]) && /^[a-z]+$/.test(pos[0])) fail(`unknown command ${pos[0]} (commands: ${COMMANDS.join(", ")})`);
2526
2685
  return { cmd, pos, flags };
2527
2686
  }
@@ -2581,18 +2740,20 @@ function notes(l, models) {
2581
2740
  });
2582
2741
  }
2583
2742
  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})` : ""}`;
2743
+ var shellArg = (s) => "'" + s.replace(/'/g, `'"'"'`) + "'";
2744
+ var findingsAt = (l, input) => lint(l).map((f) => ({ ...f, ...f.fix ? { fix: f.fix.replaceAll("<path>", shellArg(input)) } : {} }));
2584
2745
  function view(a2) {
2585
2746
  if (a2.pos.length !== 1) fail("view needs exactly one <path>");
2586
2747
  const l = load(a2.pos[0], { format: a2.flags.format });
2587
2748
  const models = nodesOf(l);
2588
2749
  notes(l, models);
2589
- const found = validate(l);
2750
+ const found = findingsAt(l, a2.pos[0]);
2590
2751
  const n = tally(found);
2591
2752
  if (n.error || a2.flags.strict && n.warn) {
2592
2753
  console.log(summaryOf(l, models[models.length - 1]));
2593
2754
  printFindings(found);
2594
2755
  console.log(`
2595
- ${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \u2014 page not written. Fix them, then validate again.`);
2756
+ ${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \u2014 page not written. Fix them, then lint again.`);
2596
2757
  process.exitCode = 1;
2597
2758
  return;
2598
2759
  }
@@ -2601,7 +2762,7 @@ ${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \u2014 page not writ
2601
2762
  console.log(file);
2602
2763
  if (n.warn) {
2603
2764
  printFindings(found.filter((f) => f.level === "warn"));
2604
- console.log(`${count(n.warn, "warning")} (not blocking; \`glassbrain validate\` has the details)`);
2765
+ console.log(`${count(n.warn, "warning")} (not blocking; \`glassbrain lint\` has the details)`);
2605
2766
  }
2606
2767
  if (a2.flags.open !== false) openFile(file);
2607
2768
  }
@@ -2655,10 +2816,10 @@ ${file}`);
2655
2816
  if (file && wantOpen) openFile(file);
2656
2817
  if (a2.flags["exit-code"] && changed) process.exitCode = 1;
2657
2818
  }
2658
- function runValidate(a2) {
2659
- if (a2.pos.length !== 1) fail("validate needs exactly one <path>");
2819
+ function runLint(a2) {
2820
+ if (a2.pos.length !== 1) fail("lint needs exactly one <path>");
2660
2821
  const l = load(a2.pos[0], { format: a2.flags.format });
2661
- const found = validate(l);
2822
+ const found = findingsAt(l, a2.pos[0]);
2662
2823
  const models = nodesOf(l);
2663
2824
  const latest = models[models.length - 1];
2664
2825
  const n = tally(found);
@@ -2680,8 +2841,8 @@ function runValidate(a2) {
2680
2841
  if (found.length) console.log("");
2681
2842
  printFindings(found);
2682
2843
  console.log(`${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \xB7 ${count(n.info, "info")}`);
2683
- console.log(`structure: ${count(structure.roots, "root")} \xB7 depth ${structure.depth}${structure.layers ? ` \xB7 ${count(structure.layers, "layer")}` : ""} \xB7 ${structure.parented}/${structure.nodes} parented \xB7 isomorphism ${structure.isomorphism.toFixed(2)}`);
2684
- console.log(`tree: glassbrain tree ${a2.pos[0]} --depth=3`);
2844
+ 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`);
2845
+ console.log(`tree: glassbrain tree ${shellArg(a2.pos[0])} --depth=3`);
2685
2846
  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` : ""}
2686
2847
  `);
2687
2848
  }
@@ -2711,19 +2872,14 @@ function runTree(a2) {
2711
2872
  function runRestructure(a2) {
2712
2873
  if (a2.pos.length !== 1) fail("restructure needs exactly one <path>");
2713
2874
  const l = load(a2.pos[0], { format: a2.flags.format });
2875
+ const blockers = lint(l).filter((f) => f.code === "duplicate-id" || f.code === "dangling-edge");
2876
+ if (blockers.length) fail(`repair identity/relation errors before restructure: ${blockers.map((f) => f.message).join("; ")}`, 1);
2714
2877
  const models = nodesOf(l);
2715
2878
  notes(l, models);
2716
2879
  const latest = models[models.length - 1];
2880
+ if (latest.errors.length) fail("repair parse errors before restructure", 1);
2717
2881
  const phys = toPhysical(latest);
2718
- const nodes = phys.nodes.map((n, seq) => ({
2719
- id: String(n.id),
2720
- label: String(n.label ?? n.id),
2721
- kind: typeof n.kind === "string" ? n.kind : void 0,
2722
- parent: n.parent === void 0 || n.parent === null ? null : String(n.parent),
2723
- order: typeof n.order === "number" ? n.order : void 0,
2724
- seq,
2725
- data: n
2726
- }));
2882
+ const nodes = planNodesOf(latest);
2727
2883
  const edges = phys.edges.map((e) => ({
2728
2884
  source: String(e.source),
2729
2885
  target: String(e.target),
@@ -2732,29 +2888,32 @@ function runRestructure(a2) {
2732
2888
  ...typeof e.weight === "number" ? { weight: e.weight } : {},
2733
2889
  data: e
2734
2890
  }));
2735
- const plan = restructure(nodes, edges);
2891
+ const ownName = (() => {
2892
+ if (l.raw.length !== 1 || l.raw[0].files.length !== 1) return null;
2893
+ try {
2894
+ const d = JSON.parse(l.raw[0].files[0].text);
2895
+ const n = typeof d.name === "string" ? d.name : typeof d.title === "string" ? d.title : null;
2896
+ return n?.trim() || null;
2897
+ } catch {
2898
+ return null;
2899
+ }
2900
+ })();
2901
+ const absIn = path2.resolve(a2.pos[0]);
2902
+ const isDir = fs2.existsSync(absIn) && fs2.statSync(absIn).isDirectory();
2903
+ const base2 = l.title.replace(/\.json$/i, "").split("/").pop() || "Overview";
2904
+ const fallback = !isDir && /^(graph|data|index|nodes|kg)$/i.test(base2) ? path2.basename(path2.dirname(absIn)) : base2;
2905
+ const plan = restructure(nodes, edges, { title: ownName ?? fallback, group: typeof a2.flags.group === "string" ? a2.flags.group.split(",") : void 0 });
2736
2906
  if (a2.flags.json) {
2737
- console.log(JSON.stringify({ before: plan.before, beforeFlat: plan.beforeFlat, after: plan.after, moves: plan.moves, wraps: plan.wraps, created: plan.created, ladder: plan.ladder, note: plan.note }, null, 1));
2907
+ 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));
2738
2908
  if (a2.flags["dry-run"]) return;
2739
2909
  } else {
2740
- console.log(planText(plan, l.title));
2910
+ console.log(planText(plan, l.title, shellArg(a2.pos[0])));
2741
2911
  if (a2.flags["dry-run"]) {
2742
2912
  console.log("\n(dry run: nothing written. Drop --dry-run to write a new pass.)");
2743
2913
  return;
2744
2914
  }
2745
2915
  }
2746
- const outNodes = plan.nodes.map((p) => {
2747
- const { parent: _p, order: _o, ...rest } = p.data ?? {};
2748
- return {
2749
- ...rest,
2750
- id: p.id,
2751
- label: p.label,
2752
- ...p.kind ? { kind: p.kind } : {},
2753
- parent: p.parent,
2754
- ...p.order !== void 0 ? { order: p.order } : {}
2755
- };
2756
- });
2757
- const graph = { name: l.title, nodes: outNodes, edges: phys.edges };
2916
+ const graph = graphOf(plan, l.title, phys.edges);
2758
2917
  const abs = path2.resolve(a2.pos[0]);
2759
2918
  const dir = fs2.existsSync(abs) && fs2.statSync(abs).isDirectory() ? abs : path2.dirname(abs);
2760
2919
  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) : [];
@@ -2771,15 +2930,18 @@ function runRestructure(a2) {
2771
2930
  nodePalette: { ...palette, ...srcProfile.nodePalette ?? {} }
2772
2931
  };
2773
2932
  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`);
2933
+ if (fs2.existsSync(path2.join(passDir, "graph.json"))) fail(`output already exists: ${passDir}; use a fresh input location or review the existing pass`);
2774
2934
  fs2.mkdirSync(passDir, { recursive: true });
2775
2935
  fs2.writeFileSync(path2.join(passDir, "_profile.json"), `${JSON.stringify(outProfile, null, 1)}
2776
2936
  `);
2777
2937
  const file = path2.join(passDir, "graph.json");
2778
2938
  fs2.writeFileSync(file, `${JSON.stringify(graph, null, 1)}
2779
2939
  `);
2780
- console.log(`
2940
+ if (!a2.flags.json) {
2941
+ console.log(`
2781
2942
  wrote ${file}`);
2782
- console.log(`next: glassbrain diff ${a2.pos[0]} ${file}`);
2943
+ console.log(`next: glassbrain diff ${a2.pos[0]} ${file}`);
2944
+ }
2783
2945
  }
2784
2946
  function runConvert(a2) {
2785
2947
  if (a2.pos.length < 1 || a2.pos.length > 2) fail("convert needs <path> [out-dir]");
@@ -2816,7 +2978,7 @@ if (a.flags.version) {
2816
2978
  process.stdout.write(HELP(path2.join(here, "../../schema/graph.schema.json")));
2817
2979
  } else {
2818
2980
  try {
2819
- ({ view, diff: runDiff, validate: runValidate, convert: runConvert, tree: runTree, restructure: runRestructure })[a.cmd](a);
2981
+ ({ view, diff: runDiff, lint: runLint, convert: runConvert, tree: runTree, restructure: runRestructure })[a.cmd](a);
2820
2982
  } catch (e) {
2821
2983
  fail(e.message, 2);
2822
2984
  }