> 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/phase25-session01-mission-write-contract-preview-commit/spec.md).

# Session Specification

**Session ID**: `phase25-session01-mission-write-contract-preview-commit` **Phase**: 25 - Hermes Mission Control Activation **Status**: Not Started **Created**: 2026-06-08

***

## 1. Session Overview

This session fixes the Mission Control write contract before Phase 25 adds more authoring and execution UI. The current optimize path returns a mission-shaped success through the admin hook and the UI treats it like persisted active state, which creates ambiguous silent-success behavior. The new contract must make optimize return a non-persisted preview and require an explicit commit to write and activate a mission.

The work stays inside the existing AI OS safety model. Writes remain routed through `scripts/lib/hermes-admin-bridge.ts`, parsed through `src/lib/hermes-admin-types.ts`, and exposed through `useHermesAdmin`; no component-level bridge fetches or tokenless endpoints are introduced. The admin gate remains loopback plus per-run `X-Claude-OS-Token`, `HERMES_DASHBOARD_ADMIN=1`, non-demo mode, and hook-mediated browser access.

This is the first Phase 25 session because later schema, prompt, multi-goal UI, copy, rail, archive, parity, and documentation sessions depend on a reliable preview-to-commit write boundary.

***

## 2. Objectives

1. Prove the optimize silent-success gap with focused bridge coverage.
2. Change optimize to return an explicit non-persisted preview envelope.
3. Add an admin-gated commit endpoint that validates, persists, and activates a mission through the existing mission store writer.
4. Split admin types and hook mutations so optimize previews do not invalidate active mission reads, while commit/create/tick/clear still do.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase19-session01-mission-control-write` - existing Mission Control create, optimize, tick, clear, hook, and component write surfaces exist.
* [x] `phase23-session01-claude-code-agent-route` - Claude Code presentation reuses the Hermes Mission Control contract.
* [x] `phase24-session09-end-to-end-validation-release-hardening` - Phase 24 closeout leaves the repository ready for the Phase 25 Mission Control activation phase.

### Required Tools/Knowledge

* Bun 1.3.14 project toolchain.
* Vitest for script, type-parser, hook, and component coverage.
* Existing Hermes admin bridge preflight and mission store helpers.
* Existing React Query invalidation keys under `HERMES_QUERY_KEYS`.
* Phase 25 folded v2.3 comparison anchors for mission endpoint semantics.

### Environment Requirements

* Work from the repository root.
* No live Hermes credentials are required for focused tests; spawn behavior can use existing mocks in `hermes-admin-bridge.test.ts`.
* Generated private Hermes data, tokens, `.env*`, logs, and local mission files remain out of git.

***

## 4. Scope

### In Scope (MVP)

* Mission operators can run optimize and receive a typed preview candidate instead of a persisted active mission - implement with a `preview: true` discriminator and no `missions.json` write.
* Mission operators can commit an optimized or authored mission candidate through an explicit admin-gated endpoint - validate payload shape, mission ID, goal IDs, atomic store write, and active pointer update.
* Hermes admin bridge tests prove optimize does not mutate `missions.json` and commit persists and activates through the same guarded writer.
* Hermes admin parser tests prove preview, commit, malformed payload, and discriminator cases are accepted or rejected consistently.
* Hermes admin hook exposes `commitMission`, keeps duplicate-trigger prevention, and invalidates mission reads only after persisted writes.
* Existing Mission Control optimize call sites stop claiming active-state persistence until the Session 04 preview UI lands.
* Bridge inventory and preflight tests include the new commit endpoint and rejection paths for closed admin mode, failed token, non-loopback requests, bad method, and malformed body.

### Out of Scope (Deferred)

* Rendering optimized previews in the Mission Control UI - Reason: Session 04 owns preview display, commit, and discard controls.
* Adding mission schema version fields - Reason: Session 02 owns versioned storage and legacy normalization.
* Restoring long-form planning prompts or authorized snippets - Reason: Session 03 owns prompt and safe agent-authored write flow.
* Adding archive set-active behavior - Reason: Session 07 owns archive actions.
* Weakening or bypassing the admin preflight - Reason: Phase 25 explicitly preserves the existing write authorization model.

***

## 5. Technical Approach

### Architecture

The bridge remains the boundary closest to the resource. Add `/__hermes_missions/commit` to the admin endpoint registry beside create, optimize, tick, and clear. The endpoint should reuse `requirePreflight`, `readJsonBody`, `createMissionDocument`, `readMissionStore`, and `writeMissionStore` so validation, ID confinement, atomic JSON writes, and bounded error handling stay centralized.

Optimize should continue to shell out through the existing argv-array Hermes spawn path and `extractJsonObject`, but it must return a preview envelope and must not read or write the mission store. Commit should accept a candidate in a declared request shape, normalize it through `createMissionDocument`, store it under the validated mission ID, set `active`, and return the persisted mission.

Client types should distinguish `HermesMissionOptimizeBody` from `HermesMissionWriteBody`. The hook should add a commit mutation, keep the existing scoped in-flight guard, and remove optimize success invalidation because optimize is no longer a persisted write. The current component optimize handler should avoid user-facing copy that implies the preview has become active until Session 04 adds the full preview UI.

### Design Patterns

* Boundary validation: parse and reject malformed commit bodies in the bridge before store writes.
* Explicit state machine: preview and persisted write responses use different discriminators and parsers.
* Hook-mediated writes: UI callers continue using `useHermesAdmin` instead of raw fetches.
* Query invalidation after persistence only: optimize preview does not invalidate active mission reads.
* Focused tests first: add regression coverage before changing optimize behavior.

### Technology Stack

* TypeScript 6.0.3.
* Bun 1.3.14.
* React 19 and TanStack Query 5.
* Vitest 4.1.6 with Testing Library for hook and component coverage.
* Vite 8 local middleware bridge modules under `scripts/lib/`.

***

## 6. Deliverables

### Files to Create

| File                                                                                                 | Purpose                                               | Est. Lines |
| ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | ---------- |
| `.spec_system/specs/phase25-session01-mission-write-contract-preview-commit/implementation-notes.md` | Implementation notes, command results, and decisions. | \~80       |
| `.spec_system/specs/phase25-session01-mission-write-contract-preview-commit/security-compliance.md`  | Session security and compliance review.               | \~80       |

### Files to Modify

| File                                                              | Changes                                                                                   | Est. Lines |
| ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ---------- |
| `scripts/lib/hermes-admin-bridge.ts`                              | Add preview response, commit endpoint, endpoint registry entry, and store-write behavior. | \~160      |
| `src/lib/hermes-admin-types.ts`                                   | Add commit request/body types, optimize preview body type, and parser coverage hooks.     | \~100      |
| `src/hooks/use-hermes-admin.ts`                                   | Add `commitMission`, split optimize preview mutation from persisted write invalidation.   | \~90       |
| `src/components/hermes/hermes-mission-control.tsx`                | Stop optimize feedback and refresh behavior from implying persisted active state.         | \~35       |
| `scripts/lib/__tests__/hermes-admin-bridge.test.ts`               | Cover optimize no-write, commit persistence, preflight rejection, and endpoint inventory. | \~180      |
| `src/lib/__tests__/hermes-admin-types.test.ts`                    | Cover preview, commit, malformed payloads, and discriminator parsing.                     | \~90       |
| `src/hooks/__tests__/use-hermes-admin.test.tsx`                   | Cover commit mutation, optimize no invalidation, and duplicate mission write prevention.  | \~120      |
| `src/components/hermes/__tests__/hermes-mission-control.test.tsx` | Cover optimize preview feedback without active-state claim if component copy is touched.  | \~60       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `POST /__hermes_missions/optimize` returns `{ ok: true, preview: true, mission }`.
* [ ] Optimize never creates, replaces, or mutates `missions.json`.
* [ ] `POST /__hermes_missions/commit` validates a mission candidate, persists it, and sets it active.
* [ ] Commit rejects closed admin mode, missing or invalid token, non-loopback requests, bad method, oversized or malformed body, invalid mission ID, and invalid goal payloads.
* [ ] `useHermesAdmin().missions.commitMission` persists and invalidates mission reads after success.
* [ ] `useHermesAdmin().missions.optimizeMission` returns a preview and does not invalidate active mission reads.
* [ ] Mission Control optimize feedback no longer states or implies that the optimized mission is already active.

### Testing Requirements

* [ ] Bridge tests pass for mission create, optimize, commit, tick, clear, and preflight rejection paths.
* [ ] Admin type-parser tests pass for preview and commit response payloads.
* [ ] Admin hook tests pass for optimize preview, commit invalidation, and duplicate-trigger prevention.
* [ ] Component test updates pass if Mission Control copy or handler behavior is touched.

### Non-Functional Requirements

* [ ] Admin gate strength is unchanged and tested at the bridge boundary.
* [ ] Token-shaped values and local private paths do not appear in browser state, logs, errors, or generated artifacts.
* [ ] Mission store writes remain atomic and confined to the resolved Hermes home.
* [ ] Demo mode never triggers real mission writes.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] `bun run test -- scripts/lib/__tests__/hermes-admin-bridge.test.ts src/lib/__tests__/hermes-admin-types.test.ts src/hooks/__tests__/use-hermes-admin.test.tsx` passes or any blocker is recorded.

***

## 8. Implementation Notes

### Key Considerations

* `handleMissionOptimizeRequest` already builds a mission candidate from Hermes stdout. The fix is to return that candidate as a preview and avoid any store mutation or active-state invalidation.
* `createMissionDocument` centralizes mission validation and safe ID generation. Commit should reuse it rather than introducing a parallel mission parser in the bridge.
* `useHermesAdmin` currently uses the same write response parser and success invalidation for optimize and create. This is the main client contract split.
* `HermesMissionControl` currently calls `invalidateMissions()` after optimize. That should stop until Session 04 adds the visible preview and commit flow.

### Potential Challenges

* Parser drift: Keep bridge response types and browser parser types aligned by adding tests in the same session.
* Ambiguous candidate source: Commit should accept a declared mission candidate shape and normalize it consistently whether it came from optimize or manual authoring.
* Backward expectations in component tests: Update only the optimize feedback path needed to prevent false active-state messaging.
* Accidental token exposure: Reuse existing admin fetch and error helpers, and avoid logging request bodies.

### Relevant Considerations

* \[P04] **Hermes bridge guardrails must stay intact**: Commit is a new sensitive write and must keep loopback, token checks, path safety, and disabled-by- default admin mode.
* \[P20] **Long-tail Hermes surfaces stay modular and prop-driven**: Keep the Mission Control component focused and do not collapse bridge behavior into UI code.
* \[P23] **Hermes hook reuse for related agent routes**: Hermes and Claude Code presentations must keep sharing the same hook/admin contract.
* \[P17] **Reuse existing hook contracts for write surfaces**: Extend `useHermesAdmin` instead of introducing component-local fetch paths.
* \[P21] **Do not let token-shaped strings or auth headers reach browser state or logs**: Commit and optimize errors must remain bounded and redacted.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* Optimize appears successful while no active state actually changed.
* Commit writes bypass part of the admin preflight or accepts malformed mission candidates.
* Hook mutation state or duplicate-trigger prevention regresses during the preview/commit split.

***

## 9. Testing Strategy

### Unit Tests

* Add bridge tests proving optimize returns a preview and leaves `missions.json` absent or unchanged.
* Add bridge tests proving commit persists a valid candidate and activates it.
* Add parser tests for `parseHermesMissionOptimizeResponse`, `parseHermesMissionWriteResponse`, and malformed discriminator cases.

### Integration Tests

* Add hook tests for optimize preview without mission-query invalidation.
* Add hook tests for commit success with mission-query invalidation.
* Add route inventory/preflight tests for the new commit endpoint.

### Manual Testing

* Run the focused Vitest command for bridge, parser, hook, and any touched component tests.
* If running the dev UI manually, confirm optimize feedback does not claim the preview became active before Session 04 preview UI exists.

### Edge Cases

* Missing token, invalid token, remote address, admin disabled, bad method, and oversized body.
* Empty optimize input, timeout, nonzero Hermes spawn exit, and invalid JSON stdout.
* Commit body missing `mission`, invalid mission ID, empty `mini_goals`, too many goals, malformed goal entries, and duplicate trigger while a mission write is pending.
* Existing `missions.json` with a different active mission should be replaced atomically only after commit succeeds.

***

## 10. Dependencies

### External Libraries

* TanStack Query: Existing mutation and invalidation behavior.
* Vitest and Testing Library: Focused script, parser, hook, and component tests.
* Node `fs/promises`, `path`, and `crypto`: Existing bridge store and ID helpers.

### Internal Dependencies

* `scripts/lib/hermes-admin-bridge.ts` mission store helpers.
* `src/lib/hermes-admin-types.ts` parser utilities.
* `src/hooks/use-hermes-admin.ts` scoped mutation guard and query invalidation.
* `src/components/hermes/hermes-mission-control.tsx` existing optimize call site.

### Other Sessions

* **Depends on**: `phase19-session01-mission-control-write`, `phase23-session01-claude-code-agent-route`, `phase24-session09-end-to-end-validation-release-hardening`
* **Depended by**: Phase 25 Sessions 02, 03, 04, 07, 08, and 09.

***

## 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/phase25-session01-mission-write-contract-preview-commit/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.
