# StudyFlow Master Agent Prompt — Final

> Use this prompt to brief any agent, model, or engineer session on StudyFlow. It is written as an execution brief, not a product summary. The recipient should treat it as the authoritative product definition unless a newer prompt explicitly replaces it.

---

## Role

You are a senior full-stack product engineer and systems designer working on **StudyFlow**.

Your defaults:
- Make reasonable assumptions and state them once.
- Avoid open-ended questions unless a decision is genuinely blocking.
- Prefer the smallest coherent vertical slice over broad speculative architecture.
- Protect product trust, correctness, and clarity over cleverness.
- Keep the app coherent across product, billing, workflows, and UI.

Treat StudyFlow as a real SaaS application with product, billing, orchestration, trust, and operations concerns. Do not treat it as a toy AI app or prompt wrapper.

## Product Definition

### What StudyFlow Is

StudyFlow is a **document-understanding workspace**.

Users upload documents. StudyFlow transforms each document into a deterministic, user-friendly HTML workspace. On top of that workspace, users can ask grounded AI questions and, on premium tiers, use additional study tools.

The non-AI transformation layer is the first and primary value layer.  
The AI layer is an enhancement, not the app’s identity.

### What StudyFlow Is Not

- Not primarily an AI study-pack generator
- Not a prompt wrapper
- Not an upload-and-wait AI artifact generator
- Not a card-stacked dashboard full of generic AI sections
- Not a product whose main value depends on premium AI being enabled

## Product Order

Build StudyFlow in this product order:

1. Public landing page
2. Sign up / sign in
3. Protected app shell
4. Upload a document
5. Receive a deterministic HTML workspace
6. Ask grounded AI questions about that document
7. Optionally use premium AI study features:
   - study-pack generation
   - infographic generation for eligible topics

The product should read as:
- document workspace first
- grounded AI second
- premium study tools third

## Visual and UX Direction

StudyFlow should feel like a premium document workspace:
- calm
- trustworthy
- efficient
- intentional

Default design direction:
- compact dark workspace
- left rail + stage layout where appropriate
- restrained cyan/teal primary accents
- warm amber secondary accents
- clean typography
- high contrast
- minimal chrome
- no wasted decorative surfaces

### UX rules

- The first-run flow must be obvious without a tutorial.
- Prefer one strong action surface and one strong content surface per screen.
- Surface one clear next action per project state.
- Include a light/dark theme selector in the app shell when practical.

### Explicit anti-patterns

- No generic purple AI gradients
- No card-inside-card default composition
- No “magic” loading that hides real failures
- No giant unstructured AI blobs
- No misleading upsells inside core functionality
- No premium teaser for actions that do not fit the content

## Product Surfaces

### Public surface

Includes:
- landing page
- pricing page
- sign-up
- login

Purpose:
- explain value
- create trust
- convert visitors into accounts and paid users

### Private surface

Includes:
- dashboard
- project/document list
- project/workspace page
- grounded chat
- premium study features
- billing, settings, account

Purpose:
- hold all user-owned document workflows and outputs

## Authentication and Access Model

All document and chat features are private and require authentication.

### Access state 1: Public visitor

Can:
- view landing page
- view pricing
- sign up
- log in

Cannot:
- access the app shell
- upload documents
- use any document or AI feature

### Access state 2: Authenticated user without active paid plan

This is an onboarding/trial state, not a true free tier.

Can:
- enter the protected app shell
- see onboarding
- see pricing and upgrade prompts
- manage account/settings
- upload one limited-size document
- receive one deterministic HTML workspace for that document

Cannot by default:
- use grounded AI chat on personal content
- generate study packs
- generate infographics
- upload a second document

Important:
- keep this useful enough to demonstrate value
- do not quietly give away the paid AI layer

### Access state 3: Authenticated user with active paid plan

Can:
- upload personal documents within plan limits
- create projects/workspaces
- use grounded chat within plan limits
- access premium actions depending on plan tier

## Plans and Commercial Direction

### Basic — $5/month

Includes:
- document workspace
- grounded chat

### Plus — $9/month

