@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.
- package/README.md +111 -9
- package/dist/src/graph/index.js +69 -37
- package/dist/src/graph/overlay.js +106 -36
- package/dist/src/import/runner.js +17 -3
- package/dist/src/linter/index.js +242 -106
- package/dist/src/loader/cluster-loader.js +36 -3
- package/dist/src/loader/edge-loader.js +8 -2
- package/dist/src/mcp/index.js +633 -142
- package/dist/src/mcp/prompts/usage-guide.js +73 -65
- package/dist/src/mutate/alias.js +68 -0
- package/dist/src/mutate/apply-cluster.js +255 -0
- package/dist/src/mutate/delete.js +47 -0
- package/dist/src/mutate/errors.js +14 -0
- package/dist/src/mutate/index.js +11 -0
- package/dist/src/mutate/rename.js +135 -0
- package/dist/src/mutate/session.js +551 -0
- package/dist/src/mutate/util.js +62 -0
- package/dist/src/reconcile/index.js +126 -3
- package/dist/src/source/file-source.js +64 -15
- package/dist/src/source/git-source.js +121 -31
- package/dist/src/writer/graph-writer.js +64 -10
- package/package.json +2 -1
|
@@ -1,93 +1,101 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* The orientation guide is built per-graph so the Concepts section can name the
|
|
3
|
+
* templates actually loaded, instead of hard-coding pack-specific examples that
|
|
4
|
+
* mislead when a different pack is in use. Pass the loaded template names; with
|
|
5
|
+
* none, it defers to get_graph_metadata.
|
|
6
|
+
*/
|
|
7
|
+
export function buildUsageGuidePrompt(templateNames = []) {
|
|
8
|
+
const templatesLine = templateNames.length
|
|
9
|
+
? templateNames.join(', ')
|
|
10
|
+
: '(call get_graph_metadata to list them)';
|
|
11
|
+
return `
|
|
2
12
|
# Corum graph - orientation guide
|
|
3
13
|
|
|
4
|
-
Corum models service architecture as a typed graph
|
|
14
|
+
Corum models service architecture as a typed graph, stored in Git.
|
|
5
15
|
|
|
6
|
-
##
|
|
7
|
-
|
|
8
|
-
IDs encode the ownership hierarchy as a dot-separated path:
|
|
9
|
-
|
|
10
|
-
{component}.{Template}.{name} - root node
|
|
11
|
-
{component}.{Template}.{name}.{section}.{child} - owned child (for example operations, schemas, fields)
|
|
16
|
+
## Concepts
|
|
12
17
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
18
|
+
- **Node**: a design artifact whose type is one of this graph's templates (listed below). Each has a template, component, lifecycle state, stability, and properties.
|
|
19
|
+
- **Template**: a node's type. Defines its property schema, which sections it owns, and which edge types it may use; templates can extend others. Templates in this graph: ${templatesLine}.
|
|
20
|
+
- **Component**: the top-level grouping a node belongs to (the first id segment).
|
|
21
|
+
- **Cluster**: one root node plus the owned-child subtree its template materializes (e.g. a model owns schemas, which own fields). One YAML file = one cluster.
|
|
22
|
+
- **Edge**: a typed, directed relationship between two nodes.
|
|
23
|
+
- *Structural* edges (has-field, has-value, renamed-from) are auto-generated from ownership and excluded from traversal by default.
|
|
24
|
+
- *Semantic* edges (triggers, produces, reads, calls, implements, maps-to, derived-from) are the modeled relationships that get_lineage / get_cluster traverse. These are the core types; packs may add more.
|
|
25
|
+
- Call get_graph_metadata for the templates and edge types actually present in this graph.
|
|
17
26
|
|
|
18
|
-
|
|
27
|
+
## Node IDs
|
|
19
28
|
|
|
20
|
-
|
|
29
|
+
A dot path encoding the ownership hierarchy:
|
|
21
30
|
|
|
22
|
-
|
|
23
|
-
|
|
31
|
+
{component}.{Template}.{name} - root node
|
|
32
|
+
{component}.{Template}.{name}.{section}.{child} - owned child
|
|
24
33
|
|
|
25
|
-
|
|
26
|
-
has-field, has-value, renamed-from
|
|
34
|
+
The Template segment is one of this graph's templates, so a root id already tells you its component and template. search_nodes and list_nodes return root nodes only.
|
|
27
35
|
|
|
28
36
|
## Graph completeness
|
|
29
37
|
|
|
30
|
-
The graph reflects modeled relationships, not guaranteed
|
|
31
|
-
|
|
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.
|
|
38
|
+
The graph reflects modeled relationships, not guaranteed-complete truth. Missing edges do not prove no relationship exists. Treat naming, shared component context, schema similarity, and lineage adjacency as hypotheses, then verify against the relevant nodes, clusters, and source.
|
|
33
39
|
|
|
34
40
|
## Recommended workflow
|
|
35
41
|
|
|
36
|
-
1. Call get_graph_metadata first
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
4. Use direction "downstream" with depth 2 from events to trace event -> command -> operation chains.
|
|
43
|
-
|
|
44
|
-
5. Use direction "upstream" from a DomainModel node to find all writers to that aggregate.
|
|
45
|
-
|
|
46
|
-
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
|
-
|
|
48
|
-
7. Add include_provenance: true only when you need to bridge a finding to the source codebase.
|
|
42
|
+
1. Call get_graph_metadata first — learn which templates and edge types actually exist. Only traverse edge types listed in edge_types_in_use.
|
|
43
|
+
2. search_nodes with domain terms to find starting nodes. Avoid list_nodes for discovery — it returns full inventories rather than ranked matches.
|
|
44
|
+
3. get_lineage with node_ids batched together in one call. direction "downstream" for what a node leads to, "upstream" for what leads into it, "both" for full flow. Bound with the smallest depth that answers the question; narrow with edge_types / node_types before increasing depth.
|
|
45
|
+
4. get_cluster only when you need one node's structural detail, not for traversal.
|
|
46
|
+
5. Add include_provenance: true only to bridge a finding back to source code.
|
|
49
47
|
|
|
50
|
-
##
|
|
48
|
+
## Token economy
|
|
51
49
|
|
|
52
|
-
|
|
50
|
+
Prefer the smallest response that answers the question.
|
|
53
51
|
|
|
54
|
-
|
|
52
|
+
- Responses default to format "toon" (lean, self-describing). Use format "yaml" for human-readable output, format "json" for conventional parsing. Add compact_keys: true to further shorten envelope keys (mapping below).
|
|
53
|
+
- Expensive tools — bound them:
|
|
54
|
+
- get_graph returns the whole graph; prefer search_nodes or get_lineage for anything targeted.
|
|
55
|
+
- get_cluster returns the root with its collapsed schemas/enums; owned descendants are opt-in (include_descendants: true) and can be large. Narrow with node_types.
|
|
56
|
+
- search_nodes returns slim summaries (id, template, component, state, stability); full_nodes: true adds every property and is far larger — leave it off unless you need the bodies. Bound with page_size.
|
|
57
|
+
- Keep include_provenance and include_edges off unless needed.
|
|
58
|
+
- get_lineage is lean by default (only i, oi, d, vet, vni per node) and omits edges; set lean:false / include_edges:true only when you need full nodes or edge-level detail.
|
|
55
59
|
|
|
56
|
-
|
|
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
|
|
60
|
+
When compact_keys is true these keys are shortened:
|
|
65
61
|
|
|
66
|
-
|
|
67
|
-
|
|
62
|
+
id -> i template -> t component -> cp
|
|
63
|
+
state -> s stability -> st properties -> p
|
|
64
|
+
nodes -> n edges -> e root -> r
|
|
65
|
+
children -> ch from -> fr to -> to
|
|
66
|
+
type -> ty notes -> nt version -> v
|
|
67
|
+
core -> c abstract -> a extends -> ex
|
|
68
|
+
origin_id -> oi depth -> d via_edge_type -> vet
|
|
69
|
+
via_node_id -> vni lastModifiedAt -> lm extractedFrom -> xf
|
|
70
|
+
derivation -> dv derivedBy -> db
|
|
68
71
|
|
|
69
72
|
## Common patterns
|
|
70
73
|
|
|
71
|
-
|
|
72
|
-
list_nodes - filter { templates: ["DomainEvent", "IntegrationEvent"], component: "orders" }
|
|
74
|
+
(all default to toon; add compact_keys: true to shrink further)
|
|
73
75
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
+
- Nodes of given templates in a component: list_nodes, filter { templates: [...], component: "..." }.
|
|
77
|
+
- What does this node produce? get_lineage, direction "downstream", edge_types ["produces"], depth 1.
|
|
78
|
+
- What triggers this node? get_lineage, direction "upstream", edge_types ["triggers"], depth 1.
|
|
79
|
+
- Full flow around a node: get_lineage, direction "both", depth 3.
|
|
80
|
+
- Field-level mappings: get_linked_fields for maps-to edges on fields owned by a root node.
|
|
81
|
+
- Schema / field detail: get_cluster (collapse_schemas true, the default) returns each schema as a compact map of field name to { type?, $ref?, collection?, nullable?, edges? } — not child nodes. Local refs use $ref: '#/schemas/name' or '#/enums/name'. Map fields appear as { type: map, key, value }. Cross-cluster field edges (maps-to, derived-from) appear in the field's edges block. Set collapse_schemas false only to get the raw child nodes instead.
|
|
76
82
|
|
|
77
|
-
|
|
78
|
-
get_lineage - node_ids: ["orders.DomainModel.order.operations.complete"], direction: "upstream"
|
|
83
|
+
## Write workflow
|
|
79
84
|
|
|
80
|
-
|
|
81
|
-
get_lineage - node_ids: ["orders.DomainEvent.order-placed"], direction: "both", depth: 3
|
|
85
|
+
Mutations require an open session; no write tool works without one.
|
|
82
86
|
|
|
83
|
-
|
|
84
|
-
|
|
87
|
+
1. start_changes first. Prefer autosave: false unless you want per-mutation checkpoints (on file sources autosave writes through immediately, producing granular/noisy history).
|
|
88
|
+
2. Mutate: apply_cluster (cluster-style upserts); create_node / update_node / rename_node / delete_node; create_edges / update_edge / delete_edge; create_fields (batch field creation).
|
|
89
|
+
3. pending_changes to inspect the journal and summary diff before committing.
|
|
90
|
+
4. commit_changes (error diagnostics block it; session stays open to fix) or discard_changes.
|
|
85
91
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
collapse_schemas: false to get the full structural node-per-field representation instead.
|
|
92
|
+
Key rules:
|
|
93
|
+
- rename_node is the only rename path. apply_cluster and imports never infer renames.
|
|
94
|
+
- apply_cluster mode "replace" is authoritative: children absent from the document are deleted, and an absent owned section means an empty section.
|
|
95
|
+
- delete_node soft-deletes (state removed, still queryable) when the node is shared history on the default branch, else hard-deletes; purge:true forces hard.
|
|
96
|
+
- discard_changes only rolls back in-memory state, not autosaved file-source writes.
|
|
97
|
+
- While a session is open, reads reflect its working graph.
|
|
93
98
|
`.trim();
|
|
99
|
+
}
|
|
100
|
+
/** Base guide with no graph-specific template list; prefer buildUsageGuidePrompt(templateNames). */
|
|
101
|
+
export const USAGE_GUIDE_PROMPT = buildUsageGuidePrompt();
|
|
@@ -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';
|