> 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-session07-hermes-chat-grounding-graph-toolset/spec.md).

# Session Specification

**Session ID**: `phase26-session07-hermes-chat-grounding-graph-toolset` **Phase**: 26 - Knowledge Graph Shared Brain Port **Status**: Not Started **Created**: 2026-06-09

***

## 1. Session Overview

This session connects the existing AI OS Hermes chat surface to the Knowledge Graph page. Sessions 01-06 already provided typed graph contracts, read and admin bridges, graph ingest and removal UI, starter chips, and the connect prompt. Session 07 turns those starter affordances into a real grounded chat by reusing the modular Hermes chat components rather than recreating the upstream route monolith.

The main behavior is a Hermes chat panel on `/knowledge-graph` that is seeded with the active graph on the first fresh turn, listens for `hermes-chat-prefill` events from starter chips, displays a visible grounding chip, and forwards graph tool options through the existing admin-gated chat path. The seed context is invisible to the displayed user message, but the UI must clearly show which graph the chat is grounded in.

The security boundary must remain the existing Hermes admin bridge: loopback request, per-run token, `HERMES_DASHBOARD_ADMIN=1`, non-demo UI state, and hook-mediated browser calls. This session adds payload fields and argv flags to the current chat path; it does not introduce a new unauthenticated write surface or a direct Knowledge Graph mutation path from chat.

***

## 2. Objectives

