The Implementation Plans

This project was built as a series of implementation plans, where every plan was written out in great detail before a round of work would begin. It would lay out the phases, the files each would touch, and the decisions made up front. This appendix documents the whole history, from the first plan to the last.

I ended up creating seven of these plans. Each one took the application to a new level with new features or improvements. During the planning the AI is like a real collaborator - communicating ideas back and forth, helping you organize your thoughts, asking about things you might not have thought about yet. When the AI sees the bigger picture it can make better decisions about the implementation. It can catch problems before they happen and the code ends up being better organized. Most of my time was spent reviewing and revising these plans. Once good, the AI worked through the entire plan in one pass - no constant confirmations, no surprises. In most cases the implementations were successful on the first try.

Plan 1 - Foundation & Setup

Phased rollout with dependencies mapped. Each phase builds on the previous one.

Phase 0 - Foundation (Database + Config)

Get all database changes in place and configure AI service credentials.

Tasks:

Phase 1 - Draft/Published System (WordPress-style)

Stories have a status. Only published stories are publicly visible. The editor always shows a single version - authors never see “shadow draft” as a concept. Editing a published story creates a shadow draft behind the scenes, but the editor simply presents the story as being in Draft state with Revert / Publish options.

Tasks:

Phase 2 - Story Summary Page + Social Features

New summary page between gallery and play. Ratings, favourites, comments, views all working.

Tasks:

Phase 3 - AI Job Queue Infrastructure

The job queue works end to end. A job can be created, auto-applied by cron, and the user is notified via the header badge.

Tasks:

Phase 4 - Level 1: AI Image Generation

Authors can generate images for scenes using AI.

Tasks:

Phase 5 - Level 2: AI Scene Generation

Authors can generate a complete scene (title, description, hint, choices) with AI.

Tasks:

Phase 6 - Level 3: AI Full Story Generation

Authors can generate a complete branching story from a premise.

Tasks:

Phase 7 - UI Redesign

Updated navigation bar and polished UI across all pages.

Tasks:

Suggested Build Order

Phase 7 tasks can be interleaved at any point - they’re cosmetic and don’t block other work.


Testing Checkpoints

After each phase, verify:

Plan 2 - UI & Feature Enhancements

Continues from 1 (Phases 0–7). All phases below build on the completed foundation.

Guest User Convention

Any interactive element that requires a login (favouriting, rating, commenting) must still be visible to guests but non-functional. On click, redirect to login.php. Never silently fail or hide the element - guests should understand the feature exists and that logging in unlocks it. Read-only features (search, browse, play, view counts, average ratings) work for everyone.


Phase 8 - Cosmetic Fixes & Quick Wins

Scattered low-effort improvements that can be verified in isolation.

Tasks:

Phase 9 - Navigation & Account Restructuring

Streamline the header, move misplaced sections, and fix the live-polling bug.

Tasks:

My Favourites as a first-class filter, story search, and interactive heart icons on cards.

Tasks:

Phase 11 - Summary Page Adjustments

Consolidate the favourite button and reposition the star rating.

Tasks:

Phase 12 - Story Editor - Scene Card Redesign

Scene cards show a thumbnail, metadata, and choices instead of just a title row.

Tasks:

Phase 13 - Scene Editor Enhancements

Rich text editing for scene descriptions; inline AI image generation with quality control.

Tasks:

Phase 14 - Create Story - Tabbed AI Generator

New-story and edit-story-properties pages gain a two-step AI generation flow; generate_story.php is retired.

Tasks:

Phase 15 - Job Notification Grouping

Users get one notification when a story or scene is fully done - not one per child image job.

Tasks:

Phase 16 - Play Page - Sticky Layout

Title and scene image remain on screen while long descriptions and choices scroll.

Tasks:

Suggested Build Order

Phase 16 has no dependencies beyond the base app and can be slotted in anywhere after Phase 8.

Plan 3 - AI Integration Redesign

Overview

This plan replaces the earlier two-tab story properties redesign with a broader rework of how AI is integrated across all editor pages. Key design principles:


Phase 17 - Admin Settings Table & Config Migration

Foundation phase. All subsequent phases that reference configurable values (model selection, pricing, job settings, site title) read from this table instead of config.php. Implement this before any other phase.

Tasks:

Phase 18 - Story & Scene AI Integration Redesign

AI toggle off: Checkboxes hidden, all fields editable normally. Form saves manually.

Flows

Create Story with AI
Scene AI Modal

Task breakdown

18.1 - Form field reorder

Reorder the story properties form fields on both Create New Story and Edit Story Properties:

New order: Theme → Layout → Story Title → Description → Story Thumbnail

