# Phase 21D - Story Intelligence Illustration Library and Generation Studio

## Summary

Phase 21D hardens the Illustration Library into an admin-controlled generation workflow for reusable Story Intelligence artwork. Library illustrations are representative visual identifiers selected to aid recognition and navigation. They do not define or replace the author's own image of a character, location or asset.

## SQL Script

The Phase 21D migration is:

`PlotLine/Sql/136_Phase21D_IllustrationLibraryGenerationStudio.sql`

It extends the Phase 21C table with Phase 21D names and audit fields, including `DisplayName`, `Description`, `Prompt`, `GenerationAttemptCount`, `ErrorMessage`, `RejectedUtc`, `RejectedByUserID` and `Superseded` status support. It also adds regeneration through `IllustrationLibraryItem_CreateRegeneration`.

## Data Model

`IllustrationLibraryItems` stores durable illustration records:

- Category and stable code
- Display name and description
- Structured specification JSON
- Final prompt and prompt template version
- Provider, model and request metadata
- Status and generation attempt count
- File and thumbnail paths, dimensions, MIME type and file size
- Approval, rejection and lineage fields
- Active flag and timestamps

Categories are `Character`, `Location` and `Asset`.

Statuses are `Planned`, `Queued`, `Generating`, `Generated`, `Approved`, `Rejected`, `Failed`, `Superseded` and the operational disabled state.

## Specification Model

Images are defined by `IllustrationGenerationSpecification`. It contains shared fields plus typed category fields:

- Character: apparent age band, presentation, hair colour, hair length, skin tone, features, clothing era and clothing style.
- Location: location type, era and setting.
- Asset: object type, colour and era.

Validation is centralised on the specification model and exercised by tests.

## Prompt Builder

`IllustrationPromptBuilder` uses template version `21D.1`. It applies one shared style template and category-specific composition rules. It forbids manuscript names, excerpts, visible text, watermarks, logos, anime/cartoon/Pixar-like styling and photoreal identity claims.

## Provider Abstraction

`IIllustrationImageProvider` exposes provider name, model name, configuration status, generation, metadata and failure details. The OpenAI implementation uses the existing server-side `StoryIntelligenceOptions` binding, including:

- `OpenAI:ApiKey`
- `StoryIntelligence:ImageGenerationModel`
- `StoryIntelligence:ImageGenerationSize`

No browser-side image calls are used, and tests do not call the paid Images API.

## Queue Behaviour

Generation runs through `IllustrationGenerationWorker`. It claims persisted queued items with row locks, increments generation attempts and processes one item at a time. Failures are stored per item and do not stop the batch. Attempts are capped in SQL to avoid an infinite retry loop.

## Persistent Storage

Generated images are stored under the persistent uploads root:

`/uploads/story-intelligence-library/{characters|locations|assets}/{stable-code}/`

The service writes WebP source images and 256px thumbnails using SkiaSharp. Existing user uploads for characters, assets, covers and floor plans are unchanged.

## Admin Studio

Route:

`/admin/story-intelligence/illustration-library`

The Studio is protected by the existing `AdminOnly` policy. It provides counts, search, category and status filters, preview, specification JSON, prompt, provider/model data, errors, approval and rejection information, and actions to create starter specs, queue generation, approve, reject, regenerate and disable.

## Starter Specifications

The starter set contains:

- 12 characters
- 6 locations
- 10 assets

They cover varied age bands, presentations, appearances, location types and object types. They are generic reusable specifications, not Alpha Flame-specific artwork.

## Approval And Regeneration

Only approved illustrations can be resolved outside the admin review screen. Regeneration creates a new planned child item and preserves the prior result. Approving a replacement marks any previous approved item for the same stable code as `Superseded`.

## Prototype Integration

`/Development/StoryIntelligenceExperience` resolves images by stable library code. If an approved match exists, it uses the library image. Otherwise, the existing SVG prototype artwork remains the fallback.

The real Story Intelligence pipeline is not connected to this feature in Phase 21D.

## Cost Controls

Generation is admin-only and requires confirmation. The Studio shows image counts rather than invented cost estimates. Normal imports never generate images. Missing provider configuration is shown clearly and does not block application startup.

## Tests

The test harness covers specification validation, prompt construction, category validation, status transitions, path safety and starter-batch counts. Provider calls are not made by automated tests.

## Deployment Permissions

The service account must be able to write under the configured persistent `UploadsRoot`. For local development this is the existing PlotDirector upload storage exposed at `/uploads`.

## First Three Test Images

1. Apply SQL scripts through `136_Phase21D_IllustrationLibraryGenerationStudio.sql`.
2. Open `/admin/story-intelligence/illustration-library`.
3. Choose `Create starter plan`.
4. Confirm image generation configuration is present.
5. Filter or search for one character, one location and one asset.
6. Queue those three items individually.
7. Review the generated images for style, cropping and consistency.
8. Approve, reject or regenerate each image from the Studio.

Do not approve automatically.

## Full Starter Batch

1. Complete the first three-image review successfully.
2. Return to `/admin/story-intelligence/illustration-library`.
3. Confirm `Queue planned items`.
4. Monitor queued, generated and failed counts.
5. Review generated images in the Studio.
6. Approve only images that meet the style, privacy and cropping requirements.

## Deferred CRUD Integration

Future Character, Location and Story Asset pages should support:

1. User-uploaded image
2. User-selected library illustration
3. Automatically suggested library illustration
4. Existing fallback icon

This phase does not redesign those CRUD pages and does not alter existing user-upload behaviour.
