diff --git a/.gitignore b/.gitignore index 37aa055..0c9a3a3 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ out/ nupkg/ .vs/ .vscode/ +node_modules/ diff --git a/README.md b/README.md index f1d3f06..b7a0e36 100644 --- a/README.md +++ b/README.md @@ -168,6 +168,10 @@ That keeps structurally separated note graphs from vanishing just because they n - `msagl`: the stock MSAGL SVG, useful as the plain baseline - `rich`: a custom SVG renderer that consumes MSAGL graph geometry and semantic metadata, then draws something with more visual hierarchy and less beige despair +## ELK Probe + +There is also a small web-side `elkjs` probe under `web/elk-probe/`. It inspects which algorithms and options are actually present in the installed `elkjs` build and can relayout existing `source-tree.json` / `control-flow.json` outputs without crossing the C# boundary. + ## Notes - unresolved and ambiguous links are written to `warnings.txt` diff --git a/web/elk-probe/README.md b/web/elk-probe/README.md new file mode 100644 index 0000000..e02eb8c --- /dev/null +++ b/web/elk-probe/README.md @@ -0,0 +1,52 @@ +# ELK Probe + +Small local `elkjs` probe for EpiphanyGraph. + +This is not the final viewer. It is a migration scout: + +- inspect which algorithms and options are actually present in the installed `elkjs` build +- adapt existing EpiphanyGraph partition JSON into ELK graphs +- run sample layouts without crossing the C# boundary +- emit simple SVG artifacts under `out/elk-probe/` for side-by-side comparison + +## Install + +```powershell +cd E:\Projects\EpiphanyGraph\web\elk-probe +npm install +``` + +## Inspect Available ELK Surface + +```powershell +npm run inspect +``` + +Writes: + +- `out/elk-probe/inspect/known-layout-algorithms.json` +- `out/elk-probe/inspect/known-layout-options.json` + +## Probe Existing Graph Output + +Point the probe at a render directory that already contains `source-tree.json` and `control-flow.json`: + +```powershell +npm run probe -- --render-dir "E:\Projects\EpiphanyGraph\out\benchmarks\aetheria-source-tree-map\20260425T082539Z\candidates\sugiyama-rich\render" +``` + +Optional flags: + +- `--render-dir ` explicit input directory; if omitted, the probe tries to use the newest benchmark candidate render it can find +- `--out-dir ` custom output directory +- `--source-tree-algorithm ` defaults to `org.eclipse.elk.layered` +- `--control-flow-algorithm ` defaults to `org.eclipse.elk.stress` + +Writes one folder per partition under `out/elk-probe//` with: + +- `input.json` +- `elk-layout.json` +- `layout.svg` +- `layout-summary.json` + +The SVG renderer here is deliberately plain. The point is to test layout integration and algorithm availability, not to declare victory with decorative sludge. diff --git a/web/elk-probe/package-lock.json b/web/elk-probe/package-lock.json new file mode 100644 index 0000000..c963ab8 --- /dev/null +++ b/web/elk-probe/package-lock.json @@ -0,0 +1,21 @@ +{ + "name": "@epiphanygraph/elk-probe", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@epiphanygraph/elk-probe", + "version": "0.1.0", + "dependencies": { + "elkjs": "^0.11.0" + } + }, + "node_modules/elkjs": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/elkjs/-/elkjs-0.11.1.tgz", + "integrity": "sha512-zxxR9k+rx5ktMwT/FwyLdPCrq7xN6e4VGGHH8hA01vVYKjTFik7nHOxBnAYtrgYUB1RpAiLvA1/U2YraWxyKKg==", + "license": "EPL-2.0" + } + } +} diff --git a/web/elk-probe/package.json b/web/elk-probe/package.json new file mode 100644 index 0000000..c27811f --- /dev/null +++ b/web/elk-probe/package.json @@ -0,0 +1,14 @@ +{ + "name": "@epiphanygraph/elk-probe", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Local elkjs probe for EpiphanyGraph layout experiments.", + "scripts": { + "probe": "node ./src/cli.mjs probe", + "inspect": "node ./src/cli.mjs inspect" + }, + "dependencies": { + "elkjs": "^0.11.0" + } +} diff --git a/web/elk-probe/src/cli.mjs b/web/elk-probe/src/cli.mjs new file mode 100644 index 0000000..713371f --- /dev/null +++ b/web/elk-probe/src/cli.mjs @@ -0,0 +1,502 @@ +import fs from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import ELK from "elkjs/lib/elk.bundled.js"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); +const defaultInspectDir = path.join(repoRoot, "out", "elk-probe", "inspect"); + +const command = process.argv[2] ?? "inspect"; +const args = parseArgs(process.argv.slice(3)); + +try { + switch (command) { + case "inspect": + await runInspect(args); + break; + case "probe": + await runProbe(args); + break; + default: + throw new Error(`Unknown command '${command}'. Use 'inspect' or 'probe'.`); + } +} catch (error) { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; +} + +async function runInspect(args) { + const outDir = resolveMaybeRelative(args["out-dir"] ?? defaultInspectDir); + const elk = createElk(); + const algorithms = await elk.knownLayoutAlgorithms(); + const options = await elk.knownLayoutOptions(); + + await fs.mkdir(outDir, { recursive: true }); + await writeJson(path.join(outDir, "known-layout-algorithms.json"), algorithms); + await writeJson(path.join(outDir, "known-layout-options.json"), options); + + console.log(`Wrote algorithm inventory to ${outDir}`); + console.log(""); + console.log("Algorithms:"); + for (const algorithm of algorithms) { + console.log(`- ${algorithm.id}`); + } + console.log(""); + console.log(`Options: ${options.length}`); +} + +async function runProbe(args) { + const renderDir = args["render-dir"] + ? resolveMaybeRelative(args["render-dir"]) + : await findLatestBenchmarkRenderDir(); + const outDir = resolveMaybeRelative( + args["out-dir"] ?? path.join(repoRoot, "out", "elk-probe", timestampNow()), + ); + const sourceTreeAlgorithm = args["source-tree-algorithm"] ?? "org.eclipse.elk.layered"; + const controlFlowAlgorithm = args["control-flow-algorithm"] ?? "org.eclipse.elk.stress"; + + await assertFile(path.join(renderDir, "source-tree.json")); + await assertFile(path.join(renderDir, "control-flow.json")); + + const elk = createElk(); + const algorithms = await elk.knownLayoutAlgorithms(); + const algorithmIds = new Set(algorithms.map((algorithm) => algorithm.id)); + + ensureAlgorithmAvailable(sourceTreeAlgorithm, algorithmIds); + ensureAlgorithmAvailable(controlFlowAlgorithm, algorithmIds); + + await fs.mkdir(outDir, { recursive: true }); + await writeJson(path.join(outDir, "known-layout-algorithms.json"), algorithms); + + const partitions = [ + { + graphKey: "source-tree", + algorithm: sourceTreeAlgorithm, + }, + { + graphKey: "control-flow", + algorithm: controlFlowAlgorithm, + }, + ]; + + for (const partition of partitions) { + const inputPath = path.join(renderDir, `${partition.graphKey}.json`); + const report = JSON.parse(await fs.readFile(inputPath, "utf8")); + const partitionOutDir = path.join(outDir, partition.graphKey); + await fs.mkdir(partitionOutDir, { recursive: true }); + + const elkGraph = buildElkGraph(report, partition.algorithm); + const layout = await elk.layout(elkGraph); + const summary = buildLayoutSummary(report, layout, partition.algorithm); + const svg = renderSvg(layout, report, partition.algorithm); + + await writeJson(path.join(partitionOutDir, "input.json"), report); + await writeJson(path.join(partitionOutDir, "elk-graph.json"), elkGraph); + await writeJson(path.join(partitionOutDir, "elk-layout.json"), layout); + await writeJson(path.join(partitionOutDir, "layout-summary.json"), summary); + await fs.writeFile(path.join(partitionOutDir, "layout.svg"), svg, "utf8"); + + console.log( + `[${partition.graphKey}] ${partition.algorithm} -> ${path.join(partitionOutDir, "layout.svg")}`, + ); + } + + console.log(""); + console.log(`Probe output: ${outDir}`); +} + +async function findLatestBenchmarkRenderDir() { + const benchmarkRoot = path.join(repoRoot, "out", "benchmarks", "aetheria-source-tree-map"); + const runEntries = await fs.readdir(benchmarkRoot, { withFileTypes: true }); + const runNames = runEntries + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort() + .reverse(); + + for (const runName of runNames) { + const candidateRoot = path.join(benchmarkRoot, runName, "candidates"); + try { + const candidateEntries = await fs.readdir(candidateRoot, { withFileTypes: true }); + const candidateNames = candidateEntries + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort((left, right) => { + const leftScore = left.includes("rich") ? 0 : 1; + const rightScore = right.includes("rich") ? 0 : 1; + return leftScore - rightScore || left.localeCompare(right); + }); + + for (const candidateName of candidateNames) { + const renderDir = path.join(candidateRoot, candidateName, "render"); + try { + await assertFile(path.join(renderDir, "source-tree.json")); + await assertFile(path.join(renderDir, "control-flow.json")); + return renderDir; + } catch { + // Keep walking until we find a valid render directory. + } + } + } catch { + // Ignore missing candidate folders and keep scanning older runs. + } + } + + throw new Error( + "Could not find a benchmark render directory automatically. Pass --render-dir explicitly.", + ); +} + +function createElk() { + return new ELK(); +} + +function buildElkGraph(report, algorithm) { + return { + id: report.GraphKey, + layoutOptions: { + "elk.algorithm": algorithm, + ...baseGraphOptions(report.GraphKey, algorithm), + }, + children: report.Nodes.map((node) => ({ + id: node.Id, + width: normalizeSize(node.Bounds.Width, 68, 260), + height: normalizeSize(node.Bounds.Height, 34, 110), + labels: [ + { + text: node.Title, + }, + ], + layoutOptions: { + ...nodeOptions(node, report.GraphKey), + }, + })), + edges: report.Edges.map((edge, index) => ({ + id: `${report.GraphKey}-edge-${index}`, + sources: [edge.SourceId], + targets: [edge.TargetId], + })), + }; +} + +function baseGraphOptions(graphKey, algorithm) { + const layered = algorithm === "org.eclipse.elk.layered"; + if (graphKey === "source-tree") { + return layered + ? { + "elk.direction": "DOWN", + "elk.layered.spacing.nodeNodeBetweenLayers": "92", + "elk.spacing.nodeNode": "42", + "elk.layered.nodePlacement.strategy": "NETWORK_SIMPLEX", + "elk.edgeRouting": "SPLINES", + } + : { + "elk.spacing.nodeNode": "48", + "elk.padding": "[top=40,left=40,bottom=40,right=40]", + }; + } + + return layered + ? { + "elk.direction": "DOWN", + "elk.layered.spacing.nodeNodeBetweenLayers": "124", + "elk.spacing.nodeNode": "84", + "elk.layered.nodePlacement.strategy": "BRANDES_KOEPF", + "elk.edgeRouting": "SPLINES", + } + : { + "elk.spacing.nodeNode": "80", + "elk.padding": "[top=60,left=60,bottom=60,right=60]", + }; +} + +function nodeOptions(node, graphKey) { + if (graphKey === "source-tree") { + return { + "elk.nodeSize.constraints": "MINIMUM_SIZE", + }; + } + + return { + "elk.nodeSize.constraints": "MINIMUM_SIZE", + }; +} + +function buildLayoutSummary(report, layout, algorithm) { + return { + graphKey: report.GraphKey, + graphTitle: report.GraphTitle, + nodeCount: report.NodeCount, + edgeCount: report.EdgeCount, + algorithm, + width: layout.width ?? 0, + height: layout.height ?? 0, + children: layout.children?.length ?? 0, + edgesWithSections: + layout.edges?.filter((edge) => Array.isArray(edge.sections) && edge.sections.length > 0).length ?? 0, + }; +} + +function renderSvg(layout, report, algorithm) { + const nodeLookup = new Map(report.Nodes.map((node) => [node.Id, node])); + const width = Math.max(1280, Math.ceil((layout.width ?? 0) + 120)); + const height = Math.max(860, Math.ceil((layout.height ?? 0) + 140)); + const headerHeight = 92; + const offsetX = 60; + const offsetY = headerHeight; + + const children = [...(layout.children ?? [])]; + const edges = [...(layout.edges ?? [])]; + + const svg = []; + svg.push(``); + svg.push( + ``, + ); + svg.push(` ${escapeXml(report.GraphTitle)} ELK layout`); + svg.push( + ` ELK probe render for ${escapeXml(report.GraphKey)} using ${escapeXml(algorithm)}.`, + ); + svg.push(` `); + svg.push(` `); + svg.push(` `); + svg.push(` `); + svg.push(` `); + svg.push(` `); + svg.push(` `); + svg.push(` `); + svg.push(` `); + svg.push(` `); + svg.push( + ` `, + ); + svg.push( + ` ${escapeXml(report.GraphTitle)}`, + ); + svg.push( + ` ${escapeXml(algorithm)}`, + ); + + svg.push(` `); + for (const edge of edges) { + const points = edgeSectionsToPoints(edge.sections, offsetX, offsetY); + if (points.length < 2) { + continue; + } + + svg.push( + ` `, + ); + } + svg.push(` `); + + svg.push(` `); + for (const child of children) { + const x = (child.x ?? 0) + offsetX; + const y = (child.y ?? 0) + offsetY; + const widthValue = child.width ?? 80; + const heightValue = child.height ?? 42; + const node = nodeLookup.get(child.id); + const color = nodeColor(node, report.GraphKey); + const lines = wrapLabel(node?.Title ?? child.id, widthValue < 120 ? 16 : 20, 2); + + svg.push( + ` `, + ); + if (node?.IsEntry) { + svg.push( + ` `, + ); + } + svg.push( + ` `, + ); + svg.push( + ` ${escapeXml(tokenFor(node))}`, + ); + + for (const [index, line] of lines.entries()) { + svg.push( + ` ${escapeXml(line)}`, + ); + } + } + svg.push(` `); + svg.push(``); + return svg.join("\n"); +} + +function edgeSectionsToPoints(sections = [], offsetX, offsetY) { + const points = []; + for (const section of sections ?? []) { + if (section.startPoint) { + points.push({ + x: section.startPoint.x + offsetX, + y: section.startPoint.y + offsetY, + }); + } + for (const bendPoint of section.bendPoints ?? []) { + points.push({ + x: bendPoint.x + offsetX, + y: bendPoint.y + offsetY, + }); + } + if (section.endPoint) { + points.push({ + x: section.endPoint.x + offsetX, + y: section.endPoint.y + offsetY, + }); + } + } + + return dedupeSequential(points); +} + +function polylinePath(points) { + const [first, ...rest] = points; + return `M ${fmt(first.x)} ${fmt(first.y)} ${rest.map((point) => `L ${fmt(point.x)} ${fmt(point.y)}`).join(" ")}`; +} + +function dedupeSequential(points) { + const deduped = []; + for (const point of points) { + const previous = deduped[deduped.length - 1]; + if (!previous || previous.x !== point.x || previous.y !== point.y) { + deduped.push(point); + } + } + + return deduped; +} + +function nodeColor(node, graphKey) { + if (node?.IsEntry) { + return "#fde68a"; + } + if (node?.Role === "anchor") { + return "#94a3b8"; + } + if (graphKey === "control-flow") { + return node?.Title?.includes("Server") ? "#60a5fa" : "#fb7185"; + } + if (node?.Title?.includes("Shared")) { + return "#67e8f9"; + } + if (node?.Title?.includes("UI") || node?.Title?.includes("Client")) { + return "#4ade80"; + } + if (node?.Title?.includes("Simulation") || node?.Title?.includes("Zone") || node?.Title?.includes("Galaxy")) { + return "#c084fc"; + } + return "#22d3ee"; +} + +function tokenFor(node) { + if (!node) { + return "N"; + } + if (node.IsEntry) { + return "E"; + } + if (node.Role === "anchor") { + return "A"; + } + const words = node.Title.split(/[\s/_-]+/).filter(Boolean); + if (words.length === 1) { + return words[0].slice(0, 2).toUpperCase(); + } + return `${words[0][0] ?? "N"}${words[1][0] ?? ""}`.toUpperCase(); +} + +function wrapLabel(label, maxChars, maxLines) { + const words = label.split(/\s+/).filter(Boolean); + const lines = []; + let current = ""; + for (const word of words) { + const candidate = current ? `${current} ${word}` : word; + if (candidate.length > maxChars && current) { + lines.push(current); + current = word; + if (lines.length === maxLines) { + break; + } + } else { + current = candidate; + } + } + if (current && lines.length < maxLines) { + lines.push(current); + } + if (lines.length === 0) { + lines.push(label); + } + if (lines.length === maxLines && words.length > 0) { + const last = lines[lines.length - 1]; + if (last.length > maxChars - 3) { + lines[lines.length - 1] = `${last.slice(0, Math.max(1, maxChars - 3))}...`; + } + } + return lines; +} + +function ensureAlgorithmAvailable(algorithm, knownAlgorithms) { + if (!knownAlgorithms.has(algorithm)) { + throw new Error( + `Algorithm '${algorithm}' is not available in this elkjs build.`, + ); + } +} + +async function assertFile(filePath) { + await fs.access(filePath); +} + +async function writeJson(filePath, value) { + await fs.writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf8"); +} + +function normalizeSize(value, min, max) { + return Math.max(min, Math.min(max, Math.round(value))); +} + +function parseArgs(argv) { + const args = {}; + for (let index = 0; index < argv.length; index += 1) { + const token = argv[index]; + if (!token.startsWith("--")) { + continue; + } + const key = token.slice(2); + const next = argv[index + 1]; + if (!next || next.startsWith("--")) { + args[key] = true; + continue; + } + args[key] = next; + index += 1; + } + return args; +} + +function resolveMaybeRelative(targetPath) { + return path.isAbsolute(targetPath) ? targetPath : path.resolve(repoRoot, targetPath); +} + +function timestampNow() { + const now = new Date(); + const pad = (value) => String(value).padStart(2, "0"); + return `${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}T${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}Z`; +} + +function escapeXml(value) { + return String(value) + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'"); +} + +function fmt(value) { + return Number(value).toFixed(2).replace(/\.00$/, ""); +}