glassbrain 0.2.0-alpha.3 → 0.2.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,9 +10,9 @@ import { fileURLToPath } from "node:url";
10
10
 
11
11
  // src/model.ts
12
12
  function buildModel(nodes, edges, errors = []) {
13
- const index2 = /* @__PURE__ */ new Map();
14
- for (const n of nodes) if (!index2.has(n.id)) index2.set(n.id, n);
15
- return { nodes, edges, errors, index: index2 };
13
+ const index = /* @__PURE__ */ new Map();
14
+ for (const n of nodes) if (!index.has(n.id)) index.set(n.id, n);
15
+ return { nodes, edges, errors, index };
16
16
  }
17
17
  function mergeSlices(slices) {
18
18
  const byId = /* @__PURE__ */ new Map();
@@ -94,6 +94,19 @@ function indexModel(model) {
94
94
  };
95
95
  return { parentOf, childrenOf, depthOf, ancestorsOf, subtreeOf, neighborsOf };
96
96
  }
97
+ function encodeParent(parent, order) {
98
+ if (!parent) return null;
99
+ if (order === void 0) return `${parent}@-1`;
100
+ if (!Number.isFinite(order) || order <= 0) throw new Error("order must be finite and positive");
101
+ const text = String(order);
102
+ if (!/[eE]/.test(text)) return `${parent}@${text}`;
103
+ const [mantissa, exponent] = text.toLowerCase().split("e");
104
+ const [whole, fraction = ""] = mantissa.split(".");
105
+ const digits = whole + fraction;
106
+ const at = whole.length + Number(exponent);
107
+ const decimal = at <= 0 ? `0.${"0".repeat(-at)}${digits}` : at >= digits.length ? digits + "0".repeat(at - digits.length) : `${digits.slice(0, at)}.${digits.slice(at)}`;
108
+ return `${parent}@${decimal}`;
109
+ }
97
110
 
98
111
  // src/profile.ts
