@atolis-hq/corum 0.1.44 → 0.1.45

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.
@@ -31,6 +31,17 @@ The graph reflects modeled relationships, not guaranteed complete truth. Missing
31
31
 
32
32
  When likely relationships are absent, treat naming, shared component context, schema similarity, and lineage adjacency as hypotheses. Then verify by inspecting the relevant nodes, clusters, and source material.
33
33
 
34
+ ## Minimal-output defaults
35
+
36
+ Prefer the smallest response that answers the question.
37
+
38
+ - Keep include_provenance off unless you need source traceability.
39
+ - For get_lineage, keep lean: true, include_edges: false, and use the smallest depth possible.
40
+ - Add edge_types, node_types, or exclude_node_types to narrow lineage before increasing depth.
41
+ - For search_nodes, avoid full_nodes: true unless summaries are insufficient.
42
+ - For get_cluster, start with collapse_schemas: true and leave include_edges and full structural expansion off unless needed.
43
+ - Avoid branch, overlay_refs, and include_static_enums unless the task explicitly requires them.
44
+
34
45
  ## Recommended workflow
35
46
 
36
47
  1. Call get_graph_metadata first to discover which edge types are in use and what node templates exist.
@@ -39,49 +50,74 @@ When likely relationships are absent, treat naming, shared component context, sc
39
50
 
40
51
  3. Call get_lineage with multiple node_ids batched together rather than separate calls per node.
41
52
 
42
- 4. Use direction "downstream" with depth 2 from events to trace event -> command -> operation chains.
53
+ 4. Use direction "downstream" with a bounded depth when you need to see what a node leads to next.
43
54
 
44
- 5. Use direction "upstream" from a DomainModel node to find all writers to that aggregate.
55
+ 5. Use direction "upstream" when you need to find what leads into or influences a node.
45
56
 
46
57
  6. Avoid get_cluster for traversal questions - use it only when you need a node's full structural detail. Prefer get_lineage for following relationships.
47
58
 
48
59
  7. Add include_provenance: true only when you need to bridge a finding to the source codebase.
49
60
 
61
+ ## Write workflow
62
+
63
+ When the task is to change the graph rather than inspect it:
64
+
65
+ 1. Call start_changes first. No write tool works without an open session.
66
+ - Prefer autosave: false unless you explicitly want per-mutation checkpoints.
67
+ - With autosave: true on file sources, every mutation writes through immediately and may create granular history/noisy diffs.
68
+
69
+ 2. Use the write tools deliberately:
70
+ - apply_cluster for cluster-style upserts
71
+ - create_node / update_node / rename_node / delete_node for explicit node edits
72
+ - create_edge / update_edge / delete_edge for explicit edge edits
73
+
74
+ 3. Use pending_changes before commit_changes to inspect the journal and summary diff.
75
+
76
+ 4. Finish with commit_changes or discard_changes.
77
+ - discard_changes only rolls back in-memory session state; it does not undo file-source mutations that were autosaved write-through.
78
+
79
+ Important mutation rules:
80
+ - rename_node is the only rename path. apply_cluster and imports never infer renames.
81
+ - apply_cluster mode "replace" is authoritative for owned sections: absent children are deleted, and an absent owned section means an empty section.
82
+ - delete_node may soft-delete or hard-delete depending on whether the node is already shared history on the default branch.
83
+ - While a session is open, normal read tools reflect the working graph for that session branch.
84
+
85
+
50
86
  ## Output format and token efficiency
51
87
 
52
88
  Start with format "toon" and compact_keys true. TOON is the most token-efficient machine-readable format and compact_keys shortens common field names. Fall back to format "yaml" if a downstream consumer needs human-readable output, or format "json" if it needs conventional structured parsing.
53
89
 
54
90
  When compact_keys is true the following field names are shortened in the response:
55
91
 
56
- id → i template → t component → cp
57
- state → s stability → st properties → p
58
- nodes → n edges → e root → r
59
- children → ch from → fr to → to
60
- type → ty notes → nt version → v
61
- core → c abstract → a extends → ex
62
- origin_id → oi depth → d via_edge_type → vet
63
- via_node_id → vni lastModifiedAt → lm extractedFrom → xf
64
- derivation → dv derivedBy → db
92
+ id -> i template -> t component -> cp
93
+ state -> s stability -> st properties -> p
94
+ nodes -> n edges -> e root -> r
95
+ children -> ch from -> fr to -> to
96
+ type -> ty notes -> nt version -> v
97
+ core -> c abstract -> a extends -> ex
98
+ origin_id -> oi depth -> d via_edge_type -> vet
99
+ via_node_id -> vni lastModifiedAt -> lm extractedFrom -> xf
100
+ derivation -> dv derivedBy -> db
65
101
 
