> 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/specs/phase41-session04-knowledge-graph-write-path/spec.md).

# Session Specification

**Session ID**: `phase41-session04-knowledge-graph-write-path` **Phase**: 41 - Hermes All-Access Remediation **Status**: Not Started **Created**: 2026-07-03 **Base Commit**: e4b94fee2683dc9618917e6fded6814789a88a46

***

## 1. Session Overview

This session moves the Knowledge Graph ingest, remove, and graph-grounded chat path from legacy manual Hermes admin gating to the Phase 41 local all-access contract. It is next because Sessions 01 through 03 made normal local startup and Hermes browser route readiness all-access by default, while the Knowledge Graph admin bridge, parser, hook, route metadata, and ingest UI still expose `HERMES_DASHBOARD_ADMIN` and read-only copy as normal local prerequisites.

The session keeps the existing Knowledge Graph safety model intact: loopback-only bridge access, same-run token checks for mutations, schema validation, body-size limits, path confinement, no-shell argv execution, timeouts, safe errors, and generated-data boundaries. The change is that normal local write readiness comes from `AI_OS_LOCAL_ALL_ACCESS=1` and automatic token readiness, with missing Graphify, token failure, demo/privacy, offline, and real dependency failures surfaced as named recoverable states.

The result should let local operators add or remove graph projects and start grounded Hermes chat without manual admin env setup when Graphify and the same-run token are available. When those dependencies are not available, the UI must explain the real dependency instead of hiding it behind generic disabled or read-only language.

***

## 2. Objectives

