@atolis-hq/corum 0.1.34 → 0.1.36

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.
@@ -5,7 +5,7 @@ import { existsSync, readFileSync, readdirSync, watch } from 'node:fs';
5
5
  import { readdir } from 'node:fs/promises';
6
6
  import { fileURLToPath, pathToFileURL } from 'node:url';
7
7
  import { parse as parseYaml } from 'yaml';
8
- import { computeClusterOverlay, getClusterView, listNodes } from '../graph/index.js';
8
+ import { computeClusterOverlay, getClusterView, getGraphSummary, getLineage, listNodes, searchNodes, } from '../graph/index.js';
9
9
  import { loadGraph, loadMultiGraph } from '../loader/index.js';
10
10
  import { VALID_EDGE_TYPE_SET } from '../loader/constants.js';
11
11
  import { getOwnedSections } from '../loader/pack-loader.js';
@@ -316,10 +316,18 @@ export function createApp(graph, reloadEvents = createReloadEvents(), source, mu
316
316
  res.json(templates);
317
317
  });
318
318
  app.get('/api/nodes', async (req, res) => {
319
- const { template, component, state, stability } = req.query;
319
+ const { component, state, stability } = req.query;
320
320
  const includeCore = req.query.includeCore === 'true';
321
+ const singleTemplate = typeof req.query.template === 'string' && req.query.template
322
+ ? [req.query.template]
323
+ : undefined;
324
+ const multiTemplates = Array.isArray(req.query.templates)
325
+ ? req.query.templates.filter((template) => typeof template === 'string')
326
+ : typeof req.query.templates === 'string' && req.query.templates
327
+ ? [req.query.templates]
328
+ : undefined;
321
329
  const filter = {
322
- template: typeof template === 'string' ? template : undefined,
330
+ templates: multiTemplates ?? singleTemplate,
323
331
  component: typeof component === 'string' ? component : undefined,
324
332
  state: typeof state === 'string' ? state : undefined,
325
333
  stability: typeof stability === 'string' ? stability : undefined,
@@ -356,9 +364,24 @@ export function createApp(graph, reloadEvents = createReloadEvents(), source, mu
356
364
  if (typeof req.query.ref === 'string' && multiCache) {
357
365
  targetGraph = await getGraphForRef(req.query.ref, multiCache, graph);
358
366
  }
367
+ const filterTemplates = Array.isArray(req.query.templates)
368
+ ? req.query.templates.filter((template) => typeof template === 'string')
369
+ : typeof req.query.templates === 'string' && req.query.templates
370
+ ? [req.query.templates]
371
+ : undefined;
372
+ const filterExcludeTemplates = Array.isArray(req.query.exclude_templates)
373
+ ? req.query.exclude_templates.filter((template) => typeof template === 'string')
374
+ : undefined;
375
+ const excludeSet = filterTemplates?.length
376
+ ? null
377
+ : filterExcludeTemplates?.length
378
+ ? new Set(filterExcludeTemplates)
379
+ : GRAPH_EXCLUDED_TEMPLATES;
359
380
  const nodes = [];
360
381
  for (const node of targetGraph.nodesById.values()) {
361
- if (GRAPH_EXCLUDED_TEMPLATES.has(node.template))
382
+ if (filterTemplates?.length && !filterTemplates.includes(node.template))
383
+ continue;
384
+ if (excludeSet?.has(node.template))
362
385
  continue;
363
386
  const ownership = getNavigationOwnership(targetGraph, node);
364
387
  nodes.push({
@@ -397,39 +420,76 @@ export function createApp(graph, reloadEvents = createReloadEvents(), source, mu
397
420
  if (typeof req.query.ref === 'string' && multiCache) {
398
421
  targetGraph = await getGraphForRef(req.query.ref, multiCache, graph);
399
422
  }
400
- const components = new Set();
401
- for (const node of targetGraph.nodesById.values()) {
402
- if (node.component)
403
- components.add(node.component);
404
- }
405
- const nodesWithEdges = new Set();
406
- const edgesByType = {
407
- triggers: 0, produces: 0, reads: 0, calls: 0, implements: 0, 'maps-to': 0, 'derived-from': 0,
408
- };
409
- for (const edgeList of targetGraph.edgesByFrom.values()) {
410
- for (const edge of edgeList) {
411
- if (!GRAPH_SEMANTIC_EDGE_TYPES.has(edge.type))
412
- continue;
413
- edgesByType[edge.type]++;
414
- nodesWithEdges.add(edge.from);
415
- nodesWithEdges.add(edge.to);
423
+ res.json(getGraphSummary(targetGraph));
424
+ });
425
+ app.get('/api/search', async (req, res) => {
426
+ try {
427
+ let targetGraph = graph;
428
+ if (typeof req.query.ref === 'string' && multiCache) {
429
+ targetGraph = await getGraphForRef(req.query.ref, multiCache, graph);
416
430
  }
431
+ const q = typeof req.query.q === 'string' ? req.query.q : '';
432
+ const queries = q.split(',').map(part => part.trim()).filter(Boolean);
433
+ const templates = Array.isArray(req.query.templates)
434
+ ? req.query.templates.filter((template) => typeof template === 'string')
435
+ : typeof req.query.templates === 'string' && req.query.templates
436
+ ? [req.query.templates]
437
+ : undefined;
438
+ const excludeTemplates = Array.isArray(req.query.exclude_templates)
439
+ ? req.query.exclude_templates.filter((template) => typeof template === 'string')
440
+ : undefined;
441
+ const rawLimit = parseInt(String(req.query.limit ?? '10'), 10);
442
+ const rawOffset = parseInt(String(req.query.offset ?? '0'), 10);
443
+ res.json(searchNodes(targetGraph, queries, {
444
+ templates,
445
+ excludeTemplates,
446
+ limit: Number.isNaN(rawLimit) ? 10 : rawLimit,
447
+ offset: Number.isNaN(rawOffset) ? 0 : rawOffset,
448
+ searchProperties: req.query.search_properties === 'true',
449
+ }));
450
+ }
451
+ catch (err) {
452
+ res.status(500).json({ error: String(err) });
417
453
  }
418
- const orphansByTemplate = {};
419
- for (const node of targetGraph.nodesById.values()) {
420
- if (!nodesWithEdges.has(node.id) && getNavigationOwnership(targetGraph, node) === undefined) {
421
- orphansByTemplate[node.template] = (orphansByTemplate[node.template] ?? 0) + 1;
454
+ });
455
+ app.get('/api/lineage', async (req, res) => {
456
+ try {
457
+ let targetGraph = graph;
458
+ if (typeof req.query.ref === 'string' && multiCache) {
459
+ targetGraph = await getGraphForRef(req.query.ref, multiCache, graph);
460
+ }
461
+ const nodeIds = Array.isArray(req.query.node_ids)
462
+ ? req.query.node_ids.filter((id) => typeof id === 'string')
463
+ : typeof req.query.node_ids === 'string' && req.query.node_ids
464
+ ? [req.query.node_ids]
465
+ : [];
466
+ if (nodeIds.length === 0) {
467
+ res.status(400).json({ error: 'node_ids query param required' });
468
+ return;
422
469
  }
470
+ const rawDepth = parseInt(String(req.query.depth ?? '2'), 10);
471
+ const direction = ['downstream', 'upstream', 'both'].includes(req.query.direction)
472
+ ? req.query.direction
473
+ : 'downstream';
474
+ const edgeTypes = Array.isArray(req.query.edge_types)
475
+ ? req.query.edge_types.filter((type) => typeof type === 'string' && VALID_EDGE_TYPE_SET.has(type))
476
+ : undefined;
477
+ const excludeNodeTypes = Array.isArray(req.query.exclude_node_types)
478
+ ? req.query.exclude_node_types.filter((type) => typeof type === 'string')
479
+ : undefined;
480
+ const options = {
481
+ depth: Number.isNaN(rawDepth) ? 2 : rawDepth,
482
+ direction,
483
+ edgeTypes,
484
+ excludeNodeTypes,
485
+ includeDanglingEdges: req.query.include_dangling_edges === 'true',
486
+ readsOutboundOnly: req.query.reads_outbound_only !== 'false',
487
+ };
488
+ res.json(getLineage(targetGraph, nodeIds, options));
489
+ }
490
+ catch (err) {
491
+ res.status(500).json({ error: String(err) });
423
492
  }
424
- const orphanNodeCount = Object.values(orphansByTemplate).reduce((a, b) => a + b, 0);
425
- res.json({
426
- nodeCount: targetGraph.nodesById.size,
427
- componentCount: components.size,
428
- orphanNodeCount,
429
- orphansByTemplate,
430
- edgesByType,
431
- diagnosticCount: targetGraph.diagnostics.length,
432
- });
433
493
  });
434
494
  app.get('/api/cluster', async (req, res) => {
435
495
  const nodeId = typeof req.query.nodeId === 'string' ? req.query.nodeId : undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atolis-hq/corum",
3
- "version": "0.1.34",
3
+ "version": "0.1.36",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
package/web/app.jsx CHANGED
@@ -530,26 +530,25 @@ function DashboardPage({ nodes, templates, gitMode, viewingRef, branches, branch
530
530
  .catch(() => setBranchDiff(null));
531
531
  }, [isOnNonDefaultBranch, viewingRef, defaultBranchRef]);
532
532
 
533
- const componentCount = new Set(nodes.map(n => n.component).filter(Boolean)).size;
534
- const nodeCount = nodes.length;
535
533
  const totalEdges = stats ? Object.values(stats.edgesByType).reduce((a, b) => a + b, 0) : '…';
536
534
 
537
535
  const templateMap = new Map(templates.map(t => [t.name, t]));
538
536
 
539
- const nodesByTemplate = [...nodes.reduce((acc, node) => {
540
- acc.set(node.template, (acc.get(node.template) ?? 0) + 1);
541
- return acc;
542
- }, new Map()).entries()].sort((a, b) => b[1] - a[1]);
537
+ const nodesByTemplate = stats
538
+ ? Object.entries(stats.nodesByTemplate).sort((a, b) => b[1] - a[1])
539
+ : [];
540
+
541
+ const nodesByComponent = stats
542
+ ? Object.entries(stats.nodesByComponent).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
543
+ : [];
543
544
 
544
- const nodesByState = [...nodes.reduce((acc, node) => {
545
- acc.set(node.state, (acc.get(node.state) ?? 0) + 1);
546
- return acc;
547
- }, new Map()).entries()].sort((a, b) => b[1] - a[1]);
545
+ const nodesByState = stats
546
+ ? Object.entries(stats.nodesByState).sort((a, b) => b[1] - a[1])
547
+ : [];
548
548
 
549
- const nodesByStability = [...nodes.reduce((acc, node) => {
550
- acc.set(node.stability, (acc.get(node.stability) ?? 0) + 1);
551
- return acc;
552
- }, new Map()).entries()].sort((a, b) => b[1] - a[1]);
549
+ const nodesByStability = stats
550
+ ? Object.entries(stats.nodesByStability).sort((a, b) => b[1] - a[1])
551
+ : [];
553
552
 
554
553
  const edgeRows = stats
555
554
  ? Object.entries(stats.edgesByType).filter(([, count]) => count > 0).sort((a, b) => b[1] - a[1])
@@ -562,8 +561,8 @@ function DashboardPage({ nodes, templates, gitMode, viewingRef, branches, branch
562
561
  return (
563
562
  <div className="content">
564
563
  <div className="dashboard-hero">
565
- <HeroCard value={componentCount} label="Components" />
566
- <HeroCard value={nodeCount} label="Nodes" />
564
+ <HeroCard value={stats ? stats.componentCount : '…'} label="Components" />
565
+ <HeroCard value={stats ? stats.nodeCount : '…'} label="Nodes" />
567
566
  <HeroCard value={totalEdges} label="Edges" />
568
567
  <HeroCard value={stats ? stats.orphanNodeCount : '…'} label="Orphan Nodes" />
569
568
  </div>
@@ -584,6 +583,7 @@ function DashboardPage({ nodes, templates, gitMode, viewingRef, branches, branch
584
583
  <div className="dashboard-panel">
585
584
  <div className="card-head">Nodes by Type</div>
586
585
  <div className="card-body" style={{ padding: '12px 16px' }}>
586
+ {stats === null && <div className="label-sm">Loading…</div>}
587
587
  {nodesByTemplate.map(([name, count]) => {
588
588
  const tmpl = templateMap.get(name);
589
589
  const colour = tmpl?.ui?.colour ?? 'var(--ink-4)';
@@ -600,6 +600,19 @@ function DashboardPage({ nodes, templates, gitMode, viewingRef, branches, branch
600
600
  </div>
601
601
  </div>
602
602
 
603
+ <div className="dashboard-panel">
604
+ <div className="card-head">Nodes by Component</div>
605
+ <div className="card-body" style={{ padding: '12px 16px' }}>
606
+ {stats === null && <div className="label-sm">Loading…</div>}
607
+ {nodesByComponent.map(([name, count]) => (
608
+ <div key={name} className="stat-row">
609
+ <span className="stat-row-label">{name}</span>
610
+ <span className="stat-row-value">{count}</span>
611
+ </div>
612
+ ))}
613
+ </div>
614
+ </div>
615
+
603
616
  <div className="dashboard-panel">
604
617
  <div className="card-head">Orphan Nodes by Type</div>
605
618
  <div className="card-body" style={{ padding: '12px 16px' }}>
@@ -640,6 +653,7 @@ function DashboardPage({ nodes, templates, gitMode, viewingRef, branches, branch
640
653
  <div className="dashboard-panel">
641
654
  <div className="card-head">State & Stability</div>
642
655
  <div className="card-body" style={{ padding: '12px 16px' }}>
656
+ {stats === null && <div className="label-sm">Loading…</div>}
643
657
  {nodesByState.map(([state, count]) => (
644
658
  <div key={state} className="stat-row">
645
659
  <span className="stat-row-label"><StateTag state={state} /></span>
@@ -38,72 +38,13 @@ function buildComponentMap(nodes, edges) {
38
38
  return { nodes: componentNodes, edges: componentEdges };
39
39
  }
40
40
 
41
- function buildFocusGraph(focalNodeId, nodes, edges, depth) {
42
- const nodeById = new Map(nodes.map(n => [n.id, n]));
43
- const visited = new Set([focalNodeId]);
44
-
45
- // All depths use directed two-pass BFS (downstream + upstream separately).
46
- // Undirected BFS lets upstream nodes "switch direction" and pull in sibling
47
- // chains — nodes that share an ancestor or descendant but are not in the
48
- // focal node's own lineage.
49
- //
50
- // parentId is an upstream relationship: an owned operation has no semantic
51
- // edges of its own, so climbing to the parent aggregate is the only way to
52
- // reach the edges that connect it to the wider graph. parentId traversal
53
- // belongs in the upstream pass only; adding it to the downstream pass would
54
- // re-introduce the same sideways crawl via the aggregate's other children.
55
-
56
- const downQueue = [{ id: focalNodeId, d: 0 }];
57
- while (downQueue.length > 0) {
58
- const item = downQueue.shift();
59
- const id = item.id;
60
- if (item.d >= depth) continue;
61
- for (const edge of edges) {
62
- if (edge.from === id && !visited.has(edge.to) && nodeById.has(edge.to)) {
63
- visited.add(edge.to);
64
- downQueue.push({ id: edge.to, d: item.d + 1 });
65
- }
66
- }
67
- }
68
-
69
- const upQueue = [{ id: focalNodeId, d: 0 }];
70
- while (upQueue.length > 0) {
71
- const item = upQueue.shift();
72
- const id = item.id;
73
- if (item.d >= depth) continue;
74
- for (const edge of edges) {
75
- if (edge.to === id && !visited.has(edge.from) && nodeById.has(edge.from)) {
76
- visited.add(edge.from);
77
- upQueue.push({ id: edge.from, d: item.d + 1 });
78
- }
79
- }
80
- const pid = nodeById.get(id)?.parentId;
81
- if (pid && !visited.has(pid) && nodeById.has(pid)) {
82
- visited.add(pid);
83
- upQueue.push({ id: pid, d: item.d + 1 });
84
- }
85
- }
86
-
87
- const visibleEdges = edges.filter(e => visited.has(e.from) && visited.has(e.to));
88
- const visibleNodeIds = new Set([focalNodeId]);
89
- for (const edge of visibleEdges) {
90
- visibleNodeIds.add(edge.from);
91
- visibleNodeIds.add(edge.to);
92
- }
93
-
94
- return {
95
- nodes: [...visibleNodeIds].map(id => nodeById.get(id)).filter(Boolean),
96
- edges: visibleEdges,
97
- };
98
- }
99
-
100
41
  function applyEdgeTypeFilter(edges, visibleTypes) {
101
42
  return edges.filter(e => visibleTypes.has(e.type));
102
43
  }
103
44
 
104
45
  if (typeof module !== 'undefined' && module.exports) {
105
- module.exports = { buildComponentMap, buildFocusGraph, applyEdgeTypeFilter, getDisplayName };
46
+ module.exports = { buildComponentMap, applyEdgeTypeFilter, getDisplayName };
106
47
  }
107
48
  if (typeof window !== 'undefined') {
108
- window.CorumGraphUtils = { buildComponentMap, buildFocusGraph, applyEdgeTypeFilter, getDisplayName };
49
+ window.CorumGraphUtils = { buildComponentMap, applyEdgeTypeFilter, getDisplayName };
109
50
  }
@@ -1,8 +1,8 @@
1
1
  // run with: node web/graph-utils.test.js
2
- const { buildComponentMap, buildFocusGraph, applyEdgeTypeFilter, getDisplayName } = require('./graph-utils.js');
2
+ const graphUtils = require('./graph-utils.js');
3
+ const { buildComponentMap, applyEdgeTypeFilter, getDisplayName } = graphUtils;
3
4
 
4
5
  (async () => {
5
-
6
6
  let passed = 0, failed = 0;
7
7
  function assert(condition, name) {
8
8
  if (condition) { console.log(` ✓ ${name}`); passed++; }
@@ -10,23 +10,22 @@ const { buildComponentMap, buildFocusGraph, applyEdgeTypeFilter, getDisplayName
10
10
  }
11
11
 
12
12
  const nodes = [
13
- { id: 'orders.DomainModel.order', template: 'DomainModel', component: 'orders', state: 'agreed', stability: 'stable' },
14
- { id: 'orders.RestAPI.ordersApi', template: 'RestAPI', component: 'orders', state: 'agreed', stability: 'stable' },
15
- { id: 'payments.DomainModel.payment', template: 'DomainModel', component: 'payments', state: 'proposed', stability: 'unstable' },
16
- { id: 'payments.RestAPI.paymentsApi', template: 'RestAPI', component: 'payments', state: 'proposed', stability: 'unstable' },
13
+ { id: 'orders.DomainModel.order', template: 'DomainModel', component: 'orders', state: 'agreed', stability: 'stable' },
14
+ { id: 'orders.RestAPI.ordersApi', template: 'RestAPI', component: 'orders', state: 'agreed', stability: 'stable' },
15
+ { id: 'payments.DomainModel.payment', template: 'DomainModel', component: 'payments', state: 'proposed', stability: 'unstable' },
16
+ { id: 'payments.RestAPI.paymentsApi', template: 'RestAPI', component: 'payments', state: 'proposed', stability: 'unstable' },
17
17
  ];
18
18
 
19
19
  const edges = [
20
- { id: 'e1', from: 'orders.RestAPI.ordersApi', to: 'orders.DomainModel.order', type: 'reads' },
21
- { id: 'e2', from: 'orders.RestAPI.ordersApi', to: 'payments.RestAPI.paymentsApi', type: 'calls' },
20
+ { id: 'e1', from: 'orders.RestAPI.ordersApi', to: 'orders.DomainModel.order', type: 'reads' },
21
+ { id: 'e2', from: 'orders.RestAPI.ordersApi', to: 'payments.RestAPI.paymentsApi', type: 'calls' },
22
22
  { id: 'e3', from: 'payments.RestAPI.paymentsApi', to: 'payments.DomainModel.payment', type: 'reads' },
23
23
  ];
24
24
 
25
- // getDisplayName
25
+ assert(graphUtils.buildFocusGraph === undefined, 'buildFocusGraph export removed');
26
26
  assert(getDisplayName('orders.DomainModel.order') === 'order', 'getDisplayName returns last segment');
27
27
  assert(getDisplayName('payments.RestAPI.paymentsApi') === 'paymentsApi', 'getDisplayName handles nested id');
28
28
 
29
- // buildComponentMap
30
29
  const cm = buildComponentMap(nodes, edges);
31
30
  assert(cm.nodes.length === 2, 'buildComponentMap: one node per component');
32
31
  assert(cm.nodes.every(n => typeof n.count === 'number' && n.count > 0), 'buildComponentMap: nodes have count');
@@ -38,80 +37,6 @@ const { buildComponentMap, buildFocusGraph, applyEdgeTypeFilter, getDisplayName
38
37
  const sameCmEdges = buildComponentMap(nodes, [{ id: 'x', from: 'orders.DomainModel.order', to: 'orders.RestAPI.ordersApi', type: 'reads' }]);
39
38
  assert(sameCmEdges.edges.length === 0, 'buildComponentMap: intra-component edges excluded');
40
39
 
41
- // buildFocusGraph - depth 1
42
- const focus1 = buildFocusGraph('orders.RestAPI.ordersApi', nodes, edges, 1);
43
- assert(focus1.nodes.some(n => n.id === 'orders.RestAPI.ordersApi'), 'buildFocusGraph depth=1: includes focal node');
44
- assert(focus1.nodes.some(n => n.id === 'orders.DomainModel.order'), 'buildFocusGraph depth=1: includes 1-hop neighbour (via reads)');
45
- assert(focus1.nodes.some(n => n.id === 'payments.RestAPI.paymentsApi'), 'buildFocusGraph depth=1: includes 1-hop neighbour (via calls)');
46
- assert(!focus1.nodes.some(n => n.id === 'payments.DomainModel.payment'), 'buildFocusGraph depth=1: excludes 2-hop neighbour');
47
- assert(focus1.edges.length === 2, 'buildFocusGraph depth=1: includes only edges within visible nodes');
48
-
49
- // buildFocusGraph - depth Infinity
50
- const focusAll = buildFocusGraph('orders.RestAPI.ordersApi', nodes, edges, Infinity);
51
- assert(focusAll.nodes.length === 4, 'buildFocusGraph depth=Infinity: includes all reachable nodes');
52
- assert(focusAll.edges.length === 3, 'buildFocusGraph depth=Infinity: includes all reachable edges');
53
-
54
- // buildFocusGraph - depth Infinity directed lineage (no sideways crawl)
55
- // ordersApi → order and ordersApi → paymentsApi → payment
56
- // Focusing on payment: upstream = {paymentsApi, ordersApi}, downstream = {}
57
- // order must NOT appear — it's downstream of ordersApi but not in payment's lineage
58
- const focusPayment = buildFocusGraph('payments.DomainModel.payment', nodes, edges, Infinity);
59
- assert(focusPayment.nodes.length === 3, 'buildFocusGraph depth=Infinity directed: excludes sideways nodes');
60
- assert(!focusPayment.nodes.some(n => n.id === 'orders.DomainModel.order'), 'buildFocusGraph depth=Infinity directed: sibling branch excluded');
61
- assert(focusPayment.nodes.some(n => n.id === 'orders.RestAPI.ordersApi'), 'buildFocusGraph depth=Infinity directed: upstream root included');
62
-
63
- // buildFocusGraph - directed BFS + parentId traversal (upstream pass only)
64
- // op --produces--> event (op is upstream of event)
65
- // op.parentId = agg
66
- // agg --reads--> tgt (tgt is sideways — downstream of agg only)
67
- //
68
- // From event, upstream directed BFS: event ← op (d=1) ← agg (d=2 via parentId).
69
- // tgt must NOT appear at any depth: only reachable via a downstream edge from agg,
70
- // which the upstream pass never follows.
71
- const parentNodes = [
72
- { id: 'b.Event.e', template: 'DomainEvent', component: 'b', state: 'agreed', stability: 'stable', parentId: null },
73
- { id: 'z.DomainModel.root', template: 'DomainModel', component: 'z', state: 'agreed', stability: 'stable', parentId: null },
74
- { id: 'a.DomainModel.agg', template: 'DomainModel', component: 'a', state: 'agreed', stability: 'stable', parentId: null },
75
- { id: 'a.DomainModel.agg.operations.op', template: 'DomainOperation', component: 'a', state: 'agreed', stability: 'stable', parentId: 'a.DomainModel.agg' },
76
- { id: 'c.DomainModel.tgt', template: 'DomainModel', component: 'c', state: 'agreed', stability: 'stable', parentId: null },
77
- ];
78
- const parentEdges = [
79
- { id: 'p1', from: 'a.DomainModel.agg.operations.op', to: 'b.Event.e', type: 'produces' },
80
- { id: 'p0', from: 'z.DomainModel.root', to: 'a.DomainModel.agg', type: 'reads' },
81
- { id: 'p2', from: 'a.DomainModel.agg', to: 'c.DomainModel.tgt', type: 'reads' },
82
- ];
83
- const fp1 = buildFocusGraph('b.Event.e', parentNodes, parentEdges, 1);
84
- assert(fp1.nodes.some(n => n.id === 'a.DomainModel.agg.operations.op'), 'parentId: depth=1 includes producing op (upstream)');
85
- assert(!fp1.nodes.some(n => n.id === 'a.DomainModel.agg'), 'parentId: depth=1 does not yet include aggregate');
86
- const fp2 = buildFocusGraph('b.Event.e', parentNodes, parentEdges, 2);
87
- assert(!fp2.nodes.some(n => n.id === 'a.DomainModel.agg'), 'parentId: depth=2 prunes aggregate when it has no surviving semantic edge');
88
- assert(!fp2.nodes.some(n => n.id === 'c.DomainModel.tgt'), 'parentId: depth=2 excludes sideways tgt');
89
- const fp3 = buildFocusGraph('b.Event.e', parentNodes, parentEdges, 3);
90
- assert(fp3.nodes.some(n => n.id === 'z.DomainModel.root'), 'parentId: depth=3 still uses aggregate traversal to reach upstream root');
91
- assert(!fp3.nodes.some(n => n.id === 'c.DomainModel.tgt'), 'parentId: depth=3 still excludes sideways tgt (directed)');
92
-
93
- // buildFocusGraph - Infinity keeps the same upstream parentId traversal
94
- const fpInf = buildFocusGraph('b.Event.e', parentNodes, parentEdges, Infinity);
95
- assert(fpInf.nodes.some(n => n.id === 'a.DomainModel.agg.operations.op'), 'parentId: Infinity follows semantic edges to op');
96
- assert(fpInf.nodes.some(n => n.id === 'z.DomainModel.root'), 'parentId: Infinity climbs through parent aggregate to upstream root');
97
- assert(fpInf.nodes.some(n => n.id === 'a.DomainModel.agg'), 'parentId: Infinity keeps aggregate once it participates in a surviving semantic edge');
98
- assert(!fpInf.nodes.some(n => n.id === 'c.DomainModel.tgt'), 'parentId: Infinity still excludes aggregate sideways connections');
99
-
100
- // buildFocusGraph - climbed parent without a surviving semantic edge is pruned
101
- const orphanParentNodes = [
102
- { id: 'payruns.DomainEvent.finalised', template: 'DomainEvent', component: 'payruns', state: 'agreed', stability: 'stable', parentId: null },
103
- { id: 'payruns.DomainModel.PayRunAggregate', template: 'DomainModel', component: 'payruns', state: 'agreed', stability: 'stable', parentId: null },
104
- { id: 'payruns.DomainModel.PayRunAggregate.operations.Finalise', template: 'DomainOperation', component: 'payruns', state: 'agreed', stability: 'stable', parentId: 'payruns.DomainModel.PayRunAggregate' },
105
- ];
106
- const orphanParentEdges = [
107
- { id: 'o1', from: 'payruns.DomainModel.PayRunAggregate.operations.Finalise', to: 'payruns.DomainEvent.finalised', type: 'produces' },
108
- ];
109
- const orphanParentFocus = buildFocusGraph('payruns.DomainEvent.finalised', orphanParentNodes, orphanParentEdges, 2);
110
- assert(orphanParentFocus.nodes.some(n => n.id === 'payruns.DomainModel.PayRunAggregate.operations.Finalise'), 'prune orphan parent: producing op remains visible');
111
- assert(!orphanParentFocus.nodes.some(n => n.id === 'payruns.DomainModel.PayRunAggregate'), 'prune orphan parent: aggregate without surviving edge is omitted');
112
- assert(orphanParentFocus.edges.length === 1, 'prune orphan parent: semantic edge remains intact');
113
-
114
- // applyEdgeTypeFilter
115
40
  const filtered = applyEdgeTypeFilter(edges, new Set(['reads']));
116
41
  assert(filtered.length === 2, 'applyEdgeTypeFilter: keeps only matching type');
117
42
  assert(filtered.every(e => e.type === 'reads'), 'applyEdgeTypeFilter: all results have correct type');
package/web/graph.jsx CHANGED
@@ -3,7 +3,7 @@
3
3
  const { useState, useEffect, useMemo, useCallback, useRef } = React;
4
4
  const { navigate, Icon, TemplateBadge, StateTag, StabilityTag } = window.CorumPrimitives;
5
5
  const { buildRoute, parseRoute } = window.CorumRouter;
6
- const { buildComponentMap, buildFocusGraph, applyEdgeTypeFilter, getDisplayName } = window.CorumGraphUtils;
6
+ const { buildComponentMap, applyEdgeTypeFilter, getDisplayName } = window.CorumGraphUtils;
7
7
 
8
8
  const RF = window.ReactFlow;
9
9
  const ReactFlowCanvas = RF.ReactFlow || RF.default;
@@ -272,9 +272,11 @@ function GraphView({ route, viewingRef, templates }) {
272
272
  const [showMinimap, setShowMinimap] = useState(false);
273
273
  const [depth, setDepth] = useState(2);
274
274
  const [layoutKey, setLayoutKey] = useState(0);
275
+ const [focusData, setFocusData] = useState(null);
275
276
  const [reactFlowInstance, setReactFlowInstance] = useState(null);
276
277
  const pendingViewportRef = useRef(null);
277
278
  const lastFocusedNodeIdRef = useRef(null);
279
+ const debounceTimerRef = useRef(null);
278
280
  const [rfNodes, setRfNodes, onNodesChange] = useNodesState([]);
279
281
  const [rfEdges, setRfEdges, onEdgesChange] = useEdgesState([]);
280
282
 
@@ -299,6 +301,7 @@ function GraphView({ route, viewingRef, templates }) {
299
301
 
300
302
  useEffect(() => {
301
303
  setGraphData(null);
304
+ setFocusData(null);
302
305
  setError(null);
303
306
  const refParam = viewingRef ? `?ref=${encodeURIComponent(viewingRef)}` : '';
304
307
  fetch(`/api/graph${refParam}`)
@@ -307,6 +310,26 @@ function GraphView({ route, viewingRef, templates }) {
307
310
  .catch(err => setError(String(err)));
308
311
  }, [viewingRef]);
309
312
 
313
+ useEffect(() => {
314
+ if (!focalNodeId) { setFocusData(null); return; }
315
+ setFocusData(null);
316
+ if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
317
+ debounceTimerRef.current = setTimeout(() => {
318
+ const params = new URLSearchParams([
319
+ ['node_ids', focalNodeId],
320
+ ['depth', depth === Infinity ? '999' : String(depth)],
321
+ ['direction', 'both'],
322
+ ['reads_outbound_only', 'false'],
323
+ ]);
324
+ if (viewingRef) params.append('ref', viewingRef);
325
+ fetch(`/api/lineage?${params}`)
326
+ .then(r => r.ok ? r.json() : Promise.reject(r.status))
327
+ .then(data => { setFocusData(data); })
328
+ .catch(err => setError(String(err)));
329
+ }, 150);
330
+ return () => { if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current); };
331
+ }, [focalNodeId, depth, viewingRef]);
332
+
310
333
  const templateMap = useMemo(() => new Map((templates ?? []).map(t => [t.name, t])), [templates]);
311
334
 
312
335
  const templateColour = useCallback(templateName => {
@@ -379,15 +402,23 @@ function GraphView({ route, viewingRef, templates }) {
379
402
  }, [level]);
380
403
 
381
404
  // Level 3: node focus
405
+ const nodeById = useMemo(
406
+ () => new Map((graphData?.nodes ?? []).map(n => [n.id, n])),
407
+ [graphData],
408
+ );
409
+
382
410
  const level3 = useMemo(() => {
383
- if (!graphData || !focalNodeId) return null;
384
- const { nodes: focusNodes, edges: focusEdges } = buildFocusGraph(
385
- focalNodeId, graphData.nodes, graphData.edges, depth
386
- );
387
- const rfN = buildRFNodesForNodes(focusNodes, templateMap, nodeId => {
411
+ if (!focusData || !focalNodeId) return null;
412
+ const parentIdMap = new Map((graphData?.nodes ?? []).map(n => [n.id, n.parentId]));
413
+ const focalNode = nodeById.get(focalNodeId);
414
+ const lineageNodes = [
415
+ ...(focalNode && !focusData.nodes.some(n => n.id === focalNodeId) ? [focalNode] : []),
416
+ ...focusData.nodes,
417
+ ].map(n => ({ ...n, parentId: parentIdMap.get(n.id) ?? null }));
418
+ const rfN = buildRFNodesForNodes(lineageNodes, templateMap, nodeId => {
388
419
  navigate(buildRoute({ pathname: '/graph', params: { focus: nodeId }, branch: viewingRef }));
389
420
  }, viewingRef);
390
- const rfE = buildRFEdgesForEdges(focusEdges, visibleEdgeTypes);
421
+ const rfE = buildRFEdgesForEdges(applyEdgeTypeFilter(focusData.edges, visibleEdgeTypes), visibleEdgeTypes);
391
422
  const layoutedN = computeLayout(rfN, rfE, NODE_W, NODE_H);
392
423
  return {
393
424
  rfN: layoutedN.map(n => n.id === focalNodeId
@@ -396,7 +427,7 @@ function GraphView({ route, viewingRef, templates }) {
396
427
  ),
397
428
  rfE,
398
429
  };
399
- }, [graphData, focalNodeId, depth, visibleEdgeTypes, templateMap, layoutKey, viewingRef]);
430
+ }, [focusData, focalNodeId, visibleEdgeTypes, templateMap, layoutKey, viewingRef, graphData, nodeById]);
400
431
 
401
432
  useEffect(() => {
402
433
  if (level !== 'focus' || !level3) return;
package/web/search.jsx CHANGED
@@ -3,44 +3,31 @@
3
3
  const { useState, useEffect, useRef } = React;
4
4
  const { TemplateBadge, Icon } = window.CorumPrimitives;
5
5
 
6
- function fuzzyMatch(query, id) {
7
- if (!query) return { score: 0 };
8
- const q = query.toLowerCase();
9
- const s = id.toLowerCase();
10
- let qi = 0, run = 0, maxRun = 0;
11
- for (let i = 0; i < s.length; i++) {
12
- if (qi >= q.length) break;
13
- if (s[i] === q[qi]) { qi++; run++; if (run > maxRun) maxRun = run; }
14
- else { run = 0; }
15
- }
16
- return qi === q.length ? { score: maxRun } : null;
17
- }
18
-
19
- function searchNodes(nodes, templates, query) {
20
- if (!query || !query.trim()) return [];
21
- const templateMap = new Map(templates.map(t => [t.name, t]));
22
- const results = [];
23
- for (const node of nodes) {
24
- if (node.parentId) continue;
25
- const match = fuzzyMatch(query.trim(), node.id);
26
- if (!match) continue;
27
- results.push({ node, template: templateMap.get(node.template), score: match.score });
28
- }
29
- results.sort((a, b) => b.score - a.score || a.node.id.length - b.node.id.length);
30
- return results.slice(0, 10);
31
- }
32
-
33
6
  function SearchModal({ nodes, templates, onNavigate, onClose }) {
34
7
  const [query, setQuery] = useState('');
8
+ const [results, setResults] = useState([]);
35
9
  const [selectedIndex, setSelectedIndex] = useState(0);
36
10
  const inputRef = useRef(null);
37
-
38
- const results = searchNodes(nodes, templates, query);
11
+ const templateMap = new Map((templates ?? []).map(t => [t.name, t]));
39
12
 
40
13
  useEffect(() => { setSelectedIndex(0); }, [query]);
41
14
 
42
15
  useEffect(() => { inputRef.current?.focus(); }, []);
43
16
 
17
+ useEffect(() => {
18
+ const q = query.trim();
19
+ if (!q) {
20
+ setResults([]);
21
+ return;
22
+ }
23
+
24
+ const url = `/api/search?q=${encodeURIComponent(q)}&limit=10`;
25
+ fetch(url)
26
+ .then(r => r.ok ? r.json() : Promise.reject(r.status))
27
+ .then(data => setResults(Array.isArray(data) ? data : []))
28
+ .catch(() => setResults([]));
29
+ }, [query]);
30
+
44
31
  useEffect(() => {
45
32
  function handleKey(e) {
46
33
  if (e.key === 'Escape') { onClose(); return; }
@@ -81,7 +68,8 @@ function SearchModal({ nodes, templates, onNavigate, onClose }) {
81
68
  {results.length > 0 && (
82
69
  <div className="search-results">
83
70
  {results.map((result, index) => {
84
- const { node, template } = result;
71
+ const { node } = result;
72
+ const template = templateMap.get(node.template);
85
73
  const name = node.id.split('.').pop();
86
74
  const colour = template?.ui?.colour ?? null;
87
75
  const tplName = template?.ui?.displayName ?? node.template;
package/web/style.css CHANGED
@@ -1526,10 +1526,22 @@ button {
1526
1526
 
1527
1527
  .dashboard-grid {
1528
1528
  display: grid;
1529
- grid-template-columns: 1fr 1fr;
1529
+ grid-template-columns: repeat(3, minmax(260px, 1fr));
1530
1530
  gap: 16px;
1531
1531
  }
1532
1532
 
1533
+ @media (max-width: 960px) {
1534
+ .dashboard-grid {
1535
+ grid-template-columns: repeat(2, minmax(260px, 1fr));
1536
+ }
1537
+ }
1538
+
1539
+ @media (max-width: 640px) {
1540
+ .dashboard-grid {
1541
+ grid-template-columns: 1fr;
1542
+ }
1543
+ }
1544
+
1533
1545
  .dashboard-panel {
1534
1546
  overflow: hidden;
1535
1547
  border: 1px solid var(--rule-2);