1. Make `HermesChatTab` reusable with optional Knowledge Graph grounding props for seed context, visible label/accent, toolsets, and yolo mode.
2. Apply the seed context invisibly only on the first fresh chat turn, while keeping displayed local messages, resumed threads, and image attachments readable.
3. Forward `toolsets` and `yolo` through `useHermesAdmin().chat.sendPrompt` and `/__hermes_chat`, then append `-t <toolsets>` and `--yolo -s graphify` to Hermes argv arrays only.
4. Mount a grounded Hermes chat panel inside the Knowledge Graph page, connected to active graph selection and starter-chip prefill.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase26-session05-read-hook-route-shell-project-gallery` - Provides `/knowledge-graph`, `useKnowledgeGraph`, active project selection, graph registry state, and page composition.
* [x] `phase26-session06-ingest-ui-connect-prompt-starter-chips` - Provides `hermes-chat-prefill` starter chips, connect prompt, token hook, admin-gated Knowledge Graph write UI, and the future `kg-chat-anchor`.
* [x] `phase17-session02-chat-tab-write` - Provides the original admin-gated Hermes chat foundation and component pattern.

### Required Tools/Knowledge

* Bun 1.3.14, React 19, TypeScript, TanStack Query, Tailwind CSS 4, Vitest, and Testing Library.
* Existing AI OS Hermes chat components under `src/components/hermes/chat/`.
* Existing admin hook and bridge behavior in `src/hooks/use-hermes-admin.ts` and `scripts/lib/hermes-admin-bridge.ts`.
* Claude OS v2.4 references for behavior only: `src/routes/agents.hermes.tsx`, `src/routes/codegraph.tsx`, and `vite.config.ts`.

### Environment Requirements

* Local Vite dev server exposes `/__token`, Hermes read endpoints, and the Hermes admin bridge.
* Live chat remains optional. Demo mode and setup-required states must stay explicit.
* Graphify skill execution is opt-in through the existing admin chat endpoint and must not bypass the Hermes gate.

***

## 4. Scope

### In Scope (MVP)

* Operator can open `/knowledge-graph` and see a grounded Hermes chat panel tied to the active project - implemented through a small Knowledge Graph wrapper that reuses `HermesChatTab`.
* Operator can click starter-question chips and have the Hermes composer prefilled and focused - implemented with a `hermes-chat-prefill` listener that cleans up on unmount.
* Operator can send a first fresh chat prompt with invisible graph seed context - implemented so the displayed user message contains only the user's prompt and attachment summary.
* Operator can resume existing Hermes threads without re-prepending seed context - implemented with selected session state and first-turn detection.
* Operator can see a "Chatting with X" grounding chip for fresh grounded chats - implemented with bounded text, accessible label/title, and project accent color.
* Operator can run graph-aware Hermes responses through `toolsets` and `yolo` - implemented by forwarding payload fields and appending argv flags after validation.
* Admin gate remains unchanged - loopback, token, admin env, request method, body-size, prompt-size, and session id checks still happen before spawn.

### Out of Scope (Deferred)

* Homepage Knowledge Graph section and Shared Brain setup scripts - *Reason: Session 08 owns homepage/script/OAuth work.*
* Documentation, release validation, and parity sign-off - *Reason: Session 09 owns closeout.*
* New Mission Control or Hermes write contracts - *Reason: this session only extends chat payload options on the existing admin-gated endpoint.*
* Direct graph registry edits or direct graphify ingest from chat - *Reason: graph writes stay in the Knowledge Graph admin hook/UI from Session 06.*

***

## 5. Technical Approach

### Architecture

Extend the existing chat module instead of introducing a new Knowledge Graph-specific chat. Add a small prop contract for optional grounding: seed context text, seed label, seed accent, toolsets, and yolo. `HermesChatTab` owns composer state, local messages, selected thread behavior, first-turn seed insertion, the prefill listener, and the visible chip. It still delegates network writes to `admin.chat.sendPrompt`.

Extend `useHermesAdmin` so `chat.sendPrompt` accepts an options object while preserving the existing `(prompt, sessionId)` call shape for current callers. The hook serializes `toolsets` and `yolo` only when provided, keeps duplicate-trigger prevention through the current in-flight ref, and invalidates the same sessions/session-detail query keys after success.

Extend `scripts/lib/hermes-admin-bridge.ts` in the existing `/__hermes_chat` handler. Validate optional `toolsets` as a bounded safe string, parse `yolo` only when strictly `true`, then append `-t <toolsets>` and `--yolo -s graphify` to the argv array before spawning Hermes. Do not build shell strings and do not weaken preflight.

Add `KnowledgeGraphGroundedChat` under `src/components/knowledge-graph/`. It derives the active graph seed context from `useKnowledgeGraph`, gets Hermes sessions through `useHermes({ sessionId, demoMode })`, obtains the admin token from Hermes state, creates `useHermesAdmin`, and renders `HermesChatTab` inside the `kg-chat-anchor` section. A pure helper in `src/lib/knowledge-graph-hermes-grounding.ts` keeps seed text deterministic and testable.

### Design Patterns

* Existing hook boundary: chat writes continue through `useHermesAdmin`, not component-owned fetches.
* First-turn seed composition: prepend graph context only for fresh chats with no selected session and no local messages.
* Reopenable context handling: selected session and demo/live mode changes reset local composer and cancel or reset pending chat state.
* Boundary validation: bridge accepts optional `toolsets` and `yolo` only after existing preflight and explicit payload validation.
* Thin route and page adapter: `/knowledge-graph` route remains unchanged; the page composes a new modular component.

### Technology Stack

* React 19 and TypeScript.
* TanStack Query through existing `useHermes`, `useHermesAdmin`, and `useKnowledgeGraph` hooks.
* Existing Tailwind CSS 4 and local Hermes/Knowledge Graph component conventions.
* Vitest and Testing Library for component, hook, bridge, and pure helper coverage.

***

## 6. Deliverables

### Files to Create

| File                                                                              | Purpose                                                                                                            | Est. Lines |
| --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ---------- |
| `src/lib/knowledge-graph-hermes-grounding.ts`                                     | Pure active-project seed context, label, accent, and tool option builder                                           | \~140      |
| `src/lib/__tests__/knowledge-graph-hermes-grounding.test.ts`                      | Unit tests for seed text, graph path fallback, labels, and no private token/header text                            | \~140      |
| `src/components/knowledge-graph/knowledge-graph-grounded-chat.tsx`                | Knowledge Graph chat wrapper that wires `useHermes`, `useHermesAdmin`, selected session state, and `HermesChatTab` | \~180      |
| `src/components/knowledge-graph/__tests__/knowledge-graph-grounded-chat.test.tsx` | Component tests for loaded, demo/offline/setup, active project, and starter prefill integration                    | \~220      |

### Files to Modify

| File                                                                     | Changes                                                                                                           | Est. Lines |
| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- | ---------- |
| `src/components/hermes/chat/chat-types.ts`                               | Add grounding prop/options types and seed compose helper if useful                                                | \~60       |
| `src/components/hermes/chat/index.ts`                                    | Export the new chat grounding types needed by the wrapper/tests                                                   | \~10       |
| `src/components/hermes/chat/hermes-chat-tab.tsx`                         | Add optional seed/tool props, prefill listener, first-turn seed prefix, grounding chip, and tool option send path | \~180      |
| `src/hooks/use-hermes-admin.ts`                                          | Add typed chat send options and serialize `toolsets`/`yolo` with existing duplicate prevention and invalidation   | \~80       |
| `scripts/lib/hermes-admin-bridge.ts`                                     | Validate chat `toolsets`/`yolo` payload and append Hermes argv flags after current preflight                      | \~90       |
| `src/components/knowledge-graph/knowledge-graph-page.tsx`                | Mount grounded chat near starter chips and connect prompt without changing read panel behavior                    | \~30       |
| `src/components/hermes/chat/__tests__/hermes-chat-tab.test.tsx`          | Cover prefill, chip rendering, first-turn seed prefix, resumed-thread behavior, and tool option calls             | \~180      |
| `src/hooks/__tests__/use-hermes-admin.test.tsx`                          | Cover chat payload forwarding for `toolsets` and `yolo`                                                           | \~80       |
| `scripts/lib/__tests__/hermes-admin-bridge.test.ts`                      | Cover argv append, invalid toolsets rejection, yolo strictness, and unchanged preflight                           | \~140      |
| `src/components/knowledge-graph/__tests__/knowledge-graph-page.test.tsx` | Cover page composition with the grounded chat anchor while preserving current graph sections                      | \~80       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `/knowledge-graph` renders a grounded Hermes chat section for the active project without hiding hero, gallery, starter chips, 3D panel, side rail, ingest card, or connect prompt.
* [ ] Starter chips dispatch `hermes-chat-prefill`; the chat composer receives the prompt, focuses the textarea, and handles repeated clicks.
* [ ] Fresh chat sends prepend seed context invisibly on the first turn only; local user bubbles show the user's original text and attachment summary only.
* [ ] Resumed sessions send without re-prepending seed context and still invalidate session/detail queries after success.
* [ ] Grounding chip displays the active project label on fresh grounded chats, uses bounded text, and remains accessible.
* [ ] `toolsets` and `yolo` reach `/__hermes_chat`, and the bridge appends `-t <toolsets>` plus `--yolo -s graphify` using argv arrays only.
* [ ] The existing Hermes admin gate remains intact and no new unauthenticated chat or graph write route is added.

### Testing Requirements

* [ ] Pure grounding tests cover seed context content, missing graph path fallback, label/accent derivation, and forbidden token/header text.
* [ ] Chat component tests cover prefill, first-turn seed prefix, display text separation, chip visibility, resumed-thread behavior, and tool option calls.
* [ ] Hook tests cover payload serialization and duplicate-trigger prevention while in-flight.
* [ ] Bridge tests cover valid `toolsets`/`yolo`, invalid `toolsets`, strict yolo parsing, argv-only spawn, and unchanged preflight failures.
* [ ] Knowledge Graph wrapper/page tests cover active project changes, demo/offline/setup states, anchor composition, and preserved graph content.

### Non-Functional Requirements

* [ ] Token values, auth headers, private command output, and raw credential-shaped strings are not rendered, copied, or logged.
* [ ] Long project names, graph paths, session ids, and prompt text stay bounded on mobile and desktop.
* [ ] Chat async work cancels or resets on selected-session/demo-mode changes and cleans event listeners on unmount.
* [ ] No new client dependency is introduced.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] `bun run test -- src/lib/__tests__/knowledge-graph-hermes-grounding.test.ts src/components/hermes/chat/__tests__/hermes-chat-tab.test.tsx src/hooks/__tests__/use-hermes-admin.test.tsx scripts/lib/__tests__/hermes-admin-bridge.test.ts src/components/knowledge-graph/__tests__/knowledge-graph-grounded-chat.test.tsx src/components/knowledge-graph/__tests__/knowledge-graph-page.test.tsx` passes.
* [ ] Relevant broader checks are ready for the validate workflow step.

***

## 8. Implementation Notes

### Key Considerations

* Keep the Knowledge Graph wrapper small. Its job is to project active graph state into Hermes chat props and selected session state.
* Treat seed context as prompt input, not displayed message content. The operator sees the visible grounding chip and their own prompt.
* The prefill listener should be removed on unmount and should not fire in SSR.
* `toolsets` can be a deliberately empty string only if implementation chooses that behavior; otherwise use a bounded allowlist string such as `graphify`. The bridge validation and tests must document the chosen behavior.
* Do not change the Mission Control, document, persona, Pantheon, or image upload admin contracts.

### Potential Challenges

* Preserving the old `sendPrompt(prompt, sessionId)` call shape: Add an options object without breaking current callers.
* Image attachments plus seed context: Build the server prompt in a deterministic order and keep attachment private paths out of display bubbles.
* Selected project changes: Avoid remount churn that wipes typed input unnecessarily, but rederive seed context before the next fresh send.
* Tool approval deadlock: Yolo graph mode is intended to avoid non-interactive tool approval hangs, but it must remain behind the existing admin preflight.
* Bridge payload validation: Invalid `toolsets` must fail closed before spawn and without echoing unsafe input.

### Relevant Considerations

* \[P04] **Hermes bridge guardrails must stay intact**: Keep loopback, token, admin, no-clobber path safety, and disabled-by-default admin mode.
* \[P24] **Fail-closed bridges need boundary validation**: Validate optional chat payload fields at the bridge boundary with explicit error mapping.
* \[P25] **Writes stay on the shared admin contract**: Do not add ad hoc component fetches or route-specific execution paths.
* \[P18] **Lazy imports plus cleanup-first effects make 3D UI safe**: Apply the same cleanup discipline to chat event listeners and async cancel/reset paths.
* \[P23] **Thin route mount + dedicated page adapter**: Keep Knowledge Graph behavior inside modular components, not the route file.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* Seed context could leak into visible chat bubbles or be appended multiple times across resumed sessions.
* A graph-aware chat write could bypass or weaken the existing Hermes admin gate.
* Tool option payloads could become shell-like if not validated and appended as argv entries only.
* Starter-chip prefill and selected-session changes can race with pending chat streams unless cleanup and reset paths are explicit.

***

## 9. Testing Strategy

### Unit Tests

* Test the grounding helper for active graph seed text, missing graph path fallback, label/accent derivation, and absence of token/header/direct mutation instructions.
* Test hook payload serialization for `toolsets` and `yolo`, including preservation of existing duplicate-trigger prevention.
* Test bridge validation helpers through route invocation so invalid toolsets never reach spawn.

### Integration Tests

* Render `HermesChatTab` with grounding props and assert chip visibility, prefill event handling, first-turn seed prefix, display message separation, resumed-thread behavior, and tool option calls.
* Render `KnowledgeGraphGroundedChat` with mocked Knowledge Graph and Hermes hooks for loaded, demo, offline, and setup-required projections.
* Extend `KnowledgeGraphPage` tests to prove the grounded chat anchor appears alongside existing page sections.

### Manual Testing

* Run the dev app with admin disabled, open `/knowledge-graph`, and confirm chat writes stay gated.
* Run with `HERMES_DASHBOARD_ADMIN=1`, select a Knowledge Graph project, click a starter chip, and confirm the composer prefill and grounding chip.
* Send a first grounded prompt and verify the bridge receives `toolsets`/`yolo` without rendering seed context or token values.

### Edge Cases

* Missing active project should render an explicit empty/fallback state and avoid sending a seedless graph prompt as grounded.
* Offline or token-failure state should keep the chat present but writes disabled.
* Repeated starter-chip clicks should replace the draft prompt without sending automatically.
* Invalid `toolsets` payload should return a bounded bridge error and never spawn Hermes.

***

## 10. Dependencies

### External Libraries

* No new external libraries.

### Other Sessions

* **Depends on**: `phase26-session05-read-hook-route-shell-project-gallery`, `phase26-session06-ingest-ui-connect-prompt-starter-chips`, and existing Hermes chat/admin sessions.
* **Depended by**: `phase26-session08-homepage-surface-shared-brain-scripts-oauth` and `phase26-session09-documentation-validation-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-session07-hermes-chat-grounding-graph-toolset/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.
