glassbrain 0.2.0-alpha.4 → 0.2.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,6 +15,10 @@ function buildModel(nodes, edges, errors = []) {
15
15
  return { nodes, edges, errors, index };
16
16
  }
17
17
  function mergeSlices(slices) {
18
+ if (slices.some((s) => s.declarations?.length) || slices.every((s) => !s.nodes.length)) return composeTrees(slices);
19
+ return mergeRuntimeSlices(slices);
20
+ }
21
+ function mergeRuntimeSlices(slices) {
18
22
  const byId = /* @__PURE__ */ new Map();
19
23
  const edges = [];
20
24
  const errors = [];
@@ -94,18 +98,177 @@ function indexModel(model) {
94
98
  };
95
99
  return { parentOf, childrenOf, depthOf, ancestorsOf, subtreeOf, neighborsOf };
96
100
  }
97
- function encodeParent(parent, order) {
98
- if (!parent) return null;
99
- if (order === void 0) return `${parent}@-1`;
100
- if (!Number.isFinite(order) || order <= 0) throw new Error("order must be finite and positive");
101
- const text = String(order);
102
- if (!/[eE]/.test(text)) return `${parent}@${text}`;
103
- const [mantissa, exponent] = text.toLowerCase().split("e");
104
- const [whole, fraction = ""] = mantissa.split(".");
105
- const digits = whole + fraction;
106
- const at = whole.length + Number(exponent);
107
- const decimal = at <= 0 ? `0.${"0".repeat(-at)}${digits}` : at >= digits.length ? digits + "0".repeat(at - digits.length) : `${digits.slice(0, at)}.${digits.slice(at)}`;
108
- return `${parent}@${decimal}`;
101
+
102
+ // src/tree.ts
103
+ var object = (x) => !!x && typeof x === "object" && !Array.isArray(x);
104
+ var ref = (x) => typeof x === "string" || typeof x === "number" ? String(x) : void 0;
105
+ var stable = (x) => JSON.stringify(x, function(_key, value) {
106
+ return object(value) ? Object.fromEntries(Object.keys(value).sort().map((k) => [k, value[k]])) : value;
107
+ });
108
+ function treeDeclarations(raw, origin) {
109
+ const declarations = [];
110
+ const rootIds = [];
111
+ const problems = [];
112
+ const stack = (Array.isArray(raw) ? raw : []).map((node, i) => ({ node, path: `nodes[${i}]`, top: true })).reverse();
113
+ if (raw !== void 0 && !Array.isArray(raw)) problems.push("nodes must be an array");
114
+ while (stack.length) {
115
+ const { node, path: path3, top } = stack.pop();
116
+ if (!object(node) || ref(node.id) === void 0) {
117
+ problems.push(`${path3}: expected a node with id`);
118
+ continue;
119
+ }
120
+ const id = ref(node.id);
121
+ if (!id.trim()) problems.push(`${path3}.id: expected a non-empty identity`);
122
+ if (top) rootIds.push(id);
123
+ const { children, ...fields } = node;
124
+ if ("parent" in node || "order" in node) problems.push(`${path3}: parent/order are not supported; nest nodes in children`);
125
+ if ("unordered" in node && typeof node.unordered !== "boolean") problems.push(`${path3}.unordered must be a boolean`);
126
+ const declaration = { id, fields: { ...fields, id }, path: `${origin}:${path3}` };
127
+ if ("children" in node) {
128
+ if (!Array.isArray(children)) problems.push(`${path3}.children must be an array`);
129
+ else {
130
+ declaration.children = children.filter(object).map((n) => ref(n.id)).filter((id2) => id2 !== void 0);
131
+ for (let i = children.length - 1; i >= 0; i--) stack.push({ node: children[i], path: `${path3}.children[${i}]`, top: false });
132
+ }
133
+ }
134
+ declarations.push(declaration);
135
+ }
136
+ return { declarations, rootIds, ...problems.length ? { error: problems.slice(0, 20).join("; ") } : {} };
137
+ }
138
+ function treeNodes(declarations = []) {
139
+ const placements = /* @__PURE__ */ new Map();
140
+ for (const d of declarations) d.children?.forEach((id, i) => placements.set(id, { parent: d.id, order: i + 1 }));
141
+ return declarations.map(({ id, fields }) => ({
142
+ id,
143
+ ...placements.get(id),
144
+ label: String(fields.label ?? fields.name ?? id),
145
+ ...typeof fields.kind === "string" ? { kind: fields.kind } : {},
146
+ ...Array.isArray(fields.flags) ? { flags: fields.flags.filter((f) => typeof f === "string") } : {},
147
+ data: fields
148
+ }));
149
+ }
150
+ function composeTrees(input) {
151
+ const slices = [...input].sort((a2, b) => a2.origin < b.origin ? -1 : a2.origin > b.origin ? 1 : 0);
152
+ const errors = [];
153
+ const records = /* @__PURE__ */ new Map();
154
+ const roots = [];
155
+ for (const slice of slices) {
156
+ if (slice.error) errors.push({ origin: slice.origin, code: "schema", message: slice.error });
157
+ if (!slice.declarations && slice.nodes.length) {
158
+ errors.push({ origin: slice.origin, code: "schema", message: "Cannot compose flat runtime slices with native children fragments." });
159
+ continue;
160
+ }
161
+ roots.push(...slice.rootIds ?? []);
162
+ for (const d of slice.declarations ?? []) {
163
+ let r = records.get(d.id);
164
+ if (!r) {
165
+ r = { fields: /* @__PURE__ */ Object.create(null), locations: /* @__PURE__ */ new Map(), origins: [] };
166
+ records.set(d.id, r);
167
+ }
168
+ if (!r.origins.includes(slice.origin)) r.origins.push(slice.origin);
169
+ for (const [field, value] of [...Object.entries(d.fields), ...d.children === void 0 ? [] : [["children", d.children]]]) {
170
+ const previous = field === "children" ? r.children : r.fields[field];
171
+ if (r.locations.has(field) && stable(previous) !== stable(value)) {
172
+ errors.push({
173
+ origin: slice.origin,
174
+ node: d.id,
175
+ code: field === "children" ? "children-conflict" : "field-conflict",
176
+ message: `"${d.id}".${field}: ${r.locations.get(field)} = ${stable(previous)} conflicts with ${d.path} = ${stable(value)}; provide one consistent value (lists are not combined).`
177
+ });
178
+ } else if (!r.locations.has(field)) {
179
+ if (field === "children") r.children = value;
180
+ else r.fields[field] = value;
181
+ r.locations.set(field, d.path);
182
+ }
183
+ }
184
+ }
185
+ }
186
+ const parents = /* @__PURE__ */ new Map();
187
+ const positions = /* @__PURE__ */ new Map();
188
+ for (const [id, r] of records) {
189
+ const seen = /* @__PURE__ */ new Set();
190
+ for (const [i, child] of (r.children ?? []).entries()) {
191
+ if (seen.has(child)) errors.push({ origin: r.origins[0], node: id, code: "children-conflict", message: `${r.locations.get("children")}: "${child}" occurs twice in children of "${id}".` });
192
+ seen.add(child);
193
+ const old = parents.get(child);
194
+ if (old !== void 0 && old !== id) {
195
+ errors.push({ origin: r.origins[0], node: child, code: "parent-error", message: `"${child}" has two parents: "${old}" (${records.get(old).locations.get("children")}) and "${id}" (${r.locations.get("children")}). Keep one placement.` });
196
+ } else {
197
+ parents.set(child, id);
198
+ positions.set(child, i + 1);
199
+ }
200
+ }
201
+ }
202
+ const done = /* @__PURE__ */ new Set();
203
+ for (const id of records.keys()) {
204
+ const chain = [], at = /* @__PURE__ */ new Map();
205
+ let cur = id;
206
+ while (cur !== void 0 && !done.has(cur)) {
207
+ if (at.has(cur)) {
208
+ const loop = [...chain.slice(at.get(cur)), cur];
209
+ errors.push({ origin: records.get(cur).origins[0], node: cur, code: "parent-error", message: `parent cycle: ${loop.join(" \u2192 ")}. Remove one children placement.` });
210
+ parents.delete(cur);
211
+ positions.delete(cur);
212
+ break;
213
+ }
214
+ at.set(cur, chain.length);
215
+ chain.push(cur);
216
+ cur = parents.get(cur);
217
+ }
218
+ chain.forEach((x) => done.add(x));
219
+ }
220
+ const orderedRoots = [.../* @__PURE__ */ new Set([...roots, ...records.keys()])].filter((id) => !parents.has(id));
221
+ const ordered = [], visited = /* @__PURE__ */ new Set(), stack = [...orderedRoots].reverse();
222
+ while (stack.length) {
223
+ const id = stack.pop();
224
+ if (visited.has(id) || !records.has(id)) continue;
225
+ visited.add(id);
226
+ ordered.push(id);
227
+ const kids = records.get(id).children ?? [];
228
+ for (let i = kids.length - 1; i >= 0; i--) if (parents.get(kids[i]) === id) stack.push(kids[i]);
229
+ }
230
+ const rootRanks = new Map(orderedRoots.map((id, i) => [id, i + 1]));
231
+ const nodes = ordered.map((id) => {
232
+ const r = records.get(id);
233
+ const n = treeNodes([{ id, fields: r.fields, path: "" }])[0];
234
+ return { ...n, parent: parents.get(id), order: positions.get(id) ?? rootRanks.get(id), origin: r.origins[0], origins: r.origins };
235
+ });
236
+ return buildModel(nodes, slices.flatMap((s) => s.edges), errors);
237
+ }
238
+ function serializeTree(model) {
239
+ if (model.errors.length || model.duplicateIds?.length) throw new Error("Cannot export a graph with unresolved input conflicts");
240
+ const records = /* @__PURE__ */ new Map();
241
+ const groups = /* @__PURE__ */ new Map();
242
+ for (const n of model.nodes) {
243
+ if (records.has(n.id)) throw new Error(`Duplicate id: ${n.id}`);
244
+ if (n.parent && !model.index.has(n.parent)) throw new Error(`Missing parent: ${n.parent}`);
245
+ const { parent: _parent, order: _order, layer: _layer, children: _children, ...data } = n.data ?? {};
246
+ records.set(n.id, Object.fromEntries(Object.entries({ ...data, id: n.id, label: n.label, kind: n.kind }).filter(([, v]) => v !== void 0)));
247
+ const group = groups.get(n.parent) ?? [];
248
+ group.push(n);
249
+ groups.set(n.parent, group);
250
+ }
251
+ for (const list of groups.values()) list.sort((a2, b) => (a2.order ?? Infinity) - (b.order ?? Infinity));
252
+ const roots = groups.get(void 0) ?? [];
253
+ const visited = /* @__PURE__ */ new Set(), stack = [...roots];
254
+ while (stack.length) {
255
+ const n = stack.pop();
256
+ if (visited.has(n.id)) throw new Error(`Parent cycle: ${n.id}`);
257
+ visited.add(n.id);
258
+ const kids = groups.get(n.id);
259
+ if (kids?.length) {
260
+ const record = records.get(n.id);
261
+ if (!("unordered" in record) && kids.every((k) => k.order === void 0)) record.unordered = true;
262
+ record.children = kids.map((k) => records.get(k.id));
263
+ stack.push(...kids);
264
+ }
265
+ }
266
+ if (visited.size !== model.nodes.length) throw new Error("Parent cycle: no rooted forest can be exported");
267
+ for (const e of model.edges) if (!records.has(e.source) || !records.has(e.target)) throw new Error(`Dangling edge: ${e.source} \u2192 ${e.target}`);
268
+ return {
269
+ nodes: roots.map((n) => records.get(n.id)),
270
+ edges: model.edges.map((e) => Object.fromEntries(Object.entries({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }).filter(([, v]) => v !== void 0)))
271
+ };
109
272
  }
110
273
 
111
274
  // src/profile.ts
@@ -117,30 +280,6 @@ function parsePhysical(origin, text) {
117
280
  return { origin, title: origin, nodes: [], edges: [], error: e instanceof Error ? e.message : String(e) };
118
281
  }
119
282
  if (!raw || typeof raw !== "object" || !("nodes" in raw) && !("edges" in raw)) return null;
120
- const ref = (v) => typeof v === "string" || typeof v === "number" ? String(v) : void 0;
121
- const parentOf = (v) => {
122
- const rawParent = ref(v);
123
- const at = rawParent?.lastIndexOf("@") ?? -1;
124
- const tail = at > 0 ? rawParent.slice(at + 1) : "";
125
- if (!/^(-1|\d+(\.\d+)?)$/.test(tail)) return { parent: rawParent, order: void 0 };
126
- const order = tail === "-1" ? void 0 : Number(tail);
127
- return { parent: rawParent.slice(0, at), order: order !== void 0 && order > 0 ? order : void 0 };
128
- };
129
- const nodes = (Array.isArray(raw.nodes) ? raw.nodes : []).filter((n) => n && typeof n === "object" && ref(n.id) !== void 0).map((n) => {
130
- const { parent, order } = parentOf(n.parent);
131
- return {
132
- id: String(n.id),
133
- label: String(n.label ?? n.name ?? n.id),
134
- kind: typeof n.kind === "string" ? n.kind : void 0,
135
- parent,
136
- order,
137
- layer: typeof n.layer === "string" ? n.layer : void 0,
138
- // Marks carried by the data itself (e.g. a placeholder "with no content yet"). They are data, not derived: when the profile's
139
- // `placeholderFlags` recognizes one, it is drawn as skeleton.
140
- ...Array.isArray(n.flags) ? { flags: n.flags.filter((f) => typeof f === "string") } : {},
141
- data: n
142
- };
143
- });
144
283
  const edges = (Array.isArray(raw.edges) ? raw.edges : []).filter((e) => e && typeof e === "object").map((e) => ({
145
284
  source: String(e.source ?? e.from),
146
285
  target: String(e.target ?? e.to),
@@ -150,19 +289,11 @@ function parsePhysical(origin, text) {
150
289
  // The whole record, like nodes' `data`: fields the library does not know survive a round trip (convert, toPhysical).
151
290
  data: e
152
291
  }));
153
- return { origin, title: String(raw.name ?? raw.title ?? origin), nodes, edges };
292
+ const parsed = treeDeclarations(raw.nodes, origin);
293
+ return { origin, title: String(raw.name ?? raw.title ?? origin), nodes: treeNodes(parsed.declarations), edges, ...parsed };
154
294
  }
155
295
  function toPhysical(model) {
156
- const clean2 = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0 && v !== ""));
157
- return {
158
- // `layer` is derived, never written: a file that gains it would freeze a view decision into the data.
159
- // `parent` is always written, `null` for a root, and carries the order: `"<id>@<order|-1>"`. `order` is never a field of its own.
160
- nodes: model.nodes.map((n) => {
161
- const { order: _order, layer: _layer, ...data } = n.data ?? {};
162
- return clean2({ ...data, id: n.id, label: n.label, kind: n.kind, parent: encodeParent(n.parent, n.order) });
163
- }),
164
- edges: model.edges.map((e) => clean2({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }))
165
- };
296
+ return serializeTree(model);
166
297
  }