This puts Theme and Layout directly below the AI settings section (when visible) so randomized values are immediately adjacent to the dropdowns that show them.

18.2 - Create New Story: AI toggle + settings section

Randomization pools:

18.3 - Create New Story: “Use AI” checkboxes

When #story-ai-section is visible:

Thumbnail checkbox special behaviour: - If an image filename is already present when the thumbnail checkbox is checked: show a confirm dialog This will replace the existing image. Continue? - Cancel: leaves checkbox unchecked - OK: collapse #story-thumb-ai-expand if open; set filename field to readonly + gray; disable [✨ AI] button; placeholder generated - When thumbnail checkbox is unchecked: restore filename field and [✨ AI] button

When #story-ai-section is hidden (AI toggled off): all checkboxes hidden, all fields editable.

18.4 - Story Thumbnail [✨ AI] button (Create + Edit Story pages)
18.5 - Create button: story creation + job queuing

On form submit when AI toggle is on:

  1. Collect which checkboxes are checked (array of field names)
  2. POST to a new api_create_story_ai.php endpoint:
    • All form field values (for context)
    • Checked fields list
    • AI settings (genre, tone, scene count, endings, word length, image quality)
  3. Endpoint creates story record (status = draft), saves unchecked field values, leaves checked fields NULL, inserts create_story job row, returns { ok: true, storyID: X }
  4. JS shows alert() with submission message
  5. On acknowledgement: window.location = 'index.php'

When AI toggle is off: form submits normally via POST (existing save_story handler); no change to current create-story flow.

18.6 - Edit Story Properties: simplify
18.7 - Scene pages: AI modal button
18.8 - Scene Thumbnail [✨ AI] button (scene pages)

Same pattern as task 18.4 but for scene pages:

18.9 - New job type: create_story

New cron handler to process create_story jobs. Extend ai_worker.php to route this type.

Job payload (stored in jobs.input_json JSON):

Handler phases (cron/ai_story_handler.php extended or new file):

  1. Properties phase (if generate_fields is non-empty):
    • Call Claude with genre + tone + context values → generate only the checked fields
    • Update story record with generated values
  2. Story plan phase:
    • Call Claude with final title + description + AI settings → story outline (scene titles + summaries)
  3. Scene write phase:
    • For each scene in the plan: write full scene content
    • Insert scene rows into DB
  4. Apply phase (ai_apply.phpapply_create_story_result()):
    • Mark parent job complete
    • If image_quality !== 'none': queue one scene_image child job per scene
    • If generate_cover === true: queue one story_cover child job
18.10 - Remove old structure

Remove from editor.php: - .story-form-tabs markup and the two tab wrapper divs - #ai-premise textarea - Generate Story Properties, Generate Scenes, Generate Everything buttons - Any “how it works” explanation paragraph from the old Tab 2

Remove from editor JS: - switchStoryTab() - generateProperties() - generateScenes() - generateEverything() - randomizeAll() → replaced by randomizeStoryAI() (task 18.2)

api_ai_properties.php - no longer called from the UI after this phase (new flow is async via api_create_story_ai.php). Move to retired/ - see task 18.12.

18.11 - CSS updates

Remove / deprecate: - .story-form-tabs, .story-tab-btn (keep in file but comment as deprecated)

Add: - .story-ai-section - AI settings panel: background: var(--bg-light); border: 1px solid var(--border); border-radius: var(--radius); padding: 1.25rem; margin-bottom: 1.5rem; - .story-ai-header - flex row, space-between: label left, dice button right - .story-ai-dropdowns - grid or flex-wrap of label+select pairs - .use-ai-checklist - the checkbox column beside the form fields - .thumb-ai-expand - expandable image AI section: background: var(--bg-light); border: 1px solid var(--border); border-radius: var(--radius); padding: 1rem; margin-top: 0.5rem; - .btn-ai-inline - the [✨ AI] pill button used beside headings and file inputs: small, outlined, purple accent - #scene-ai-modal - modal overlay styles (fixed, dark backdrop, centered card) - .field-ai-checked - applied to readonly AI-checked inputs: opacity: 0.55; background: var(--bg-light);

18.12 - File retirement

Move the following files to a retired/ subfolder at the project root. The folder acts as a temporary holding area - files are kept for reference until all functionality has been confirmed, then deleted.

File Reason
api_ai_properties.php Replaced by async api_create_story_ai.php (task 18.5)
generate_story.php Already superseded (redirects to editor.php); no longer needed

Create the retired/ folder if it does not exist. No code changes needed - these files are simply moved, not modified.


What changes vs what stays the same

