> 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/phase39-session03-registry-validation-and-save-parity/spec.md).

# Session Specification

**Session ID**: `phase39-session03-registry-validation-and-save-parity` **Phase**: 39 - AI Rogue Level Authoring Infrastructure **Status**: Not Started **Created**: 2026-06-30

***

## 1. Session Overview

This session makes malformed AI Rogue level specs and browser-local save ID drift fail fast before any new authored floor is added. Sessions 01 and 02 created the pure level registry and routed current depth decisions through it; the next prerequisite for Session 04 is a validation layer that proves every level reference points at a known runtime catalog entry and every persisted runtime ID remains accepted by the save schema.

The work stays inside AI Rogue runtime, content, save-schema, and tests. It does not add new content, change shipped depth 1-3 gameplay, introduce renderer imports into the registry path, or widen public demo and browser-local storage boundaries.

The plan also prepares the retirement path for future content IDs. Persisted IDs may remain loadable as explicit compatibility entries, but any such entry must be named, tested, and separate from active runtime catalogs.

***

## 2. Objectives

1. Extend `validateAiRogueContentRegistry()` so level specs fail on unknown theme, enemy, protocol, prefab, terminal, objective, music, ambience, pickup, boss, and finale ownership references.
2. Add persisted ID parity coverage for `AiRogueEnemyKind`, `AiRogueSectorThemeId`, `AiRogueProtocolId`, and `AiRogueTerminalId`.
3. Make save-schema persisted ID lists testable while preserving current parser behavior, schema version, browser-local privacy rules, and retired-ID compatibility hooks.
4. Keep content registry and save-schema tests pure TypeScript with no route, renderer, bridge, generated-data, PixiJS, remote content, or public-demo coupling.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase39-session01-baseline-and-registry-skeleton` - Adds the initial level registry and validator.
* [x] `phase39-session02-depth-resolver-migration` - Routes authored depth decisions through level specs and preserves depth 1-3 behavior.

### Required Tools Or Knowledge

* Bun 1.3.14 package/runtime baseline.
* Existing AI Rogue registry files in `src/extensions/ai-rogue/runtime/content/`.
* Runtime catalogs in `entities.ts`, `themes.ts`, `protocols.ts`, `terminals.ts`, `prefabs.ts`, and `audio.ts`.
* Save-schema parser and zod enum shape in `src/extensions/ai-rogue/save-schema.ts`.

### Environment Requirements

* Local repository checkout with dependencies installed or installable through `bun install`.
* Focused validation available through `bunx vitest run` and `bun run typecheck`.

***

## 4. Scope

### In Scope (MVP)

* AI Rogue content authors get clear registry validation failures for unknown level references - harden `validateAiRogueContentRegistry()` and its tests.
* AI Rogue save schemas expose testable persisted ID lists - factor protocol, enemy, terminal, and theme zod enum literals into exported readonly arrays plus explicit empty compatibility arrays for retired IDs.
* Save-schema parity tests fail when an active runtime enemy kind, sector theme, protocol ID, or terminal ID is absent from persisted parser coverage.
* Parity tests allow only documented compatibility extras in save schemas, so retired IDs stay loadable without hiding accidental drift.
* Existing authoring tests prefer level-spec lookups over rotating depth helper behavior while legacy wrappers remain available.
* Import-boundary tests continue to prove the content registry and save schema do not pull route, renderer, bridge, generated-data, or PixiJS modules into shared runtime paths.

### Out Of Scope (Deferred)

* Adding new persisted IDs - Reason: Session 04 reuses current IDs, and later content sessions own deliberate new IDs.
* Adding a fourth playable floor - Reason: Session 04 depends on these gates.
* Removing legacy compatibility helpers - Reason: compatibility exports remain an active Phase 39 migration boundary.
* Splitting all runtime catalogs into new content modules - Reason: the stub says to split catalogs only when expansion or real churn requires it.
* Changing save schema version or migration semantics - Reason: this session validates existing browser-local state rather than introducing a persistence migration.
* Route-visible UI, PixiJS renderer changes, public demo behavior, remote content loading, hosted writes, collectors, analytics, or telemetry - Reason: this is pure runtime and save-schema validation work.

***

## 5. Technical Approach

### Architecture

Keep the AI Rogue content registry pure runtime data. `validate.ts` should continue to consume runtime catalog metadata and return sanitized issue objects with issue codes, paths, level IDs, and depths, but without echoing unsafe source values. Add the missing validation cases around objective and finale ownership, and make each deliberate malformed reference covered by a focused test case.

Keep save-schema ID ownership local to `save-schema.ts`. Do not import runtime catalogs into the parser module. Instead, export readonly persisted-ID arrays from the save-schema module and build zod enums from those arrays. The parity test imports runtime catalogs and save-schema arrays, then asserts active runtime IDs are covered and save-only extras appear only in explicit compatibility arrays.

Use tests, not runtime coupling, to connect catalogs and save schemas. This keeps browser-local persistence parsers stable, avoids renderer or route chunk growth, and gives future content sessions a direct failure when adding or retiring a persisted ID.

### Design Patterns

* Parser-owned constants: Keep zod enum literals next to the parser while making them inspectable by tests.
* Superset parity with explicit compatibility: Runtime active IDs must be in save schemas; save-only IDs must be listed as compatibility IDs.
* Sanitized validation issues: Validation can expose codes and paths, not raw unsafe labels, private paths, tokens, prompts, or generated data.
* Pure runtime registry: Content and validation modules must avoid route, renderer, bridge, generated-data, public-demo, and PixiJS imports.

***

## 6. Deliverables

### Files To Create

| File                                                           | Purpose                                                                            | Est. Lines |
| -------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/__tests__/save-schema-parity.test.ts` | Compare active runtime IDs with save-schema persisted and compatibility ID arrays. | \~140      |

