@atolis-hq/corum 0.1.44 → 0.1.46

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,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
+ }
@@ -0,0 +1,551 @@
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 { edge, errors } = this.planEdge(input, new Set());
141
+ if (errors.length > 0)
142
+ throw new MutationError(errors);
143
+ const warnings = lintEdge(this.graph, edge).filter(d => d.severity === 'warning');
144
+ insertEdgeIntoIndexes(this.graph, edge);
145
+ const summary = `create edge ${edge.id}`;
146
+ await this.record('create_edge', { from: input.from, to: input.to, type: input.type }, summary);
147
+ return { edge: edge, warnings, summary };
148
+ }
149
+ /**
150
+ * Batch-create explicit edges as a single atomic operation: every input is
151
+ * validated (including duplicate-within-batch detection) before any edge is
152
+ * applied, so a failing item leaves the working graph untouched rather than
153
+ * partially applying earlier items. One journal entry for the whole batch.
154
+ */
155
+ async createEdges(inputs) {
156
+ this.assertOpen();
157
+ const seenIds = new Set();
158
+ const errors = [];
159
+ const candidates = [];
160
+ inputs.forEach((input, index) => {
161
+ const planned = this.planEdge(input, seenIds, index);
162
+ if (planned.errors.length > 0)
163
+ errors.push(...planned.errors);
164
+ else
165
+ candidates.push(planned.edge);
166
+ });
167
+ if (errors.length > 0)
168
+ throw new MutationError(errors);
169
+ const warnings = [];
170
+ for (const edge of candidates) {
171
+ warnings.push(...lintEdge(this.graph, edge).filter(d => d.severity === 'warning'));
172
+ insertEdgeIntoIndexes(this.graph, edge);
173
+ }
174
+ const summary = `create ${candidates.length} edge${candidates.length === 1 ? '' : 's'}`;
175
+ await this.record('create_edges', { ids: candidates.map(e => e.id) }, summary);
176
+ return { edges: candidates, warnings, summary };
177
+ }
178
+ /** Pure validation + edge construction (no mutation) shared by `createEdge` and `createEdges`. */
179
+ planEdge(input, seenIds, index) {
180
+ const errors = [];
181
+ const prefix = index !== undefined ? `edges[${index}]: ` : '';
182
+ const edgeTypes = this.graph.edgeTypes ?? CORE_EDGE_TYPE_MAP;
183
+ const typeDef = edgeTypes.get(input.type);
184
+ if (!typeDef) {
185
+ errors.push(mutationDiagnostic('error', `${prefix}unknown edge type '${input.type}'`));
186
+ }
187
+ if (!this.graph.nodesById.has(input.from)) {
188
+ errors.push(mutationDiagnostic('error', `${prefix}cannot create edge: 'from' node not found: ${input.from}`, input.from));
189
+ }
190
+ if (!this.graph.nodesById.has(input.to) && typeDef?.hidden !== true) {
191
+ errors.push(mutationDiagnostic('error', `${prefix}cannot create edge: 'to' node not found: ${input.to}`, input.to));
192
+ }
193
+ validateStateStability(input.state, input.stability, errors);
194
+ const id = `${input.from}__${input.type}__${input.to}`;
195
+ if (findEdgeById(this.graph, id) || seenIds.has(id)) {
196
+ errors.push(mutationDiagnostic('error', `${prefix}edge already exists: ${id}`));
197
+ }
198
+ if (errors.length > 0)
199
+ return { errors };
200
+ seenIds.add(id);
201
+ const edge = {
202
+ id,
203
+ from: input.from,
204
+ to: input.to,
205
+ type: input.type,
206
+ state: input.state ?? 'proposed',
207
+ stability: input.stability ?? 'unstable',
208
+ ...(input.notes !== undefined && { notes: input.notes }),
209
+ ...(input.properties !== undefined && { properties: { ...input.properties } }),
210
+ };
211
+ return { edge, errors };
212
+ }
213
+ /** Patch an explicit edge. Endpoints and type are immutable (delete + create instead). */
214
+ async updateEdge(id, patch) {
215
+ this.assertOpen();
216
+ const edge = findEdgeById(this.graph, id);
217
+ if (!edge) {
218
+ throw new MutationError([mutationDiagnostic('error', `cannot update: edge not found: ${id}`)]);
219
+ }
220
+ const errors = [];
221
+ validateStateStability(patch.state, patch.stability, errors);
222
+ if (errors.length > 0)
223
+ throw new MutationError(errors);
224
+ if (patch.state !== undefined)
225
+ edge.state = patch.state;
226
+ if (patch.stability !== undefined)
227
+ edge.stability = patch.stability;
228
+ if (patch.notes !== undefined) {
229
+ if (patch.notes === null)
230
+ delete edge.notes;
231
+ else
232
+ edge.notes = patch.notes;
233
+ }
234
+ if (patch.properties !== undefined) {
235
+ const merged = { ...(edge.properties ?? {}) };
236
+ applyPropertyPatch(merged, patch.properties);
237
+ if (Object.keys(merged).length === 0)
238
+ delete edge.properties;
239
+ else
240
+ edge.properties = merged;
241
+ }
242
+ const warnings = lintEdge(this.graph, edge).filter(d => d.severity === 'warning');
243
+ const summary = `update edge ${id}`;
244
+ await this.record('update_edge', { id, ...patch }, summary);
245
+ return { edge, warnings, summary };
246
+ }
247
+ /** Patch a node's properties/state/stability. `null` clears a property key. Names change via renameNode only. */
248
+ async updateNode(id, patch) {
249
+ this.assertOpen();
250
+ const node = this.graph.nodesById.get(id);
251
+ if (!node) {
252
+ throw new MutationError([mutationDiagnostic('error', `cannot update: node not found: ${id}`, id)]);
253
+ }
254
+ const errors = [];
255
+ validateStateStability(patch.state, patch.stability, errors);
256
+ if (errors.length > 0)
257
+ throw new MutationError(errors);
258
+ if (patch.state !== undefined)
259
+ node.state = patch.state;
260
+ if (patch.stability !== undefined)
261
+ node.stability = patch.stability;
262
+ if (patch.properties !== undefined)
263
+ applyPropertyPatch(node.properties, patch.properties);
264
+ node.lastModifiedAt = mutationTimestamp();
265
+ const warnings = lintNode(this.graph, node).filter(d => d.severity === 'warning');
266
+ const summary = `update ${id}`;
267
+ await this.record('update_node', { id, ...patch }, summary);
268
+ return { node, warnings, summary };
269
+ }
270
+ /**
271
+ * Create a root cluster or an owned child (with nested children in one
272
+ * call), reusing the loader's cluster materialisation so structural edges
273
+ * and defaults match load semantics exactly (design §8 create_node).
274
+ */
275
+ async createNode(input) {
276
+ this.assertOpen();
277
+ const result = input.parentId !== undefined
278
+ ? this.materialiseChild(input)
279
+ : this.materialiseRoot(input.document);
280
+ // Collision check before merging — the working graph is untouched on failure.
281
+ const errors = [];
282
+ for (const nodeId of result.nodes.keys()) {
283
+ if (this.graph.nodesById.has(nodeId)) {
284
+ errors.push(mutationDiagnostic('error', `node already exists: ${nodeId}`, nodeId));
285
+ }
286
+ }
287
+ if (errors.length > 0)
288
+ throw new MutationError(errors);
289
+ const timestamp = mutationTimestamp();
290
+ const warnings = [];
291
+ for (const node of result.nodes.values()) {
292
+ node.lastModifiedAt = timestamp;
293
+ this.graph.nodesById.set(node.id, node);
294
+ }
295
+ for (const edges of result.edgesByFrom.values()) {
296
+ for (const edge of edges) {
297
+ if (!findEdgeById(this.graph, edge.id))
298
+ insertEdgeIntoIndexes(this.graph, edge);
299
+ }
300
+ }
301
+ for (const node of result.nodes.values()) {
302
+ warnings.push(...lintNode(this.graph, node).filter(d => d.severity === 'warning'));
303
+ }
304
+ const createdIds = [...result.nodes.keys()];
305
+ const summary = `create ${createdIds[0]}${createdIds.length > 1 ? ` (+${createdIds.length - 1} owned)` : ''}`;
306
+ await this.record('create_node', {
307
+ id: createdIds[0],
308
+ ...(input.parentId !== undefined && { parentId: input.parentId, section: input.section, name: input.name }),
309
+ }, summary);
310
+ return { createdIds, warnings, summary };
311
+ }
312
+ /**
313
+ * Upsert a cluster-style nested document (design §8/§14f). `merge` updates
314
+ * only what the document mentions; `replace` makes the document
315
+ * authoritative for every owned section — absent children (and every child
316
+ * of an absent owned section) are deleted via §6 semantics against the
317
+ * session's trail-threshold set. A changed key is never a rename
318
+ * (delete+add plus a possible-rename warning). Validates before applying;
319
+ * a no-op apply records no journal entry.
320
+ */
321
+ async applyCluster(document, mode) {
322
+ this.assertOpen();
323
+ const outcome = applyClusterToGraph(this.graph, document, mode, this.defaultBranchIds);
324
+ const changeCount = outcome.createdIds.length + outcome.updatedIds.length + outcome.deleted.length;
325
+ const summary = `apply_cluster ${outcome.rootId} (${mode}): ` +
326
+ `+${outcome.createdIds.length} ~${outcome.updatedIds.length} -${outcome.deleted.length}`;
327
+ if (changeCount > 0) {
328
+ await this.record('apply_cluster', { rootId: outcome.rootId, mode }, summary);
329
+ }
330
+ return { ...outcome, summary };
331
+ }
332
+ /** Journal + working-graph-vs-base summary diff (design §8 pending_changes). */
333
+ pendingChanges() {
334
+ this.assertOpen();
335
+ return {
336
+ branch: this.branch,
337
+ baseSha: this.baseSha,
338
+ autosave: this.autosave,
339
+ journal: [...this.journal],
340
+ diff: {
341
+ nodes: diffCounts(this.baseNodes, snapshotNodes(this.graph)),
342
+ edges: diffCounts(this.baseEdges, snapshotEdges(this.graph)),
343
+ },
344
+ };
345
+ }
346
+ /**
347
+ * Abort the session (design §7). No further writes; with file-source
348
+ * autosave, write-through mutations already on disk are NOT rolled back —
349
+ * autosave trades checkpoint durability for commit-level atomicity.
350
+ */
351
+ discard() {
352
+ this.closed = true;
353
+ if (currentSession === this)
354
+ currentSession = null;
355
+ }
356
+ /**
357
+ * Lint-gate, serialise, and commit the working graph (design §7/§10/§14e).
358
+ *
359
+ * - Full `lintGraph` first: error diagnostics BLOCK the commit
360
+ * (MutationError; the session stays open so the caller can fix and
361
+ * retry); warnings ride along on the result.
362
+ * - File-source autosave (write-through): every mutation is already on
363
+ * disk, so after the lint gate this just closes the session. A lint
364
+ * failure here leaves the session open with the content still on disk —
365
+ * per-operation validation makes error-severity drift unlikely, and the
366
+ * caller can repair and re-commit.
367
+ * - Moved-head detection (design §10): if the branch head moved since
368
+ * session start and the intervening commits are not all session WIP
369
+ * checkpoints, the commit fails; discard and replay.
370
+ * - Squash guard (design §14e): with git autosave, when every commit since
371
+ * baseSha is a session WIP (compared by SHA set), the run is squashed
372
+ * into one commit parented at baseSha (force-push where needed);
373
+ * otherwise the final commit lands on top and WIP checkpoints are
374
+ * preserved.
375
+ */
376
+ async commitChanges(message) {
377
+ this.assertOpen();
378
+ const lint = lintGraph(this.graph);
379
+ if (lint.some(d => d.severity === 'error')) {
380
+ throw new MutationError(lint);
381
+ }
382
+ const warnings = lint.filter(d => d.severity === 'warning');
383
+ if (this.journal.length === 0) {
384
+ this.discard();
385
+ return { committed: false, squashed: false, warnings, note: 'no pending changes' };
386
+ }
387
+ if (this.isFileSource && this.autosave) {
388
+ // Write-through: content already persisted per mutation; commit closes the session.
389
+ this.discard();
390
+ return {
391
+ committed: true,
392
+ squashed: false,
393
+ warnings,
394
+ note: 'autosave write-through: changes already persisted per mutation; session closed',
395
+ };
396
+ }
397
+ const msg = message ?? this.defaultCommitMessage();
398
+ let shas = [];
399
+ try {
400
+ shas = await this.source.log(this.branch, this.baseSha);
401
+ }
402
+ catch {
403
+ shas = []; // create-mode: the branch does not exist until the first commit
404
+ }
405
+ const externals = shas.filter(sha => !this.wipShas.has(sha));
406
+ if (externals.length > 0 && this.wipShas.size === 0) {
407
+ throw new MutationError([mutationDiagnostic('error', `branch '${this.branch}' head moved since session start (base ${this.baseSha}) — discard the session and replay`)]);
408
+ }
409
+ let squashed = false;
410
+ let note;
411
+ if (externals.length === 0 && shas.length > 0) {
412
+ // Guard holds: every commit since baseSha is a session WIP — squash.
413
+ await this.source.commit(this.branch, serializeGraph(this.graph), msg, {
414
+ replaceGraphContent: true,
415
+ createBranchIfMissing: this.createBranch,
416
+ parentSha: this.baseSha,
417
+ force: true,
418
+ });
419
+ squashed = true;
420
+ note = 'WIP checkpoints squashed into a single commit';
421
+ }
422
+ else {
423
+ await this.source.commit(this.branch, serializeGraph(this.graph), msg, {
424
+ replaceGraphContent: true,
425
+ createBranchIfMissing: this.createBranch,
426
+ });
427
+ if (externals.length > 0)
428
+ note = 'WIP checkpoints preserved (external commit interleaved)';
429
+ }
430
+ this.discard();
431
+ return { committed: true, message: msg, squashed, warnings, note };
432
+ }
433
+ // -- internals ------------------------------------------------------------
434
+ assertOpen() {
435
+ if (this.closed) {
436
+ throw new MutationError([mutationDiagnostic('error', 'working session is closed — start a new session')]);
437
+ }
438
+ }
439
+ async record(op, args, summary) {
440
+ this.journal.push({ op, args, summary });
441
+ if (!this.autosave)
442
+ return;
443
+ // Autosave checkpoint (design §7 table): file sources write through to
444
+ // disk; git sources land a WIP checkpoint commit whose SHA is recorded
445
+ // for the squash guard.
446
+ await this.source.commit(this.branch, serializeGraph(this.graph), `corum-wip: ${summary}`, {
447
+ replaceGraphContent: true,
448
+ createBranchIfMissing: this.createBranch,
449
+ });
450
+ if (!this.isFileSource) {
451
+ this.wipShas.add(await this.source.head(this.branch));
452
+ }
453
+ }
454
+ defaultCommitMessage() {
455
+ const summaries = this.journal.map(entry => entry.summary);
456
+ const MAX = 3;
457
+ const shown = summaries.slice(0, MAX).join('; ');
458
+ const more = summaries.length > MAX ? ` (+${summaries.length - MAX} more)` : '';
459
+ return `corum: ${shown}${more}`;
460
+ }
461
+ /** Parse a root cluster document through the loader (same semantics as loading the YAML file). */
462
+ materialiseRoot(document) {
463
+ return materialiseRootDocument(document, this.graph.templates);
464
+ }
465
+ /** Materialise one owned child (plus nested children) via the loader's machinery. */
466
+ materialiseChild(input) {
467
+ const { parentId, section, name, document } = input;
468
+ const errors = [];
469
+ const parent = this.graph.nodesById.get(parentId);
470
+ if (!parent) {
471
+ throw new MutationError([mutationDiagnostic('error', `cannot create node: parent not found: ${parentId}`, parentId)]);
472
+ }
473
+ if (typeof section !== 'string' || typeof name !== 'string') {
474
+ throw new MutationError([mutationDiagnostic('error', 'create node: owned-child creation requires section and name', parentId)]);
475
+ }
476
+ const segmentError = validateSegment(name);
477
+ if (segmentError) {
478
+ throw new MutationError([mutationDiagnostic('error', `create node: ${segmentError}`, parentId)]);
479
+ }
480
+ const template = this.graph.templates.get(parent.template);
481
+ const ownedSections = template ? getOwnedSections(template) : {};
482
+ if (!(section in ownedSections)) {
483
+ throw new MutationError([mutationDiagnostic('error', `template '${parent.template}' does not own a '${section}' section`, parentId)]);
484
+ }
485
+ const result = { nodes: new Map(), edgesByFrom: new Map(), edgesByTo: new Map() };
486
+ const diagnostics = [];
487
+ materialiseChildren(result, parent, this.clusterRootOf(parent), { [section]: { [name]: document } }, this.graph.templates, '<mutation>', diagnostics);
488
+ errors.push(...diagnostics.filter(d => d.severity === 'error'));
489
+ if (errors.length > 0)
490
+ throw new MutationError([...errors, ...diagnostics.filter(d => d.severity === 'warning')]);
491
+ return result;
492
+ }
493
+ clusterRootOf(node) {
494
+ let current = node;
495
+ while (current.parentId !== undefined) {
496
+ const parent = this.graph.nodesById.get(current.parentId);
497
+ if (!parent)
498
+ break;
499
+ current = parent;
500
+ }
501
+ return current;
502
+ }
503
+ }
504
+ // -- helpers ----------------------------------------------------------------
505
+ function validateStateStability(state, stability, errors) {
506
+ if (state !== undefined && !VALID_STATE_SET.has(state)) {
507
+ errors.push(mutationDiagnostic('error', `invalid state '${state}'`));
508
+ }
509
+ if (stability !== undefined && !VALID_STABILITY_SET.has(stability)) {
510
+ errors.push(mutationDiagnostic('error', `invalid stability '${stability}'`));
511
+ }
512
+ }
513
+ function applyPropertyPatch(target, patch) {
514
+ for (const [key, value] of Object.entries(patch)) {
515
+ if (value === null)
516
+ delete target[key];
517
+ else
518
+ target[key] = value;
519
+ }
520
+ }
521
+ function snapshotNodes(graph) {
522
+ const map = new Map();
523
+ for (const node of graph.nodesById.values())
524
+ map.set(node.id, JSON.stringify(node));
525
+ return map;
526
+ }
527
+ function snapshotEdges(graph) {
528
+ const map = new Map();
529
+ for (const edges of graph.edgesByFrom.values()) {
530
+ for (const edge of edges)
531
+ map.set(edge.id, JSON.stringify(edge));
532
+ }
533
+ return map;
534
+ }
535
+ function diffCounts(base, current) {
536
+ let added = 0;
537
+ let modified = 0;
538
+ let removed = 0;
539
+ for (const [id, value] of current) {
540
+ const before = base.get(id);
541
+ if (before === undefined)
542
+ added++;
543
+ else if (before !== value)
544
+ modified++;
545
+ }
546
+ for (const id of base.keys()) {
547
+ if (!current.has(id))
548
+ removed++;
549
+ }
550
+ return { added, modified, removed };
551
+ }