> 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-session02-mission-schema-version-legacy-compatibility/spec.md).

# Session Specification

**Session ID**: `phase25-session02-mission-schema-version-legacy-compatibility` **Phase**: 25 - Hermes Mission Control Activation **Status**: Completed **Created**: 2026-06-08

***

## 1. Session Overview

This session versions Mission Control mission documents and hardens the read normalization layer before Phase 25 adds prompt, authoring, briefing, rail, and archive behavior on top of the mission contract. Session 01 split optimize from commit; Session 02 makes the mission files written by create and commit explicitly versioned and makes older or v2.3-shaped `missions.json` files safe to read through the AI OS envelope.

The work stays inside the existing local Hermes boundary. Browser reads still use `/__hermes_missions`, `src/hooks/use-hermes.ts`, and `src/lib/hermes-types.ts`; admin writes still use the loopback, token-gated, admin-enabled bridge in `scripts/lib/hermes-admin-bridge.ts` and the typed admin parsers in `src/lib/hermes-admin-types.ts`. Raw v2.3 endpoint envelopes are not exposed as an AI OS browser contract.

The plan also records a state repair. The analysis script initially reported Session 01 as incomplete because `.spec_system/state.json` had a stale `completed_sessions` array, while the Phase 25 PRD, session stub, state history, spec artifacts, and validation report all recorded Session 01 as completed with PASS. Session 02 is therefore the next real unblocked session, and the state file is synchronized to recognize the completed prerequisite.

***

## 2. Objectives

