> For the complete documentation index, see [llms.txt](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase26-session04-reusable-3d-code-graph-renderer/spec.md).

# Session Specification

**Session ID**: `phase26-session04-reusable-3d-code-graph-renderer` **Phase**: 26 - Knowledge Graph Shared Brain Port **Status**: Complete **Created**: 2026-06-09 **Completed**: 2026-06-09

***

## 1. Session Overview

This session builds the reusable 3D Knowledge Graph renderer that later powers the `/knowledge-graph` route and the homepage preview. It ports the behavior of the upstream `GraphifyGraph3D` component into AI OS-native file structure, contracts, lazy loading, and test patterns instead of copying the upstream route shape wholesale.

The work depends on the completed graph contracts, seed fixtures, read bridge, registry endpoints, and admin ingest/removal bridge from Sessions 01-03. The renderer consumes the typed `KnowledgeGraph` contract and exposes a stable component API for Session 05 to mount in the route shell.

The implementation must keep the existing 3D vendor budget safe by loading `react-force-graph-3d`, `three`, and bloom code lazily, mirroring the cleanup discipline from `memory-graph-3d.tsx`, and proving teardown behavior with component tests that mock vendor modules.

***

## 2. Objectives

1. Create a typed reusable `KnowledgeGraph3D` component with the required `embedded`, `maxNodes`, `onSelect`, `onMeta`, and `pinnedId` props.
2. Implement graph projection behavior: degree calculation, max-node capping, Full/Core density, god-node marking, adjacency lighting, and community clustering.
3. Add the lazy scene lifecycle: dynamic 3D vendor imports, resize observer, fog, lights, starfield, bloom, auto-orbit, fly-to, camera fit, and cleanup.
4. Provide the loader shell, controls, legend, capping notice, and focused component tests needed for Session 05 to safely reuse the renderer.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase26-session01-graph-data-contracts-seed-fixtures` - Provides Knowledge Graph contracts, seed fixtures, parsers, and demo data.
* [x] `phase26-session02-graph-read-bridge-registry-endpoints` - Provides registry and graph read endpoints that return the renderer input shape.
* [x] `phase26-session03-graph-ingest-removal-admin-bridge` - Provides live ingest and removal admin bridge behavior for future non-seed graphs.

### Required Tools/Knowledge

* Existing 3D renderer lifecycle in `src/components/memory-graph-3d.tsx`.
* Existing force-graph type helpers in `src/lib/graph-types.ts`.
* Typed Knowledge Graph contracts in `src/lib/knowledge-graph-types.ts`.
* Upstream reference file `/home/aiwithapex/projects/claudeos/claude-os-v2.4/src/components/graphify-graph-3d.tsx`.
* Vitest and Testing Library component test patterns.

### Environment Requirements

* Bun 1.3.14 and project dependencies installed.
* Browser globals such as `ResizeObserver` and `requestAnimationFrame` mocked in component tests where needed.
* No live graphify binary is required for this renderer session.

***

## 4. Scope

### In Scope (MVP)

* A route/page can render a reusable 3D Knowledge Graph component - implement `src/components/knowledge-graph/knowledge-graph-3d.tsx` with contract-aligned props and no route-specific state.
* A route/page can show a stable loading surface while the heavy graph vendor chunk loads - add `src/components/knowledge-graph/knowledge-graph-loader.tsx` mirroring the Mnemosyne loader pattern.
* A route/page can keep large graphs readable - implement degree ranking, max-node capping, Full/Core density, capped-node notice, and on-meta summary.
* A user can inspect graph relationships visually - implement god nodes, community colors, adjacency hover/pinned lighting, extracted-link particles, fly-to, camera fit, and legend.
* The browser stays responsive and testable - lazy-load 3D vendor modules, clean up resize observers and animation frames, and add mocked vendor tests.

### Out of Scope (Deferred)

* `/knowledge-graph` route, read hook, project gallery, side rail, and hero header - *Reason: Session 05 owns route assembly and data loading.*
* Ingest UI, connect prompt, and starter chips - *Reason: Session 06 owns admin controls and Hermes prompt affordances.*
* Hermes chat grounding and graph toolset - *Reason: Session 07 owns chat grounding behavior.*
* Homepage preview and Shared Brain scripts - *Reason: Session 08 owns homepage and scripts.*

***

## 5. Technical Approach

### Architecture

Create a dedicated `src/components/knowledge-graph/` directory. The renderer will accept an already parsed `KnowledgeGraph` value and project it into a force-graph view model with display fields, degree counts, community colors, god-node flags, and filtered links. It will not fetch data, mutate registry state, call bridge endpoints, or know about route selection beyond the `pinnedId` prop.

The component will mirror `MemoryGraph3D` for lazy vendor imports, resize measurement, embedded-mode control restrictions, canvas scroll behavior, starfield/bloom setup, and cleanup-first effects. Knowledge Graph-specific logic stays inside the renderer or small local helpers so Session 05 can mount the component without duplicating projection logic.

Tests will mock `react-force-graph-3d`, `three`, and the bloom pass so the component can verify prop-driven behavior, controls, capping, meta callbacks, selection callbacks, and cleanup without depending on WebGL.

### Design Patterns

* Props-only reusable component: Keeps route state and data fetching out of the renderer so Session 05 can compose it safely.
* Lazy import boundary: Preserves the 3D vendor chunk budget and keeps SSR/build behavior aligned with the existing Mnemosyne renderer.
* Cleanup-first effects: Resize observers, animation frames, and scene enhancements must be cancelled or scoped on unmount.
* Pure projection before render: Degree, cap, density, adjacency, and god-node calculations should be deterministic and easy to test through behavior.
* Accessible operational controls: Full/Core and Pause/Play controls use real buttons with labels, focus states, and stable dimensions.

### Technology Stack

* React 19 and TypeScript 6.
* Tailwind CSS 4 and existing dashboard component conventions.
* `react-force-graph-3d` `^1.29.1`, loaded dynamically.
* `three` `^0.184.0`, loaded dynamically with the bloom pass.
* Vitest 4 and Testing Library 16.

***

## 6. Deliverables

### Files to Create

| File                                                                       | Purpose                                                                                        | Est. Lines |
| -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------- |
| `src/components/knowledge-graph/knowledge-graph-3d.tsx`                    | Reusable lazy 3D renderer with projection, scene lifecycle, controls, legend, and callbacks.   | \~520      |
| `src/components/knowledge-graph/knowledge-graph-loader.tsx`                | Loader/Suspense shell matching the Knowledge Graph visual language.                            | \~180      |
| `src/components/knowledge-graph/__tests__/knowledge-graph-3d.test.tsx`     | Component tests with mocked force-graph, three, bloom, callbacks, caps, controls, and cleanup. | \~280      |
| `src/components/knowledge-graph/__tests__/knowledge-graph-loader.test.tsx` | Loader smoke and reduced-motion-safe rendering tests.                                          | \~80       |

### Files to Modify

| File                     | Changes                                                                                                                        | Est. Lines |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------ | ---------- |
| `src/lib/graph-types.ts` | Add generic force-graph helper types or endpoint helpers needed by the Knowledge Graph renderer without breaking Memory Graph. | \~30       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Renderer accepts a typed `KnowledgeGraph` and displays contract-aligned nodes and links.
* [ ] God nodes, community clusters, density toggle, capping notice, and legend are visible.
* [ ] `onSelect`, `onMeta`, and `pinnedId` behave per the upstream contract.
* [ ] Lazy imports gate the 3D vendor modules behind the renderer boundary.
* [ ] Resize observer, animation frame, and scene lifecycle cleanup runs on unmount.

### Testing Requirements

* [ ] Component tests cover loading, rendered graph, Full/Core density, capping, callbacks, hover/pinned behavior, and cleanup.
* [ ] Loader tests cover visible status text and stable shell rendering.
* [ ] Targeted test command for the new component tests passes.

### Non-Functional Requirements

* [ ] No new client graph dependency is introduced.
* [ ] Existing 3D vendor chunk budget is protected through lazy imports.
* [ ] Renderer does not fetch, mutate, spawn processes, or access admin bridge paths.
* [ ] Controls are keyboard reachable and screen-reader labeled.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] No hand edits to `src/routeTree.gen.ts`.

***

## 8. Implementation Notes

### Key Considerations

* Use `KnowledgeGraphNode` and `KnowledgeGraphLink` as the browser contract source of truth; normalize force-graph runtime endpoint objects only at the renderer boundary.
* Keep the component API stable for Session 05: `embedded?: boolean`, `maxNodes?: number`, `onSelect?: (node) => void`, `onMeta?: (meta) => void`, and `pinnedId?: string | null`.
* Keep UI dense and operational. This is a dashboard tool surface, not a marketing hero or decorative graph.
* Avoid touching route files or sidebar navigation in this session.

### Potential Challenges

* WebGL vendor testing: Mock vendor modules and assert component behavior through rendered controls and callback payloads.
* Heavy chunk regression: Keep imports inside effects or a lazy boundary and avoid top-level imports from `react-force-graph-3d`, `three`, or bloom.
* Scene cleanup drift: Store animation frame IDs and observer handles locally and cancel them in effect cleanup.
* Force-graph endpoint mutation: Use a shared endpoint normalization helper so string endpoints and runtime node objects both work.

### Relevant Considerations

* \[P01] **3D vendor chunk budget**: The renderer must lazy-load heavy 3D modules and share the existing dependency surface.
* \[P18] **Lazy imports plus cleanup-first effects make 3D UI safe**: Apply the Mnemosyne renderer lifecycle pattern and verify cleanup in tests.
* \[P23] **Thin route mount + dedicated page adapter**: Keep this renderer route-agnostic so Session 05 can mount it from a dedicated page adapter.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Heavy vendor modules accidentally enter the main route chunk.
* Resize observers, animation frames, or scene objects keep running after unmount.
* Large graphs become unreadable or crash-prone without capping and density controls.
* Hover, pinned, and selection states drift out of sync with route-owned state.
* Icon-only controls lack labels or keyboard access.

***

## 9. Testing Strategy

### Unit Tests

* Test graph projection behavior through visible capping notices, meta callback values, density control changes, and legend output.
* Test node click and pinned-id behavior with mocked force-graph callbacks.
* Test helper behavior added to `graph-types.ts` for string and object endpoints.

### Integration Tests

* Render `KnowledgeGraph3D` with the Session 01 seed/demo graph fixture and mocked vendor modules.
* Verify lazy-load fallback appears before the mock graph component resolves.
* Verify unmount disconnects `ResizeObserver` and cancels animation frames.

### Manual Testing

* Mount the component in a local scratch route or Story-like harness during implementation and verify Full/Core, Pause/Play, capping, legend, hover, node click, and pinned fly-to behavior.

### Edge Cases

* Empty graph with zero nodes and links.
* Graph larger than `maxNodes`.
* Links whose source/target are already force-graph runtime node objects.
* Missing optional node fields such as `source_file`, `source_location`, or `norm_label`.
* Reduced-motion preference while auto-orbit is available.

***

## 10. Dependencies

### External Libraries

* `react-force-graph-3d`: `^1.29.1`
* `three`: `^0.184.0`
* `lucide-react`: `^1.16.0`
* `@testing-library/react`: `^16.3.2`
* `vitest`: `^4.1.6`

### Other Sessions

* **Depends on**: `phase26-session01-graph-data-contracts-seed-fixtures`, `phase26-session02-graph-read-bridge-registry-endpoints`, `phase26-session03-graph-ingest-removal-admin-bridge`
* **Depended by**: `phase26-session05-read-hook-route-shell-project-gallery`, `phase26-session08-homepage-surface-shared-brain-scripts-oauth`

***

## Next Steps

Run the implement workflow step to begin AI-led implementation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase26-session04-reusable-3d-code-graph-renderer/spec.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