### Files To Modify

| File                                                                 | Changes                                                                                                                                       | Est. Lines |
| -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `src/extensions/ai-rogue/save-schema.ts`                             | Export persisted and compatibility ID arrays; build protocol, enemy, terminal, and theme zod enums from them without changing parse behavior. | \~80       |
| `src/extensions/ai-rogue/runtime/content/types.ts`                   | Add any missing validation issue codes needed for objective or finale ownership.                                                              | \~10       |
| `src/extensions/ai-rogue/runtime/content/validate.ts`                | Harden local reference, objective, music, ambience, pickup, boss, and finale checks with sanitized issue output.                              | \~120      |
| `src/extensions/ai-rogue/runtime/content/__tests__/levels.test.ts`   | Add malformed-reference and authoring-path tests with explicit expected issue codes and no unsafe value echoing.                              | \~120      |
| `src/extensions/ai-rogue/runtime/__tests__/runtime-boundary.test.ts` | Extend import-boundary coverage if needed for registry and save-schema purity.                                                                | \~40       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Deliberately invalid enemy, theme, terminal, protocol, prefab, pickup, objective, music, ambience, boss, or finale ownership references fail registry validation with clear issue codes and paths.
* [ ] Adding a runtime enemy kind, sector theme, protocol ID, or terminal ID without save-schema coverage fails the parity test.
* [ ] Save-only compatibility IDs are allowed only through explicit exported compatibility arrays.
* [ ] Existing depth 1-3 registry and save-schema parse behavior remains unchanged.

### Testing Requirements

* [ ] Focused registry validation tests written and passing.
* [ ] Focused save-schema parity tests written and passing.
* [ ] Runtime boundary test passes or is extended to cover the new imports.
* [ ] `bun run typecheck` passes.

### Non-Functional Requirements

* [ ] Content registry and save-schema code remain route, renderer, bridge, generated-data, public-demo, and PixiJS free.
* [ ] Validation errors stay sanitized and do not echo unsafe private strings.
* [ ] Browser-local save schema version remains `1`.
* [ ] No new runtime content, remote loading, hosted writes, collectors, or public-demo behavior is introduced.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] Primary user-facing surfaces are untouched; no product-surface copy changes are required.