1. Add a current `schema_version` field to mission documents returned by read endpoints and written by create, optimize preview, commit, tick, and clear flows.
2. Normalize legacy and v2.3-shaped mission stores safely, including missing version, missing optional goal fields, unknown statuses, malformed entries, and active-pointer mismatches.
3. Keep the AI OS `/__hermes_missions` envelope authoritative while documenting the raw v2.3 store and endpoint incompatibility.
4. Cover schema and legacy permutations with focused bridge, parser, fixture, and quality-gate tests.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase25-session01-mission-write-contract-preview-commit` - provides the preview-to-commit write boundary, new commit endpoint, and PASS validation for optimize no-write behavior.

### Required Tools/Knowledge

* Bun 1.3.14 project toolchain.
* Vitest for script bridge and parser coverage.
* Existing Hermes mission read bridge in `scripts/lib/hermes-dev-bridge.ts`.
* Existing Hermes admin write bridge in `scripts/lib/hermes-admin-bridge.ts`.
* Existing read/admin parser contracts in `src/lib/hermes-types.ts` and `src/lib/hermes-admin-types.ts`.
* Phase 25 folded v2.3 comparison anchors for mission file shape and endpoint behavior.

### Environment Requirements

* Work from the repository root.
* No live Hermes credentials are required; fixture-backed `missions.json` files and existing bridge test harnesses cover this session.
* Generated private Hermes data, `.env*`, logs, token-bearing values, and local mission files remain out of git.

***

## 4. Scope

### In Scope (MVP)

* Mission documents expose `schema_version` in AI OS read and admin contracts - implement as an additive field with a current constant and parser coverage.
* Mission create, optimize preview, and commit produce current-version mission documents - add the field at the write-document creation boundary.
* Legacy mission files without `schema_version` load safely and upgrade in memory - default missing versions to the current schema before browser output.
* Existing mission stores persist upgraded shapes on the next write - normalize mission records when the admin bridge reads the store before create, commit, tick, or clear writes.
* v2.3-shaped stores load without throwing - support `{ active, missions }` files with optional `full_prompt`, optional `estimate`, no schema version, and loose statuses.
* Malformed mission entries remain contained - skip invalid archived entries, null invalid active pointers, bound mission counts, and keep deterministic ordering.
* Documentation names the AI OS envelope and explicitly notes that raw v2.3 `{ mission }` endpoint responses are not the browser contract.

### Out of Scope (Deferred)

* New UI affordances - Reason: Session 04 owns optimized preview UI and multi-goal authoring.
* New write endpoints beyond Session 01 commit - Reason: this session hardens existing read/write contracts only.
* Full storage migration away from `~/.hermes/missions.json` - Reason: this phase only versions the current local file contract.
* Rendering `schema_version` in Mission Control cards - Reason: it is a contract field, not an operator-facing workflow affordance.
* Raw v2.3 endpoint-envelope support in the browser parser - Reason: AI OS owns the richer `{ ok, active, mission, total, missions }` envelope.

***

## 5. Technical Approach

### Architecture

Use the bridge layer as the resource boundary. Define the current mission schema version close to the mission normalization and write helpers, then return typed mission summaries with `schema_version` from `scripts/lib/hermes-dev-bridge.ts`. Keep the read endpoint output inside the AI OS envelope and continue sanitizing mission strings before they reach browser state.

In `scripts/lib/hermes-admin-bridge.ts`, make `createMissionDocument` write the current schema version for new mission candidates. Harden `readMissionStore` so existing records are parsed through the same shape-normalization rules before a later create, commit, tick, or clear persists them. Store writes continue using `writeAtomicJson`, the resolved Hermes home, and existing path confinement.

Client contracts stay explicit. `src/lib/hermes-types.ts` and `src/lib/hermes-admin-types.ts` should surface `schema_version`, reject malformed required fields, and keep exhaustive handling for mission actor and status values. Demo fixtures and docs move with the contract so parser tests and operator documentation stay aligned.

### Design Patterns

* Additive contract versioning: legacy payloads gain safe defaults instead of breaking existing local files.
* Boundary validation: malformed local file entries are contained before browser output or persisted rewrites.
* Atomic file writes: upgraded stores persist only through the existing `writeAtomicJson` path.
* Deterministic projection: archived mission lists stay bounded and sorted for stable UI and tests.
* Contract-first tests: add legacy fixture permutations before relying on later UI sessions.

### Technology Stack

* TypeScript 6.0.3.
* Bun 1.3.14.
* React 19 and TanStack Query 5 via existing hooks.
* Vitest 4.1.6 for bridge, parser, and fixture coverage.
* Vite 8 local middleware bridge modules under `scripts/lib/`.

***

## 6. Deliverables

### Files to Create

| File                                                                                                       | Purpose                                               | Est. Lines |
| ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | ---------- |
| `.spec_system/specs/phase25-session02-mission-schema-version-legacy-compatibility/implementation-notes.md` | Implementation notes, command results, and decisions. | \~80       |
| `.spec_system/specs/phase25-session02-mission-schema-version-legacy-compatibility/security-compliance.md`  | Session security and compliance review.               | \~80       |

### Files to Modify

| File                                                | Changes                                                                                 | Est. Lines |
| --------------------------------------------------- | --------------------------------------------------------------------------------------- | ---------- |
| `scripts/lib/hermes-dev-bridge.ts`                  | Add mission schema version projection and hardened legacy normalization.                | \~130      |
| `scripts/lib/hermes-admin-bridge.ts`                | Write schema version on create/optimize/commit and normalize store reads before writes. | \~120      |
| `src/lib/hermes-types.ts`                           | Add `schema_version` to mission read types and parser.                                  | \~25       |
| `src/lib/hermes-admin-types.ts`                     | Add `schema_version` to admin mission document types and parser.                        | \~25       |
| `src/lib/hermes-demo-data.ts`                       | Add schema version to demo mission fixtures.                                            | \~10       |
| `docs/data-contract.md`                             | Document mission schema version, AI OS envelope, and v2.3 incompatibility.              | \~45       |
| `scripts/lib/__tests__/hermes-dev-bridge.test.ts`   | Cover legacy stores, malformed entries, active mismatch, and sanitized upgrades.        | \~170      |
| `scripts/lib/__tests__/hermes-admin-bridge.test.ts` | Cover schema version persistence and legacy-store upgrade on writes.                    | \~130      |
| `src/lib/__tests__/hermes-types.test.ts`            | Cover read parser schema version requirements and malformed mission payloads.           | \~50       |
| `src/lib/__tests__/hermes-admin-types.test.ts`      | Cover admin parser schema version requirements across write responses.                  | \~50       |

***

## 7. Success Criteria

### Functional Requirements

* [x] Mission documents returned from `/__hermes_missions` include `schema_version`.
* [x] Mission documents written by create, optimize preview, and commit include the current schema version.
* [x] Legacy mission documents without `schema_version` load with a current default in browser-visible output.
* [x] Unknown goal statuses normalize to `queued`.
* [x] Missing `full_prompt`, `estimate`, `done_when`, `deadline_iso`, `created_at`, and `image_path` fields do not break parsing or expose bad browser state.
* [x] Malformed archived mission entries are skipped without throwing.
* [x] Invalid active pointers return `active: null` and `mission: null` while preserving valid archived mission summaries.
* [x] The next admin write persists upgraded mission shapes through the atomic store writer.
* [x] Docs state that AI OS supports v2.3-shaped on-disk stores, not raw v2.3 `{ mission }` endpoint envelopes.

### Testing Requirements

* [x] `scripts/lib/__tests__/hermes-dev-bridge.test.ts` covers all legacy and malformed read permutations.
* [x] `scripts/lib/__tests__/hermes-admin-bridge.test.ts` covers schema persistence and upgraded-store writes.
* [x] `src/lib/__tests__/hermes-types.test.ts` covers the read parser contract.
* [x] `src/lib/__tests__/hermes-admin-types.test.ts` covers the admin parser contract.
* [x] Focused Vitest runs pass.

### Non-Functional Requirements

* [ ] Admin gate strength is unchanged; no new tokenless write path appears.
* [ ] Local private paths, token-shaped values, and raw mission file parse failures stay out of browser-visible errors and logs.
* [ ] Mission list output remains bounded by `MAX_MISSION_COUNT` and sorted deterministically.
* [ ] Store writes remain atomic and confined to the resolved Hermes home.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] `bun run typecheck` passes.
* [ ] `bun run typecheck:scripts` passes.

***

## 8. Implementation Notes

### Key Considerations

* The state history, Phase 25 PRD, session stub, and validation report already record Session 01 as completed. This plan treats that as the completed prerequisite and synchronizes the state array accordingly.
* `schema_version` should be an additive field. Do not require operators to manually migrate existing `~/.hermes/missions.json` files.
* The read bridge and admin bridge have separate local type declarations today. Keep changes local to those files unless implementation shows a real need for a shared module.
* Mission strings must continue through existing sanitization helpers before browser output.

### Potential Challenges

* Parser strictness versus legacy tolerance: keep bridge normalization tolerant, but keep browser/admin response parsers strict after normalization.
* Active pointer ambiguity: return no active mission if the pointer is invalid, while still surfacing valid archived mission summaries.
* Store rewrite timing: upgrade legacy records in memory on read, then persist only on existing authorized writes so read-only bridge calls do not mutate local files.

### Relevant Considerations

* \[P04] **Hermes bridge guardrails must stay intact**: Keep loopback, token, no-clobber path safety, and disabled-by-default admin mode unchanged.
* \[P20] **Long-tail Hermes surfaces stay modular and prop-driven**: Keep the Mission Control contract focused so later UI sessions can reuse the same typed data.
* \[P23] **Hermes hook reuse for related agent routes**: Hermes and Claude Code consume the same mission contract; do not fork parser behavior by route.
* \[P17] **Reuse existing hook contracts for write surfaces**: Keep writes in the admin bridge and hook layer, not component-level fetches.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Local mission files with legacy or malformed records could break the route before the operator can recover.
* A schema upgrade could accidentally mutate local mission files from a read-only endpoint.
* Parser or fixture drift could leave Hermes and Claude Code route variants rendering different mission shapes.

***

## 9. Testing Strategy

### Unit Tests

* Add bridge tests for v2.3-shaped stores, missing schema versions, missing optional goal fields, unknown statuses, malformed entries, and invalid active pointers.
* Add admin bridge tests for schema version persistence on create, optimize preview, commit, and upgraded legacy stores persisted by later writes.
* Add parser tests for read and admin mission payloads with valid and malformed `schema_version` fields.

### Integration Tests

* Run focused Vitest files for Hermes read bridge, admin bridge, read parser, admin parser, and affected demo fixture parser coverage.
* Run TypeScript and script TypeScript checks after contract changes.

### Manual Testing

* Review `/agents/hermes` and `/agents/claude-code` mission fixture behavior if parser or demo fixture changes affect visible output.
* Inspect docs and session artifacts for ASCII-only content and LF line endings.

### Edge Cases

* `missions.json` is absent, empty, malformed JSON, or too large.
* `active` points to a missing or skipped mission.
* `missions` is not an object or contains invalid values.
* A mission lacks `schema_version`, `deadline_iso`, `created_at`, or `image_path`.
* A goal lacks `full_prompt`, `estimate`, `done_when`, `num`, or `status`.
* A goal has unknown actor or status values.
* More than the bounded mission count exists.

***

## 10. Dependencies

### External Libraries

* None.

### Other Sessions

* **Depends on**: `phase25-session01-mission-write-contract-preview-commit`
* **Depended by**: `phase25-session03-safe-planning-prompt-authorized-write`, `phase25-session04-multi-goal-authoring-preview-ui`, `phase25-session05-full-prompt-drawer-copy-briefings`, `phase25-session06-active-mission-rail-progress`, `phase25-session07-mission-archive-actions`, `phase25-session08-claude-code-parity-responsive-e2e`, `phase25-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/phase25-session02-mission-schema-version-legacy-compatibility/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.
