@atolis-hq/corum 0.1.39 → 0.1.41

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.
@@ -0,0 +1,103 @@
1
+ /**
2
+ * ADR-009b rule 1 support: index of existing standalone schemas (`{component}.Schema.{name}`)
3
+ * and their field names, used by adapters to reuse-before-inline and to detect shape drift.
4
+ * Schemas marked `removed` are excluded — they are no longer available for reuse.
5
+ */
6
+ export function buildExistingSchemaIndex(graph) {
7
+ const index = new Map();
8
+ for (const node of graph.nodesById.values()) {
9
+ const parts = node.id.split('.');
10
+ if (parts.length !== 3 || parts[1] !== 'Schema')
11
+ continue;
12
+ if (node.state === 'removed')
13
+ continue;
14
+ const fields = new Set();
15
+ const prefix = `${node.id}.fields.`;
16
+ for (const other of graph.nodesById.values()) {
17
+ if (!other.id.startsWith(prefix))
18
+ continue;
19
+ if (other.id.slice(prefix.length).includes('.'))
20
+ continue;
21
+ fields.add(other.id.slice(prefix.length));
22
+ }
23
+ index.set(node.id, fields);
24
+ }
25
+ return index;
26
+ }
27
+ /**
28
+ * ADR-009b rule 4: detect inline→standalone promotions produced by this run —
29
+ * a newly created standalone schema (`{C}.Schema.{N}`) that did not exist before
30
+ * this run, matched against any prior inline copy (`{rootId}.schemas.{N}`) under
31
+ * the same component.
32
+ */
33
+ export function detectSchemaPromotions(priorNodeIds, newlyCreatedSchemaIds) {
34
+ const promotions = [];
35
+ for (const newId of newlyCreatedSchemaIds) {
36
+ if (priorNodeIds.has(newId))
37
+ continue;
38
+ const [component, , name] = newId.split('.');
39
+ for (const oldId of priorNodeIds) {
40
+ if (oldId.split('.')[0] !== component)
41
+ continue;
42
+ if (oldId.endsWith(`.schemas.${name}`)) {
43
+ promotions.push({ oldPrefix: oldId, newPrefix: newId });
44
+ }
45
+ }
46
+ }
47
+ return promotions;
48
+ }
49
+ /**
50
+ * ADR-009b rule 4: mechanically rewrite every edge endpoint that falls under a
51
+ * promoted schema's old subtree to the new subtree — import-derived and
52
+ * design-derived edges alike. Warns (and leaves the edge untouched) when the
53
+ * rewritten target does not exist in the new subtree.
54
+ */
55
+ export function rewritePromotedSchemaEdges(graph, promotions, diagnostics) {
56
+ if (promotions.length === 0)
57
+ return;
58
+ const allEdges = new Map();
59
+ for (const edges of graph.edgesByFrom.values()) {
60
+ for (const edge of edges)
61
+ allEdges.set(edge.id, edge);
62
+ }
63
+ function rewriteEndpoint(id) {
64
+ for (const { oldPrefix, newPrefix } of promotions) {
65
+ if (id !== oldPrefix && !id.startsWith(`${oldPrefix}.`))
66
+ continue;
67
+ const rewritten = newPrefix + id.slice(oldPrefix.length);
68
+ if (!graph.nodesById.has(rewritten))
69
+ return { id, changed: false, unresolved: true };
70
+ return { id: rewritten, changed: true, unresolved: false };
71
+ }
72
+ return { id, changed: false, unresolved: false };
73
+ }
74
+ for (const edge of allEdges.values()) {
75
+ const from = rewriteEndpoint(edge.from);
76
+ const to = rewriteEndpoint(edge.to);
77
+ if (from.unresolved || to.unresolved) {
78
+ diagnostics.push({
79
+ severity: 'warning',
80
+ file: '',
81
+ message: `Cannot rewrite edge ${edge.id} for schema promotion — rewritten target does not exist (unresolvable)`,
82
+ });
83
+ continue;
84
+ }
85
+ if (!from.changed && !to.changed)
86
+ continue;
87
+ removeEdge(graph, edge);
88
+ const rewritten = { ...edge, from: from.id, to: to.id, id: `${from.id}__${edge.type}__${to.id}` };
89
+ addEdge(graph, rewritten);
90
+ }
91
+ }
92
+ function removeEdge(graph, edge) {
93
+ const fromList = graph.edgesByFrom.get(edge.from);
94
+ if (fromList)
95
+ graph.edgesByFrom.set(edge.from, fromList.filter(e => e.id !== edge.id));
96
+ const toList = graph.edgesByTo.get(edge.to);
97
+ if (toList)
98
+ graph.edgesByTo.set(edge.to, toList.filter(e => e.id !== edge.id));
99
+ }
100
+ function addEdge(graph, edge) {
101
+ graph.edgesByFrom.set(edge.from, [...(graph.edgesByFrom.get(edge.from) ?? []), edge]);
102
+ graph.edgesByTo.set(edge.to, [...(graph.edgesByTo.get(edge.to) ?? []), edge]);
103
+ }
@@ -0,0 +1,221 @@
1
+ import { getEdgeTypeConstraints } from '../graph/roles.js';
2
+ import { getTemplateSchema } from '../loader/template-props.js';
3
+ /**
4
+ * Full linter rule set (ADR-006 / ADR-006b, review finding S6).
5
+ *
6
+ * Runs against an already-loaded Graph and returns warning-severity
7
+ * diagnostics only — the linter never raises errors, since the underlying
8
+ * structural invariants it depends on (node/edge existence, template
9
+ * resolution) are already enforced by the loader itself. Callers append the
10
+ * result to the loader's diagnostics array; `strict` loads are unaffected
11
+ * because they only throw on `error` severity.
12
+ *
13
+ * Rules implemented (see docs/adr/REF-006-rules.md for the full catalogue):
14
+ * - T-003/T-004/T-005: node properties validated (shallow) against the
15
+ * owning template's JSON-schema-like `properties` block.
16
+ * - E-005/E-006: explicit (non-generated) edges validated against the
17
+ * endpoint templates' declared `edge-types` outgoing/incoming/supports.
18
+ * - Edge property validation: edge.properties validated against the
19
+ * matching EdgeTypeDef's `properties` schema, using the same shallow
20
+ * validator as node properties.
21
+ * - ADR-009b rule 5: flags an inline schema (`{rootId}.schemas.{name}`)
22
+ * whose (component, name) matches an existing standalone schema
23
+ * (`{component}.Schema.{name}`) — the order-dependent interim state
24
+ * between an importer creating the inline copy and a later re-import
25
+ * converging it via reuse-before-inline.
26
+ */
27
+ export function lintGraph(graph) {
28
+ const diagnostics = [];
29
+ lintNodeProperties(graph, diagnostics);
30
+ lintEdgeTypeConstraints(graph, diagnostics);
31
+ lintEdgeProperties(graph, diagnostics);
32
+ lintInlineStandaloneSchemaCollisions(graph, diagnostics);
33
+ return diagnostics;
34
+ }
35
+ function lintInlineStandaloneSchemaCollisions(graph, diagnostics) {
36
+ for (const node of graph.nodesById.values()) {
37
+ const parts = node.id.split('.');
38
+ // Only inline schema nodes themselves (`{rootId}.schemas.{name}`) — not their
39
+ // fields/descendants, and not standalone schemas (`{component}.Schema.{name}`).
40
+ if (parts.length < 3 || parts[parts.length - 2] !== 'schemas')
41
+ continue;
42
+ const name = parts[parts.length - 1];
43
+ const standaloneId = `${node.component}.Schema.${name}`;
44
+ const standalone = graph.nodesById.get(standaloneId);
45
+ if (!standalone || standalone.state === 'removed')
46
+ continue;
47
+ diagnostics.push({
48
+ severity: 'warning',
49
+ file: approxFilePath(graph, node),
50
+ nodeId: node.id,
51
+ message: `inline schema '${node.id}' collides with existing standalone schema '${standaloneId}' — re-import to converge via reuse-before-inline`,
52
+ });
53
+ }
54
+ }
55
+ function lintNodeProperties(graph, diagnostics) {
56
+ for (const node of graph.nodesById.values()) {
57
+ const template = graph.templates.get(node.template);
58
+ if (!template?.properties)
59
+ continue;
60
+ const schema = getTemplateSchema(template.properties);
61
+ const file = approxFilePath(graph, node);
62
+ if (!schema.additionalProperties) {
63
+ for (const key of Object.keys(node.properties)) {
64
+ if (!(key in schema.properties)) {
65
+ diagnostics.push({
66
+ severity: 'warning',
67
+ file,
68
+ nodeId: node.id,
69
+ message: `unknown property '${key}' is not declared in template '${node.template}'`,
70
+ });
71
+ }
72
+ }
73
+ }
74
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
75
+ const value = node.properties[key];
76
+ if (value === undefined)
77
+ continue;
78
+ const type = propSchema.type;
79
+ if (typeof type === 'string' && !valueMatchesType(value, type)) {
80
+ diagnostics.push({
81
+ severity: 'warning',
82
+ file,
83
+ nodeId: node.id,
84
+ message: `property '${key}' expected type '${type}' but got '${describeType(value)}'`,
85
+ });
86
+ }
87
+ }
88
+ for (const key of schema.required) {
89
+ if (node.properties[key] === undefined) {
90
+ diagnostics.push({
91
+ severity: 'warning',
92
+ file,
93
+ nodeId: node.id,
94
+ message: `missing required property '${key}' declared by template '${node.template}'`,
95
+ });
96
+ }
97
+ }
98
+ }
99
+ }
100
+ function lintEdgeTypeConstraints(graph, diagnostics) {
101
+ for (const edges of graph.edgesByFrom.values()) {
102
+ for (const edge of edges) {
103
+ if (edge.generated)
104
+ continue;
105
+ const fromNode = graph.nodesById.get(edge.from);
106
+ if (fromNode) {
107
+ const constraints = getEdgeTypeConstraints(graph.templates, fromNode.template);
108
+ if (constraints) {
109
+ const allowed = new Set([...(constraints.outgoing ?? []), ...(constraints.supports ?? [])]);
110
+ if (!allowed.has(edge.type)) {
111
+ diagnostics.push({
112
+ severity: 'warning',
113
+ file: approxFilePath(graph, fromNode),
114
+ nodeId: fromNode.id,
115
+ message: `edge type '${edge.type}' is not declared as outgoing or supported by template '${fromNode.template}' (edge ${edge.id})`,
116
+ });
117
+ }
118
+ }
119
+ }
120
+ const toNode = graph.nodesById.get(edge.to);
121
+ if (toNode) {
122
+ const constraints = getEdgeTypeConstraints(graph.templates, toNode.template);
123
+ if (constraints) {
124
+ const allowed = new Set([...(constraints.incoming ?? []), ...(constraints.supports ?? [])]);
125
+ if (!allowed.has(edge.type)) {
126
+ diagnostics.push({
127
+ severity: 'warning',
128
+ file: approxFilePath(graph, toNode),
129
+ nodeId: toNode.id,
130
+ message: `edge type '${edge.type}' is not declared as incoming or supported by template '${toNode.template}' (edge ${edge.id})`,
131
+ });
132
+ }
133
+ }
134
+ }
135
+ }
136
+ }
137
+ }
138
+ function lintEdgeProperties(graph, diagnostics) {
139
+ if (!graph.edgeTypes)
140
+ return;
141
+ for (const edges of graph.edgesByFrom.values()) {
142
+ for (const edge of edges) {
143
+ const def = graph.edgeTypes.get(edge.type);
144
+ if (!def?.properties)
145
+ continue;
146
+ const schema = getTemplateSchema(def.properties);
147
+ const props = edge.properties ?? {};
148
+ const file = edgePropertyFile(graph, edge);
149
+ if (!schema.additionalProperties) {
150
+ for (const key of Object.keys(props)) {
151
+ if (!(key in schema.properties)) {
152
+ diagnostics.push({
153
+ severity: 'warning',
154
+ file,
155
+ message: `edge '${edge.id}' has unknown property '${key}' not declared by edge type '${edge.type}'`,
156
+ });
157
+ }
158
+ }
159
+ }
160
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
161
+ const value = props[key];
162
+ if (value === undefined)
163
+ continue;
164
+ const type = propSchema.type;
165
+ if (typeof type === 'string' && !valueMatchesType(value, type)) {
166
+ diagnostics.push({
167
+ severity: 'warning',
168
+ file,
169
+ message: `edge '${edge.id}' property '${key}' expected type '${type}' but got '${describeType(value)}'`,
170
+ });
171
+ }
172
+ }
173
+ for (const key of schema.required) {
174
+ if (props[key] === undefined) {
175
+ diagnostics.push({
176
+ severity: 'warning',
177
+ file,
178
+ message: `edge '${edge.id}' missing required property '${key}' declared by edge type '${edge.type}'`,
179
+ });
180
+ }
181
+ }
182
+ }
183
+ }
184
+ }
185
+ function edgePropertyFile(graph, edge) {
186
+ const fromNode = graph.nodesById.get(edge.from);
187
+ return fromNode ? approxFilePath(graph, fromNode) : edge.id;
188
+ }
189
+ /** Best-effort node-id-to-cluster-file mapping (mirrors writer/graph-writer.ts clusterPath), for diagnostic messages only. */
190
+ function approxFilePath(graph, node) {
191
+ let current = node;
192
+ while (current.parentId) {
193
+ const parent = graph.nodesById.get(current.parentId);
194
+ if (!parent)
195
+ break;
196
+ current = parent;
197
+ }
198
+ const parts = current.id.split('.');
199
+ if (parts.length < 2)
200
+ return current.id;
201
+ const [component, template, ...rest] = parts;
202
+ return `components/${component}/${template}s/${rest.join('/') || template}.yaml`;
203
+ }
204
+ function valueMatchesType(value, type) {
205
+ switch (type) {
206
+ case 'string': return typeof value === 'string';
207
+ case 'boolean': return typeof value === 'boolean';
208
+ case 'number': return typeof value === 'number';
209
+ case 'integer': return typeof value === 'number' && Number.isInteger(value);
210
+ case 'array': return Array.isArray(value);
211
+ case 'object': return typeof value === 'object' && value !== null && !Array.isArray(value);
212
+ default: return true;
213
+ }
214
+ }
215
+ function describeType(value) {
216
+ if (Array.isArray(value))
217
+ return 'array';
218
+ if (value === null)
219
+ return 'null';
220
+ return typeof value;
221
+ }
@@ -1,7 +1,15 @@
1
1
  import { parse as parseYaml } from 'yaml';
