@atolis-hq/corum 0.1.57 → 0.1.58

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.
@@ -286,7 +286,7 @@ export function mapDocument(document, entry, packConfig, componentNameReplacemen
286
286
  nodes.push(makeNode(packConfig.constructs['enumDefinition']?.template ?? 'EnumDefinition', component, entry.spec, registeredId));
287
287
  for (const value of s.enum) {
288
288
  const valueId = deriveNodeId('enumValue', component, String(value), { parentId: registeredId, section: 'values' });
289
- const valueNode = makeNode(packConfig.constructs['enumValue']?.template ?? 'EnumValue', component, entry.spec, valueId);
289
+ const valueNode = makeNode(packConfig.constructs['enumValue']?.template ?? 'EnumValue', component, entry.spec, valueId, registeredId);
290
290
  valueNode.properties = { name: String(value) };
291
291
  nodes.push(valueNode);
292
292
  edges.push({ id: `${registeredId}__has-value__${valueId}`, from: registeredId, to: valueId, type: 'has-value', state: 'implemented', stability: 'unstable' });
@@ -363,7 +363,7 @@ export function mapDocument(document, entry, packConfig, componentNameReplacemen
363
363
  if (sourceSchema) {
364
364
  const schemaKey = payloadSchemaName;
365
365
  const schemaId = deriveNodeId('schema', component, schemaKey, { parentId: eventId, section: 'schemas' });
366
- nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, entry.spec, schemaId));
366
+ nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, entry.spec, schemaId, eventId));
367
367
  edges.push({ id: `${eventId}__has-field__${schemaId}`, from: eventId, to: schemaId, type: 'has-field', state: 'implemented', stability: 'unstable' });
368
368
  emitFields(sourceSchema, schemaId, 'fields', eventId, packConfig, entry.spec, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, new Map(), new Map());
369
369
  properties.payload = `#/schemas/${schemaKey}`;
@@ -372,7 +372,7 @@ export function mapDocument(document, entry, packConfig, componentNameReplacemen
372
372
  }
373
373
  else if (rawPayload.type === 'object' && rawPayload.properties) {
374
374
  const schemaId = deriveNodeId('schema', component, messageName, { parentId: eventId, section: 'schemas' });
375
- nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, entry.spec, schemaId));
375
+ nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, entry.spec, schemaId, eventId));
376
376
  edges.push({ id: `${eventId}__has-field__${schemaId}`, from: eventId, to: schemaId, type: 'has-field', state: 'implemented', stability: 'unstable' });
377
377
  emitFields(rawPayload, schemaId, 'fields', eventId, packConfig, entry.spec, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, new Map(), new Map());
378
378
  properties.payload = `#/schemas/${messageName}`;
@@ -399,9 +399,10 @@ export function mapDocument(document, entry, packConfig, componentNameReplacemen
399
399
  }
400
400
  return { nodes, edges, diagnostics };
401
401
  }
