Engineering case study
Elvyn: an AI-assisted productivity app
A mobile app for planning tasks, capturing thoughts and reflecting on progress, with an AI coach that answers from the user's own notes and asks before it changes anything.
- Status
- Personal project, in development. Not publicly released and has no users.
- Role
- Sole developer: backend, mobile client and AI integration.
- Stack
- FastAPI, SQLAlchemy 2.0, Alembic, PostgreSQL (Supabase), pgvector, Celery, Redis, Gemini, React Native (Expo), TypeScript
Overview
Elvyn helps a person plan their day and keep track of what they are thinking. The app has tasks with reminders and recurring schedules, a calendar, a Brain Dump for quick notes (including voice capture), daily check-ins, a log of wins, and an AI screen where the user can ask questions.
The interesting problem is the AI screen. A generic chatbot knows nothing about the user. Elvyn retrieves the user's own earlier notes and check-ins when a question refers to them, and gives the model that text as context. It also needs to let the model help without letting it silently change or delete the user's data.
The repository is still named change-app, from the project's earlier working name.



Swipe to see more screens
My role
I designed and built all of it: the API and database schema, authentication, background workers, the retrieval pipeline and prompt construction, the AI tool layer, and the React Native client. There is no team and no other contributor.
Architecture
- Sign-in. The mobile app signs in with Supabase Auth and receives a JWT.
- Requests. The app calls the FastAPI backend with that token. The backend verifies it and scopes every query to that user.
- Data. FastAPI reads and writes PostgreSQL, which also stores the pgvector embeddings.
- AI. FastAPI calls Gemini to generate answers and to embed the user's question.
- Background jobs. FastAPI queues work in Redis. Celery workers pick it up: they embed new notes through Gemini and save the vectors to PostgreSQL, send reminders, and deliver outbox events.
The backend is organised by domain rather than by layer: separate packages for users, tasks, brain dumps, check-ins, wins, memory (retrieval) and AI. Each owns its models, schemas and routes. Migrations are managed with Alembic, and the API is fully async, using SQLAlchemy 2.0's async sessions.
Engineering decisions
Authentication and user-data isolation
Supabase issues the JWT. The backend verifies it on each request, supporting both ES256 (public keys fetched from the project's JWKS endpoint) and HS256, and then loads the user's profile. Every domain query filters by the authenticated user's id, including the vector search, which also filters by embedding model and an optional time window. I chose to enforce this in application queries consistently and not rely on a single mechanism.
Background work lives outside the request
Embedding calls are slow and can fail, and reminders must fire when the app is closed. Celery with Redis runs reminders every minute, spawns recurring tasks hourly, delivers events, and indexes memory. The trade-off is more moving parts to run and monitor than in-process background tasks. I accepted that because these jobs have to survive a request ending or the API restarting.
Transactional outbox for task events
Task events are written to an outbox table in the same transaction as the change they describe, and a worker delivers them afterwards. A unique constraint de-duplicates events, so a retried job cannot deliver the same event twice.
The model suggests; the application decides
The AI layer exposes a small set of tools. Creating a task executes directly. Updating or deleting a task returns a proposal that the user must confirm in the app before anything changes. Tool arguments are validated strictly, so a malformed or unexpected model output is rejected instead of acted on.
AI and RAG
How retrieval works
- Index. Brain dumps and check-ins are split into chunks and embedded with Gemini (
gemini-embedding-2, 768 dimensions, L2-normalised, document task type). Vectors are stored in a pgvector table together with the owner, source, content hash and embedding model. - Decide. A question triggers retrieval only when it refers to the user's past ("what did I say about…", "last week", "keep putting off") or matches a retrieval intent. Other questions skip the embedding call.
- Search. The question is embedded as a query and compared by cosine distance against only that user's chunks, optionally limited to a time window parsed from the question.
- Select. Hits must clear a minimum similarity (0.55), fall within a band of the best hit, respect a per-source cap, and fit a character budget. The selected chunks are sorted by date.
- Prompt. The chunks are sanitised, placed in the prompt as context, and returned to the app as sources so the user can see what the answer was based on.
Retrieval supplies context to the model for that one request. Nothing is trained or fine-tuned on the user's data.
def select_memories(hits, *, min_similarity=MIN_SIMILARITY, band=RELATIVE_BAND,
max_chunks=MAX_CHUNKS, per_source_cap=PER_SOURCE_CAP,
max_block_chars=MAX_BLOCK_CHARS):
ranked = sorted(hits, key=lambda h: h["similarity"], reverse=True)
if not ranked or ranked[0]["similarity"] < min_similarity:
return []
top = ranked[0]["similarity"]
chosen, per_source, used = [], {}, 0
for h in ranked:
sim = h["similarity"]
if sim < min_similarity or sim < top - band:
break
key = (h["source_type"], str(h["source_id"]))
if per_source.get(key, 0) >= per_source_cap:
continue
text = sanitize_for_prompt(h["content"])
if used + len(text) > max_block_chars:
continue
chosen.append(...) # excerpt: object construction elided
per_source[key] = per_source.get(key, 0) + 1
used += len(text)
if len(chosen) >= max_chunks:
break
return sorted(chosen, key=lambda m: m.created_at) # chronological reads better
change-backend/app/memory/retrieval.py. Returning nothing when no hit is relevant enough matters: an irrelevant memory in the prompt is worse than none.What is implemented and what is not
| Capability | Status (October 2026) |
|---|---|
| Chunking, embeddings and pgvector storage | Implemented |
| Retrieval with thresholds, per-source cap and time windows | Implemented; covered by unit tests with mocked dependencies |
| Sources returned to the app and shown with answers | Implemented |
| Idempotent background indexing and reconciliation sweep | Implemented |
| End-to-end verification against a live Postgres instance | In progress. The Postgres integration test needs a configured test database, and I have not yet recorded a full run. |
| Retrieval quality evaluation set | Not done. Thresholds are configurable and were calibrated with a small lab script, not a formal benchmark. |
Challenges and solutions
Indexing while the data changes underneath it
Embedding takes network time, and in that window a note can be edited or the user can switch AI off. After embedding, the indexer re-checks the user's AI entitlement with a share lock, reloads the source row with FOR UPDATE, and discards the work if the content changed or access was revoked. Otherwise a stale vector or a vector for a disabled user could be saved.
The AI should never take the chat down
Query embedding has a five-second timeout, and the vector search runs inside a SAVEPOINT so a failed query cannot poison the surrounding transaction. On any failure the app logs a warning (ids and scores only, never note text) and answers without memory.
Keeping the index correct over time
Chunks store a content hash and the embedding model, so unchanged text is never re-embedded and a model upgrade is detected and re-embedded in batches. A sweep every 15 minutes indexes anything missed, removes orphaned chunks and deletes chunks for users who no longer have AI enabled. If enqueueing a job fails, the sweep recovers it.
Stored text is untrusted input
Retrieved notes go into a prompt, so they are sanitised: the delimiter tag that wraps memories in the prompt is stripped out, code fences and quotes are neutralised, whitespace is collapsed and each chunk is capped in length. This reduces the risk of a stored note breaking out of its block, but it is not a complete defence against prompt injection.
Current status
Elvyn is a personal project in development. It is not publicly released and has no users.
The backend has an automated pytest suite of several dozen tests, mostly run against mocked dependencies. The mobile client runs on a device through Expo. Known gaps at the time of writing: the retrieval path has not had a recorded run against a live database; request rate limiting is configured but not yet applied to routes; and the repository does not yet have continuous integration or an example environment file. I list them because I would rather you hear them from me.
Source code
The repository is public: github.com/Kunle777/change-app. The best places to start are change-backend/app/memory/ (indexing and retrieval), change-backend/app/ai/ (prompting and tool actions) and change-backend/celery_app.py (scheduled jobs). The README's roadmap section is older than the code, so trust the code where they differ.