167
298
  var DEFAULT_LAYER = { id: "default", label: "Graph", z: 0, structural: true };
168
299
  function defineProfile(input) {
@@ -723,12 +854,36 @@ function adapt(files, only) {
723
854
  const out = pick.convert(files);
724
855
  const skipped = pick === MARKDOWN ? [] : files.filter((f) => /\.jsonl?$/i.test(f.path) && !pick.detect([f])).map((f) => f.path);
725
856
  return {
726
- sources: out.sources.map((s) => ({ origin: s.origin, text: JSON.stringify(s.graph) })),
857
+ sources: treeSources(out),
727
858
  profile: out.profile,
728
859
  adapter: pick,
729
860
  skipped
730
861
  };
731
862
  }
863
+ function treeSources(out) {
864
+ const children = /* @__PURE__ */ new Map();
865
+ for (const s of out.sources) for (const n of s.graph.nodes) {
866
+ if (!n.parent) continue;
867
+ const kids = children.get(n.parent) ?? /* @__PURE__ */ new Map();
868
+ kids.set(n.id, typeof n.order === "number" ? n.order : void 0);
869
+ children.set(n.parent, kids);
870
+ }
871
+ const written = /* @__PURE__ */ new Set();
872
+ return out.sources.map((s) => ({ origin: s.origin, text: JSON.stringify({
873
+ ...s.graph,
874
+ nodes: s.graph.nodes.map((n) => {
875
+ const { parent: _parent, order: _order, layer: _layer, ...fields } = n;
876
+ const kids = children.get(n.id);
877
+ if (!kids || written.has(n.id)) return fields;
878
+ written.add(n.id);
879
+ return {
880
+ ...fields,
881
+ ...fields.unordered === void 0 && [...kids.values()].every((v) => v === void 0) ? { unordered: true } : {},
882
+ children: [...kids].sort((a2, b) => (a2[1] ?? Infinity) - (b[1] ?? Infinity)).map(([id]) => ({ id }))
883
+ };
884
+ })
885
+ }) }));
886
+ }
732
887
  var isNativeGraph = (f) => {
733
888
  if (!/\.json$/i.test(f.path)) return false;
734
889
  try {
@@ -781,25 +936,25 @@ function walk(root) {
781
936
  function gitSpec(spec, cwd) {
782
937
  const m = /^([^:]+):(.*)$/.exec(spec);
783
938
  if (!m || /^[a-zA-Z]$/.test(m[1])) return null;
784
- const [, ref, rel0] = m;
939
+ const [, ref2, rel0] = m;
785
940
  const git = (...args) => execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 1 << 30, stdio: ["ignore", "pipe", "pipe"] });
786
941
  try {
787
- git("rev-parse", "--verify", "--quiet", `${ref}^{commit}`);
942
+ git("rev-parse", "--verify", "--quiet", `${ref2}^{commit}`);
788
943
  } catch {
789
944
  return null;
790
945
  }
791
946
  const rel = rel0.replace(/^\.?\/*/, "").replace(/\/+$/, "");
792
- const title = `${path.basename(rel || cwd)} @ ${ref}`;
947
+ const title = `${path.basename(rel || cwd)} @ ${ref2}`;
793
948
  let type;
794
949
  try {
795
- type = git("cat-file", "-t", `${ref}:./${rel}`).trim();
950
+ type = git("cat-file", "-t", `${ref2}:./${rel}`).trim();
796
951
  } catch {
797
- throw new Error(`${rel || "."} does not exist at ${ref}`);
952
+ throw new Error(`${rel || "."} does not exist at ${ref2}`);
798
953
  }
799
- if (type === "blob") return { files: [{ path: path.basename(rel), text: git("show", `${ref}:./${rel}`) }], title, isDir: false };
800
- const names2 = git("ls-tree", "-r", "--name-only", ref, "--", rel || ".").split("\n").filter(Boolean);
954
+ if (type === "blob") return { files: [{ path: path.basename(rel), text: git("show", `${ref2}:./${rel}`) }], title, isDir: false };
955
+ const names2 = git("ls-tree", "-r", "--name-only", ref2, "--", rel || ".").split("\n").filter(Boolean);
801
956
  const prefix = rel ? `${rel}/` : "";
802
- const files = names2.map((n) => n.split(path.sep).join("/")).filter((n) => DATA.test(n) && !n.split("/").some((s) => s.startsWith(".") && !DOT_OK.has(s) || SKIP_DIR.has(s))).slice(0, MAX_FILES).map((n) => ({ path: n.startsWith(prefix) ? n.slice(prefix.length) : n, text: git("show", `${ref}:./${n}`) }));
957
+ const files = names2.map((n) => n.split(path.sep).join("/")).filter((n) => DATA.test(n) && !n.split("/").some((s) => s.startsWith(".") && !DOT_OK.has(s) || SKIP_DIR.has(s))).slice(0, MAX_FILES).map((n) => ({ path: n.startsWith(prefix) ? n.slice(prefix.length) : n, text: git("show", `${ref2}:./${n}`) }));
803
958
  return { files, title, isDir: true };
804
959
  }
805
960
  var META = /* @__PURE__ */ new Set(["_profile.json", "_layout.json"]);
@@ -885,7 +1040,7 @@ var DIFF_FLAG = {
885
1040
  merged: "gb-merged"
886
1041
  };
887
1042
  var KEPT_FLAG = "gb-kept";
888
- var stable = (v, ignore) => {
1043
+ var stable2 = (v, ignore) => {
889
1044
  const walk2 = (x) => {
890
1045
  if (Array.isArray(x)) return x.map(walk2);
891
1046
  if (x && typeof x === "object") {
@@ -903,7 +1058,7 @@ function changedFields(a2, b, ignore) {
903
1058
  const ob = b ?? {};
904
1059
  const keys = new Set([...Object.keys(oa), ...Object.keys(ob)].filter((k) => !ignore.has(k)));
905
1060
  const out = [];
906
- for (const k of keys) if (stable(oa[k], ignore) !== stable(ob[k], ignore)) out.push(k);
1061
+ for (const k of keys) if (stable2(oa[k], ignore) !== stable2(ob[k], ignore)) out.push(k);
907
1062
  return out.sort();
908
1063
  }
909
1064
  var EDIT_CAP = 512;
@@ -938,7 +1093,7 @@ function editDistance(a2, b) {
938
1093
  return prev[m] + over;
939
1094
  }
940
1095
  function changeAmount(a2, b, fields, ignore) {
941
- const pick = (n) => fields.map((k) => stable((n.data ?? {})[k], ignore)).join("\0");
1096
+ const pick = (n) => fields.map((k) => stable2((n.data ?? {})[k], ignore)).join("\0");
942
1097
  return editDistance(pick(a2), pick(b)) + editDistance(a2.label ?? "", b.label ?? "");
943
1098
  }
944
1099
  var edgeKey = (e) => `${e.source} ${e.target} ${e.kind ?? ""}`;
@@ -961,8 +1116,30 @@ function diffModels(before, after, opts = {}) {
961
1116
  const b = afterByKey.get(k);
962
1117
  if (b) resolve.set(list[0].id, b.id);
963
1118
  }
964
- const ref = (id) => id === void 0 ? void 0 : resolve.get(id) ?? id;
1119
+ const ref2 = (id) => id === void 0 ? void 0 : resolve.get(id) ?? id;
965
1120
  const consumed = new Set(resolve.keys());
1121
+ const reordered = /* @__PURE__ */ new Set();
1122
+ if (!ignore.has("position")) {
1123
+ const groups = /* @__PURE__ */ new Map();
1124
+ for (const a2 of before.nodes) {
1125
+ const id = resolve.get(a2.id), b = id ? after.index.get(id) : void 0;
1126
+ if (!b || ref2(a2.parent) !== b.parent) continue;
1127
+ if (a2.parent && before.index.get(a2.parent)?.data?.unordered === true || b.parent && after.index.get(b.parent)?.data?.unordered === true) continue;
1128
+ const p = b.parent;
1129
+ const g = groups.get(p) ?? { old: [], next: [] };
1130
+ g.old.push(a2);
1131
+ g.next.push(b);
1132
+ groups.set(p, g);
1133
+ }
1134
+ for (const g of groups.values()) {
1135
+ g.old.sort((a2, b) => (a2.order ?? Infinity) - (b.order ?? Infinity));
1136
+ const ranks = new Map(after.nodes.map((n, i) => [n.id, i]));
1137
+ g.next.sort((a2, b) => (a2.order ?? ranks.get(a2.id)) - (b.order ?? ranks.get(b.id)));
1138
+ g.old.forEach((a2, i) => {
1139
+ if (resolve.get(a2.id) !== g.next[i].id) reordered.add(g.next[i].id);
1140
+ });
1141
+ }
1142
+ }
966
1143
  const changes = [];
967
1144
  const prevData = /* @__PURE__ */ new Map();
968
1145
  const moved = /* @__PURE__ */ new Map();
@@ -974,8 +1151,13 @@ function diffModels(before, after, opts = {}) {
974
1151
  flag = DIFF_FLAG.added;
975
1152
  changes.push({ kind: "added", id: b.id });
976
1153
  } else {
977
- const fields = changedFields(a2.data, b.data, ignore);
978
- const aParent = ref(a2.parent) ?? null;
1154
+ const own = (n) => {
1155
+ const { children: _children, parent: _parent, order: _order, ...data } = n.data ?? {};
1156
+ return { ...data, kind: n.kind };
1157
+ };
1158
+ const fields = changedFields(own(a2), own(b), ignore);
1159
+ if (reordered.has(b.id)) fields.push("position");
1160
+ const aParent = ref2(a2.parent) ?? null;
979
1161
  if (aParent !== (b.parent ?? null)) {
980
1162
  flag = DIFF_FLAG.moved;
981
1163
  changes.push({
@@ -1012,7 +1194,7 @@ function diffModels(before, after, opts = {}) {
1012
1194
  const merged = !!to && after.index.has(to);
1013
1195
  const kind = merged ? "merged" : "removed";
1014
1196
  changes.push({ kind, id: a2.id, pairId: merged ? to : void 0 });
1015
- const parent = ref(a2.parent);
1197
+ const parent = ref2(a2.parent);
1016
1198
  nodes.push({
1017
1199
  ...withFlag(a2, DIFF_FLAG[kind]),
1018
1200
  parent: parent && (unionIds.has(parent) || !consumed.has(a2.parent)) ? parent : void 0
@@ -1022,7 +1204,7 @@ function diffModels(before, after, opts = {}) {
1022
1204
  const afterEdges = new Map(after.edges.map((e) => [edgeKey(e), e]));
1023
1205
  const beforeEdges = new Map(
1024
1206
  before.edges.map((e) => {
1025
- const r = { ...e, source: ref(e.source), target: ref(e.target) };
1207
+ const r = { ...e, source: ref2(e.source), target: ref2(e.target) };
1026
1208
  return [edgeKey(r), r];
1027
1209
  })
1028
1210
  );
@@ -1057,7 +1239,8 @@ function diffModels(before, after, opts = {}) {
1057
1239
 
1058
1240
  // src/layers.ts
1059
1241
  var EMPTY = { layers: [], layerOf: /* @__PURE__ */ new Map() };
1060
- function orderedChildren(children, id) {
1242
+ function orderedChildren(children, id, unordered = false) {
1243
+ if (unordered) return null;
1061
1244
  const kids = children.get(id) ?? [];
1062
1245
  if (kids.length < 2) return null;
1063
1246
  const withOrder = kids.filter((n) => typeof n.order === "number" && Number.isFinite(n.order));
@@ -1086,10 +1269,10 @@ function deriveLayers(model, colors = [], force = false) {
1086
1269
  let anchor;
1087
1270
  if (roots.length === 1) {
1088
1271
  anchor = roots[0];
1089
- ordered = orderedChildren(children, anchor.id);
1272
+ ordered = orderedChildren(children, anchor.id, anchor.data?.unordered === true);
1090
1273
  if (!ordered && force) ordered = children.get(anchor.id) ?? null;
1091
- } else if (force && roots.length > 1) {
1092
- ordered = roots;
1274
+ } else if (roots.length > 1 && (force || roots.every((n) => n.order !== void 0))) {
1275
+ ordered = [...roots].sort((a2, b) => (a2.order ?? Infinity) - (b.order ?? Infinity));
1093
1276
  }
1094
1277
  if (!ordered || ordered.length < 2) return EMPTY;
1095
1278
  const layers = ordered.map((n, i) => ({
@@ -1116,50 +1299,152 @@ var graph_schema_default = {
1116
1299
  $schema: "https://json-schema.org/draft/2020-12/schema",
1117
1300
  $id: "https://unpkg.com/glassbrain/schema/graph.schema.json",
1118
1301
  title: "glassbrain graph",
1119
- description: 'One file of a glassbrain knowledge graph. A graph is nodes plus edges; structure comes from `parent` (containment), not from edges. Every node carries `parent`: null for the root, otherwise `"<id>@<order>"` where `order` is a positive number or -1 for explicitly unordered. Several files in one folder are merged into one graph (same id = same node). Unknown fields are kept and shown in the detail panel.',
1302
+ description: "An ordered forest of node fragments plus semantic edges. Nest nodes in children; array order is reading order. Same id means the same node: absent fields are filled, equal values are accepted, conflicting values are errors. Children declarations must have identical direct child id sequences. Top-level fragments acquire a parent wherever another node contains their id. Each node has at most one parent; cycles are invalid.",
1120
1303
  type: "object",
1121
- anyOf: [{ required: ["nodes"] }, { required: ["edges"] }],
1304
+ anyOf: [
1305
+ {
1306
+ required: [
1307
+ "nodes"
1308
+ ]
1309
+ },
1310
+ {
1311
+ required: [
1312
+ "edges"
1313
+ ]
1314
+ }
1315
+ ],
1122
1316
  properties: {
1123
- name: { type: "string", description: "Title of this file (shown as its source name)." },
1124
- title: { type: "string", description: "Alias of `name`." },
1317
+ name: {
1318
+ type: "string",
1319
+ description: "Title of this file (shown as its source name)."
1320
+ },
1321
+ title: {
1322
+ type: "string",
1323
+ description: "Alias of `name`."
1324
+ },
1125
1325
  nodes: {
1126
1326
  type: "array",
1127
- items: { $ref: "#/$defs/node" }
1327
+ items: {
1328
+ $ref: "#/$defs/node"
1329
+ }
1128
1330
  },
1129
1331
  edges: {
1130
1332
  type: "array",
1131
- items: { $ref: "#/$defs/edge" }
1333
+ items: {
1334
+ $ref: "#/$defs/edge"
1335
+ }
1132
1336
  }
1133
1337
  },
1134
1338
  $defs: {
1135
1339
  node: {
1136
1340
  type: "object",
1137
- required: ["id", "parent"],
1341
+ required: [
1342
+ "id"
1343
+ ],
1138
1344
  properties: {
1139
- id: { type: ["string", "number"], pattern: "^[^\\s@]{1,80}$", description: "Stable identity. Keep it the same across versions: that is how a diff knows it is the same thing. No `@` and no whitespace, at most 80 characters; prefer a short code (`a-z0-9_`, under 20)." },
1140
- label: { type: "string", description: "Display name. Falls back to `name`, then `id`." },
1141
- name: { type: "string", description: "Alias of `label`." },
1142
- kind: { type: "string", description: "What sort of thing this is. Colors come from the profile's `nodePalette[kind]`; kinds not in the palette are drawn as skeleton." },
1143
- parent: { type: ["string", "null"], pattern: "^[^\\s@]{1,80}@(-1|[1-9]\\d*(\\.\\d+)?|0\\.\\d*[1-9]\\d*)$", description: '`"<id>@<order>"`: the id of the node this one sits inside, then its position among the siblings (1, 2, 3\u2026; 3.5 inserts between 3 and 4), or -1 for explicitly unordered. null for the root. Required: the only source of structure, and the layout, the layers and the outline are all built from it.' },
1144
- flags: { type: "array", items: { type: "string" }, description: "Boolean markers; each becomes a CSS-like class. A flag listed in the profile's `placeholderFlags` draws the node as a placeholder." },
1145
- description: { type: "string", description: "Markdown shown in the detail panel. `[text](node:<id>)` links jump to another node." }
1345
+ id: {
1346
+ type: [
1347
+ "string",
1348
+ "number"
1349
+ ],
1350
+ pattern: "\\S",
1351
+ description: "Non-empty stable identity. Keep it the same across versions: that is how a diff knows it is the same thing. Prefer a short code."
1352
+ },
1353
+ label: {
1354
+ type: "string",
1355
+ description: "Display name. Falls back to `name`, then `id`."
1356
+ },
1357
+ name: {
1358
+ type: "string",
1359
+ description: "Alias of `label`."
1360
+ },
1361
+ kind: {
1362
+ type: "string",
1363
+ description: "What sort of thing this is. Colors come from the profile's `nodePalette[kind]`; kinds not in the palette are drawn as skeleton."
1364
+ },
1365
+ flags: {
1366
+ type: "array",
1367
+ items: {
1368
+ type: "string"
1369
+ },
1370
+ description: "Boolean markers; each becomes a CSS-like class. A flag listed in the profile's `placeholderFlags` draws the node as a placeholder."
1371
+ },
1372
+ description: {
1373
+ type: "string",
1374
+ description: "Markdown shown in the detail panel. `[text](node:<id>)` links jump to another node."
1375
+ },
1376
+ children: {
1377
+ type: "array",
1378
+ items: {
1379
+ $ref: "#/$defs/node"
1380
+ },
1381
+ description: "Ordered direct children. Omitted means unspecified; [] explicitly declares no children. Multiple declarations must name the same ids in the same order; child fields are composed independently by id."
1382
+ },
1383
+ unordered: { type: "boolean" },
1384
+ parent: false,
1385
+ order: false,
1386
+ layer: false
1146
1387
  },
1147
1388
  additionalProperties: true
1148
1389
  },
1149
1390
  edge: {
1150
1391
  type: "object",
1151
1392
  anyOf: [
1152
- { required: ["source", "target"] },
1153
- { required: ["from", "to"] }
1393
+ {
1394
+ required: [
1395
+ "source",
1396
+ "target"
1397
+ ]
1398
+ },
1399
+ {
1400
+ required: [
1401
+ "from",
1402
+ "to"
1403
+ ]
1404
+ }
1154
1405
  ],
1155
1406
  properties: {
1156
- source: { type: ["string", "number"], description: "Node id the edge starts at." },
1157
- target: { type: ["string", "number"], description: "Node id the edge points to." },
1158
- from: { type: ["string", "number"], description: "Alias of `source`." },
1159
- to: { type: ["string", "number"], description: "Alias of `target`." },
1160
- kind: { type: "string", description: "Relation type. Colors come from the profile's `edgePalette[kind]`. An edge is identified by its two ends plus its kind." },
1161
- label: { type: "string" },
1162
- weight: { type: "number", minimum: 0, maximum: 1, description: "0\u20131 (confidence, strength\u2026); drives line width." }
1407
+ source: {
1408
+ type: [
1409
+ "string",
1410
+ "number"
1411
+ ],
1412
+ description: "Node id the edge starts at."
1413
+ },
1414
+ target: {
1415
+ type: [
1416
+ "string",
1417
+ "number"
1418
+ ],
1419
+ description: "Node id the edge points to."
1420
+ },
1421
+ from: {
1422
+ type: [
1423
+ "string",
1424
+ "number"
1425
+ ],
1426
+ description: "Alias of `source`."
1427
+ },
1428
+ to: {
1429
+ type: [
1430
+ "string",
1431
+ "number"
1432
+ ],
1433
+ description: "Alias of `target`."
1434
+ },
1435
+ kind: {
1436
+ type: "string",
1437
+ description: "Relation type. Colors come from the profile's `edgePalette[kind]`. An edge is identified by its two ends plus its kind."
1438
+ },
1439
+ label: {
1440
+ type: "string"
1441
+ },
1442
+ weight: {
1443
+ type: "number",
1444
+ minimum: 0,
1445
+ maximum: 1,
1446
+ description: "0\u20131 (confidence, strength\u2026); drives line width."
1447
+ }
1163
1448
  },
1164
1449
  additionalProperties: true
1165
1450
  }
@@ -1327,6 +1612,11 @@ function checkSchema(root, value, limit = 50) {
1327
1612
  const resolve = (s) => s.$ref ? root.$defs[s.$ref.replace("#/$defs/", "")] : s;
1328
1613
  const walk2 = (s0, v, path3, out2) => {
1329
1614
  if (out2.length >= limit) return;
1615
+ if (s0 === false) {
1616
+ out2.push({ path: path3, message: "retired field; use children" });
1617
+ return;
1618
+ }
1619
+ if (s0 === true) return;
1330
1620
  const s = resolve(s0);
1331
1621
  for (const k of Object.keys(s)) if (!KNOWN.has(k)) throw new Error(`schema-check: unsupported keyword "${k}"`);
1332
1622
  if (s.type) {
@@ -1352,7 +1642,7 @@ function checkSchema(root, value, limit = 50) {
1352
1642
  for (const r of s.required ?? []) if (!(r in o)) out2.push({ path: path3, message: `missing "${r}"` });
1353
1643
  for (const [k, val] of Object.entries(o)) {
1354
1644
  const sub = s.properties?.[k] ?? (typeof s.additionalProperties === "object" ? s.additionalProperties : null);
1355
- if (sub) walk2(sub, val, `${path3}.${k}`, out2);
1645
+ if (sub !== null && sub !== void 0) walk2(sub, val, `${path3}.${k}`, out2);
1356
1646
  else if (s.additionalProperties === false) out2.push({ path: path3, message: `unknown field "${k}"` });
1357
1647
  }
1358
1648
  }
@@ -1595,7 +1885,7 @@ var misplacedField = {
1595
1885
  code: "schema",
1596
1886
  level: "error",
1597
1887
  run: ({ model }) => {
1598
- const reserved = ["id", "label", "kind", "parent", "description"];
1888
+ const reserved = ["id", "label", "kind", "children", "description"];
1599
1889
  const out = [];
1600
1890
  for (const n of model.nodes) {
1601
1891
  const nested = n.data?.data;
@@ -1618,10 +1908,8 @@ var layerField = {
1618
1908
  level: "error",
1619
1909
  run: ({ model }) => model.nodes.filter((n) => n.data && typeof n.data === "object" && "layer" in n.data).map((n) => ({
1620
1910
  node: n.id,
1621
- message: `"${n.id}" still carries "layer": layers are not written any more, they come from the order in "parent"`,
1622
- fix: `delete the field. To make the graph read as floors, number one node's children in "parent" instead:
1623
- - { "id": "${n.id}", "parent": "\u2026@-1", "layer": "${n.layer}" }
1624
- + { "id": "${n.id}", "parent": "\u2026@2" }`
1911
+ message: `"${n.id}" still carries "layer": layers are not written any more, they come from children`,
1912
+ fix: `delete "layer" and put the node in its container's children array.`
1625
1913
  }))
1626
1914
  };
1627
1915
  var unknownParent = {
@@ -1630,10 +1918,7 @@ var unknownParent = {
1630
1918
  run: ({ model, index, labelOf }) => model.nodes.filter((n) => n.parent && !index.has(n.parent)).map((n) => ({
1631
1919
  node: n.id,
1632
1920
  message: `"${n.id}" sits inside "${n.parent}", which does not exist`,
1633
- fix: `point it at a node that exists (one of: ${[...index.keys()].slice(0, 3).map((id) => `"${id}"`).join(", ")}), or add "${n.parent}":
1634
- - "parent": "${n.parent}@-1"
1635
- + "parent": "${[...index.keys()][0] ?? "EXISTING_ID"}@-1"
1636
- ("parent": null also works, but a file has one root: a second null is a parent-error.)`
1921
+ fix: `add the missing container "${n.parent}" and nest "${n.id}" in its children, or move "${n.id}" to nodes.`
1637
1922
  }))
1638
1923
  };
1639
1924
  var parentCycle = {
@@ -1655,9 +1940,7 @@ var parentCycle = {
1655
1940
  out.push({
1656
1941
  node: cur,
1657
1942
  message: `parent cycle: ${[...loop, cur].join(" \u2192 ")}`,
1658
- fix: `a node cannot sit inside itself. Pick the one that should be the top of the loop and give it "parent": null:
1659
- - { "id": "${loop[0]}", "parent": "${cur}@-1" }
1660
- + { "id": "${loop[0]}", "parent": null }`
1943
+ fix: `remove one children placement in this cycle; a node cannot contain itself.`
1661
1944
  });
1662
1945
  break;
1663
1946
  }
@@ -1671,57 +1954,18 @@ var parentCycle = {
1671
1954
  return out;
1672
1955
  }
1673
1956
  };
1674
- var orderMixed = {
1675
- code: "order-error",
1676
- level: "error",
1677
- run: ({ children }) => {
1678
- const out = [];
1679
- for (const [parent, kids] of children) {
1680
- const withOrder = kids.filter((k) => typeof k.order === "number").length;
1681
- if (withOrder === 0 || withOrder === kids.length) continue;
1682
- const missing = kids.filter((k) => typeof k.order !== "number").slice(0, 3);
1683
- const next = Math.max(0, ...kids.map((k) => typeof k.order === "number" ? k.order : 0)) + 1;
1684
- out.push({
1685
- node: parent,
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")}`
1690
- });
1691
- }
1692
- return out;
1693
- }
1694
- };
1695
- var orderDuplicate = {
1696
- code: "order-error",
1957
+ var reservedContains = {
1958
+ code: "parent-error",
1697
1959
  level: "error",
1698
- run: ({ children }) => {
1699
- const out = [];
1700
- for (const [parent, kids] of children) {
1701
- const seen = /* @__PURE__ */ new Map();
1702
- for (const k of kids) {
1703
- if (typeof k.order !== "number") continue;
1704
- const arr = seen.get(k.order);
1705
- arr ? arr.push(k) : seen.set(k.order, [k]);
1706
- }
1707
- for (const [value, same] of seen) {
1708
- if (same.length < 2) continue;
1709
- out.push({
1710
- node: parent,
1711
- message: `"${parent}" has ${same.length} children at order ${value} (${names(same.map((n) => n.id))}); two items cannot share a place`,
1712
- fix: `spread them. Fractions are allowed, so nothing else has to move:
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")}`
1715
- });
1716
- }
1717
- }
1718
- return out;
1719
- }
1960
+ run: ({ model }) => model.edges.some((e) => e.kind === "contains") ? [{
1961
+ message: 'edge kind "contains" is reserved for the parent structure',
1962
+ fix: "express containment with a children array and remove the redundant edge. If this is another relationship, give its kind a distinct name and update edgePalette."
1963
+ }] : []
1720
1964
  };
1721
1965
  var conflictingDefinition = {
1722
1966
  code: "duplicate-id",
1723
1967
  level: "error",
1724
- run: ({ model, index, sameFileDuplicates }) => (model.duplicateIds ?? []).filter((id) => !sameFileDuplicates.has(id)).map((id) => ({
1968
+ run: ({ model, index }) => (model.duplicateIds ?? []).map((id) => ({
1725
1969
  node: id,
1726
1970
  message: `"${id}" is defined differently in ${names(index.get(id)?.origins ?? [])}; the first one is kept, the rest is dropped silently`,
1727
1971
  fix: `one id is one thing. Either make the copies identical, or give one a new id and point its edges at that:
@@ -1797,7 +2041,7 @@ var wideNode = {
1797
2041
  message: `"${labelOf(id)}" holds ${what}; ${isAnchor ? "review whether each floor is a major section" : "review whether this is one natural collection"}`,
1798
2042
  fix: `inspect membership and depth: glassbrain tree <path> --path "${id}"
1799
2043
  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." : ""}`
2044
+ Prefer fewer than 5 children per group; this is guidance, not a quota. Keep a natural collection together; add a named group only when it explains membership.${isAnchor ? "\n Each root child can be shown as a floor; use the view switch to read them together." : ""}`
1801
2045
  });
1802
2046
  }
1803
2047
  return out;
@@ -1899,29 +2143,12 @@ var colorNote = {
1899
2143
  }];
1900
2144
  }
1901
2145
  };
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
- };
1918
2146
  var rules = [
1919
2147
  misplacedField,
1920
2148
  layerField,
1921
2149
  unknownParent,
1922
2150
  parentCycle,
1923
- orderMixed,
1924
- orderDuplicate,
2151
+ reservedContains,
1925
2152
  conflictingDefinition,
1926
2153
  danglingEdge,
1927
2154
  duplicateEdge,
@@ -1931,8 +2158,7 @@ var rules = [
1931
2158
  singleKind,
1932
2159
  kindNote,
1933
2160
  colorNote,
1934
- lowCoverage,
1935
- orderHint
2161
+ lowCoverage
1936
2162
  ];
1937
2163
  function checkGraph(model, profile, opts) {
1938
2164
  const children = /* @__PURE__ */ new Map();
@@ -1949,10 +2175,10 @@ function checkGraph(model, profile, opts) {
1949
2175
  index: model.index,
1950
2176
  children,
1951
2177
  layers: deriveLayers(model),
1952
- labelOf: (id) => model.index.get(id)?.label ?? id,
1953
- sameFileDuplicates: opts.sameFileDuplicates ?? /* @__PURE__ */ new Set()
2178
+ labelOf: (id) => model.index.get(id)?.label ?? id
1954
2179
  };
1955
- const out = rules.flatMap((rule) => rule.run(ctx).map((issue) => ({
2180
+ const invalidStructure = unknownParent.run(ctx).length > 0 || parentCycle.run(ctx).length > 0;
2181
+ const out = rules.filter((rule) => !invalidStructure || rule !== unevenKinds).flatMap((rule) => rule.run(ctx).map((issue) => ({
1956
2182
  level: issue.level ?? rule.level,
1957
2183
  code: rule.code,
1958
2184
  where: opts.where,
@@ -1977,7 +2203,12 @@ function structureOf(model) {
1977
2203
  arr ? arr.push(n) : children.set(n.parent, [n]);
1978
2204
  }
1979
2205
  const derived = deriveLayers(model);
1980
- const analysis = analyzeShape(model.nodes);
2206
+ let analysis;
2207
+ try {
2208
+ analysis = analyzeShape(model.nodes);
2209
+ } catch {
2210
+ analysis = analyzeShape([]);
2211
+ }
1981
2212
  return {
1982
2213
  nodes: model.nodes.length,
1983
2214
  edges: model.edges.length,
@@ -1987,7 +2218,7 @@ function structureOf(model) {
1987
2218
  layers: derived.layers.length,
1988
2219
  regularity: +(1 - analysis.peak).toFixed(3),
1989
2220
  shape: { peak: analysis.peak, assessed: analysis.assessed, unassessed: analysis.unassessed, branches: analysis.branches },
1990
- ordered: derived.layers.length > 0 || [...children.keys()].some((id) => orderedChildren(children, id) !== null)
2221
+ ordered: derived.layers.length > 0 || [...children.keys()].some((id) => orderedChildren(children, id, model.index.get(id)?.data?.unordered === true) !== null)
1991
2222
  };
1992
2223
  }
1993
2224
  function countsBy(values) {
@@ -2043,7 +2274,7 @@ function lint(loaded) {
2043
2274
  level: "warn",
2044
2275
  code: "schema",
2045
2276
  where: "_profile.json",
2046
- message: `${retired.map((k) => `"${k}"`).join(" and ")} no longer configure anything: layers come from the order in "parent"`,
2277
+ message: `${retired.map((k) => `"${k}"`).join(" and ")} no longer configure anything: layers come from the ordered children structure`,
2047
2278
  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.`
2048
2279
  });
2049
2280
  }
@@ -2052,7 +2283,6 @@ function lint(loaded) {
2052
2283
  for (const { version, files } of loaded.raw) {
2053
2284
  const prefix = loaded.versions.length > 1 ? `${version}/` : "";
2054
2285
  const notJson = /* @__PURE__ */ new Set();
2055
- const sameFileDuplicates = /* @__PURE__ */ new Set();
2056
2286
  if (loaded.format === "native") {
2057
2287
  for (const f of files) {
2058
2288
  if (!/\.json$/i.test(f.path)) continue;
@@ -2069,76 +2299,16 @@ function lint(loaded) {
2069
2299
  continue;
2070
2300
  }
2071
2301
  for (const e of checkSchema(graph_schema_default, doc)) out.push({ level: "error", code: "schema", where: prefix + f.path, message: `${e.path}: ${e.message}` });
2072
- const rawNodes = (Array.isArray(doc.nodes) ? doc.nodes : []).filter((n) => !!n && typeof n === "object");
2073
- const bare = rawNodes.filter((n) => !("parent" in n));
2074
- if (bare.length) out.push({
2075
- level: "error",
2076
- code: "parent-error",
2077
- where: prefix + f.path,
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:
2080
- - { "id": "${String(bare[0].id)}" }
2081
- + { "id": "${String(bare[0].id)}", "parent": null }
2082
- - { "id": "child" }
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.`
2112
- });
2113
- const seen = /* @__PURE__ */ new Map();
2114
- for (const id of idsIn(doc)) seen.set(id, (seen.get(id) ?? 0) + 1);
2115
- for (const [id, count2] of seen) {
2116
- if (count2 < 2) continue;
2117
- sameFileDuplicates.add(id);
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` });
2119
- }
2120
2302
  }
2121
2303
  }
2122
2304
  const v = loaded.versions.find((x) => x.name === version);
2123
2305
  const model = modelOf(v, profile);
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 });
2125
- if (version === latest) out.push(...checkGraph(model, profile, { where: prefix || loaded.title, sameFileDuplicates }));
2306
+ for (const e of model.errors) if (!notJson.has(e.origin)) out.push({ level: "error", code: e.code ?? "schema", where: prefix + e.origin, message: e.message, node: e.node });
2307
+ if (version === latest) out.push(...checkGraph(model, profile, { where: prefix || loaded.title }));
2126
2308
  if (!model.nodes.length) out.push({ level: "warn", code: "schema", where: prefix || loaded.title, message: "No nodes found" });
2127
2309
  }
2128
2310
  return out.sort((a2, b) => RANK[a2.level] - RANK[b.level]);
2129
2311
  }
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
- }
2137
- function idsIn(doc) {
2138
- const nodes = doc.nodes;
2139
- if (!Array.isArray(nodes)) return [];
2140
- return nodes.filter((n) => !!n && typeof n === "object" && "id" in n && n.id != null).map((n) => String(n.id));
2141
- }
2142
2312
  var ignoreOf = (profile, extra = []) => [.../* @__PURE__ */ new Set([...Array.isArray(profile?.diffIgnore) ? profile.diffIgnore : [], ...extra])];
2143
2313
  function diff(before, after, labels, ignore = []) {
2144
2314
  const delta = diffModels(before, after, { labels, ignore });
@@ -2244,7 +2414,7 @@ function tree(model, opts) {
2244
2414
  const bySize = (a2, b) => (size.get(b.id) ?? 1) - (size.get(a2.id) ?? 1) || labelOf(a2.id).localeCompare(labelOf(b.id));
2245
2415
  const sorted = /* @__PURE__ */ new Map();
2246
2416
  for (const [id, list] of kids) {
2247
- sorted.set(id, orderedChildren(kids, id) ?? [...list].sort(bySize));
2417
+ sorted.set(id, orderedChildren(kids, id, model.index.get(id)?.data?.unordered === true) ?? [...list].sort(bySize));
2248
2418
  }
2249
2419
  const outgoing = /* @__PURE__ */ new Map();
2250
2420
  for (const e of model.edges) {
@@ -2272,13 +2442,14 @@ function tree(model, opts) {
2272
2442
  if (collapsed && tall > 0) bits.push(`${tall} deep`);
2273
2443
  if (edges.length) bits.push(edgeText(edges));
2274
2444
  const label = `${labelOf(node.id)}${broken(node) ? " (parent missing)" : ""}`;
2275
- const orderTag = typeof node.order === "number" ? `[${node.order}] ` : "";
2445
+ const order = node.parent && model.index.get(node.parent)?.data?.unordered === true ? void 0 : node.order;
2446
+ const orderTag = typeof order === "number" ? `[${order}] ` : "";
2276
2447
  entries.push({
2277
2448
  id: node.id,
2278
2449
  label,
2279
2450
  depth: level,
2280
2451
  layer: layerOf(node),
2281
- ...typeof node.order === "number" ? { order: node.order } : {},
2452
+ ...typeof order === "number" ? { order } : {},
2282
2453
  nodes: inside,
2283
2454
  deep: tall,
2284
2455
  collapsed,
@@ -2449,7 +2620,7 @@ function restructure(input, edges, opts = {}) {
2449
2620
  }
2450
2621
  if (outside - within < 0.15) continue;
2451
2622
  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;
2623
+ if (byId.get(b.parent)?.data.unordered !== true && ordered.every((n) => n.order !== void 0) && Math.max(...indices) - Math.min(...indices) + 1 !== members.length) continue;
2453
2624
  suggestions.push({
2454
2625
  parent: b.parent,
2455
2626
  members: ordered.filter((n) => members.includes(n.id)).map((n) => n.id),
@@ -2470,12 +2641,14 @@ function restructure(input, edges, opts = {}) {
2470
2641
  const siblings = nodes.filter((n) => n.parent === parent).sort((a2, b) => (a2.order ?? a2.seq ?? 0) - (b.order ?? b.seq ?? 0));
2471
2642
  if (members.length === siblings.length)
2472
2643
  throw new Error("grouping every sibling adds no distinction");
2473
- const numbered = siblings.every((n) => n.order !== void 0);
2644
+ const unordered = byId.get(parent)?.data.unordered === true;
2645
+ const numbered = !unordered && siblings.every((n) => n.order !== void 0);
2474
2646
  const indices = siblings.map((n, i) => opts.group.includes(n.id) ? i : -1).filter((i) => i >= 0);
2475
2647
  if (numbered && Math.max(...indices) - Math.min(...indices) + 1 !== members.length)
2476
2648
  throw new Error("ordered group members must be consecutive");
2477
2649
  const label = siblings.filter((n) => opts.group.includes(n.id)).map((n) => n.label || n.id).join(" & ");
2478
2650
  const group = add(label, "group", parent);
2651
+ if (unordered) group.data.unordered = true;
2479
2652
  if (numbered)
2480
2653
  group.order = Math.min(...members.map((n) => n.order));
2481
2654
  for (const n of members)
@@ -2533,47 +2706,33 @@ function planNodesOf(model) {
2533
2706
  label: n.label,
2534
2707
  kind: n.kind,
2535
2708
  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,
2709
+ order: n.order,
2537
2710
  seq,
2538
2711
  data: n.data ?? {}
2539
2712
  }));
2540
2713
  }
2541
2714
  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
- };
2715
+ const model = buildModel(plan.nodes.map((p) => ({ ...p, parent: p.parent ?? void 0 })), []);
2716
+ return { name, nodes: toPhysical(model).nodes, edges };
2556
2717
  }
2557
2718
 
2558
2719
  // cli/glassbrain.ts
2559
2720
  var HELP = (schema) => `glassbrain: open, diff and lint a knowledge graph, written as plain JSON.
2560
2721
 
2561
2722
  [ DATA ]
2562
- JSON with two arrays, \`nodes\` and \`edges\`. The parent structure helps readability.
2723
+ JSON with two arrays, \`nodes\` and \`edges\`. The children structure helps readability.
2563
2724
  { "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
2725
+ { "id": "start", "label": "Start", "kind": "folder", "children": [ // the root
2726
+ { "id": "login", "label": "Login", "kind": "file", // first child
2566
2727
  "description": "Checks the password, then opens a session.", // markdown
2567
2728
  "owner": "auth" }, // any other field: kept, shown
2568
- { "id": "db", "label": "DB", "kind": "file", "parent": "start@2" } ], // second child
2729
+ { "id": "db", "label": "DB", "kind": "file" } ] } ], // second child
2569
2730
  "edges": [
2570
2731
  { "source": "login", "target": "db", "kind": "uses" } ] }
2571
2732
 
2572
2733
  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.
2734
+ * \`id\` identifies a node; nest it in \`children\` in reading order. Recommend \`kind\` for its category.
2735
+ * Children structure helps readability. Prefer fewer than 5 children; keep natural collections. Consider deeper grouping if crowded.
2577
2736
  * Keep kinds few and consistent (around 8 or fewer).
2578
2737
  * Keep depth and detail meaningful. Lint flags structural imbalance as \`bad-structure\`.
2579
2738
  * Put supporting details in descriptions. Extra fields are kept and shown.
@@ -2592,7 +2751,7 @@ var HELP = (schema) => `glassbrain: open, diff and lint a knowledge graph, writt
2592
2751
  \u251C\u2500\u2500 2-filled/graph.json each pass is the whole graph: copy the last, edit the copy
2593
2752
  \u2514\u2500\u2500 3-linked/graph.json then lint, and diff against the pass before
2594
2753
 
2595
- Inside a pass, JSON at any depth merges by id; split by area only when a file gets too big to write.
2754
+ Inside a pass, same ids fill absent fields; conflicting values or child-id sequences error. Split by area when needed.
2596
2755
 
2597
2756
  [ APPEARANCE ]
2598
2757
  kg/_profile.json, shared by every pass, also when opening a pass file directly.
@@ -2617,7 +2776,7 @@ var HELP = (schema) => `glassbrain: open, diff and lint a knowledge graph, writt
2617
2776
  glassbrain lint <path> Lint errors, warnings, info; exit 1 on errors.
2618
2777
  Always lint before handing over.
2619
2778
  glassbrain tree <path> log the containment tree as text
2620
- glassbrain restructure <path> preserve content; repair containment and order, suggest groups;
2779
+ glassbrain restructure <path> preserve content; repair containment, preserve reading order, suggest groups;
2621
2780
  write graph.json and _profile.json in a new folder
2622
2781
  glassbrain diff <old> <new> only what changed between two graphs
2623
2782
  glassbrain diff <git-ref> <path> the same graph at an earlier commit (default HEAD)
@@ -2783,6 +2942,7 @@ function runDiff(a2) {
2783
2942
  const ma = modelOf(va, profile);
2784
2943
  notes(before, []);
2785
2944
  notes(after, []);
2945
+ if (mb.errors.length || ma.errors.length || mb.duplicateIds?.length || ma.duplicateIds?.length) fail("repair input conflicts before diff", 1);
2786
2946
  const ignore = ignoreOf(profileJson, typeof a2.flags.ignore === "string" ? a2.flags.ignore.split(",").map((s) => s.trim()).filter(Boolean) : []);
2787
2947
  const { summary } = diff(mb, ma, labels, ignore);
2788
2948
  const labelOf = (id) => ma.index.get(id)?.label ?? mb.index.get(id)?.label ?? id;
@@ -2847,6 +3007,7 @@ function runTree(a2) {
2847
3007
  const models = nodesOf(l);
2848
3008
  notes(l, models);
2849
3009
  const latest = models[models.length - 1];
3010
+ if (latest.errors.length) fail(latest.errors.map((e) => `${e.origin}: ${e.message}`).join("\n"), 1);
2850
3011
  const version = l.versions[l.versions.length - 1].name;
2851
3012
  const result = tree(latest, {
2852
3013
  title: l.versions.length > 1 ? `${l.title}/${version}` : l.title,
@@ -2863,7 +3024,7 @@ function runTree(a2) {
2863
3024
  function runRestructure(a2) {
2864
3025
  if (a2.pos.length !== 1) fail("restructure needs exactly one <path>");
2865
3026
  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");
3027
+ const blockers = lint(l).filter((f) => ["duplicate-id", "dangling-edge", "field-conflict", "children-conflict"].includes(f.code));
2867
3028
  if (blockers.length) fail(`repair identity/relation errors before restructure: ${blockers.map((f) => f.message).join("; ")}`, 1);
2868
3029
  const models = nodesOf(l);
2869
3030
  notes(l, models);
@@ -2938,13 +3099,18 @@ function runConvert(a2) {
2938
3099
  if (a2.pos.length < 1 || a2.pos.length > 2) fail("convert needs <path> [out-dir]");
2939
3100
  const l = load(a2.pos[0], { format: a2.flags.format });
2940
3101
  const models = nodesOf(l);
2941
- const graphs = l.versions.map((v, i) => ({ name: v.name, graph: { name: v.name, ...toPhysical(models[i]) } }));
3102
+ const graphs = l.versions.map((v, i) => ({ name: v.name, graph: { name: v.name, ...l.profile ? { profile: l.profile } : {}, ...toPhysical(models[i]) } }));
2942
3103
  const outDir = a2.pos[1];
2943
3104
  if (!outDir) {
2944
3105
  if (graphs.length > 1) fail("several versions: give an out-dir");
2945
3106
  console.log(JSON.stringify(graphs[0].graph, null, 1));
2946
3107
  return;
2947
3108
  }
3109
+ const outputs = graphs.map((g) => path2.join(outDir, ...graphs.length > 1 ? [g.name] : [], "graph.json"));
3110
+ if (l.profile) outputs.push(path2.join(outDir, "_profile.json"));
3111
+ if (l.layouts) outputs.push(path2.join(outDir, "_layout.json"));
3112
+ const existing = outputs.find((file) => fs2.existsSync(file));
3113
+ if (existing) fail(`output already exists: ${existing}; choose a fresh output directory`);
2948
3114
  fs2.mkdirSync(outDir, { recursive: true });
2949
3115
  for (const g of graphs) {
2950
3116
  const dir = graphs.length > 1 ? path2.join(outDir, g.name) : outDir;