402
- function makeNode(template, component, specPath, id) {
402
+ function makeNode(template, component, specPath, id, parentId) {
403
403
  return {
404
404
  id,
405
+ ...(parentId !== undefined && { parentId }),
405
406
  template,
406
407
  component,
407
408
  state: 'implemented',
@@ -443,7 +444,7 @@ function resolveSchemaRef(schemaName, nullable, collection, rootId, component, p
443
444
  if (src) {
444
445
  const inlineId = deriveNodeId('schema', component, schemaName, { parentId: rootId, section: 'schemas' });
445
446
  if (!nodes.some(n => n.id === inlineId)) {
446
- nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, specPath, inlineId));
447
+ nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, specPath, inlineId, rootId));
447
448
  edges.push({ id: `${rootId}__has-field__${inlineId}`, from: rootId, to: inlineId, type: 'has-field', state: 'implemented', stability: 'unstable' });
448
449
  const localRef = `#/schemas/${schemaName}`;
449
450
  localSchemas.set(schemaName, localRef);
@@ -459,7 +460,7 @@ function createMapping(mappingName, addlRaw, parentId, rootId, component, packCo
459
460
  if (existingId)
460
461
  return existingId;
461
462
  const mappingId = `${parentId}.mappings.${mappingName}`;
462
- const mappingNode = makeNode('Mapping', component, specPath, mappingId);
463
+ const mappingNode = makeNode('Mapping', component, specPath, mappingId, parentId);
463
464
  const props = {};
464
465
  if (!addlRaw || typeof addlRaw === 'boolean') {
465
466
  props['type'] = 'string';
@@ -507,7 +508,7 @@ function emitFields(schema, parentId, section, rootId, packConfig, specPath, nod
507
508
  const resolvedSchemaId = componentSchemaIdOf(rawFieldSchema);
508
509
  const fieldSchema = resolveAllOfRef(rawFieldSchema);
509
510
  const fieldId = deriveNodeId('field', component, fieldName, { parentId, section });
510
- const fieldNode = makeNode(packConfig.constructs['payloadField']?.template ?? 'Field', component, specPath, fieldId);
511
+ const fieldNode = makeNode(packConfig.constructs['payloadField']?.template ?? 'Field', component, specPath, fieldId, parentId);
511
512
  const required = Array.isArray(schema.required) && schema.required.includes(fieldName);
512
513
  // Resolve reference: prefer x-parser-schema-id (resolved by @asyncapi/parser), fall back to literal $ref
513
514
  const schemaName = (resolvedSchemaId !== undefined && (sharedSchemas.has(resolvedSchemaId) || sourceSchemas.has(resolvedSchemaId)))
@@ -546,7 +547,7 @@ function emitFields(schema, parentId, section, rootId, packConfig, specPath, nod
546
547
  const schemaParent = rootId ?? parentId;
547
548
  const inlineId = deriveNodeId('schema', component, fieldName, { parentId: schemaParent, section: 'schemas' });
548
549
  if (!nodes.some(n => n.id === inlineId)) {
549
- nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, specPath, inlineId));
550
+ nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, specPath, inlineId, schemaParent));
550
551
  edges.push({ id: `${schemaParent}__has-field__${inlineId}`, from: schemaParent, to: inlineId, type: 'has-field', state: 'implemented', stability: 'unstable' });
551
552
  const localRef = `#/schemas/${fieldName}`;
552
553
  localSchemas.set(fieldName, localRef);
@@ -11,6 +11,7 @@ export function mapDocument(document, specPath, existingSchemas = new Map()) {
11
11
  const allSchemas = (document.components?.schemas ?? {});
12
12
  // Maps #/components/schemas/X and #/components/schemas/X/properties/Y to materialized node IDs
13
13
  const refToNodeId = new Map();
14
+ const documentNodeIds = new Set(Object.keys(document.nodes).map(normalizeNodeId));
14
15
  const rootNodeIds = getRootNodeIds(document.nodes);
15
16
  // Pre-pass: determine canonical component for each schema (shared if referenced by 2+ components)
16
17
  const schemaComponents = computeSchemaComponents(document, allSchemas);
@@ -41,7 +42,7 @@ export function mapDocument(document, specPath, existingSchemas = new Map()) {
41
42
  if (entry['x-aka']?.length) {
42
43
  properties['x-aka'] = entry['x-aka'];
43
44
  }
44
- const node = makeNode(entry.type, component, specPath, normalizedNodeId, entry.provenance, properties);
45
+ const node = makeNode(entry.type, component, specPath, normalizedNodeId, entry.provenance, properties, getDocumentParentId(normalizedNodeId, documentNodeIds));
45
46
  nodes.push(node);
46
47
  if (schemaName) {
47
48
  const expanded = new Map();
@@ -123,10 +124,16 @@ function computeSchemaComponents(document, allSchemas) {
123
124
  }
124
125
  return result;
125
126
  }
127
+ // Interchange documents encode explicit owned entries as {parent}.{section}.{name}.
128
+ // Materialize that relationship at the adapter boundary, before graph queries or writes.
129
+ function getDocumentParentId(nodeId, nodeIds) {
130
+ const parentId = nodeId.split('.').slice(0, -2).join('.');
131
+ return nodeIds.has(parentId) ? parentId : undefined;
132
+ }
126
133
  function getRootNodeIds(nodes) {
127
- const nodeIds = Object.keys(nodes).map(normalizeNodeId);
128
- return nodeIds
129
- .filter(nodeId => !nodeIds.some(other => other !== nodeId && nodeId.startsWith(`${other}.`)))
134
+ const nodeIds = new Set(Object.keys(nodes).map(normalizeNodeId));
135
+ return [...nodeIds]
136
+ .filter(nodeId => getDocumentParentId(nodeId, nodeIds) === undefined)
130
137
  .sort((a, b) => b.length - a.length);
131
138
  }
132
139
  function computeSchemaUsage(document, allSchemas, rootNodeIds) {
@@ -247,7 +254,8 @@ function addSchemaLink(schemaLinks, from, to) {
247
254
  function resolveOwningRootNodeId(nodeId, rootNodeIds) {
248
255
  if (nodeId.startsWith('#/'))
249
256
  return undefined;
250
- return rootNodeIds.find(rootNodeId => nodeId === rootNodeId || nodeId.startsWith(`${rootNodeId}.`));
257
+ // Interchange edge endpoints may be implicit; the longest declared root wins.
258
+ return [...rootNodeIds].sort((a, b) => b.length - a.length).find(rootNodeId => nodeId === rootNodeId || nodeId.startsWith(`${rootNodeId}.`));
251
259
  }
252
260
  function schemaRefName(ref) {
253
261
  const prefix = '#/components/schemas/';
@@ -316,7 +324,7 @@ function materializeStandaloneSchema(schemaName, component, allSchemas, nodes, e
316
324
  continue;
317
325
  const valueId = `${schemaId}.values.${value}`;
318
326
  refToNodeId.set(`${schemaRef}/properties/${value}`, valueId);
319
- nodes.push(makeNode('EnumValue', component, specPath, valueId, undefined, { name: value }));
327
+ nodes.push(makeNode('EnumValue', component, specPath, valueId, undefined, { name: value }, schemaId));
320
328
  edges.push(makeHasValueEdge(schemaId, valueId));
321
329
  }
322
330
  return schemaId;
@@ -328,7 +336,7 @@ function materializeStandaloneSchema(schemaName, component, allSchemas, nodes, e
328
336
  const fieldRef = `${schemaRef}/properties/${fieldName}`;
329
337
  if (!refToNodeId.has(fieldRef))
330
338
  refToNodeId.set(fieldRef, fieldId);
331
- const fieldNode = makeNode('Field', component, specPath, fieldId, undefined, {});
339
+ const fieldNode = makeNode('Field', component, specPath, fieldId, undefined, {}, schemaId);
332
340
  const required = Array.isArray(schemaDef?.required) && schemaDef.required.includes(fieldName);
333
341
  fieldNode.properties = resolveFieldProperties(fieldName, rawProp, required, schemaId, schemaId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents, existingSchemas, diagnostics);
334
342
  nodes.push(fieldNode);
@@ -366,7 +374,7 @@ function expandSchema(schemaName, rootNodeId, allSchemas, nodes, edges, specPath
366
374
  continue;
367
375
  const valueId = `${enumId}.values.${value}`;
368
376
  refToNodeId.set(`${schemaRef}/properties/${value}`, valueId);
369
- nodes.push(makeNode('EnumValue', enumComponent, specPath, valueId, undefined, { name: value }));
377
+ nodes.push(makeNode('EnumValue', enumComponent, specPath, valueId, undefined, { name: value }, enumId));
370
378
  edges.push(makeHasValueEdge(enumId, valueId));
371
379
  }
372
380
  }
@@ -392,7 +400,7 @@ function expandSchema(schemaName, rootNodeId, allSchemas, nodes, edges, specPath
392
400
  expanded.set(schemaName, schemaId);
393
401
  if (!refToNodeId.has(schemaRef))
394
402
  refToNodeId.set(schemaRef, schemaId);
395
- nodes.push(makeNode('Schema', component, specPath, schemaId, undefined, {}));
403
+ nodes.push(makeNode('Schema', component, specPath, schemaId, undefined, {}, rootNodeId));
396
404
  edges.push(makeHasFieldEdge(rootNodeId, schemaId));
397
405
  const localMappings = new Map();
398
406
  for (const [fieldName, rawProp] of Object.entries(schemaDef?.properties ?? {})) {
@@ -400,7 +408,7 @@ function expandSchema(schemaName, rootNodeId, allSchemas, nodes, edges, specPath
400
408
  const fieldRef = `${schemaRef}/properties/${fieldName}`;
401
409
  if (!refToNodeId.has(fieldRef))
402
410
  refToNodeId.set(fieldRef, fieldId);
403
- const fieldNode = makeNode('Field', component, specPath, fieldId, undefined, {});
411
+ const fieldNode = makeNode('Field', component, specPath, fieldId, undefined, {}, schemaId);
404
412
  const required = Array.isArray(schemaDef?.required) && schemaDef.required.includes(fieldName);
405
413
  fieldNode.properties = resolveFieldProperties(fieldName, rawProp, required, schemaId, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents, existingSchemas, diagnostics);
406
414
  nodes.push(fieldNode);
@@ -444,7 +452,7 @@ function createMapping(mappingName, addlDef, schemaId, rootNodeId, allSchemas, n
444
452
  return existing;
445
453
  const mappingId = `${schemaId}.mappings.${mappingName}`;
446
454
  localMappings.set(mappingName, mappingId);
447
- const mappingNode = makeNode('Mapping', component, specPath, mappingId, undefined, {});
455
+ const mappingNode = makeNode('Mapping', component, specPath, mappingId, undefined, {}, schemaId);
448
456
  const props = {};
449
457
  if (!addlDef || typeof addlDef === 'boolean') {
450
458
  props.type = 'string';
@@ -506,9 +514,10 @@ function mapScalar(type, format) {
506
514
  return 'boolean';
507
515
  return 'string';
508
516
  }
509
- function makeNode(template, component, specPath, id, provenance, properties) {
517
+ function makeNode(template, component, specPath, id, provenance, properties, parentId) {
510
518
  return {
511
519
  id,
520
+ ...(parentId !== undefined && { parentId }),
512
521
  template,
513
522
  component,
514
523
  state: 'implemented',
@@ -98,7 +98,7 @@ export function mapDocument(document, entry, packConfig, componentNameReplacemen
98
98
  nodes.push(enumNode);
99
99
  s.enum.forEach((value) => {
100
100
  const valueId = deriveNodeId('enumValue', undefined, String(value), enumId, 'values');
101
- const valueNode = makeNode(packConfig.constructs.enumValue?.template ?? 'EnumValue', component, entry.spec, valueId);
101
+ const valueNode = makeNode(packConfig.constructs.enumValue?.template ?? 'EnumValue', component, entry.spec, valueId, enumId);
102
102
  valueNode.properties = { name: String(value) };
103
103
  nodes.push(valueNode);
104
104
  edges.push({ id: `${enumId}__has-value__${valueId}`, from: enumId, to: valueId, type: 'has-value', state: 'implemented', stability: 'unstable' });
@@ -309,9 +309,10 @@ function extractParameters(pathItem, operation, packConfig, specPath, diagnostic
309
309
  }
310
310
  return Object.keys(parameters).length > 0 ? parameters : undefined;
311
311
  }
312
- function makeNode(template, component, specPath, id) {
312
+ function makeNode(template, component, specPath, id, parentId) {
313
313
  return {
314
314
  id,
315
+ ...(parentId !== undefined && { parentId }),
315
316
  template,
316
317
  component,
317
318
  state: 'implemented',
@@ -348,7 +349,7 @@ function emitSchemaNode(schema, name, parentId, section, rootId, packConfig, spe
348
349
  function createInlineSchema(schema, name, parentId, section, rootId, packConfig, specPath, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, localSchemas, localMappings) {
349
350
  const schemaId = deriveNodeId('schema', undefined, name, parentId, section);
350
351
  const [component] = parentId.split('.');
351
- const node = makeNode(packConfig.constructs.requestSchema?.template ?? 'Schema', component, specPath, schemaId);
352
+ const node = makeNode(packConfig.constructs.requestSchema?.template ?? 'Schema', component, specPath, schemaId, parentId);
352
353
  nodes.push(node);
353
354
  edges.push({ id: `${parentId}__has-field__${schemaId}`, from: parentId, to: schemaId, type: 'has-field', state: 'implemented', stability: 'unstable' });
354
355
  const localRef = `#/${section}/${name}`;
@@ -379,7 +380,7 @@ function createMapping(mappingName, addlRaw, parentId, rootId, packConfig, specP
379
380
  return existingId;
380
381
  const [component] = parentId.split('.');
381
382
  const mappingId = `${parentId}.mappings.${mappingName}`;
382
- const mappingNode = makeNode('Mapping', component, specPath, mappingId);
383
+ const mappingNode = makeNode('Mapping', component, specPath, mappingId, parentId);
383
384
  const props = {};
384
385
  if (typeof addlRaw === 'boolean' || addlRaw === undefined) {
385
386
  props['type'] = 'string';
@@ -459,7 +460,7 @@ function emitFields(schema, parentId, section, rootId, packConfig, specPath, nod
459
460
  const fieldSchema = resolveAllOfRef(rawFieldSchema);
460
461
  const fieldId = deriveNodeId('field', undefined, fieldName, parentId, section);
461
462
  const [component] = parentId.split('.');
462
- const fieldNode = makeNode(packConfig.constructs.schemaProperty?.template ?? 'Field', component, specPath, fieldId);
463
+ const fieldNode = makeNode(packConfig.constructs.schemaProperty?.template ?? 'Field', component, specPath, fieldId, parentId);
463
464
  const required = Array.isArray(schema.required) && schema.required.includes(fieldName);
464
465
  if (isRefSchema(fieldSchema)) {
465
466
  fieldNode.properties = resolveFieldRef(refName(fieldSchema.$ref), 'one', required, rootId, fieldSchema, packConfig, specPath, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, localSchemas, localMappings);
@@ -65,12 +65,23 @@ export function listNodes(graph, filter = {}) {
65
65
  return true;
66
66
  });
67
67
  }
68
+ /** Whether a node belongs to an owner's transitive materialized parent chain. */
69
+ export function isOwnedDescendant(graph, nodeId, ownerId) {
70
+ const seen = new Set([nodeId]);
71
+ let parentId = graph.nodesById.get(nodeId)?.parentId;
72
+ while (parentId !== undefined && !seen.has(parentId)) {
73
+ if (parentId === ownerId)
74
+ return true;
75
+ seen.add(parentId);
76
+ parentId = graph.nodesById.get(parentId)?.parentId;
77
+ }
78
+ return false;
79
+ }
68
80
  export function getCluster(graph, nodeId) {
69
81
  const root = graph.nodesById.get(nodeId);
70
82
  if (!root)
71
83
  throw new QueryError(`Node not found: ${nodeId}`);
72
- const prefix = `${nodeId}.`;
73
- const children = [...graph.nodesById.values()].filter(node => node.id.startsWith(prefix));
84
+ const children = [...graph.nodesById.values()].filter(node => isOwnedDescendant(graph, node.id, nodeId));
74
85
  const clusterIds = new Set([nodeId, ...children.map(node => node.id)]);
75
86
  const edges = [];
76
87
  const seen = new Set();
@@ -167,9 +178,8 @@ export function expandExternalNodes(graph, externalIds) {
167
178
  }
168
179
  for (const id of dataQueue) {
169
180
  // Include structural children (fields, values, mappings)
170
- const prefix = `${id}.`;
171
181
  for (const childId of graph.nodesById.keys()) {
172
- if (childId.startsWith(prefix))
182
+ if (isOwnedDescendant(graph, childId, id))
173
183
  result.add(childId);
174
184
  }
175
185
  // Follow outbound uses-type one hop to collect referenced enum/schema types
@@ -181,9 +191,8 @@ export function expandExternalNodes(graph, externalIds) {
181
191
  continue;
182
192
  result.add(edge.to);
183
193
  if (isDataNodeTemplate(graph, target.template)) {
184
- const targetPrefix = `${edge.to}.`;
185
194
  for (const childId of graph.nodesById.keys()) {
186
- if (childId.startsWith(targetPrefix))
195
+ if (isOwnedDescendant(graph, childId, edge.to))
187
196
  result.add(childId);
188
197
  }
189
198
  }
@@ -199,9 +208,8 @@ export function getLinkedFields(graph, nodeId) {
199
208
  const root = graph.nodesById.get(rootId);
200
209
  if (!root)
201
210
  throw new QueryError(`Node not found: ${nodeId}`);
202
- const prefix = `${rootId}.`;
203
211
  const ownedFieldIds = new Set([...graph.nodesById.entries()]
204
- .filter(([id, node]) => id.startsWith(prefix) && templateHasRole(graph.templates, node.template, 'field'))
212
+ .filter(([id, node]) => isOwnedDescendant(graph, id, rootId) && templateHasRole(graph.templates, node.template, 'field'))
205
213
  .map(([id]) => id));
206
214
  const edges = [];
207
215
  const nodeIds = new Set();
@@ -232,11 +240,10 @@ export function getLinkedFields(graph, nodeId) {
232
240
  }
233
241
  function findParent(graph, nodeId) {
234
242
  const node = graph.nodesById.get(nodeId);
235
- if (node?.parentId !== undefined && graph.nodesById.has(node.parentId)) {
236
- return node.parentId;
237
- }
238
- // Fallback for nodes without a materialised parentId (e.g. adapter output
239
- // before a load round-trip): walk the ID hierarchy in 2-segment strides.
243
+ if (node)
244
+ return node.parentId !== undefined && graph.nodesById.has(node.parentId) ? node.parentId : undefined;
245
+ // Fallback only for absent IDs (e.g. retired field IDs): walk the hierarchy in
246
+ // 2-segment strides. Existing nodes use only materialized ownership.
240
247
  const parts = nodeId.split('.');
241
248
  let endIdx = parts.length - 2;
242
249
  while (endIdx >= 1) {
@@ -250,17 +257,21 @@ function findParent(graph, nodeId) {
250
257
  const OVERLAY_EXCLUDED = new Set(['local', 'shared']);
251
258
  export function computeClusterOverlay(multi, viewingRef, overlayRefs, clusterRootId) {
252
259
  const overlay = multi.overlay(viewingRef);
253
- const prefix = `${clusterRootId}.`;
260
+ const graphsByRef = new Map([multi.default, ...multi.branches].map(branch => [branch.ref, branch.graph]));
254
261
  const fields = [...overlay.nodes.values()]
255
262
  .filter(node => {
256
263
  if (OVERLAY_EXCLUDED.has(node.ghostState))
257
264
  return false;
258
- if (!node.id.startsWith(prefix))
259
- return false;
260
- return overlayRefs.some(ref => node.presence.has(ref));
265
+ return overlayRefs.some(ref => {
266
+ const graph = graphsByRef.get(ref);
267
+ return node.presence.has(ref) && graph !== undefined && isOwnedDescendant(graph, node.id, clusterRootId);
268
+ });
261
269
  })
262
270
  .map(node => {
263
- const sourceRef = overlayRefs.find(ref => node.presence.has(ref)) ?? viewingRef;
271
+ const sourceRef = overlayRefs.find(ref => {
272
+ const graph = graphsByRef.get(ref);
273
+ return node.presence.has(ref) && graph !== undefined && isOwnedDescendant(graph, node.id, clusterRootId);
274
+ }) ?? viewingRef;
264
275
  const sourceNode = node.presence.get(sourceRef) ?? [...node.presence.values()][0];
265
276
  return { id: node.id, ghostState: node.ghostState, sourceRef, node: sourceNode };
266
277
  });
@@ -1,9 +1,8 @@
1
- import { getStructuralNodeTemplates, isVisibleEdgeType } from './index.js';
1
+ import { getStructuralNodeTemplates, isVisibleEdgeType, isOwnedDescendant } from './index.js';
2
2
  import { getTemplateRole } from './roles.js';
3
3
  const FIELD_EDGE_TYPES = new Set(['maps-to', 'derived-from']);
4
4
  export function collapseClusterSchemas(graph, cluster) {
5
5
  const rootId = cluster.root.id;
6
- const rootPrefix = `${rootId}.`;
7
6
  // Indexes keyed by local name or parent ID
8
7
  const schemaChildIds = new Set();
9
8
  const schemaNames = new Map(); // localName → nodeId
@@ -23,7 +22,7 @@ export function collapseClusterSchemas(graph, cluster) {
23
22
  return parent ? getTemplateRole(graph.templates, parent.template) : undefined;
24
23
  };
25
24
  for (const n of cluster.descendants) {
26
- if (!n.id.startsWith(rootPrefix)) {
25
+ if (!isOwnedDescendant(graph, n.id, rootId)) {
27
26
  semanticDescendants.push(n);
28
27
  continue;
29
28
  }
@@ -137,12 +136,11 @@ function buildField(fieldNode, graph, rootId, parentMappings) {
137
136
  if (isNullable)
138
137
  field.nullable = true;
139
138
  // Gather outbound field edges that cross the cluster boundary
140
- const clusterPrefix = `${rootId}.`;
141
139
  const fieldEdges = {};
142
140
  for (const e of graph.edgesByFrom.get(fieldNode.id) ?? []) {
143
141
  if (!FIELD_EDGE_TYPES.has(e.type))
144
142
  continue;
145
- if (e.to.startsWith(clusterPrefix))
143
+ if (isOwnedDescendant(graph, e.to, rootId))
146
144
  continue;
147
145
  const targets = fieldEdges[e.type] ?? [];
148
146
  targets.push(e.to);
@@ -1,3 +1,4 @@
1
+ import { isOwnedDescendant } from '../graph/index.js';
1
2
  export function deduplicateResults(results, rules) {
2
3
  const diagnostics = [];
3
4
  for (const rule of rules) {
@@ -8,7 +9,12 @@ export function deduplicateResults(results, rules) {
8
9
  primaryNodes.set(node.id, node);
9
10
  }
10
11
  }
11
- const primaryNodeIds = new Set(primaryNodes.keys());
12
+ const secondaryGraph = {
13
+ nodesById: new Map(results
14
+ .filter(result => result.adapterId === rule.secondary)
15
+ .flatMap(result => result.nodes.map(node => [node.id, node]))),
16
+ };
17
+ const primaryGraph = { nodesById: primaryNodes };
12
18
  const redirects = new Map();
13
19
  // Phase 1a: x-aka matching
14
20
  for (const r of results) {
@@ -45,7 +51,7 @@ export function deduplicateResults(results, rules) {
45
51
  }
46
52
  // Phase 2: add only root collisions (those not covered by another collision)
47
53
  for (const nodeId of rawSameIds) {
48
- const coveredByRoot = rawSameIds.some(id => id !== nodeId && nodeId.startsWith(id + '.'));
54
+ const coveredByRoot = rawSameIds.some(id => isOwnedDescendant(secondaryGraph, nodeId, id));
49
55
  if (!coveredByRoot) {
50
56
  redirects.set(nodeId, nodeId);
51
57
  diagnostics.push({
@@ -57,24 +63,38 @@ export function deduplicateResults(results, rules) {
57
63
  }
58
64
  if (redirects.size === 0)
59
65
  continue;
60
- for (const r of results) {
61
- r.edges = r.edges.flatMap(edge => {
62
- const rewritten = rewriteEdge(edge, redirects, primaryNodeIds);
63
- return rewritten === null ? [] : [rewritten];
64
- });
66
+ // Build exact endpoint mappings from ownership before dropping secondary nodes.
67
+ // Prefix replacement derives the new spelling only after ownership is known.
68
+ const endpointRedirects = new Map();
69
+ for (const node of secondaryGraph.nodesById.values()) {
70
+ let current = node;
71
+ const seen = new Set();
72
+ while (current && !seen.has(current.id)) {
73
+ seen.add(current.id);
74
+ const primaryId = redirects.get(current.id);
75
+ if (primaryId !== undefined) {
76
+ const rewritten = primaryId + node.id.slice(current.id.length);
77
+ const targetExists = primaryNodes.has(rewritten)
78
+ && (node.id === current.id || isOwnedDescendant(primaryGraph, rewritten, primaryId));
79
+ endpointRedirects.set(node.id, primaryId === current.id || targetExists ? rewritten : null);
80
+ break;
81
+ }
82
+ current = current.parentId === undefined ? undefined : secondaryGraph.nodesById.get(current.parentId);
83
+ }
65
84
  }
66
85
  for (const r of results) {
67
- if (r.adapterId !== rule.secondary)
68
- continue;
69
- r.nodes = r.nodes.filter(node => {
70
- if (redirects.has(node.id))
71
- return false;
72
- for (const secondaryId of redirects.keys()) {
73
- if (node.id.startsWith(secondaryId + '.'))
74
- return false;
75
- }
76
- return true;
86
+ r.edges = r.edges.flatMap(edge => {
87
+ const from = endpointRedirects.has(edge.from) ? endpointRedirects.get(edge.from) : edge.from;
88
+ const to = endpointRedirects.has(edge.to) ? endpointRedirects.get(edge.to) : edge.to;
89
+ if (from === null || to === null)
90
+ return [];
91
+ if (from === edge.from && to === edge.to)
92
+ return [edge];
93
+ return [{ ...edge, from, to, id: `${from}__${edge.type}__${to}` }];
77
94
  });
95
+ if (r.adapterId === rule.secondary) {
96
+ r.nodes = r.nodes.filter(node => !endpointRedirects.has(node.id));
97
+ }
78
98
  }
79
99
  }
80
100
  for (const r of results) {
@@ -84,29 +104,3 @@ export function deduplicateResults(results, rules) {
84
104
  }
85
105
  return { results, diagnostics };
86
106
  }
87
- function rewriteEdge(edge, redirects, primaryNodeIds) {
88
- const from = rewriteEndpoint(edge.from, redirects, primaryNodeIds);
89
- const to = rewriteEndpoint(edge.to, redirects, primaryNodeIds);
90
- if (from === null || to === null)
91
- return null;
92
- if (from === edge.from && to === edge.to)
93
- return edge;
94
- return { ...edge, from, to, id: `${from}__${edge.type}__${to}` };
95
- }
96
- function rewriteEndpoint(endpoint, redirects, primaryNodeIds) {
97
- const exact = redirects.get(endpoint);
98
- if (exact !== undefined && exact !== endpoint)
99
- return exact;
100
- for (const [secondaryId, primaryId] of redirects) {
101
- if (secondaryId === primaryId)
102
- continue;
103
- const prefix = secondaryId + '.';
104
- if (endpoint.startsWith(prefix)) {
105
- const rewritten = primaryId + '.' + endpoint.slice(prefix.length);
106
- if (!primaryNodeIds.has(rewritten))
107
- return null;
108
- return rewritten;
109
- }
110
- }
111
- return endpoint;
112
- }
@@ -37,7 +37,7 @@ export async function runImport(config, runtimeConfig, options = {}) {
37
37
  const graph = await loadGraph({ source, ref: targetBranchExists ? targetBranch : defaultBranch });
38
38
  // ADR-009b: snapshot of node identities before this run, and the shared
39
39
  // reuse-before-inline index (target graph + same-run entries as they land).
40
- const priorNodeIds = new Set(graph.nodesById.keys());
40
+ const priorNodes = new Map(graph.nodesById);
41
41
  const existingSchemas = buildExistingSchemaIndex(graph);
42
42
  const entryResults = [];
43
43
  for (const entry of config.imports) {
@@ -82,8 +82,7 @@ export async function runImport(config, runtimeConfig, options = {}) {
82
82
  const newlyCreatedSchemaIds = new Set();
83
83
  for (const er of entryResults) {
84
84
  for (const node of er.nodes) {
85
- const parts = node.id.split('.');
86
- if (parts.length === 3 && parts[1] === 'Schema')
85
+ if (node.parentId === undefined && node.template === 'Schema')
87
86
  newlyCreatedSchemaIds.add(node.id);
88
87
  }
89
88
  }
@@ -114,7 +113,7 @@ export async function runImport(config, runtimeConfig, options = {}) {
114
113
  }
115
114
  // ADR-009b rule 4: mechanically rewrite edges when a schema was promoted
116
115
  // inline → standalone by this run.
117
- const promotions = detectSchemaPromotions(priorNodeIds, newlyCreatedSchemaIds);
116
+ const promotions = detectSchemaPromotions(priorNodes, newlyCreatedSchemaIds);
118
117
  rewritePromotedSchemaEdges(graph, promotions, allDiagnostics);
119
118
  const graphPath = runtimeConfig.kind === 'filesystem' ? runtimeConfig.graphPath : undefined;
120
119
  const contentMap = serializeGraph(graph, { sourceGraphPath: graphPath, outputGraphPath: graphPath });
@@ -1,20 +1,21 @@
1
+ import { isOwnedDescendant } from '../graph/index.js';
1
2
  /**
2
- * ADR-009b rule 1 support: index of existing standalone schemas (`{component}.Schema.{name}`)
3
+ * ADR-009b rule 1 support: index of existing standalone Schema roots
3
4
  * and their field names, used by adapters to reuse-before-inline and to detect shape drift.
4
5
  * Schemas marked `removed` are excluded — they are no longer available for reuse.
5
6
  */
6
7
  export function buildExistingSchemaIndex(graph) {
7
8
  const index = new Map();
8
9
  for (const node of graph.nodesById.values()) {
9
- const parts = node.id.split('.');
10
- if (parts.length !== 3 || parts[1] !== 'Schema')
10
+ if (node.parentId !== undefined || node.template !== 'Schema')
11
11
  continue;
12
12
  if (node.state === 'removed')
13
13
  continue;
14
14
  const fields = new Set();
15
15
  const prefix = `${node.id}.fields.`;
16
16
  for (const other of graph.nodesById.values()) {
17
- if (!other.id.startsWith(prefix))
17
+ // The prefix parses a section name; parentId establishes ownership.
18
+ if (other.parentId !== node.id || !other.id.startsWith(prefix))
18
19
  continue;
19
20
  if (other.id.slice(prefix.length).includes('.'))
20
21
  continue;
@@ -30,13 +31,16 @@ export function buildExistingSchemaIndex(graph) {
30
31
  * this run, matched against any prior inline copy (`{rootId}.schemas.{N}`) under
31
32
  * the same component.
32
33
  */
33
- export function detectSchemaPromotions(priorNodeIds, newlyCreatedSchemaIds) {
34
+ export function detectSchemaPromotions(priorNodes, newlyCreatedSchemaIds) {
34
35
  const promotions = [];
35
36
  for (const newId of newlyCreatedSchemaIds) {
36
- if (priorNodeIds.has(newId))
37
+ if (priorNodes.has(newId))
37
38
  continue;
38
- const [component, , name] = newId.split('.');
39
- for (const oldId of priorNodeIds) {
39
+ const [component, , ...nameParts] = newId.split('.');
40
+ const name = nameParts.join('.');
41
+ for (const [oldId, oldNode] of priorNodes) {
42
+ if (oldNode.parentId === undefined)
43
+ continue;
40
44
  if (oldId.split('.')[0] !== component)
41
45
  continue;
42
46
  if (oldId.endsWith(`.schemas.${name}`)) {
@@ -62,11 +66,12 @@ export function rewritePromotedSchemaEdges(graph, promotions, diagnostics) {
62
66
  }
63
67
  function rewriteEndpoint(id) {
64
68
  for (const { oldPrefix, newPrefix } of promotions) {
65
- if (id !== oldPrefix && !id.startsWith(`${oldPrefix}.`))
69
+ if (id !== oldPrefix && !isOwnedDescendant(graph, id, oldPrefix))
66
70
  continue;
67
71
  const rewritten = newPrefix + id.slice(oldPrefix.length);
68
- if (!graph.nodesById.has(rewritten))
72
+ if (!graph.nodesById.has(rewritten) || (id !== oldPrefix && !isOwnedDescendant(graph, rewritten, newPrefix))) {
69
73
  return { id, changed: false, unresolved: true };
74
+ }
70
75
  return { id: rewritten, changed: true, unresolved: false };
71
76
  }
72
77
  return { id, changed: false, unresolved: false };
@@ -1,7 +1,7 @@
1
1
  import { validateSegment } from '../loader/id-grammar.js';
2
2
  import { buildAliasMap } from './alias.js';
3
3
  import { MutationError } from './errors.js';
4
- import { collectEdgesTouching, insertEdgeIntoIndexes, mutationDiagnostic, mutationTimestamp, removeEdgeFromIndexes, } from './util.js';
4
+ import { collectEdgesTouching, collectSubtreeIds, insertEdgeIntoIndexes, mutationDiagnostic, mutationTimestamp, removeEdgeFromIndexes, } from './util.js';
5
5
  /**
6
6
  * Trail threshold (design §4/§14c): a rename or delete records a trail iff
7
7
  * the node's ID exists in the default branch's committed graph. The explicit
@@ -20,7 +20,7 @@ export function replaceLastSegment(id, newName) {
20
20
  }
21
21
  /**
22
22
  * First-class rename (design §3, §14a). Rewrites the node ID, every
23
- * descendant ID (exact-segment prefix), parentId fields, and every edge
23
+ * owned descendant ID, parentId fields, and every edge
24
24
  * endpoint referencing an affected ID; optionally records the trail
25
25
  * (`corum.identity.previousIds` + `renamed-from` edge). Validates everything before the
26
26
  * first write — a thrown MutationError leaves the graph untouched.
@@ -42,10 +42,11 @@ export function renameNode(graph, oldId, newName, recordTrail) {
42
42
  if (newId === oldId) {
43
43
  throw new MutationError([mutationDiagnostic('error', `cannot rename ${oldId}: new name equals current name`, oldId)]);
44
44
  }
45
- const newPrefix = `${newId}.`;
46
- for (const id of graph.nodesById.keys()) {
47
- if (id === newId || id.startsWith(newPrefix)) {
48
- errors.push(mutationDiagnostic('error', `cannot rename ${oldId} to ${newId}: node ${id} already exists`, oldId));
45
+ // Ownership selects which nodes move; prefix replacement only derives their new IDs.
46
+ const idMap = new Map(collectSubtreeIds(graph, oldId).map(id => [id, newId + id.slice(oldId.length)]));
47
+ for (const targetId of idMap.values()) {
48
+ if (graph.nodesById.has(targetId)) {
49
+ errors.push(mutationDiagnostic('error', `cannot rename ${oldId} to ${newId}: node ${targetId} already exists`, oldId));
49
50
  }
50
51
  }
51
52
  if (errors.length > 0)
@@ -54,14 +55,6 @@ export function renameNode(graph, oldId, newName, recordTrail) {
54
55
  if (aliasMap.has(newId)) {
55
56
  warnings.push(mutationDiagnostic('warning', `new id ${newId} is a retired id (previously renamed to ${aliasMap.get(newId)}); the live node wins for resolution`, newId));
56
57
  }
57
- // -- Step 2: build the id map (node + exact-segment descendants) ---------
58
- const oldPrefix = `${oldId}.`;
59
- const idMap = new Map();
60
- idMap.set(oldId, newId);
61
- for (const id of graph.nodesById.keys()) {
62
- if (id.startsWith(oldPrefix))
63
- idMap.set(id, newId + id.slice(oldId.length));
64
- }
65
58
  // -- Step 3: collect affected edges (exact endpoint match) ---------------
66
59
  const affectedEdges = collectEdgesTouching(graph, idMap.keys());
67
60
  // -- Step 4: apply --------------------------------------------------------
@@ -1,3 +1,4 @@
1
+ import { isOwnedDescendant } from '../graph/index.js';
1
2
  /** Timestamp convention for mutated nodes (matches adapter mappers: date-only ISO). */
2
3
  export function mutationTimestamp() {
3
4
  return new Date().toISOString().split('T')[0];
@@ -6,14 +7,12 @@ export function mutationDiagnostic(severity, message, nodeId) {
6
7
  return { severity, file: '<mutation>', ...(nodeId !== undefined && { nodeId }), message };
7
8
  }
8
9
  /**
9
- * IDs of a node's owned subtree (the node itself plus every exact-segment
10
- * descendant — `orders.x` never matches `orders.xy`).
10
+ * IDs of a node's owned subtree, following materialized parent relationships.
11
11
  */
12
12
  export function collectSubtreeIds(graph, rootId) {
13
- const prefix = `${rootId}.`;
14
13
  const ids = [];
15
14
  for (const id of graph.nodesById.keys()) {
16
- if (id === rootId || id.startsWith(prefix))
15
+ if (id === rootId || isOwnedDescendant(graph, id, rootId))
17
16
  ids.push(id);
18
17
  }
19
18
  return ids;
@@ -118,7 +118,7 @@ function getDirectOwnedChildren(graph, parentId, sectionName, sourceSection) {
118
118
  const prefix = `${parentId}.${sectionName}.`;
119
119
  const children = [...graph.nodesById.values()]
120
120
  .filter(node => {
121
- if (!node.id.startsWith(prefix))
121
+ if (node.parentId !== parentId || !node.id.startsWith(prefix))
122
122
  return false;
123
123
  const remaining = node.id.slice(prefix.length);
124
124
  return !remaining.includes('.');
@@ -240,6 +240,6 @@ function getAllEdges(graph) {
240
240
  function getRootNodes(graph) {
241
241
  const nodes = [...graph.nodesById.values()];
242
242
  return nodes
243
- .filter(node => !nodes.some(other => other.id !== node.id && node.id.startsWith(`${other.id}.`)))
243
+ .filter(node => node.parentId === undefined)
244
244
  .sort((a, b) => a.id.localeCompare(b.id));
245
245
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atolis-hq/corum",
3
- "version": "0.1.57",
3
+ "version": "0.1.58",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",