@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.
@@ -0,0 +1,513 @@
1
+ import { FileGraphSource } from '../source/file-source.js';
2
+ import { loadGraph } from '../loader/index.js';
3
+ import { serializeGraph } from '../writer/graph-writer.js';
4
+ import { lintEdge, lintGraph, lintNode } from '../linter/index.js';
5
+ import { CORE_EDGE_TYPE_MAP, VALID_STABILITY_SET, VALID_STATE_SET } from '../loader/constants.js';
6
+ import { validateSegment } from '../loader/id-grammar.js';
7
+ import { getOwnedSections } from '../loader/pack-loader.js';
8
+ import { materialiseChildren } from '../loader/cluster-loader.js';
9
+ import { MutationError } from './errors.js';
10
+ import { applyClusterToGraph, materialiseRootDocument } from './apply-cluster.js';
11
+ import { renameNode as renameNodePrimitive, shouldRecordTrail } from './rename.js';
12
+ import { deleteEdge as deleteEdgePrimitive, deleteNode as deleteNodePrimitive } from './delete.js';
13
+ import { findEdgeById, insertEdgeIntoIndexes, mutationDiagnostic, mutationTimestamp } from './util.js';
14
+ let currentSession = null;
15
+ /** The open working session, if any — MCP reads serve `session.graph` while one is open. */
16
+ export function getActiveSession() {
17
+ return currentSession;
18
+ }
19
+ /** Discard the active session, if any (design §7: abort, no writes). */
20
+ export function discardSession() {
21
+ currentSession?.discard();
22
+ }
23
+ /**
24
+ * Open a working session on `source` (design §7). Loads the working graph
25
+ * from the branch head, captures the trail-threshold ID set of the default
26
+ * branch and the base head marker once (design §14c), and registers the
27
+ * session as the process-wide active session.
28
+ */
29
+ export async function startSession(source, options = {}) {
30
+ if (currentSession) {
31
+ if (currentSession.hasPendingChanges()) {
32
+ throw new MutationError([mutationDiagnostic('error', 'a working session with pending changes is already open — commit or discard it first')]);
33
+ }
34
+ currentSession.discard(); // clean reset (design §7)
35
+ }
36
+ const isFileSource = source instanceof FileGraphSource;
37
+ const defaultBranch = await source.defaultBranch();
38
+ const branch = options.branch ?? defaultBranch;
39
+ if (options.create) {
40
+ if (isFileSource) {
41
+ throw new MutationError([mutationDiagnostic('error', `file sources have a single branch ('${defaultBranch}') and cannot create '${branch}' (design §9)`)]);
42
+ }
43
+ if (branch === defaultBranch) {
44
+ throw new MutationError([mutationDiagnostic('error', `create requires a branch name different from the default branch '${defaultBranch}'`)]);
45
+ }
46
+ if ((await source.listBranches()).includes(branch)) {
47
+ throw new MutationError([mutationDiagnostic('error', `cannot create branch '${branch}': it already exists`)]);
48
+ }
49
+ }
50
+ if (!isFileSource && branch === defaultBranch) {
51
+ throw new MutationError([mutationDiagnostic('error', `cannot start a write session on the default branch '${defaultBranch}' - it is read-only; specify a writable branch or use create: true`)]);
52
+ }
53
+ // In create mode the branch does not exist yet: the base is the default
54
+ // branch head; the branch itself is created on first commit.
55
+ const baseRef = options.create ? defaultBranch : branch;
56
+ const graph = await loadGraph({ source, ref: baseRef, strict: false });
57
+ // Trail threshold set (design §14c): captured once, from the DEFAULT branch
58
+ // head — even when the session works on another branch.
59
+ const defaultGraph = baseRef === defaultBranch
60
+ ? graph
61
+ : await loadGraph({ source, ref: defaultBranch, strict: false });
62
+ const defaultBranchIds = new Set(defaultGraph.nodesById.keys());
63
+ const baseSha = await source.head(baseRef);
64
+ const autosave = options.autosave ?? false;
65
+ const session = new WorkingSession(source, branch, defaultBranch, isFileSource, options.create === true, autosave, graph, baseSha, defaultBranchIds);
66
+ currentSession = session;
67
+ return session;
68
+ }
69
+ export class WorkingSession {
70
+ source;
71
+ branch;
72
+ defaultBranch;
73
+ isFileSource;
74
+ createBranch;
75
+ autosave;
76
+ graph;
77
+ baseSha;
78
+ defaultBranchIds;
79
+ journal = [];
80
+ wipShas = new Set();
81
+ baseNodes;
82
+ baseEdges;
83
+ closed = false;
84
+ constructor(source, branch, defaultBranch, isFileSource, createBranch, autosave, graph, baseSha, defaultBranchIds) {
85
+ this.source = source;
86
+ this.branch = branch;
87
+ this.defaultBranch = defaultBranch;
88
+ this.isFileSource = isFileSource;
89
+ this.createBranch = createBranch;
90
+ this.autosave = autosave;
91
+ this.graph = graph;
92
+ this.baseSha = baseSha;
93
+ this.defaultBranchIds = defaultBranchIds;
94
+ this.baseNodes = snapshotNodes(graph);
95
+ this.baseEdges = snapshotEdges(graph);
96
+ }
97
+ isClosed() {
98
+ return this.closed;
99
+ }
100
+ hasPendingChanges() {
101
+ return !this.closed && this.journal.length > 0;
102
+ }
103
+ /**
104
+ * Rename a node (design §3). Trail threshold (design §4): when
105
+ * `recordTrail` is not given, a trail is recorded iff the node's ID exists
106
+ * on the default branch head captured at session start.
107
+ */
108
+ async renameNode(id, newName, recordTrail) {
109
+ this.assertOpen();
110
+ const trail = shouldRecordTrail(this.defaultBranchIds, id, recordTrail);
111
+ const { newId, warnings } = renameNodePrimitive(this.graph, id, newName, trail);
112
+ const summary = `rename ${id} -> ${newId}${trail ? ' (trail recorded)' : ''}`;
113
+ await this.record('rename_node', { id, newName, recordTrail: trail }, summary);
114
+ return { newId, recordedTrail: trail, warnings, summary };
115
+ }
116
+ /** Delete a node and its owned subtree (design §6); tier per trail threshold unless overridden. */
117
+ async deleteNode(id, opts = {}) {
118
+ this.assertOpen();
119
+ const result = deleteNodePrimitive(this.graph, id, opts, this.defaultBranchIds);
120
+ const summary = `delete ${id} (${result.tier}, ${result.affectedIds.length} node${result.affectedIds.length === 1 ? '' : 's'})`;
121
+ await this.record('delete_node', { id, ...opts }, summary);
122
+ return { ...result, warnings: [], summary };
123
+ }
124
+ /** Delete an edge — always hard (design §6). */
125
+ async deleteEdge(id) {
126
+ this.assertOpen();
127
+ const edge = deleteEdgePrimitive(this.graph, id);
128
+ const summary = `delete edge ${id}`;
129
+ await this.record('delete_edge', { id }, summary);
130
+ return { edge, warnings: [], summary };
131
+ }
132
+ /**
133
+ * Create an explicit edge. Errors: unknown endpoints (a hidden edge type's
134
+ * `to` may dangle), unknown edge type, duplicate edge, invalid
135
+ * state/stability. Edge-type constraint and property-schema violations are
136
+ * lint warnings on the result.
137
+ */
138
+ async createEdge(input) {
139
+ this.assertOpen();
140
+ const errors = [];
141
+ const edgeTypes = this.graph.edgeTypes ?? CORE_EDGE_TYPE_MAP;
142
+ const typeDef = edgeTypes.get(input.type);
143
+ if (!typeDef) {
144
+ errors.push(mutationDiagnostic('error', `unknown edge type '${input.type}'`));
145
+ }
146
+ if (!this.graph.nodesById.has(input.from)) {
147
+ errors.push(mutationDiagnostic('error', `cannot create edge: 'from' node not found: ${input.from}`, input.from));
148
+ }
149
+ if (!this.graph.nodesById.has(input.to) && typeDef?.hidden !== true) {
150
+ errors.push(mutationDiagnostic('error', `cannot create edge: 'to' node not found: ${input.to}`, input.to));
151
+ }
152
+ validateStateStability(input.state, input.stability, errors);
153
+ const id = `${input.from}__${input.type}__${input.to}`;
154
+ if (findEdgeById(this.graph, id)) {
155
+ errors.push(mutationDiagnostic('error', `edge already exists: ${id}`));
156
+ }
157
+ if (errors.length > 0)
158
+ throw new MutationError(errors);
159
+ const edge = {
160
+ id,
161
+ from: input.from,
162
+ to: input.to,
163
+ type: input.type,
164
+ state: input.state ?? 'proposed',
165
+ stability: input.stability ?? 'unstable',
166
+ ...(input.notes !== undefined && { notes: input.notes }),
167
+ ...(input.properties !== undefined && { properties: { ...input.properties } }),
168
+ };
169
+ const warnings = lintEdge(this.graph, edge).filter(d => d.severity === 'warning');
170
+ insertEdgeIntoIndexes(this.graph, edge);
171
+ const summary = `create edge ${id}`;
172
+ await this.record('create_edge', { from: input.from, to: input.to, type: input.type }, summary);
173
+ return { edge, warnings, summary };
174
+ }
175
+ /** Patch an explicit edge. Endpoints and type are immutable (delete + create instead). */
176
+ async updateEdge(id, patch) {
177
+ this.assertOpen();
178
+ const edge = findEdgeById(this.graph, id);
179
+ if (!edge) {
180
+ throw new MutationError([mutationDiagnostic('error', `cannot update: edge not found: ${id}`)]);
181
+ }
182
+ const errors = [];
183
+ validateStateStability(patch.state, patch.stability, errors);
184
+ if (errors.length > 0)
185
+ throw new MutationError(errors);
186
+ if (patch.state !== undefined)
187
+ edge.state = patch.state;
188
+ if (patch.stability !== undefined)
189
+ edge.stability = patch.stability;
190
+ if (patch.notes !== undefined) {
191
+ if (patch.notes === null)
192
+ delete edge.notes;
193
+ else
194
+ edge.notes = patch.notes;
195
+ }
196
+ if (patch.properties !== undefined) {
197
+ const merged = { ...(edge.properties ?? {}) };
198
+ applyPropertyPatch(merged, patch.properties);
199
+ if (Object.keys(merged).length === 0)
200
+ delete edge.properties;
201
+ else
202
+ edge.properties = merged;
203
+ }
204
+ const warnings = lintEdge(this.graph, edge).filter(d => d.severity === 'warning');
205
+ const summary = `update edge ${id}`;
206
+ await this.record('update_edge', { id, ...patch }, summary);
207
+ return { edge, warnings, summary };
208
+ }
209
+ /** Patch a node's properties/state/stability. `null` clears a property key. Names change via renameNode only. */
210
+ async updateNode(id, patch) {
211
+ this.assertOpen();
212
+ const node = this.graph.nodesById.get(id);
213
+ if (!node) {
214
+ throw new MutationError([mutationDiagnostic('error', `cannot update: node not found: ${id}`, id)]);
215
+ }
216
+ const errors = [];
217
+ validateStateStability(patch.state, patch.stability, errors);
218
+ if (errors.length > 0)
219
+ throw new MutationError(errors);
220
+ if (patch.state !== undefined)
221
+ node.state = patch.state;
222
+ if (patch.stability !== undefined)
223
+ node.stability = patch.stability;
224
+ if (patch.properties !== undefined)
225
+ applyPropertyPatch(node.properties, patch.properties);
226
+ node.lastModifiedAt = mutationTimestamp();
227
+ const warnings = lintNode(this.graph, node).filter(d => d.severity === 'warning');
228
+ const summary = `update ${id}`;
229
+ await this.record('update_node', { id, ...patch }, summary);
230
+ return { node, warnings, summary };
231
+ }
232
+ /**
233
+ * Create a root cluster or an owned child (with nested children in one
234
+ * call), reusing the loader's cluster materialisation so structural edges
235
+ * and defaults match load semantics exactly (design §8 create_node).
236
+ */
237
+ async createNode(input) {
238
+ this.assertOpen();
239
+ const result = input.parentId !== undefined
240
+ ? this.materialiseChild(input)
241
+ : this.materialiseRoot(input.document);
242
+ // Collision check before merging — the working graph is untouched on failure.
243
+ const errors = [];
244
+ for (const nodeId of result.nodes.keys()) {
245
+ if (this.graph.nodesById.has(nodeId)) {
246
+ errors.push(mutationDiagnostic('error', `node already exists: ${nodeId}`, nodeId));
247
+ }
248
+ }
249
+ if (errors.length > 0)
250
+ throw new MutationError(errors);
251
+ const timestamp = mutationTimestamp();
252
+ const warnings = [];
253
+ for (const node of result.nodes.values()) {
254
+ node.lastModifiedAt = timestamp;
255
+ this.graph.nodesById.set(node.id, node);
256
+ }
257
+ for (const edges of result.edgesByFrom.values()) {
258
+ for (const edge of edges) {
259
+ if (!findEdgeById(this.graph, edge.id))
260
+ insertEdgeIntoIndexes(this.graph, edge);
261
+ }
262
+ }
263
+ for (const node of result.nodes.values()) {
264
+ warnings.push(...lintNode(this.graph, node).filter(d => d.severity === 'warning'));
265
+ }
266
+ const createdIds = [...result.nodes.keys()];
267
+ const summary = `create ${createdIds[0]}${createdIds.length > 1 ? ` (+${createdIds.length - 1} owned)` : ''}`;
268
+ await this.record('create_node', {
269
+ id: createdIds[0],
270
+ ...(input.parentId !== undefined && { parentId: input.parentId, section: input.section, name: input.name }),
271
+ }, summary);
272
+ return { createdIds, warnings, summary };
273
+ }
274
+ /**
275
+ * Upsert a cluster-style nested document (design §8/§14f). `merge` updates
276
+ * only what the document mentions; `replace` makes the document
277
+ * authoritative for every owned section — absent children (and every child
278
+ * of an absent owned section) are deleted via §6 semantics against the
279
+ * session's trail-threshold set. A changed key is never a rename
280
+ * (delete+add plus a possible-rename warning). Validates before applying;
281
+ * a no-op apply records no journal entry.
282
+ */
283
+ async applyCluster(document, mode) {
284
+ this.assertOpen();
285
+ const outcome = applyClusterToGraph(this.graph, document, mode, this.defaultBranchIds);
286
+ const changeCount = outcome.createdIds.length + outcome.updatedIds.length + outcome.deleted.length;
287
+ const summary = `apply_cluster ${outcome.rootId} (${mode}): ` +
288
+ `+${outcome.createdIds.length} ~${outcome.updatedIds.length} -${outcome.deleted.length}`;
289
+ if (changeCount > 0) {
290
+ await this.record('apply_cluster', { rootId: outcome.rootId, mode }, summary);
291
+ }
292
+ return { ...outcome, summary };
293
+ }
294
+ /** Journal + working-graph-vs-base summary diff (design §8 pending_changes). */
295
+ pendingChanges() {
296
+ this.assertOpen();
297
+ return {
298
+ branch: this.branch,
299
+ baseSha: this.baseSha,
300
+ autosave: this.autosave,
301
+ journal: [...this.journal],
302
+ diff: {
303
+ nodes: diffCounts(this.baseNodes, snapshotNodes(this.graph)),
304
+ edges: diffCounts(this.baseEdges, snapshotEdges(this.graph)),
305
+ },
306
+ };
307
+ }
308
+ /**
309
+ * Abort the session (design §7). No further writes; with file-source
310
+ * autosave, write-through mutations already on disk are NOT rolled back —
311
+ * autosave trades checkpoint durability for commit-level atomicity.
312
+ */
313
+ discard() {
314
+ this.closed = true;
315
+ if (currentSession === this)
316
+ currentSession = null;
317
+ }
318
+ /**
319
+ * Lint-gate, serialise, and commit the working graph (design §7/§10/§14e).
320
+ *
321
+ * - Full `lintGraph` first: error diagnostics BLOCK the commit
322
+ * (MutationError; the session stays open so the caller can fix and
323
+ * retry); warnings ride along on the result.
324
+ * - File-source autosave (write-through): every mutation is already on
325
+ * disk, so after the lint gate this just closes the session. A lint
326
+ * failure here leaves the session open with the content still on disk —
327
+ * per-operation validation makes error-severity drift unlikely, and the
328
+ * caller can repair and re-commit.
329
+ * - Moved-head detection (design §10): if the branch head moved since
330
+ * session start and the intervening commits are not all session WIP
331
+ * checkpoints, the commit fails; discard and replay.
332
+ * - Squash guard (design §14e): with git autosave, when every commit since
333
+ * baseSha is a session WIP (compared by SHA set), the run is squashed
334
+ * into one commit parented at baseSha (force-push where needed);
335
+ * otherwise the final commit lands on top and WIP checkpoints are
336
+ * preserved.
337
+ */
338
+ async commitChanges(message) {
339
+ this.assertOpen();
340
+ const lint = lintGraph(this.graph);
341
+ if (lint.some(d => d.severity === 'error')) {
342
+ throw new MutationError(lint);
343
+ }
344
+ const warnings = lint.filter(d => d.severity === 'warning');
345
+ if (this.journal.length === 0) {
346
+ this.discard();
347
+ return { committed: false, squashed: false, warnings, note: 'no pending changes' };
348
+ }
349
+ if (this.isFileSource && this.autosave) {
350
+ // Write-through: content already persisted per mutation; commit closes the session.
351
+ this.discard();
352
+ return {
353
+ committed: true,
354
+ squashed: false,
355
+ warnings,
356
+ note: 'autosave write-through: changes already persisted per mutation; session closed',
357
+ };
358
+ }
359
+ const msg = message ?? this.defaultCommitMessage();
360
+ let shas = [];
361
+ try {
362
+ shas = await this.source.log(this.branch, this.baseSha);
363
+ }
364
+ catch {
365
+ shas = []; // create-mode: the branch does not exist until the first commit
366
+ }
367
+ const externals = shas.filter(sha => !this.wipShas.has(sha));
368
+ if (externals.length > 0 && this.wipShas.size === 0) {
369
+ throw new MutationError([mutationDiagnostic('error', `branch '${this.branch}' head moved since session start (base ${this.baseSha}) — discard the session and replay`)]);
370
+ }
371
+ let squashed = false;
372
+ let note;
373
+ if (externals.length === 0 && shas.length > 0) {
374
+ // Guard holds: every commit since baseSha is a session WIP — squash.
375
+ await this.source.commit(this.branch, serializeGraph(this.graph), msg, {
376
+ replaceGraphContent: true,
377
+ createBranchIfMissing: this.createBranch,
378
+ parentSha: this.baseSha,
379
+ force: true,
380
+ });
381
+ squashed = true;
382
+ note = 'WIP checkpoints squashed into a single commit';
383
+ }
384
+ else {
385
+ await this.source.commit(this.branch, serializeGraph(this.graph), msg, {
386
+ replaceGraphContent: true,
387
+ createBranchIfMissing: this.createBranch,
388
+ });
389
+ if (externals.length > 0)
390
+ note = 'WIP checkpoints preserved (external commit interleaved)';
391
+ }
392
+ this.discard();
393
+ return { committed: true, message: msg, squashed, warnings, note };
394
+ }
395
+ // -- internals ------------------------------------------------------------
396
+ assertOpen() {
397
+ if (this.closed) {
398
+ throw new MutationError([mutationDiagnostic('error', 'working session is closed — start a new session')]);
399
+ }
400
+ }
401
+ async record(op, args, summary) {
402
+ this.journal.push({ op, args, summary });
403
+ if (!this.autosave)
404
+ return;
405
+ // Autosave checkpoint (design §7 table): file sources write through to
406
+ // disk; git sources land a WIP checkpoint commit whose SHA is recorded
407
+ // for the squash guard.
408
+ await this.source.commit(this.branch, serializeGraph(this.graph), `corum-wip: ${summary}`, {
409
+ replaceGraphContent: true,
410
+ createBranchIfMissing: this.createBranch,
411
+ });
412
+ if (!this.isFileSource) {
413
+ this.wipShas.add(await this.source.head(this.branch));
414
+ }
415
+ }
416
+ defaultCommitMessage() {
417
+ const summaries = this.journal.map(entry => entry.summary);
418
+ const MAX = 3;
419
+ const shown = summaries.slice(0, MAX).join('; ');
420
+ const more = summaries.length > MAX ? ` (+${summaries.length - MAX} more)` : '';
421
+ return `corum: ${shown}${more}`;
422
+ }
423
+ /** Parse a root cluster document through the loader (same semantics as loading the YAML file). */
424
+ materialiseRoot(document) {
425
+ return materialiseRootDocument(document, this.graph.templates);
426
+ }
427
+ /** Materialise one owned child (plus nested children) via the loader's machinery. */
428
+ materialiseChild(input) {
429
+ const { parentId, section, name, document } = input;
430
+ const errors = [];
431
+ const parent = this.graph.nodesById.get(parentId);
432
+ if (!parent) {
433
+ throw new MutationError([mutationDiagnostic('error', `cannot create node: parent not found: ${parentId}`, parentId)]);
434
+ }
435
+ if (typeof section !== 'string' || typeof name !== 'string') {
436
+ throw new MutationError([mutationDiagnostic('error', 'create node: owned-child creation requires section and name', parentId)]);
437
+ }
438
+ const segmentError = validateSegment(name);
439
+ if (segmentError) {
440
+ throw new MutationError([mutationDiagnostic('error', `create node: ${segmentError}`, parentId)]);
441
+ }
442
+ const template = this.graph.templates.get(parent.template);
443
+ const ownedSections = template ? getOwnedSections(template) : {};
444
+ if (!(section in ownedSections)) {
445
+ throw new MutationError([mutationDiagnostic('error', `template '${parent.template}' does not own a '${section}' section`, parentId)]);
446
+ }
447
+ const result = { nodes: new Map(), edgesByFrom: new Map(), edgesByTo: new Map() };
448
+ const diagnostics = [];
449
+ materialiseChildren(result, parent, this.clusterRootOf(parent), { [section]: { [name]: document } }, this.graph.templates, '<mutation>', diagnostics);
450
+ errors.push(...diagnostics.filter(d => d.severity === 'error'));
451
+ if (errors.length > 0)
452
+ throw new MutationError([...errors, ...diagnostics.filter(d => d.severity === 'warning')]);
453
+ return result;
454
+ }
455
+ clusterRootOf(node) {
456
+ let current = node;
457
+ while (current.parentId !== undefined) {
458
+ const parent = this.graph.nodesById.get(current.parentId);
459
+ if (!parent)
460
+ break;
461
+ current = parent;
462
+ }
463
+ return current;
464
+ }
465
+ }
466
+ // -- helpers ----------------------------------------------------------------
467
+ function validateStateStability(state, stability, errors) {
468
+ if (state !== undefined && !VALID_STATE_SET.has(state)) {
469
+ errors.push(mutationDiagnostic('error', `invalid state '${state}'`));
470
+ }
471
+ if (stability !== undefined && !VALID_STABILITY_SET.has(stability)) {
472
+ errors.push(mutationDiagnostic('error', `invalid stability '${stability}'`));
473
+ }
474
+ }
475
+ function applyPropertyPatch(target, patch) {
476
+ for (const [key, value] of Object.entries(patch)) {
477
+ if (value === null)
478
+ delete target[key];
479
+ else
480
+ target[key] = value;
481
+ }
482
+ }
483
+ function snapshotNodes(graph) {
484
+ const map = new Map();
485
+ for (const node of graph.nodesById.values())
486
+ map.set(node.id, JSON.stringify(node));
487
+ return map;
488
+ }
489
+ function snapshotEdges(graph) {
490
+ const map = new Map();
491
+ for (const edges of graph.edgesByFrom.values()) {
492
+ for (const edge of edges)
493
+ map.set(edge.id, JSON.stringify(edge));
494
+ }
495
+ return map;
496
+ }
497
+ function diffCounts(base, current) {
498
+ let added = 0;
499
+ let modified = 0;
500
+ let removed = 0;
501
+ for (const [id, value] of current) {
502
+ const before = base.get(id);
503
+ if (before === undefined)
504
+ added++;
505
+ else if (before !== value)
506
+ modified++;
507
+ }
508
+ for (const id of base.keys()) {
509
+ if (!current.has(id))
510
+ removed++;
511
+ }
512
+ return { added, modified, removed };
513
+ }
@@ -0,0 +1,62 @@
1
+ /** Timestamp convention for mutated nodes (matches adapter mappers: date-only ISO). */
2
+ export function mutationTimestamp() {
3
+ return new Date().toISOString().split('T')[0];
4
+ }
5
+ export function mutationDiagnostic(severity, message, nodeId) {
6
+ return { severity, file: '<mutation>', ...(nodeId !== undefined && { nodeId }), message };
7
+ }
8
+ /**
9
+ * IDs of a node's owned subtree (the node itself plus every exact-segment
10
+ * descendant — `orders.x` never matches `orders.xy`).
11
+ */
12
+ export function collectSubtreeIds(graph, rootId) {
13
+ const prefix = `${rootId}.`;
14
+ const ids = [];
15
+ for (const id of graph.nodesById.keys()) {
16
+ if (id === rootId || id.startsWith(prefix))
17
+ ids.push(id);
18
+ }
19
+ return ids;
20
+ }
21
+ /** Every edge touching any of the given IDs (exact endpoint match), deduplicated. */
22
+ export function collectEdgesTouching(graph, ids) {
23
+ const edges = new Set();
24
+ for (const id of ids) {
25
+ for (const edge of graph.edgesByFrom.get(id) ?? [])
26
+ edges.add(edge);
27
+ for (const edge of graph.edgesByTo.get(id) ?? [])
28
+ edges.add(edge);
29
+ }
30
+ return [...edges];
31
+ }
32
+ export function removeEdgeFromIndexes(graph, edge) {
33
+ removeFromBucket(graph.edgesByFrom, edge.from, edge);
34
+ removeFromBucket(graph.edgesByTo, edge.to, edge);
35
+ }
36
+ export function insertEdgeIntoIndexes(graph, edge) {
37
+ const from = graph.edgesByFrom.get(edge.from) ?? [];
38
+ from.push(edge);
39
+ graph.edgesByFrom.set(edge.from, from);
40
+ const to = graph.edgesByTo.get(edge.to) ?? [];
41
+ to.push(edge);
42
+ graph.edgesByTo.set(edge.to, to);
43
+ }
44
+ export function findEdgeById(graph, edgeId) {
45
+ for (const edges of graph.edgesByFrom.values()) {
46
+ for (const edge of edges) {
47
+ if (edge.id === edgeId)
48
+ return edge;
49
+ }
50
+ }
51
+ return undefined;
52
+ }
53
+ function removeFromBucket(index, key, edge) {
54
+ const bucket = index.get(key);
55
+ if (!bucket)
56
+ return;
57
+ const remaining = bucket.filter(e => e !== edge);
58
+ if (remaining.length === 0)
59
+ index.delete(key);
60
+ else
61
+ index.set(key, remaining);
62
+ }