Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

Add graft viz implementation plan

Shrish Dwivedid765336cb350
diff --git a/docs/superpowers/plans/2026-07-15-graft-viz.md b/docs/superpowers/plans/2026-07-15-graft-viz.md
new file mode 100644
index 00000000..de66746b
--- /dev/null
+++ b/docs/superpowers/plans/2026-07-15-graft-viz.md
@@ -0,0 +1,110 @@
+# graft viz Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Ship `graft viz` — a local interactive visualizer for both Graft graphs, with semantic edges per the approved spec.
+
+**Architecture:** A zero-runtime-dep `node:http` server (`src/viz/serve.ts`) exposes the assembled context graph (`src/viz/assemble.ts`), the raw `graph.json`, and an SSE reload channel; a prebuilt vanilla-TS viewer (`viewer/` → `dist/viewer/` via esbuild) renders tabs (Context/Code/Outline), a d3-force graph with the semantic edge grammar, detail panel, search, and themes. Spec: `docs/superpowers/specs/2026-07-15-graft-viz-design.md`. Visual reference of record: the approved mockup (artifact "graft viz — design & mockup").
+
+**Tech Stack:** TypeScript ESM (Node ≥ 20), commander, gray-matter (already deps); new devDeps: `esbuild`, `d3-force` (+ `@types/d3-force`) — bundled into the viewer, never a runtime dep.
+
+## Global Constraints
+
+- Node >= 20, ESM (`"type": "module"`), strict TS — match existing `tsconfig.json`
+- No new **runtime** dependencies (server uses `node:http`, `node:fs`, `node:path`, `node:child_process` only)
+- Relation enum (engine + viewer normalization): `part_of, uses, depends_on, produces, configures, validates, implements` — legacy mapping `influences→configures`; `supports|defines|measures→validates`
+- Tests: node built-in runner via `npm test` (`node --import tsx --test test/*.test.ts`)
+- Byte-stable outputs where applicable; no timestamps in generated JSON
+- Commit after each task; branch `feat/graft-viz`
+
+---
+
+### Task 1: Graph assembly (`assemble.ts`) — TDD
+
+**Files:**
+- Create: `src/viz/assemble.ts`
+- Create: `test/viz-assemble.test.ts`
+- Create: `test/fixtures/viz-context/{alpha.md, beta.md, broken.md, manifest.json}`
+
+**Interfaces:**
+- Produces: `assembleContextGraph(contextDir: string): VizGraph` where
+ `VizGraph = { meta: { nodeCount: number; edgeCount: number; skippedFiles: number; droppedEdges: number }, nodes: VizNode[], edges: VizEdge[] }`,
+ `VizNode = { id: string; name: string; type: string; summary: string; sources: string[] }`,
+ `VizEdge = { source: string; target: string; relation: string; description?: string }`
+- Also exports `NORMALIZE_RELATION: Record<string,string>` and `normalizeRelation(rel: string): string`
+
+- [ ] **Step 1: Write fixtures + failing tests** — fixture `alpha.md` links to `beta` (`relation: influences`) and to missing `gamma`; `broken.md` has invalid YAML. Tests assert: 2 nodes; 1 edge normalized to `configures`; `droppedEdges === 1`; `skippedFiles === 1`; summary extracted from generated block.
+- [ ] **Step 2: Run** `npm test -- test/viz-assemble.test.ts` → FAIL (module not found)
+- [ ] **Step 3: Implement** — read `*.md` (excluding non-node files) with gray-matter; node id = slug (fallback: filename); summary = body text inside `<!-- context:generated:start/end -->` stripped of `## Summary`/`## Related` headings, first 500 chars; edges from `links[]`; drop dangling; normalize relations.
+- [ ] **Step 4: Run tests** → PASS
+- [ ] **Step 5: Commit** `feat(viz): assemble context graph JSON from .context markdown`
+
+### Task 2: Server (`serve.ts`) — TDD
+
+**Files:**
+- Create: `src/viz/serve.ts`
+- Create: `test/viz-serve.test.ts`
+
+**Interfaces:**
+- Consumes: `assembleContextGraph`
+- Produces: `startVizServer(opts: { contextDir: string; viewerDir: string; port: number; repoName: string }): Promise<{ url: string; close(): Promise<void> }>` — tries `port..port+10`; routes: `GET /` `/app.js` `/style.css` (static from viewerDir), `GET /api/context-graph` (assembled JSON + `repoName` in meta), `GET /api/code-graph` (`graph.json` passthrough if `meta.version === 1`, else 404 `{error}`), `GET /events` (SSE, `fs.watch` on contextDir debounced 300 ms → `data: change\n\n`)
+
+- [ ] **Step 1: Failing tests** — start on port 0-ish random base against fixtures dir + temp viewer dir with stub `index.html`; assert context-graph shape, code-graph 404 without file and 200 with valid fixture `graph.json`, port fallback (occupy base port first), SSE emits on file touch.
+- [ ] **Step 2: Run** → FAIL
+- [ ] **Step 3: Implement** (no runtime deps; content-types html/js/css/json; SSE keeps sockets, closes cleanly)
+- [ ] **Step 4: Run tests** → PASS
+- [ ] **Step 5: Commit** `feat(viz): local http server with SSE live reload`
+
+### Task 3: Viewer
+
+**Files:**
+- Create: `viewer/index.html`, `viewer/style.css`, `viewer/main.ts`, `viewer/graph.ts`, `viewer/tree.ts`, `viewer/detail.ts`, `viewer/data.ts`
+- Create: `scripts/build-viewer.mjs` (esbuild: bundle `main.ts` → `dist/viewer/app.js`, copy html/css)
+- Modify: `package.json` (devDeps `esbuild`, `d3-force`, `@types/d3-force`; `"build": "tsc -p tsconfig.json && node scripts/build-viewer.mjs"`; add `dist/viewer` to published files if a `files` field exists)
+
+**Interfaces:**
+- Consumes: `/api/context-graph`, `/api/code-graph`, `/events` from Task 2
+- Produces: `dist/viewer/{index.html, app.js, style.css}`
+
+- [ ] **Step 1: Port the approved mockup** (visual reference of record; local working copy at the session scratchpad `graft-viz-design.html`) into modules, replacing the hand-rolled sim with `d3-force` (`forceSimulation`, `forceManyBody`, `forceLink` with per-family `distance` [part_of 85 / uses-family 145 / contract 150 / association 185], `forceCenter`, `forceCollide`) and persistent SVG elements (create once, update `transform`/`d` per tick — no rebuild). Keep verbatim: token palette & both themes, tabs, semantic edge grammar (form per family, chevron/hollow/filled markers), verb chips with counts + hints, focus mode (amber out / teal in + labels only on focused edges), detail panel (Depends on / Depended on by), outline tree, search (Enter zooms), theme toggle, zoom/pan/drag. Add: SSE refetch that preserves positions by node id; empty states ("run `graft init`" / "run `graft graph`"); `references` chip hint "mentioned but never called"; inferred-confidence edges render dashed.
+- [ ] **Step 2: Build** `node scripts/build-viewer.mjs` → `dist/viewer/*` exists, `app.js` < 150 kB
+- [ ] **Step 3: Manual smoke** — serve fixtures via Task 2 server, check tabs/selection/chips in browser
+- [ ] **Step 4: Commit** `feat(viz): viewer app (semantic edges, focus mode, outline, themes)`
+
+### Task 4: CLI wiring
+
+**Files:**
+- Modify: `src/cli.ts` (add `viz` command), `src/index.ts` (export viz types)
+
+**Interfaces:**
+- Consumes: `startVizServer`
+- Produces: `graft viz [dir] --port <n> --no-open`; viewerDir resolved relative to compiled module (`new URL("../viewer/", import.meta.url)` from `dist/`); browser open via `open`/`xdg-open`/`start` spawn, skipped with `--no-open`; exit 1 + guidance when context dir missing
+
+- [ ] **Step 1: Implement command** (commander, matching existing `init`/`graph`/`check` style and `--dir` global)
+- [ ] **Step 2: Verify** `npm run cli -- viz . --no-open` prints URL; curl endpoints respond
+- [ ] **Step 3: Commit** `feat(cli): graft viz command`
+
+### Task 5: Engine — closed relation enum
+
+**Files:**
+- Modify: `src/ai/synthesize.ts` (tool schema `relation` → `enum: ["part_of","uses","depends_on","produces","configures","validates","implements"]`; prompt text lists the verbs with their reviewer-questions)
+- Test: extend `test/viz-assemble.test.ts` with normalization table cases
+
+- [ ] **Step 1: Failing test** for `normalizeRelation` full table (influences→configures; supports/defines/measures→validates; known verbs pass through)
+- [ ] **Step 2: Run** → FAIL, **Step 3: implement enum + prompt edit**, **Step 4: tests PASS**
+- [ ] **Step 5: Commit** `feat(engine): closed relation vocabulary for synthesized links`
+
+### Task 6: End-to-end + docs
+
+**Files:**
+- Modify: `README.md` (viz section: command, screenshot placeholder-free description, verb vocabulary table)
+
+- [ ] **Step 1:** `npm run build && npm test` → all green
+- [ ] **Step 2:** `node dist/cli.js viz . --no-open` against this repo's real `.context/`; browser-verify against the design reference (chips: part of 2 · uses 2 · configures 1 · produces 1 · validates 2 after normalization)
+- [ ] **Step 3:** Commit `docs: README section for graft viz`
+
+## Self-Review
+
+- Spec coverage: tabs/delivery/interactions (T3–T4), semantic edges + vocabulary (T1, T3, T5), scale items 3–5 (T3; 1–2 explicitly v2 in spec), error handling (T1, T2, T4), testing (T1, T2, T6). ✔
+- No placeholders: viewer task consumes an existing concrete source file (the approved mockup) rather than pseudo-code. ✔
+- Type consistency: `VizGraph/VizNode/VizEdge` defined once in Task 1 and consumed by name in Tasks 2–3. ✔