Item Status
editor.php story form - tab structure Removed
editor.php - Create New Story form Reworked (18.1–18.5)
editor.php - Edit Story Properties form Simplified (18.6)
editor.php - Create/Edit Scene form Modal button added (18.7–18.8)
api_ai_properties.php Retired - moved to retired/ (18.12)
generate_story.php Retired - moved to retired/ (18.12)
api_jobs.php Unchanged (still used by scene modal)
api_create_story_ai.php New file (18.5)
cron/ai_worker.php Minor: route new create_story type
cron/ai_story_handler.php Extended: properties phase added
cron/ai_apply.php Extended: apply_create_story_result()
generateProperties() / generateScenes() / generateEverything() Removed
randomizeAll()randomizeStoryAI() Renamed + scoped to story create page
switchStoryTab() Removed
Scene generation job type + handlers Unchanged
Cover image job type Unchanged
Play page Unchanged
save_story POST handler Unchanged

Files to change

File Change
editor.php Rework story form (18.1–18.6), add scene AI modal + thumbnail buttons (18.7–18.8)
styles/editor.css Remove tab styles, add AI panel + modal + thumbnail expand styles (18.11)
api_create_story_ai.php New - create draft story record + queue create_story job
cron/ai_worker.php Route create_story job type to new handler
cron/ai_story_handler.php Add properties generation phase for create_story jobs
cron/ai_apply.php Add apply_create_story_result()

Phase 19 - Header Redesign

Separate phase. No dependency on Phase 18. Reads app_title from $SETTINGS (set in Phase 17).

Phase 20 - AI Job Cost Tracking

No dependency on Phase 18 or 19. Depends on Phase 17 (settings table provides active model and pricing reference). Phase 18’s create_story job type picks up cost tracking automatically once its handlers call db_update_job_cost().

Tasks:

Phase 21 - Extract AI Prompts to External Files

Moves all system prompt text out of PHP handler files and into standalone .txt template files in a new prompts/ directory. Prompts that contain dynamic values use {PLACEHOLDER} tokens that are substituted in PHP via str_replace().

Plan 4 - UI Polish, Social Enhancements & AI Improvements

Overview

This plan continues from 3 (Phases 17–22). Phase numbering runs 23–33. Phase 22 (documentation) was deferred from 3 and is rolled into Phase 33 here.

Broad areas covered:

  1. UI / UX polish - global modal system, gallery card overhaul, soft delete & trash, story tree view, job queue enhancements
  2. Story management - multi-genre stories, clone relocation, editor tweaks, summary page draft access
  3. AI enhancements - rate-limit retry with backoff, audience targeting, two-level image style selector, mood/lighting modifiers, per-story image settings, guardrails
  4. Admin / automation - DB-driven genre + image style lists with chip editors, guardrails section, maintenance cron, log & trash retention settings

All phases assume 3 is complete and deployed.


Phase 23 - Global Modal System

Replace all alert(), confirm(), and prompt() JavaScript calls site-wide with a shared modal component. This phase must come before all others that open modals (tree view, delete confirmations, clone confirms, etc.).

Tasks:

Phase 24 - Soft Delete & Trash System

Introduces a deleted story status so that deleting a story moves it to a trash bin rather than removing it permanently. Owners can restore; admins can restore or permanently purge. Permanent deletion is handled automatically by the maintenance cron (Phase 29).

Tasks:

Adds a genre column to stories, exposes it in creation/edit forms, and overhauls the gallery cards and filtering bar. The clone button moves from the gallery card to summary.php. summary.php is also fixed to stop auto-redirecting owners/admins to the editor so that draft stories have a proper landing page. The social section on summary.php is redesigned into a unified horizontal strip with larger icons and numbers, and the “Favorites” feature is renamed to “Likes” throughout the UI.

Tasks:

Phase 26 - Story Editor Tweaks

Small targeted changes to editor.php.

Tasks:

Phase 27 - API Rate-Limit Retry

Adds a consistent retry-with-backoff wrapper around all AI API calls across the three cron handlers. Currently a 429 rate-limit response immediately fails the job; this phase gives each call up to 5 retries with a 20-second delay between attempts before giving up.

Tasks:

Phase 28 - DB-Driven Settings: Image Styles, Genres & AI Creator Overhaul

Extends the AI creator with audience targeting, a rich two-level image style selector, and mood/lighting modifiers. Moves image style options and the story genre list from hardcoded PHP arrays into admin-editable DB settings with chip-list editors. Upgrades stories from single-genre to multi-genre (JSON array). Stores chosen image settings on each story so inline cover and scene image panels can offer a “Use story settings” shortcut.

Tasks:

Phase 29 - AI Guardrails