1. Replace the Knowledge Graph admin status contract with local all-access write readiness while preserving compatibility fields where needed.
2. Align Knowledge Graph browser parsers and hooks with write readiness, automatic token readiness, Graphify availability, demo/privacy, fallback, and offline states.
3. Update `/knowledge-graph`, ingest/remove controls, and grounded chat copy so local mode is not presented as read-only or manual-admin disabled.
4. Add focused bridge, parser, hook, route, component, home-section, and e2e coverage for local write-ready behavior and named recovery states.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase41-session01-local-access-startup-contract` - Provides canonical `AI_OS_LOCAL_ALL_ACCESS=1` normal local startup behavior.
* [x] `phase41-session02-hermes-bridge-status` - Provides the Phase 41 bridge status pattern for `writeReady`, local all-access fields, compatibility aliases, and named blockers.
* [x] `phase41-session03-hermes-route-modes-and-hooks` - Provides ready browser route state as `live-local` and automatic token/write readiness semantics for Hermes consumers.

### Required Tools Or Knowledge

* Knowledge Graph admin bridge and existing write safeguards in `scripts/lib/knowledge-graph-admin-bridge.ts`.
* Knowledge Graph admin parser contract in `src/lib/knowledge-graph-admin-types.ts`.
* Knowledge Graph browser hooks in `src/hooks/use-knowledge-graph-admin.ts`, `src/hooks/use-knowledge-graph-token.ts`, and `src/hooks/use-knowledge-graph.ts`.
* Knowledge Graph route, ingest/remove UI, grounded chat, page, home section, and focused tests.

### Environment Requirements

* No real `.env.local`, generated private data, credentials, bearer tokens, local logs, coverage, browser reports, or raw operator data are edited or committed.
* Tests use fixture tokens, mocked bridge responses, temporary directories, and redacted paths only.
* Graphify remains optional for development startup; missing Graphify is a named recovery state.

***

## 4. Scope

### In Scope (MVP)

* AI OS local operators can see Knowledge Graph write readiness by default when local all-access, same-run token, and Graphify availability are present - update the bridge and parser contract.
* AI OS local operators can ingest a local path or Git/GitHub URL through the existing bridge with token, loopback, schema, timeout, no-shell argv, path, size, and rollback safeguards preserved.
* AI OS local operators can remove graph artifacts through the existing bridge without manual Hermes admin env setup, while preserving source repository and directory safety.
* AI OS local operators can use graph-grounded Hermes chat with local all-access copy, explicit token/dependency recovery, and demo/privacy boundaries.
* Maintainers can rely on route, component, hook, parser, server, home-section, and e2e tests that prove missing manual Hermes admin env no longer blocks Knowledge Graph writes.

### Out Of Scope (Deferred)

* Broad Knowledge Graph schema changes - Reason: the session only changes write readiness and recovery state contracts.
* Generated local data regeneration or hand-editing `src/data/live-data.json` - Reason: Session 17 owns generated data closeout.
* Active docs and Knowledge Graph handover documentation cleanup - Reason: Session 15 owns active docs after implementation sessions land.
* Voice, Intelligence, OpenClaw, Claude Code, extension, public demo, archive, and generated-data all-access migrations - Reason: Sessions 05 through 17 own those surfaces.

***

## 5. Technical Approach

### Architecture

Follow the Session 02 Hermes bridge status pattern for the Knowledge Graph admin status payload. Add explicit write readiness fields to `scripts/lib/knowledge-graph-admin-bridge.ts`, such as `writeReady`, `localAccessMode`, `localAllAccess`, `compatibilityAlias`, and `writeBlockers`, while keeping `adminEnabled` only as a temporary compatibility mirror for existing browser code. `requirePreflight()` should continue to enforce method, loopback/Host-header, and token requirements, but mutation readiness should no longer depend on `HERMES_DASHBOARD_ADMIN=1` when the local all-access contract is enabled.

Update `src/lib/knowledge-graph-admin-types.ts` so browser code parses the new status contract strictly. Then update `useKnowledgeGraphAdmin()` to derive `canUseAdmin` from parsed `writeReady`, same-run token availability, browser online state, non-demo mode, and Graphify availability. Keep ingest/remove duplicate-trigger prevention and query invalidation in the hook.

Update the Knowledge Graph page surfaces to consume named states instead of manual-admin language. The ingest card should distinguish all-access ready, token unavailable, Graphify missing, demo/privacy, offline, and bridge failure states. The grounded chat status should stop calling local demo chat "read-only" as normal behavior and should report the actual all-access or dependency-limited state.

### Design Patterns

* Parser-owned contract: Bridge status is trusted only after strict browser parser validation.
* Hook-owned readiness projection: UI components consume stable write readiness and blocker states instead of duplicating bridge policy.
* Defense-in-depth controls: Removing manual env opt-in does not weaken loopback, Host-header, token, schema, timeout, safe-error, no-shell argv, path, and body-size controls.
* Product-facing recovery copy: Normal route copy names the operator outcome and dependency recovery, while diagnostics stay in tests and notes.

***

## 6. Deliverables

### Files To Create

| File | Purpose                                                                                                 | Est. Lines |
| ---- | ------------------------------------------------------------------------------------------------------- | ---------- |
| None | No new production files are required; this session modifies existing bridge, hook, UI, and test owners. | \~0        |

### Files To Modify

| File                                                                              | Changes                                                                                                                                                                                 | Est. Lines |
| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `scripts/lib/knowledge-graph-admin-bridge.ts`                                     | Replace manual admin-gate write readiness with local all-access status fields, keep token/loopback/schema/no-shell/path safeguards, and preserve compatibility fields during migration. | \~120      |
| `src/lib/knowledge-graph-admin-types.ts`                                          | Parse the expanded status contract, named blockers, and compatibility alias fields while keeping ingest/remove response validation strict.                                              | \~100      |
| `src/hooks/use-knowledge-graph-admin.ts`                                          | Derive mutation capability from `writeReady`, token availability, online state, demo mode, and Graphify availability; preserve duplicate-trigger prevention.                            | \~90       |
| `src/hooks/use-knowledge-graph-token.ts`                                          | Update token state copy and tests where needed so missing token is a recoverable local readiness failure, not admin-disabled behavior.                                                  | \~20       |
| `src/hooks/use-knowledge-graph.ts`                                                | Keep live, bundled seed, demo, offline, empty, and error states explicit and align status copy with write-ready local mode.                                                             | \~35       |
| `src/routes/knowledge-graph.tsx`                                                  | Update route metadata so `/knowledge-graph` no longer presents local mode as read-only.                                                                                                 | \~8        |
| `src/components/knowledge-graph/knowledge-graph-ingest-card.tsx`                  | Update gate derivation, labels, form disabled states, and status copy for all-access ready, token, Graphify, demo, offline, and error states.                                           | \~100      |
| `src/components/knowledge-graph/knowledge-graph-grounded-chat.tsx`                | Update grounded chat status copy and readiness behavior for local all-access and named recovery states.                                                                                 | \~35       |
| `src/components/knowledge-graph/knowledge-graph-page.tsx`                         | Adjust hook wiring if status fields or token/readiness naming changes.                                                                                                                  | \~20       |
| `src/components/home/knowledge-graph-section.tsx`                                 | Adjust home section copy or fixtures only where the new live local status appears.                                                                                                      | \~20       |
| `scripts/lib/__tests__/knowledge-graph-admin-bridge.test.ts`                      | Cover local all-access status, no manual admin env, mutation preflight, token failure, Graphify missing, loopback, host, and safe error behavior.                                       | \~150      |
| `src/lib/__tests__/knowledge-graph-admin-types.test.ts`                           | Cover expanded parser fields, named blockers, compatibility alias, malformed payloads, and structured errors.                                                                           | \~90       |
| `src/hooks/__tests__/use-knowledge-graph-admin.test.tsx`                          | Cover write-ready capability, token missing, Graphify missing, demo, offline, bridge errors, duplicate writes, and query invalidation.                                                  | \~130      |
| `src/hooks/__tests__/use-knowledge-graph-token.test.tsx`                          | Update token success, demo, offline, and malformed token coverage if copy or state names change.                                                                                        | \~30       |
| `src/hooks/__tests__/use-knowledge-graph.test.tsx`                                | Update live/seed/demo/offline status expectations where all-access copy affects hook projection.                                                                                        | \~40       |
| `src/components/knowledge-graph/__tests__/knowledge-graph-ingest-card.test.tsx`   | Cover ready, token failure, Graphify missing, demo, offline, bridge failure, duplicate submit, and remove confirmation states.                                                          | \~140      |
| `src/components/knowledge-graph/__tests__/knowledge-graph-grounded-chat.test.tsx` | Cover grounded chat local all-access copy, demo/privacy copy, offline fallback, and token/admin hook wiring.                                                                            | \~80       |
| `src/components/knowledge-graph/__tests__/knowledge-graph-page.test.tsx`          | Update page fixture status shape and assert the ingest form remains present with all-access readiness.                                                                                  | \~50       |
| `src/routes/__tests__/knowledge-graph.test.tsx`                                   | Update metadata assertions and public-demo no-bridge expectations.                                                                                                                      | \~35       |
| `src/components/home/__tests__/knowledge-graph-section.test.tsx`                  | Update home-section fixtures and copy expectations for live local graph status.                                                                                                         | \~25       |
| `tests/e2e/knowledge-graph.spec.ts`                                               | Update route smoke and blocked/ready ingest assertions for named recovery states without manual admin env.                                                                              | \~60       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `/__graphify_admin_status` reports Knowledge Graph write readiness from the local all-access contract rather than `HERMES_DASHBOARD_ADMIN`.
* [ ] Ingest and remove preflight still enforce method, loopback/Host-header, same-run token, schema, body-size, path confinement, no-shell argv, timeout, and safe-error controls.
* [ ] `useKnowledgeGraphAdmin()` reports `canUseAdmin` true in normal local dev when write readiness, token readiness, and Graphify availability are present.
* [ ] Ingest/remove controls prevent duplicate triggers while in flight and show explicit token, Graphify, demo/privacy, offline, and bridge failure recovery states.
* [ ] Grounded Hermes chat uses local all-access readiness copy and keeps demo/privacy and offline behavior as named exceptions.

### Testing Requirements

* [ ] Bridge and parser tests cover local all-access status, compatibility alias behavior, token failure, loopback failure, Graphify missing, malformed payloads, and structured errors.
* [ ] Hook tests cover write-ready, token missing, Graphify missing, demo, offline, bridge error, duplicate-trigger prevention, and query invalidation.
* [ ] Route, component, home-section, and e2e tests prove local Knowledge Graph no longer presents normal mode as read-only or manual-admin disabled.

### Non-Functional Requirements

* [ ] No browser-visible payload, test fixture, or copy exposes provider keys, bearer tokens, auth JSON, raw prompts, transcripts, raw command output, private paths, local usernames, or secret-shaped strings.
* [ ] Graphify missing remains a recoverable dependency state and does not become a hard startup requirement.
* [ ] UI copy is product-facing; implementation diagnostics stay in tests, bridge errors, or notes.

### Quality Gates

* [ ] All files ASCII-encoded
* [ ] Unix LF line endings
* [ ] Code follows project conventions
* [ ] Primary user-facing surfaces contain product-facing copy only

***

## 8. Implementation Notes

### Working Assumptions

* `adminEnabled` should remain temporarily as a compatibility mirror while new decisions use `writeReady`: Session 02 and Session 03 used this migration pattern for Hermes, and existing Knowledge Graph hook/component tests currently consume `adminEnabled`. Planning can proceed because compatibility fields can be preserved without keeping manual admin env as the normal gate.
* Graphify availability should be part of write readiness messaging but not a startup requirement: The current bridge status already marks Graphify as `optional: true`, the Phase 41 stub names missing Graphify as a recovery state, and the Knowledge Graph docs say graphify should stay optional until a product decision changes that.
* No database-layer work is needed: The analyzer reports `monorepo: false`, conventions state there is no app database, and this session touches local files, browser hooks, bridge routes, and tests only.

### Conflict Resolutions

* `docs/knowledge-graph/knowledge-graph-handover.md` still says admin writes require `HERMES_DASHBOARD_ADMIN=1`, while AGENTS, the master PRD, the Phase 41 PRD, and the Session 04 stub require normal local all-access write readiness. The Phase 41 policy wins for current implementation; active docs cleanup is deferred to Session 15.
* `.spec_system/PRD/PRD_UX.md` still contains older read-only/default-off agent page language, while Phase 41 requires all-access delivery for shipped local operator goals. The current Phase 41 PRD and AGENTS instructions win; the older UX language is migration debt for later docs/spec-memory sessions.
* The current route metadata and e2e test describe a blocked ingest gate, while the Session 04 acceptance checks require writes to execute or reach real dependency failure paths without manual admin env. The selected interpretation is to replace generic blocked/admin-disabled expectations with named dependency states such as token failure, Graphify missing, demo/privacy, or offline.

### Key Considerations

* `src/data/live-data.json` is generated and gitignored; this session must not edit it.
* Local control-plane safeguards remain defense in depth and should be strengthened by tests where touched.
* Keep AI OS host naming for Knowledge Graph local operator behavior and do not add new global `findtrend` identifiers.

### Potential Challenges

* Bridge status changes can cascade through several fixture types: update parser and hook fixtures first so component tests can share the new shape.
* Missing Graphify can look like disabled writes: keep Graphify status distinct from token and local access states in the hook and ingest card.
* Grounded chat consumes Hermes admin hooks as well as Knowledge Graph data: verify it still passes token and demo mode correctly after copy and readiness changes.

### Relevant Considerations

* \[P41] **Local access default migration**: Knowledge Graph local operator flows must stop presenting manual admin env setup as the normal write path.
* \[P41] **Do not accept scaffolding as delivery**: The plan includes real ingest/remove and grounded-chat behavior plus tests, not label-only changes.
* \[P26] **Knowledge Graph contract alignment**: Bridge, parser, hooks, route UI, home summary, and Hermes grounding share one graph contract and must move together.
* \[P38/P40] **Local control-plane gates are defense in depth**: Loopback, Host-header, token, schema, timeout, redaction, no-shell argv, and path confinement remain mandatory.
* \[P40/P41] **Write safeguards are reusable**: Reuse the existing command, atomic write, rollback, and duplicate-trigger protections while changing readiness policy.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* Mutation controls can enable before token, write readiness, and Graphify status have all resolved.
* Missing Graphify can be misreported as disabled access, causing the operator to chase obsolete admin env setup.
* Ingest/remove actions can duplicate or partially write if UI and bridge in-flight guards or atomic rollback behavior regress.

***

## 9. Testing Strategy

### Unit Tests

* Test expanded bridge status and mutation preflight behavior in `scripts/lib/__tests__/knowledge-graph-admin-bridge.test.ts`.
* Test strict browser parser behavior in `src/lib/__tests__/knowledge-graph-admin-types.test.ts`.
* Test Knowledge Graph admin, token, and read hook state projections in `src/hooks/__tests__/use-knowledge-graph-admin.test.tsx`, `src/hooks/__tests__/use-knowledge-graph-token.test.tsx`, and `src/hooks/__tests__/use-knowledge-graph.test.tsx`.

### Integration Tests

* Test ingest/remove UI states in `src/components/knowledge-graph/__tests__/knowledge-graph-ingest-card.test.tsx`.
* Test grounded Hermes wiring and copy in `src/components/knowledge-graph/__tests__/knowledge-graph-grounded-chat.test.tsx`.
* Test page, route metadata, and home-section fixture integration in `src/components/knowledge-graph/__tests__/knowledge-graph-page.test.tsx`, `src/routes/__tests__/knowledge-graph.test.tsx`, and `src/components/home/__tests__/knowledge-graph-section.test.tsx`.

### Runtime Verification

* Run `bun run test -- scripts/lib/__tests__/knowledge-graph-admin-bridge.test.ts src/lib/__tests__/knowledge-graph-admin-types.test.ts src/hooks/__tests__/use-knowledge-graph-admin.test.tsx src/hooks/__tests__/use-knowledge-graph-token.test.tsx src/hooks/__tests__/use-knowledge-graph.test.tsx src/components/knowledge-graph/__tests__/knowledge-graph-ingest-card.test.tsx src/components/knowledge-graph/__tests__/knowledge-graph-grounded-chat.test.tsx src/components/knowledge-graph/__tests__/knowledge-graph-page.test.tsx src/routes/__tests__/knowledge-graph.test.tsx src/components/home/__tests__/knowledge-graph-section.test.tsx`.
* Run `bun run test -- tests/e2e/knowledge-graph.spec.ts` or the repo-supported Playwright equivalent if Vitest does not own that file.
* Run `bun run typecheck` because bridge status type changes touch browser TypeScript.
* Run ASCII and LF validation for session artifacts and touched source/test files.

### Edge Cases

* Demo/public mode must not fetch local bridge or token routes and must keep writes off as a named privacy boundary.
* Offline browser state must not fetch token or admin status and must show bundled seed data where applicable.
* Token failure must block mutations without changing the state into generic disabled/admin-disabled.
* Missing Graphify must block ingest with install/configure recovery copy while route reads and bundled seed data remain available.
* Bridge write errors must remain redacted and must not expose temp paths, local usernames, raw command output, or token-shaped strings.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase41-session01-local-access-startup-contract`, `phase41-session02-hermes-bridge-status`, `phase41-session03-hermes-route-modes-and-hooks`
* Depended by: `phase41-session14-end-to-end-test-matrix`, `phase41-session15-active-docs-and-runbooks`, `phase41-session16-spec-memory-and-archive-supersession`, `phase41-session17-generated-data-closeout`

***

## Next Steps

Run the `implement` workflow step to begin 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/specs/phase41-session04-knowledge-graph-write-path/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.
