> 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-session05-read-hook-route-shell-project-gallery/spec.md).

# Session Specification

**Session ID**: `phase26-session05-read-hook-route-shell-project-gallery` **Phase**: 26 - Knowledge Graph Shared Brain Port **Status**: Not Started **Created**: 2026-06-09

***

## 1. Session Overview

This session assembles the first operator-facing Knowledge Graph surface for AI OS. Sessions 01-04 already provided the typed graph contracts, demo and seed data, loopback read bridge, admin bridge, and reusable 3D graph renderer. Session 05 wires those pieces into a read hook, thin TanStack route, dedicated page adapter, visual hero, project gallery, 3D graph panel, side rail, and sidebar navigation entry.

The implementation keeps the AI OS architecture authoritative. The upstream Claude OS route remains a behavioral reference, but the AI OS route stays thin, the presentation logic moves into modular components under `src/components/knowledge-graph/`, and runtime reads go through a typed hook backed by TanStack Query and existing parser functions.

The session intentionally stops before ingest controls and grounded Hermes chat. Session 06 owns ingest UI, connect prompt, and starter chips. Session 07 owns Hermes chat grounding. Session 05 only exposes Hermes status context from existing hook data so the page can compile and display route-level readiness without adding new write paths.

***

## 2. Objectives

1. Add a typed Knowledge Graph read hook that polls the registry every 8 seconds, loads the active graph, computes derived god nodes and savings, and falls back to bundled demo or seed data for empty, offline, or failed reads.
2. Add `/knowledge-graph` as a thin TanStack route with a dedicated page adapter and route metadata, leaving `src/routeTree.gen.ts` to normal route generation.
3. Build the MVP page surface: wired hero header using the thinker asset and KG animation CSS, scrollable project gallery, Session 04 renderer mount, side rail stats, confidence, important files, savings, and selected-node details.
4. Add the sidebar "Knowledge Graph" navigation entry with the `Waypoints` icon and focused hook, component, route, and route-tree tests.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase26-session01-graph-data-contracts-seed-fixtures` - Provides typed graph contracts, demo fixtures, seed graph, registry, god-node helpers, and savings helpers.
* [x] `phase26-session02-graph-read-bridge-registry-endpoints` - Provides loopback-only `/__graphify_list` and `/__graphify_graph` endpoints with path confinement and bundled fallback.
* [x] `phase26-session03-graph-ingest-removal-admin-bridge` - Provides admin bridge context and shared Knowledge Graph query keys used by list invalidation.
* [x] `phase26-session04-reusable-3d-code-graph-renderer` - Provides the reusable lazy 3D renderer, projection helpers, loader, legend, density toggle, and selected-node callback.

### Required Tools/Knowledge

* Bun 1.3.14, React 19, TypeScript, TanStack Router, TanStack Query, Tailwind CSS 4, Vitest, Testing Library.
* Existing patterns in `src/hooks/use-hermes.ts`, `src/hooks/use-knowledge-graph-admin.ts`, `src/routes/agents.claude-code.tsx`, and `src/components/app-sidebar.tsx`.
* Claude OS v2.4 reference route, sidebar change, KG CSS, and thinker asset under `/home/aiwithapex/projects/claudeos/claude-os-v2.4/`.

### Environment Requirements

* Local dev/test environment can run `bun run test` and route generation through normal Vite/TanStack tooling.
* `graphify` is optional; the route must remain useful with bundled seed or demo data when live graph reads are unavailable.
* Do not hand-edit `src/routeTree.gen.ts`; add the route file and let dev/build tooling regenerate it.

***

## 4. Scope

### In Scope (MVP)

* Operator can open `/knowledge-graph` and see a real page backed by the read bridge or bundled fallback - implement thin route plus page adapter.
* Operator can see live registry entries, switch projects, and keep the registry fresh every 8 seconds - implement typed hook state and project selection.
* Operator can inspect a selected graph through the Session 04 renderer - mount `KnowledgeGraph3D` and preserve loading, empty, error, offline, demo, and selected-node states.
* Operator can scan project stats, confidence mix, important files, savings, provenance, and selected-node source information - implement side rail and gallery components.
* Operator can identify the surface in navigation - add the sidebar entry with `Waypoints` and route tests.
* Operator sees the dormant KG hero as a real wired header - add the thinker WebP asset, KG CSS, reduced-motion behavior, and accessible visual treatment.

### Out of Scope (Deferred)

* Ingest UI, remove controls, connect prompt, and starter chips - *Reason: Session 06 owns mutating/admin UI and prompt safety.*
* Hermes chat grounding, graph toolsets, yolo forwarding, and graphify skill integration - *Reason: Session 07 owns chat behavior and must preserve the existing admin gate.*
* Homepage Knowledge Graph section, Shared Brain setup scripts, dashboard ingest scripts, and Hermes OAuth-provider setup fix - *Reason: Session 08 owns homepage and script parity.*
* Final docs, release validation, Playwright parity sign-off, and full security closeout - *Reason: Session 09 owns phase release hardening.*

***

## 5. Technical Approach

### Architecture

Add `useKnowledgeGraph` as the single read projection for the page. The hook uses TanStack Query for `/__graphify_list` and `/__graphify_graph?id=...`, applies existing parsers from `src/lib/knowledge-graph-types.ts`, reuses `KNOWLEDGE_GRAPH_QUERY_KEYS` from the admin hook, and uses `useBrowserOnlineState` to expose offline state without issuing requests. The hook owns active project state, default selection, derived graph metadata, god nodes, token savings estimate, selected node state, and Hermes status from `useHermes`.

Add `src/routes/knowledge-graph.tsx` as a thin route that imports `KnowledgeGraphPage`. The page adapter composes reusable components under `src/components/knowledge-graph/`: hero header, project gallery, graph panel, and side rail. The route tree is regenerated by normal tooling. Tests assert the route exists after generation rather than manually editing generated code.

The visual surface should be dense and operational, not a landing page. The hero uses the upstream KG animation idea plus `thinker.webp` as a functional status header, with reduced-motion fallbacks and no dead CSS. The main 3D scene uses the Session 04 renderer and loader, preserving lazy imports and cleanup-first lifecycle behavior.

### Design Patterns

* Thin route plus dedicated page adapter: Keeps TanStack route files minimal and follows the P23 route pattern.
* Hook-layer polling: Centralizes registry and graph reads in one testable hook instead of component-local timers.
* Typed degradation over throws: Converts empty, offline, error, and demo states into explicit view data so the page stays useful without `graphify`.
* Lazy 3D renderer boundary: Reuses Session 04 renderer and loader so the vendor chunk stays deferred.
* Accessibility-first interactive controls: Gallery cards, density controls, and selected-node affordances need labels, focus states, and keyboard support.

### Technology Stack

* React 19 and TypeScript.
* TanStack Router and TanStack Query.
* Tailwind CSS 4 and existing app shell/sidebar patterns.
* `react-force-graph-3d` and `three` through the existing Session 04 lazy renderer.
* Vitest and Testing Library for hook, component, route, and route-tree coverage.

***

## 6. Deliverables

### Files to Create

| File                                                                     | Purpose                                                                                                      | Est. Lines |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ---------- |
| `src/hooks/use-knowledge-graph.ts`                                       | Typed read hook for registry polling, active graph loading, fallback state, derived stats, and Hermes status | \~260      |
| `src/hooks/__tests__/use-knowledge-graph.test.tsx`                       | Hook tests for loaded, empty, offline, error fallback, selection, polling, and Hermes status                 | \~240      |
| `src/routes/knowledge-graph.tsx`                                         | Thin TanStack route and route head metadata                                                                  | \~25       |
| `src/components/knowledge-graph/knowledge-graph-page.tsx`                | Page adapter that composes hero, gallery, graph panel, and side rail                                         | \~170      |
| `src/components/knowledge-graph/knowledge-graph-hero.tsx`                | Wired hero header using KG CSS classes and thinker asset                                                     | \~120      |
| `src/components/knowledge-graph/knowledge-graph-project-gallery.tsx`     | Scrollable registry gallery with active selection and explicit empty/error states                            | \~170      |
| `src/components/knowledge-graph/knowledge-graph-panel.tsx`               | Renderer mount, loading/empty/error/offline shells, and selected-node wiring                                 | \~150      |
| `src/components/knowledge-graph/knowledge-graph-side-rail.tsx`           | Stats, confidence, important files, savings, provenance, and selected-node details                           | \~190      |
| `src/components/knowledge-graph/__tests__/knowledge-graph-page.test.tsx` | Component tests for page states, gallery selection, side rail, and renderer mock wiring                      | \~220      |
| `src/assets/hermes-art/knowledge-graph/thinker.webp`                     | Committed hero asset from upstream reference after size policy check                                         | Binary     |

### Files to Modify

| File                                                                                      | Changes                                                        | Est. Lines |
| ----------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ---------- |
| `src/components/app-sidebar.tsx`                                                          | Add `Waypoints` import and "Knowledge Graph" nav entry         | \~8        |
| `src/routes/__tests__/route-tree.test.ts`                                                 | Add `/knowledge-graph` route-tree expectation after generation | \~4        |
| `src/routes/__tests__/agents.test.tsx` or `src/routes/__tests__/knowledge-graph.test.tsx` | Add route render/head coverage for the new route               | \~120      |
| `src/styles.css`                                                                          | Add scoped `kg-*` hero animations and reduced-motion rules     | \~80       |
| `src/routeTree.gen.ts`                                                                    | Regenerated by normal TanStack tooling only                    | Generated  |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `/knowledge-graph` renders the hero, project gallery, 3D panel, and side rail from seed or live data.
* [ ] The registry query polls `/__graphify_list` every 8 seconds when browser, online, and not demo.
* [ ] Active project selection loads `/__graphify_graph?id=...` and resets safely when the registry changes.
* [ ] Empty, offline, fetch-error, parser-error, and demo states remain explicit and render usable fallback UI.
* [ ] The hero header uses `thinker.webp` and active KG CSS classes rather than unused copied styles.
* [ ] Sidebar navigation includes "Knowledge Graph" with the `Waypoints` icon and routes to `/knowledge-graph`.

### Testing Requirements

* [ ] Hook tests cover loaded, empty, offline, failed fetch, malformed payload fallback, active project selection, and polling interval options.
* [ ] Component tests cover page loaded/demo/empty/offline/error states, gallery selection, selected-node side rail, and renderer mock callbacks.
* [ ] Route tests cover route head metadata and route render.
* [ ] Route-tree test covers generated `/knowledge-graph` registration.

### Non-Functional Requirements

* [ ] 3D renderer remains lazy-loaded and no new eager `react-force-graph-3d` import is introduced in route/page code.
* [ ] Reduced-motion users do not get looping hero or constellation animations.
* [ ] Browser-visible output does not expose private local paths beyond already sanitized graph contract fields.
* [ ] Hero asset follows media policy and remains under the committed asset size limit.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] `bun run test -- src/hooks/__tests__/use-knowledge-graph.test.tsx src/components/knowledge-graph/__tests__/knowledge-graph-page.test.tsx src/routes/__tests__/route-tree.test.ts` passes.
* [ ] Relevant broader checks are ready for the validate workflow step.

***

## 8. Implementation Notes

### Key Considerations

* Keep the route file minimal and put page behavior in `KnowledgeGraphPage`.
* Reuse existing parser functions instead of ad hoc shape checks in the hook.
* Reuse the Session 04 renderer and loader; do not import `react-force-graph-3d` directly from page or route code.
* Copy `thinker.webp` from the upstream reference and check asset size before committing.
* Do not add mutating ingest/remove UI in this session even though the admin bridge exists.
* Do not hand-edit `src/routeTree.gen.ts`; generate it through normal tooling.

### Potential Challenges

* Active graph race with registry refresh: Reconcile selected id against the latest registry and fall back to the first entry or demo entry.
* Malformed live payload: Catch parser errors and surface a typed error/fallback state instead of throwing from render.
* Offline browser state: Avoid issuing live fetches while offline and expose a stable offline view.
* 3D chunk budget: Keep renderer behind the existing lazy boundary and avoid additional eager imports.
* Asset sizing: If the upstream asset exceeds policy, optimize or resize it before adding.

### Relevant Considerations

* \[P01] **3D vendor chunk budget**: Keep graph rendering lazy and avoid new eager imports of `react-force-graph-3d` or `three`.
* \[P04] **Hermes bridge guardrails must stay intact**: This session is read-only; Hermes status is presentation data and does not add write endpoints.
* \[P18] **Lazy imports plus cleanup-first effects make 3D UI safe**: Reuse the Session 04 renderer and cleanup behavior.
* \[P23] **Thin route mount + dedicated page adapter**: Follow the established route file and page adapter split.
* \[P23] **Do not hand-edit generated route trees**: Generate `src/routeTree.gen.ts` through tooling only.
* \[P24] **Fail-closed bridges need boundary validation**: Hook reads must consume parsed bridge responses and surface explicit failure states.
* \[P25] **Writes stay on the shared admin contract**: Do not introduce component fetches for graph ingest/remove in Session 05.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* Registry and graph fetches can fail, return malformed data, or go offline while the page is open.
* Project selection can become stale when polling prunes or reorders the registry.
* Interactive gallery and graph selection controls can become inaccessible or lose state on route revisit.
* Large or lazy 3D rendering can regress performance if imported outside the renderer boundary.

***

## 9. Testing Strategy

### Unit Tests

* Test `useKnowledgeGraph` with mocked fetch responses for successful registry/graph, empty registry, offline browser, malformed registry, malformed graph, failed graph load, selected project changes, and polling settings.
* Test derived data for god nodes, savings, important files, provenance labels, and selected node reset.

### Integration Tests

* Render `KnowledgeGraphPage` with a mocked hook and mocked `KnowledgeGraph3D` to verify hero, gallery, panel, side rail, state shells, and selected-node callback behavior.
* Render the route module and assert route metadata through the existing route test helpers.

### Manual Testing

* Run the dev app, open `/knowledge-graph`, confirm the seed graph loads with gallery and side rail.
* Toggle offline in browser dev tools or mock failed endpoints and confirm explicit offline/error fallback UI.
* Navigate from the sidebar entry and confirm active route styling.

### Edge Cases

* Registry returns no entries.
* Registry returns entries but active graph fetch fails.
* Parser rejects malformed list or graph payload.
* Browser is offline before first load or becomes offline after successful load.
* Registry polling removes the selected project id.
* User re-enters the page after leaving it.
* Long labels and source paths render without overflowing cards or side rail rows.

***

## 10. Dependencies

### External Libraries

* `@tanstack/react-query`: existing runtime query layer.
* `@tanstack/react-router`: existing route layer and route-tree generation.
* `lucide-react`: existing icon library; use `Waypoints` for the sidebar entry.
* `react-force-graph-3d` and `three`: existing lazy-renderer dependencies from Session 04.

### Other Sessions

* **Depends on**: Sessions 01, 02, 03, and 04.
* **Depended by**: Session 06 (ingest UI host), Session 07 (Hermes chat grounding host), Session 08 (homepage surface references), Session 09 (validation and release).

***

## 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-session05-read-hook-route-shell-project-gallery/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.
