glassbrain 0.1.3 → 0.2.0-alpha.1

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.
@@ -45,6 +45,55 @@ function addOrigin(list, origin) {
45
45
  function originsOfNode(n) {
46
46
  return n.origins?.length ? n.origins : n.origin ? [n.origin] : [];
47
47
  }
48
+ function indexModel(model) {
49
+ const parentOf = /* @__PURE__ */ new Map();
50
+ const childrenOf = /* @__PURE__ */ new Map();
51
+ for (const n of model.nodes) {
52
+ if (!n.parent) continue;
53
+ parentOf.set(n.id, n.parent);
54
+ const arr = childrenOf.get(n.parent);
55
+ arr ? arr.push(n.id) : childrenOf.set(n.parent, [n.id]);
56
+ }
57
+ const neighborsOf = /* @__PURE__ */ new Map();
58
+ for (const e of model.edges) {
59
+ for (const [a2, b] of [[e.source, e.target], [e.target, e.source]]) {
60
+ const arr = neighborsOf.get(a2);
61
+ arr ? arr.push(b) : neighborsOf.set(a2, [b]);
62
+ }
63
+ }
64
+ const depthMemo = /* @__PURE__ */ new Map();
65
+ const depthOf = (id, seen = /* @__PURE__ */ new Set()) => {
66
+ const hit = depthMemo.get(id);
67
+ if (hit != null) return hit;
68
+ seen.add(id);
69
+ const p = parentOf.get(id);
70
+ const d = p && !seen.has(p) ? depthOf(p, seen) + 1 : 1;
71
+ depthMemo.set(id, d);
72
+ return d;
73
+ };
74
+ const ancestorsOf = (id) => {
75
+ const out = [];
76
+ let p = parentOf.get(id);
77
+ while (p && !out.includes(p)) {
78
+ out.push(p);
79
+ p = parentOf.get(p);
80
+ }
81
+ return out;
82
+ };
83
+ const subtreeOf = (id) => {
84
+ const out = /* @__PURE__ */ new Set([id]);
85
+ const stack = [id];
86
+ while (stack.length) {
87
+ for (const c of childrenOf.get(stack.pop()) ?? []) {
88
+ if (out.has(c)) continue;
89
+ out.add(c);
90
+ stack.push(c);
91
+ }
92
+ }
93
+ return out;
94
+ };
95
+ return { parentOf, childrenOf, depthOf, ancestorsOf, subtreeOf, neighborsOf };
96
+ }
48
97
 
49
98
  // src/profile.ts
50
99
  function parsePhysical(origin, text) {
@@ -86,38 +135,6 @@ function toPhysical(model) {
86
135
  };
87
136
  }
88
137
  var DEFAULT_LAYER = { id: "default", label: "Graph", z: 0, structural: true };
89
- function validateStructure(model) {
90
- const out = [];
91
- const seen = /* @__PURE__ */ new Set();
92
- const dup = /* @__PURE__ */ new Set();
93
- for (const n of model.nodes) {
94
- if (seen.has(n.id)) dup.add(n.id);
95
- else seen.add(n.id);
96
- }
97
- for (const id of model.duplicateIds ?? []) dup.add(id);
98
- for (const id of dup) out.push({ kind: "duplicate", group: "Duplicate id", level: "warn", nodeId: id, message: `Duplicate node id: ${id} (defined more than once; the first one is kept)` });
99
- const seenEdge = /* @__PURE__ */ new Set();
100
- const dupEdge = /* @__PURE__ */ new Map();
101
- for (const e of model.edges) {
102
- const key = `${e.source}\0${e.target}\0${e.kind ?? ""}`;
103
- if (seenEdge.has(key)) dupEdge.set(key, e);
104
- else seenEdge.add(key);
105
- }
106
- for (const e of dupEdge.values()) {
107
- out.push({
108
- kind: "duplicate-edge",
109
- group: "Duplicate edge",
110
- level: "warn",
111
- edge: { source: e.source, target: e.target },
112
- message: `Duplicate edge: ${e.source} \u2192 ${e.target}${e.kind ? ` (${e.kind})` : ""} is defined more than once`
113
- });
114
- }
115
- for (const e of model.edges) {
116
- const miss = [!seen.has(e.source) && e.source, !seen.has(e.target) && e.target].filter(Boolean).join(" / ");
117
- if (miss) out.push({ kind: "dangling", group: "Dangling edge", level: "warn", edge: { source: e.source, target: e.target }, message: `Dangling edge: points to missing node ${miss}` });
118
- }
119
- return out;
120
- }
121
138
  function defineProfile(input) {
122
139
  const layers = input.layers?.length ? input.layers : [DEFAULT_LAYER];
123
140
  const fallbackLayer = layers[0].id;
@@ -735,18 +752,18 @@ function gitSpec(spec, cwd) {
735
752
  throw new Error(`${rel || "."} does not exist at ${ref}`);
736
753
  }
737
754
  if (type === "blob") return { files: [{ path: path.basename(rel), text: git("show", `${ref}:./${rel}`) }], title, isDir: false };
738
- const names = git("ls-tree", "-r", "--name-only", ref, "--", rel || ".").split("\n").filter(Boolean);
755
+ const names2 = git("ls-tree", "-r", "--name-only", ref, "--", rel || ".").split("\n").filter(Boolean);
739
756
  const prefix = rel ? `${rel}/` : "";
740
- const files = names.map((n) => n.split(path.sep).join("/")).filter((n) => DATA.test(n) && !n.split("/").some((s) => s.startsWith(".") && !DOT_OK.has(s) || SKIP_DIR.has(s))).slice(0, MAX_FILES).map((n) => ({ path: n.startsWith(prefix) ? n.slice(prefix.length) : n, text: git("show", `${ref}:./${n}`) }));
757
+ const files = names2.map((n) => n.split(path.sep).join("/")).filter((n) => DATA.test(n) && !n.split("/").some((s) => s.startsWith(".") && !DOT_OK.has(s) || SKIP_DIR.has(s))).slice(0, MAX_FILES).map((n) => ({ path: n.startsWith(prefix) ? n.slice(prefix.length) : n, text: git("show", `${ref}:./${n}`) }));
741
758
  return { files, title, isDir: true };
742
759
  }
743
760
  var META = /* @__PURE__ */ new Set(["_profile.json", "_layout.json"]);
744
761
  var natural = (a2, b) => a2.localeCompare(b, void 0, { numeric: true });
745
762
  function load(spec, opts = {}) {
746
- const tree = readSpec(spec, opts.cwd);
763
+ const tree2 = readSpec(spec, opts.cwd);
747
764
  const metaErrors = [];
748
765
  const meta = (name) => {
749
- const f = tree.files.find((x) => x.path === name);
766
+ const f = tree2.files.find((x) => x.path === name);
750
767
  if (!f) return null;
751
768
  try {
752
769
  return JSON.parse(f.text);
@@ -755,12 +772,12 @@ function load(spec, opts = {}) {
755
772
  return null;
756
773
  }
757
774
  };
758
- const data = tree.files.filter((f) => !META.has(f.path));
775
+ const data = tree2.files.filter((f) => !META.has(f.path));
759
776
  const isJson = (f) => /\.json$/i.test(f.path);
760
777
  const dirs = [...new Set(data.filter((f) => f.path.includes("/")).map((f) => f.path.split("/")[0]))].sort(natural);
761
- const versioned = tree.isDir && !opts.format && dirs.length >= 2 && !dirs.some((d) => DOT_OK.has(d)) && !data.some((f) => !f.path.includes("/") && isJson(f)) && dirs.every((d) => data.some((f) => f.path.startsWith(`${d}/`) && isJson(f)));
778
+ const versioned = tree2.isDir && !opts.format && dirs.length >= 2 && !dirs.some((d) => DOT_OK.has(d)) && !data.some((f) => !f.path.includes("/") && isJson(f)) && dirs.every((d) => data.some((f) => f.path.startsWith(`${d}/`) && isJson(f)));
762
779
  const ignored = versioned ? data.filter((f) => !isJson(f)).map((f) => f.path) : [];
763
- const groups = versioned ? dirs.map((d) => ({ name: d, files: data.filter((f) => f.path.startsWith(`${d}/`) && isJson(f)).map((f) => ({ ...f, path: f.path.slice(d.length + 1) })) })) : [{ name: tree.title, files: data }];
780
+ const groups = versioned ? dirs.map((d) => ({ name: d, files: data.filter((f) => f.path.startsWith(`${d}/`) && isJson(f)).map((f) => ({ ...f, path: f.path.slice(d.length + 1) })) })) : [{ name: tree2.title, files: data }];
764
781
  let suggested = null;
765
782
  let format = "native";
766
783
  const versions = groups.map((g) => {
@@ -773,7 +790,7 @@ function load(spec, opts = {}) {
773
790
  return { name: g.name, sources: r.sources };
774
791
  });
775
792
  return {
776
- title: tree.title,
793
+ title: tree2.title,
777
794
  versions,
778
795
  profile: meta("_profile.json") ?? suggested,
779
796
  layouts: meta("_layout.json"),
@@ -1143,6 +1160,310 @@ function checkSchema(root, value, limit = 50) {
1143
1160
  return out;
1144
1161
  }
1145
1162
 
1163
+ // cli/checks.ts
1164
+ var MAX_NAMES = 4;
1165
+ var MIN_SAMPLE = 10;
1166
+ var names = (xs) => `${xs.slice(0, MAX_NAMES).join(", ")}${xs.length > MAX_NAMES ? ` and ${xs.length - MAX_NAMES} more` : ""}`;
1167
+ var misplacedField = {
1168
+ code: "misplaced-field",
1169
+ level: "error",
1170
+ run: ({ model }) => {
1171
+ const reserved = ["id", "label", "kind", "parent", "layer", "description"];
1172
+ const out = [];
1173
+ for (const n of model.nodes) {
1174
+ const nested = n.data?.data;
1175
+ if (!nested || typeof nested !== "object" || Array.isArray(nested)) continue;
1176
+ const found = reserved.filter((k) => k in nested);
1177
+ if (!found.length) continue;
1178
+ out.push({ node: n.id, message: `"${n.id}" keeps ${found.map((k) => `"${k}"`).join(", ")} under "data"; only top-level fields are read` });
1179
+ }
1180
+ return out;
1181
+ }
1182
+ };
1183
+ var missingParent = {
1184
+ code: "missing-parent",
1185
+ level: "error",
1186
+ run: ({ model, index }) => model.nodes.filter((n) => n.parent && !index.has(n.parent)).map((n) => ({ node: n.id, message: `"${n.id}" sits inside "${n.parent}", which does not exist` }))
1187
+ };
1188
+ var parentCycle = {
1189
+ code: "parent-cycle",
1190
+ level: "error",
1191
+ run: ({ model, index }) => {
1192
+ const out = [];
1193
+ const done = /* @__PURE__ */ new Set();
1194
+ for (const start of model.nodes) {
1195
+ if (done.has(start.id)) continue;
1196
+ const path3 = [];
1197
+ const at = /* @__PURE__ */ new Map();
1198
+ let cur = start.id;
1199
+ while (cur && !done.has(cur)) {
1200
+ const seen = at.get(cur);
1201
+ if (seen !== void 0) {
1202
+ const loop = path3.slice(seen);
1203
+ loop.forEach((id) => done.add(id));
1204
+ out.push({ node: cur, message: `parent cycle: ${[...loop, cur].join(" \u2192 ")}` });
1205
+ break;
1206
+ }
1207
+ at.set(cur, path3.length);
1208
+ path3.push(cur);
1209
+ const parent = index.get(cur)?.parent;
1210
+ cur = parent && index.has(parent) ? parent : void 0;
1211
+ }
1212
+ for (const id of path3) done.add(id);
1213
+ }
1214
+ return out;
1215
+ }
1216
+ };
1217
+ var unknownLayer = {
1218
+ code: "unknown-layer",
1219
+ level: "error",
1220
+ run: ({ model, profile }) => {
1221
+ const declared = profile.layers.map((l) => l.id);
1222
+ const known = new Set(declared);
1223
+ return model.nodes.filter((n) => n.layer && !known.has(n.layer)).map((n) => ({ node: n.id, layer: n.layer, message: `layer "${n.layer}" is not declared (declared: ${declared.join(", ")})` }));
1224
+ }
1225
+ };
1226
+ var crossLayerParent = {
1227
+ code: "cross-layer-parent",
1228
+ level: "error",
1229
+ run: ({ model, index, layerOf }) => {
1230
+ const out = [];
1231
+ for (const n of model.nodes) {
1232
+ const parent = n.parent ? index.get(n.parent) : void 0;
1233
+ if (!parent || layerOf(parent) === layerOf(n)) continue;
1234
+ out.push({
1235
+ node: n.id,
1236
+ layer: layerOf(n),
1237
+ message: `"${n.id}" is on layer "${layerOf(n)}" but its parent "${parent.id}" is on "${layerOf(parent)}"; each layer is its own tree, layers connect by edges only`
1238
+ });
1239
+ }
1240
+ return out;
1241
+ }
1242
+ };
1243
+ var conflictingDefinition = {
1244
+ code: "conflicting-definition",
1245
+ level: "error",
1246
+ run: ({ model, index, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1247
+ node: id,
1248
+ message: `"${id}" is defined differently in ${names(index.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`
1249
+ }))
1250
+ };
1251
+ var danglingEdge = {
1252
+ code: "dangling-edge",
1253
+ level: "error",
1254
+ run: ({ model, index }) => {
1255
+ const out = [];
1256
+ for (const e of model.edges) {
1257
+ const missing = [!index.has(e.source) && e.source, !index.has(e.target) && e.target].filter(Boolean).join(" / ");
1258
+ if (missing) out.push({ message: `edge ${e.source} \u2192 ${e.target}${e.kind ? ` (${e.kind})` : ""} points at the missing node ${missing}` });
1259
+ }
1260
+ return out;
1261
+ }
1262
+ };
1263
+ var duplicateEdge = {
1264
+ code: "duplicate-edge",
1265
+ level: "warn",
1266
+ run: ({ model }) => {
1267
+ const times = /* @__PURE__ */ new Map();
1268
+ for (const e of model.edges) {
1269
+ const key = `${e.source}\0${e.target}\0${e.kind ?? ""}`;
1270
+ times.set(key, (times.get(key) ?? 0) + 1);
1271
+ }
1272
+ const out = [];
1273
+ for (const [key, count2] of times) {
1274
+ if (count2 < 2) continue;
1275
+ const [source, target, kind] = key.split("\0");
1276
+ out.push({ message: `edge ${source} \u2192 ${target}${kind ? ` (${kind})` : ""} is written ${count2} times; it is drawn once` });
1277
+ }
1278
+ return out;
1279
+ }
1280
+ };
1281
+ var multipleRoots = {
1282
+ code: "multiple-roots",
1283
+ level: "warn",
1284
+ run: ({ model, layerOf }) => {
1285
+ const tops = /* @__PURE__ */ new Map();
1286
+ for (const n of model.nodes) {
1287
+ if (n.parent) continue;
1288
+ const layer = layerOf(n);
1289
+ const arr = tops.get(layer);
1290
+ if (arr) arr.push(n);
1291
+ else tops.set(layer, [n]);
1292
+ }
1293
+ const out = [];
1294
+ for (const [layer, nodes] of tops) {
1295
+ if (nodes.length < 2) continue;
1296
+ out.push({
1297
+ layer,
1298
+ message: `layer "${layer}" has ${nodes.length} top-level nodes (${names(nodes.map((n) => n.label || n.id))}); it reads as ${nodes.length} separate trees, not one`
1299
+ });
1300
+ }
1301
+ return out;
1302
+ }
1303
+ };
1304
+ var preferFewerKinds = {
1305
+ code: "prefer-fewer-kinds",
1306
+ level: "info",
1307
+ run: ({ model }) => {
1308
+ const out = [];
1309
+ const spread = (space, counts, total) => {
1310
+ const kinds = counts.size;
1311
+ if (!kinds || total < MIN_SAMPLE) return;
1312
+ const average = total / kinds;
1313
+ if (kinds > 10 || average < 5) {
1314
+ out.push({ message: `${space} kinds: ${kinds} (${average.toFixed(1)} per kind); 10 kinds or 5 per kind reads better` });
1315
+ }
1316
+ };
1317
+ spread("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1318
+ spread("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1319
+ return out;
1320
+ }
1321
+ };
1322
+ var loneKind = {
1323
+ code: "lone-kind",
1324
+ level: "info",
1325
+ run: ({ model }) => {
1326
+ const out = [];
1327
+ const lone = (space, counts, total) => {
1328
+ if (total < MIN_SAMPLE) return;
1329
+ const once = [...counts].filter(([, c]) => c === 1).map(([k]) => k);
1330
+ if (once.length) out.push({ message: `${once.length} ${space} kind${once.length > 1 ? "s" : ""} used once: ${names(once)}` });
1331
+ };
1332
+ lone("node", countsBy(model.nodes.map((n) => n.kind)), model.nodes.length);
1333
+ lone("edge", countsBy(model.edges.map((e) => e.kind)), model.edges.length);
1334
+ return out;
1335
+ }
1336
+ };
1337
+ var preferFewerLayers = {
1338
+ code: "prefer-fewer-layers",
1339
+ level: "info",
1340
+ run: ({ model, layerOf }) => {
1341
+ const perLayer = /* @__PURE__ */ new Map();
1342
+ for (const n of model.nodes) perLayer.set(layerOf(n), (perLayer.get(layerOf(n)) ?? 0) + 1);
1343
+ const used = perLayer.size;
1344
+ const smallest = Math.min(...perLayer.values());
1345
+ if (used <= 5 && !(used > 3 && smallest < 3)) return [];
1346
+ return [{
1347
+ message: `${used} layers in use${used > 3 ? `, the smallest holds ${smallest}` : ""}; 2\u20135 is what a reader can hold, fewer when a layer holds almost nothing`
1348
+ }];
1349
+ }
1350
+ };
1351
+ var flatParent = {
1352
+ code: "flat-parent",
1353
+ level: "info",
1354
+ run: ({ children, labelOf }) => [...children].filter(([, kids]) => kids.length > 30).slice(0, 3).map(([id, kids]) => ({ node: id, message: `"${labelOf(id)}" holds ${kids.length} children; one more level of grouping reads better` }))
1355
+ };
1356
+ var lowCoverage = {
1357
+ code: "low-coverage",
1358
+ level: "info",
1359
+ run: ({ model, children }) => {
1360
+ const leaves = model.nodes.filter((n) => !children.has(n.id));
1361
+ if (leaves.length < 20) return [];
1362
+ const described = leaves.filter((n) => typeof n.data?.description === "string" && n.data.description.trim()).length;
1363
+ if (described / leaves.length >= 0.5) return [];
1364
+ return [{ message: `${leaves.length - described} of ${leaves.length} leaf nodes have no description` }];
1365
+ }
1366
+ };
1367
+ var colorsContrast = {
1368
+ code: "colors-contrast",
1369
+ level: "info",
1370
+ run: ({ profile }) => {
1371
+ const grays = Object.values(profile.nodePalette).map(hexGray).filter((g) => g !== null);
1372
+ if (grays.length < 4) return [];
1373
+ const e = entropy(grays);
1374
+ if (e >= 0.6) return [];
1375
+ return [{ message: `${grays.length} kind colors sit in few brightness bands (entropy ${e.toFixed(2)} < 0.60); neighboring kinds will read alike` }];
1376
+ }
1377
+ };
1378
+ var rules = [
1379
+ misplacedField,
1380
+ missingParent,
1381
+ parentCycle,
1382
+ unknownLayer,
1383
+ crossLayerParent,
1384
+ conflictingDefinition,
1385
+ danglingEdge,
1386
+ duplicateEdge,
1387
+ multipleRoots,
1388
+ preferFewerKinds,
1389
+ loneKind,
1390
+ preferFewerLayers,
1391
+ flatParent,
1392
+ lowCoverage,
1393
+ colorsContrast
1394
+ ];
1395
+ var RANK = { error: 0, warn: 1, info: 2 };
1396
+ function checkGraph(model, profile, opts) {
1397
+ const fallbackLayer = profile.layers[0].id;
1398
+ const children = /* @__PURE__ */ new Map();
1399
+ for (const n of model.nodes) {
1400
+ if (!n.parent || !model.index.has(n.parent)) continue;
1401
+ const arr = children.get(n.parent);
1402
+ if (arr) arr.push(n);
1403
+ else children.set(n.parent, [n]);
1404
+ }
1405
+ const ctx = {
1406
+ model,
1407
+ profile,
1408
+ where: opts.where,
1409
+ index: model.index,
1410
+ children,
1411
+ layerOf: (n) => n.layer ?? fallbackLayer,
1412
+ labelOf: (id) => model.index.get(id)?.label ?? id,
1413
+ sameFileDuplicates: opts.sameFileDuplicates ?? /* @__PURE__ */ new Set()
1414
+ };
1415
+ const out = rules.flatMap((rule) => rule.run(ctx).map((issue) => ({
1416
+ level: rule.level,
1417
+ code: rule.code,
1418
+ where: opts.where,
1419
+ message: issue.message,
1420
+ ...issue.node !== void 0 ? { node: issue.node } : {},
1421
+ ...issue.layer !== void 0 ? { layer: issue.layer } : {}
1422
+ })));
1423
+ return out.sort((a2, b) => RANK[a2.level] - RANK[b.level]);
1424
+ }
1425
+ function structureOf(model) {
1426
+ const index = indexModel(model);
1427
+ let depth = 0;
1428
+ let parented = 0;
1429
+ for (const n of model.nodes) {
1430
+ if (n.parent && model.index.has(n.parent)) parented++;
1431
+ depth = Math.max(depth, index.depthOf(n.id));
1432
+ }
1433
+ return {
1434
+ nodes: model.nodes.length,
1435
+ edges: model.edges.length,
1436
+ roots: model.nodes.filter((n) => !n.parent).length,
1437
+ depth,
1438
+ parented
1439
+ };
1440
+ }
1441
+ function countsBy(values) {
1442
+ const out = /* @__PURE__ */ new Map();
1443
+ for (const v of values) if (v) out.set(v, (out.get(v) ?? 0) + 1);
1444
+ return out;
1445
+ }
1446
+ function hexGray(value) {
1447
+ const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(value.trim());
1448
+ if (!m) return null;
1449
+ const hex = m[1].length === 3 ? [...m[1]].map((c) => c + c).join("") : m[1];
1450
+ const r = parseInt(hex.slice(0, 2), 16);
1451
+ const g = parseInt(hex.slice(2, 4), 16);
1452
+ const b = parseInt(hex.slice(4, 6), 16);
1453
+ return 0.299 * r + 0.587 * g + 0.114 * b;
1454
+ }
1455
+ function entropy(values) {
1456
+ const bins = new Array(16).fill(0);
1457
+ for (const v of values) bins[Math.min(15, Math.max(0, Math.floor(v / 16)))]++;
1458
+ let sum = 0;
1459
+ for (const count2 of bins) if (count2) {
1460
+ const p = count2 / values.length;
1461
+ sum -= p * Math.log2(p);
1462
+ }
1463
+ const max = Math.log2(Math.min(16, values.length));
1464
+ return max ? sum / max : 0;
1465
+ }
1466
+
1146
1467
  // cli/model.ts
1147
1468
  function profileFromJson(id, json) {
1148
1469
  if (!json) return defineProfile({ id });
@@ -1150,16 +1471,18 @@ function profileFromJson(id, json) {
1150
1471
  return defineProfile({ id, ...rest, kindLabels: { ...rest.kindLabels, ...edgeLabels } });
1151
1472
  }
1152
1473
  var modelOf = (v, profile) => parseSources(v.sources, profile);
1474
+ var RANK2 = { error: 0, warn: 1, info: 2 };
1153
1475
  function validate(loaded) {
1154
1476
  const out = [];
1155
1477
  const profile = profileFromJson("cli", loaded.profile);
1156
1478
  if (loaded.profile) {
1157
- for (const e of checkSchema(profile_schema_default, loaded.profile)) out.push({ level: "error", where: "_profile.json", message: `${e.path}: ${e.message}` });
1479
+ for (const e of checkSchema(profile_schema_default, loaded.profile)) out.push({ level: "error", code: "schema", where: "_profile.json", message: `${e.path}: ${e.message}` });
1158
1480
  }
1159
- for (const e of loaded.metaErrors) out.push({ level: "error", where: e.file, message: e.message });
1481
+ for (const e of loaded.metaErrors) out.push({ level: "error", code: "schema", where: e.file, message: e.message });
1160
1482
  for (const { version, files } of loaded.raw) {
1161
1483
  const prefix = loaded.versions.length > 1 ? `${version}/` : "";
1162
1484
  const notJson = /* @__PURE__ */ new Set();
1485
+ const sameFileDuplicates = /* @__PURE__ */ new Set();
1163
1486
  if (loaded.format === "native") {
1164
1487
  for (const f of files) {
1165
1488
  if (!/\.json$/i.test(f.path)) continue;
@@ -1168,45 +1491,35 @@ function validate(loaded) {
1168
1491
  doc = JSON.parse(f.text);
1169
1492
  } catch (e) {
1170
1493
  notJson.add(f.path);
1171
- out.push({ level: "error", where: prefix + f.path, message: `not JSON: ${e.message}` });
1494
+ out.push({ level: "error", code: "not-json", where: prefix + f.path, message: `not JSON: ${e.message}` });
1172
1495
  continue;
1173
1496
  }
1174
1497
  if (!doc || typeof doc !== "object" || !("nodes" in doc) && !("edges" in doc)) {
1175
- out.push({ level: "warn", where: prefix + f.path, message: 'not a graph (no "nodes" or "edges"), skipped' });
1498
+ out.push({ level: "warn", code: "not-a-graph", where: prefix + f.path, message: 'not a graph (no "nodes" or "edges"), skipped' });
1176
1499
  continue;
1177
1500
  }
1178
- for (const e of checkSchema(graph_schema_default, doc)) out.push({ level: "error", where: prefix + f.path, message: `${e.path}: ${e.message}` });
1501
+ for (const e of checkSchema(graph_schema_default, doc)) out.push({ level: "error", code: "schema", where: prefix + f.path, message: `${e.path}: ${e.message}` });
1502
+ const seen = /* @__PURE__ */ new Map();
1503
+ for (const id of idsIn(doc)) seen.set(id, (seen.get(id) ?? 0) + 1);
1504
+ for (const [id, count2] of seen) {
1505
+ if (count2 < 2) continue;
1506
+ sameFileDuplicates.add(id);
1507
+ 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` });
1508
+ }
1179
1509
  }
1180
1510
  }
1181
1511
  const v = loaded.versions.find((x) => x.name === version);
1182
1512
  const model = modelOf(v, profile);
1183
- for (const e of model.errors) if (!notJson.has(e.origin)) out.push({ level: "error", where: prefix + e.origin, message: e.message });
1184
- for (const i of [...validateStructure(model), ...structure(model)]) out.push({ level: i.level, where: prefix || loaded.title, message: i.message });
1185
- if (!model.nodes.length) out.push({ level: "warn", where: prefix || loaded.title, message: "No nodes found" });
1513
+ for (const e of model.errors) if (!notJson.has(e.origin)) out.push({ level: "error", code: "schema", where: prefix + e.origin, message: e.message });
1514
+ out.push(...checkGraph(model, profile, { where: prefix || loaded.title, sameFileDuplicates }));
1515
+ if (!model.nodes.length) out.push({ level: "warn", code: "empty", where: prefix || loaded.title, message: "No nodes found" });
1186
1516
  }
1187
- return out;
1517
+ return out.sort((a2, b) => RANK2[a2.level] - RANK2[b.level]);
1188
1518
  }
1189
- function structure(model) {
1190
- const out = [];
1191
- for (const n of model.nodes) {
1192
- if (n.parent && !model.index.has(n.parent)) {
1193
- out.push({ kind: "missing-parent", level: "warn", nodeId: n.id, message: `Missing parent: ${n.id} sits inside ${n.parent}, which does not exist (drawn at top level)` });
1194
- }
1195
- }
1196
- const reported = /* @__PURE__ */ new Set();
1197
- for (const n of model.nodes) {
1198
- const seen = [];
1199
- for (let p = n.id; p && !reported.has(p); p = model.index.get(p)?.parent) {
1200
- if (seen.includes(p)) {
1201
- const loop = seen.slice(seen.indexOf(p));
1202
- loop.forEach((x) => reported.add(x));
1203
- out.push({ kind: "parent-cycle", level: "error", nodeId: p, message: `Parent cycle: ${[...loop, p].join(" \u2192 ")}` });
1204
- break;
1205
- }
1206
- seen.push(p);
1207
- }
1208
- }
1209
- return out;
1519
+ function idsIn(doc) {
1520
+ const nodes = doc.nodes;
1521
+ if (!Array.isArray(nodes)) return [];
1522
+ return nodes.filter((n) => !!n && typeof n === "object" && "id" in n && n.id != null).map((n) => String(n.id));
1210
1523
  }
1211
1524
  var ignoreOf = (profile, extra = []) => [.../* @__PURE__ */ new Set([...Array.isArray(profile?.diffIgnore) ? profile.diffIgnore : [], ...extra])];
1212
1525
  function diff(before, after, labels, ignore = []) {
@@ -1270,80 +1583,266 @@ function diffText(s, labelOf, limit = 20) {
1270
1583
  return L.join("\n");
1271
1584
  }
1272
1585
 
1586
+ // cli/tree.ts
1587
+ var one = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1588
+ var MAX_SIBLINGS = 12;
1589
+ var MAX_LINES = 200;
1590
+ var MAX_EDGES = 6;
1591
+ function tree(model, profile, opts) {
1592
+ const fallbackLayer = profile.layers[0].id;
1593
+ const layerOf = (n) => n.layer ?? fallbackLayer;
1594
+ const labelOf = (id) => model.index.get(id)?.label ?? id;
1595
+ const depth = Math.max(1, opts.depth ?? 3);
1596
+ const perNode = Math.max(1, opts.perNode ?? MAX_SIBLINGS);
1597
+ const maxLines = Math.max(1, opts.maxLines ?? MAX_LINES);
1598
+ const kids = /* @__PURE__ */ new Map();
1599
+ for (const n of model.nodes) {
1600
+ if (!n.parent || !model.index.has(n.parent)) continue;
1601
+ const arr = kids.get(n.parent);
1602
+ if (arr) arr.push(n);
1603
+ else kids.set(n.parent, [n]);
1604
+ }
1605
+ const size = /* @__PURE__ */ new Map();
1606
+ const height = /* @__PURE__ */ new Map();
1607
+ const measuring = /* @__PURE__ */ new Set();
1608
+ const measure = (id) => {
1609
+ const hit = size.get(id);
1610
+ if (hit !== void 0) return hit;
1611
+ if (measuring.has(id)) return 1;
1612
+ measuring.add(id);
1613
+ let total = 1;
1614
+ let tall = 0;
1615
+ for (const k of kids.get(id) ?? []) {
1616
+ total += measure(k.id);
1617
+ tall = Math.max(tall, (height.get(k.id) ?? 0) + 1);
1618
+ }
1619
+ measuring.delete(id);
1620
+ size.set(id, total);
1621
+ height.set(id, tall);
1622
+ return total;
1623
+ };
1624
+ for (const n of model.nodes) measure(n.id);
1625
+ const bySize = (a2, b) => (size.get(b.id) ?? 1) - (size.get(a2.id) ?? 1) || labelOf(a2.id).localeCompare(labelOf(b.id));
1626
+ const sorted = /* @__PURE__ */ new Map();
1627
+ for (const [id, list] of kids) sorted.set(id, [...list].sort(bySize));
1628
+ const outgoing = /* @__PURE__ */ new Map();
1629
+ for (const e of model.edges) {
1630
+ if (!model.index.has(e.source) || !model.index.has(e.target)) continue;
1631
+ const item = `${e.kind ?? "\u2192"}::${labelOf(e.target)}`;
1632
+ const arr = outgoing.get(e.source);
1633
+ if (arr) arr.push(item);
1634
+ else outgoing.set(e.source, [item]);
1635
+ }
1636
+ for (const list of outgoing.values()) list.sort();
1637
+ const entries = [];
1638
+ const edgeText = (all) => `(${all.slice(0, MAX_EDGES).join(", ")}${all.length > MAX_EDGES ? ` \u2026 ${all.length - MAX_EDGES} more` : ""})`;
1639
+ const broken = (n) => n.parent && !model.index.has(n.parent);
1640
+ const visit = (node, level, prefix, connector) => {
1641
+ const list = sorted.get(node.id) ?? [];
1642
+ const canExpand = level + 1 < depth && list.length > 0;
1643
+ const collapsed = list.length > 0 && !canExpand;
1644
+ const inside = (size.get(node.id) ?? 1) - 1;
1645
+ const tall = height.get(node.id) ?? 0;
1646
+ const edges = collapsed ? [] : outgoing.get(node.id) ?? [];
1647
+ const bits = [];
1648
+ if (inside > 0) bits.push(one(inside, "node"));
1649
+ if (collapsed && tall > 0) bits.push(`${tall} deep`);
1650
+ if (edges.length) bits.push(edgeText(edges));
1651
+ const label = `${labelOf(node.id)}${broken(node) ? " (parent missing)" : ""}`;
1652
+ entries.push({
1653
+ id: node.id,
1654
+ label,
1655
+ depth: level,
1656
+ layer: layerOf(node),
1657
+ nodes: inside,
1658
+ deep: tall,
1659
+ collapsed,
1660
+ edges,
1661
+ text: `${prefix}${connector}${label}${bits.length ? ` ${bits.join(" \xB7 ")}` : ""}`
1662
+ });
1663
+ if (!canExpand) return;
1664
+ const shown = list.slice(0, perNode);
1665
+ const childPrefix = prefix + (level === 0 ? "" : connector.includes("\u2514") ? " " : "\u2502 ");
1666
+ shown.forEach((child, i) => {
1667
+ const last = i === shown.length - 1 && list.length <= perNode;
1668
+ visit(child, level + 1, childPrefix, last ? "\u2514\u2500 " : "\u251C\u2500 ");
1669
+ });
1670
+ if (list.length > perNode) {
1671
+ entries.push({
1672
+ id: null,
1673
+ label: `\u2026 ${list.length - perNode} more`,
1674
+ depth: level + 1,
1675
+ nodes: 0,
1676
+ deep: 0,
1677
+ collapsed: false,
1678
+ edges: [],
1679
+ text: `${childPrefix}\u2514\u2500 \u2026 ${list.length - perNode} more`
1680
+ });
1681
+ }
1682
+ };
1683
+ const structure = structureOf(model);
1684
+ let header = `${opts.title} ${one(structure.nodes, "node")} \xB7 ${one(structure.edges, "edge")} \xB7 ${one(structure.roots, "root")} \xB7 depth ${structure.depth}`;
1685
+ const roots = model.nodes.filter((n) => !n.parent || broken(n));
1686
+ if (opts.path) {
1687
+ const start = model.index.get(opts.path);
1688
+ if (!start) throw new Error(`no node "${opts.path}" in ${opts.title}`);
1689
+ const chain = [];
1690
+ let up = start.parent;
1691
+ const seen = /* @__PURE__ */ new Set([start.id]);
1692
+ while (up && model.index.has(up) && !seen.has(up)) {
1693
+ seen.add(up);
1694
+ chain.unshift(labelOf(up));
1695
+ up = model.index.get(up)?.parent;
1696
+ }
1697
+ header += `
1698
+ path: ${[...chain, labelOf(start.id)].join(" \u203A ")}`;
1699
+ visit(start, 0, "", "");
1700
+ } else if (opts.orphans) {
1701
+ for (const n of roots.slice(0, perNode)) {
1702
+ const inside = (size.get(n.id) ?? 1) - 1;
1703
+ const label = `${labelOf(n.id)}${broken(n) ? " (parent missing)" : ""}`;
1704
+ entries.push({
1705
+ id: n.id,
1706
+ label,
1707
+ depth: 0,
1708
+ layer: layerOf(n),
1709
+ nodes: inside,
1710
+ deep: height.get(n.id) ?? 0,
1711
+ collapsed: true,
1712
+ edges: [],
1713
+ text: `${label}${inside ? ` ${one(inside, "node")}` : ""}`
1714
+ });
1715
+ }
1716
+ if (roots.length > perNode) {
1717
+ entries.push({ id: null, label: `\u2026 ${roots.length - perNode} more`, depth: 0, nodes: 0, deep: 0, collapsed: false, edges: [], text: `\u2026 ${roots.length - perNode} more` });
1718
+ }
1719
+ } else {
1720
+ const shown = roots.slice(0, perNode);
1721
+ shown.forEach((root) => visit(root, 0, "", ""));
1722
+ if (roots.length > perNode) {
1723
+ entries.push({ id: null, label: `\u2026 ${roots.length - perNode} more`, depth: 0, nodes: 0, deep: 0, collapsed: false, edges: [], text: `\u2026 ${roots.length - perNode} more roots` });
1724
+ }
1725
+ }
1726
+ const more = Math.max(0, entries.length - maxLines);
1727
+ return { header, entries: more ? entries.slice(0, maxLines) : entries, more };
1728
+ }
1729
+ function treeText(result) {
1730
+ const lines = [result.header, ...result.entries.map((e) => e.text)];
1731
+ if (result.more) lines.push(`\u2026 ${result.more} more lines (raise --depth, or narrow with --path <id>)`);
1732
+ return lines.join("\n");
1733
+ }
1734
+
1273
1735
  // cli/glassbrain.ts
1274
- var HELP = (schema) => `glassbrain: open, diff and validate knowledge graphs.
1275
- Your agent writes the graph as plain JSON; glassbrain shows it and what changed.
1276
- Not installed? Put npx in front: npx glassbrain kg
1736
+ var HELP = (schema) => `glassbrain: open, diff and validate a knowledge graph, written as plain JSON.
1737
+
1738
+ [ THE THREE AXES ]
1739
+ Different things. Do not use one where another belongs.
1740
+ pass a snapshot in time \u2014 one folder per pass (1-skeleton/, 2-filled/)
1741
+ parent containment \u2014 what sits inside what (see [ DATA ])
1742
+ layer a plane in 2.5D \u2014 levels or parallel bands (see [ APPEARANCE ])
1743
+
1744
+ [ DATA ]
1745
+ Two arrays. The \`//\` notes are not part of the file: strip them and it is valid JSON
1746
+ (if validate says \`not JSON\`, a note survived the copy).
1277
1747
 
1278
- WRITE A GRAPH
1279
- One JSON file, two arrays. \`parent\` says what sits inside what; that is the
1280
- whole structure. Every other relation is an edge.
1748
+ { "nodes": [
1749
+ { "id": "src", "label": "src", "kind": "folder" }, // required, stable, not a counter
1750
+ { "id": "src/login.ts", "label": "login.ts", "kind": "file",
1751
+ "parent": "src", // top level: what it sits inside
1752
+ "description": "Checks the password, then opens a session.", // markdown, from the source
1753
+ "owner": "auth" }, // any other field: kept, shown
1754
+ { "id": "src/db.ts", "label": "db.ts", "kind": "file", "parent": "src" } ],
1755
+ "edges": [
1756
+ { "source": "src/login.ts", "target": "src/db.ts", "kind": "uses" } ] }
1281
1757
 
1282
- { "nodes": [
1283
- { "id": "src", "label": "src", "kind": "folder" },
1284
- { "id": "src/login.ts", "label": "login.ts", "kind": "file", "parent": "src",
1285
- "description": "Checks the password, then opens a session. Markdown." },
1286
- { "id": "src/db.ts", "label": "db.ts", "kind": "file", "parent": "src" } ],
1287
- "edges": [
1288
- { "source": "src/login.ts", "target": "src/db.ts", "kind": "uses" } ] }
1758
+ \`parent\` is read only as a top-level field. Nested (\`data.parent\`) it is shown and
1759
+ nothing else. \`kind\` gives the color; \`description\` is what the panel says.
1760
+
1761
+ SHAPE how a graph reads (validate names what is off)
1762
+ one root per layer, every other node has a parent (warn: multiple-roots)
1763
+ at most 8 node kinds and 10 edge kinds, each used 5+ (info: prefer-fewer-kinds)
1764
+ a container with more than 30 children wants a level (info: flat-parent)
1765
+ describe the leaves; under half described is noted (info: low-coverage)
1289
1766
 
1290
- id any string, stable across versions: a path or a slug, never a counter
1291
- label what is shown (defaults to id)
1292
- kind any word for what sort of thing it is (folder, page, feature, decision)
1293
- parent the id of the node it sits inside
1294
- description markdown for the detail panel; [text](node:<id>) links to a node
1295
- flags markers, e.g. ["stub"] for a node not filled in yet
1296
- Order in the arrays does not matter. Other fields are kept and shown in the detail panel.
1297
1767
  Full schema: ${schema}
1298
1768
 
1299
- BUILD IT IN PASSES
1300
- Each pass is a new folder: copy the last one, edit the copy.
1301
- kg/1-skeleton every node at the depth asked (or what a newcomer needs), read from
1302
- the source (not memory), nested by parent; flag each one "stub"
1303
- kg/2-filled descriptions (1-3 sentences, from the source), stub flags removed
1304
- kg/3-linked edges a reader would agree with
1305
- After each pass:
1306
- glassbrain validate kg --strict fix everything it reports
1307
- glassbrain diff kg/1-skeleton kg/2-filled only this pass's job: ~changed in 2,
1308
- edges added in 3, nothing else
1309
- At the end:
1310
- glassbrain kg opens all passes; give the user the path
1769
+ [ STRUCTURE ]
1770
+ A folder is a graph. Passes are optional; one numbered folder each.
1771
+
1772
+ kg/
1773
+ \u251C\u2500\u2500 _profile.json colors and layers, shared by every pass (see [ APPEARANCE ])
1774
+ \u251C\u2500\u2500 1-skeleton/graph.json a graph (see [ DATA ])
1775
+ \u251C\u2500\u2500 2-filled/graph.json each pass is the whole graph: copy the last, edit the copy
1776
+ \u2514\u2500\u2500 3-linked/graph.json then validate, and diff against the pass before
1777
+
1778
+ Files inside one pass merge by id: the same node described twice is one node.
1779
+ Two files defining that id differently is an error, not a merge.
1780
+ Split by area only when a file gets too big to write.
1781
+
1782
+ [ APPEARANCE ]
1783
+ kg/_profile.json, shared by every pass. Everything in it is optional.
1311
1784
 
1312
- COLORS: kg/_profile.json, shared by every pass
1313
- Give each kind a color, or every node and edge is drawn the same grey:
1314
- { "nodePalette": { "file": "#6366f1", "function": "#10b981" },
1315
- "edgePalette": { "calls": "#2563eb" }, "placeholderFlags": ["stub"] }
1316
- Layers (2.5D), sizes, labels and the rest: ${schema.replace("graph.schema", "profile.schema")}
1785
+ COLORS one entry per kind you use; unlisted kinds stay neutral.
1786
+ { "nodePalette": { "file": "#6366f1", "folder": "#94a3b8" },
1787
+ "edgePalette": { "uses": "#2563eb" } }
1788
+ Colors that land in one brightness band read alike (validate notes it).
1317
1789
 
1318
- COMMANDS
1319
- glassbrain <path> open in the browser (same as: view)
1320
- glassbrain diff <old> <new> what changed between two graphs
1321
- glassbrain diff <git-ref> <path> <path> at that commit vs. now (default ref: HEAD)
1322
- glassbrain validate <path> check against the schema and the structure
1790
+ LAYERS planes, not folders: \`parent\` is "sits inside", \`layer\` is "belongs to another
1791
+ level of the same picture".
1792
+ A node joins one with "layer"; missing means the first. 2-5 planes:
1793
+ a code graph 1 data \xB7 2 API \xB7 3 interface
1794
+ a topic graph 1 background \xB7 2 the thing \xB7 3 readings of it
1795
+ Fewer when a plane holds one or two nodes; more than 5 stops being an outline.
1796
+ { "layers": [ { "id": "api", "label": "API", "z": 0 },
1797
+ { "id": "ui", "label": "UI", "z": 1 } ] }
1798
+ Each plane is its own tree: a node's parent must be on the same layer (error).
1799
+
1800
+ Full schema: ${schema.replace("graph.schema", "profile.schema")}
1801
+
1802
+ [ COMMANDS ]
1803
+ Always validate before handing over; a page is only written for a graph with no errors.
1804
+
1805
+ glassbrain <path> write one html page, print its path (passes play as steps)
1806
+ glassbrain validate <path> errors, warnings, info; exit 1 on errors
1807
+ glassbrain tree <path> the containment tree as text
1808
+ glassbrain diff <old> <new> only what changed between two graphs
1809
+ glassbrain diff <git-ref> <path> the same graph at an earlier commit (default HEAD)
1323
1810
  glassbrain convert <path> [out-dir] write any supported format as glassbrain JSON
1324
1811
 
1325
- <path> is a file, a folder, or <git-ref>:<path> (HEAD~1:kg/graph.json).
1326
- A folder of sub-folders is a list of versions. Also opens, as they are:
1327
- Graphify graph.json, Understand-Anything knowledge-graph.json, MCP memory.jsonl,
1328
- a markdown folder (Obsidian / LLM wiki).
1812
+ <path> is a file, a folder, or <git-ref>:<path> (HEAD~1:kg/graph.json). Graphify,
1813
+ Understand-Anything, memory.jsonl and markdown folders are read as-is.
1814
+
1815
+ validate speaks in three levels:
1816
+ error broken schema, an id twice, a parent missing / on another layer / in a
1817
+ cycle, an edge to a missing node, two files defining one id apart
1818
+ warn discouraged several roots in one layer, one relation written twice
1819
+ info distribution kinds, flat parents, empty leaves, layer count, color contrast
1820
+ exit codes: 0 clean \xB7 1 errors (--strict: warnings too) \xB7 2 usage.
1821
+ It always ends with the structure and the tree command for that graph.
1329
1822
 
1330
- OPTIONS
1331
- --json machine-readable output (diff, validate)
1332
- --strict exit 1 on warnings too (validate)
1823
+ [ OPTIONS ]
1824
+ --json machine-readable output (validate, tree, diff)
1825
+ --strict warnings fail too (validate, view)
1826
+ --depth <n> tree: levels to expand (default 3)
1827
+ --path <id> tree: one node, its ancestors and its subtree
1828
+ --orphans tree: only nodes with no parent
1829
+ --out <file.html> write the page here instead of a temp file (view, diff)
1830
+ --open / --no-open open the browser or not (diff opens only in a terminal)
1333
1831
  --exit-code exit 1 when anything changed (diff)
1334
1832
  --all list every change, not the first 20 (diff)
1335
1833
  --ignore <a,b> fields that do not count as a change (diff)
1336
- --out <file.html> write the page here instead of a temp file (view, diff)
1337
- --open / --no-open open the browser or not (diff opens only in a terminal)
1338
1834
  --format <id> force a format: native, graphify, understand-anything, memory, obsidian
1339
- -h, --help this help
1340
- -v, --version the version
1835
+ -h, --help / -v, --version this help / the version
1341
1836
 
1342
- More: https://github.com/voidixyn/glassbrain
1837
+ [ SKILLS ]
1838
+ Optional fixed workflows (a codebase, docs into features):
1839
+ https://github.com/voidixyn/glassbrain/tree/main/skills
1840
+ npx skills add voidixyn/glassbrain
1841
+ Help alone is enough to write, validate and read a graph.
1343
1842
  `;
1344
- var VALUED = /* @__PURE__ */ new Set(["out", "format", "ignore"]);
1345
- var SWITCHES = /* @__PURE__ */ new Set(["open", "json", "all", "exit-code", "strict", "help", "version"]);
1346
- var COMMANDS = ["view", "diff", "validate", "convert"];
1843
+ var VALUED = /* @__PURE__ */ new Set(["out", "format", "ignore", "depth", "path"]);
1844
+ var SWITCHES = /* @__PURE__ */ new Set(["open", "json", "all", "exit-code", "strict", "help", "version", "orphans"]);
1845
+ var COMMANDS = ["view", "diff", "validate", "convert", "tree"];
1347
1846
  function parseArgs(argv) {
1348
1847
  const pos = [];
1349
1848
  const flags = {};
@@ -1390,6 +1889,16 @@ function writePage(payload, out) {
1390
1889
  return file;
1391
1890
  }
1392
1891
  var count = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
1892
+ var TAG = { error: "error", warn: "warn ", info: "info " };
1893
+ var tally = (found) => ({
1894
+ error: found.filter((f) => f.level === "error").length,
1895
+ warn: found.filter((f) => f.level === "warn").length,
1896
+ info: found.filter((f) => f.level === "info").length
1897
+ });
1898
+ function printFindings(found, limit = 40) {
1899
+ for (const f of found.slice(0, limit)) console.log(`${TAG[f.level]} ${f.code} ${f.where} ${f.message}`);
1900
+ if (found.length > limit) console.log(`\u2026 ${found.length - limit} more (--json)`);
1901
+ }
1393
1902
  var slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "graph";
1394
1903
  function openFile(file) {
1395
1904
  const [cmd, args] = process.platform === "darwin" ? ["open", [file]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", file]] : ["xdg-open", [file]];
@@ -1419,9 +1928,23 @@ function view(a2) {
1419
1928
  const l = load(a2.pos[0], { format: a2.flags.format });
1420
1929
  const models = nodesOf(l);
1421
1930
  notes(l, models);
1931
+ const found = validate(l);
1932
+ const n = tally(found);
1933
+ if (n.error || a2.flags.strict && n.warn) {
1934
+ console.log(summaryOf(l, models[models.length - 1]));
1935
+ printFindings(found);
1936
+ console.log(`
1937
+ ${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \u2014 page not written. Fix them, then validate again.`);
1938
+ process.exitCode = 1;
1939
+ return;
1940
+ }
1422
1941
  const file = writePage({ title: l.title, profile: l.profile, versions: l.versions, layouts: l.layouts, start: { at: l.versions.length - 1, compare: false } }, a2.flags.out);
1423
1942
  console.log(summaryOf(l, models[models.length - 1]));
1424
1943
  console.log(file);
1944
+ if (n.warn) {
1945
+ printFindings(found.filter((f) => f.level === "warn"));
1946
+ console.log(`${count(n.warn, "warning")} (not blocking; \`glassbrain validate\` has the details)`);
1947
+ }
1425
1948
  if (a2.flags.open !== false) openFile(file);
1426
1949
  }
1427
1950
  function sides(pos) {
@@ -1478,19 +2001,54 @@ function runValidate(a2) {
1478
2001
  if (a2.pos.length !== 1) fail("validate needs exactly one <path>");
1479
2002
  const l = load(a2.pos[0], { format: a2.flags.format });
1480
2003
  const found = validate(l);
1481
- const errors = found.filter((f) => f.level === "error").length;
1482
- const warns = found.length - errors;
1483
2004
  const models = nodesOf(l);
2005
+ const latest = models[models.length - 1];
2006
+ const n = tally(found);
2007
+ const structure = structureOf(latest);
2008
+ const failing = n.error > 0 || a2.flags.strict && n.warn > 0;
1484
2009
  if (a2.flags.json) {
1485
- console.log(JSON.stringify({ format: l.format, ignored: l.ignored, versions: l.versions.map((v, i) => ({ name: v.name, nodes: models[i].nodes.length, edges: models[i].edges.length })), errors, warnings: warns, issues: found }, null, 1));
2010
+ console.log(JSON.stringify({
2011
+ format: l.format,
2012
+ ignored: l.ignored,
2013
+ versions: l.versions.map((v, i) => ({ name: v.name, nodes: models[i].nodes.length, edges: models[i].edges.length })),
2014
+ errors: n.error,
2015
+ warnings: n.warn,
2016
+ infos: n.info,
2017
+ structure,
2018
+ issues: found
2019
+ }, null, 1));
1486
2020
  } else {
1487
- for (const f of found.slice(0, 200)) console.log(`${f.level === "error" ? "error" : "warn "} ${f.where} ${f.message}`);
1488
- if (found.length > 200) console.log(`\u2026 ${found.length - 200} more`);
2021
+ console.log(summaryOf(l, latest));
2022
+ if (found.length) console.log("");
2023
+ printFindings(found);
2024
+ console.log(`${count(n.error, "error")} \xB7 ${count(n.warn, "warning")} \xB7 ${count(n.info, "info")}`);
2025
+ console.log(`structure: ${count(structure.roots, "root")} \xB7 depth ${structure.depth} \xB7 ${structure.parented}/${structure.nodes} parented`);
2026
+ console.log(`tree: glassbrain tree ${a2.pos[0]} --depth=3`);
1489
2027
  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` : ""}
1490
2028
  `);
1491
- console.log(`${found.length ? "\n" : ""}${summaryOf(l, models[models.length - 1])} \u2014 ${count(errors, "error")}, ${count(warns, "warning")}`);
1492
2029
  }
1493
- if (errors || a2.flags.strict && warns) process.exitCode = 1;
2030
+ if (failing) process.exitCode = 1;
2031
+ }
2032
+ function runTree(a2) {
2033
+ if (a2.pos.length !== 1) fail("tree needs exactly one <path>");
2034
+ const depth = a2.flags.depth === void 0 ? 3 : Number(a2.flags.depth);
2035
+ if (!Number.isInteger(depth) || depth < 1) fail("--depth needs a positive integer");
2036
+ const l = load(a2.pos[0], { format: a2.flags.format });
2037
+ const models = nodesOf(l);
2038
+ notes(l, models);
2039
+ const latest = models[models.length - 1];
2040
+ const version = l.versions[l.versions.length - 1].name;
2041
+ const result = tree(latest, profileFromJson("cli", l.profile), {
2042
+ title: l.versions.length > 1 ? `${l.title}/${version}` : l.title,
2043
+ depth,
2044
+ path: typeof a2.flags.path === "string" ? a2.flags.path : void 0,
2045
+ orphans: a2.flags.orphans === true
2046
+ });
2047
+ if (a2.flags.json) {
2048
+ console.log(JSON.stringify({ title: l.title, ...structureOf(latest), entries: result.entries, more: result.more }, null, 1));
2049
+ } else {
2050
+ console.log(treeText(result));
2051
+ }
1494
2052
  }
1495
2053
  function runConvert(a2) {
1496
2054
  if (a2.pos.length < 1 || a2.pos.length > 2) fail("convert needs <path> [out-dir]");
@@ -1526,7 +2084,7 @@ if (a.flags.version) {
1526
2084
  process.stdout.write(HELP(path2.join(here, "../../schema/graph.schema.json")));
1527
2085
  } else {
1528
2086
  try {
1529
- ({ view, diff: runDiff, validate: runValidate, convert: runConvert })[a.cmd](a);
2087
+ ({ view, diff: runDiff, validate: runValidate, convert: runConvert, tree: runTree })[a.cmd](a);
1530
2088
  } catch (e) {
1531
2089
  fail(e.message, 2);
1532
2090
  }