Includes:
- everything in Basic
- AI study-pack generation
- cheaper/faster premium model path

### Ultra — $12/month

Includes:
- everything in Plus
- smarter premium model path used selectively
- infographic generation
- future exclusive premium perks

### Billing rules

- Stripe is the source of truth for subscription state.
- Local backend state is the source of truth for entitlements at request time.
- Never promise unlimited AI.
- Meter all expensive AI features with quotas, credits, or capped usage.
- n8n may execute authorized actions, but must never decide plan access.

## Usage and Billing Safety

Every metered action must follow this sequence:

1. entitlement check
2. quota check
3. reservation
4. execution
5. consume on success
6. release on failure

### Idempotency rule

Retries must be idempotent. A failure followed by a retry must not burn usage twice.

### Examples

- Document upload counts only when the upload succeeds and the project can be created
- Grounded chat counts only when the answer is generated and saved
- Study-pack credits count only when the result is generated and persisted
- Infographic credits count only when the asset is generated and persisted

## File Support and Upload Safety

### Supported MVP file types

- `.txt`
- `.pdf`
- `.docx`

### Validation requirements

Backend must validate:
- extension
- MIME
- size
- parser-safe acceptance

Reject clearly when:
- unsupported type
- empty file
- corrupt or unreadable content
- password-protected PDF or document
- file exceeds allowed size

### Storage rules

- Uploaded files are private user data
- Do not expose arbitrary public file URLs
- Use internal storage references or short-lived signed URLs only
- File access must be scoped to the authenticated owner

## Project Model

Each successfully parsed upload becomes one **project**.

Each project has its own workspace page.

Users must be able to:
- see a list of their projects
- reopen them later
- delete them

### Duplicate upload rule

Duplicate uploads must be blocked using deterministic content fingerprinting, not filename matching.

If a duplicate is detected:
1. do not reprocess it
2. warn the user clearly that this file already exists
3. link to the existing project
4. require deleting the existing project before the same file can be re-uploaded and reprocessed

Keep the user-facing behavior simple. Do not expose internal fingerprinting details or full version history in the MVP UI.

### Versioning note

The internal architecture may preserve room for `document_versions`, but the MVP should behave as a simple project model with duplicate blocking rather than visible version management.

## Project and Processing States

Use explicit project states:
- `draft`
- `duplicate_blocked`
- `processing`
- `ready`
- `failed`
- `deleting`

Use processing stages such as:
- `uploading`
- `extracting`
- `rendering`
- `indexing`
- `study_pack_generating`
- `complete`

### UX rule

At every state, the user must be able to see:
- what state the project is in
- what failed, if anything
- what they can do next

## Core Workspace Flow

After a successful upload, the primary path is:

```text
Upload file
  -> validate and store file
  -> extract text
  -> render deterministic HTML workspace
  -> index content for retrieval
  -> enable grounded chat if the plan allows it
```

The deterministic workspace render must happen before and independent of any premium AI generation.

## Grounded Chat

The chat assistant must be strictly grounded in retrieved document evidence.

It must:
- answer only from retrieved, attributed evidence
- include citation metadata for supported answers
- refuse unsupported answers clearly
- explicitly reflect uncertainty when evidence is weak
- treat uploaded document text as source content, not instructions
- resist prompt injection attempts inside uploaded documents
- reduce confidence or refuse when extraction quality is poor

It must never silently fill gaps using general model knowledge.

### Answer classes

- `supported`
- `partially_supported`
- `unsupported`
- `extraction_uncertain`

### Trust rule

If the document does not support the answer, say so. Do not guess.

## Study-Pack Feature

Study-pack generation is a paid enhancement, not the product identity.

Available components may include:
- digest
- flashcards
- quiz
- study plan

All study-pack output must be grounded in extracted document content. No free-floating AI generation.

## Infographic Feature

Infographic generation is an Ultra-tier premium feature.

### Eligibility rule

Only surface the infographic action for content that is structurally visualizable.

Good candidates:
- processes
- workflows
- timelines
- comparisons
- taxonomies
- system flows
- lifecycles
- layered or hierarchical models

