> 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-session02-graph-read-bridge-registry-endpoints/spec.md).

# Session Specification

**Session ID**: `phase26-session02-graph-read-bridge-registry-endpoints` **Phase**: 26 - Knowledge Graph Shared Brain Port **Status**: Not Started **Created**: 2026-06-09

***

## 1. Session Overview

This session adds the loopback-only Knowledge Graph read bridge for Phase 26. It registers `/__graphify_list` and `/__graphify_graph?id=` in the Vite dev server through an AI OS-native bridge module under `scripts/lib/`, matching the Hermes bridge registration style instead of copying upstream endpoint logic into `vite.config.ts`.

The bridge makes the checked-in seed registry and graph from Session 01 usable by later route, hook, renderer, ingest, and Hermes grounding work. It reads the registry fresh from disk, self-heals stale local entries, serves graph JSON with path confinement, and falls back to the bundled AI OS seed graph when a safe requested graph artifact is unavailable.

This is the natural next session because Session 01 completed the contracts and seed fixtures, while Sessions 03, 05, 06, and 07 depend on a stable read path for registry listing and graph streaming.

***

## 2. Objectives

1. Add a registered Knowledge Graph dev bridge module with loopback-only GET endpoints.
2. Implement registry listing with graph artifact validation, stale local source pruning, and durable `git:` or empty source retention.
3. Implement confined graph streaming by sanitized id with bundled seed fallback and explicit error mapping for invalid ids and path escapes.
4. Add focused bridge tests covering registration, listing, pruning, streaming, fallback, loopback rejection, and confinement failures.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase26-session01-graph-data-contracts-seed-fixtures` - Provides `src/lib/knowledge-graph-types.ts`, demo fixtures, `src/data/graphs/index.json`, and `src/data/graphs/ai-os.json`.

### Required Tools/Knowledge

* Existing Hermes and OpenClaw bridge registration patterns in `scripts/lib/hermes-dev-bridge.ts`, `scripts/lib/openclaw-dev-bridge.ts`, and `vite.config.ts`.
* Existing script bridge test helpers under `scripts/lib/__tests__/`.
* Upstream v2.4 reference behavior for `/__graphify_list` and `/__graphify_graph?id=`.
* Bun 1.3.14, TypeScript 6.0.3, Vite 8, and Vitest 4.1.6.

### Environment Requirements

* Local filesystem access to `src/data/graphs/`.
* No live `graphify` binary, network access, admin token usage, or browser UI is required for this session.

***

## 4. Scope

### In Scope (MVP)

* AI OS can register Knowledge Graph read endpoints - create `scripts/lib/knowledge-graph-dev-bridge.ts` and wire it into `vite.config.ts` via `configureServer`.
* AI OS can list graph registry entries - implement `GET /__graphify_list` with typed JSON array output, no-store headers, malformed-registry handling, and deterministic ordering.
* AI OS can self-heal stale registry entries - prune entries whose graph artifact is missing or whose local source path no longer exists, while retaining `git:` and empty source entries.
* AI OS can stream graph JSON safely - implement `GET /__graphify_graph?id=` with strict id validation, graph-directory confinement, content headers, stream error handling, and bundled seed fallback for safe missing artifacts.
* AI OS can prove bridge safety - add bridge tests for success paths and rejection paths.

### Out of Scope (Deferred)

* Ingest/removal writes - *Reason: Session 03 owns the admin-gated graphify/git bridge and all mutating behavior.*
* Knowledge Graph route, hook, gallery, and UI consumption - *Reason: Session 05 owns browser read consumption and presentation.*
* 3D renderer - *Reason: Session 04 owns lazy 3D rendering, capping, bloom, density controls, and cleanup.*
* Ingest UI, connect prompt, starter chips, and Hermes grounding - *Reason: Sessions 06 and 07 own those browser and chat behaviors.*

***

## 5. Technical Approach

### Architecture

Add `scripts/lib/knowledge-graph-dev-bridge.ts` as a focused bridge module that exports `registerKnowledgeGraphDevBridge(server, options)`. The module should reuse the bridge conventions already present in Hermes/OpenClaw: explicit request/response types, injected `isLoopback`, optional logger, no-store JSON responses, and unit-testable handler functions.

`vite.config.ts` should import and register the bridge inside the existing dev middleware plugin, passing `server.middlewares`, `isLoopback`, graph directory paths resolved from `__dirname`, and the same structured logger adapter used by the other local bridges.

The bridge owns filesystem path decisions. It should resolve a shared graph directory, registry path, and seed graph path from options with safe defaults. It should treat raw registry `path` or `sourcePath` values as prune metadata only, and it should handle both workspace-relative and absolute `graphPath` values by resolving and confining them to the shared graph directory before any read or deletion attempt.

### Design Patterns

* Bridge module boundary: Keep endpoint code out of `vite.config.ts` and expose handler functions for direct Vitest coverage.
* Fail-closed path confinement: Resolve graph artifacts under one graph directory; reject invalid ids and path escapes explicitly.
* Typed response after raw compatibility pass: Use bridge-local compatibility handling for optional raw registry fields, then return parsed graph registry entries for the list payload.
* Idempotent self-healing: Registry pruning rewrites only when stale local entries are removed and never deletes outside the confined graph directory.
* Bundled seed fallback: Safe missing graph artifacts stream the checked-in AI OS seed graph so later UI work remains useful without live graphify ingest.

### Technology Stack

* TypeScript 6.0.3.
* Bun 1.3.14.
* Vite 8 dev middleware.
* Vitest 4.1.6.
* Node `fs`, `fs/promises`, `path`, and `stream` APIs.

***

## 6. Deliverables

### Files to Create

| File                                                       | Purpose                                                                  | Est. Lines |
| ---------------------------------------------------------- | ------------------------------------------------------------------------ | ---------- |
| `scripts/lib/knowledge-graph-dev-bridge.ts`                | Loopback-only graph registry list and graph stream bridge                | \~380      |
| `scripts/lib/__tests__/knowledge-graph-dev-bridge.test.ts` | Focused bridge tests for success, pruning, fallback, and rejection paths | \~430      |

### Files to Modify

| File             | Changes                                                                          | Est. Lines |
| ---------------- | -------------------------------------------------------------------------------- | ---------- |
| `vite.config.ts` | Import and register `registerKnowledgeGraphDevBridge` with graph directory paths | \~16       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `/__graphify_list` returns a typed registry JSON array from `src/data/graphs/index.json`.
* [ ] `/__graphify_list` prunes stale local entries whose graph artifact or local source path is missing, while retaining `git:` and empty source entries.
* [ ] `/__graphify_graph?id=` rejects invalid ids and path-escape attempts.
* [ ] `/__graphify_graph?id=` streams confined graph JSON and falls back to `src/data/graphs/ai-os.json` for safe missing graph artifacts.
* [ ] Vite dev middleware registers both graph read endpoints alongside existing Hermes/OpenClaw/Trend Finder bridges.

### Testing Requirements

* [ ] Unit tests written and passing for endpoint registration and response headers.
* [ ] Unit tests written and passing for registry read and stale-entry pruning.
* [ ] Unit tests written and passing for graph stream success and seed fallback.
* [ ] Unit tests written and passing for non-loopback, method, invalid-id, and path-confinement rejection.
* [ ] Focused `bun run test -- scripts/lib/__tests__/knowledge-graph-dev-bridge.test.ts` completed.
* [ ] `bun run typecheck:scripts` completed or a documented blocker recorded.

### Non-Functional Requirements

* [ ] No write-capable, token-gated, shell, git, or graphify spawn behavior is introduced.
* [ ] Browser-visible errors remain bounded and do not expose private filesystem paths.
* [ ] Registry pruning is idempotent and preserves durable git/empty source entries.
* [ ] No new runtime dependency is introduced.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.

***

## 8. Implementation Notes

### Key Considerations

* Preserve upstream endpoint names (`/__graphify_list` and `/__graphify_graph`) for compatibility, but keep code shape AI OS-native.
* Success payload for `/__graphify_list` should remain a JSON array so copied upstream read consumers and future route work can consume it simply.
* Use explicit error responses for bridge failures: `{ "ok": false, "code": "...", "error": "..." }`.
* Do not require `x-claude-os-token` for this read bridge unless implementation uncovers an established local pattern that marks graph reads sensitive; the session stub requires loopback-only gating.
* Keep raw local source paths out of returned payloads unless they are already part of the registry contract and safe for browser use.

### Potential Challenges

* Registry compatibility: Future Session 03 writes may add absolute `graphPath` and source path fields; bridge path helpers should tolerate those raw fields while preserving the current typed browser contract.
* Streaming tests: Test response doubles need to wait for stream completion, as existing asset bridge tests do.
* Fallback semantics: Invalid ids and path escapes must be rejected; seed fallback applies only after an id is syntactically safe and the requested graph artifact cannot be served.

### Relevant Considerations

* \[P04] **Hermes bridge guardrails must stay intact**: Reuse the loopback-only bridge pattern and keep read behavior separate from admin writes.
* \[P24] **Fail-closed bridges need boundary validation**: Validate ids, paths, methods, and malformed registry data at the bridge boundary.
* \[P25] **Writes stay on the shared admin contract**: Do not add ingest/remove, shell, git, workspace-write, or admin behavior in this read session.
* \[P02] **Typed degradation over throws**: A missing live graph should degrade to the bundled seed fallback; malformed or unsafe inputs should fail explicitly.
* \[P00] **Stack conventions**: Keep the implementation TypeScript-first, Bun and Vite compatible, and covered by Vitest.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* A malformed id or graph path escaping the shared graph directory.
* Registry pruning deleting durable entries or files outside the graph directory.
* Missing live graph artifacts breaking the later UI instead of degrading to the bundled seed graph.

***

## 9. Testing Strategy

### Unit Tests

* Capture bridge registrations and assert both graph endpoints are registered.
* Verify non-GET methods, non-loopback requests, invalid ids, and path escapes return bounded JSON errors.
* Create a temp graph directory and registry, then verify `/__graphify_list` reads valid entries with no-store headers.
* Verify stale local entries are pruned when graph files or local source paths are missing, while `git:` and empty source entries remain.
* Verify `/__graphify_graph?id=` streams a confined graph file with JSON headers.
* Verify a safe missing graph id streams the bundled seed graph fallback.
* Verify malformed registry JSON produces a bounded failure or empty typed list, depending on the implemented compatibility choice, without leaking local paths.

### Integration Tests

* Vite registration is covered by direct `vite.config.ts` import/typecheck and the bridge registration test; no browser e2e test is required in this session.

### Manual Testing

* Inspect the new bridge module for shell/git/admin behavior; none should exist.
* Inspect error strings for private absolute path leakage.
* Run focused bridge tests and script typecheck.

### Edge Cases

* Empty registry array.
* Registry entry with missing graph artifact.
* Registry entry with missing local source path.
* Registry entry with `path` or `sourcePath` starting `git:`.
* Registry entry with empty local source path.
* Absolute `graphPath` that resolves inside the graph directory.
* Absolute or relative `graphPath` that escapes the graph directory.
* Encoded or punctuation-heavy graph id.

***

## 10. Dependencies

### External Libraries

* None new.

### Other Sessions

* **Depends on**: `phase26-session01-graph-data-contracts-seed-fixtures`
* **Depended by**: `phase26-session03-graph-ingest-removal-admin-bridge`, `phase26-session05-read-hook-route-shell-project-gallery`, `phase26-session06-ingest-ui-connect-prompt-starter-chips`, `phase26-session07-hermes-chat-grounding-graph-toolset`

***

## 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-session02-graph-read-bridge-registry-endpoints/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.
