> 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/phase16-session02-backend-endpoint-parity-write-safety/spec.md).

# Session Specification

**Session ID**: `phase16-session02-backend-endpoint-parity-write-safety` **Phase**: 16 - Hermes v2.3 Port Foundation **Status**: Not Started **Created**: 2026-06-02

***

## 1. Session Overview

This session brings the AI OS Hermes dev and admin bridges to the backend endpoint parity required before any expanded Hermes UI can safely consume v2.3 features. It adds the missing read endpoints for connections, profiles, templates, missions, and documents, then adds the remaining write endpoints for missions, image upload, Pantheon sync, documents, and Obsidian.

The central deliverable is the write-safety foundation. Existing AI OS guardrails already provide loopback checks, per-run token gating, admin mode, redaction, bounded body reads, and argv-array spawn for chat. This session generalizes path confinement into a reusable helper and applies the same contract to every new write path instead of weakening AI OS to match v2.3's looser inline handlers.

The work stays script-side. Client hooks, typed client payloads, demo fixtures, and UI components remain deferred to Session 03 and Phases 17-20 so backend security can be reviewed and tested before browser surfaces call these writes.

***

## 2. Objectives

1. Generalize path confinement into `confinePath(base, userValue)` and reuse it for every file operation handler.
2. Add the five missing Hermes read endpoint families to `scripts/lib/hermes-dev-bridge.ts` with loopback gating and token gating for sensitive profile data.
3. Add the ten missing Hermes write endpoints to `scripts/lib/hermes-admin-bridge.ts` behind method, loopback, token, admin, body, path, spawn, confirmation, and audit safeguards.
4. Extend bridge tests so every new write endpoint has merge-gate coverage for token, loopback, method, body size, traversal, and spawn/git safety where relevant.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase16-session01-guardrails-architecture-parity-baseline` - Confirms the architecture decision, IA decision, current endpoint baseline, and bridge extension points.

### Required Tools/Knowledge

* Bun 1.3.14 and Vitest 4.1.6 through the repo-local `package.json` scripts.
* Phase 16 master reference: `.spec_system/PRD/phase_16/PRD_phase_16.md`.
* Session stub: `.spec_system/PRD/phase_16/session_02_backend_endpoint_parity_write_safety.md`.
* v2.3 source anchors in `/home/aiwithapex/projects/claudeos/claude-os-v2.3/vite.config.ts`.
* Existing bridge tests in `scripts/lib/__tests__/hermes-dev-bridge.test.ts` and `scripts/lib/__tests__/hermes-admin-bridge.test.ts`.

### Environment Requirements

* The AI OS repo is available at `/home/aiwithapex/projects/aios`.
* The v2.3 source root is readable for payload and handler parity checks.
* No dev server is required for implementation; focused Vitest and typecheck commands validate the bridge changes.

***

## 4. Scope

### In Scope (MVP)

* The local operator can read Hermes connections from safe local metadata - add `/__hermes_connections` without exposing secret values or raw private paths.
* The local operator can read Hermes profiles only after token approval - add `/__hermes_profiles` as a sensitive read with bounded command or file parsing and explicit failure fallback.
* The local operator can read Pantheon templates - add `/__hermes_pantheon_templates` from a script-side template catalog aligned with the current persona install/create model.
* The local operator can read mission and document state - add `/__hermes_missions` and `/__hermes_documents` GET/file/trash behavior with bounded listing, deterministic ordering, symlink/path escape refusal, and no-store responses.
* The local operator can run mission writes safely - add mission create, optimize, tick, and clear endpoints with schema-validated input, atomic file updates, idempotency/confirmation where destructive, argv-array spawn, timeout, output cap, and explicit error mapping.
* The local operator can upload images safely - add `/__hermes_image_upload` with content-type allow-list, raw body cap, cache-dir confinement, unique filenames, and sanitized response fields.
* The local operator can run Pantheon sync safely - add `POST /__hermes_pantheon_sync` with mirror confinement, explicit confirmation, argv-array git calls, timeout, output cap, and sanitized audit logging.
* The local operator can mutate documents safely - add document soft-delete, restore, and purge endpoints with reversible trash moves, non-clobbering restore, confirmation for destructive purge, and traversal/symlink refusal.
* The local operator can enable Obsidian memory bridging safely - add `POST /__hermes_obsidian` with an explicit vault-path allow-list, confined symlink/write behavior, confirmation, and fallback errors for denied vaults.
* The next implementation agent can rely on security tests - extend dev and admin bridge tests for endpoint registration, method/loopback/token/body rejection, traversal refusal, spawn/git argv safety, timeout, and redaction.

### Out of Scope (Deferred)

* Client hook queries and mutations - *Reason: owned by Session 03.*
* Client read/write payload parser types - *Reason: owned by Session 03.*
* Demo fixtures for the expanded Hermes page - *Reason: owned by Session 03.*
* Any Hermes UI, tabs, cards, modals, or visual shell changes - *Reason: owned by Phases 17-20.*
* Changing the already-ported chat and persona write behavior except to reuse a shared helper without behavior regression - *Reason: existing writes are already in scope only for helper reuse and regression tests.*

***

## 5. Technical Approach

### Architecture

Extend the existing extracted bridge modules instead of adding middleware back into `vite.config.ts`. `scripts/lib/hermes-dev-bridge.ts` owns read endpoints and `scripts/lib/hermes-admin-bridge.ts` owns admin/write endpoints. Vite continues to register both modules from the existing configureServer wiring.

The write path follows the Phase 16 Write-Path Safety Contract. Every new write calls `requirePreflight(req, options, method, true)` before parsing payloads, uses bounded body readers, validates every external input, confines every file path to its intended base, logs endpoint/outcome only, and returns sanitized errors. Spawn and git execution reuse the chat pattern: known binary resolution, argv arrays, no shell interpolation, timeout, output cap, and redacted stderr.

Read endpoints stay conservative. They return bounded summaries, no raw credentials, no unbounded file contents, and deterministic order. Sensitive profile reads require the token. Document file streaming is loopback-only and path-confined to the documents root, with symlink escapes refused before any bytes are served.

### Design Patterns

* Existing bridge boundary: Keep dev/read logic and admin/write logic in their current modules.
* Reusable path confinement: Replace ad hoc `resolve` plus `relative` checks with one `confinePath` helper and tests.
* Schema-validated request handling: Parse unknown JSON into narrow records, reject invalid fields early, and map errors to stable response codes.
* Atomic private writes: Write mission state through temp-file replacement and keep document deletes reversible by default.
* Args-array process execution: Use argv arrays for Hermes and git calls, never shell strings.
* Security tests as merge gate: Add focused tests before treating endpoints as shippable.

### Technology Stack

* Node HTTP middleware through Vite 8 dev server registration.
* TypeScript 6.0.3 for bridge modules and tests.
* Bun 1.3.14 for scripts and test execution.
* Vitest 4.1.6 for focused bridge coverage.
* Existing `js-yaml`, `sanitize`, and scan helper utilities where applicable.

***

## 6. Deliverables

### Files to Create

| File                                                                                                | Purpose                                                                             | Est. Lines |
| --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ---------- |
| `.spec_system/specs/phase16-session02-backend-endpoint-parity-write-safety/implementation-notes.md` | Implementation evidence, validation results, endpoint inventory, and security notes | \~160      |

### Files to Modify

| File                                                | Changes                                                                                                                                         | Est. Lines |
| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `scripts/lib/hermes-dev-bridge.ts`                  | Add read endpoint types, helpers, endpoint registration, and safe readers for connections, profiles, templates, missions, and documents         | \~350      |
| `scripts/lib/hermes-admin-bridge.ts`                | Add `confinePath`, mission/image/sync/document/Obsidian handlers, spawn/git helpers, audit logging, and helper reuse for existing persona paths | \~550      |
| `scripts/lib/__tests__/hermes-dev-bridge.test.ts`   | Add read endpoint registration, sensitive profile, document confinement, mission, template, and connection tests                                | \~220      |
| `scripts/lib/__tests__/hermes-admin-bridge.test.ts` | Add write-safety tests for new endpoints, path traversal, body caps, confirmation, spawn/git argv safety, timeout, and redaction                | \~420      |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `confinePath(base, userValue)` exists and every file-op handler reuses it.
* [ ] `/__hermes_connections`, `/__hermes_profiles`, `/__hermes_pantheon_templates`, `/__hermes_missions`, and `/__hermes_documents` endpoint families are registered and return bounded v2.3-parity payloads.
* [ ] `/__hermes_profiles` rejects missing or invalid tokens.
* [ ] Mission create/optimize/tick/clear endpoints are registered behind admin preflight and update mission state without traversal or partial-write risk.
* [ ] Image upload accepts only approved image content types, rejects oversized bodies before writing, and writes only inside the confined image cache.
* [ ] Pantheon sync uses confined mirror paths and argv-array git execution.
* [ ] Document delete/restore/purge endpoints soft-delete, restore without clobbering, and permanently purge only after explicit confirmation.
* [ ] Obsidian writes require an explicit vault allow-list and never write outside the selected allowed vault.
* [ ] Logs and responses do not include secret values, raw prompts, command bodies, or unsafe private path details.

### Testing Requirements

* [ ] Focused dev bridge tests cover new endpoint registration and read safety.
* [ ] Focused admin bridge tests cover every new write endpoint's method, loopback, token, admin, body size, traversal, and confirmation behavior.
* [ ] Spawn/git tests prove shell metacharacters remain inert argv elements and runaway processes are killed by timeout.
* [ ] `bun run test -- scripts/lib/__tests__/hermes-dev-bridge.test.ts scripts/lib/__tests__/hermes-admin-bridge.test.ts` passes.
* [ ] `bun run typecheck:scripts` passes.

### Non-Functional Requirements

* [ ] Existing chat and persona behavior does not regress.
* [ ] Endpoint responses remain deterministic, bounded, and no-store where appropriate.
* [ ] The work preserves AI OS host identity and does not introduce browser exposure for secrets or private local-agent internals.
* [ ] No new runtime dependency is required.

### Quality Gates

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

***

## 8. Implementation Notes

### Key Considerations

* `analyze-project.sh --json` selected Phase 16 with Session 01 completed and Session 02 as the next uncompleted candidate.
* Session 03 is blocked until these endpoints exist and have security tests.
* `scripts/lib/hermes-admin-bridge.ts` already has the core security primitives: `requirePreflight`, admin gate, token check, redaction, bounded JSON reads, and chat spawn behavior.
* `scripts/lib/hermes-dev-bridge.ts` already enforces GET-only, loopback-only, and sensitive-token reads through `handleHermesDevBridgeRequest`.
* V23 source line anchors are guidance only; implementation should follow AI OS bridge architecture and tests.

### Potential Challenges

* Scope pressure from ten writes: keep implementations shallow, safe, and backend-only; defer client hook polish to Session 03.
* Raw-body image upload differs from JSON write handlers: use a separate bounded raw reader and content-type allow-list.
* Pantheon sync and mission optimize spawn external processes: reuse the chat spawn pattern, add timeout/output caps, and keep user data as argv.
* Obsidian writes target an external vault: fail closed unless the vault path is explicitly allowed and can be confined.
* Document file serving can expose symlink escapes: resolve real paths or otherwise refuse symlinks before streaming.

### Relevant Considerations

* \[P04] **Hermes bridge guardrails must stay intact**: Every new write remains loopback, token, admin, path, and audit gated.
* \[P08] **Local agent privacy/readiness boundary**: Do not expose raw paths, prompts, transcripts, logs, credentials, command output, workspace content, or auth payloads in responses.
* \[P01] **Old `claude-os-*` naming in code identifiers**: Keep `x-claude-os-token` as the compatibility token header; do not rename it in this session.
* \[P14] **Atomic private writes and path confinement**: Use atomic writes and path confinement for mission state, documents, uploads, and vault writes.
* \[P00] **Stack conventions**: Keep the implementation within Bun, Vite, TypeScript, Vitest, and existing local bridge conventions.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* A write endpoint accepts a traversal or symlink escape and mutates a file outside its intended local root.
* Spawn or git endpoints accidentally pass user input through a shell or leave runaway processes alive.
* Error responses or logs expose raw local paths, prompt text, command output, credentials, or document contents.

***

## 9. Testing Strategy

### Unit Tests

* Extend `scripts/lib/__tests__/hermes-dev-bridge.test.ts` for endpoint registration, GET-only behavior, profile token gating, connection/profile fallback parsing, templates, mission reads, document listing, trash listing, and document file path refusal.
* Extend `scripts/lib/__tests__/hermes-admin-bridge.test.ts` for `confinePath`, mission writes, image upload, Pantheon sync, document delete/restore/purge, Obsidian writes, preflight failures, oversized bodies, traversal attempts, confirmation gates, spawn/git argv, timeout, and sanitized errors.

### Integration Tests

* Use focused middleware invocation tests rather than a running dev server.
* Run `bun run typecheck:scripts` after the bridge implementation.

### Manual Testing

* Optional local smoke after tests: start the Vite dev server with `HERMES_DASHBOARD_ADMIN=1` and call representative endpoints from loopback with the per-run token.

### Edge Cases

* Missing Hermes home should return empty or setup-required style payloads, not throw.
* Missing profile binary, missing mission file, missing mirror repo, missing documents root, and denied Obsidian vault should degrade with explicit response codes.
* `../`, absolute paths, symlinks, hidden files, empty IDs, invalid trash IDs, and oversized request bodies must be rejected.
* Shell metacharacters in mission prompts, git refs, filenames, and vault paths must remain inert data.

***

## 10. Dependencies

### External Libraries

* None new. Reuse Node standard modules, existing `js-yaml`, and existing repo-local helpers.

### Other Sessions

* **Depends on**: `phase16-session01-guardrails-architecture-parity-baseline`
* **Depended by**: `phase16-session03-data-layer-demo-fixtures`, Phase 17 Session 02, Phase 17 Session 03, Phase 18 Session 01, Phase 19 Session 01, and Phase 19 Session 02.

***

## 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/phase16-session02-backend-endpoint-parity-write-safety/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.
