# ai.txt # Machine-readable technical reference for the AI systems in this application. # Audience: AI agents, crawlers, integrators, and developers. # Everything below reflects code that actually exists in this codebase. # Anything not listed here does not exist as an AI feature. App name: Birch & Light Product line: Birch & Light stories, podcasts, songs, articles, and the LightMap app (with Talk, its AI thinking partner) Version: 2026.07 Last updated: 2026-07-30 Live URL: https://birchandlight.com Related files: /robots.txt, /llms.txt, /sitemap.xml ## AI SYSTEMS OVERVIEW All model calls are server side. No model is ever called from the browser, and no model API key is exposed to client code. Every call goes to the Lovable AI Gateway at https://ai.gateway.lovable.dev/v1/chat/completions. Most functions route through a shared helper at supabase/functions/_shared/logged-gateway-fetch.ts, which also writes a usage row to public.ai_usage_logs. Five content-generation functions call the gateway with a direct fetch and therefore do not write usage rows: see the ai_usage_logs entry under DATABASE SCHEMA for the list. Parent-facing AI systems: 1. Talk Reflective parenting thinking-partner grounded in the parent's own logged history for a specific child. 2. Talk rewrite Rewrites an existing Talk reply for a different audience (co-parent, teacher, therapist, the child, other). 3. Suggested Support Reads recent logs and recommends relevant Birch & Light stories, articles, podcasts, and songs. 4. Reflection prompts Generates short follow-up reflection prompts during logging. 5. LightMap help chat Product-support assistant that answers "how does LightMap work" questions only. Admin-only content production AI systems: 6. Story blueprint generation 7. Parent guide generation 8. Podcast episode copy generation 9. Story cover image generation 10. Dynamic story page image generation 11. Ebook illustration generation and targeted edit 12. June-series illustration generation 13. Story image replace and story image edit 14. Coloring pack generation (admin batch and per-story) 15. Companion PDF generation 16. AI usage statistics reporting ## AI SYSTEM DETAIL ### 1. Talk File: supabase/functions/lightmap-chat/index.ts Access: Authenticated. Requires a Supabase user session. The requesting user must own or have an accepted share on the child record, and must pass public.has_lightmap_access (active membership, trial, grandfathered, founding, complimentary, or admin). Models: openai/gpt-5.4 (main reply) google/gemini-2.5-flash-lite (intent classifier, conversation summarizer, conversation auto-titling) Streams: Yes. Server-sent events (text/event-stream). Input: JSON body with the parent message, child id, conversation id, and prior turns. Server-side context is assembled from the child's logged moments, bright spots, story notes, the parent-curated care profile, and the onboarding assessment. Output: SSE token stream. Metadata is returned on response headers: x-assistant-message-id, x-user-message-id, x-intent, x-crisis-detected, x-prompt-version. Intents: pattern_query, in_the_moment, reflection, topic_reset, general_question, crisis Rate limit: 50 messages per user per day, enforced server side. Exceeding it returns HTTP 429 with a plain-language message. The admin account bypasses this. Notes: The active system prompt is bundled in the function. An optional database override can be stored in public.muse_system_prompts; that table is currently empty, so the bundled prompt is what runs. ### 2. Talk rewrite File: supabase/functions/muse-rewrite/index.ts Access: Authenticated. The caller must own the source LightMap message. Model: openai/gpt-5.4-mini Streams: No. Input: JSON body: source_message_id (uuid, required), audience (required, one of co_parent, teacher, therapist, family, child, other), audience_detail (string, used when audience is "other"). Output: JSON { id, content }. Persisted to public.lightmap_chat_rewrites. Rate limit: 30 rewrites per user per day, counted server side against public.lightmap_chat_rewrites. Exceeding it is rejected. ### 3. Suggested Support File: supabase/functions/lightmap-support/index.ts Access: Authenticated. Verifies the session, then checks public.has_lightmap_access. Model: google/gemini-3-flash-preview Streams: No. Input: JSON body: moments, brightSpots, storyNotes, reflections, parentReflections, childName, lifeStage, personLabel. Output: JSON with a recommendations array. Each recommendation is hydrated server side against the internal content catalog, so titles, links, and media types come from real catalog rows rather than from the model. Rate limit: Upstream 429 is surfaced to the client as HTTP 429. ### 4. Reflection prompts File: supabase/functions/lightmap-parent-tips/index.ts Access: Authenticated, plus public.has_lightmap_access. Without access the function returns 403 "membership_required". Model: google/gemini-2.5-flash Streams: No. Input: JSON body: answer (string, truncated to 500 chars), prompt (string, truncated to 200 chars), recentAnswers (string array). Output: JSON { validation: string, tips: string[] }. ### 5. LightMap help chat File: supabase/functions/lightmap-help-chat/index.ts Access: Authenticated. Model: google/gemini-2.5-flash-lite Streams: No. Input: JSON body: messages, an array of { role, content }. Output: JSON with the assistant reply, or { error: "rate_limited" } on HTTP 429. Scope: Product help only. It declines image generation, code, essays, and any request unrelated to how LightMap works. ### 6. Story blueprint generation File: supabase/functions/generate-story-blueprint/index.ts Access: Admin only. Model: google/gemini-3-flash-preview Streams: No. Input: JSON body: title (required), story_text (required). Output: Structured JSON story blueprint. ### 7. Parent guide generation File: supabase/functions/generate-parent-guide/index.ts Access: Admin only. Model: google/gemini-2.5-pro Streams: No. Input: JSON body: title, story_slug, directional_copy (all required). Output: Structured JSON guide, stored on dynamic_stories.parent_guide or public.parent_guide_overrides. ### 8. Podcast episode copy generation File: supabase/functions/generate-episode-copy/index.ts Access: Admin only. Returns 403 "Admin only" without an admin role row. Model: google/gemini-2.5-flash Streams: No. Input: JSON body: slug (required). Output: JSON episode copy fields. ### 9. Story cover image generation File: supabase/functions/generate-story-cover/index.ts Access: Admin only. Returns 403 "Admin role required". Model: google/gemini-3-pro-image-preview Streams: No. Input: JSON body: slug, title, story_text. Output: JSON with the generated cover image location. ### 10. Dynamic story page image generation File: supabase/functions/generate-dynamic-page-image/index.ts Access: Admin only. Returns 403 "Admin role required". Model: google/gemini-3-pro-image-preview Streams: No. Input: JSON body: slug, page_index (number), prompt. Output: JSON with the generated page illustration location. Written to public.dynamic_story_pages.illustration_url. ### 11. Ebook illustration generation File: supabase/functions/generate-ebook-illustration/index.ts Access: Admin only. Models: google/gemini-3-pro-image-preview (primary, used for faithful edits) google/gemini-2.5-flash-image (fallback) Streams: No. Input: Book id, spread index, prompt, and character reference material. Output: JSON with the generated illustration location in storage. ### 12. June-series illustration generation File: supabase/functions/generate-june-illustration/index.ts Access: Admin only. Models: google/gemini-3-pro-image-preview with a google/gemini-2.5-flash-image retry path and simplified-prompt retries. Streams: No. ### 13. Story image replace and edit Files: supabase/functions/admin-replace-story-image/index.ts supabase/functions/admin-generate-story-image/index.ts supabase/functions/admin-edit-story-image/index.ts Access: Admin only. Models: google/gemini-2.5-flash-image (replace and generate; the generate function accepts a model override in the body, defaulting to this) google/gemini-3-pro-image-preview (targeted edit) Streams: No. ### 14. Coloring pack generation Files: supabase/functions/generate-coloring-pack/index.ts (admin batch) supabase/functions/story-coloring-pack/index.ts (per story) Access: generate-coloring-pack is admin only and throws "Admin access required". story-coloring-pack requires an authenticated user (401 Unauthorized without a session). Its read action, serving an already generated pack, needs only that session. Every mutating action (stage-source, page, assemble, remove) additionally requires an admin email and returns 403 "Admin only". Model: google/gemini-2.5-flash-image Streams: No. Input: generate-coloring-pack: bookId (defaults to "the-princess-and-the-witch-inside"), spread (optional number). story-coloring-pack: action, slug (must match ^[a-z0-9-]+$). ### 15. Companion PDF generation File: supabase/functions/admin-generate-companion-pdfs/index.ts Access: Admin only. Models: google/gemini-2.5-flash, google/gemini-2.5-pro, google/gemini-3-flash-preview Streams: No. ### 16. AI usage statistics File: supabase/functions/admin-ai-usage-stats/index.ts Access: Admin only. Model: None. This function reads public.ai_usage_logs and aggregates it. Output: JSON usage and cost aggregates for the admin dashboard. ## DATABASE SCHEMA (AI-RELEVANT TABLES) All tables below live in the public schema, have row level security enabled, and are scoped to the owning user unless stated otherwise. ai_usage_logs id, function_name, model, user_id, status, error_message, prompt_tokens, completion_tokens, total_tokens, latency_ms, created_at Written by supabase/functions/_shared/logged-gateway-fetch.ts. Admin read only. Token columns are populated only for non-streaming JSON responses, so streaming Talk calls and image calls log status and latency with null token counts. user_id is populated only when the calling function passes it. Not logged at all, because these five call the gateway with a direct fetch: generate-dynamic-page-image, generate-episode-copy, generate-parent-guide, generate-story-blueprint, generate-story-cover. muse_system_prompts id, version, body, notes, is_active, created_by, created_at Optional database override for LightMap system prompt. Currently empty, so the prompt bundled in lightmap-chat is the one in use. lightmap_chat_conversations id, user_id, child_id, title, folder, created_at, updated_at, archived_at lightmap_chat_messages id, user_id, child_id, conversation_id, role, content, intent, was_correction, crisis_detected, idempotency_key, created_at lightmap_chat_ratings id, message_id, user_id, child_id, rating, intent, created_at, updated_at lightmap_chat_rewrites id, source_message_id, user_id, conversation_id, audience, audience_detail, content, prompt_version, model, created_at onboarding_assessments user_id, child_age_band, challenges, impact, parent_confidence, already_tried, goal, professional_support, completed_at, created_at, updated_at Read as context by Talk. dynamic_stories id, slug, title, meta_title, meta_description, short_hook, for_kids_who, themes, cover_url, parent_guide, published, created_by, character_refs, story_summary, parent_insight, child_takeaway, parent_guide_source_copy, created_at, updated_at dynamic_story_pages id, story_id, page_index, kind, paragraphs, illustration_url, alt, created_at parent_guide_overrides slug, guide, source_copy, updated_by, updated_at story_assets id, slug, slot, bucket, file_path, public_url, title, blurb, lyrics, audio_duration_seconds, reference_copy, parent_takeaway, uploaded_by, created_at, updated_at Talk also reads, but does not write, the family log tables: moments, bright_spots, story_notes, child_care_profiles, child_diagnoses, and child_medications_seed. Those are covered by the same per-user row level security. ## API ENDPOINTS Base: https://.functions.supabase.co/ Method: POST for every endpoint listed here. OPTIONS is handled for CORS preflight. Auth: Send Authorization: Bearer . A publishable key alone satisfies the platform JWT check but not the in-function checks, which call auth.getUser(), then public.has_lightmap_access or an admin role lookup. There is no public unauthenticated AI endpoint in this application. POST /lightmap-chat Auth: user session + child access + membership access Body: parent message, child id, conversation id, prior turns Resp: text/event-stream, plus x-assistant-message-id, x-user-message-id, x-intent, x-crisis-detected, x-prompt-version headers 429 when the 50 message per day cap is hit POST /muse-rewrite Auth: user session, must own the source message Body: { source_message_id, audience, audience_detail? } Resp: application/json { id, content } 400 when source_message_id or a valid audience is missing Capped at 30 rewrites per user per day POST /lightmap-support Auth: user session + membership access Body: { moments, brightSpots, storyNotes, reflections, parentReflections, childName, lifeStage, personLabel } Resp: application/json { recommendations: [...] } POST /lightmap-parent-tips Auth: user session + membership access (403 "membership_required" otherwise) Body: { answer, prompt, recentAnswers } Resp: application/json { validation, tips } POST /lightmap-help-chat Auth: user session Body: { messages: [{ role, content }] } Resp: application/json, or 429 { error: "rate_limited" } POST /generate-story-blueprint Auth: admin Body: { title, story_text } POST /generate-parent-guide Auth: admin Body: { title, story_slug, directional_copy } POST /generate-episode-copy Auth: admin Body: { slug } POST /generate-story-cover Auth: admin Body: { slug, title, story_text } POST /generate-dynamic-page-image Auth: admin Body: { slug, page_index, prompt } POST /generate-ebook-illustration Auth: admin POST /generate-june-illustration Auth: admin POST /admin-generate-story-image Auth: admin Body accepts an optional model override POST /admin-replace-story-image Auth: admin POST /admin-edit-story-image Auth: admin POST /generate-coloring-pack Auth: admin Body: { bookId?, spread? } POST /story-coloring-pack Auth: user for the read action, admin for every mutating action. Body: { action, slug } POST /admin-generate-companion-pdfs Auth: admin POST /admin-ai-usage-stats Auth: admin No model call Common error shapes across the AI endpoints: 401 Unauthorized missing or invalid session 403 Admin only / Admin role required 400 validation error with a field-specific message 429 rate limited, either the per-user daily cap or an upstream gateway limit 402 AI credits exhausted, surfaced to the user as a support message 500 configuration error, for example a missing gateway key ## CONTENT & BEHAVIOR RULES These rules are enforced in the system prompts and in server-side guard code. Clinical boundaries - LightMap is not a therapist, doctor, or diagnostic tool. It never diagnoses. - Clinical questions are redirected to a qualified professional. - LightMap never recommends dosing, or starting, stopping, or changing any medication. - Diagnoses stored in the care profile are treated as parent-reported facts, never as model conclusions. - Care profile details such as medication names, diagnoses, and date of birth are not surfaced in in-the-moment replies unless the parent named them first, and are never summarized back to the parent unprompted. Safety and crisis - A regex crisis detector runs before anything else. Crisis always overrides both the off-topic guard and the normal reply path. - Crisis responses stream immediately and surface 988 (Suicide & Crisis Lifeline, call or text, US) and Crisis Text Line (text HOME to 741741, US, CA, UK, IE). - LightMap never refuses a safety concern. Scope - LightMap is not a general-purpose assistant. An off-topic guard blocks politics and current events, sports, finance and crypto, coding help, recipes, celebrity and entertainment chatter, image generation requests, homework and essays, and personality probing such as roleplay requests. - A parenting-context allow list overrides the off-topic guard, so a message like "my kid loves the Chiefs" is answered rather than refused. - An off-topic refusal is one warm redirect of one to two sentences. No lecturing, moralizing, or extended apology. - LightMap help chat is narrower still and answers product questions only. Grounding - LightMap reasons over the parent's own logged data for a named child. It speaks as a person reading that child's story alongside the parent, not as analytics software. - Suggested Support recommendations are hydrated against the real content catalog server side, so recommended titles and links cannot be hallucinated. Rewrite safety - Child-directed rewrites never promise outcomes that cannot be guaranteed. - Content inappropriate for the chosen audience is abstracted or summarized rather than repeated, and the rewrite never silently refuses. It either returns a safe child-directed version or an explicit "this part is for grown-ups" version. House style - No em dashes anywhere in generated or written copy. - Warm, plain, non-clinical, non-babyish voice. - Outcomes are framed as design intent, for example "a story designed to help", never as a medical guarantee. Privacy - Child and family log data never leaves the per-user row level security boundary. - Report sharing with a therapist or teacher is read only, parent initiated, and revocable by the parent at any time. ## AI ROADMAP Natural extensions given the architecture above. These are proposals, not shipped features. Nothing in this section currently exists in the codebase. 1. Semantic search over articles, stories, podcasts, and songs, using an embeddings table plus pgvector. This would replace the current synonym map in src/lib/searchSynonyms.ts and could be fed by public.search_misses to close real gaps rather than guessed ones. 2. Retrieval-backed LightMap. Embed the parent's own logs and the Birch & Light article library so LightMap cites the specific log entry or article it is drawing on, which also makes long histories usable without growing the prompt. 3. Care-team report narration. The weekly and full PDF reports are already generated. A short model-written plain-language summary at the top, generated from the same data, would make them faster for a clinician to read. 4. Pattern digests on a schedule. The pg_cron infrastructure already runs digests and reminders, so a weekly "here is what shifted" note grounded in log deltas is a small addition rather than a new subsystem. 5. A quality loop on LightMap. public.lightmap_chat_ratings already stores thumb ratings by intent. Aggregating those against prompt_version would let prompt changes be evaluated rather than guessed at. 6. Voice logging. Speech to text on the logging screen would fit the reflection use case better than typing does, especially at the end of a hard day. 7. Illustration consistency checking. Character reference material is already stored in dynamic_stories.character_refs, so a vision pass that flags a generated illustration as off-model before it is saved would cut the manual review loop. ## CONTACT Website: https://birchandlight.com Contact: https://birchandlight.com/contact Email: tara@enchantragroup.com Instagram: https://www.instagram.com/birchandlight Facebook: https://www.facebook.com/birchandlight TikTok: https://www.tiktok.com/@birchandlight Created by Tara Alison, founder of Birch & Light.