66
102
  - get_lineage is lean by default: it returns only id (i), origin_id (oi), depth (d), via_edge_type (vet), and via_node_id (vni) unless lean is set to false.
67
103
  - get_lineage omits edges by default; add include_edges true when you need graph reconstruction or edge-level auditing.
68
104
 
69
105
  ## Common patterns
70
106
 
71
- All events in a component:
72
- list_nodes - filter { templates: ["DomainEvent", "IntegrationEvent"], component: "orders" }
107
+ All nodes of selected templates in a component:
108
+ list_nodes - filter { templates: ["TemplateA", "TemplateB"], component: "component-name" }, format: "toon", compact_keys: true
73
109
 
74
- What does an operation produce?
75
- get_lineage - node_ids: ["orders.DomainModel.order.operations.place"], direction: "downstream"
110
+ What does this node produce?
111
+ get_lineage - node_ids: ["component.Template.node"], direction: "downstream", edge_types: ["produces"], depth: 1, lean: true, include_edges: false, format: "toon", compact_keys: true
76
112
 
77
- What triggers an operation?
78
- get_lineage - node_ids: ["orders.DomainModel.order.operations.complete"], direction: "upstream"
113
+ What triggers this node?
114
+ get_lineage - node_ids: ["component.Template.node"], direction: "upstream", edge_types: ["triggers"], depth: 1, lean: true, include_edges: false, format: "toon", compact_keys: true
79
115
 
80
- Full event flow around a node:
81
- get_lineage - node_ids: ["orders.DomainEvent.order-placed"], direction: "both", depth: 3
116
+ Full relationship flow around a node:
117
+ get_lineage - node_ids: ["component.Template.node"], direction: "both", depth: 3, lean: true, include_edges: false, format: "toon", compact_keys: true
82
118
 
83
119
  Field-level mappings between nodes:
84
- get_linked_fields - returns all maps-to edges touching fields owned by a root node
120
+ get_linked_fields - id plus connected maps-to edges for fields owned by a root node; keep format: "toon", compact_keys: true
85
121
 
86
122
  Schema / field details:
87
123
  get_cluster - root includes compact schemas and enums blocks by default. Each schema entry
@@ -89,5 +125,9 @@ Schema / field details:
89
125
  use $ref: '#/schemas/name' or $ref: '#/enums/name' pointing into the same blocks. Mapping
90
126
  fields appear as { type: map, key: string, value: { ... } } inline on the field. Field-level
91
127
  cross-cluster edges (maps-to, derived-from) appear as an edges block on the field. Pass
