Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
feat(viz): assemble context graph JSON from .context markdown
Shrish Dwivedi1cf7aa7f1aad
diff --git a/src/viz/assemble.ts b/src/viz/assemble.tsnew file mode 100644index 00000000..d17de6f8--- /dev/null+++ b/src/viz/assemble.ts@@ -0,0 +1,130 @@+/**+ * Assembles the viz-facing JSON for the context graph: reads every `.md` node+ * file in a context dir (frontmatter = node + edges) and produces a single+ * `{meta, nodes, edges}` document the viewer can render directly.+ *+ * Design rules (see docs/superpowers/specs/2026-07-15-graft-viz-design.md):+ * - relations are normalized into the closed verb vocabulary — vague LLM+ * softeners map to the concrete verb they usually mean+ * - edges whose target slug doesn't exist are dropped (LLM output can dangle)+ * - a node file with unparseable frontmatter is skipped, never fatal+ * - both drop counts are reported in `meta` so the UI can say so+ */+import { readFileSync, readdirSync, existsSync } from "node:fs";+import { join } from "node:path";+import matter from "gray-matter";+import type { NodeLink, SourceRef } from "../context/node-file.js";++export interface VizNode {+ id: string;+ name: string;+ type: string;+ summary: string;+ sources: string[];+}++export interface VizEdge {+ source: string;+ target: string;+ relation: string;+ description?: string;+}++export interface VizGraph {+ meta: {+ nodeCount: number;+ edgeCount: number;+ skippedFiles: number;+ droppedEdges: number;+ };+ nodes: VizNode[];+ edges: VizEdge[];+}++/**+ * Legacy vague verbs → the concrete verb they usually mean. Keeps old+ * `.context/` folders readable without regeneration; the synthesizer itself+ * is constrained to the closed vocabulary going forward.+ */+export const NORMALIZE_RELATION: Record<string, string> = {+ influences: "configures",+ supports: "validates",+ defines: "validates",+ measures: "validates",+};++export function normalizeRelation(rel: string): string {+ return NORMALIZE_RELATION[rel] ?? rel;+}++const GEN_START = "<!-- context:generated:start -->";+const GEN_END = "<!-- context:generated:end -->";+const SUMMARY_MAX = 500;++/** Pull the prose summary out of a node body's generated block. */+function extractSummary(body: string): string {+ let text = body;+ const start = text.indexOf(GEN_START);+ const end = text.indexOf(GEN_END);+ if (start >= 0 && end > start) text = text.slice(start + GEN_START.length, end);+ // Keep only the Summary section if headings are present.+ const related = text.indexOf("## Related");+ if (related >= 0) text = text.slice(0, related);+ text = text.replace(/^##\s+Summary\s*$/m, "");+ text = text.trim();+ return text.length > SUMMARY_MAX ? text.slice(0, SUMMARY_MAX).trimEnd() + "…" : text;+}++/** Read a context dir and assemble the render-ready graph document. */+export function assembleContextGraph(contextDir: string): VizGraph {+ const nodes: VizNode[] = [];+ const rawEdges: VizEdge[] = [];+ let skippedFiles = 0;++ if (existsSync(contextDir)) {+ for (const entry of readdirSync(contextDir).sort()) {+ if (!entry.endsWith(".md")) continue;+ let parsed: matter.GrayMatterFile<string>;+ try {+ parsed = matter(readFileSync(join(contextDir, entry), "utf8"));+ } catch {+ skippedFiles++;+ continue;+ }+ const fm = parsed.data as Record<string, unknown>;+ const id = String(fm.slug ?? entry.replace(/\.md$/, ""));+ const sources = Array.isArray(fm.sources) ? (fm.sources as SourceRef[]) : [];+ const links = Array.isArray(fm.links) ? (fm.links as NodeLink[]) : [];+ nodes.push({+ id,+ name: String(fm.name ?? id),+ type: String(fm.type ?? "concept"),+ summary: extractSummary(parsed.content),+ sources: sources.map((s) => s.path),+ });+ for (const link of links) {+ if (!link || typeof link.to !== "string") continue;+ rawEdges.push({+ source: id,+ target: link.to,+ relation: normalizeRelation(String(link.relation ?? "uses")),+ ...(link.description ? { description: link.description } : {}),+ });+ }+ }+ }++ const known = new Set(nodes.map((n) => n.id));+ const edges = rawEdges.filter((e) => known.has(e.source) && known.has(e.target));++ return {+ meta: {+ nodeCount: nodes.length,+ edgeCount: edges.length,+ skippedFiles,+ droppedEdges: rawEdges.length - edges.length,+ },+ nodes,+ edges,+ };+}diff --git a/test/viz-assemble.test.ts b/test/viz-assemble.test.tsnew file mode 100644index 00000000..bd2a200c--- /dev/null+++ b/test/viz-assemble.test.ts@@ -0,0 +1,105 @@+/**+ * Tests for the viz graph assembly: .context/*.md frontmatter → {meta, nodes, edges}+ * with relation normalization, dangling-edge dropping, and malformed-file skipping.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync, writeFileSync, rmSync } from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { assembleContextGraph, normalizeRelation } from "../src/viz/assemble.js";++function makeContextDir(): string {+ const dir = mkdtempSync(join(tmpdir(), "graftviz-"));+ writeFileSync(+ join(dir, "alpha.md"),+ `---+name: Alpha+slug: alpha+type: system+sources:+ - path: src/a.ts+ hash: abc123+links:+ - to: beta+ relation: influences+ description: Affects beta somehow.+ - to: gamma+ relation: uses+---+<!-- context:generated:start -->+## Summary+Alpha coordinates the whole show.++## Related+- uses [[beta]]+<!-- context:generated:end -->+## Notes+_preserved_+`,+ );+ writeFileSync(+ join(dir, "beta.md"),+ `---+name: Beta+slug: beta+type: concept+sources: []+links: []+---+<!-- context:generated:start -->+## Summary+Beta holds shared state.+<!-- context:generated:end -->+`,+ );+ // Invalid YAML frontmatter — must be skipped, not fatal.+ writeFileSync(join(dir, "broken.md"), `---\nname: [unclosed\n---\nbody\n`);+ writeFileSync(join(dir, "manifest.json"), "{}\n");+ return dir;+}++test("assembleContextGraph builds nodes and edges from frontmatter", () => {+ const dir = makeContextDir();+ try {+ const g = assembleContextGraph(dir);++ assert.equal(g.nodes.length, 2);+ assert.deepEqual(g.nodes.map((n) => n.id).sort(), ["alpha", "beta"]);++ const alpha = g.nodes.find((n) => n.id === "alpha")!;+ assert.equal(alpha.name, "Alpha");+ assert.equal(alpha.type, "system");+ assert.deepEqual(alpha.sources, ["src/a.ts"]);+ assert.equal(alpha.summary, "Alpha coordinates the whole show.");++ // influences → configures; dangling gamma edge dropped+ assert.equal(g.edges.length, 1);+ assert.deepEqual(g.edges[0], {+ source: "alpha",+ target: "beta",+ relation: "configures",+ description: "Affects beta somehow.",+ });++ assert.equal(g.meta.nodeCount, 2);+ assert.equal(g.meta.edgeCount, 1);+ assert.equal(g.meta.droppedEdges, 1);+ assert.equal(g.meta.skippedFiles, 1);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test("normalizeRelation maps vague verbs to the closed vocabulary", () => {+ assert.equal(normalizeRelation("influences"), "configures");+ assert.equal(normalizeRelation("supports"), "validates");+ assert.equal(normalizeRelation("defines"), "validates");+ assert.equal(normalizeRelation("measures"), "validates");+ // members of the vocabulary pass through untouched+ for (const rel of ["part_of", "uses", "depends_on", "produces", "configures", "validates", "implements"]) {+ assert.equal(normalizeRelation(rel), rel);+ }+ // unknown verbs are kept verbatim (viewer renders them as their own chip)+ assert.equal(normalizeRelation("orchestrates"), "orchestrates");+});