Adds admin-configurable content guardrails to all AI generation. Claude is instructed to return a red_flag field when generated content breaches a guardrail topic; image prompts receive a “Do not depict” prefix. Breaches set the job to error and are logged.

Tasks:

Phase 30 - Admin Maintenance Section

Adds a Maintenance section to the admin panel for controlling automatic cleanup of deleted stories and log files. A new cron/maintenance.php CLI script performs the actual work, invoked daily by the AI dispatcher.

Tasks:

Phase 31 - Story Tree View

Adds a “Tree View” button to the story editor that opens a modal containing an SVG-rendered, navigable tree of all scenes in the story. Nodes are clickable links to the scene editor.

Tasks:

Phase 32 - Job Queue Enhancements

Upgrades job_queue.php with a stat dashboard (admin only), search/filter bar (all users), a “Clear Completed” button, and a job detail modal showing raw input/result JSON with syntax highlighting.

Tasks:

Plan 5 - Cosmetic Polish & Settings Rework

Cosmetic polish plus a re-work of the account/admin settings area. Source of truth: _dev/implementation/5/notes-5.txt.

Phases continue from the 4 sequence. 5 runs Phases 33–38 and contains no documentation phase - the documentation update (which also absorbs 4’s never-done Phase 33) now lives in 6, see _dev/implementation/6/notes-6.md.

Conventions for 5

Phase 33 - Genre Backfill (data)

Populate genre for stories that currently have none, by analysing each story’s title + description and assigning one or two genres from the managed story_genres list.

Tasks:

Phase 34 - Account & Admin Settings Restructure

Split the monolithic account.php into focused pages and turn the header cog into a settings dropdown. This is the only non-cosmetic phase.

Tasks:

index.php story cards + the “My Likes” label.

Tasks:

Phase 36 - Summary Page Tweaks

summary.php social strip and header.

Tasks:

Phase 37 - Story Editor & Tree View Tweaks

editor.php (story + scene views), the AI generation modals, and the tree-view modal width.

Tasks:

Phase 38 - Play Page Tweaks

play.php and styles/play_layout.css. No theme files are touched in 5.

Tasks:

Resolved decisions

  1. Profile Image panel (34.1): Keep on account.php (Password + BYOK + Profile Image).
  2. Scene thumbnail sizes (34.3): Small=140 / Medium=200 / Large=280 px, defined as a tunable reference array in config.php.
  3. Play themes: deferred to 6. No theme changes in 5. The data-driven theme engine (one CSS-variable template + presets table + AI-generated per-story palettes, curated mood-tagged Google-font allow-list, user override) is captured in _dev/implementation/6/notes-6.md. The 5 image_top fixes are play-layout only.

Plan 6 - Backend Cleanups & Theme Engine

Backend/AI cleanups plus the larger nice-to-haves parked after 5. All 6 items are now specified as phases below - notes-6.md has been closed out (everything promoted here). notes-6.txt remains the owner’s raw scratchpad.

Phases continue from the 5 sequence (5 ran Phases 33–38). 6 starts at Phase 39. The Documentation Update stays last so it can capture everything that ships.

Conventions for 6

Phase 39 - Audience Instruction Lookup (prompt refactor)

Stop making the AI re-derive the audience complexity from an inline table; resolve it server-side and pass the specific instruction into the prompt.

Tasks:

Three long lists need paging; do the two that matter now, leave users for later. Decisions are locked with the owner.

Phase 41 - Curated Mood-Tagged Font Allow-List

A data foundation for Phase 42 (the theme engine): a vetted set of Google fonts the AI can pick from, each tagged by mood and guaranteed to load. Built once; reused by the engine’s AI step, the play-page font <link>, and the editor’s font picker. (Like the Phase 33 genre backfill, this is a small but distinct data-foundation phase - it gates Phase 42’s AI font selection, so it lands first.)

Phase 42 - Data-Driven Theme Engine

Replace the per-file play themes with a single CSS-variable template driven by stored values - enabling unlimited looks, AI-generated per-story palettes, and full user override. Builds on the Phase 41 font allow-list.

Plan 7 - Story Image Gallery

Phase 44 - Story Image Gallery

A per-story image gallery - a companion to the Tree View - that shows the cover image first, then every scene that has artwork (scenes without an image are skipped). A site-wide gallery was deferred, but the data layer is built behind a reusable seam so a global mode can be added later without a rewrite.

Tasks:

Documentation

A final documentation pass kept the steering documents - the .claude/ references and the project’s CLAUDE.md rule book - in sync with everything that shipped. It was scheduled last in each round so it only ever described features that actually landed, and it involved no application-code changes.