> 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-session03-graph-ingest-removal-admin-bridge/spec.md).

# Session Specification

**Session ID**: `phase26-session03-graph-ingest-removal-admin-bridge` **Phase**: 26 - Knowledge Graph Shared Brain Port **Status**: Not Started **Created**: 2026-06-09

***

## 1. Session Overview

This session adds the write-capable Knowledge Graph admin bridge for AI OS. It ports the upstream graphify ingest and remove behavior into the existing AI OS admin model instead of placing mutating endpoint code directly in `vite.config.ts`. The server side owns loopback, token, and `HERMES_DASHBOARD_ADMIN=1` checks; the client side owns a small typed admin hook so later UI work cannot bypass the mediated write path.

The bridge accepts a local path or Git/GitHub URL, runs `git` and `graphify` through argv arrays only, validates and caps the generated graph, writes a confined graph artifact, and upserts a registry entry with an absolute `graphPath` for Shared Brain consumers. Removal deletes only the stored graph artifact and registry entry, never the source repository.

This is next because Sessions 01 and 02 completed the graph contracts, seed fixtures, registry listing, and graph streaming read bridge. Sessions 05, 06, and 07 need a safe write path before the route, ingest card, and Hermes grounding can consume live project graphs.

***

## 2. Objectives

1. Implement a registered Knowledge Graph admin bridge with status, ingest, and removal endpoints behind the shared AI OS admin preflight.
2. Run `git` and `graphify` only through argv-array process calls with bounded timeouts, explicit failure mapping, and guaranteed temp/scratch cleanup.
3. Validate graph output, enforce vendored-dependency and 12,000-node guards, compute metadata, and write path-confined artifacts plus absolute-path registry entries.
4. Add typed admin response parsers and a minimal `useKnowledgeGraphAdmin()` hook that blocks demo/offline/token-disabled writes and prevents duplicate submits.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase26-session01-graph-data-contracts-seed-fixtures` - Provides typed Knowledge Graph contracts, parser helpers, demo data, and bundled seed graph files.
* [x] `phase26-session02-graph-read-bridge-registry-endpoints` - Provides the loopback-only read bridge, registry compatibility normalization, graph path confinement helpers, and Vite registration precedent.

### Required Tools/Knowledge

* Bun 1.3.14, TypeScript 6.0.3, Vite 8, React Query, and Vitest.
* Existing AI OS admin bridge patterns in `scripts/lib/hermes-admin-bridge.ts` and `scripts/lib/openclaw-admin-bridge.ts`.
* Existing admin hook and parser patterns in `src/hooks/use-openclaw-admin.ts`, `src/hooks/use-hermes-admin.ts`, and related tests.
* Upstream ingest/remove reference in `/home/aiwithapex/projects/claudeos/claude-os-v2.4/vite.config.ts`.

### Environment Requirements

* Local filesystem access to the AI OS repo and `src/data/graphs/`.
* `git` available for URL-ingest tests through an injected command helper.
* Live `graphify` is optional; the implementation must return an explicit missing-binary error when it is absent.

***

## 4. Scope

### In Scope (MVP)

* AI OS can report Knowledge Graph admin readiness - add a status endpoint that reports the `HERMES_DASHBOARD_ADMIN` gate, token requirement, dev-only status, and graphify optionality without exposing private paths.
* AI OS can ingest a local path or Git/GitHub URL - parse bounded JSON bodies, validate URLs, shallow-clone into a temp directory, expand local `~` paths, verify source existence, and clean temp/scratch directories on all outcomes.
* AI OS can run external tools safely - resolve `graphify` and `git`, call them through argv arrays only, bound timeouts and output, and map missing binary, clone failure, timeout, and graphify failure to stable error codes.
* AI OS can reject unsafe graph output - parse graphify output through `parseKnowledgeGraph()`, refuse graphs over 12,000 nodes, guard common vendored dependency explosions, and avoid writing malformed artifacts.
* AI OS can write and update graph registry state - compute metadata, god nodes, language, provenance, path-aware ids, collision hashes, color preservation, absolute `graphPath` values, and browser-safe response projections.
* AI OS can remove stored graphs safely - delete only confined `src/data/graphs/<id>.json` artifacts and registry entries, idempotently, with explicit invalid-id and path-escape rejection.
* AI OS can mediate future UI writes - add typed admin response parsers and `useKnowledgeGraphAdmin()` with offline, demo, token, disabled, pending, success, and error states.
* AI OS can prove the bridge is fail-closed - add focused tests for success and rejection paths.

### Out of Scope (Deferred)

* Ingest card, remove button, prompt card, and starter chips - *Reason: Session 06 owns operator-facing UI components after the route shell exists.*
* `/knowledge-graph` route, read hook, project gallery, and hero - *Reason: Session 05 owns browser read consumption and page composition.*
* Reusable 3D renderer - *Reason: Session 04 owns rendering, capping, bloom, density controls, and cleanup behavior.*
* Hermes chat grounding and graph toolset forwarding - *Reason: Session 07 owns chat grounding on top of the graph registry and active graph context.*
* Shared Brain setup scripts and homepage card - *Reason: Session 08 owns scripts, homepage surface, and OAuth setup false-positive fixes.*

***

## 5. Technical Approach

### Architecture

Create `scripts/lib/knowledge-graph-admin-bridge.ts` as a focused admin bridge module exporting `registerKnowledgeGraphAdminBridge(server, options)` plus testable helpers for request handling, path resolution, command execution, graph normalization, registry writes, and removal. `vite.config.ts` should import and register it next to the existing Hermes, OpenClaw, Trend Finder, and Knowledge Graph read bridges, passing the shared per-run `REFRESH_TOKEN`, `isLoopback`, Hermes admin env, graph directory paths, and logger adapter.

The server bridge should keep write behavior separate from the read bridge but reuse the same graph directory assumptions. Stored registry entries may keep absolute `graphPath` values for local agent Shared Brain usage; browser-visible responses should project those entries through the same safe registry contract used by the read bridge where practical.

Add `src/lib/knowledge-graph-admin-types.ts` for strict response/error parsers and `src/hooks/use-knowledge-graph-admin.ts` for the future UI. The hook should mirror OpenClaw's concise admin hook shape: status query, token/demo/offline gates, duplicate-trigger prevention, mutation reset on context change, and query invalidation for graph list consumers once those keys exist.

### Design Patterns

* Shared admin preflight: Loopback, per-run token, dev-only admin env gate, and bounded JSON errors are enforced before any write work begins.
* Argv-only process boundary: External commands receive argv arrays, never shell strings.
* Compensation on failure: Temp clones, `graphify-out`, partial graph writes, and pending registry updates are cleaned up or avoided when a later step fails.
* Fail-closed validation: Request payloads, ids, URLs, paths, graph JSON, and registry entries are validated before mutation.
* Browser-safe projection: Store absolute paths where Shared Brain requires them, but keep UI responses bounded and private-path-safe.

### Technology Stack

* TypeScript 6.0.3.
* Bun 1.3.14.
* Vite 8 dev middleware.
* React 19 and React Query for the hook.
* Vitest 4.1.6 and Testing Library hook tests.
* Node `child_process`, `fs/promises`, `os`, and `path` APIs.

***

## 6. Deliverables

### Files to Create

| File                                                         | Purpose                                                                         | Est. Lines |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------- | ---------- |
| `scripts/lib/knowledge-graph-admin-bridge.ts`                | Admin-gated graphify ingest, remove, status, helpers, and registration          | \~620      |
| `scripts/lib/__tests__/knowledge-graph-admin-bridge.test.ts` | Bridge success and rejection-path tests                                         | \~620      |
| `src/lib/knowledge-graph-admin-types.ts`                     | Typed admin status, ingest, remove, and error response parsers                  | \~260      |
| `src/lib/__tests__/knowledge-graph-admin-types.test.ts`      | Parser tests for status, ingest, remove, and errors                             | \~220      |
| `src/hooks/use-knowledge-graph-admin.ts`                     | Minimal admin hook for status, ingest, remove, duplicate prevention, and gating | \~300      |
| `src/hooks/__tests__/use-knowledge-graph-admin.test.tsx`     | Hook tests for disabled, demo, token, duplicate, success, and error states      | \~300      |

### Files to Modify

| File             | Changes                                                                                                       | Est. Lines |
| ---------------- | ------------------------------------------------------------------------------------------------------------- | ---------- |
| `vite.config.ts` | Import and register `registerKnowledgeGraphAdminBridge` with shared token, admin env, graph paths, and logger | \~18       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `/__graphify_admin_status` reports dev-only admin status without requiring a token and without exposing private graphify candidate paths.
* [ ] `POST /__graphify_ingest` accepts a local path or Git/GitHub URL only behind loopback, `X-Claude-OS-Token`, and `HERMES_DASHBOARD_ADMIN=1`.
* [ ] Git URL ingest validates the URL, shallow-clones to a temp directory, and cleans the temp directory on success and failure.
* [ ] Local path ingest expands `~`, verifies existence, and never shells a path string.
* [ ] `graphify` and `git` run through argv arrays with timeouts and bounded output.
* [ ] Generated graph JSON is parsed, capped at 12,000 nodes, guarded against vendored dependency blowups, and never written when invalid.
* [ ] Registry entries are upserted with absolute `graphPath`, deterministic path-aware ids, collision hashes, metadata, god nodes, provenance, and preserved colors.
* [ ] `DELETE /__graphify_remove?id=` deletes only confined stored graph artifacts and registry entries.
* [ ] `useKnowledgeGraphAdmin()` exposes gated ingest/remove actions and blocks demo, offline, disabled, token-missing, and duplicate-submit states.

### Testing Requirements

* [ ] Bridge tests cover registration, status, method rejection, non-loopback, invalid token, admin-disabled, malformed JSON, oversized body, missing binary, unsafe URL, local path missing, graphify failure, oversized graph, successful local ingest, successful Git ingest, and removal.
* [ ] Parser tests cover valid status, ingest, remove, structured error bodies, future error codes, and malformed payload rejection.
* [ ] Hook tests cover disabled admin, demo mode, offline, token failure, duplicate prevention, successful ingest/remove calls, and error mapping.
* [ ] Focused `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` completed.
* [ ] `bun run typecheck:scripts` and `bun run typecheck` completed or blockers recorded.

### Non-Functional Requirements

* [ ] Browser-visible errors are bounded and do not expose tokens, auth headers, temp paths, local home paths, raw command output, or full source paths.
* [ ] Write operations are idempotent where possible and leave no partial registry entry after a failed ingest.
* [ ] No new runtime dependency is introduced.
* [ ] The read bridge behavior from Session 02 remains unchanged.

### Quality Gates

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

***

## 8. Implementation Notes

### Key Considerations

* Keep upstream endpoint names for compatibility: `/__graphify_ingest` and `/__graphify_remove`. Add `/__graphify_admin_status` for AI OS hook gating.
* Prefer injected command and filesystem helpers in tests so live `git` and `graphify` are not required.
* Do not mutate `src/data/graphs/index.json` until the graph output has parsed, passed size guards, and the graph artifact write is ready to commit.
* Removal should remove the stored dashboard artifact and registry entry only; it must never delete the source repo or temp source path.
* Hook work should stay minimal. Session 06 owns UI controls and copy.

### Potential Challenges

* Absolute registry paths conflict with browser-safe parser expectations: normalize or project responses for browser use while preserving stored absolute `graphPath` for Shared Brain consumers.
* Command failure details can leak paths or secrets: redact and bound output before logging or responding.
* Git URL validation can be too permissive: allow common HTTPS, SSH, `.git`, and `github.com/owner/repo` forms while rejecting whitespace and shell metacharacters.
* Graphify output shape may vary: parse through the Session 01 graph contracts and map unsupported shapes to explicit errors rather than guessing.

### Relevant Considerations

* \[P04] **Hermes bridge guardrails must stay intact**: Keep the admin preflight shape shared with existing Hermes writes and do not add unauthenticated graph mutations.
* \[P24] **Fail-closed bridges need boundary validation**: Validate method, loopback, token, JSON body, path, URL, id, graph output, and registry writes at the boundary.
* \[P25] **Writes stay on the shared admin contract**: Browser writes go through a dedicated admin hook; do not add route-specific fetches or component-owned privileged behavior.
* \[P02] **Typed degradation over throws**: Missing graphify should be a typed unavailable state, while malformed write inputs fail explicitly.
* \[P01] **3D vendor chunk budget**: This session is server/hook work only and must not introduce renderer or 3D imports.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* A malformed URL, id, path, or registry entry escaping the graph directory or deleting the wrong file.
* A failed clone or graphify run leaving temp directories, scratch output, or partial registry state behind.
* UI-facing admin responses exposing private paths or command output.
* Duplicate client triggers starting concurrent ingests or removes.

***

## 9. Testing Strategy

### Unit Tests

* Capture middleware registration and assert status, ingest, and remove routes.
* Assert status returns enabled/disabled gate state and no private path details.
* Assert method, loopback, token, admin-disabled, malformed JSON, oversized body, invalid id, unsafe URL, missing local path, missing graphify, graphify failure, oversized graph, malformed graph, and path escape failures.
* Assert successful local ingest writes the graph artifact and upserts the registry with metadata, god nodes, color, provenance, and absolute graph path.
* Assert successful Git ingest uses `git clone --depth 1`, uses temp cleanup, and stores a stable non-temp source marker.
* Assert removal deletes the stored graph artifact, removes the registry entry, and is safe for missing artifacts.

### Integration Tests

* Verify `vite.config.ts` registers the admin bridge next to the read bridge without changing existing bridge registration order or options.
* Verify hook fetches status, sends tokenized ingest/remove requests, maps structured errors, blocks demo/offline/token-missing states, and prevents duplicate in-flight actions.

### Manual Testing

* With `HERMES_DASHBOARD_ADMIN` unset, confirm status is disabled and ingest is rejected.
* With admin enabled and `graphify` absent, confirm ingest returns a missing binary message rather than crashing.
* With admin enabled and a small fixture graphify output through tests, confirm registry/list behavior remains compatible with the Session 02 read bridge.

### Edge Cases

* Empty path, whitespace path, `~` path, nonexistent path, GitHub shorthand URL, HTTPS Git URL, SSH Git URL, URL with shell metacharacters, duplicate repo basename, generic `src` subdirectory name, missing `graphify-out/graph.json`, graph over 12,000 nodes, registry with existing color, and removal of an already-missing artifact.

***

## 10. Dependencies

### External Libraries

* None new.

### Internal Modules

* `src/lib/knowledge-graph-types.ts` for graph parsing, metadata helpers, and god-node derivation.
* `scripts/lib/hermes-dev-bridge.ts` for shared middleware request/response types.
* `scripts/lib/hermes-admin-bridge.ts` and `scripts/lib/openclaw-admin-bridge.ts` for admin preflight precedent.
* `src/hooks/use-openclaw-admin.ts` and `src/hooks/use-hermes-admin.ts` for hook gating and duplicate-prevention precedent.

### Other Sessions

* **Depends on**: `phase26-session01-graph-data-contracts-seed-fixtures`, `phase26-session02-graph-read-bridge-registry-endpoints`.
* **Depended by**: `phase26-session05-read-hook-route-shell-project-gallery`, `phase26-session06-ingest-ui-connect-prompt-starter-chips`, `phase26-session07-hermes-chat-grounding-graph-toolset`, `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-session03-graph-ingest-removal-admin-bridge/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.