92
- collapse_schemas: false to get the full structural node-per-field representation instead.
128
+ collapse_schemas: false only when the compact root.schemas / root.enums view is insufficient. Start with
129
+ format: "toon", compact_keys: true, collapse_schemas: true.
130
+
131
+ Mutation session:
132
+ start_changes -> one or more write calls -> pending_changes -> commit_changes
93
133
  `.trim();
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Alias map built from `renamed-from` trail edges: retired ID → live ID.
3
+ * `edge.from` is the live end; `edge.to` is the retired ID (intentionally
4
+ * dangling — see design §3/§5).
5
+ */
6
+ export function buildAliasMap(graph) {
7
+ const aliasMap = new Map();
8
+ for (const edges of graph.edgesByFrom.values()) {
9
+ for (const edge of edges) {
10
+ if (edge.type === 'renamed-from')
11
+ aliasMap.set(edge.to, edge.from);
12
+ }
13
+ }
14
+ return aliasMap;
15
+ }
16
+ /**
17
+ * Rewrite `id` when it equals `oldPrefix` or starts with `oldPrefix.` —
18
+ * exact-segment boundary, never plain string prefix (`orders.x` must not
19
+ * match `orders.xy`). Returns null when the prefix does not apply.
20
+ */
21
+ export function rewriteIdPrefix(id, oldPrefix, newPrefix) {
22
+ if (id === oldPrefix)
23
+ return newPrefix;
24
+ if (id.startsWith(`${oldPrefix}.`))
25
+ return newPrefix + id.slice(oldPrefix.length);
26
+ return null;
27
+ }
28
+ /**
29
+ * Resolve a (possibly retired) ID to a live ID through the alias map.
30
+ * Live node wins outright; exact hits and longest dot-boundary prefix
31
+ * rewrites are applied to fixpoint with a cycle guard. An unresolved ID is
32
+ * returned unchanged — the caller decides what that means (genuinely new
33
+ * node, unknown node, …).
34
+ */
35
+ export function resolveAlias(graph, aliasMap, id) {
36
+ const seen = new Set();
37
+ for (;;) {
38
+ if (graph.nodesById.has(id))
39
+ return id; // live node wins outright
40
+ if (seen.has(id))
41
+ return id; // cycle guard — give up
42
+ seen.add(id);
43
+ const exact = aliasMap.get(id);
44
+ if (exact !== undefined) {
45
+ id = exact;
46
+ continue;
47
+ }
48
+ // Longest dot-boundary prefix with a mapping.
49
+ let prefix = id;
50
+ let rewritten;
51
+ for (;;) {
52
+ const dot = prefix.lastIndexOf('.');
53
+ if (dot === -1)
54
+ break;
55
+ prefix = prefix.slice(0, dot);
56
+ const mapped = aliasMap.get(prefix);
57
+ if (mapped !== undefined) {
58
+ rewritten = mapped + id.slice(prefix.length);
59
+ break;
60
+ }
61
+ }
62
+ if (rewritten !== undefined) {
63
+ id = rewritten;
64
+ continue;
65
+ }
66
+ return id; // unresolved — caller decides
67
+ }
68
+ }
@@ -0,0 +1,255 @@
1
+ import { stringify as stringifyYaml } from 'yaml';
2
+ import { loadClusters, materialiseChildren } from '../loader/cluster-loader.js';
3
+ import { getOwnedSections } from '../loader/pack-loader.js';
4
+ import { VALID_STABILITY_SET, VALID_STATE_SET } from '../loader/constants.js';
5
+ import { lintNode } from '../linter/index.js';
6
+ import { detectPossibleRenames } from '../reconcile/index.js';
7
+ import { MutationError } from './errors.js';
8
+ import { deleteNode } from './delete.js';
9
+ import { findEdgeById, insertEdgeIntoIndexes, mutationDiagnostic, mutationTimestamp } from './util.js';
10
+ export function applyClusterToGraph(graph, document, mode, defaultBranchIds) {
11
+ if (mode !== 'merge' && mode !== 'replace') {
12
+ throw new MutationError([mutationDiagnostic('error', `apply_cluster: mode must be 'merge' or 'replace', got '${String(mode)}'`)]);
13
+ }
14
+ const rootId = document.id;
15
+ if (typeof rootId !== 'string') {
16
+ throw new MutationError([mutationDiagnostic('error', 'apply_cluster: document requires a string id')]);
17
+ }
18
+ const plan = { errors: [], creates: [], updates: [], deletes: [] };
19
+ const root = graph.nodesById.get(rootId);
20
+ if (!root) {
21
+ // New root: the whole document is a create (same path as create_node roots).
22
+ const result = materialiseRootDocument(document, graph.templates);
23
+ const topNode = result.nodes.get(rootId);
24
+ if (!topNode) {
25
+ throw new MutationError([mutationDiagnostic('error', `apply_cluster: document did not materialise root '${rootId}'`, rootId)]);
26
+ }
27
+ for (const nodeId of result.nodes.keys()) {
28
+ if (graph.nodesById.has(nodeId)) {
29
+ plan.errors.push(mutationDiagnostic('error', `node already exists: ${nodeId}`, nodeId));
30
+ }
31
+ }
32
+ plan.creates.push({ result, topNode });
33
+ }
34
+ else {
35
+ if (typeof document.template === 'string' && document.template !== root.template) {
36
+ throw new MutationError([mutationDiagnostic('error', `apply_cluster: cannot change template of ${rootId} from '${root.template}' to '${document.template}' — delete and recreate instead`, rootId)]);
37
+ }
38
+ planNode(graph, plan, mode, root, document, true);
39
+ }
40
+ if (plan.errors.length > 0)
41
+ throw new MutationError(plan.errors);
42
+ // -- apply (deletes → creates → updates; the name sets are disjoint) --------
43
+ const deleted = [];
44
+ for (const node of plan.deletes) {
45
+ const result = deleteNode(graph, node.id, {}, defaultBranchIds);
46
+ deleted.push({ id: node.id, tier: result.tier });
47
+ }
48
+ const timestamp = mutationTimestamp();
49
+ const createdIds = [];
50
+ for (const { result } of plan.creates) {
51
+ for (const node of result.nodes.values()) {
52
+ node.lastModifiedAt = timestamp;
53
+ graph.nodesById.set(node.id, node);
54
+ createdIds.push(node.id);
55
+ }
56
+ for (const edges of result.edgesByFrom.values()) {
57
+ for (const edge of edges) {
58
+ if (!findEdgeById(graph, edge.id))
59
+ insertEdgeIntoIndexes(graph, edge);
60
+ }
61
+ }
62
+ }
63
+ const updatedIds = [];
64
+ for (const update of plan.updates) {
65
+ update.node.properties = update.properties;
66
+ update.node.corum = update.corum;
67
+ if (update.state !== undefined)
68
+ update.node.state = update.state;
69
+ if (update.stability !== undefined)
70
+ update.node.stability = update.stability;
71
+ update.node.lastModifiedAt = timestamp;
72
+ updatedIds.push(update.node.id);
73
+ }
74
+ // -- warnings ----------------------------------------------------------------
75
+ const warnings = [];
76
+ for (const { result } of plan.creates) {
77
+ for (const node of result.nodes.values()) {
78
+ warnings.push(...lintNode(graph, node).filter(d => d.severity === 'warning'));
79
+ }
80
+ }
81
+ for (const update of plan.updates) {
82
+ warnings.push(...lintNode(graph, update.node).filter(d => d.severity === 'warning'));
83
+ }
84
+ // §6a heuristic, mirrored from the import reconciler: a delete plus a create
85
+ // with the same template under the same parent suggests an unrecorded rename.
86
+ warnings.push(...detectPossibleRenames({ toAdd: plan.creates.map(c => c.topNode), toUpdate: [], toRemove: plan.deletes }, '<mutation>'));
87
+ return { rootId, createdIds, updatedIds, deleted, warnings };
88
+ }
89
+ /**
90
+ * Plan updates/creates/deletes for `node` against its cluster-style `doc`
91
+ * record, recursing into owned sections. Pure — collects into `plan` only.
92
+ */
93
+ function planNode(graph, plan, mode, node, doc, isRoot) {
94
+ const template = graph.templates.get(node.template);
95
+ const ownedSections = template ? getOwnedSections(template) : {};
96
+ const ownedSectionNames = new Set(Object.keys(ownedSections));
97
+ // state/stability: root documents carry them under metadata (cluster YAML)
98
+ // or at the top level; children carry them at the top level.
99
+ const meta = isRoot && isRecord(doc.metadata) ? doc.metadata : undefined;
100
+ const state = readEnum(doc.state ?? meta?.state, VALID_STATE_SET, 'state', node.id, plan.errors);
101
+ const stability = readEnum(doc.stability ?? meta?.stability, VALID_STABILITY_SET, 'stability', node.id, plan.errors);
102
+ // Properties: roots use the explicit `properties:` block; children flatten
103
+ // property keys at the top level (everything except state/stability and
104
+ // owned-section keys — loader semantics).
105
+ const docProps = isRoot
106
+ ? (isRecord(doc.properties) ? doc.properties : undefined)
107
+ : Object.fromEntries(Object.entries(doc).filter(([key]) => !ownedSectionNames.has(key) && key !== 'state' && key !== 'stability'));
108
+ let newProps;
109
+ let newCorum;
110
+ if (mode === 'merge') {
111
+ newProps = { ...node.properties };
112
+ if (docProps) {
113
+ for (const [key, value] of Object.entries(docProps)) {
114
+ if (value === null)
115
+ delete newProps[key];
116
+ else
117
+ newProps[key] = value;
118
+ }
119
+ }
120
+ newCorum = node.corum;
121
+ }
122
+ else {
123
+ newProps = { ...(docProps ?? {}) };
124
+ newCorum = node.corum;
125
+ }
126
+ const changed = JSON.stringify(newProps) !== JSON.stringify(node.properties) ||
127
+ JSON.stringify(newCorum) !== JSON.stringify(node.corum) ||
128
+ (state !== undefined && state !== node.state) ||
129
+ (stability !== undefined && stability !== node.stability);
130
+ if (changed) {
131
+ plan.updates.push({ node, properties: newProps, corum: newCorum, state, stability });
132
+ }
133
+ // -- owned sections ----------------------------------------------------------
134
+ for (const sectionName of ownedSectionNames) {
135
+ const docSection = doc[sectionName];
136
+ const sectionPrefix = `${node.id}.${sectionName}.`;
137
+ const graphChildren = sectionChildren(graph, node.id, sectionPrefix);
138
+ if (docSection === undefined) {
139
+ // merge: absent section untouched; replace: absent section = empty section.
140
+ if (mode === 'replace')
141
+ plan.deletes.push(...graphChildren);
142
+ continue;
143
+ }
144
+ if (!isRecord(docSection)) {
145
+ plan.errors.push(mutationDiagnostic('error', `apply_cluster: section '${sectionName}' of ${node.id} must be an object of named children`, node.id));
146
+ continue;
147
+ }
148
+ for (const [localName, value] of Object.entries(docSection)) {
149
+ if (!isRecord(value)) {
150
+ plan.errors.push(mutationDiagnostic('error', `apply_cluster: child '${localName}' in ${sectionName} of ${node.id} must be an object`, node.id));
151
+ continue;
152
+ }
153
+ const childId = `${sectionPrefix}${localName}`;
154
+ const existing = graph.nodesById.get(childId);
155
+ if (existing) {
156
+ planNode(graph, plan, mode, existing, value, false);
157
+ }
158
+ else {
159
+ planCreateChild(graph, plan, node, sectionName, localName, value);
160
+ }
161
+ }
162
+ if (mode === 'replace') {
163
+ for (const child of graphChildren) {
164
+ const localName = child.id.slice(sectionPrefix.length);
165
+ if (!(localName in docSection))
166
+ plan.deletes.push(child);
167
+ }
168
+ }
169
+ }
170
+ }
171
+ /** Materialise a new owned child (plus nested children) purely into the plan. */
172
+ function planCreateChild(graph, plan, parent, sectionName, localName, value) {
173
+ const result = { nodes: new Map(), edgesByFrom: new Map(), edgesByTo: new Map() };
174
+ const diagnostics = [];
175
+ materialiseChildren(result, parent, clusterRootOf(graph, parent), { [sectionName]: { [localName]: value } }, graph.templates, '<mutation>', diagnostics);
176
+ plan.errors.push(...diagnostics.filter(d => d.severity === 'error'));
177
+ const childId = `${parent.id}.${sectionName}.${localName}`;
178
+ const topNode = result.nodes.get(childId);
179
+ for (const nodeId of result.nodes.keys()) {
180
+ if (graph.nodesById.has(nodeId)) {
181
+ plan.errors.push(mutationDiagnostic('error', `node already exists: ${nodeId}`, nodeId));
182
+ }
183
+ }
184
+ if (topNode)
185
+ plan.creates.push({ result, topNode });
186
+ }
187
+ /**
188
+ * Parse a root cluster document through the loader — the exact semantics of
189
+ * loading the equivalent YAML file (structural edges, defaults, owned-child
190
+ * materialisation). Shared by `createNode` and `applyCluster`.
191
+ */
192
+ export function materialiseRootDocument(document, templates) {
193
+ const doc = { ...document };
194
+ const id = doc.id;
195
+ if (typeof id !== 'string') {
196
+ throw new MutationError([mutationDiagnostic('error', 'create node: root document requires a string id')]);
197
+ }
198
+ if (typeof doc.template !== 'string') {
199
+ throw new MutationError([mutationDiagnostic('error', `create node: document for ${id} requires a template`, id)]);
200
+ }
201
+ if (typeof doc.schemaVersion !== 'string')
202
+ doc.schemaVersion = '1.0';
203
+ const metadata = isRecord(doc.metadata) ? { ...doc.metadata } : {};
204
+ if (typeof metadata.component !== 'string')
205
+ metadata.component = id.split('.')[0];
206
+ if (typeof metadata.lastModifiedAt !== 'string')
207
+ metadata.lastModifiedAt = mutationTimestamp();
208
+ doc.metadata = metadata;
209
+ const parts = id.split('.');
210
+ if (parts.length < 3) {
211
+ throw new MutationError([mutationDiagnostic('error', `create node: '${id}' is not a valid cluster root id (component.Template.name)`, id)]);
212
+ }
213
+ const filePath = `components/${parts[0]}/${parts[1]}s/${parts.slice(2).join('/')}.yaml`;
214
+ const diagnostics = [];
215
+ const result = loadClusters(new Map([[filePath, stringifyYaml(doc)]]), templates, diagnostics);
216
+ if (diagnostics.some(d => d.severity === 'error'))
217
+ throw new MutationError(diagnostics);
218
+ return result;
219
+ }
220
+ // -- helpers ----------------------------------------------------------------
221
+ /** Direct children of `parentId` in one owned section (exactly one extra segment). */
222
+ function sectionChildren(graph, parentId, sectionPrefix) {
223
+ const children = [];
224
+ for (const node of graph.nodesById.values()) {
225
+ if (node.parentId !== parentId)
226
+ continue;
227
+ if (!node.id.startsWith(sectionPrefix))
228
+ continue;
229
+ if (node.id.slice(sectionPrefix.length).includes('.'))
230
+ continue;
231
+ children.push(node);
232
+ }
233
+ return children;
234
+ }
235
+ function clusterRootOf(graph, node) {
236
+ let current = node;
237
+ while (current.parentId !== undefined) {
238
+ const parent = graph.nodesById.get(current.parentId);
239
+ if (!parent)
240
+ break;
241
+ current = parent;
242
+ }
243
+ return current;
244
+ }
245
+ function readEnum(value, valid, label, nodeId, errors) {
246
+ if (value === undefined)
247
+ return undefined;
248
+ if (typeof value === 'string' && valid.has(value))
249
+ return value;
250
+ errors.push(mutationDiagnostic('error', `invalid ${label} '${String(value)}'`, nodeId));
251
+ return undefined;
252
+ }
253
+ function isRecord(value) {
254
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
255
+ }
@@ -0,0 +1,47 @@
1
+ import { MutationError } from './errors.js';
2
+ import { shouldRecordTrail } from './rename.js';
3
+ import { collectEdgesTouching, collectSubtreeIds, findEdgeById, mutationDiagnostic, mutationTimestamp, removeEdgeFromIndexes, } from './util.js';
4
+ /**
5
+ * Delete a node and its owned subtree (design §6).
6
+ *
7
+ * Tier resolution: `purge: true` → hard. Otherwise `recordTrail` override
8
+ * wins (true → soft, false → hard); with no override, soft iff the node's ID
9
+ * is in `defaultBranchIds` (the trail threshold, §4), else hard — pure design
10
+ * work leaves no tombstones.
11
+ */
12
+ export function deleteNode(graph, nodeId, opts = {}, defaultBranchIds) {
13
+ const node = graph.nodesById.get(nodeId);
14
+ if (!node) {
15
+ throw new MutationError([mutationDiagnostic('error', `cannot delete: node not found: ${nodeId}`, nodeId)]);
16
+ }
17
+ const soft = opts.purge === true
18
+ ? false
19
+ : shouldRecordTrail(defaultBranchIds ?? new Set(), nodeId, opts.recordTrail);
20
+ const subtreeIds = collectSubtreeIds(graph, nodeId);
21
+ const timestamp = mutationTimestamp();
22
+ if (soft) {
23
+ for (const id of subtreeIds) {
24
+ const subtreeNode = graph.nodesById.get(id);
25
+ subtreeNode.state = 'removed';
26
+ subtreeNode.lastModifiedAt = timestamp;
27
+ }
28
+ return { tier: 'soft', affectedIds: subtreeIds };
29
+ }
30
+ // Hard delete: remove subtree nodes and every edge touching any removed ID
31
+ // from both indexes — no orphan edges survive.
32
+ for (const edge of collectEdgesTouching(graph, subtreeIds)) {
33
+ removeEdgeFromIndexes(graph, edge);
34
+ }
35
+ for (const id of subtreeIds)
36
+ graph.nodesById.delete(id);
37
+ return { tier: 'hard', affectedIds: subtreeIds };
38
+ }
39
+ /** Delete an edge. Always hard — edges carry no subtree (design §6). */
40
+ export function deleteEdge(graph, edgeId) {
41
+ const edge = findEdgeById(graph, edgeId);
42
+ if (!edge) {
43
+ throw new MutationError([mutationDiagnostic('error', `cannot delete: edge not found: ${edgeId}`)]);
44
+ }
45
+ removeEdgeFromIndexes(graph, edge);
46
+ return edge;
47
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Thrown when a mutation fails validation. Mirrors QueryError but carries the
3
+ * linter-style diagnostics so agents can self-correct. A MutationError is
4
+ * always thrown *before* the first write — the graph is never half-mutated.
5
+ */
6
+ export class MutationError extends Error {
7
+ diagnostics;
8
+ constructor(diagnostics) {
9
+ const errorCount = diagnostics.filter(d => d.severity === 'error').length;
10
+ super(`Mutation failed with ${errorCount} error(s): ${diagnostics.filter(d => d.severity === 'error').map(d => d.message).join('; ')}`);
11
+ this.diagnostics = diagnostics;
12
+ this.name = 'MutationError';
13
+ }
14
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Graph mutation engine (design: node identity and MCP write tools, §7).
3
+ * All graph mutations live here; MCP write tools and the web edit mode are
4
+ * thin wrappers over this module.
5
+ */
6
+ export { MutationError } from './errors.js';
7
+ export { buildAliasMap, resolveAlias, rewriteIdPrefix } from './alias.js';
8
+ export { renameNode, replaceLastSegment, shouldRecordTrail } from './rename.js';
9
+ export { deleteEdge, deleteNode } from './delete.js';
10
+ export { applyClusterToGraph, materialiseRootDocument } from './apply-cluster.js';
11
+ export { WorkingSession, discardSession, getActiveSession, startSession } from './session.js';
@@ -0,0 +1,135 @@
1
+ import { validateSegment } from '../loader/id-grammar.js';
2
+ import { buildAliasMap } from './alias.js';
3
+ import { MutationError } from './errors.js';
4
+ import { collectEdgesTouching, insertEdgeIntoIndexes, mutationDiagnostic, mutationTimestamp, removeEdgeFromIndexes, } from './util.js';
5
+ /**
6
+ * Trail threshold (design §4/§14c): a rename or delete records a trail iff
7
+ * the node's ID exists in the default branch's committed graph. The explicit
8
+ * `record_trail` override always wins. `defaultBranchIds` is captured once at
9
+ * session start by the caller.
10
+ */
11
+ export function shouldRecordTrail(defaultBranchIds, nodeId, override) {
12
+ if (override !== undefined)
13
+ return override;
14
+ return defaultBranchIds.has(nodeId);
15
+ }
16
+ /** Replace the last dot-separated segment of an ID. */
17
+ export function replaceLastSegment(id, newName) {
18
+ const dot = id.lastIndexOf('.');
19
+ return dot === -1 ? newName : id.slice(0, dot + 1) + newName;
20
+ }
21
+ /**
22
+ * First-class rename (design §3, §14a). Rewrites the node ID, every
23
+ * descendant ID (exact-segment prefix), parentId fields, and every edge
24
+ * endpoint referencing an affected ID; optionally records the trail
25
+ * (`corum.identity.previousIds` + `renamed-from` edge). Validates everything before the
26
+ * first write — a thrown MutationError leaves the graph untouched.
27
+ */
28
+ export function renameNode(graph, oldId, newName, recordTrail) {
29
+ const warnings = [];
30
+ // -- Step 1: validate (pure reads only) ----------------------------------
31
+ const errors = [];
32
+ const node = graph.nodesById.get(oldId);
33
+ if (!node) {
34
+ throw new MutationError([mutationDiagnostic('error', `cannot rename: node not found: ${oldId}`, oldId)]);
35
+ }
36
+ const segmentError = validateSegment(newName);
37
+ if (segmentError) {
38
+ errors.push(mutationDiagnostic('error', `cannot rename ${oldId}: ${segmentError}`, oldId));
39
+ throw new MutationError(errors);
40
+ }
41
+ const newId = replaceLastSegment(oldId, newName);
42
+ if (newId === oldId) {
43
+ throw new MutationError([mutationDiagnostic('error', `cannot rename ${oldId}: new name equals current name`, oldId)]);
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));
49
+ }
50
+ }
51
+ if (errors.length > 0)
52
+ throw new MutationError(errors);
53
+ const aliasMap = buildAliasMap(graph);
54
+ if (aliasMap.has(newId)) {
55
+ 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
+ // -- 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
+ // -- Step 3: collect affected edges (exact endpoint match) ---------------
66
+ const affectedEdges = collectEdgesTouching(graph, idMap.keys());
67
+ // -- Step 4: apply --------------------------------------------------------
68
+ // 4a. Remove affected edges from BOTH indexes before any rewrite — an edge
69
+ // with only its `to` rewritten still moves bucket in edgesByTo.
70
+ for (const edge of affectedEdges)
71
+ removeEdgeFromIndexes(graph, edge);
72
+ // 4b. Rewrite node IDs and parentIds.
73
+ const timestamp = mutationTimestamp();
74
+ for (const [from, to] of idMap) {
75
+ const moved = graph.nodesById.get(from);
76
+ graph.nodesById.delete(from);
77
+ moved.id = to;
78
+ if (moved.parentId !== undefined) {
79
+ const rewrittenParent = idMap.get(moved.parentId);
80
+ if (rewrittenParent !== undefined)
81
+ moved.parentId = rewrittenParent;
82
+ }
83
+ moved.lastModifiedAt = timestamp;
84
+ graph.nodesById.set(to, moved);
85
+ }
86
+ // 4c. Rewrite edge endpoints, recompute IDs, reinsert. Explicit edges keep
87
+ // their properties, state, and stability; structural edges are
88
+ // endpoint-rewritten too (equivalent to regeneration from ownership).
89
+ for (const edge of affectedEdges) {
90
+ edge.from = idMap.get(edge.from) ?? edge.from;
91
+ edge.to = idMap.get(edge.to) ?? edge.to;
92
+ edge.id = `${edge.from}__${edge.type}__${edge.to}`;
93
+ insertEdgeIntoIndexes(graph, edge);
94
+ }
95
+ // -- Step 5: trail (after step 4 so the new edge is not itself rewritten) -
96
+ if (recordTrail) {
97
+ const previous = Array.isArray(node.corum?.identity?.previousIds)
98
+ ? [...node.corum.identity.previousIds]
99
+ : [];
100
+ previous.push(oldId);
101
+ node.corum = { ...(node.corum ?? {}), identity: { ...(node.corum?.identity ?? {}), previousIds: previous } };
102
+ const trailEdge = {
103
+ id: `${newId}__renamed-from__${oldId}`,
104
+ from: newId,
105
+ to: oldId,
106
+ type: 'renamed-from',
107
+ state: 'proposed',
108
+ stability: 'unstable',
109
+ };
110
+ insertEdgeIntoIndexes(graph, trailEdge);
111
+ }
112
+ // -- Step 6: rename-back pruning ------------------------------------------
113
+ // Invariants: previousIds never contains the current ID; no renamed-from
114
+ // edge is a self-loop (step 4c may have produced one by rewriting the old
115
+ // trail edge whose `from` was the restored identity).
116
+ if (Array.isArray(node.corum?.identity?.previousIds)) {
117
+ const pruned = node.corum.identity.previousIds.filter(name => name !== newId);
118
+ if (pruned.length === 0) {
119
+ if (node.corum?.identity)
120
+ delete node.corum.identity.previousIds;
121
+ if (node.corum?.identity && Object.keys(node.corum.identity).length === 0)
122
+ delete node.corum.identity;
123
+ if (node.corum && Object.keys(node.corum).length === 0)
124
+ delete node.corum;
125
+ }
126
+ else {
127
+ node.corum = { ...(node.corum ?? {}), identity: { ...(node.corum?.identity ?? {}), previousIds: pruned } };
128
+ }
129
+ }
130
+ for (const edge of [...(graph.edgesByFrom.get(newId) ?? [])]) {
131
+ if (edge.type === 'renamed-from' && edge.to === newId)
132
+ removeEdgeFromIndexes(graph, edge);
133
+ }
134
+ return { newId, warnings };
135
+ }