99
112
  function parsePhysical(origin, text) {
@@ -105,18 +118,29 @@ function parsePhysical(origin, text) {
105
118
  }
106
119
  if (!raw || typeof raw !== "object" || !("nodes" in raw) && !("edges" in raw)) return null;
107
120
  const ref = (v) => typeof v === "string" || typeof v === "number" ? String(v) : void 0;
108
- const nodes = (Array.isArray(raw.nodes) ? raw.nodes : []).filter((n) => n && typeof n === "object" && ref(n.id) !== void 0).map((n) => ({
109
- id: String(n.id),
110
- label: String(n.label ?? n.name ?? n.id),
111
- kind: typeof n.kind === "string" ? n.kind : void 0,
112
- parent: ref(n.parent),
113
- order: typeof n.order === "number" && Number.isFinite(n.order) ? n.order : void 0,
114
- layer: typeof n.layer === "string" ? n.layer : void 0,
115
- // Marks carried by the data itself (e.g. a placeholder "with no content yet"). They are data, not derived: when the profile's
116
- // `placeholderFlags` recognizes one, it is drawn as skeleton.
117
- ...Array.isArray(n.flags) ? { flags: n.flags.filter((f) => typeof f === "string") } : {},
118
- data: n
119
- }));
121
+ const parentOf = (v) => {
122
+ const rawParent = ref(v);
123
+ const at = rawParent?.lastIndexOf("@") ?? -1;
124
+ const tail = at > 0 ? rawParent.slice(at + 1) : "";
125
+ if (!/^(-1|\d+(\.\d+)?)$/.test(tail)) return { parent: rawParent, order: void 0 };
126
+ const order = tail === "-1" ? void 0 : Number(tail);
127
+ return { parent: rawParent.slice(0, at), order: order !== void 0 && order > 0 ? order : void 0 };
128
+ };
129
+ const nodes = (Array.isArray(raw.nodes) ? raw.nodes : []).filter((n) => n && typeof n === "object" && ref(n.id) !== void 0).map((n) => {
130
+ const { parent, order } = parentOf(n.parent);
131
+ return {
132
+ id: String(n.id),
133
+ label: String(n.label ?? n.name ?? n.id),
134
+ kind: typeof n.kind === "string" ? n.kind : void 0,
135
+ parent,
136
+ order,
137
+ layer: typeof n.layer === "string" ? n.layer : void 0,
138
+ // Marks carried by the data itself (e.g. a placeholder "with no content yet"). They are data, not derived: when the profile's
139
+ // `placeholderFlags` recognizes one, it is drawn as skeleton.
140
+ ...Array.isArray(n.flags) ? { flags: n.flags.filter((f) => typeof f === "string") } : {},
141
+ data: n
142
+ };
143
+ });
120
144
  const edges = (Array.isArray(raw.edges) ? raw.edges : []).filter((e) => e && typeof e === "object").map((e) => ({
121
145
  source: String(e.source ?? e.from),
122
146
  target: String(e.target ?? e.to),
@@ -132,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,15 +1656,15 @@ 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
  }
@@ -1423,7 +1672,7 @@ var parentCycle = {
1423
1672
  }
1424
1673
  };
1425
1674
  var orderMixed = {
1426
- code: "order-mixed",
1675
+ code: "order-error",
1427
1676
  level: "error",
1428
1677
  run: ({ children }) => {
1429
1678
  const out = [];
@@ -1434,17 +1683,17 @@ var orderMixed = {
1434
1683
  const next = Math.max(0, ...kids.map((k) => typeof k.order === "number" ? k.order : 0)) + 1;
1435
1684
  out.push({
1436
1685
  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")}`
1686
+ message: `${withOrder} of ${kids.length} children of "${parent}" are numbered; a sibling set is numbered or explicitly unordered ("@-1")`,
1687
+ fix: `give the rest an order, or mark them all unordered with "@-1":
1688
+ ${missing.map((k, i) => ` - { "id": "${k.id}", "parent": "${parent}@-1" }
1689
+ + { "id": "${k.id}", "parent": "${parent}@${next + i}" }`).join("\n")}`
1441
1690
  });
1442
1691
  }
1443
1692
  return out;
1444
1693
  }
1445
1694
  };
1446
1695
  var orderDuplicate = {
1447
- code: "order-duplicate",
1696
+ code: "order-error",
1448
1697
  level: "error",
1449
1698
  run: ({ children }) => {
1450
1699
  const out = [];
@@ -1461,8 +1710,8 @@ var orderDuplicate = {
1461
1710
  node: parent,
1462
1711
  message: `"${parent}" has ${same.length} children at order ${value} (${names(same.map((n) => n.id))}); two items cannot share a place`,
1463
1712
  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")}`
1713
+ ${same.slice(1).map((k, i) => ` - { "id": "${k.id}", "parent": "${parent}@${value}" }
1714
+ + { "id": "${k.id}", "parent": "${parent}@${value + (i + 1) / 10}" }`).join("\n")}`
1466
1715
  });
1467
1716
  }
1468
1717
  }
@@ -1470,28 +1719,28 @@ ${same.slice(1).map((k, i) => ` - { "id": "${k.id}", "order": ${value} }
1470
1719
  }
1471
1720
  };
1472
1721
  var conflictingDefinition = {
1473
- code: "conflicting-definition",
1722
+ code: "duplicate-id",
1474
1723
  level: "error",
1475
- run: ({ model, index: index2, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1724
+ run: ({ model, index, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1476
1725
  node: id,
1477
- message: `"${id}" is defined differently in ${names(index2.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`,
1726
+ message: `"${id}" is defined differently in ${names(index.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`,
1478
1727
  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.`
1728
+ ${names(index.get(id)?.origins ?? [])} \u2014 keep one definition of "${id}", or rename the other to "${id}-2" and update every edge that meant it.`
1480
1729
  }))
1481
1730
  };
1482
1731
  var danglingEdge = {
1483
1732
  code: "dangling-edge",
1484
1733
  level: "error",
1485
- run: ({ model, index: index2, labelOf }) => {
1734
+ run: ({ model, index, labelOf }) => {
1486
1735
  const out = [];
1487
1736
  for (const e of model.edges) {
1488
- const missing = [!index2.has(e.source) && e.source, !index2.has(e.target) && e.target].filter(Boolean).join(" / ");
1737
+ const missing = [!index.has(e.source) && e.source, !index.has(e.target) && e.target].filter(Boolean).join(" / ");
1489
1738
  if (!missing) continue;
1490
1739
  out.push({
1491
1740
  message: `edge ${e.source} \u2192 ${e.target}${e.kind ? ` (${e.kind})` : ""} points at the missing node ${missing}`,
1492
1741
  fix: `an edge can only join nodes that exist. Add the node, or repoint the edge:
1493
1742
  - { "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"}" }`
1743
+ + { "source": "${index.has(e.source) ? e.source : labelOf(e.target) || e.source}", "target": "${index.has(e.target) ? e.target : "EXISTING_ID"}" }`
1495
1744
  });
1496
1745
  }
1497
1746
  return out;
@@ -1519,88 +1768,17 @@ var duplicateEdge = {
1519
1768
  return out;
1520
1769
  }
1521
1770
  };
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
- }
1771
+ var unevenKinds = {
1772
+ code: "bad-structure",
1773
+ level: "info",
1774
+ run: ({ model }) => analyzeShape(model.nodes).branches.filter((b) => b.score >= 0.2).sort((a2, b) => b.score - a2.score).map((b) => ({
1775
+ node: b.parent,
1776
+ level: b.children.length > WIDE_WARN ? "error" : b.score >= 0.4 ? "warn" : "info",
1777
+ message: `"${b.parent}": ${b.children.length} children with uneven structural relationships (structure pressure ${b.score.toFixed(3)}, dispersion ${b.dispersion.toFixed(3)}, effective template support ${b.support.toFixed(2)})`,
1778
+ fix: `inspect this branch: glassbrain tree <path> --path "${b.parent}"
1779
+ closest compared pair: ${b.closest?.a} / ${b.closest?.b} (distance ${b.closest?.distance}). Differences can be intentional.
1780
+ glassbrain restructure <path> --dry-run --json shows grouping suggestions; no content is deleted.`
1781
+ }))
1604
1782
  };
1605
1783
  var wideNode = {
1606
1784
  code: "wide-node",
@@ -1616,14 +1794,10 @@ var wideNode = {
1616
1794
  out.push({
1617
1795
  level,
1618
1796
  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" }`
1797
+ message: `"${labelOf(id)}" holds ${what}; ${isAnchor ? "review whether each floor is a major section" : "review whether this is one natural collection"}`,
1798
+ fix: `inspect membership and depth: glassbrain tree <path> --path "${id}"
1799
+ glassbrain restructure <path> --dry-run shows candidate groups and their ids.
1800
+ Prefer fewer than 5 children per group; this is guidance, not a quota. Keep a natural collection together; add a named group only when it explains membership.${isAnchor ? "\n Each numbered root child becomes a floor. Use @-1 for an unordered collection; reserve numbered root children for major sections." : ""}`
1627
1801
  });
1628
1802
  }
1629
1803
  return out;
@@ -1643,25 +1817,24 @@ var uncoloredKind = {
1643
1817
  fix: `add one colour per kind to _profile.json (one entry per kind, not per node):
1644
1818
  { "nodePalette": ${JSON.stringify(palette)} }
1645
1819
  ${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).`
1820
+ ` : ""} Colors that land closer than 10 in Lab distance read as one kind (lint notes it).`
1647
1821
  }];
1648
1822
  }
1649
1823
  };
1650
1824
  var singleKind = {
1651
1825
  code: "single-kind",
1652
- level: "warn",
1826
+ level: "info",
1653
1827
  run: ({ model }) => {
1654
1828
  const used = new Set(model.nodes.map((n) => n.kind).filter(Boolean));
1655
1829
  if (used.size !== 1 || model.nodes.length < MIN_SAMPLE) return [];
1656
1830
  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" } }`
1831
+ message: `every node has kind "${[...used][0]}"; check whether this is one natural category`,
1832
+ fix: `keep one kind for genuinely similar things. Introduce another only when it expresses a useful distinction; counts alone do not justify it.`
1660
1833
  }];
1661
1834
  }
1662
1835
  };
1663
- var preferFewerKinds = {
1664
- code: "prefer-fewer-kinds",
1836
+ var kindNote = {
1837
+ code: "kind-note",
1665
1838
  level: "info",
1666
1839
  run: ({ model }) => {
1667
1840
  const out = [];
@@ -1671,33 +1844,25 @@ var preferFewerKinds = {
1671
1844
  const average = total / kinds;
1672
1845
  if (kinds > 10 || average < 5) {
1673
1846
  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.`
1847
+ message: `${space} kinds: ${kinds} (${average.toFixed(1)} per kind); around 8 colors and repeated kinds are easier to scan, but counts are advisory`,
1848
+ fix: `inspect whether kinds express distinct meanings. Preserve precise relation kinds and meaningful rare categories; merge only synonyms.`
1676
1849
  });
1677
1850
  }
1678
1851
  };
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
1852
  const lone = (space, counts, total) => {
1690
1853
  if (total < MIN_SAMPLE) return;
1691
1854
  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.` });
1855
+ if (once.length) out.push({ message: `${once.length} ${space} kind${once.length > 1 ? "s" : ""} used once: ${names(once)}`, fix: `keep a rare kind when its meaning is distinct; do not add instances merely to meet a count.` });
1693
1856
  };
1857
+ spread("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1858
+ spread("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1694
1859
  lone("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1695
1860
  lone("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1696
1861
  return out;
1697
1862
  }
1698
1863
  };
1699
1864
  var lowCoverage = {
1700
- code: "low-coverage",
1865
+ code: "coverage-note",
1701
1866
  level: "info",
1702
1867
  run: ({ model, children }) => {
1703
1868
  const leaves = model.nodes.filter((n) => !children.has(n.id));
@@ -1711,8 +1876,8 @@ var lowCoverage = {
1711
1876
  }];
1712
1877
  }
1713
1878
  };
1714
- var colorsContrast = {
1715
- code: "colors-contrast",
1879
+ var colorNote = {
1880
+ code: "color-note",
1716
1881
  level: "info",
1717
1882
  run: ({ profile }) => {
1718
1883
  const colors = Object.entries(profile.nodePalette).map(([kind, hex]) => ({ kind, lab: hexLab(hex) }));
@@ -1734,6 +1899,22 @@ var colorsContrast = {
1734
1899
  }];
1735
1900
  }
1736
1901
  };
1902
+ var orderHint = {
1903
+ code: "order-hint",
1904
+ level: "info",
1905
+ run: ({ model, children }) => {
1906
+ const roots = model.nodes.filter((n) => !n.parent);
1907
+ if (roots.length !== 1) return [];
1908
+ const root = roots[0];
1909
+ const kids = children.get(root.id) ?? [];
1910
+ if (kids.length < 2 || kids.some((k) => typeof k.order === "number")) return [];
1911
+ return [{
1912
+ node: root.id,
1913
+ message: `"${root.label || root.id}" has ${kids.length} unordered children; it opens flat, with optional floors`,
1914
+ fix: `keep @-1 for a collection. Number the root children only when they are major sections worth separate floors; view can also preview floors without changing the data.`
1915
+ }];
1916
+ }
1917
+ };
1737
1918
  var rules = [
1738
1919
  misplacedField,
1739
1920
  layerField,
@@ -1744,16 +1925,14 @@ var rules = [
1744
1925
  conflictingDefinition,
1745
1926
  danglingEdge,
1746
1927
  duplicateEdge,
1747
- multipleRoots,
1748
- noHierarchy,
1749
- unevenBranches,
1928
+ unevenKinds,
1750
1929
  wideNode,
1751
1930
  uncoloredKind,
1752
1931
  singleKind,
1753
- preferFewerKinds,
1754
- loneKind,
1932
+ kindNote,
1933
+ colorNote,
1755
1934
  lowCoverage,
1756
- colorsContrast
1935
+ orderHint
1757
1936
  ];
1758
1937
  function checkGraph(model, profile, opts) {
1759
1938
  const children = /* @__PURE__ */ new Map();
@@ -1763,17 +1942,6 @@ function checkGraph(model, profile, opts) {
1763
1942
  if (arr) arr.push(n);
1764
1943
  else children.set(n.parent, [n]);
1765
1944
  }
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
1945
  const ctx = {
1778
1946
  model,
1779
1947
  profile,
@@ -1782,7 +1950,6 @@ function checkGraph(model, profile, opts) {
1782
1950
  children,
1783
1951
  layers: deriveLayers(model),
1784
1952
  labelOf: (id) => model.index.get(id)?.label ?? id,
1785
- heightOf: (id) => heightOf(id),
1786
1953
  sameFileDuplicates: opts.sameFileDuplicates ?? /* @__PURE__ */ new Set()
1787
1954
  };
1788
1955
  const out = rules.flatMap((rule) => rule.run(ctx).map((issue) => ({
@@ -1796,12 +1963,12 @@ function checkGraph(model, profile, opts) {
1796
1963
  return out;
1797
1964
  }
1798
1965
  function structureOf(model) {
1799
- const index2 = indexModel(model);
1966
+ const index = indexModel(model);
1800
1967
  let depth = 0;
1801
1968
  let parented = 0;
1802
1969
  for (const n of model.nodes) {
1803
1970
  if (n.parent && model.index.has(n.parent)) parented++;
1804
- depth = Math.max(depth, index2.depthOf(n.id));
1971
+ depth = Math.max(depth, index.depthOf(n.id));
1805
1972
  }
1806
1973
  const children = /* @__PURE__ */ new Map();
1807
1974
  for (const n of model.nodes) {
@@ -1809,18 +1976,8 @@ function structureOf(model) {
1809
1976
  const arr = children.get(n.parent);
1810
1977
  arr ? arr.push(n) : children.set(n.parent, [n]);
1811
1978
  }
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
1979
  const derived = deriveLayers(model);
1980
+ const analysis = analyzeShape(model.nodes);
1824
1981
  return {
1825
1982
  nodes: model.nodes.length,
1826
1983
  edges: model.edges.length,
@@ -1828,7 +1985,8 @@ function structureOf(model) {
1828
1985
  depth,
1829
1986
  parented,
1830
1987
  layers: derived.layers.length,
1831
- isomorphism: +isomorphism(model, children, (id) => heightOf(id)).score.toFixed(2),
1988
+ regularity: +(1 - analysis.peak).toFixed(3),
1989
+ shape: { peak: analysis.peak, assessed: analysis.assessed, unassessed: analysis.unassessed, branches: analysis.branches },
1832
1990
  ordered: derived.layers.length > 0 || [...children.keys()].some((id) => orderedChildren(children, id) !== null)
1833
1991
  };
1834
1992
  }
@@ -1875,7 +2033,7 @@ function derivedProfile(base2, sources, json, force) {
1875
2033
  }
1876
2034
  var modelOf = (v, profile) => parseSources(v.sources, profile);
1877
2035
  var RANK = { error: 0, warn: 1, info: 2 };
1878
- function validate(loaded) {
2036
+ function lint(loaded) {
1879
2037
  const out = [];
1880
2038
  const profile = profileOf(loaded);
1881
2039
  if (loaded.profile) {
@@ -1883,11 +2041,10 @@ function validate(loaded) {
1883
2041
  const retired = ["layers", "singleRoot"].filter((k) => k in loaded.profile);
1884
2042
  if (retired.length) out.push({
1885
2043
  level: "warn",
1886
- code: "profile-retired",
2044
+ code: "schema",
1887
2045
  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 } }`
2046
+ message: `${retired.map((k) => `"${k}"`).join(" and ")} no longer configure anything: layers come from the order in "parent"`,
2047
+ fix: `delete ${retired.length > 1 ? "them" : "it"} from _profile.json. The page opens on the floors when the graph has them; write "appearance": { "defaultLayers": false } to open flat.`
1891
2048
  });
1892
2049
  }
1893
2050
  for (const e of loaded.metaErrors) out.push({ level: "error", code: "schema", where: e.file, message: e.message });
@@ -1904,32 +2061,61 @@ function validate(loaded) {
1904
2061
  doc = JSON.parse(f.text);
1905
2062
  } catch (e) {
1906
2063
  notJson.add(f.path);
1907
- out.push({ level: "error", code: "not-json", where: prefix + f.path, message: `not JSON: ${e.message}` });
2064
+ out.push({ level: "error", code: "schema", where: prefix + f.path, message: `not JSON: ${e.message}` });
1908
2065
  continue;
1909
2066
  }
1910
2067
  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' });
2068
+ out.push({ level: "warn", code: "schema", where: prefix + f.path, message: 'not a graph (no "nodes" or "edges"), skipped' });
1912
2069
  continue;
1913
2070
  }
1914
2071
  for (const e of checkSchema(graph_schema_default, doc)) out.push({ level: "error", code: "schema", where: prefix + f.path, message: `${e.path}: ${e.message}` });
1915
- const bare = (Array.isArray(doc.nodes) ? doc.nodes : []).filter((n) => !!n && typeof n === "object" && !("parent" in n));
2072
+ const rawNodes = (Array.isArray(doc.nodes) ? doc.nodes : []).filter((n) => !!n && typeof n === "object");
2073
+ const bare = rawNodes.filter((n) => !("parent" in n));
1916
2074
  if (bare.length) out.push({
1917
2075
  level: "error",
1918
- code: "missing-parent",
2076
+ code: "parent-error",
1919
2077
  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:
2078
+ message: `${bare.length} node${bare.length > 1 ? "s" : ""} without "parent" (${bare.slice(0, 3).map((n) => `"${String(n.id)}"`).join(", ")}${bare.length > 3 ? ` and ${bare.length - 3} more` : ""}); every node has one: null for the root, otherwise "<id>@<order>"`,
2079
+ fix: `add the field. The top of the tree is null; everything else names its container and its place:
1922
2080
  - { "id": "${String(bare[0].id)}" }
1923
2081
  + { "id": "${String(bare[0].id)}", "parent": null }
1924
2082
  - { "id": "child" }
1925
- + { "id": "child", "parent": "${String(bare[0].id)}" }`
2083
+ + { "id": "child", "parent": "${String(bare[0].id)}@-1" }`
2084
+ });
2085
+ const malformed = rawNodes.filter((n) => "parent" in n && typeof n.parent === "string" && !parentParts(n.parent));
2086
+ if (malformed.length) {
2087
+ const sample = malformed[0];
2088
+ const value = String(sample.parent);
2089
+ const at = value.lastIndexOf("@");
2090
+ const id = at > 0 ? value.slice(0, at) : value;
2091
+ out.push({
2092
+ level: "error",
2093
+ code: "parent-error",
2094
+ where: prefix + f.path,
2095
+ message: `${malformed.length} node${malformed.length > 1 ? "s" : ""} with a malformed "parent" (${malformed.slice(0, 3).map((n) => `"${String(n.parent)}"`).join(", ")}${malformed.length > 3 ? ` and ${malformed.length - 3} more` : ""}); it is "<id>@<order>"`,
2096
+ fix: `write the container's id, then "@", then a positive number (-1 = explicitly unordered):
2097
+ - { "id": "${String(sample.id)}", "parent": ${JSON.stringify(value)} }
2098
+ + { "id": "${String(sample.id)}", "parent": "${id}@-1" }`
2099
+ });
2100
+ }
2101
+ const roots = rawNodes.filter((n) => n.parent === null);
2102
+ if (roots.length > 1) out.push({
2103
+ level: "error",
2104
+ code: "parent-error",
2105
+ where: prefix + f.path,
2106
+ message: `${roots.length} nodes with "parent": null (${roots.slice(0, 3).map((n) => `"${String(n.id)}"`).join(", ")}${roots.length > 3 ? ` and ${roots.length - 3} more` : ""}); a file has one root`,
2107
+ fix: `one file is one tree. Add a root and hang the others under it (numbered children open the floors):
2108
+ + { "id": "overview", "label": "Overview", "parent": null }
2109
+ ${roots.slice(0, 3).map((n, i) => `- { "id": "${String(n.id)}", "parent": null }
2110
+ + { "id": "${String(n.id)}", "parent": "overview@${i + 1}" }`).join("\n ")}
2111
+ or split the file: one file per tree.`
1926
2112
  });
1927
2113
  const seen = /* @__PURE__ */ new Map();
1928
2114
  for (const id of idsIn(doc)) seen.set(id, (seen.get(id) ?? 0) + 1);
1929
2115
  for (const [id, count2] of seen) {
1930
2116
  if (count2 < 2) continue;
1931
2117
  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` });
2118
+ out.push({ level: "error", code: "duplicate-id", where: prefix + f.path, message: `id "${id}" appears ${count2} times in this file; the first one is kept` });
1933
2119
  }
1934
2120
  }
1935
2121
  }
@@ -1937,10 +2123,17 @@ function validate(loaded) {
1937
2123
  const model = modelOf(v, profile);
1938
2124
  for (const e of model.errors) if (!notJson.has(e.origin)) out.push({ level: "error", code: "schema", where: prefix + e.origin, message: e.message });
1939
2125
  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" });
2126
+ if (!model.nodes.length) out.push({ level: "warn", code: "schema", where: prefix || loaded.title, message: "No nodes found" });
1941
2127
  }
1942
2128
  return out.sort((a2, b) => RANK[a2.level] - RANK[b.level]);
1943
2129
  }
2130
+ var ORDER_TAIL = /^(-1|\d+(\.\d+)?)$/;
2131
+ function parentParts(raw) {
2132
+ const at = raw.lastIndexOf("@");
2133
+ if (at < 1) return null;
2134
+ const order = raw.slice(at + 1);
2135
+ return ORDER_TAIL.test(order) && (order === "-1" || Number.isFinite(Number(order)) && Number(order) > 0) ? { id: raw.slice(0, at), order } : null;
2136
+ }
1944
2137
  function idsIn(doc) {
1945
2138
  const nodes = doc.nodes;
1946
2139
  if (!Array.isArray(nodes)) return [];
@@ -2015,6 +2208,7 @@ var MAX_LINES = 200;
2015
2208
  var MAX_EDGES = 6;
2016
2209
  function tree(model, opts) {
2017
2210
  const derived = deriveLayers(model);
2211
+ const evidence = new Map(analyzeShape(model.nodes).branches.map((b) => [b.parent, b]));
2018
2212
  const layerOf = (n) => derived.layerOf.get(n.id);
2019
2213
  const labelOf = (id) => model.index.get(id)?.label ?? id;
2020
2214
  const depth = Math.max(1, opts.depth ?? 3);
@@ -2072,6 +2266,8 @@ function tree(model, opts) {
2072
2266
  const tall = height.get(node.id) ?? 0;
2073
2267
  const edges = collapsed ? [] : outgoing.get(node.id) ?? [];
2074
2268
  const bits = [];
2269
+ const assessment = evidence.get(node.id);
2270
+ if (assessment) bits.push(`${list.length} ${list.length === 1 ? "child" : "children"} \xB7 ${assessment.assessed ? `pressure ${assessment.score.toFixed(3)}` : "unassessed"}`);
2075
2271
  if (inside > 0) bits.push(one(inside, "node"));
2076
2272
  if (collapsed && tall > 0) bits.push(`${tall} deep`);
2077
2273
  if (edges.length) bits.push(edgeText(edges));
@@ -2087,7 +2283,7 @@ function tree(model, opts) {
2087
2283
  deep: tall,
2088
2284
  collapsed,
2089
2285
  edges,
2090
- text: `${prefix}${connector}${orderTag}${label}${bits.length ? ` ${bits.join(" \xB7 ")}` : ""}`
2286
+ text: `${prefix}${connector}${orderTag}${label}${labelOf(node.id) !== node.id ? ` [${node.id}]` : ""}${bits.length ? ` ${bits.join(" \xB7 ")}` : ""}`
2091
2287
  });
2092
2288
  if (!canExpand) return;
2093
2289
  const shown = list.slice(0, perNode);
@@ -2110,7 +2306,7 @@ function tree(model, opts) {
2110
2306
  }
2111
2307
  };
2112
2308
  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)}`;
2309
+ let header = `${opts.title} ${one(structure.nodes, "node")} \xB7 ${one(structure.edges, "edge")} \xB7 ${one(structure.roots, "root")} \xB7 depth ${structure.depth}${structure.layers ? ` \xB7 ${one(structure.layers, "layer")}` : ""} \xB7 structure pressure ${structure.shape.peak.toFixed(3)} \xB7 ${structure.shape.assessed} assessed / ${structure.shape.unassessed} unassessed`;
2114
2310
  const roots = model.nodes.filter((n) => !n.parent || broken(n));
2115
2311
  if (opts.path) {
2116
2312
  const start = model.index.get(opts.path);
@@ -2162,307 +2358,267 @@ function treeText(result) {
2162
2358
  }
2163
2359
 
2164
2360
  // cli/restructure.ts
2165
- function index(nodes) {
2361
+ function restructure(input, edges, opts = {}) {
2362
+ const nodes = input.map((n) => ({ ...n, data: { ...n.data } }));
2166
2363
  const byId = new Map(nodes.map((n) => [n.id, n]));
2167
- const children = /* @__PURE__ */ new Map();
2364
+ if (byId.size !== nodes.length)
2365
+ throw new Error("duplicate ids: resolve them before restructure");
2366
+ const done = /* @__PURE__ */ new Set();
2168
2367
  for (const n of nodes) {
2169
- if (!n.parent || !byId.has(n.parent)) {
2170
- n.parent = null;
2171
- continue;
2368
+ const seen = /* @__PURE__ */ new Set();
2369
+ let cur = n;
2370
+ while (cur && !done.has(cur.id)) {
2371
+ if (seen.has(cur.id))
2372
+ throw new Error("parent cycle: repair it before restructure");
2373
+ seen.add(cur.id);
2374
+ if (cur.parent && !byId.has(cur.parent))
2375
+ throw new Error(`unknown parent ${cur.parent}: repair it before restructure`);
2376
+ cur = cur.parent ? byId.get(cur.parent) : void 0;
2172
2377
  }
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;
2378
+ for (const id of seen)
2379
+ done.add(id);
2380
+ }
2381
+ for (const e of edges)
2382
+ if (!byId.has(e.source) || !byId.has(e.target))
2383
+ throw new Error("dangling edge: repair endpoints before restructure");
2384
+ const before = analyzeShape(nodes).peak, beforeFlat = !nodes.some((n) => n.parent);
2385
+ const created = [], moves = [], orders = [];
2386
+ const unique = (base2) => {
2387
+ let id = base2, i = 2;
2388
+ while (byId.has(id))
2389
+ id = `${base2}-${i++}`;
2390
+ return id;
2201
2391
  };
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;
2392
+ const add = (label, kind, parent, base2 = "group") => {
2393
+ const n = { id: unique(base2), label, kind, parent, data: {} };
2394
+ nodes.push(n);
2395
+ byId.set(n.id, n);
2396
+ created.push({ id: n.id, label, kind, parent });
2397
+ return n;
2214
2398
  };
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;
2399
+ const move = (n, parent, why) => {
2400
+ moves.push({ id: n.id, from: n.parent, to: parent, why });
2401
+ n.parent = parent;
2228
2402
  };
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++;
2403
+ if (beforeFlat) {
2404
+ const paths = /* @__PURE__ */ new Map();
2405
+ const ensure = (p, isFile = false) => {
2406
+ const key = `${isFile ? "f" : "d"}:${p}`;
2407
+ const found = paths.get(key);
2408
+ if (found)
2409
+ return found;
2410
+ const slash = p.lastIndexOf("/");
2411
+ const parent = slash > 0 ? ensure(p.slice(0, slash)).id : null;
2412
+ const n = add(p.slice(slash + 1) || p, isFile ? "file" : "folder", parent, isFile ? "file" : "folder");
2413
+ paths.set(key, n);
2414
+ return n;
2415
+ };
2416
+ for (const n of [...input]) {
2417
+ const raw = typeof n.data.source_file === "string" ? n.data.source_file : n.id.includes("/") ? n.id.split("#")[0] : null;
2418
+ if (raw && raw.includes("/"))
2419
+ move(byId.get(n.id), ensure(raw, true).id, "explicit source path");
2283
2420
  }
2284
2421
  }
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;
2422
+ const roots = nodes.filter((n) => !n.parent);
2423
+ if (roots.length > 1) {
2424
+ const root = add(opts.title?.trim() || "Overview", "overview", null, "root");
2425
+ for (const n of roots)
2426
+ move(n, root.id, "one root");
2427
+ }
2428
+ const analysis = analyzeShape(nodes);
2429
+ const suggestions = [];
2430
+ for (const b of analysis.branches) {
2431
+ if (b.score < 0.2 || !b.closest || b.children.length < 3)
2337
2432
  continue;
2433
+ const seen = /* @__PURE__ */ new Set();
2434
+ const ordered = b.children.map((id) => byId.get(id)).sort((a2, b2) => (a2.order ?? a2.seq ?? 0) - (b2.order ?? b2.seq ?? 0));
2435
+ for (const seed of b.pairs.slice(0, 6)) {
2436
+ const members = [seed.a, seed.b];
2437
+ for (const id of b.children) {
2438
+ if (!members.includes(id) && members.every((m) => analysis.distance(m, id) <= seed.distance + 0.12)) members.push(id);
2439
+ }
2440
+ if (members.length === b.children.length) continue;
2441
+ const key = [...members].sort().join("\0");
2442
+ if (seen.has(key)) continue;
2443
+ seen.add(key);
2444
+ let within = 0, outside = Infinity;
2445
+ for (const m of members) for (const id of b.children) {
2446
+ const d = analysis.distance(m, id);
2447
+ if (members.includes(id)) within = Math.max(within, d);
2448
+ else outside = Math.min(outside, d);
2449
+ }
2450
+ if (outside - within < 0.15) continue;
2451
+ const indices = ordered.map((n, i) => members.includes(n.id) ? i : -1).filter((i) => i >= 0);
2452
+ if (ordered.every((n) => n.order !== void 0) && Math.max(...indices) - Math.min(...indices) + 1 !== members.length) continue;
2453
+ suggestions.push({
2454
+ parent: b.parent,
2455
+ members: ordered.filter((n) => members.includes(n.id)).map((n) => n.id),
2456
+ within: +within.toFixed(6),
2457
+ outside: +outside.toFixed(6),
2458
+ cost: { created: 1, moved: members.length },
2459
+ reason: "This sibling set is structurally closer within than to every outsider. Inspect the named nodes in tree; group only if their meanings belong together."
2460
+ });
2338
2461
  }
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) => {
2462
+ }
2463
+ if (opts.group) {
2464
+ const picked = opts.group.map((id) => byId.get(id));
2465
+ if (picked.length < 2 || picked.some((n) => !n) || new Set(opts.group).size !== picked.length)
2466
+ throw new Error("--group needs two or more distinct existing sibling ids");
2467
+ const members = picked, parent = members[0].parent;
2468
+ if (!parent || members.some((n) => n.parent !== parent))
2469
+ throw new Error("--group members must have the same parent");
2470
+ const siblings = nodes.filter((n) => n.parent === parent).sort((a2, b) => (a2.order ?? a2.seq ?? 0) - (b.order ?? b.seq ?? 0));
2471
+ if (members.length === siblings.length)
2472
+ throw new Error("grouping every sibling adds no distinction");
2473
+ const numbered = siblings.every((n) => n.order !== void 0);
2474
+ const indices = siblings.map((n, i) => opts.group.includes(n.id) ? i : -1).filter((i) => i >= 0);
2475
+ if (numbered && Math.max(...indices) - Math.min(...indices) + 1 !== members.length)
2476
+ throw new Error("ordered group members must be consecutive");
2477
+ const label = siblings.filter((n) => opts.group.includes(n.id)).map((n) => n.label || n.id).join(" & ");
2478
+ const group = add(label, "group", parent);
2479
+ if (numbered)
2480
+ group.order = Math.min(...members.map((n) => n.order));
2481
+ for (const n of members)
2482
+ move(n, group.id, "explicit --group selection");
2483
+ }
2484
+ const children = /* @__PURE__ */ new Map();
2485
+ for (const n of nodes)
2486
+ if (n.parent) {
2487
+ const xs = children.get(n.parent) ?? [];
2488
+ xs.push(n);
2489
+ children.set(n.parent, xs);
2490
+ }
2491
+ for (const kids of children.values()) {
2492
+ const values = kids.filter((n) => n.order !== void 0).map((n) => n.order);
2493
+ if (!values.length)
2494
+ continue;
2495
+ if (values.length === kids.length && new Set(values).size === values.length && values.every((n) => Number.isFinite(n) && n > 0))
2496
+ continue;
2497
+ kids.sort((a2, b) => (a2.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER) || (a2.seq ?? 0) - (b.seq ?? 0));
2498
+ kids.forEach((n, i) => {
2499
+ if (n.order !== i + 1)
2500
+ orders.push({ id: n.id, from: n.order ?? null, to: i + 1 });
2341
2501
  n.order = i + 1;
2342
2502
  });
2343
2503
  }
2504
+ const after = analyzeShape(nodes).peak;
2505
+ return {
2506
+ nodes,
2507
+ edges,
2508
+ moves,
2509
+ created,
2510
+ removed: [],
2511
+ wraps: created.filter((n) => n.kind === "group").map((n) => n.id),
2512
+ before,
2513
+ after,
2514
+ beforeFlat,
2515
+ ladder: [],
2516
+ orders,
2517
+ suggestions,
2518
+ note: "Structure pressure is not correctness. No original node or relation was removed. Group suggestions require --group; lower pressure after grouping is not proof of improvement."
2519
+ };
2344
2520
  }
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");
2521
+ function planText(r, title, inputPath = "<path>") {
2522
+ const lines = [`${title}: structure pressure ${r.before.toFixed(3)} \u2192 ${r.after.toFixed(3)}`, r.note ?? "", `created ${r.created.length}; moved ${r.moves.length}; renumbered ${r.orders.length}; removed 0`];
2523
+ for (const m of r.moves.slice(0, 12))
2524
+ lines.push(` ${m.id}: ${m.from ?? "(root)"} \u2192 ${m.to} (${m.why})`);
2525
+ for (const s of r.suggestions)
2526
+ lines.push(`suggest group ${s.members.join(",")} under ${s.parent}: within ${s.within.toFixed(3)}, outside ${s.outside.toFixed(3)}; cost +1 node, ${s.members.length} moves.
2527
+ inspect with tree; apply with glassbrain restructure ${inputPath} --group ${s.members.join(",")}`);
2528
+ return lines.filter(Boolean).join("\n");
2529
+ }
2530
+ function planNodesOf(model) {
2531
+ return model.nodes.map((n, seq) => ({
2532
+ id: n.id,
2533
+ label: n.label,
2534
+ kind: n.kind,
2535
+ parent: n.parent ?? null,
2536
+ order: typeof n.order === "number" ? n.order : typeof n.data?.order === "number" && Number.isFinite(n.data.order) && n.data.order > 0 ? n.data.order : void 0,
2537
+ seq,
2538
+ data: n.data ?? {}
2539
+ }));
2540
+ }
2541
+ function graphOf(plan, name, edges) {
2542
+ return {
2543
+ name,
2544
+ nodes: plan.nodes.map((p) => {
2545
+ const { parent: _p, order: _o, layer: _layer, ...rest } = p.data ?? {};
2546
+ return {
2547
+ ...rest,
2548
+ id: p.id,
2549
+ label: p.label,
2550
+ ...p.kind ? { kind: p.kind } : {},
2551
+ parent: encodeParent(p.parent, p.order)
2552
+ };
2553
+ }),
2554
+ edges
2555
+ };
2376
2556
  }
2377
2557
 
2378
2558
  // 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
2559
+ var HELP = (schema) => `glassbrain: open, diff and lint a knowledge graph, written as plain JSON.
2386
2560
 
2387
2561
  [ 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 } ],
2562
+ JSON with two arrays, \`nodes\` and \`edges\`. The parent structure helps readability.
2563
+ { "nodes": [
2564
+ { "id": "start", "label": "Start", "kind": "folder","parent": null }, // the root: parent is null
2565
+ { "id": "login", "label": "Login", "kind": "file", "parent": "start@1", // first child
2566
+ "description": "Checks the password, then opens a session.", // markdown
2567
+ "owner": "auth" }, // any other field: kept, shown
2568
+ { "id": "db", "label": "DB", "kind": "file", "parent": "start@2" } ], // second child
2400
2569
  "edges": [
2401
- { "source": "src/login.ts", "target": "src/db.ts", "kind": "uses" } ] }
2570
+ { "source": "login", "target": "db", "kind": "uses" } ] }
2402
2571
 
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
2572
+ GUIDELINES
2573
+ * \`parent\` is required on EVERY node: null for the only root, otherwise "<id>@<order>".
2574
+ * \`@order\` sorts siblings: use distinct positive numbers; decimals are allowed.
2575
+ * Use \`@-1\` only to force an unordered group; all siblings must then use @-1.
2576
+ * Parent structure helps readability. Prefer fewer than 5 children; keep natural collections. Consider deeper grouping if crowded.
2577
+ * Keep kinds few and consistent (around 8 or fewer).
2578
+ * Keep depth and detail meaningful. Lint flags structural imbalance as \`bad-structure\`.
2579
+ * Put supporting details in descriptions. Extra fields are kept and shown.
2422
2580
 
2423
2581
  Full schema: ${schema}
2424
2582
 
2425
2583
  [ STRUCTURE ]
2426
- A folder is a graph. Passes are optional; one numbered folder each.
2584
+ * For most cases, one graph is enough. Just write one, unless the task calls for more. *
2585
+
2586
+ But you can keep multiple ones. Use them for staged workflows, diffs, or version control.
2587
+ One folder per pass; folder names set the order. For example:
2427
2588
 
2428
2589
  kg/
2429
2590
  \u251C\u2500\u2500 _profile.json colors, shared by every pass (see [ APPEARANCE ])
2430
2591
  \u251C\u2500\u2500 1-skeleton/graph.json a graph (see [ DATA ])
2431
2592
  \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
2593
+ \u2514\u2500\u2500 3-linked/graph.json then lint, and diff against the pass before
2433
2594
 
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.
2595
+ Inside a pass, JSON at any depth merges by id; split by area only when a file gets too big to write.
2437
2596
 
2438
2597
  [ APPEARANCE ]
2439
- kg/_profile.json, shared by every pass. Everything in it is optional.
2598
+ kg/_profile.json, shared by every pass, also when opening a pass file directly.
2599
+ A local pass profile overrides it; an exported bundle carries its own profile.
2440
2600
 
2441
2601
  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.
2602
+ every uncoloured kind looks the same, so lint reports it as an error.
2443
2603
  { "nodePalette": { "file": "#6366f1", "folder": "#94a3b8" },
2444
2604
  "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).
2605
+ Colors closer than 10 in Lab distance read as one kind (lint notes it).
2447
2606
 
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.
2607
+ VIEW set { "appearance": { "defaultLayers": true } } to open in layers.
2608
+ Only sets the opening state; use the page switches to change it.
2452
2609
 
2453
2610
  Full schema: ${schema.replace("graph.schema", "profile.schema")}
2454
2611
 
2455
2612
  [ COMMANDS ]
2456
- Always validate before handing over; a page is only written for a graph with no errors.
2613
+ * Always lint before handing over; view refuses graphs with errors. *
2457
2614
 
2458
2615
  glassbrain <path> write one html page, print its path (passes play as steps)
2459
2616
  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.
2617
+ glassbrain lint <path> Lint errors, warnings, info; exit 1 on errors.
2618
+ Always lint before handing over.
2619
+ glassbrain tree <path> log the containment tree as text
2620
+ glassbrain restructure <path> preserve content; repair containment and order, suggest groups;
2621
+ write graph.json and _profile.json in a new folder
2466
2622
  glassbrain diff <old> <new> only what changed between two graphs
2467
2623
  glassbrain diff <git-ref> <path> the same graph at an earlier commit (default HEAD)
2468
2624
  glassbrain convert <path> [out-dir] write any supported format as glassbrain JSON
@@ -2470,22 +2626,14 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
2470
2626
  <path> is a file, a folder, or <git-ref>:<path> (HEAD~1:kg/graph.json). Graphify,
2471
2627
  Understand-Anything, memory.jsonl and markdown folders are read as-is.
2472
2628
 
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
2629
 
2483
2630
  [ OPTIONS ]
2484
- --json machine-readable output (validate, tree, diff, restructure)
2485
- --strict warnings fail too (validate, view)
2631
+ --json machine-readable output (lint, tree, diff, restructure)
2632
+ --strict warnings fail too (lint, view)
2486
2633
  --depth <n> tree: levels to expand (default 3)
2487
2634
  --path <id> tree: one node, its ancestors and its subtree
2488
2635
  --orphans tree: only nodes with no parent
2636
+ --group <a,b> restructure: explicitly group selected siblings
2489
2637
  --dry-run restructure: print the plan, write nothing
2490
2638
  --out <file.html> write the page here instead of a temp file (view, diff)
2491
2639
  --open / --no-open open the browser or not (diff opens only in a terminal)
@@ -2495,9 +2643,10 @@ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, w
2495
2643
  --format <id> force a format: native, graphify, understand-anything, memory, obsidian
2496
2644
  -h, --help / -v, --version this help / the version
2497
2645
  `;
2498
- var VALUED = /* @__PURE__ */ new Set(["out", "format", "ignore", "depth", "path"]);
2646
+ var VALUED = /* @__PURE__ */ new Set(["out", "format", "ignore", "depth", "path", "group"]);
2499
2647
  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"];
2648
+ var COMMANDS = ["view", "diff", "lint", "convert", "tree", "restructure"];
2649
+ var ALIASES = { validate: "lint", "re-structure": "restructure" };
2501
2650
  function parseArgs(argv) {
2502
2651
  const pos = [];
2503
2652
  const flags = {};
@@ -2521,7 +2670,8 @@ function parseArgs(argv) {
2521
2670
  } else if (a2.startsWith("-") && a2 !== "-") fail(`unknown option ${a2} (see glassbrain --help)`);
2522
2671
  else pos.push(a2);
2523
2672
  }
2524
- const cmd = COMMANDS.includes(pos[0]) ? pos.shift() : "view";
2673
+ const name = Object.hasOwn(ALIASES, pos[0]) ? ALIASES[pos[0]] : pos[0];
2674
+ const cmd = COMMANDS.includes(name) ? (pos.shift(), name) : "view";
2525
2675
  if (cmd === "view" && pos.length > 1 && !fs2.existsSync(pos[0]) && /^[a-z]+$/.test(pos[0])) fail(`unknown command ${pos[0]} (commands: ${COMMANDS.join(", ")})`);
2526
2676
  return { cmd, pos, flags };
2527
2677
  }
@@ -2581,18 +2731,20 @@ function notes(l, models) {
2581
2731
  });
2582
2732
  }
2583
2733
  var summaryOf = (l, m) => `${l.title}: ${l.versions.length > 1 ? `${l.versions.length} versions, latest ` : ""}${count(m.nodes.length, "node")}, ${count(m.edges.length, "edge")}${l.format !== "native" ? ` (read as ${l.format})` : ""}`;
2734
+ var shellArg = (s) => "'" + s.replace(/'/g, `'"'"'`) + "'";
2735
+ var findingsAt = (l, input) => lint(l).map((f) => ({ ...f, ...f.fix ? { fix: f.fix.replaceAll("<path>", shellArg(input)) } : {} }));
2584
2736
  function view(a2) {
2585
2737
  if (a2.pos.length !== 1) fail("view needs exactly one <path>");
2586
2738
  const l = load(a2.pos[0], { format: a2.flags.format });
2587
2739
  const models = nodesOf(l);
2588
2740
  notes(l, models);
2589
- const found = validate(l);
2741
+ const found = findingsAt(l, a2.pos[0]);
2590
2742
  const n = tally(found);
2591
2743
  if (n.error || a2.flags.strict && n.warn) {
2592
2744
  console.log(summaryOf(l, models[models.length - 1]));
2593
2745
  printFindings(found);
2594
2746
  console.log(`
2595
- ${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \u2014 page not written. Fix them, then validate again.`);
2747
+ ${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \u2014 page not written. Fix them, then lint again.`);
2596
2748
  process.exitCode = 1;
2597
2749
  return;
2598
2750
  }
@@ -2601,7 +2753,7 @@ ${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \u2014 page not writ
2601
2753
  console.log(file);
2602
2754
  if (n.warn) {
2603
2755
  printFindings(found.filter((f) => f.level === "warn"));
2604
- console.log(`${count(n.warn, "warning")} (not blocking; \`glassbrain validate\` has the details)`);
2756
+ console.log(`${count(n.warn, "warning")} (not blocking; \`glassbrain lint\` has the details)`);
2605
2757
  }
2606
2758
  if (a2.flags.open !== false) openFile(file);
2607
2759
  }
@@ -2655,10 +2807,10 @@ ${file}`);
2655
2807
  if (file && wantOpen) openFile(file);
2656
2808
  if (a2.flags["exit-code"] && changed) process.exitCode = 1;
2657
2809
  }
2658
- function runValidate(a2) {
2659
- if (a2.pos.length !== 1) fail("validate needs exactly one <path>");
2810
+ function runLint(a2) {
2811
+ if (a2.pos.length !== 1) fail("lint needs exactly one <path>");
2660
2812
  const l = load(a2.pos[0], { format: a2.flags.format });
2661
- const found = validate(l);
2813
+ const found = findingsAt(l, a2.pos[0]);
2662
2814
  const models = nodesOf(l);
2663
2815
  const latest = models[models.length - 1];
2664
2816
  const n = tally(found);
@@ -2680,8 +2832,8 @@ function runValidate(a2) {
2680
2832
  if (found.length) console.log("");
2681
2833
  printFindings(found);
2682
2834
  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`);
2835
+ console.log(`structure: ${count(structure.roots, "root")} \xB7 depth ${structure.depth}${structure.layers ? ` \xB7 ${count(structure.layers, "layer")}` : ""} \xB7 ${structure.parented}/${structure.nodes} parented \xB7 structure pressure ${structure.shape.peak.toFixed(3)} \xB7 ${structure.shape.assessed} assessed / ${structure.shape.unassessed} unassessed`);
2836
+ console.log(`tree: glassbrain tree ${shellArg(a2.pos[0])} --depth=3`);
2685
2837
  if (l.ignored.length) process.stderr.write(`note: not read: ${l.ignored.slice(0, 5).join(", ")}${l.ignored.length > 5 ? ` and ${l.ignored.length - 5} more` : ""}
2686
2838
  `);
2687
2839
  }
@@ -2711,19 +2863,14 @@ function runTree(a2) {
2711
2863
  function runRestructure(a2) {
2712
2864
  if (a2.pos.length !== 1) fail("restructure needs exactly one <path>");
2713
2865
  const l = load(a2.pos[0], { format: a2.flags.format });
2866
+ const blockers = lint(l).filter((f) => f.code === "duplicate-id" || f.code === "dangling-edge");
2867
+ if (blockers.length) fail(`repair identity/relation errors before restructure: ${blockers.map((f) => f.message).join("; ")}`, 1);
2714
2868
  const models = nodesOf(l);
2715
2869
  notes(l, models);
2716
2870
  const latest = models[models.length - 1];
2871
+ if (latest.errors.length) fail("repair parse errors before restructure", 1);
2717
2872
  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
- }));
2873
+ const nodes = planNodesOf(latest);
2727
2874
  const edges = phys.edges.map((e) => ({
2728
2875
  source: String(e.source),
2729
2876
  target: String(e.target),
@@ -2732,29 +2879,32 @@ function runRestructure(a2) {
2732
2879
  ...typeof e.weight === "number" ? { weight: e.weight } : {},
2733
2880
  data: e
2734
2881
  }));
2735
- const plan = restructure(nodes, edges);
2882
+ const ownName = (() => {
2883
+ if (l.raw.length !== 1 || l.raw[0].files.length !== 1) return null;
2884
+ try {
2885
+ const d = JSON.parse(l.raw[0].files[0].text);
2886
+ const n = typeof d.name === "string" ? d.name : typeof d.title === "string" ? d.title : null;
2887
+ return n?.trim() || null;
2888
+ } catch {
2889
+ return null;
2890
+ }
2891
+ })();
2892
+ const absIn = path2.resolve(a2.pos[0]);
2893
+ const isDir = fs2.existsSync(absIn) && fs2.statSync(absIn).isDirectory();
2894
+ const base2 = l.title.replace(/\.json$/i, "").split("/").pop() || "Overview";
2895
+ const fallback = !isDir && /^(graph|data|index|nodes|kg)$/i.test(base2) ? path2.basename(path2.dirname(absIn)) : base2;
2896
+ const plan = restructure(nodes, edges, { title: ownName ?? fallback, group: typeof a2.flags.group === "string" ? a2.flags.group.split(",") : void 0 });
2736
2897
  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));
2898
+ console.log(JSON.stringify({ before: plan.before, beforeFlat: plan.beforeFlat, after: plan.after, moves: plan.moves, wraps: plan.wraps, created: plan.created, removed: plan.removed, ladder: plan.ladder, suggestions: plan.suggestions, orders: plan.orders, note: plan.note }, null, 1));
2738
2899
  if (a2.flags["dry-run"]) return;
2739
2900
  } else {
2740
- console.log(planText(plan, l.title));
2901
+ console.log(planText(plan, l.title, shellArg(a2.pos[0])));
2741
2902
  if (a2.flags["dry-run"]) {
2742
2903
  console.log("\n(dry run: nothing written. Drop --dry-run to write a new pass.)");
2743
2904
  return;
2744
2905
  }
2745
2906
  }
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 };
2907
+ const graph = graphOf(plan, l.title, phys.edges);
2758
2908
  const abs = path2.resolve(a2.pos[0]);
2759
2909
  const dir = fs2.existsSync(abs) && fs2.statSync(abs).isDirectory() ? abs : path2.dirname(abs);
2760
2910
  const passes = fs2.existsSync(dir) ? fs2.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => /^(\d+)-/.exec(e.name)?.[1]).filter(Boolean).map(Number) : [];
@@ -2771,15 +2921,18 @@ function runRestructure(a2) {
2771
2921
  nodePalette: { ...palette, ...srcProfile.nodePalette ?? {} }
2772
2922
  };
2773
2923
  const passDir = l.versions.length > 1 || passes.length ? path2.join(dir, `${(passes.length ? Math.max(...passes) : 0) + 1}-restructured`) : path2.join(dir, `${path2.basename(abs, ".json") || "graph"}.restructured`);
2924
+ if (fs2.existsSync(path2.join(passDir, "graph.json"))) fail(`output already exists: ${passDir}; use a fresh input location or review the existing pass`);
2774
2925
  fs2.mkdirSync(passDir, { recursive: true });
2775
2926
  fs2.writeFileSync(path2.join(passDir, "_profile.json"), `${JSON.stringify(outProfile, null, 1)}
2776
2927
  `);
2777
2928
  const file = path2.join(passDir, "graph.json");
2778
2929
  fs2.writeFileSync(file, `${JSON.stringify(graph, null, 1)}
2779
2930
  `);
2780
- console.log(`
2931
+ if (!a2.flags.json) {
2932
+ console.log(`
2781
2933
  wrote ${file}`);
2782
- console.log(`next: glassbrain diff ${a2.pos[0]} ${file}`);
2934
+ console.log(`next: glassbrain diff ${a2.pos[0]} ${file}`);
2935
+ }
2783
2936
  }
2784
2937
  function runConvert(a2) {
2785
2938
  if (a2.pos.length < 1 || a2.pos.length > 2) fail("convert needs <path> [out-dir]");
@@ -2816,7 +2969,7 @@ if (a.flags.version) {
2816
2969
  process.stdout.write(HELP(path2.join(here, "../../schema/graph.schema.json")));
2817
2970
  } else {
2818
2971
  try {
2819
- ({ view, diff: runDiff, validate: runValidate, convert: runConvert, tree: runTree, restructure: runRestructure })[a.cmd](a);
2972
+ ({ view, diff: runDiff, lint: runLint, convert: runConvert, tree: runTree, restructure: runRestructure })[a.cmd](a);
2820
2973
  } catch (e) {
2821
2974
  fail(e.message, 2);
2822
2975
  }