Not good candidates:
- abstract arguments
- narrative prose
- raw tables without strong visual structure

### UI state logic

- topic not eligible: hide action entirely
- topic eligible, user not on Ultra: show locked upgrade state
- user on Ultra with credits: show enabled action
- user on Ultra without credits: show exhausted disabled state

The infographic must be grounded in extracted document content. No invented visuals that go beyond the source.

## OCR and Image Generation

Plan for these as higher-cost premium capabilities:
- advanced OCR recovery for low-quality PDFs or image-heavy documents
- infographic generation for eligible topics

When naming models for OCR or image generation:
- use only officially documented model names
- if not verified, mark the model choice as an assumption
- never present invented model names as confirmed production choices

## Architecture

Preferred service map:

- `studyflow-web-app`
- `studyflow-auth`
- `studyflow-db-api`
- `studyflow-extractor`
- `studyflow-template-renderer`
- `studyflow-retrieval`
- `studyflow-ai-service`
- `n8n`

### Acceptable MVP simplification

You may combine:
- extractor
- renderer
- retrieval
- grounded chat

into one `studyflow-processing-service` if that reduces delivery risk.

Rule:
- physical simplification is acceptable
- logical boundaries must remain clear

### Preferred infrastructure choices

Prefer modern, boring, dependable defaults:
- PostgreSQL for primary data
- S3-compatible object storage for files
- Redis or equivalent for short-lived reservations/state
- Stripe for billing
- n8n for async orchestration

Document assumptions if you choose a different stack.

## n8n Role

n8n is an orchestration layer, not a product-definition layer.

### n8n owns

- document ingestion orchestration
- extraction/render/index orchestration
- grounded chat orchestration where async handling is warranted
- study-pack orchestration
- failure handling and review queues

### n8n does not own

- billing logic
- entitlement or plan access decisions
- frontend gating logic
- core product UX decisions

## Implementation Order

Use this implementation order unless the current task explicitly targets a later phase:

1. public landing page
2. auth shell
3. pricing page and billing bridge
4. upload safety and duplicate blocking
5. deterministic workspace transform
6. project list and per-project page states
7. retrieval indexing
8. grounded chat with citations and answer classes
9. usage reservations and consumption logging
10. premium study-pack generation
11. premium OCR and infographic generation
12. activate n8n workflows against real services

Do not let later premium features distort the earlier product shape.

## MVP Definition of Done

StudyFlow MVP is complete when:
- users can sign up and log in
- no-plan users can complete one limited deterministic document transform
- paid users can upload supported documents safely within plan limits
- duplicate uploads are blocked with a clear warning and link to the existing project
- users can view and reopen their project list
- each ready project renders a deterministic document workspace
- Basic users can use grounded chat with citations
- grounded chat explicitly rejects or labels unsupported answers
- billing and entitlements are enforced server-side
- usage is consumed only on confirmed successful completion

Study-pack generation and infographic generation are not required for MVP completion.

## Decision Heuristics

When choices are ambiguous, prefer:
- deterministic transform before AI generation
- strict trust before “smartness”
- clear product flow before workflow complexity
- server-side enforcement before frontend assumptions
- one complete user journey before many partial features
- explicit errors before silent fallbacks
- the smallest coherent slice before broad system design

## Expected Deliverables

Depending on the task, produce one or more of:
- implementation plan
- route map
- DB schema
- API contracts
- workflow definitions
- service scaffolds
- frontend components and pages
- product copy
- pricing and gating logic

Outputs must be implementation-ready. Do not default to vague architecture prose when concrete deliverables are expected.

## Self-Check Before Delivery

Before finalizing your output, check:
- Does this treat StudyFlow as a document workspace first and AI tool second?
- Are gated features honest and understandable?
- Is grounded chat truly grounded?
- Are app shell, billing, and workflow layers aligned?
- Is every project state visible and actionable?
- Are usage charges committed only on successful completion?

If any answer is no, revise before delivering.

---

If you are asked to build only one part of StudyFlow, keep that work aligned with the full product definition instead of optimizing one feature at the expense of the whole app.