***

## 8. Implementation Notes

### Working Assumptions

* Save-schema parity should be enforced in tests instead of by importing runtime catalogs into `save-schema.ts`: current `save-schema.ts` owns zod browser-local parsers, while runtime catalogs live under `src/extensions/ai-rogue/runtime/`; keeping the parser module independent avoids route or renderer import growth and preserves the current persistence boundary.
* Compatibility arrays can start empty: the Session 03 stub requires old IDs to remain loadable if retired, but the current Phase 39 state has no retired enemy, theme, protocol, or terminal IDs. Empty exported arrays give later sessions a documented place to add retired IDs deliberately.

### Key Considerations

* Session 04 depends on these gates before adding the reused-media fourth floor.
* `protocolForDepth()` keeps legacy fallback behavior outside authored depths, but level-spec tests should prefer `levelSpecForDepth()` and `AI_ROGUE_LEVEL_SPECS`.
* Music and ambience IDs currently have runtime type unions and ambience file metadata; validation can still remain catalog-backed by using available runtime exports and focused tests.
* Protocol and enemy save schemas are named local schemas today, while terminal and theme enums are inline; implementation should preserve behavior while making all four persisted ID lists inspectable.

### Relevant Considerations

* \[P35] **AI Rogue compatibility exports remain**: Keep legacy wrappers and compatibility surfaces until direct consumers migrate and boundary tests stay green.
* \[P30/P32/P34-P35] **Route-lazy runtime ownership scales**: Keep Pixi behind the Play route/local facade and avoid renderer imports in registry or save-schema modules.
* \[P30/P32/P34-P35] **Schema-backed browser-local state works**: Use zod parser defaults and explicit compatibility hooks rather than ad hoc save migrations.
* \[P30/P34-P38] **Visibility gates catch real issues**: Pair focused unit tests, import-boundary checks, typecheck, and ASCII/LF validation before content expansion.
* \[P30/P32/P34-P38] **Do not widen AI Rogue capabilities without review**: Avoid collectors, WebGPU expansion, workers, hosted writes, remote loading, saved audio state, or rejected-art reuse.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Validation can appear complete while missing one authored level reference.
* Save-schema enum drift can silently drop browser-local saved runs after content expansion.
* Tests can hide drift if compatibility IDs are not explicit and audited.

***

## 9. Testing Strategy

### Unit Tests

* Extend `runtime/content/__tests__/levels.test.ts` for malformed theme, enemy, protocol, prefab, terminal, objective, music, ambience, pickup, boss, and finale ownership references.
* Add `save-schema-parity.test.ts` for runtime-to-save ID coverage and compatibility-only extras.
* Extend `runtime-boundary.test.ts` only if the new exports or tests reveal an import boundary not currently covered.

### Integration Tests

* Run the existing `src/extensions/ai-rogue/__tests__/save-schema.test.ts` to confirm parse behavior remains stable.
* Run the existing registry, resolver, and helper tests touched by Sessions 01 and 02 to confirm the validation work did not change depth 1-3 behavior.

### Runtime Verification

* No browser runtime verification is required because the session touches no route-visible UI, PixiJS mounting, controls, audio unlock behavior, or public demo surface.

### Edge Cases

* Unknown references nested under generation, placements, enemy tables, guarantees, objective, and finale metadata.
* Save-schema arrays with active runtime IDs missing.
* Save-schema arrays with extra IDs not listed as compatibility IDs.
* Unsafe labels or lessons that must not be echoed in validation issues.
* Empty compatibility arrays during the current no-retired-ID state.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase39-session01-baseline-and-registry-skeleton` and `phase39-session02-depth-resolver-migration`.
* Depended by: `phase39-session04-existing-media-floor-four`, `phase39-session05-enemy-metadata-and-derived-asset-checks`, and later Phase 39 content, boss, validation, and documentation sessions.

***

## 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/archive/sessions/phase39-session03-registry-validation-and-save-parity/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.