2
2
  import { getOwnedSections } from './pack-loader.js';
3
3
  import { listYamlKeys, readYaml } from '../source/content-utils.js';
4
- import { STRUCTURAL_EDGE_BY_ITEM_TEMPLATE, VALID_STABILITY_SET, VALID_STATE_SET } from './constants.js';
4
+ import { VALID_STABILITY_SET, VALID_STATE_SET } from './constants.js';
5
+ import { validateRootId, validateSegment } from './id-grammar.js';
6
+ import { getTemplateRole } from '../graph/roles.js';
7
+ import { getPropertySchemasFromTemplate } from './template-props.js';
8
+ /** Containment edge generated for owned children, keyed by the child template's declared role. */
9
+ const STRUCTURAL_EDGE_BY_ROLE = {
10
+ field: 'has-field',
11
+ value: 'has-value',
12
+ };
5
13
  export function loadClusters(content, templates, diagnostics) {
6
14
  const result = { nodes: new Map(), edgesByFrom: new Map(), edgesByTo: new Map() };
7
15
  for (const key of listYamlKeys(content, 'components')) {
@@ -24,12 +32,17 @@ export function loadClusters(content, templates, diagnostics) {
24
32
  diagnostics.push({ severity: 'error', file: key, message: 'cluster missing required root fields' });
25
33
  continue;
26
34
  }
35
+ const idError = validateRootId(record.id);
36
+ if (idError) {
37
+ diagnostics.push({ severity: 'error', file: key, message: idError });
38
+ continue;
39
+ }
27
40
  const root = {
28
41
  id: record.id,
29
42
  template: record.template,
30
43
  component: meta.component,
31
- state: asState(meta.state, 'proposed'),
32
- stability: asStability(meta.stability, 'unstable'),
44
+ state: asState(meta.state, 'proposed', diagnostics, key, record.id),
45
+ stability: asStability(meta.stability, 'unstable', diagnostics, key, record.id),
33
46
  schemaVersion: record.schemaVersion,
34
47
  lastModifiedAt: meta.lastModifiedAt,
35
48
  ...(typeof meta.extractedFrom === 'string' && { extractedFrom: meta.extractedFrom }),
@@ -41,11 +54,11 @@ export function loadClusters(content, templates, diagnostics) {
41
54
  const rootTemplate = templates.get(root.template);
42
55
  if (rootTemplate) {
43
56
  for (const target of getNodeRefTargets(root, rootTemplate)) {
44
- const readsId = `${root.id}__reads__${target}`;
57
+ const usesTypeId = `${root.id}__uses-type__${target}`;
45
58
  const existingFrom = result.edgesByFrom.get(root.id) ?? [];
46
- if (!existingFrom.some(e => e.id === readsId)) {
59
+ if (!existingFrom.some(e => e.id === usesTypeId)) {
47
60
  addEdge(result, {
48
- id: readsId, from: root.id, to: target, type: 'reads',
61
+ id: usesTypeId, from: root.id, to: target, type: 'uses-type',
49
62
  state: root.state, stability: root.stability, generated: true,
50
63
  });
51
64
  }
@@ -55,19 +68,6 @@ export function loadClusters(content, templates, diagnostics) {
55
68
  }
56
69
  return result;
57
70
  }
58
- function getPropertySchemasFromTemplate(props) {
59
- if (Array.isArray(props.allOf)) {
60
- const merged = {};
61
- for (const schema of props.allOf) {
62
- Object.assign(merged, getPropertySchemasFromTemplate(schema));
63
- }
64
- return merged;
65
- }
66
- if (typeof props.properties === 'object' && props.properties !== null) {
67
- return props.properties;
68
- }
69
- return {};
70
- }
71
71
  function getNodeRefTargets(node, template) {
72
72
  if (!template.properties)
73
73
  return [];
@@ -106,6 +106,16 @@ function materialiseChildren(result, parent, clusterRoot, source, templates, fil
106
106
  if (!isRecord(section))
107
107
  continue;
108
108
  for (const [localName, value] of Object.entries(section)) {
109
+ const segmentError = validateSegment(localName);
110
+ if (segmentError) {
111
+ diagnostics.push({
112
+ severity: 'error',
113
+ file: filePath,
114
+ nodeId: parent.id,
115
+ message: `owned item name '${localName}' in ${sectionName}: ${segmentError}`,
116
+ });
117
+ continue;
118
+ }
109
119
  if (!isRecord(value)) {
110
120
  diagnostics.push({
111
121
  severity: 'error',
@@ -118,16 +128,18 @@ function materialiseChildren(result, parent, clusterRoot, source, templates, fil
118
128
  const childId = `${parent.id}.${sectionName}.${localName}`;
119
129
  const child = {
120
130
  id: childId,
131
+ parentId: parent.id,
121
132
  template: childTemplateName,
122
133
  component: parent.component,
123
- state: asState(value.state, parent.state),
124
- stability: asStability(value.stability, parent.stability),
134
+ state: asState(value.state, parent.state, diagnostics, filePath, childId),
135
+ stability: asStability(value.stability, parent.stability, diagnostics, filePath, childId),
125
136
  schemaVersion: parent.schemaVersion,
126
137
  lastModifiedAt: parent.lastModifiedAt,
127
138
  properties: stripOwnedSections(value, childTemplateName, templates),
128
139
  };
129
140
  addNode(result, child, filePath, diagnostics);
130
- const edgeType = STRUCTURAL_EDGE_BY_ITEM_TEMPLATE[childTemplateName];
141
+ const childRole = getTemplateRole(templates, childTemplateName);
142
+ const edgeType = childRole !== undefined ? STRUCTURAL_EDGE_BY_ROLE[childRole] : undefined;
131
143
  if (edgeType) {
132
144
  addEdge(result, {
133
145
  id: `${parent.id}__${edgeType}__${child.id}`,
@@ -141,14 +153,14 @@ function materialiseChildren(result, parent, clusterRoot, source, templates, fil
141
153
  const childTemplate = templates.get(child.template);
142
154
  if (childTemplate) {
143
155
  for (const target of getNodeRefTargets(child, childTemplate)) {
144
- const readsId = `${clusterRoot.id}__reads__${target}`;
156
+ const usesTypeId = `${clusterRoot.id}__uses-type__${target}`;
145
157
  const existingFrom = result.edgesByFrom.get(clusterRoot.id) ?? [];
146
- if (!existingFrom.some(e => e.id === readsId)) {
158
+ if (!existingFrom.some(e => e.id === usesTypeId)) {
147
159
  addEdge(result, {
148
- id: readsId,
160
+ id: usesTypeId,
149
161
  from: clusterRoot.id,
150
162
  to: target,
151
- type: 'reads',
163
+ type: 'uses-type',
152
164
  state: clusterRoot.state,
153
165
  stability: clusterRoot.stability,
154
166
  generated: true,
@@ -183,9 +195,19 @@ function addEdge(result, edge) {
183
195
  function isRecord(value) {
184
196
  return typeof value === 'object' && value !== null && !Array.isArray(value);
185
197
  }
186
- function asState(value, fallback) {
187
- return typeof value === 'string' && VALID_STATE_SET.has(value) ? value : fallback;
198
+ function asState(value, fallback, diagnostics, file, nodeId) {
199
+ if (value === undefined)
200
+ return fallback;
201
+ if (typeof value === 'string' && VALID_STATE_SET.has(value))
202
+ return value;
203
+ diagnostics.push({ severity: 'warning', file, nodeId, message: `invalid state '${String(value)}', defaulting to '${fallback}'` });
204
+ return fallback;
188
205
  }
189
- function asStability(value, fallback) {
190
- return typeof value === 'string' && VALID_STABILITY_SET.has(value) ? value : fallback;
206
+ function asStability(value, fallback, diagnostics, file, nodeId) {
207
+ if (value === undefined)
208
+ return fallback;
209
+ if (typeof value === 'string' && VALID_STABILITY_SET.has(value))
210
+ return value;
211
+ diagnostics.push({ severity: 'warning', file, nodeId, message: `invalid stability '${String(value)}', defaulting to '${fallback}'` });
212
+ return fallback;
191
213
  }
@@ -11,22 +11,26 @@ export const VALID_STABILITIES = [
11
11
  'stable',
12
12
  'deprecated',
13
13
  ];
14
- export const VALID_EDGE_TYPES = [
15
- 'triggers',
16
- 'produces',
17
- 'reads',
18
- 'calls',
19
- 'implements',
20
- 'maps-to',
21
- 'derived-from',
22
- 'renamed-from',
23
- 'has-field',
24
- 'has-value',
25
- ];
14
+ /**
15
+ * Core edge type definitions — the single declaration of the built-in
16
+ * vocabulary and its semantic categories. Packs extend this set via
17
+ * `edge-types.yaml` (see loader/edge-type-loader.ts).
18
+ */
19
+ export const CORE_EDGE_TYPES = {
20
+ 'triggers': { name: 'triggers', category: 'semantic' },
21
+ 'produces': { name: 'produces', category: 'semantic' },
22
+ 'reads': { name: 'reads', category: 'semantic' },
23
+ 'uses-type': { name: 'uses-type', category: 'semantic' },
24
+ 'calls': { name: 'calls', category: 'semantic' },
25
+ 'implements': { name: 'implements', category: 'semantic' },
26
+ 'maps-to': { name: 'maps-to', category: 'lineage' },
27
+ 'derived-from': { name: 'derived-from', category: 'lineage' },
28
+ 'renamed-from': { name: 'renamed-from', category: 'lineage', hidden: true },
29
+ 'has-field': { name: 'has-field', category: 'structural' },
30
+ 'has-value': { name: 'has-value', category: 'structural' },
31
+ };
32
+ export const CORE_EDGE_TYPE_MAP = new Map(Object.entries(CORE_EDGE_TYPES));
33
+ export const VALID_EDGE_TYPES = Object.keys(CORE_EDGE_TYPES);
26
34
  export const VALID_STATE_SET = new Set(VALID_STATES);
27
35
  export const VALID_STABILITY_SET = new Set(VALID_STABILITIES);
28
36
  export const VALID_EDGE_TYPE_SET = new Set(VALID_EDGE_TYPES);
29
- export const STRUCTURAL_EDGE_BY_ITEM_TEMPLATE = {
30
- Field: 'has-field',
31
- EnumValue: 'has-value',
32
- };
@@ -1,7 +1,7 @@
1
1
  import { parse as parseYaml } from 'yaml';
2
- import { VALID_EDGE_TYPE_SET } from './constants.js';
2
+ import { CORE_EDGE_TYPE_MAP, VALID_STABILITY_SET, VALID_STATE_SET } from './constants.js';
3
3
  import { listYamlKeys, readYaml } from '../source/content-utils.js';
4
- export function loadEdges(content, nodes, diagnostics) {
4
+ export function loadEdges(content, nodes, diagnostics, edgeTypes = CORE_EDGE_TYPE_MAP) {
5
5
  const result = { edgesByFrom: new Map(), edgesByTo: new Map() };
6
6
  for (const key of listYamlKeys(content, 'edges')) {
7
7
  let raw;
@@ -21,7 +21,7 @@ export function loadEdges(content, nodes, diagnostics) {
21
21
  diagnostics.push({ severity: 'error', file: key, message: 'edge missing required from, to, or type' });
22
22
  continue;
23
23
  }
24
- if (!VALID_EDGE_TYPE_SET.has(edgeRecord.type)) {
24
+ if (!edgeTypes.has(edgeRecord.type)) {
25
25
  diagnostics.push({ severity: 'error', file: key, message: `invalid edge type: ${edgeRecord.type}` });
26
26
  continue;
27
27
  }
@@ -36,19 +36,39 @@ export function loadEdges(content, nodes, diagnostics) {
36
36
  }
37
37
  if (unresolvedEndpoint)
38
38
  continue;
39
+ const properties = edgeRecord.properties;
39
40
  addEdge(result, {
40
41
  id: `${edgeRecord.from}__${edgeRecord.type}__${edgeRecord.to}`,
41
42
  from: edgeRecord.from,
42
43
  to: edgeRecord.to,
43
44
  type: edgeRecord.type,
44
- state: typeof edgeRecord.state === 'string' ? edgeRecord.state : 'proposed',
45
- stability: typeof edgeRecord.stability === 'string' ? edgeRecord.stability : 'unstable',
45
+ state: resolveState(edgeRecord.state, diagnostics, key),
46
+ stability: resolveStability(edgeRecord.stability, diagnostics, key),
46
47
  notes: typeof edgeRecord.notes === 'string' ? edgeRecord.notes : undefined,
48
+ ...(typeof properties === 'object' && properties !== null && !Array.isArray(properties) && {
49
+ properties: properties,
50
+ }),
47
51
  });
48
52
  }
49
53
  }
50
54
  return result;
51
55
  }
56
+ function resolveState(value, diagnostics, file) {
57
+ if (value === undefined)
58
+ return 'proposed';
59
+ if (typeof value === 'string' && VALID_STATE_SET.has(value))
60
+ return value;
61
+ diagnostics.push({ severity: 'warning', file, message: `invalid edge state '${String(value)}', defaulting to 'proposed'` });
62
+ return 'proposed';
63
+ }
64
+ function resolveStability(value, diagnostics, file) {
65
+ if (value === undefined)
66
+ return 'unstable';
67
+ if (typeof value === 'string' && VALID_STABILITY_SET.has(value))
68
+ return value;
69
+ diagnostics.push({ severity: 'warning', file, message: `invalid edge stability '${String(value)}', defaulting to 'unstable'` });
70
+ return 'unstable';
71
+ }
52
72
  function addEdge(result, edge) {
53
73
  const from = result.edgesByFrom.get(edge.from) ?? [];
54
74
  from.push(edge);
@@ -0,0 +1,72 @@
1
+ import { parse as parseYaml } from 'yaml';
2
+ import { listYamlKeys, readYaml } from '../source/content-utils.js';
3
+ import { CORE_EDGE_TYPES } from './constants.js';
4
+ const VALID_CATEGORIES = new Set(['structural', 'semantic', 'lineage']);
5
+ /** Edge type names appear inside edge ids ({from}__{type}__{to}). */
6
+ const EDGE_TYPE_NAME_RE = /^[a-z][a-z0-9-]*$/;
7
+ /**
8
+ * Build the edge type vocabulary: core definitions plus any `edge-types.yaml`
9
+ * declared by loaded packs. Core definitions cannot be overridden; collisions
10
+ * between packs keep the first definition with a warning.
11
+ */
12
+ export function loadEdgeTypes(packContent, diagnostics) {
13
+ const edgeTypes = new Map(Object.entries(CORE_EDGE_TYPES));
14
+ const keys = listYamlKeys(packContent, '').filter(key => key.endsWith('/edge-types.yaml'));
15
+ for (const key of keys) {
16
+ let raw;
17
+ try {
18
+ raw = parseYaml(readYaml(packContent, key));
19
+ }
20
+ catch (err) {
21
+ diagnostics.push({ severity: 'error', file: key, message: `failed to parse YAML: ${err}` });
22
+ continue;
23
+ }
24
+ const declared = raw?.['edge-types'];
25
+ if (typeof declared !== 'object' || declared === null || Array.isArray(declared)) {
26
+ diagnostics.push({ severity: 'error', file: key, message: `edge-types.yaml must declare an 'edge-types' map` });
27
+ continue;
28
+ }
29
+ for (const [name, defRaw] of Object.entries(declared)) {
30
+ if (!EDGE_TYPE_NAME_RE.test(name)) {
31
+ diagnostics.push({
32
+ severity: 'error',
33
+ file: key,
34
+ message: `invalid edge type name '${name}': must match ${EDGE_TYPE_NAME_RE}`,
35
+ });
36
+ continue;
37
+ }
38
+ if (typeof defRaw !== 'object' || defRaw === null) {
39
+ diagnostics.push({ severity: 'error', file: key, message: `edge type '${name}' must be an object` });
40
+ continue;
41
+ }
42
+ const def = defRaw;
43
+ if (typeof def.category !== 'string' || !VALID_CATEGORIES.has(def.category)) {
44
+ diagnostics.push({
45
+ severity: 'error',
46
+ file: key,
47
+ message: `edge type '${name}' has invalid category '${String(def.category)}': expected structural, semantic, or lineage`,
48
+ });
49
+ continue;
50
+ }
51
+ const existing = edgeTypes.get(name);
52
+ if (existing) {
53
+ diagnostics.push({
54
+ severity: 'warning',
55
+ file: key,
56
+ message: `edge type '${name}' is already declared${name in CORE_EDGE_TYPES ? ' by core' : ''} — keeping the existing definition`,
57
+ });
58
+ continue;
59
+ }
60
+ edgeTypes.set(name, {
61
+ name,
62
+ category: def.category,
63
+ ...(typeof def.description === 'string' && { description: def.description }),
64
+ ...(typeof def.properties === 'object' && def.properties !== null && {
65
+ properties: def.properties,
66
+ }),
67
+ ...(def.hidden === true && { hidden: true }),
68
+ });
69
+ }
70
+ }
71
+ return edgeTypes;
72
+ }