Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
docs: add complete AI documentation system
spacesdrive0f46e9f3a98f
diff --git a/.gitignore b/.gitignoreindex dc20e28..18e3e8d 100644--- a/.gitignore+++ b/.gitignore@@ -49,4 +49,5 @@ yarn-debug.log*.mcp.json.agentsskills-lock.json-.dev.vars\ No newline at end of file+.dev.vars+diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..465e89a--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,79 @@+# Changelog++All notable changes to Twiligent are documented here.+Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).++---++## [Unreleased]++### Fixed+- Strip non-ASCII characters from `SUPABASE_URL` and `SUPABASE_SERVICE_KEY` env vars in `scripts/publish-scheduled.js` using `/[^\x20-\x7E]/g` to defend against BOM injected by PowerShell 5.1 when setting GitHub Actions secrets+- Replaced embedded literal U+FEFF in BOM-strip regex with proper `` unicode escape++---++## [1.0.0] — 2025 (Initial Production Release)++### Added++**Backend (Cloudflare Worker + Hono)**+- `GET /api/health` — public health check endpoint+- `POST /api/accounts` — add YouTube channel by URL or handle+- `POST /api/accounts/instagram` — add Instagram account via access token+- `GET /api/accounts` — list all user accounts+- `DELETE /api/accounts/:id` — remove account and invalidate Redis cache+- `POST /api/accounts/refresh-all` — batch refresh all account stats+- `POST /api/accounts/:id/refresh` — refresh single account stats+- `POST /api/accounts/:id/refresh-ig-token` — extend Instagram long-lived token+- `GET /api/accounts/:id/analytics` — full YouTube analytics with video-level computation+- `GET /api/accounts/:id/videos` — YouTube video list (cached in Redis)+- `GET /api/accounts/:id/ig-analytics` — Instagram analytics with engagement computation+- `GET /api/accounts/:id/ig-media` — Instagram media list (cached in Redis)+- `GET /api/comparison` — cross-account comparison data+- `GET /api/auth/instagram/url` — generate HMAC-signed Instagram OAuth URL+- `GET /api/auth/instagram/callback` — OAuth code exchange, account creation, redirect+- `GET /api/resolve-channel` — resolve YouTube URL/handle to channel ID+- `GET /api/keys` — return configuration status for all required API keys+- `GET /api/cloudinary-config` — return Cloudinary cloud name and upload preset+- `POST /api/accounts/:id/ig-publish` — create Instagram media container+- `GET /api/ig-container/:id/status` — poll container processing status+- `POST /api/accounts/:id/ig-media-publish` — publish container to Instagram+- `GET /api/accounts/:id/ig-publishing-limit` — check daily publishing quota+- `GET/POST /api/scheduled-posts` — list and create scheduled posts+- `PUT/DELETE /api/scheduled-posts/:id` — edit and delete individual posts+- `DELETE /api/scheduled-posts` — clear all non-publishing posts+- `GET/POST /api/process-scheduled` — manual scheduler trigger+- `GET/PUT /api/settings/github` — GitHub PAT and repo settings++**Cron triggers (wrangler.toml)**+- `*/15 * * * *` → `processScheduledPosts()` publishes due Instagram posts+- `0 0 * * *` → `autoRefreshInstagramTokens()` refreshes tokens expiring within 15 days++**Database (Supabase)**+- `accounts` table — `id, user_id, platform, data jsonb`+- `settings` table — `user_id, key, value jsonb` (PK: user_id + key)+- `scheduled_posts` table — `id, user_id, account_id, status, scheduled_at, data jsonb`++**Frontend (React 19 + Vite)**+- `/login` — email/password authentication via Supabase Auth+- `/` — Overview dashboard: KPI cards, area chart, pie chart, leaderboard tables+- `/channel/:id` — Deep YouTube channel analytics+- `/instagram/:id` — Deep Instagram profile analytics+- `/videos` — Cross-account YouTube video explorer+- `/shorts` — Shorts-filtered video explorer+- `/reels` — Instagram reels/media explorer+- `/upload` — Instagram publishing UI + scheduled post queue+- `/accounts` — Account management: add, remove, refresh, Instagram OAuth+- `/settings` — API key status + GitHub PAT configuration++**GitHub Actions**+- `deploy-backend.yml` — deploy Worker on push to `main` (paths: `backend/**`)+- `deploy-frontend.yml` — build and deploy Pages on push to `main` (paths: `frontend/**`)+- `publish-scheduled.yml` — run scheduled publisher every 15 minutes via cron++**Infrastructure**+- HMAC-signed OAuth state (no Redis dependency for auth flows)+- Optional Upstash Redis caching with silent fallback+- Cloudinary media hosting for Instagram publishing pipeline+- `safeAccount()` strips Instagram access tokens from all API responsesdiff --git a/DECISIONS.md b/DECISIONS.mdnew file mode 100644index 0000000..7a89cba--- /dev/null+++ b/DECISIONS.md@@ -0,0 +1,287 @@+# Architecture Decision Log++Records every significant architectural decision, the alternatives considered, and the reasoning. Append new entries — never modify or delete existing ones.++---++## ADR-001: Cloudflare Workers as backend runtime++**Date:** 2024 (initial)+**Status:** Accepted++**Decision:** Use Cloudflare Workers (edge runtime) instead of a traditional server or serverless function.++**Alternatives considered:**+- Node.js server on Render / Railway+- Vercel Edge Functions+- AWS Lambda++**Reasoning:**+- Zero cold starts at the edge+- Global distribution at no extra cost+- Free tier includes built-in cron triggers+- Native `crypto.subtle` API for HMAC — no dependency needed+- `wrangler` CLI makes local dev and deploy identical++**Trade-offs:**+- No Node.js standard library (no `fs`, `Buffer`, `path`)+- Bundle must be a single ESM file+- Must use `ctx.waitUntil()` for background async work in cron handlers+- All secrets are bound at deploy time, not injected at runtime++---++## ADR-002: Hono as the HTTP framework++**Date:** 2024 (initial)+**Status:** Accepted++**Decision:** Use Hono v4 instead of itty-router or writing raw fetch handlers.++**Alternatives considered:**+- itty-router (lighter but less expressive)+- Raw `Request`/`Response` handlers+- Express (not compatible with Workers)++**Reasoning:**+- First-class Cloudflare Workers support+- Type-safe context (`c.set()` / `c.get()`)+- Middleware composability matches the auth → route pattern+- `app.route()` enables clean sub-application isolation+- Active maintenance and large community++**Trade-offs:**+- Slightly larger bundle than itty-router+- Hono context is not the same as Express `req`/`res`++---++## ADR-003: Supabase for database and auth++**Date:** 2024 (initial)+**Status:** Accepted++**Decision:** Use Supabase (PostgreSQL + Supabase Auth) instead of a standalone DB + custom auth.++**Alternatives considered:**+- PlanetScale (MySQL, no RLS)+- Neon (PostgreSQL, no built-in auth)+- D1 (Cloudflare's SQLite, limited at time of decision)+- Custom JWT auth with Workers KV++**Reasoning:**+- Built-in JWT auth eliminates building token issuance+- Service-role key enables backend bypass of RLS+- Anon key enables frontend JWT verification without exposing secrets+- Real PostgreSQL enables complex queries and jsonb+- Free tier is generous for this use case++**Trade-offs:**+- External service dependency+- jsonb data column means no column-level DB constraints on account fields+- RLS is bypassed by the backend — application-layer isolation is the security model++---++## ADR-004: All platform credentials as Worker secrets, not per-user DB values++**Date:** 2024 (initial)+**Status:** Accepted++**Decision:** YouTube API key, Instagram App ID/Secret, Cloudinary credentials are all stored as Cloudflare Worker secrets — shared across all users of the instance.++**Alternatives considered:**+- Per-user API key storage in Supabase `settings` table+- User-provided keys stored encrypted in DB++**Reasoning:**+- The app is self-hosted — there is one admin and a small team+- Per-user keys add UI complexity with marginal security benefit at this scale+- Worker secrets are encrypted at rest and never exposed in API responses++**Trade-offs:**+- All users share the YouTube API daily quota+- Changing credentials requires a Worker redeploy+- `GET /api/keys` only returns `{configured: true/false}` — the frontend can see what is configured but never the values++---++## ADR-005: jsonb data column for accounts and scheduled posts++**Date:** 2024 (initial)+**Status:** Accepted++**Decision:** Store all platform-specific account fields and post metadata in a `data jsonb` column rather than individual typed columns.++**Alternatives considered:**+- Separate `youtube_accounts` and `instagram_accounts` tables+- Platform-specific columns with nullability++**Reasoning:**+- Each platform has very different field shapes (YouTube channel vs Instagram profile)+- New platforms can be added without schema migrations+- The backend merges `data` into the returned object: `{ id, platform, ...data }`++**Trade-offs:**+- No column-level DB constraints on data fields+- Queries cannot use index-accelerated filters on data sub-fields without JSON indexing+- `accessToken` lives inside `data.accessToken` — must be consistently stripped by `safeAccount()`++---++## ADR-006: HMAC-signed OAuth state (no Redis required for auth)++**Date:** 2024 (initial)+**Status:** Accepted++**Decision:** Instagram OAuth state token is self-verifying via HMAC-SHA256. Redis is not required for the OAuth flow.++**Format:** `base64url(userId:timestamp).base64url(HMAC-SHA256(payload, INSTAGRAM_APP_SECRET))`+**Expiry:** 10 minutes (enforced by checking the embedded timestamp)++**Alternatives considered:**+- Store state in Upstash Redis with 10-minute TTL+- Store state in Workers KV++**Reasoning:**+- The app must function without Redis configured+- HMAC is cryptographically equivalent to a signed opaque token+- `crypto.subtle` is natively available in Workers — no dependency needed++**Trade-offs:**+- State cannot be invalidated early (e.g., on logout) — only expires by time+- If `INSTAGRAM_APP_SECRET` is compromised, historical state tokens can be forged++---++## ADR-007: Dual-scheduler for Instagram publishing++**Date:** 2024 (initial)+**Status:** Accepted++**Decision:** Implement Instagram scheduled posting via both the Cloudflare Worker cron (`*/15 * * * *`) and a GitHub Actions workflow running the same schedule.++**Alternatives considered:**+- Worker cron only+- GitHub Actions only+- External cron service (cron-job.org, EasyCron)++**Reasoning:**+- GitHub Actions is free on public repos (unlimited minutes)+- Provides redundancy if the Worker cron fails or is paused+- `scripts/publish-scheduled.js` can run without any npm install — it uses native fetch only+- The same Supabase table is the source of truth for both systems++**Trade-offs:**+- There is a risk of double-publishing if both run at exactly the same moment. Mitigated by the `publishing` status lock — the first scheduler to claim a post sets it to `publishing`, so the second will skip it.+- `SUPABASE_URL` and `SUPABASE_SERVICE_KEY` must be set as GitHub Actions secrets separately from Worker secrets++---++## ADR-008: Upstash Redis as optional cache layer++**Date:** 2024 (initial)+**Status:** Accepted++**Decision:** Redis caching is optional. All cache operations are wrapped in try/catch and silently fall back to live API calls when Redis is absent or fails.++**Alternatives considered:**+- Workers KV (persistent, not ideal for cache with invalidation)+- Mandatory Redis (breaks self-hosted deployments without Upstash)+- No cache at all++**Reasoning:**+- Self-hosted users may not want to create an Upstash account+- YouTube and Instagram API quotas are the real constraint — caching is an optimization+- Silent fallback means Redis can be added or removed without code changes++**Trade-offs:**+- Without Redis, every analytics page load fetches 500+ videos/media items from external APIs+- Cache TTL is not set — cached data persists until the account is deleted or explicitly invalidated++---++## ADR-009: Cloudinary as media intermediary for Instagram publishing++**Date:** 2024 (initial)+**Status:** Accepted++**Decision:** Users upload media to Cloudinary first; the resulting public URL is passed to the Instagram Graph API.++**Alternatives considered:**+- Upload to Supabase Storage, then pass the public URL+- Upload directly from the browser to a Worker endpoint that re-streams to Instagram+- Require users to host media elsewhere++**Reasoning:**+- Instagram's Graph API requires a publicly accessible, stable URL+- Cloudinary provides immediate CDN distribution+- The unsigned upload preset lets the browser upload directly — the backend never handles binary file streams+- Cloudinary's transformation URLs can generate thumbnails and previews++**Trade-offs:**+- Requires a Cloudinary account and upload preset configuration+- Media stays in Cloudinary after posting — could accumulate cost if not cleaned up+- `GET /api/cloudinary-config` exposes the cloud name and unsigned preset to the frontend (acceptable — unsigned presets are intentionally public)++---++## ADR-010: No TypeScript in any layer++**Date:** 2024 (initial)+**Status:** Accepted++**Decision:** The entire project is plain JavaScript and JSX. No TypeScript, no JSDoc type annotations, no type checking step.++**Alternatives considered:**+- TypeScript throughout+- TypeScript for backend only (Wrangler supports it natively)+- JSDoc annotations for IDE assistance++**Reasoning:**+- Reduced build complexity — no tsc step in Workers or Vite+- The project is small enough that naming conventions and documentation provide adequate clarity+- Worker bundles avoid a TS compilation step++**Trade-offs:**+- No compile-time type safety+- IDE autocomplete relies on runtime inference rather than explicit types+- Future developers familiar with TS may find this surprising++---++## ADR-011: Application-layer row isolation instead of RLS++**Date:** 2024 (initial)+**Status:** Accepted++**Decision:** The backend uses the service-role key (which bypasses RLS) on every request. Row isolation is enforced by always appending `.eq('user_id', userId)` where `userId` comes exclusively from the verified JWT.++**Alternatives considered:**+- Enable RLS and use the anon key on the backend+- Use the anon key with `setAuth(token)` to impersonate the user++**Reasoning:**+- Service-role key simplifies cron handlers (scheduler, token refresh) which need to query across all users+- Having a single key avoids key-switching logic in `lib/db.js`+- The security boundary is the `requireAuth` middleware — once the JWT is verified, `userId` is trusted++**Trade-offs:**+- A bug that accidentally omits `.eq('user_id', userId)` could expose another user's data+- RLS would catch that bug automatically; the current approach does not+- Mitigated by centralizing all queries in `lib/db.js` where the pattern is consistent++---++## ADR-012: GitHub settings stored in Supabase `settings` table++**Date:** 2024 (initial)+**Status:** Accepted++**Decision:** GitHub PAT and repo config for the future "push to GitHub" feature are stored in the `settings` table as `key='api_keys'`.++**Status:** The settings table and API routes exist. The GitHub push feature is planned but not yet implemented.++**Trade-offs:**+- GitHub PAT is stored in plaintext in Supabase jsonb — acceptable for a self-hosted deployment where the admin trusts the storage layer+- The `settings` table design (user_id + key + jsonb value) is generic enough to hold any future per-user configurationdiff --git a/ROADMAP.md b/ROADMAP.mdnew file mode 100644index 0000000..332df62--- /dev/null+++ b/ROADMAP.md@@ -0,0 +1,133 @@+# Roadmap++Planned features, improvements, and known gaps. Items within each section are roughly prioritized — top items first.++Update this file whenever a feature ships (move to CHANGELOG.md) or when priorities change.++---++## In Progress++- **BOM-stripping fix for GitHub Actions publisher** — Hardening `scripts/publish-scheduled.js` against PowerShell-injected BOM characters in secrets++---++## Next Up (High Priority)++### Reddit Integration++Add Reddit as a connected platform for analytics.++**Approach:** Cookie-based authentication (no OAuth required)+- User logs into Reddit in a browser popup+- Session cookies (`token_v2`, `reddit_session`) are captured and stored in `accounts.data`+- Cookies are auto-refreshed: Reddit rotates `Set-Cookie` on every authenticated response — save the updated cookie on each API call+- Endpoints to fetch: `GET /user/{username}/submitted.json`, `/user/{username}/about.json`++**Files to add:**+- `backend/services/reddit.js` — cookie-based fetch wrapper, token refresh, analytics computation+- `backend/routes/reddit.js` — analytics routes (analytics, posts, comments)+- `frontend/src/features/analytics/reddit/RedditAnalytics.jsx` — analytics page+- `frontend/src/features/accounts/components/RedditConnect.jsx` — login popup + cookie capture++**Files to modify:**+- `backend/server.js` — mount Reddit routes+- `backend/lib/db.js` — no changes needed (platform='reddit' works with existing schema)+- `backend/lib/cache.js` — add `getRedditCache`, `setRedditCache`, `deleteRedditCache`+- `frontend/src/App.jsx` — add `/reddit/:id` route+- `frontend/src/layout/Sidebar.jsx` — add Reddit nav links+- `docs/architecture/data-flows/` — add `REDDIT.md`++---++### Twitter/X Integration++Add Twitter/X for analytics (read-only via twitterapi.io or official v2 API).++**Decision pending:** twitterapi.io ($0.00015/tweet, unlimited access) vs Twitter v2 API (free tier: 500k reads/month).++**Approach (twitterapi.io):**+- User provides their Twitter username or OAuth token+- Fetch tweets, impressions, engagement via twitterapi.io REST API+- No OAuth popup needed for public accounts++**Files to add:**+- `backend/services/twitter.js`+- `backend/routes/twitter.js`+- `frontend/src/features/analytics/twitter/TwitterAnalytics.jsx`++---++## Planned (Medium Priority)++### GitHub Integration for Content Publishing++The `settings` table already stores GitHub PAT and repo config. Build the actual feature.++**Scope:**+- Push published Instagram post data (caption, media URL, timestamp, engagement) to a GitHub repo as JSON/Markdown files+- Useful for content archiving and portfolio generation++**Files to modify:** `backend/routes/settings.js` (already has GET/PUT), `backend/services/` (add `github.js`)++---++### Bulk Schedule from CSV++Allow users to upload a CSV file to schedule multiple Instagram posts at once.++**Current:** Bulk scheduling UI exists in `UploadContent.jsx` but only via manual row entry.+**Goal:** CSV upload → parse → preview → schedule all rows++---++### Analytics Date Range Filtering++Currently analytics always fetch the most recent N posts/videos.+Add date range filtering to all analytics views.++---++### Webhook Notifications++Send a webhook (to Slack, Discord, or custom URL) when:+- A scheduled post publishes successfully+- A scheduled post fails+- An Instagram token is nearing expiry (< 7 days)++---++### Export to CSV/PDF++Add export buttons to analytics pages. Users should be able to download their data.++---++## Backlog (Lower Priority)++### TikTok Integration++TikTok's API requires a business account and app review. Lower priority until the other platforms are solid.++### YouTube Publishing++YouTube's upload API requires OAuth with `youtube.upload` scope. Architecture would mirror Instagram publishing — add a media pipeline with Cloudinary → YouTube upload → status polling.++### Multi-User Teams++Currently each Supabase auth user is completely isolated. A team feature would allow multiple users to share the same accounts. Requires a `teams` table, `team_members` join table, and query changes across `lib/db.js`.++### Mobile App++React Native app using the same Cloudflare Worker backend.++---++## Known Issues / Tech Debt++- Redis cache TTL is never set — cached analytics data persists indefinitely until account deletion. Should add a TTL (e.g., 24 hours for video lists).+- `public/` directory at repo root contains a legacy Express prototype — should be removed once it is confirmed unused.+- Root `package.json` and `node_modules/` belong to the legacy prototype — can be removed.+- `wrangler.toml` has no `vars` section for non-secret configuration — any non-sensitive config currently requires a redeploy to change.+- No error monitoring (Sentry, Cloudflare Analytics, etc.) — failures are only visible in Cloudflare Worker logs.+- The `scripts/publish-scheduled.js` scheduler has no rate limiting — if 100 posts are due at the same time, it will attempt to publish all 100 concurrently within a single GitHub Actions run.diff --git a/claude.md b/claude.mdnew file mode 100644index 0000000..668b46d--- /dev/null+++ b/claude.md@@ -0,0 +1,300 @@+# Twiligent - AI Operating Manual++## Project Identity++Twiligent is a self-hosted social media analytics and publishing dashboard for creators and teams managing multiple YouTube channels and Instagram accounts. It is a private deployment product - the owner runs their own instance with their own API credentials. There is no SaaS model, no multi-tenancy abstraction, and no billing system.++- Primary users: Small creator teams, agencies, individual power users+- Primary value: Unified analytics and scheduled Instagram publishing across multiple accounts+- Current platforms: YouTube (analytics only), Instagram (analytics and publishing)+- GitHub repository: https://github.com/spacesdrive/twiligent++---++## Reading Order Before Any Change++Before implementing any feature or fix, read these documents in this exact order:++1. This file - project identity, rules, and documentation map+2. `docs/WRITING_STANDARDS.md` - typography, icons, writing style, UI copy rules+3. `docs/architecture/OVERVIEW.md` - system topology and request flow+4. `docs/guidelines/JAVASCRIPT.md` - code standards (always apply)+5. Relevant architecture doc - backend, frontend, database, or cloudflare+6. Relevant feature guide - if one exists in `docs/features/`+7. Relevant engineering guideline - if the task touches a specific layer++For MCP usage, read `docs/mcp/OVERVIEW.md` before using any MCP server.++---++## Documentation Map++```+docs/+ WRITING_STANDARDS.md Typography, icons, writing style, UI copy, commit messages+ architecture/+ OVERVIEW.md System topology, connections, request lifecycle+ backend/+ HONO.md App structure, middleware, routing pattern+ ROUTES.md All routes, method, auth requirement, purpose+ SERVICES.md instagram.js, youtube.js service layer+ MIDDLEWARE.md requireAuth, CORS, context injection+ CACHING.md Redis strategy, cache keys, invalidation+ CRON.md Scheduled handlers, cron triggers+ frontend/+ REACT_ARCHITECTURE.md Provider tree, lazy loading, App.jsx+ ROUTING.md All pages, paths, layout nesting+ CONTEXTS.md AuthContext, AppContext, usage rules+ API_LAYER.md api.js, request(), auth header injection+ FEATURES.md Feature module conventions, directory map+ database/+ SCHEMA.md All tables, columns, types, constraints+ SECURITY.md RLS policy, service vs anon key, isolation+ cloudflare/+ WORKERS.md Worker export, env binding, cron handler+ PAGES.md Frontend deployment, build step, env vars+ CI_CD.md GitHub Actions workflows, path filters+ data-flows/+ AUTHENTICATION.md Login, JWT lifecycle, session management+ PUBLISHING.md Cloudinary to IG container to publish pipeline+ ANALYTICS.md YouTube and Instagram analytics fetch and compute+ SCHEDULING.md Scheduled post lifecycle, dual-scheduler design+ guidelines/+ JAVASCRIPT.md Code style, modules, naming, comments policy+ REACT.md Component rules, hooks, JSX conventions+ HONO.md Route handlers, middleware, context usage+ CLOUDFLARE_WORKERS.md Worker-safe patterns, env access, no Node APIs+ SUPABASE.md Client usage, query patterns, service vs anon+ SHADCN.md Component usage, composition rules, imports+ TAILWIND.md Utility usage, token references, responsive+ NAMING.md File names, function names, variable names+ ERROR_HANDLING.md Error boundaries, API errors, logging+ STATE_MANAGEMENT.md Context vs local state, when to lift+ API_CONVENTIONS.md Response shapes, error shapes, status codes+ mcp/+ OVERVIEW.md When to use each MCP, decision tree+ CONTEXT7.md Library docs, API reference lookups+ FILESYSTEM.md File search, symbol location, refactoring+ SEQUENTIAL_THINKING.md Complex planning, architecture decisions+ PARALLEL_SEARCH.md UX research, best practices, browser compat+ workflows/+ FEATURE_DEVELOPMENT.md 25-step feature implementation sequence+ TESTING.md Test types, commands, pass criteria+ GIT.md Commit format, branch rules, changelog+ DEPLOYMENT.md Backend deploy, frontend deploy, verification+ features/+ NEW_ANALYTICS_PAGE.md Add analytics view for a new platform+ NEW_API_ENDPOINT.md Add a route to the Hono backend+ NEW_REACT_PAGE.md Add a page to the React SPA+ NEW_SCHEDULED_TASK.md Add a new cron handler to the Worker+ NEW_DATABASE_TABLE.md Add a Supabase table with migrations+ NEW_INTEGRATION.md Add a third-party platform (API + OAuth)+ philosophy/+ ARCHITECTURE.md Architectural principles and constraints+ SECURITY.md Security model, key handling, isolation+ PERFORMANCE.md Caching strategy, edge optimization++DECISIONS.md Architectural decision log+CHANGELOG.md Version history and feature changes+ROADMAP.md Planned features and priorities+```++---++## Writing and Design Standards++Read `docs/WRITING_STANDARDS.md` for the full specification. The non-negotiable rules:++- Never use emojis, em dashes (--), or emoticons anywhere in the project+- Never use emoji as icons in UI - use Lucide React SVG icons+- Write clear, professional English with no marketing buzzwords or filler text+- UI copy names things from the user's perspective, not the system's internals+- Error messages explain what went wrong and what to do - no "Something went wrong"+- One comment per non-obvious logic block, maximum - never restate what the code does+- Every page must feel like it belongs to the same application: consistent padding, cards, skeletons, toasts, icons++---++## Engineering Standards++Act like a senior engineer shipping a production application.++Every implementation must be:++- Scalable - does not assume small data sets or single users+- Maintainable - follows established patterns so the next engineer can extend it+- Documented - routes, schema changes, env vars, and data flows are reflected in docs+- Optimized - no unnecessary re-renders, no N+1 queries, no uncached hot paths+- Production-ready - proper error handling at every boundary, no console.log left in++Never implement the quickest solution when a significantly better architecture exists. Always optimize for long-term maintainability over short-term speed.++---++## MCP Usage Rules++### Context7 - Library and API documentation++Use Context7 before implementing anything that involves an external library or API:++- React, Vite, Tailwind, React Router - even for well-known APIs+- Cloudflare Workers, Hono, Supabase, Upstash Redis+- Lucide React, shadcn/ui components+- Browser APIs, modern JavaScript features+- Any third-party package++Do not rely on training knowledge for library APIs. Training data goes stale. Prefer the latest stable API from Context7.++Workflow: `resolve-library-id` first, then `query-docs` with the full question.++### Parallel Search - Research and best practices++Use Parallel Search whenever:++- Researching libraries or comparing implementations+- Checking best practices for a UI pattern, algorithm, or architecture+- Researching browser API behavior or compatibility+- Finding performance optimizations+- Checking accessibility requirements+- Comparing npm packages before recommending one++Search multiple reliable sources before deciding. Never rely on a single article. Summarize findings and implement the best-supported solution.++### Sequential Thinking - Complex planning++Use Sequential Thinking before implementing any large feature:++- Break the problem into ordered steps+- Identify dependencies between steps+- Identify reusable abstractions+- Identify edge cases before they become bugs+- Identify future scalability concerns++Think before coding. Sequential Thinking reduces rewrites.++### Filesystem MCP - File operations within the project++Use Filesystem MCP when searching, reading, or modifying the project:++- Prefer editing existing files over recreating them+- Maintain clean folder structure - no duplicate utilities or components+- Refactor when appropriate rather than adding parallel implementations++### shadcn MCP - Component lookup++Use shadcn MCP for any UI component need:++- Dialogs, forms, cards, buttons, tables, navigation, sheets, dropdowns, popovers+- Check the registry for an official component before building a custom one+- Prefer official shadcn composition patterns over custom implementations++---++## Pre-Feature Research Protocol++Before adding any new feature:++1. Research best practices for the feature type using Parallel Search+2. Research any relevant browser APIs using Parallel Search+3. Research existing UX patterns for this type of feature using Parallel Search+4. Fetch current library documentation using Context7 for any library involved+5. Run Sequential Thinking to plan the implementation before writing code++This is not optional for features that touch new UI patterns, new APIs, or new integrations.++---++## AI Operating Rules++**Always read before writing.** Read every file you will modify. Read all files in the same directory that might be affected. Read sibling files to understand conventions before adding new ones.++**Match the existing pattern.** This project has established conventions for routes, context hooks, db.js queries, cache.js patterns, and api.js methods. Find the nearest existing example and follow it exactly before introducing anything new.++**No TypeScript.** The entire project - backend and frontend - is JavaScript/JSX. Do not suggest or introduce TypeScript unless explicitly asked.++**No dependencies without explicit approval.** The backend uses zero npm dependencies at runtime beyond `hono`, `@supabase/supabase-js`, and `@upstash/redis`. Adding packages to the Cloudflare Worker increases bundle size and startup time. The `scripts/publish-scheduled.js` file uses zero npm dependencies by design.++**Security invariants - never violate these:**+- `SUPABASE_SERVICE_KEY` is only ever used server-side (backend Worker)+- `SUPABASE_ANON_KEY` on the backend is only for JWT verification+- Instagram `accessToken` is always stripped by `safeAccount()` before any response+- All user-scoped queries always append `.eq('user_id', userId)` where `userId` comes from a verified JWT, never from user input+- `backend/.dev.vars` must never be committed++**Use the established db.js pattern.** All database operations go through `lib/db.js`. Never write inline Supabase queries in route handlers. Add new operations to `db.js` and import them.++**Use the established api.js pattern.** All frontend-to-backend calls go through `frontend/src/services/api.js`. Never call `fetch()` directly in components. Add new endpoints to the `api` object in `api.js`.++**Redis failures are always silent.** Wrap all Redis operations in try/catch. Cache misses must fall back to live API calls. The app must work with Redis completely absent.++**Documentation is part of implementation.** When any of the following change - routes, DB schema, environment variables, deployment config, cron jobs, data flows, component conventions - update the relevant docs immediately using the table below.++---++## Git and Commit Standards++- Repository: https://github.com/spacesdrive/twiligent+- Author name: spacesdrive+- Author email: [email protected]+- Read `docs/workflows/GIT.md` for the full commit format++Commit after every meaningful change. Do not batch unrelated changes into one commit. Use Conventional Commits format:++```+type(scope): short imperative description++Optional body explaining why, not what.+```++Tag releases after changes or patches:+- Bug fixes: patch version (v1.0.1, v1.0.2)+- New features: minor version (v1.1.0)+- Breaking changes: major version (v2.0.0)++Do not add "Co-Authored-By: Claude" lines to commit messages. Commits should show only the project author.++---++## Documentation Maintenance Policy++When anything changes, update every relevant docs file from the table below. The rule is: if a file documents something that changed, update it.++| What changed | Files to update |+|---|---|+| New route added | `docs/architecture/backend/ROUTES.md`, `docs/architecture/OVERVIEW.md`, `docs/workflows/TESTING.md` (add to manual verification checklist) |+| Route deleted or changed | `docs/architecture/backend/ROUTES.md`, `docs/architecture/OVERVIEW.md` |+| New DB table | `docs/architecture/database/SCHEMA.md`, `docs/architecture/database/SECURITY.md`, `DECISIONS.md`, `CHANGELOG.md` |+| New DB column | `docs/architecture/database/SCHEMA.md` |+| New env var / Worker secret | `docs/architecture/cloudflare/WORKERS.md`, `docs/architecture/cloudflare/CI_CD.md`, `docs/workflows/DEPLOYMENT.md`, `DECISIONS.md` |+| Env var removed | `docs/architecture/cloudflare/WORKERS.md`, `docs/architecture/cloudflare/CI_CD.md`, `docs/workflows/DEPLOYMENT.md` |+| New npm package (backend) | `docs/architecture/backend/HONO.md`, `DECISIONS.md` |+| New npm package (frontend) | `docs/architecture/frontend/REACT_ARCHITECTURE.md`, `DECISIONS.md` |+| New frontend feature module | `docs/architecture/frontend/FEATURES.md`, `docs/architecture/frontend/ROUTING.md`, `docs/architecture/OVERVIEW.md` |+| New data flow | `docs/architecture/data-flows/` (add or update relevant file), `docs/architecture/OVERVIEW.md` |+| New cron trigger | `docs/architecture/cloudflare/WORKERS.md`, `docs/architecture/backend/CRON.md`, `docs/architecture/cloudflare/CI_CD.md` |+| New GitHub Actions workflow | `docs/architecture/cloudflare/CI_CD.md`, `docs/workflows/DEPLOYMENT.md` |+| New backend service file | `docs/architecture/backend/SERVICES.md` |+| New cache key | `docs/architecture/backend/CACHING.md` |+| New middleware | `docs/architecture/backend/MIDDLEWARE.md`, `docs/architecture/backend/HONO.md` |+| Auth flow changed | `docs/architecture/data-flows/AUTHENTICATION.md` |+| Publishing flow changed | `docs/architecture/data-flows/PUBLISHING.md` |+| Scheduling flow changed | `docs/architecture/data-flows/SCHEDULING.md` |+| Analytics computation changed | `docs/architecture/data-flows/ANALYTICS.md` |+| New React context or hook | `docs/architecture/frontend/CONTEXTS.md` |+| api.js changed | `docs/architecture/frontend/API_LAYER.md` |+| App.jsx routing changed | `docs/architecture/frontend/ROUTING.md` |+| Frontend deployment config changed | `docs/architecture/cloudflare/PAGES.md` |+| Architecture decision made | `DECISIONS.md` (append only, never delete) |+| Any feature shipped | `CHANGELOG.md` (append to Unreleased section) |+| Release tagged | `CHANGELOG.md` (convert Unreleased to version number with date) |+| Any planned feature added or changed | `ROADMAP.md` |+| Writing or design rule changed | `docs/WRITING_STANDARDS.md`, this file (Writing and Design Standards section) |+| MCP usage rule changed | `docs/mcp/OVERVIEW.md`, this file (MCP Usage Rules section) |+| Engineering standard changed | `docs/philosophy/ARCHITECTURE.md`, this file (Engineering Standards section) |+| Security model changed | `docs/philosophy/SECURITY.md`, `docs/architecture/database/SECURITY.md` |+| Caching strategy changed | `docs/philosophy/PERFORMANCE.md`, `docs/architecture/backend/CACHING.md` |+| New integration (platform) | `docs/architecture/backend/SERVICES.md`, `docs/architecture/backend/ROUTES.md`, `docs/architecture/backend/CACHING.md`, `docs/architecture/frontend/FEATURES.md`, `docs/architecture/frontend/ROUTING.md`, `DECISIONS.md`, `CHANGELOG.md` |+| Feature guide added or changed | `docs/features/` (relevant file) |+| Workflow changed | `docs/workflows/` (relevant file) |+| Guideline changed | `docs/guidelines/` (relevant file) |+| Philosophy changed | `docs/philosophy/` (relevant file) |diff --git a/docs/WRITING_STANDARDS.md b/docs/WRITING_STANDARDS.mdnew file mode 100644index 0000000..55c2368--- /dev/null+++ b/docs/WRITING_STANDARDS.md@@ -0,0 +1,122 @@+# Writing and Design Standards++These rules apply to all generated code, documentation, UI copy, commit messages, comments, and any user-facing text in this project. Follow them without exception.++---++## Typography++- Never use emojis.+- Never use Unicode emoji icons.+- Never use emoticons.+- Never use em dashes (--). Use a standard hyphen (-) or restructure the sentence.+- Never use en dashes where a hyphen is appropriate.+- Always use standard ASCII hyphens (-).++---++## Icons++- Never use emoji as icons in UI.+- Use SVG icons only.+- Prefer Lucide React icons (`lucide-react`).+- If Lucide does not have an appropriate icon, use another open-source SVG icon library (e.g. Heroicons, Radix Icons).+- All icons in the same UI context must have consistent size, stroke width, spacing, and visual weight.++---++## Writing Style++Write in clear, professional English.++Avoid:++- Unnecessary buzzwords+- Filler text or padding sentences+- Exaggerated marketing language ("powerful", "blazing fast", "revolutionary")+- Repetitive wording across adjacent sentences++Prefer:++- Concise, direct sentences+- Descriptive headings that name the content, not the type of content+- Readable formatting with appropriate whitespace+- Consistent terminology throughout the project (pick one name for a concept and use it everywhere)++---++## Markdown++Use clean Markdown in all documentation.++Prefer:++- Headings for structure+- Bullet lists for non-sequential items+- Numbered lists for steps or ordered items+- Tables when comparing or listing structured data++Avoid:++- Excessive bold formatting (bold is for the single most critical item in a block, not decoration)+- Nested bullet lists deeper than two levels+- HTML tags inside Markdown except when necessary++---++## Code Comments++Add a comment only when the WHY is non-obvious: a hidden constraint, a subtle invariant, a workaround for a specific external bug, or behavior that would surprise a future reader.++Do not add comments that:++- Describe what the code does (well-named identifiers already do that)+- Reference the current task, ticket, or PR ("added for issue #123")+- Explain callers or downstream effects ("used by X")+- Restate what is visible in the code++One short line per comment, maximum. No multi-paragraph comment blocks.++---++## UI Copy++Write from the user's perspective, not the system's internals.++- Name things by what the user recognizes, not how the code is structured+- Action labels describe exactly what happens: "Publish" not "Submit", "Delete account" not "Remove"+- Success feedback confirms what happened: "Post published" not "Success"+- Error messages explain what went wrong and what to do: "Instagram token expired - reconnect your account" not "Authentication error"+- No apologies in error messages+- No vague messages like "Something went wrong"++---++## Commit Messages++Follow Conventional Commits format (see `docs/workflows/GIT.md` for full details).++- Subject line: type(scope): short imperative sentence+- No period at the end of the subject line+- Subject line under 72 characters+- No emojis or decorative characters+- Past tense is wrong: "add" not "added", "fix" not "fixed"+- Body is optional; include it when the why is non-obvious++---++## UI Consistency++Every page must feel like it belongs to the same application.++Maintain:++- Consistent page padding (`p-6` wrapper)+- Consistent vertical rhythm (`space-y-6` between sections)+- Consistent card structure (shadcn `Card` with `CardHeader`/`CardContent`)+- Consistent loading states (shadcn `Skeleton`)+- Consistent error display (toast notifications via `showToast`)+- Consistent icon usage (Lucide, same stroke width)+- Consistent button variants (primary for main action, outline for secondary)++The entire project should feel like one polished application, not independently built pages.diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.mdnew file mode 100644index 0000000..7bab312--- /dev/null+++ b/docs/architecture/OVERVIEW.md@@ -0,0 +1,122 @@+# Architecture Overview++## System Topology++```+┌─────────────────────────────────────────────────────────────────┐+│ Browser (User) │+│ React SPA — Cloudflare Pages │+│ https://twiligent.pages.dev │+└────────────────────────┬────────────────────────────────────────┘+ │ HTTPS + Bearer JWT+ ▼+┌─────────────────────────────────────────────────────────────────┐+│ Cloudflare Worker — "twiligent" │+│ https://twiligent.ujjwalkrai.workers.dev/api │+│ │+│ Hono v4 app │+│ ├── Global middleware: CORS, Supabase client, Redis client │+│ ├── Public: GET /api/health, GET /api/auth/instagram/callback │+│ └── Protected (/api/*): requireAuth → routes │+│ │+│ Cron handlers (wrangler.toml triggers): │+│ ├── */15 * * * * → processScheduledPosts() │+│ └── 0 0 * * * → autoRefreshInstagramTokens() │+└──────┬──────────┬──────────────┬────────────────────────────────┘+ │ │ │+ ▼ ▼ ▼+┌──────────┐ ┌─────────┐ ┌──────────────────────────────────────┐+│ Supabase │ │ Upstash │ │ External APIs │+│ Postgres │ │ Redis │ │ ├── YouTube Data API v3 │+│ │ │ (cache) │ │ ├── Instagram Graph API v25 │+│ tables: │ │ │ │ └── Cloudinary Upload API │+│ accounts │ │ keys: │ └──────────────────────────────────────┘+│ settings │ │ videos: │+│ sched_ │ │ {u}:{a} │+│ posts │ │ ig:{u}: │+│ │ │ {a} │+│ auth: │ │ │+│ users │ │ optional│+└──────────┘ └─────────┘+```++## Deployment Topology++| Component | Platform | URL |+|---|---|---|+| Backend API | Cloudflare Workers | `twiligent.ujjwalkrai.workers.dev` |+| Frontend SPA | Cloudflare Pages | `twiligent.pages.dev` |+| Database + Auth | Supabase | `nheuatbcevaxgxyvahtr.supabase.co` |+| Media cache | Upstash Redis | Configured via `UPSTASH_REDIS_REST_URL` |+| Media hosting | Cloudinary | `CLOUDINARY_CLOUD_NAME` |+| CI/CD | GitHub Actions | `spacesdrive/twiligent` |++## Request Lifecycle (Protected Route)++```+Browser+ → fetch(`${VITE_API_URL}/accounts`, { Authorization: Bearer <jwt> })+ ↓+Cloudflare Worker edge node (nearest to user)+ → CORS middleware (checks origin)+ → Client injection middleware (creates Supabase + Redis clients from env)+ → requireAuth middleware+ → extracts Bearer token from Authorization header+ → supabaseAuth.auth.getUser(token) → Supabase validates JWT+ → sets c.userId, c.userEmail on Hono context+ → route handler (e.g., accounts router)+ → db.getAccounts(supabase, userId) [lib/db.js]+ → supabase.from('accounts').select(...).eq('user_id', userId)+ → normalizes rows+ → returns JSON response+```++## Cron Lifecycle++```+Cloudflare scheduler fires cron trigger+ → Worker.scheduled(event, env, ctx)+ → getSupabase(env) [creates service-role client]+ → if event.cron === '*/15 * * * *':+ ctx.waitUntil(processScheduledPosts(supabase))+ → db.getDuePosts(supabase) [no userId filter — scans all users]+ → for each post: publishToInstagram(post, account)+ → db.updatePost(supabase, id, { status: 'published' })+ → if event.cron === '0 0 * * *':+ ctx.waitUntil(autoRefreshInstagramTokens(supabase))+ → db.getAccounts(supabase) [all users, platform='instagram']+ → for each expiring token: igFetch refresh endpoint+ → db.updateAccount(supabase, id, { accessToken: newToken })+```++## Data Storage Strategy++| Data type | Where stored | Why |+|---|---|---|+| User accounts (auth) | Supabase Auth | Built-in JWT issuance |+| YouTube/Instagram accounts | `accounts` table, `data` jsonb | Flexible schema across platforms |+| User settings (GitHub PAT) | `settings` table, `value` jsonb | Generic key-value per user |+| Scheduled posts | `scheduled_posts` table | Queryable by status + scheduled_at |+| Video/media analytics | Upstash Redis (`videos:` / `ig:` keys) | Avoids repeated heavy API calls |+| Media files (for publishing) | Cloudinary CDN | Instagram requires public URL |+| API secrets | Cloudflare Worker secrets | Encrypted at rest, never in responses |++## Environment Configuration++See `docs/architecture/cloudflare/WORKERS.md` for the full list of required Worker secrets and how to set them.++Frontend env vars are documented in `docs/architecture/cloudflare/PAGES.md`.++## Key Architectural Invariants++1. **The Worker never receives binary file uploads.** Cloudinary handles file ingestion directly from the browser. The Worker only receives Cloudinary URLs.++2. **Redis is always optional.** Every cache call is wrapped in try/catch and falls back to live APIs. Removing Upstash credentials degrades performance but never breaks functionality.++3. **The service-role key is never used on the frontend.** The frontend uses only the anon key (for Supabase Auth client-side). The service-role key is a Worker secret.++4. **`safeAccount()` is the only place access tokens are stripped.** Any route that returns account data must pass through this function before responding.++5. **`db.js` is the only file that contains Supabase queries.** Route handlers import and call db functions — they never call `supabase.from()` directly.++6. **`api.js` is the only file that calls `fetch()` in the frontend.** Components call `api.methodName()` — they never construct fetch calls.diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.mdnew file mode 100644index 0000000..9c41a1b--- /dev/null+++ b/docs/architecture/backend/CACHING.md@@ -0,0 +1,74 @@+# Backend Caching Strategy++## Overview++Caching is implemented via Upstash Redis (REST API) using the `@upstash/redis` SDK. It is **entirely optional** — if `UPSTASH_REDIS_REST_URL` is not set, `getRedis()` returns `null` and all cache functions in `lib/cache.js` silently no-op.++## Cache Layer: `backend/lib/cache.js`++All cache operations follow this contract:+- Accept `redis` as the first argument+- If `redis` is `null`, return immediately (no-op)+- Wrap all `redis` calls in `try/catch` — a Redis failure must never break the main request++```js+export async function getVideosCache(redis, userId, accountId) {+ if (!redis) return null;+ try { return (await redis.get(`videos:${userId}:${accountId}`)) || null; } catch { return null; }+}+```++## Cache Keys++| Key pattern | Content | Set when | Invalidated when |+|---|---|---|---|+| `videos:{userId}:{accountId}` | Array of YouTube video objects with stats | `GET /api/accounts/:id/analytics` succeeds | `DELETE /api/accounts/:id` |+| `ig:{userId}:{accountId}` | Array of Instagram media objects | `GET /api/accounts/:id/ig-analytics` succeeds | `DELETE /api/accounts/:id` |+| `oauth_ig:{state}` | userId string (legacy, Redis-backed) | Instagram OAuth URL generation | Consumed on callback; 10-min TTL |++**Note:** The `oauth_ig:` key is a legacy path. The current OAuth implementation uses HMAC-signed state tokens that don't require Redis. This key is set and consumed only when Redis is available, as a secondary verification layer.++## Cache TTL++Currently no TTL is set on `videos:` or `ig:` keys. Cached data persists until:+1. The account is deleted (explicit `redis.del()`)+2. The Redis instance is flushed manually++**Known issue:** This means analytics data can become stale. A future improvement is to set a TTL (e.g., 24 hours) on both key types. See `ROADMAP.md`.++## Cache Usage in Routes++The analytics routes use this pattern:++```js+// GET /api/accounts/:id/analytics+const cached = await getVideosCache(redis, userId, accountId);+if (cached) return c.json(cached);++// fetch fresh data from YouTube API...+const result = { /* computed analytics */ };++await setVideosCache(redis, userId, accountId, result);+return c.json(result);+```++## Adding New Cache Keys++1. Add getter, setter, and deleter functions to `backend/lib/cache.js`+2. Follow the existing naming convention: `{entity}:{userId}:{accountId}`+3. Always guard with `if (!redis) return null/undefined`+4. Always wrap in `try/catch`+5. Call the deleter in the account deletion handler if the cache is account-specific+6. Update this document++## HMAC OAuth State (Not Redis)++The `createOAuthState()` and `verifyOAuthState()` functions in `cache.js` are **not** Redis-based. They use `crypto.subtle.sign()` (native Web Crypto API in Workers) to create self-verifying state tokens. Redis is not involved.++```+State format: base64url(userId:timestamp).base64url(HMAC-SHA256-signature)+Expiry: 10 minutes (checked by comparing embedded timestamp to Date.now())+Secret: INSTAGRAM_APP_SECRET+```++These functions are in `cache.js` for historical reasons — they started as Redis-backed and were migrated to HMAC. They could logically live in `lib/auth.js` but remain in `cache.js` for stability.diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.mdnew file mode 100644index 0000000..c860e78--- /dev/null+++ b/docs/architecture/backend/CRON.md@@ -0,0 +1,86 @@+# Backend Cron Jobs++## Configuration (`backend/wrangler.toml`)++```toml+[triggers]+crons = ["*/15 * * * *", "0 0 * * *"]+```++Both cron triggers invoke the `scheduled` export from `backend/server.js`.++## Cron Handlers++### `*/15 * * * *` — Instagram Scheduled Post Publisher++**Function:** `processScheduledPosts(supabase)` in `backend/utils/scheduler.js`++**What it does:**+1. Queries `scheduled_posts` where `status = 'pending'` and `scheduled_at <= now()`+2. For each due post:+ - Fetches the associated account from `accounts` table+ - Sets post status to `'publishing'` (prevents double-publish if two schedulers run concurrently)+ - Calls `publishToInstagram(post, account)` in `backend/services/instagram.js`+ - On success: sets status to `'published'`, stores `publishedMediaId` and `publishedAt` in `data`+ - On failure: sets status to `'failed'`, stores `error` message in `data`++**No userId filter** — the scheduler operates across all users. It uses the service-role Supabase client.++**Concurrency safety:** The `'publishing'` status acts as a mutex. If the Worker cron and GitHub Actions cron overlap, the second one to claim a post will find it already in `'publishing'` state and skip it (it won't appear in the `status=pending` query).++### `0 0 * * *` — Instagram Token Auto-Refresh++**Function:** `autoRefreshInstagramTokens(supabase)` in `backend/services/instagram.js`++**What it does:**+1. Queries all accounts with `platform = 'instagram'`+2. For each account, checks if the Instagram long-lived token expires within 15 days+3. If expiring soon: calls `GET https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=<token>`+4. Updates the account's `accessToken` in Supabase++**Token lifecycle:**+- Instagram issues long-lived tokens valid for 60 days+- Tokens must be refreshed before they expire+- The daily cron refreshes any token expiring within 15 days+- This gives a 15-day window for recovery if the cron fails for a few days++## The `ctx.waitUntil()` Pattern++Cron handlers use `ctx.waitUntil()` to run work after the handler returns:++```js+async scheduled(event, env, ctx) {+ const supabase = getSupabase(env);+ if (event.cron === '*/15 * * * *') {+ ctx.waitUntil(processScheduledPosts(supabase));+ }+}+```++This is required because Workers have a request deadline. `ctx.waitUntil()` tells the Workers runtime to keep the isolate alive until the promise resolves, even after the handler returns.++## Dual-Scheduler (GitHub Actions Fallback)++The same `*/15` publishing logic also runs via `scripts/publish-scheduled.js` in GitHub Actions. See `docs/architecture/data-flows/SCHEDULING.md` for details on how both systems coexist safely.++## Adding a New Cron Trigger++1. Add the cron expression to `wrangler.toml`:+ ```toml+ crons = ["*/15 * * * *", "0 0 * * *", "0 12 * * 1"]+ ```++2. Add a handler branch in `server.js`:+ ```js+ } else if (event.cron === '0 12 * * 1') {+ ctx.waitUntil(myWeeklyJob(supabase));+ }+ ```++3. Implement `myWeeklyJob(supabase)` in the appropriate service or utils file++4. Update `docs/architecture/backend/CRON.md` (this file)++5. Update `docs/architecture/cloudflare/WORKERS.md`++6. Append to `DECISIONS.md` if this represents an architectural choicediff --git a/docs/architecture/backend/HONO.md b/docs/architecture/backend/HONO.mdnew file mode 100644index 0000000..701c2e6--- /dev/null+++ b/docs/architecture/backend/HONO.md@@ -0,0 +1,136 @@+# Backend — Hono Application Structure++## Entry Point: `backend/server.js`++The entire backend is a single Hono application exported as a Cloudflare Workers module.++```js+// The two exports Cloudflare Workers looks for:+export default {+ fetch: app.fetch, // handles all HTTP requests+ async scheduled(event, env, ctx) { ... } // handles cron triggers+};+```++## Application Structure++```+const app = new Hono(); // root application++// Global middleware (runs on every request)+app.use('*', cors());+app.use('*', clientInjectionMiddleware); // attaches supabase + redis to context++// Public routes+app.get('/api/health', ...);+app.get('/api/auth/instagram/callback', callbackHandler);++// Protected sub-application+const api = new Hono();+api.use('*', requireAuth); // JWT verification on all /api/* routes+api.route('/', keysRouter);+api.route('/', accountsRouter);+api.route('/', analyticsRouter);+api.route('/', publishingRouter);+api.route('/', scheduledPostsRouter);+api.route('/', settingsRouter);+api.get('/auth/instagram/url', urlHandler);++app.route('/api', api); // mount protected sub-app under /api+```++## Context Values++These are set on the Hono context (`c`) and available in all route handlers:++| Key | Type | Set by | Available after |+|---|---|---|---|+| `supabase` | Supabase client (service-role) | global middleware | All routes |+| `redis` | Upstash Redis client \| null | global middleware | All routes |+| `userId` | string (UUID) | `requireAuth` | Protected routes only |+| `userEmail` | string | `requireAuth` | Protected routes only |++**Accessing context values in a handler:**+```js+export async function myHandler(c) {+ const supabase = c.get('supabase');+ const redis = c.get('redis');+ const userId = c.get('userId');+ // ...+}+```++## Route File Pattern++Every route file follows this structure:++```js+// backend/routes/myFeature.js+import { Hono } from 'hono';+import { getMyData, createMyData } from '../lib/db.js';++const router = new Hono();++router.get('/my-resource', async (c) => {+ const userId = c.get('userId');+ const supabase = c.get('supabase');+ try {+ const data = await getMyData(supabase, userId);+ return c.json(data);+ } catch (err) {+ console.error('GET /my-resource:', err.message);+ return c.json({ error: err.message }, 500);+ }+});++router.post('/my-resource', async (c) => {+ const userId = c.get('userId');+ const supabase = c.get('supabase');+ const body = await c.req.json();+ // validate body...+ try {+ await createMyData(supabase, body, userId);+ return c.json({ success: true }, 201);+ } catch (err) {+ console.error('POST /my-resource:', err.message);+ return c.json({ error: err.message }, 500);+ }+});++export default router;+```++Then in `server.js`:+```js+import myFeatureRouter from './routes/myFeature.js';+// ...+api.route('/', myFeatureRouter);+```++## Error Handling++The global error handler catches uncaught errors:+```js+app.onError((err, c) => {+ console.error('Worker error:', err.message);+ return c.json({ error: 'Internal server error' }, 500);+});+```++Route handlers should catch their own errors and return descriptive messages. Do not throw from route handlers — catch and return JSON error responses with appropriate status codes.++## Environment Access++Worker environment variables are accessed via `c.env` in middleware and handlers, or via the `env` parameter in the `scheduled` handler:++```js+// In middleware or handler:+const apiKey = c.env.YOUTUBE_API_KEY;++// In cron handler:+async scheduled(event, env, ctx) {+ const supabase = getSupabase(env);+}+```++**Never hardcode secrets.** All secrets must come from `c.env` (Worker secrets set via `wrangler secret put`).diff --git a/docs/architecture/backend/MIDDLEWARE.md b/docs/architecture/backend/MIDDLEWARE.mdnew file mode 100644index 0000000..3306c5c--- /dev/null+++ b/docs/architecture/backend/MIDDLEWARE.md@@ -0,0 +1,104 @@+# Backend Middleware++## Middleware Stack (in execution order)++```+Request arrives+ │+ ▼+1. CORS middleware app.use('*', cors())+ │+ ▼+2. Client injection app.use('*', clientInjectionMiddleware)+ │+ ▼+3. requireAuth api.use('*', requireAuth) ← protected routes only+ │+ ▼+Route handler+```++---++## 1. CORS Middleware++**Source:** `hono/cors` (Hono built-in)+**Applied to:** Every request++Configured with defaults — allows all origins in development. For production, the Worker's CORS behavior should be tightened to only allow `FRONTEND_URL`.++**Current config:** `cors()` with no options (allows all origins). This is acceptable for a self-hosted deployment where the Worker URL is not publicly advertised.++---++## 2. Client Injection Middleware++**Source:** Inline in `backend/server.js`+**Applied to:** Every request++Creates per-request Supabase and Redis client instances and sets them on the Hono context. This is the correct pattern for Cloudflare Workers — clients must be created fresh per request because there is no persistent process memory.++```js+app.use('*', async (c, next) => {+ c.set('supabase', getSupabase(c.env));+ c.set('redis', getRedis(c.env));+ await next();+});+```++**`getSupabase(env)`** — creates a Supabase client with the service-role key. Used for all DB operations.+**`getRedis(env)`** — creates an Upstash Redis client if `UPSTASH_REDIS_REST_URL` is set, otherwise returns `null`. All cache functions in `lib/cache.js` handle `null` silently.++---++## 3. requireAuth Middleware++**Source:** `backend/middleware/auth.js`+**Applied to:** All routes mounted under the `api` sub-application (`/api/*`)++```js+export async function requireAuth(c, next) {+ const token = c.req.header('Authorization')?.replace('Bearer ', '');+ if (!token) return c.json({ error: 'Unauthorized' }, 401);+ const supabaseAuth = getSupabaseAuth(c.env);+ const { data: { user }, error } = await supabaseAuth.auth.getUser(token);+ if (error || !user) return c.json({ error: 'Invalid or expired token' }, 401);+ c.set('userId', user.id);+ c.set('userEmail', user.email);+ await next();+}+```++**What it does:**+1. Extracts `Authorization: Bearer <token>` header+2. Creates a Supabase **anon** client (not service-role) to verify the JWT+3. Calls `supabaseAuth.auth.getUser(token)` — Supabase validates the token signature+4. Sets `userId` (UUID) and `userEmail` (string) on the Hono context+5. Returns 401 JSON if token is missing, invalid, or expired++**Critical:** `userId` from this middleware is the only trusted source of user identity. Route handlers must use `c.get('userId')` — never accept a userId from request body or query params.++---++## Adding New Middleware++Place new middleware files in `backend/middleware/`. Follow this pattern:++```js+// backend/middleware/myMiddleware.js+export async function myMiddleware(c, next) {+ // do something before route handler+ await next();+ // optionally do something after route handler+}+```++Apply globally in `server.js`:+```js+app.use('*', myMiddleware);+```++Or apply to a specific route group:+```js+api.use('/admin/*', adminOnlyMiddleware);+```diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdnew file mode 100644index 0000000..4edfa47--- /dev/null+++ b/docs/architecture/backend/ROUTES.md@@ -0,0 +1,80 @@+# Backend Routes++All routes live under `/api`. Routes under the `api` sub-app require a valid Supabase JWT (`requireAuth` middleware). Public routes bypass auth.++## Public Routes++| Method | Path | Handler | Purpose |+|---|---|---|---|+| GET | `/api/health` | inline | Returns `{ status: 'ok', timestamp }` |+| GET | `/api/auth/instagram/callback` | `instagramAuth.callbackHandler` | OAuth code exchange; browser redirect after Instagram login |++## Protected Routes (require `Authorization: Bearer <jwt>`)++### Keys+| Method | Path | File | Purpose |+|---|---|---|---|+| GET | `/api/keys` | `routes/keys.js` | Returns `{ youtube: bool, instagram: bool, cloudinary: bool }` — whether each API key is configured |++### Accounts+| Method | Path | File | Purpose |+|---|---|---|---|+| GET | `/api/accounts` | `routes/accounts.js` | List all user accounts (tokens stripped via `safeAccount()`) |+| POST | `/api/accounts` | `routes/accounts.js` | Add YouTube channel — resolves URL/handle to channel ID, fetches stats |+| DELETE | `/api/accounts/:id` | `routes/accounts.js` | Remove account + invalidate Redis cache for that account |+| POST | `/api/accounts/refresh-all` | `routes/accounts.js` | Refresh stats for every account; returns updated accounts list |+| POST | `/api/accounts/:id/refresh` | `routes/accounts.js` | Refresh a single account's stats |+| POST | `/api/accounts/instagram` | `routes/accounts.js` | Add Instagram account via a raw access token (for manual setup) |+| POST | `/api/accounts/:id/refresh-ig-token` | `routes/accounts.js` | Extend Instagram long-lived token (valid up to 60 days; refresh when < 15 days remain) |++### Analytics+| Method | Path | File | Purpose |+|---|---|---|---|+| GET | `/api/accounts/:id/analytics` | `routes/analytics.js` | Full YouTube analytics — fetches up to 500 videos, runs `computeVideoAnalytics()`, returns 50+ metrics |+| GET | `/api/accounts/:id/videos` | `routes/analytics.js` | Returns cached video list (from Redis if available) |+| GET | `/api/accounts/:id/ig-analytics` | `routes/analytics.js` | Instagram analytics — fetches up to 500 media, runs `computeInstagramAnalytics()` |+| GET | `/api/accounts/:id/ig-media` | `routes/analytics.js` | Returns cached Instagram media list |+| GET | `/api/comparison` | `routes/analytics.js` | Cross-account comparison data for the Overview dashboard |++### Instagram OAuth+| Method | Path | File | Purpose |+|---|---|---|---|+| GET | `/api/auth/instagram/url` | `routes/instagramAuth.js` | Generates Instagram OAuth URL with HMAC-signed state. Returns `{ url }`. |++### Publishing+| Method | Path | File | Purpose |+|---|---|---|---|+| GET | `/api/cloudinary-config` | `routes/publishing.js` | Returns `{ cloudName, uploadPreset }` for frontend Cloudinary upload |+| GET | `/api/accounts/:id/ig-publishing-limit` | `routes/publishing.js` | Checks daily Instagram publishing quota remaining |+| POST | `/api/accounts/:id/ig-publish` | `routes/publishing.js` | Creates Instagram media container via Graph API; returns `{ containerId }` |+| GET | `/api/ig-container/:id/status` | `routes/publishing.js` | Polls container status (`FINISHED`, `IN_PROGRESS`, `ERROR`, `EXPIRED`) |+| POST | `/api/accounts/:id/ig-media-publish` | `routes/publishing.js` | Publishes the container to Instagram; returns `{ mediaId }` |++### Scheduled Posts+| Method | Path | File | Purpose |+|---|---|---|---|+| GET | `/api/scheduled-posts` | `routes/scheduledPosts.js` | List all user's scheduled posts, ordered by `scheduled_at` ascending |+| POST | `/api/scheduled-posts` | `routes/scheduledPosts.js` | Create a new scheduled post with `status: 'pending'` |+| PUT | `/api/scheduled-posts/:id` | `routes/scheduledPosts.js` | Edit a pending post (caption, scheduled time, media, etc.) |+| DELETE | `/api/scheduled-posts/:id` | `routes/scheduledPosts.js` | Delete a single post |+| DELETE | `/api/scheduled-posts` | `routes/scheduledPosts.js` | Delete all posts except those with `status: 'publishing'` |+| GET | `/api/process-scheduled` | `routes/scheduledPosts.js` | Manual trigger — runs `processScheduledPosts()` immediately (dev/test) |+| POST | `/api/process-scheduled` | `routes/scheduledPosts.js` | Same as above |++### Settings+| Method | Path | File | Purpose |+|---|---|---|---|+| GET | `/api/settings/github` | `routes/settings.js` | Retrieve GitHub PAT + repo config for the current user |+| PUT | `/api/settings/github` | `routes/settings.js` | Save GitHub PAT + repo config |++## Adding a New Route++See `docs/features/NEW_API_ENDPOINT.md` for the complete workflow.++**Quick checklist:**+1. Create `backend/routes/myFeature.js` (copy an existing route file as a template)+2. Export the router as default+3. Import and mount in `backend/server.js` via `api.route('/', myFeatureRouter)`+4. Add all db operations to `backend/lib/db.js`+5. Update `docs/architecture/backend/ROUTES.md` (this file)+6. Update `frontend/src/services/api.js` with corresponding frontend methodsdiff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdnew file mode 100644index 0000000..7e0962c--- /dev/null+++ b/docs/architecture/backend/SERVICES.md@@ -0,0 +1,106 @@+# Backend Services++Services in `backend/services/` contain all logic for communicating with external APIs (YouTube, Instagram) and computing analytics. Route handlers call services; services never import from routes.++## `backend/services/instagram.js`++### HTTP Client++All Instagram Graph API calls go through `igFetch(path, token, options)`:++```js+async function igFetch(path, token, options = {}) {+ const url = `https://graph.instagram.com/v25.0${path}`;+ const res = await fetch(url, {+ headers: { Authorization: `Bearer ${token}` },+ ...options,+ });+ const data = await res.json();+ if (data.error) throw new Error(data.error.message);+ return data;+}+```++### Key Functions++| Function | Purpose |+|---|---|+| `exchangeCodeForToken(code, env)` | Short-lived code → short-lived token (Instagram OAuth step 1) |+| `exchangeForLongLivedToken(shortToken, env)` | Short-lived → 60-day long-lived token (Instagram OAuth step 2) |+| `getIGProfile(accessToken)` | Fetches `id, username, account_type, media_count` for the token |+| `getIGMedia(accessToken, limit)` | Paginates media items up to `limit` (default 500) |+| `refreshLongLivedToken(accessToken)` | Extends a long-lived token; call before expiry |+| `autoRefreshInstagramTokens(supabase)` | Cron handler — refreshes all tokens expiring within 15 days |+| `computeInstagramAnalytics(media, profile)` | Computes engagement rates, hashtag analysis, timing patterns, monthly breakdown |+| `publishIGContainer(igUserId, params, token)` | Creates a media container via Graph API |+| `publishIGMedia(igUserId, containerId, token)` | Publishes a container; returns `mediaId` |++### `safeAccount(account)`++Strips the `accessToken` field before the account object is returned in any API response:++```js+function safeAccount(account) {+ const { accessToken, ...safe } = account;+ return safe;+}+```++**This function must be applied to every account object before it leaves the backend.** Route handlers are responsible for calling `safeAccount()` or using `db.getAccounts()` variants that apply it.++---++## `backend/services/youtube.js`++### HTTP Client++All YouTube Data API v3 calls use `ytFetch(path, params, env)`:++```js+async function ytFetch(path, params, env) {+ const qs = new URLSearchParams({ ...params, key: env.YOUTUBE_API_KEY });+ const res = await fetch(`https://www.googleapis.com/youtube/v3${path}?${qs}`);+ const data = await res.json();+ if (data.error) throw new Error(data.error.message);+ return data;+}+```++### Key Functions++| Function | Purpose |+|---|---|+| `resolveChannelId(input, env)` | Resolves a YouTube URL, handle, or channel ID to a canonical channel ID |+| `fetchChannelData(channelId, env)` | Fetches channel snippet, statistics, and branding |+| `fetchAllVideos(channelId, uploadPlaylistId, env)` | Paginates through playlist items API (50 per page, up to 10 pages = 500 videos) + batch-fetches video statistics |+| `computeVideoAnalytics(videos, channel)` | Computes 50+ analytics metrics from the video dataset |++### Analytics Computation++`computeVideoAnalytics()` returns a rich analytics object including:+- Channel-level: total views, subscribers, videos, avg views per video+- Engagement: avg likes, comments, like rate, comment rate+- Performance: best/worst video, views per day (normalized by age)+- Frequency: videos per month, posting regularity+- Shorts vs. long-form split (by count and views)+- Monthly breakdown of uploads and views+- Category distribution++`computeInstagramAnalytics()` (in `instagram.js`) returns:+- Engagement rate (likes + comments / followers)+- Average likes, comments per post+- Best performing post+- Hashtag frequency analysis+- Caption length vs. engagement correlation+- Posting time distribution (hour of day, day of week)+- Monthly media count and engagement++---++## Adding a New Service++1. Create `backend/services/myPlatform.js`+2. Define an internal fetch helper (`myPlatformFetch`) that handles base URL, auth headers, and error extraction+3. Export named functions for each operation (fetch data, exchange tokens, compute analytics)+4. If the platform requires OAuth, add token exchange functions following the Instagram pattern+5. Update `docs/architecture/backend/SERVICES.md` (this file)diff --git a/docs/architecture/cloudflare/CI_CD.md b/docs/architecture/cloudflare/CI_CD.mdnew file mode 100644index 0000000..62b267f--- /dev/null+++ b/docs/architecture/cloudflare/CI_CD.md@@ -0,0 +1,91 @@+# CI/CD — GitHub Actions++## Workflows++### `deploy-backend.yml`++**Trigger:** Push to `main` branch, when files under `backend/**` or `.github/workflows/deploy-backend.yml` change++**What it does:**+1. Checkout repo+2. Run `wrangler deploy` via `cloudflare/wrangler-action@v4`++**Required GitHub secrets:**+- `CLOUDFLARE_API_TOKEN` — API token with Worker deploy permission+- `CLOUDFLARE_ACCOUNT_ID` — your Cloudflare account ID++**Does not** redeploy on frontend-only changes, documentation changes, or script changes.++---++### `deploy-frontend.yml`++**Trigger:** Push to `main` branch, when files under `frontend/**` or `.github/workflows/deploy-frontend.yml` change++**What it does:**+1. Checkout repo+2. `npm ci` (in `frontend/`)+3. `npm run build` — Vite builds to `frontend/dist/`+4. Deploy `dist/` to Cloudflare Pages via `wrangler pages deploy`++**Required GitHub secrets:**+- `CLOUDFLARE_API_TOKEN`+- `CLOUDFLARE_ACCOUNT_ID`+- `VITE_SUPABASE_URL` — injected at build time+- `VITE_SUPABASE_ANON_KEY` — injected at build time+- `VITE_API_URL` — injected at build time (the Worker URL)++**Note:** `VITE_*` variables are baked into the built JS bundle at build time. They are not runtime environment variables.++---++### `publish-scheduled.yml`++**Trigger:**+- `schedule: cron('*/15 * * * *')` — every 15 minutes+- `workflow_dispatch` — manual trigger from GitHub Actions UI++**What it does:**+1. Checkout repo+2. Setup Node.js 20+3. `node scripts/publish-scheduled.js`++**Required GitHub secrets:**+- `SUPABASE_URL` — the Supabase project URL+- `SUPABASE_SERVICE_KEY` — service-role key (needed to query all users' posts)++**This is the GitHub Actions fallback for the Worker cron.** Both this workflow and the Worker cron (`*/15`) run the same publishing logic against the same Supabase table. The `publishing` status mutex prevents double-publishing.++---++## Path Filtering++GitHub Actions path filters mean:+- Editing `frontend/` only → triggers `deploy-frontend.yml`, not `deploy-backend.yml`+- Editing `backend/` only → triggers `deploy-backend.yml`, not `deploy-frontend.yml`+- Editing `scripts/` → triggers neither deploy workflow (only `publish-scheduled.yml` on its cron)+- Editing `docs/` → triggers nothing+- Editing `CLAUDE.md`, `DECISIONS.md`, etc. → triggers nothing++## Deployment Verification++After a deploy, verify:++**Backend:**+```bash+curl https://twiligent.ujjwalkrai.workers.dev/api/health+# Should return: {"status":"ok","timestamp":"..."}+```++**Frontend:**+Open `https://twiligent.pages.dev` — verify login page loads, accounts load after auth.++**Publisher:**+Trigger `publish-scheduled.yml` manually via GitHub Actions UI → Actions → "Instagram Scheduled Publisher" → "Run workflow" → check the run log for expected output.++## Adding a New Workflow++1. Create `.github/workflows/my-workflow.yml`+2. Add appropriate path filters to avoid unnecessary runs+3. Document it in `docs/architecture/cloudflare/CI_CD.md` (this file)+4. Add any required secrets via GitHub repo → Settings → Secrets → Actionsdiff --git a/docs/architecture/cloudflare/PAGES.md b/docs/architecture/cloudflare/PAGES.mdnew file mode 100644index 0000000..930b023--- /dev/null+++ b/docs/architecture/cloudflare/PAGES.md@@ -0,0 +1,84 @@+# Cloudflare Pages (Frontend Deployment)++## Overview++The React frontend is deployed to Cloudflare Pages. It is a static SPA — all routing is client-side (React Router), and the Cloudflare Pages `_redirects` file handles the SPA fallback.++## Build Configuration++| Setting | Value |+|---|---|+| Framework preset | None (Vite) |+| Build command | `cd frontend && npm install && npm run build` |+| Build output directory | `frontend/dist` |+| Root directory | `/` (repo root) |+| Node.js version | 20 |++These are configured in the Cloudflare Pages project settings, not in a file.++## SPA Fallback++All requests that don't match a static file should serve `index.html` so React Router can handle the path. This is configured in:++```+frontend/public/_redirects+```++```+/* /index.html 200+```++If this file is missing, direct URL navigation (e.g., visiting `/settings`) will return a 404.++## Environment Variables++The frontend accesses environment variables at **build time** via Vite's `VITE_` prefix convention:++| Variable | Purpose | Where set |+|---|---|---|+| `VITE_SUPABASE_URL` | Supabase project URL (public) | Cloudflare Pages → Settings → Environment Variables |+| `VITE_SUPABASE_ANON_KEY` | Supabase anon key (public) | Cloudflare Pages → Settings → Environment Variables |+| `VITE_API_URL` | Backend Worker URL | Cloudflare Pages → Settings → Environment Variables |++**These are public values** — they are baked into the JavaScript bundle. Do not add the service role key here. Do not add any private API credentials here.++Vite exposes them at runtime as `import.meta.env.VITE_*`.++## Deployment++Cloudflare Pages deploys automatically on every push to `main` that changes files in `frontend/`. This is configured in `.github/workflows/deploy-frontend.yml`.++Manual deployment (emergency or first setup):++```bash+cd frontend+npm install+npm run build+npx wrangler pages deploy dist --project-name=twiligent+```++## Custom Domain++The app is accessible at both:+- `twiligent.pages.dev` (Cloudflare Pages default)+- Custom domain configured in Cloudflare Pages → Custom domains++## Local Development++```bash+cd frontend && npm run dev+```++The frontend dev server proxies `/api` requests to the Worker (see `frontend/vite.config.js`). Start the backend Worker at the same time:++```bash+cd backend && wrangler dev+```++## First-Time Setup++1. Create a new Cloudflare Pages project in the Cloudflare dashboard+2. Connect it to the GitHub repository+3. Set build command and output directory as above+4. Add environment variables (`VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`, `VITE_API_URL`)+5. Trigger the first deploy manually or push to `main`diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.mdnew file mode 100644index 0000000..2289e51--- /dev/null+++ b/docs/architecture/cloudflare/WORKERS.md@@ -0,0 +1,105 @@+# Cloudflare Workers++## Worker Configuration (`backend/wrangler.toml`)++```toml+name = "twiligent"+main = "server.js"+compatibility_date = "2025-01-01"++[triggers]+crons = ["*/15 * * * *", "0 0 * * *"]+```++- `name` — the Worker name as deployed on Cloudflare; also determines the default URL+- `main` — entry point file (ES module)+- `compatibility_date` — pins the Workers runtime API version+- `crons` — cron trigger schedules (see `docs/architecture/backend/CRON.md`)++## Worker Export Format++The Worker exports two handlers:++```js+export default {+ fetch: app.fetch, // handles HTTP requests (the Hono app)+ async scheduled(event, env, ctx) { // handles cron triggers+ // event.cron — the cron expression that fired+ // env — Worker environment bindings (secrets + vars)+ // ctx.waitUntil(promise) — keeps Worker alive for background work+ }+};+```++## Environment Bindings (Secrets)++All secrets are set via `wrangler secret put <NAME>`. They are available at runtime as `env.NAME` or `c.env.NAME`.++| Secret | Required | Purpose |+|---|---|---|+| `SUPABASE_URL` | Yes | Supabase project URL |+| `SUPABASE_SERVICE_KEY` | Yes | Service-role key — bypasses RLS, all DB operations |+| `SUPABASE_ANON_KEY` | Yes | Anon key — used only for JWT verification in `requireAuth` |+| `YOUTUBE_API_KEY` | Yes | Shared YouTube Data API v3 key (all users share quota) |+| `INSTAGRAM_APP_ID` | Yes | Meta/Facebook App ID for OAuth |+| `INSTAGRAM_APP_SECRET` | Yes | Used for OAuth token exchange + HMAC state signing |+| `CLOUDINARY_CLOUD_NAME` | Yes | Cloudinary cloud name |+| `CLOUDINARY_UPLOAD_PRESET` | Yes | Unsigned upload preset for direct browser uploads |+| `BACKEND_URL` | Yes | This Worker's public URL (for OAuth callback construction) |+| `FRONTEND_URL` | Yes | Frontend URL (for post-OAuth redirect back to the SPA) |+| `UPSTASH_REDIS_REST_URL` | Optional | Upstash Redis endpoint; caching disabled if absent |+| `UPSTASH_REDIS_REST_TOKEN` | Optional | Upstash auth token |++### Setting secrets++```bash+wrangler secret put SUPABASE_URL+wrangler secret put SUPABASE_SERVICE_KEY+# (paste value when prompted — no echo)+```++### Local development (`.dev.vars`)++Create `backend/.dev.vars` (gitignored) with the same keys:++```+SUPABASE_URL=https://your-project.supabase.co+SUPABASE_SERVICE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...+SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...+YOUTUBE_API_KEY=AIzaSy...+INSTAGRAM_APP_ID=123456789+INSTAGRAM_APP_SECRET=abc123...+CLOUDINARY_CLOUD_NAME=mycloud+CLOUDINARY_UPLOAD_PRESET=ml_default+BACKEND_URL=http://localhost:8787+FRONTEND_URL=http://localhost:5173+UPSTASH_REDIS_REST_URL=https://...+UPSTASH_REDIS_REST_TOKEN=...+```++Run locally: `cd backend && wrangler dev`++## Worker Constraints++These are hard constraints imposed by the Cloudflare Workers runtime. Violating them causes runtime errors:++1. **No Node.js APIs.** No `fs`, `Buffer`, `path`, `process.env` (use `c.env`), `require()`. Everything must be ESM `import`.++2. **No binary file handling.** The Worker cannot efficiently stream large binary files. Never add routes that accept file uploads — Cloudinary handles that directly from the browser.++3. **No persistent state between requests.** The Worker isolate may be a fresh instance on every request. Do not rely on module-level variables to persist state across requests. All state must come from Supabase, Redis, or Worker KV.++4. **CPU time limit.** Workers have a CPU time limit per request (typically 50ms on free tier, up to 30s on paid). Long-running synchronous operations will be killed. Use async/await for all I/O.++5. **`ctx.waitUntil()` in cron handlers.** Cron handlers must use `ctx.waitUntil(promise)` for async work. Without it, the Worker may terminate before the work completes.++6. **Bundle size.** The Worker bundle must be a single ESM file (Wrangler handles bundling). Avoid large dependencies.++## Adding a New Worker Secret++1. Set via `wrangler secret put NEW_SECRET_NAME`+2. Add to `backend/.env.example` with a placeholder value+3. Add to `backend/.dev.vars` locally+4. Set as a GitHub secret if needed by deploy workflow+5. Update `docs/architecture/cloudflare/WORKERS.md` (this file)+6. Append to `DECISIONS.md` if it represents an architectural dependencydiff --git a/docs/architecture/data-flows/ANALYTICS.md b/docs/architecture/data-flows/ANALYTICS.mdnew file mode 100644index 0000000..725db1a--- /dev/null+++ b/docs/architecture/data-flows/ANALYTICS.md@@ -0,0 +1,138 @@+# Data Flow — Analytics++## YouTube Analytics Flow++```+User navigates to /channel/:id+ │+ ▼+ChannelAnalytics.jsx mounts → api.getAnalytics(id)+ → GET /api/accounts/:id/analytics+ │+ ▼+ Worker: analyticsRouter+ 1. getAccountById(supabase, id, userId) — verify ownership+ 2. redis cache check: getVideosCache(redis, userId, id)+ → cache hit: return cached data immediately+ → cache miss: continue+ 3. Fetch from YouTube Data API:+ a. GET /channels?part=snippet,statistics,contentDetails&id={channelId}+ → channel metadata + subscriber/view/video counts + uploadPlaylistId+ b. Paginate /playlistItems?part=contentDetails&playlistId={uploadPlaylistId}+ → up to 10 pages × 50 items = 500 video IDs+ c. Batch /videos?part=snippet,statistics&id={id1,id2,...}+ → 50 videos per batch request → statistics (views, likes, comments, duration)+ 4. computeVideoAnalytics(videos, channel)+ → 50+ computed metrics+ 5. setVideosCache(redis, userId, id, result)+ → cache result for future requests+ 6. Return JSON+```++### computeVideoAnalytics() Output (partial)++```js+{+ channel: { /* channel metadata */ },+ totals: {+ videos: 100,+ totalViews: 1234567,+ subscribers: 50000,+ avgViewsPerVideo: 12345,+ avgLikesPerVideo: 456,+ avgCommentsPerVideo: 23,+ avgLikeRate: 3.7, // likes/views %+ avgCommentRate: 0.19, // comments/views %+ },+ bestVideo: { /* video with most views */ },+ worstVideo: { /* video with fewest views */ },+ shortsCount: 30, // duration ≤ 60s+ longsCount: 70,+ shortsViewPercent: 25.4,+ monthlyBreakdown: [ // last 12 months+ { month: '2025-06', uploads: 4, views: 45000 },+ // ...+ ],+ categoryDistribution: [ // YouTube category ID breakdown+ { category: 'Gaming', count: 40, viewPercent: 60 },+ // ...+ ],+ videos: [ /* all 500 video objects */ ]+}+```++## Instagram Analytics Flow++```+User navigates to /instagram/:id+ │+ ▼+InstagramAnalytics.jsx mounts → api.getIGAnalytics(id)+ → GET /api/accounts/:id/ig-analytics+ │+ ▼+ Worker: analyticsRouter+ 1. getAccountById(supabase, id, userId) — verify ownership + get accessToken+ 2. redis cache check: getIGCache(redis, userId, id)+ → cache hit: return immediately+ → cache miss: continue+ 3. Fetch from Instagram Graph API:+ a. GET /me?fields=id,username,account_type,media_count,followers_count+ → profile data+ b. Paginate /me/media?fields=id,media_type,timestamp,like_count,comments_count,+ caption,permalink,thumbnail_url,media_url+ → up to 500 media items (10 pages × 50)+ 4. computeInstagramAnalytics(media, profile)+ → engagement metrics+ 5. setIGCache(redis, userId, id, result)+ 6. Return JSON+```++### computeInstagramAnalytics() Output (partial)++```js+{+ profile: { username, followersCount, mediaCount },+ totals: {+ totalMedia: 200,+ avgLikes: 234,+ avgComments: 12,+ engagementRate: 4.92, // (avg likes + avg comments) / followers × 100+ bestPost: { /* highest likes */ },+ },+ mediaTypeBreakdown: [+ { type: 'IMAGE', count: 120, avgLikes: 200 },+ { type: 'REELS', count: 80, avgLikes: 310 },+ ],+ postingTimeDistribution: {+ byHour: [/* 0-23 */],+ byDayOfWeek: [/* 0-6 */]+ },+ hashtagAnalysis: [+ { tag: '#travel', count: 45, avgLikes: 280 },+ // ...+ ],+ captionLengthCorrelation: [+ /* { lengthBucket, avgLikes } showing if longer captions perform better */+ ],+ monthlyBreakdown: [+ { month: '2025-06', posts: 8, avgLikes: 245 },+ // ...+ ],+ media: [ /* all 500 media objects */ ]+}+```++## Overview Dashboard (Cross-Account)++```+User navigates to /+ │+ ▼+Overview.jsx uses accounts from AppContext+ → Combined totals computed from account.subscriberCount, viewCount, etc.+ → api.getComparison() → GET /api/comparison+ → returns all accounts sorted by view count, subscriber count+```++The Overview doesn't fetch fresh analytics — it uses the cached account metadata (subscriber counts, view counts) already in `AppContext.accounts`. Deep per-account analytics (video lists, engagement rates) are only fetched when the user navigates to a specific account page.diff --git a/docs/architecture/data-flows/AUTHENTICATION.md b/docs/architecture/data-flows/AUTHENTICATION.mdnew file mode 100644index 0000000..fe5a8e3--- /dev/null+++ b/docs/architecture/data-flows/AUTHENTICATION.md@@ -0,0 +1,98 @@+# Data Flow — Authentication++## Login Flow++```+User visits the app+ │+ ▼+React Router: no session → ProtectedRoute redirects to /login+ │+ ▼+Login.jsx renders email/password form+ │+ ▼+User submits → AuthContext.signIn(email, password)+ → supabase.auth.signInWithPassword({ email, password })+ → Supabase validates credentials+ → Returns { session: { access_token, user: { id, email } } }+ → AuthProvider.setSession(session)+ → onAuthStateChange fires, React re-renders+ │+ ▼+ProtectedRoute sees session is now set → renders children (app)+ │+ ▼+AppProvider mounts → loadAccounts() fires+ → api.getAccounts() → GET /api/accounts (with JWT)+ → accounts[] populated+ │+ ▼+User sees Overview dashboard+```++## Session Lifecycle++```+Session created (on signIn)+ │+ ▼+Supabase JWT stored in browser (localStorage by default)+ │+ ▼+On app load: supabase.auth.getSession() checks stored token+ - If valid: session is set immediately (no network request)+ - If expired: Supabase attempts to refresh via refresh_token+ - If refresh fails: session is null → redirect to /login+ │+ ▼+supabase.auth.onAuthStateChange watches for:+ - TOKEN_REFRESHED: updates session with new access_token+ - SIGNED_OUT: clears session → ProtectedRoute redirects to /login+ - USER_UPDATED: updates user in session+```++## JWT Verification (Backend)++```+API call arrives at Worker with Authorization: Bearer <token>+ │+ ▼+requireAuth middleware+ → extracts token from header+ → getSupabaseAuth(env) — creates Supabase client with ANON key+ → supabaseAuth.auth.getUser(token)+ → Supabase validates:+ 1. JWT signature (signed with Supabase project secret)+ 2. Token expiry (exp claim)+ 3. Token not invalidated (Supabase can invalidate on signOut)+ → On success: { user: { id, email } }+ → c.set('userId', user.id)+ → c.set('userEmail', user.email)+ → await next() → route handler executes+```++## Sign Out Flow++```+User clicks Sign Out (Header.jsx)+ → AuthContext.signOut()+ → supabase.auth.signOut()+ → Supabase invalidates refresh token server-side+ → Local session cleared from browser storage+ → onAuthStateChange fires with SIGNED_OUT+ → session = null+ → ProtectedRoute → redirect to /login+```++## Token Refresh++Supabase JS client handles token refresh automatically. The access token expires after 1 hour; the refresh token can be used to obtain a new access token. The `onAuthStateChange` listener fires `TOKEN_REFRESHED` when this happens, keeping the `session` in `AuthContext` current.++No manual refresh logic is needed in the frontend.++## Instagram OAuth (Separate Flow)++Instagram OAuth is not user authentication — it is account connection. The flow is documented in the system overview under "Instagram OAuth" and does not use Supabase Auth.++The Instagram OAuth state is secured via HMAC (see `docs/architecture/backend/CACHING.md`) and the flow ends by creating a row in the `accounts` table, not a Supabase Auth user.diff --git a/docs/architecture/data-flows/PUBLISHING.md b/docs/architecture/data-flows/PUBLISHING.mdnew file mode 100644index 0000000..a93a8eb--- /dev/null+++ b/docs/architecture/data-flows/PUBLISHING.md@@ -0,0 +1,97 @@+# Data Flow — Instagram Publishing++## Immediate Publishing++```+User selects account + uploads media + fills caption+ │+ ▼+1. Frontend: Upload media to Cloudinary+ api.getCloudinaryConfig() → GET /api/cloudinary-config+ → returns { cloudName, uploadPreset }++ Browser uploads directly to Cloudinary using unsigned preset+ → Cloudinary returns public URL (e.g., https://res.cloudinary.com/cloud/image/upload/...)+ │+ ▼+2. Frontend: Create media container+ api.createIGContainer(accountId, { mediaUrl, caption, mediaType, ... })+ → POST /api/accounts/:id/ig-publish+ → Backend: calls Instagram Graph API+ POST https://graph.instagram.com/v25.0/{igUserId}/media+ params: { image_url|video_url, caption, media_type, access_token }+ → Returns { containerId }+ │+ ▼+3. For REELS or STORIES: poll container status (images skip this step)+ api.getIGContainerStatus(containerId, accountId)+ → GET /api/ig-container/:containerId/status?accountId=:id+ → Backend: GET https://graph.instagram.com/v25.0/{containerId}?fields=status_code,status+ → Poll every 3 seconds, timeout at 3 minutes+ → Wait for status_code = 'FINISHED'+ → ERROR → throw error, mark as failed+ → EXPIRED → throw error+ │+ ▼+4. Frontend: Publish the container+ api.publishIGContainer(accountId, containerId)+ → POST /api/accounts/:id/ig-media-publish+ → Backend: POST https://graph.instagram.com/v25.0/{igUserId}/media_publish+ body: { creation_id: containerId, access_token }+ → Returns { mediaId }+ │+ ▼+5. Frontend: Show success toast with mediaId+```++## Scheduled Publishing++```+User creates a scheduled post+ │+ ▼+1. Frontend: api.createScheduledPost({ accountId, scheduledAt, mediaUrl, caption, ... })+ → POST /api/scheduled-posts+ → Backend: db.createPost(supabase, post, userId)+ INSERT INTO scheduled_posts (id, user_id, account_id, status='pending', scheduled_at, data)+ │+ ▼+2. Every 15 minutes, one of two schedulers fires:+ A. Cloudflare Worker cron → processScheduledPosts(supabase)+ B. GitHub Actions → node scripts/publish-scheduled.js → direct Supabase REST calls+ │+ ▼+3. Scheduler queries due posts:+ SELECT * FROM scheduled_posts WHERE status='pending' AND scheduled_at <= now()+ │+ ▼+4. For each due post:+ a. UPDATE scheduled_posts SET status='publishing' WHERE id=:id AND status='pending'+ (This is the mutex — prevents double-publish if both schedulers fire simultaneously)++ b. SELECT account WHERE id=:accountId+ (Gets the accessToken from accounts.data)++ c. Execute the publish pipeline (same as immediate publishing, steps 2-4 above)++ d. On success: UPDATE SET status='published', data.publishedMediaId=:id, data.publishedAt=:ts++ e. On failure: UPDATE SET status='failed', data.error=:message+```++## Media Type Differences++| Type | Container params | Status polling | Notes |+|---|---|---|---|+| IMAGE | `image_url`, optional `alt_text`, `location_id`, `user_tags` | No | Publishes immediately |+| REELS | `video_url`, `media_type=REELS`, optional `share_to_feed`, `cover_url`, `audio_name`, `thumb_offset`, `collaborators` | Yes | Requires FINISHED before publish |+| STORIES | `video_url` or `image_url`, `media_type=STORIES`, optional `user_tags` | Yes (for video) | Images publish immediately |++## Error States++| Error | Cause | Recovery |+|---|---|---|+| Container `ERROR` | Instagram processing failed (bad codec, too long, etc.) | User must re-upload |+| Container `EXPIRED` | >24 hours since container was created | User must re-create container |+| `media_publish` 400 | Usually quota exceeded or invalid containerId | Check publishing limit |+| `status=failed` in scheduled post | Any of the above, plus `accessToken` expired | Re-connect the account |diff --git a/docs/architecture/data-flows/SCHEDULING.md b/docs/architecture/data-flows/SCHEDULING.mdnew file mode 100644index 0000000..1b05819--- /dev/null+++ b/docs/architecture/data-flows/SCHEDULING.md@@ -0,0 +1,78 @@+# Data Flow — Scheduled Publishing (Dual Scheduler)++## Overview++Two independent systems check for due posts every 15 minutes. Both target the same Supabase table. The `publishing` status field acts as a mutex to prevent double-publishing.++## System A: Cloudflare Worker Cron++**Trigger:** `*/15 * * * *` cron in `wrangler.toml`+**Handler:** `backend/utils/scheduler.js` → `processScheduledPosts(supabase)`+**Supabase client:** service-role (created from Worker env)++## System B: GitHub Actions++**Trigger:** `publish-scheduled.yml` workflow → `schedule: cron('*/15 * * * *')`+**Handler:** `scripts/publish-scheduled.js` (standalone Node.js, zero npm deps)+**Supabase client:** direct REST API calls using `SUPABASE_URL` + `SUPABASE_SERVICE_KEY` GitHub secrets++## Why Both?++- Redundancy: if the Worker cron fails or is paused, GitHub Actions continues+- GitHub Actions is free on public repos+- The Worker cron covers private repo deployments or when GitHub Actions minutes are exhausted++## The Mutex Pattern++When a scheduler picks up a post to publish, it immediately sets `status = 'publishing'`. This is done via a targeted UPDATE before the Instagram API call:++```sql+UPDATE scheduled_posts+SET status = 'publishing'+WHERE id = :id AND status = 'pending'+```++The `AND status = 'pending'` condition means only one scheduler can successfully claim a post. The second scheduler to run will find no matching rows for that post ID and skip it.++**Race condition window:** There is a small window between the `SELECT` (fetch due posts) and the `UPDATE` (claim as publishing) where both schedulers could claim the same post. Supabase/PostgreSQL serializes these writes, so one will win and the other will find `status ≠ pending` and skip.++## Post Status Lifecycle++```+pending The post is waiting to be published+ │+ ▼ scheduler picks it up+publishing Claimed by a scheduler — in-flight+ │+ ├─ Instagram API succeeds ──→ published+ │ + data.publishedMediaId+ │ + data.publishedAt+ │+ └─ Instagram API fails ─────→ failed+ + data.error (error message)+```++`published` and `failed` posts are visible in the UI. Users can delete failed posts and reschedule.++## Scheduler Code Comparison++Both schedulers implement the same logic:++| Step | Worker (`scheduler.js`) | GitHub Actions (`publish-scheduled.js`) |+|---|---|---|+| Fetch due posts | `db.getDuePosts(supabase)` | `GET /scheduled_posts?status=eq.pending&scheduled_at=lte.now` |+| Fetch account | `db.getAccountById(supabase, accountId)` | `GET /accounts?id=eq.{accountId}` |+| Mark publishing | `db.updatePost(...)` | `PATCH /scheduled_posts?id=eq.{id}` |+| Publish to IG | Instagram Graph API calls | Same |+| Update status | `db.updatePost(...)` | `PATCH /scheduled_posts?id=eq.{id}` |++## Configuration Requirements++### For Worker Cron (System A)+- Worker secrets: `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `INSTAGRAM_APP_ID` (not used by scheduler directly — the account's stored `accessToken` is used)+- No additional setup beyond deploying the Worker++### For GitHub Actions (System B)+- GitHub repo secrets: `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`+- The `publish-scheduled.yml` workflow must be enabled+- Note: These GitHub secrets are only required for System B — the main deploy workflows (`deploy-backend.yml`, `deploy-frontend.yml`) do not need themdiff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.mdnew file mode 100644index 0000000..4c8989c--- /dev/null+++ b/docs/architecture/database/SCHEMA.md@@ -0,0 +1,174 @@+# Database Schema++## Overview++Supabase (PostgreSQL) with three application tables. All tables include `user_id` (UUID) referencing `auth.users` to scope data per user.++The backend uses the **service-role key** (bypasses Row Level Security) but enforces isolation by always appending `.eq('user_id', userId)` on user-scoped queries. The `userId` comes exclusively from the verified JWT — never from request input.++Cron handlers (`processScheduledPosts`, `autoRefreshInstagramTokens`) intentionally omit the `userId` filter to operate across all users.++---++## Table: `accounts`++Stores connected YouTube channels and Instagram accounts.++| Column | Type | Nullable | Description |+|---|---|---|---|+| `id` | text | NOT NULL | PK. Client-generated: `Date.now().toString(36) + Math.random().toString(36).slice(2)` |+| `user_id` | uuid | NOT NULL | FK → `auth.users.id`. All user-scoped queries filter on this. |+| `platform` | text | NOT NULL | `'youtube'` or `'instagram'` |+| `data` | jsonb | NOT NULL | All platform-specific fields (see below) |++### `data` jsonb shape for YouTube accounts++```json+{+ "channelId": "UCxxxxxx",+ "title": "Channel Name",+ "description": "...",+ "customUrl": "@handle",+ "country": "US",+ "publishedAt": "2020-01-01T00:00:00Z",+ "subscriberCount": 12345,+ "viewCount": 456789,+ "videoCount": 100,+ "thumbnailUrl": "https://...",+ "uploadPlaylistId": "UUxxxxxx",+ "lastRefreshed": "2025-07-01T00:00:00Z"+}+```++### `data` jsonb shape for Instagram accounts++```json+{+ "igUserId": "17841400000000000",+ "username": "myaccount",+ "accountType": "BUSINESS",+ "mediaCount": 200,+ "followersCount": 5000,+ "accessToken": "EAAxxxx...",+ "tokenExpiresAt": "2025-09-01T00:00:00Z",+ "lastRefreshed": "2025-07-01T00:00:00Z"+}+```++**Critical:** `accessToken` is always stripped by `safeAccount()` before being returned in any API response. It is intentionally stored server-side for use by the publishing and token-refresh pipelines.++### Indexes recommended++- `accounts(user_id)` — speeds up all user-scoped queries+- `accounts(platform)` — speeds up cross-user platform queries in cron handlers++---++## Table: `settings`++Per-user key-value configuration store.++| Column | Type | Nullable | Description |+|---|---|---|---|+| `user_id` | uuid | NOT NULL | PK (composite). FK → `auth.users.id` |+| `key` | text | NOT NULL | PK (composite). Currently only `'api_keys'` |+| `value` | jsonb | — | Configuration payload |++### Primary key: `(user_id, key)`++This means each user can have one row per `key`. Upserts use `onConflict: 'user_id,key'`.++### `value` jsonb shape for `key='api_keys'`++```json+{+ "githubPat": "ghp_xxxx",+ "githubRepo": "owner/repo-name"+}+```++The `api_keys` setting currently stores GitHub PAT and repo for the planned GitHub push feature. This key name is generic enough to accommodate future per-user configuration values.++---++## Table: `scheduled_posts`++Stores Instagram posts queued for future publishing.++| Column | Type | Nullable | Description |+|---|---|---|---|+| `id` | text | NOT NULL | PK. Client-generated: same pattern as `accounts.id` |+| `user_id` | uuid | NOT NULL | FK → `auth.users.id` |+| `account_id` | text | NOT NULL | FK → `accounts.id` |+| `status` | text | NOT NULL | `'pending'`, `'publishing'`, `'published'`, `'failed'` |+| `scheduled_at` | timestamptz | NOT NULL | UTC timestamp when the post should be published |+| `data` | jsonb | — | Post content and result data (see below) |++### Status lifecycle++```+pending → publishing → published+ ↘ failed+```++The `publishing` status is a mutex — it prevents double-publishing when both the Worker cron and GitHub Actions scheduler fire at the same time.++### `data` jsonb shape++```json+{+ "mediaType": "IMAGE | REELS | STORIES",+ "mediaUrl": "https://res.cloudinary.com/...",+ "caption": "Post caption text",+ "shareToFeed": true,+ "coverUrl": "https://...",+ "audioName": "...",+ "thumbOffset": 1000,+ "locationId": "...",+ "userTags": [{ "username": "...", "x": 0.5, "y": 0.5 }],+ "altText": "...",+ "collaborators": ["username1", "username2"],+ "publishedMediaId": "17841400000000001",+ "publishedAt": "2025-07-01T10:00:00Z",+ "error": "Error message if failed"+}+```++### Indexes recommended++- `scheduled_posts(user_id)` — user-scoped queries+- `scheduled_posts(status, scheduled_at)` — the cron scheduler query: `status=pending AND scheduled_at <= now()`++---++## `lib/db.js` — Query Layer++All SQL operations are centralized in `backend/lib/db.js`. Route handlers and cron handlers import named functions from this file — they never call `supabase.from()` directly.++### Available functions++```js+// Accounts+getAccounts(supabase, userId?) // null userId = all users (for cron)+getAccountById(supabase, id, userId?)+createAccount(supabase, account, userId)+updateAccount(supabase, id, updates, userId?)+deleteAccount(supabase, id, userId?)++// Settings+getSettings(supabase, userId)+saveSettings(supabase, keys, userId)++// Scheduled Posts+getPosts(supabase, userId?)+getPostById(supabase, id, userId?)+getDuePosts(supabase) // for cron — no userId filter, selects pending+overdue+createPost(supabase, post, userId)+updatePost(supabase, id, updates, userId?)+deletePost(supabase, id, userId?)+deleteAllPosts(supabase, userId) // skips 'publishing' status posts+```++## Adding a New Table++See `docs/features/NEW_DATABASE_TABLE.md` for the full workflow including migration strategy.diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.mdnew file mode 100644index 0000000..6fdee45--- /dev/null+++ b/docs/architecture/database/SECURITY.md@@ -0,0 +1,61 @@+# Database Security++## Key Principle: Application-Layer Isolation++The backend uses the **service-role key** for all database operations. This key bypasses Row Level Security (RLS). Data isolation is enforced by the application:++1. `requireAuth` middleware verifies the JWT and sets `c.userId` from Supabase's response — this is the only trusted source of `userId`+2. Every user-scoped query in `lib/db.js` appends `.eq('user_id', userId)` using this verified value+3. `userId` is never accepted from request body, query params, or any other user-controlled input++**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `lib/db.js` makes this auditable — every public function signature documents whether it accepts a userId.++## Why Not Use RLS?++See `DECISIONS.md` ADR-011 for the full reasoning. Summary:+- Cron handlers (scheduler, token refresh) need to query across all users — they cannot be scoped to a single JWT+- Using the service-role key with application-layer filtering achieves the same isolation with less complexity++## Key Hierarchy++| Key | Where used | What it can do |+|---|---|---|+| `SUPABASE_SERVICE_KEY` | Cloudflare Worker (server-side only) | All operations, bypasses RLS |+| `SUPABASE_ANON_KEY` | Cloudflare Worker (`requireAuth` only) | Only `getUser(token)` — JWT verification |+| `VITE_SUPABASE_ANON_KEY` | Frontend browser | Supabase Auth (sign in, sign up, sign out, session management) |++The anon key has no meaningful permissions beyond what Supabase Auth allows. It cannot read or write application tables unless RLS policies explicitly permit it.++**The service-role key must never appear in:**+- Frontend code+- API responses+- Git history+- Logs+- GitHub Actions logs (it is set as a GitHub secret and masked)++## Instagram Access Token Protection++The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-lived token that grants full publish access to the user's Instagram account.++**Protection mechanisms:**+1. Stored only in the Supabase `accounts` table (server-side)+2. Never returned in API responses — `safeAccount()` strips it+3. Only used by: `services/instagram.js` (for API calls) and `utils/scheduler.js` (for cron publishing)+4. The `GET /api/accounts` endpoint passes all accounts through `safeAccount()` before returning++**If you add a new route that returns account data, you must call `safeAccount()`.** There is no automatic stripping — it is an explicit step in route handlers.++## GitHub PAT Security++The GitHub Personal Access Token stored in `settings.value.githubPat` is stored in plaintext in Supabase. This is acceptable for a self-hosted deployment where the user controls the Supabase instance, but:+- Never log this value+- Never include it in API responses beyond the settings endpoint+- The `GET /api/settings/github` route should consider returning a masked value (e.g., `ghp_...xxxx`) instead of the full token in the response++## Audit Points++When reviewing security, check these files:+- `backend/middleware/auth.js` — JWT verification+- `backend/lib/db.js` — every function that accepts an optional `userId` should either: require it explicitly, or have a documented reason for omitting it (cron use case)+- `backend/services/instagram.js` — `safeAccount()` definition and usage+- All route files in `backend/routes/` — verify `safeAccount()` is called on every account responsediff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.mdnew file mode 100644index 0000000..9520463--- /dev/null+++ b/docs/architecture/frontend/API_LAYER.md@@ -0,0 +1,101 @@+# Frontend API Layer++## Location: `frontend/src/services/api.js`++The single source of truth for all frontend-to-backend communication. **Never call `fetch()` directly in components or contexts.** Always add methods here and call them from components.++## The `request()` Function++```js+const API = import.meta.env.VITE_API_URL || 'http://localhost:8787/api';++async function request(path, options = {}) {+ const { data: { session } } = await supabase.auth.getSession();+ const token = session?.access_token;++ const res = await fetch(`${API}${path}`, {+ headers: {+ 'Content-Type': 'application/json',+ ...(token ? { 'Authorization': `Bearer ${token}` } : {}),+ },+ ...options,+ });+ const data = await res.json();+ if (!res.ok && !data.success) throw new Error(data.message || data.error || 'Request failed');+ return data;+}+```++**What it does automatically:**+1. Gets the current Supabase session token+2. Attaches `Authorization: Bearer <token>` header if logged in+3. Parses the JSON response+4. Throws an `Error` if the response is not OK (unless `data.success` is explicitly true)++**Error handling:** The error message comes from the backend's `{ error: '...' }` response body, falling back to `'Request failed'`. Callers are responsible for catching this error and showing appropriate UI.++## The `api` Object++All backend endpoints are methods on the exported `api` object:++```js+export const api = {+ health: () => request('/health'),+ getAccounts: () => request('/accounts'),+ addAccount: (input) => request('/accounts', { method: 'POST', body: JSON.stringify({ input }) }),+ // ... (see api.js for full list)+};+```++## Adding a New API Method++1. Add to `api.js`:+ ```js+ export const api = {+ // ... existing methods+ getMyResource: (id) => request(`/my-resource/${id}`),+ createMyResource: (data) => request('/my-resource', { method: 'POST', body: JSON.stringify(data) }),+ };+ ```++2. Use in a component:+ ```jsx+ import { api } from '../services/api';+ // ...+ const data = await api.getMyResource(id);+ ```++3. Update `docs/architecture/backend/ROUTES.md` if this is a new backend route++## Error Handling Pattern in Components++```jsx+const [loading, setLoading] = useState(false);+const { showToast } = useAppContext();++async function handleAction() {+ setLoading(true);+ try {+ const result = await api.someMethod(data);+ showToast('Action completed!');+ // update state with result+ } catch (err) {+ showToast(err.message, 'error');+ } finally {+ setLoading(false);+ }+}+```++## Authentication++The `request()` function automatically attaches the JWT. Components do not need to handle auth tokens — the API layer manages this transparently. If the user is not logged in, the token will be absent and the backend will return 401, which `request()` will throw as an error.++## Base URL++| Environment | Value |+|---|---|+| Local development | `http://localhost:8787/api` (default fallback) |+| Production | `https://twiligent.ujjwalkrai.workers.dev/api` (from `VITE_API_URL`) |++Set `VITE_API_URL` in `frontend/.env` for local development if your Worker runs on a different port.diff --git a/docs/architecture/frontend/CONTEXTS.md b/docs/architecture/frontend/CONTEXTS.mdnew file mode 100644index 0000000..60ff930--- /dev/null+++ b/docs/architecture/frontend/CONTEXTS.md@@ -0,0 +1,109 @@+# Frontend Contexts++## AuthContext (`frontend/src/context/AuthContext.jsx`)++Wraps Supabase Auth state and exposes it to the entire app.++### What it provides++```js+const { session, user, signIn, signUp, signOut } = useAuth();+```++| Value | Type | Description |+|---|---|---|+| `session` | `Session \| null` | Current Supabase session; null if not logged in |+| `user` | `User \| null` | `session.user` shorthand |+| `signIn(email, password)` | async function | Calls `supabase.auth.signInWithPassword()` |+| `signUp(email, password)` | async function | Calls `supabase.auth.signUp()` |+| `signOut()` | async function | Calls `supabase.auth.signOut()` |++### How it works++```js+const [session, setSession] = useState(null);++useEffect(() => {+ supabase.auth.getSession().then(({ data: { session } }) => setSession(session));+ const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {+ setSession(session);+ });+ return () => subscription.unsubscribe();+}, []);+```++`onAuthStateChange` ensures the session updates in real time when the user signs in, signs out, or the token refreshes.++### Where to use it++- `ProtectedRoute` — reads `session` to decide whether to redirect to `/login`+- `Login.jsx` — calls `signIn()` and `signUp()`+- `Header.jsx` — calls `signOut()`, shows `user.email`+- Do **not** use in page/feature components — they should never need auth state directly++---++## AppContext (`frontend/src/context/AppContext.jsx`)++Provides the global accounts list and shared utilities to all feature pages.++### What it provides++```js+const { accounts, setAccounts, loading, showToast, loadAccounts, refreshAll } = useAppContext();+```++| Value | Type | Description |+|---|---|---|+| `accounts` | `Account[]` | All connected accounts (YouTube + Instagram), normalized via `normalizeAccount()` |+| `setAccounts` | setter | Direct setter (used by AccountManager after add/delete) |+| `loading` | `boolean` | True during `refreshAll()` only |+| `showToast(msg, severity)` | function | Shows a Sonner toast. `severity`: `'success'` (default), `'error'`, `'warning'`, `'info'` |+| `loadAccounts()` | async function | Fetches `GET /api/accounts` and updates `accounts` |+| `refreshAll()` | async function | Calls `POST /api/accounts/refresh-all`, sets `loading` true during request |++### Loading behavior++`loadAccounts()` is called automatically on mount. It does not set `loading = true` — it's a background load. Only `refreshAll()` sets `loading = true` (used to show a spinner in the Header).++### Where to use it++All feature pages and layout components use `useAppContext()`:+- `Sidebar.jsx` — generates per-account nav links from `accounts`+- `Overview.jsx` — renders the all-accounts dashboard+- `AccountManager.jsx` — calls `loadAccounts()` after add/delete+- `ChannelAnalytics.jsx` — finds the account by `params.id`+- All pages that show toast notifications call `showToast()`++### Account shape after `normalizeAccount()`++```js+{+ id: 'account-id',+ platform: 'youtube' | 'instagram',+ // YouTube fields:+ channelId: '...',+ title: '...',+ description: '...',+ subscriberCount: 12345,+ viewCount: 456789,+ videoCount: 100,+ thumbnailUrl: '...',+ // Instagram fields:+ igUserId: '...',+ username: '...',+ followersCount: 5000,+ mediaCount: 200,+ // Note: accessToken is NEVER present — stripped by safeAccount() on the backend+}+```++---++## Context Rules++1. Never use `AuthContext` in feature pages — they should not care about auth state+2. Never use `AppContext` in `AuthContext` or vice versa+3. `AppProvider` must be inside `ProtectedRoute` (it makes authenticated API calls on mount)+4. All toast notifications go through `showToast()` — never call `toast()` from sonner directly in pages+5. Do not add new global state to `AppContext` unless it truly needs to be shared across multiple unrelated pages. Prefer local component state.diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.mdnew file mode 100644index 0000000..6d11870--- /dev/null+++ b/docs/architecture/frontend/FEATURES.md@@ -0,0 +1,86 @@+# Frontend Feature Modules++## Directory Map++```+frontend/src/+├── features/+│ ├── analytics/+│ │ ├── channel/+│ │ │ └── ChannelAnalytics.jsx ← YouTube channel analytics+│ │ ├── instagram/+│ │ │ └── InstagramAnalytics.jsx ← Instagram account analytics+│ │ └── overview/+│ │ └── Overview.jsx ← Cross-platform aggregate dashboard+│ ├── accounts/+│ │ └── Accounts.jsx ← Add/remove connected accounts+│ ├── publish/+│ │ └── Publish.jsx ← Instagram immediate publish+│ ├── schedule/+│ │ └── Schedule.jsx ← Instagram scheduled posts queue+│ ├── settings/+│ │ └── Settings.jsx ← GitHub PAT and other settings+│ └── videos/+│ └── VideoExplorer.jsx ← YouTube video library with filtering+```++## Feature Conventions++### One directory per feature domain++Each top-level directory under `features/` represents a product area. Sub-directories represent per-platform views within that area.++```+features/analytics/youtube/ ← correct+features/ChannelAnalytics.jsx ← wrong (flat, not grouped)+```++### One page component per file++Each `.jsx` file in `features/` is a routable page. It is lazy-imported in `App.jsx` and mapped to a URL path. Shared sub-components that appear only on that page live in the same directory:++```+features/analytics/channel/+ ChannelAnalytics.jsx ← page (exported as default)+ VideoCard.jsx ← sub-component used only here+ useChannelData.js ← hook used only here+```++Shared components used across multiple features go in `components/` (shadcn UI pieces) or `components/shared/` (custom cross-feature pieces).++### Page components receive no props++Pages are entry points from the router. They get their context from `useAppContext()` and URL params from `useParams()`. They are never rendered as child components by other pages.++### Feature state is local++Each page manages its own loading/data/error state. Pages do not write to `AppContext` — the context is for account list and toast only. If you need shared state between two pages, it belongs in the URL (query params or route params), not in context.++### Naming++- Page files: `PascalCase.jsx` matching the feature name — `ChannelAnalytics.jsx`, `Schedule.jsx`+- Sub-components: `PascalCase.jsx` named for what they render — `VideoCard.jsx`, `StatRow.jsx`+- Hooks: `camelCase.js` with `use` prefix — `useChannelData.js`+- Directories: `camelCase` matching the feature — `analytics/channel/`, `publish/`++## Current Features++| Feature | Path | Description |+|---|---|---|+| Overview | `/` | Aggregate KPIs across all connected accounts |+| Accounts | `/accounts` | Connect/disconnect social accounts |+| Channel Analytics | `/channel/:id` | YouTube analytics for one channel |+| Instagram Analytics | `/instagram/:id` | Instagram analytics for one account |+| Video Explorer | `/videos/:id` | YouTube video library with search and sort |+| Publish | `/publish/:id` | Publish a post to Instagram immediately |+| Schedule | `/schedule/:id` | View and manage the scheduled post queue |+| Settings | `/settings` | GitHub PAT and platform settings |++## Adding a New Feature++1. Create `frontend/src/features/myFeature/MyPage.jsx`+2. Follow `docs/features/NEW_REACT_PAGE.md` for the component template+3. Add lazy import and route in `App.jsx`+4. Add sidebar link in `Sidebar.jsx` if it's a top-level destination or per-account page+5. Add API methods in `api.js`+6. Update this file with the new entry in the Current Features tablediff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.mdnew file mode 100644index 0000000..8ca53f5--- /dev/null+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md@@ -0,0 +1,105 @@+# Frontend React Architecture++## Stack++| Concern | Library | Version |+|---|---|---|+| Framework | React | 19 |+| Router | React Router | 7 |+| Build tool | Vite | 7 |+| UI components | shadcn/ui (base-nova style) | — |+| Styling | Tailwind CSS | 4 |+| Charts | Recharts | 3 |+| Theming | next-themes | — |+| Toasts | Sonner | — |+| Icons | Lucide React | — |++## Entry: `frontend/src/main.jsx`++```jsx+ReactDOM.createRoot(document.getElementById('root')).render(<App />);+```++## Application Shell: `frontend/src/App.jsx`++Defines the router, provider tree, and lazy-loaded page imports.++**Lazy loading:** All pages except `Login` are wrapped in `React.lazy()`. This means pages are code-split into separate JS chunks and loaded on first navigation. The `<Suspense fallback={null}>` wrapper renders nothing while the chunk loads.++**Router:** Uses `createBrowserRouter` (React Router v7 data router). This enables nested layouts via `<Outlet />` in `MainLayout`.++## Provider Tree++```+ThemeProvider (next-themes) ← OS/user theme preference+ TooltipProvider (shadcn) ← global tooltip context+ AuthProvider (AuthContext.jsx) ← Supabase session+ Suspense (fallback=null)+ RouterProvider+ /login → Login (no protection)+ /* →+ ProtectedRoute ← redirects to /login if no session+ AppProvider ← accounts[], loading, showToast+ MainLayout ← sidebar + header + <Outlet />+ (lazy page)+ Toaster (Sonner, bottom-right) ← toast notifications+```++**Why `AppProvider` is inside `ProtectedRoute`:** `AppProvider` calls `api.getAccounts()` on mount. This request requires a valid JWT. If `AppProvider` were outside `ProtectedRoute`, it would fire before auth is confirmed and fail with 401.++## Directory Structure++```+frontend/src/+ main.jsx Entry point+ App.jsx Router + provider tree+ index.css Tailwind + CSS variable tokens+ lib/+ supabase.js Supabase anon client (singleton)+ utils.js cn() = clsx + tailwind-merge+ services/+ api.js All backend HTTP calls+ context/+ AuthContext.jsx Session, signIn, signUp, signOut+ AppContext.jsx Accounts list, loading, showToast+ utils/+ formatters.js fmtNum, fmtDate, fmtDuration, normalizeAccount, etc.+ hooks/+ use-mobile.js useIsMobile()+ layout/+ index.jsx MainLayout: SidebarProvider + AppSidebar + Header + Outlet+ Sidebar.jsx Collapsible sidebar with per-account nav links+ Header.jsx Breadcrumb, refresh, theme toggle, sign-out+ components/+ ProtectedRoute.jsx Auth guard component+ MainCard.jsx Standard page wrapper card+ ui/ shadcn generated components (40+)+ pages/+ Login.jsx Auth page (not lazy-loaded, always small)+ features/+ analytics/+ overview/ Overview.jsx — all-accounts dashboard+ channel/ ChannelAnalytics.jsx — per-channel YouTube+ instagram/ InstagramAnalytics.jsx — per-account Instagram+ videos/ VideoExplorer.jsx — all videos table+ shorts/ ShortsExplorer.jsx — shorts-filtered table+ reels/ ReelsExplorer.jsx — Instagram media grid+ publishing/+ UploadContent.jsx Instagram publishing + schedule queue+ accounts/+ AccountManager.jsx Add/remove/refresh accounts+ settings/+ Settings.jsx API keys status + GitHub config+```++## Naming Conventions++- Feature files: `PascalCase.jsx` (matches component name)+- Utility files: `camelCase.js`+- Context files: `PascalCaseContext.jsx`+- Hook files: `use-kebab-case.js`+- shadcn ui files: `kebab-case.jsx` (generated convention, do not rename)++## Adding a New Page++See `docs/features/NEW_REACT_PAGE.md`.diff --git a/docs/architecture/frontend/ROUTING.md b/docs/architecture/frontend/ROUTING.mdnew file mode 100644index 0000000..e4de809--- /dev/null+++ b/docs/architecture/frontend/ROUTING.md@@ -0,0 +1,90 @@+# Frontend Routing++## Router Configuration++The app uses React Router v6 in `frontend/src/App.jsx`. The router uses `BrowserRouter` with a nested layout route.++## Route Table++| Path | Component | Notes |+|---|---|---|+| `/login` | `Login.jsx` | Public — redirects to `/` if already authenticated |+| `/` (layout) | `AppLayout` (inline) | Protected — redirects to `/login` if unauthenticated |+| `/` (index) | `Overview.jsx` | Default page after login |+| `/accounts` | `Accounts.jsx` | Connect/disconnect accounts |+| `/channel/:id` | `ChannelAnalytics.jsx` | `:id` = account.id for YouTube accounts |+| `/instagram/:id` | `InstagramAnalytics.jsx` | `:id` = account.id for Instagram accounts |+| `/videos/:id` | `VideoExplorer.jsx` | `:id` = account.id for YouTube accounts |+| `/publish/:id` | `Publish.jsx` | `:id` = account.id for Instagram accounts |+| `/schedule/:id` | `Schedule.jsx` | `:id` = account.id for Instagram accounts |+| `/settings` | `Settings.jsx` | User/platform settings |++## Auth Guard++There is no dedicated `<ProtectedRoute>` component. Auth protection is applied inline in the layout route:++```jsx+// App.jsx+function AppLayout() {+ const { user, loading } = useAuthContext();++ if (loading) return <LoadingScreen />;+ if (!user) return <Navigate to="/login" replace />;++ return <SidebarLayout />;+}+```++All routes nested under `AppLayout` are protected. `/login` is the only public route.++## Lazy Loading++All page components are lazy-loaded to reduce initial bundle size:++```jsx+const Overview = lazy(() => import('./features/analytics/overview/Overview'));+const ChannelAnalytics = lazy(() => import('./features/analytics/channel/ChannelAnalytics'));+// ... etc+```++All lazy components are wrapped in `<Suspense>` with a shared fallback.++## Adding a New Route++1. Add the lazy import at the top of `App.jsx`:+ ```jsx+ const MyPage = lazy(() => import('./features/myFeature/MyPage'));+ ```++2. Add the route inside the children of the layout route:+ ```jsx+ { path: 'my-page/:id', element: <MyPage /> }+ ```++3. If the page appears in the sidebar, add it to `Sidebar.jsx`.++4. Update the Route Table in this file.++## URL Parameters++The `:id` param in per-account routes always refers to `account.id` — the primary key of the `accounts` table. Pages look up the account from `AppContext`:++```js+const { id } = useParams();+const account = accounts.find(a => a.id === id);+```++If `account` is undefined (invalid ID or account deleted), the page renders an empty state — it does not redirect.++## Navigation++Navigation between routes uses React Router's `<Link>` component or the `useNavigate` hook. The `Sidebar.jsx` generates links dynamically from the accounts list in `AppContext`:++```jsx+// Per-account links generated at render time+accounts+ .filter(a => a.platform === 'youtube')+ .map(a => ({ title: a.title, url: `/channel/${a.id}` }))+```++This means the sidebar updates automatically when accounts are added or removed.diff --git a/docs/features/NEW_ANALYTICS_PAGE.md b/docs/features/NEW_ANALYTICS_PAGE.mdnew file mode 100644index 0000000..f9ec32d--- /dev/null+++ b/docs/features/NEW_ANALYTICS_PAGE.md@@ -0,0 +1,175 @@+# Guide: Adding an Analytics Page for a New Platform++Use this when adding a full analytics view for a new connected platform (e.g., Reddit, Twitter/X, TikTok). This guide is specific to analytics pages that follow the pattern of `ChannelAnalytics.jsx` and `InstagramAnalytics.jsx`.++## Architecture Impact++Adding a platform analytics page touches all layers:++| Layer | What changes |+|---|---|+| **Backend service** | New service file with platform API client, data fetcher, analytics computation |+| **Backend cache** | New cache key functions in `lib/cache.js` |+| **Backend db** | No schema change needed — `platform='reddit'` works with existing `accounts` table |+| **Backend routes** | New analytics routes (`/accounts/:id/platform-analytics`, `/accounts/:id/platform-media`) |+| **Backend server** | Mount new router in `server.js` |+| **Frontend api** | New methods in `api.js` |+| **Frontend page** | New analytics page in `features/analytics/platform/` |+| **Frontend routing** | New route in `App.jsx` |+| **Frontend navigation** | New nav links in `Sidebar.jsx` for platform accounts |+| **Frontend overview** | Add platform KPIs to Overview dashboard if appropriate |++## File Structure to Create++```+backend/+ services/+ reddit.js ← API client + analytics computation+ routes/+ reddit.js ← analytics routes++frontend/src/+ features/+ analytics/+ reddit/+ RedditAnalytics.jsx+```++## Step 1: Backend Service++Model it after `backend/services/instagram.js`:++```js+// backend/services/reddit.js++async function redditFetch(path, cookies) {+ const res = await fetch(`https://www.reddit.com${path}.json`, {+ headers: {+ 'Cookie': cookies,+ 'User-Agent': 'Twiligent/1.0',+ },+ });+ if (!res.ok) throw new Error(`Reddit API ${res.status}`);+ return res.json();+}++export async function getRedditProfile(username, cookies) { ... }+export async function getRedditPosts(username, cookies, limit = 100) { ... }+export function computeRedditAnalytics(posts, profile) {+ // Return analytics object with:+ // - totalPosts, totalKarma, avgUpvotes, avgComments+ // - best performing post+ // - posting time distribution+ // - subreddit breakdown+ // - monthly breakdown+ return { profile, totals: { ... }, posts, monthlyBreakdown: [...] };+}+```++## Step 2: Backend Cache++```js+// Add to backend/lib/cache.js+export async function getRedditCache(redis, userId, accountId) {+ if (!redis) return null;+ try { return (await redis.get(`reddit:${userId}:${accountId}`)) || null; } catch { return null; }+}++export async function setRedditCache(redis, userId, accountId, data) {+ if (!redis) return;+ try { await redis.set(`reddit:${userId}:${accountId}`, data); } catch { /* non-fatal */ }+}++export async function deleteRedditCache(redis, userId, accountId) {+ if (!redis) return;+ try { await redis.del(`reddit:${userId}:${accountId}`); } catch { /* non-fatal */ }+}+```++## Step 3: Backend Routes++```js+// backend/routes/reddit.js+import { Hono } from 'hono';+import { getAccountById } from '../lib/db.js';+import { getRedditCache, setRedditCache } from '../lib/cache.js';+import { getRedditProfile, getRedditPosts, computeRedditAnalytics } from '../services/reddit.js';++const router = new Hono();++router.get('/accounts/:id/reddit-analytics', async (c) => {+ const id = c.req.param('id');+ const userId = c.get('userId');+ const supabase = c.get('supabase');+ const redis = c.get('redis');+ try {+ const account = await getAccountById(supabase, id, userId);+ if (!account) return c.json({ error: 'Account not found' }, 404);++ const cached = await getRedditCache(redis, userId, id);+ if (cached) return c.json(cached);++ const profile = await getRedditProfile(account.username, account.cookies);+ const posts = await getRedditPosts(account.username, account.cookies);+ const analytics = computeRedditAnalytics(posts, profile);++ await setRedditCache(redis, userId, id, analytics);+ return c.json(analytics);+ } catch (err) {+ console.error(`GET /accounts/${id}/reddit-analytics:`, err.message);+ return c.json({ error: err.message }, 500);+ }+});++export default router;+```++## Step 4: Mount Route + Account Deletion Cache Invalidation++```js+// backend/server.js+import redditRouter from './routes/reddit.js';+api.route('/', redditRouter);+```++```js+// backend/routes/accounts.js — in the delete handler+await deleteRedditCache(redis, userId, id); // add alongside existing cache deletes+```++## Step 5: Frontend Page++Model after `InstagramAnalytics.jsx`. Key sections:+- Profile header (username, follower count, karma)+- KPI row: avg upvotes, avg comments, total posts, engagement rate+- Best performing post card+- Monthly breakdown chart (Recharts AreaChart or BarChart)+- Subreddit distribution (pie or bar)+- Posting time heatmap (if available)++## Step 6: Add to App.jsx, Sidebar, and api.js++```jsx+// App.jsx+const RedditAnalytics = lazy(() => import('./features/analytics/reddit/RedditAnalytics'));+// route:+{ path: 'reddit/:id', element: <RedditAnalytics /> }+```++```js+// api.js+getRedditAnalytics: (id) => request(`/accounts/${id}/reddit-analytics`),+```++```jsx+// Sidebar.jsx — in per-account link generation for Reddit accounts+{ title: 'Reddit', url: `/reddit/${account.id}`, icon: RedditIcon }+```++## Step 7: Update Documentation++- `docs/architecture/backend/ROUTES.md` — new routes+- `docs/architecture/backend/CACHING.md` — new cache keys+- `docs/architecture/backend/SERVICES.md` — Reddit service+- `docs/architecture/data-flows/` — create `REDDIT.md` for the analytics flow+- `CHANGELOG.md` — feature entrydiff --git a/docs/features/NEW_API_ENDPOINT.md b/docs/features/NEW_API_ENDPOINT.mdnew file mode 100644index 0000000..afaed59--- /dev/null+++ b/docs/features/NEW_API_ENDPOINT.md@@ -0,0 +1,131 @@+# Guide: Adding a New API Endpoint++Follow this guide when adding a route to the Hono backend. Read the existing `backend/routes/accounts.js` and `backend/routes/scheduledPosts.js` as reference implementations before starting.++## Files to Create or Modify++| Action | File |+|---|---|+| Create (if new feature area) | `backend/routes/myFeature.js` |+| Modify | `backend/lib/db.js` (add query functions) |+| Modify | `backend/server.js` (mount new router) |+| Modify | `frontend/src/services/api.js` (add frontend method) |+| Update | `docs/architecture/backend/ROUTES.md` |++## Step 1: Add Database Functions (if needed)++In `backend/lib/db.js`, add query functions for the new resource. Follow the established patterns:++```js+// For user-scoped data: always accept userId, always apply .eq('user_id', userId)+export async function getMyResources(supabase, userId) {+ const { data, error } = await supabase+ .from('my_table')+ .select('id, name, data')+ .eq('user_id', userId)+ .order('created_at', { ascending: false });+ if (error) throw error;+ return (data || []).map(row => ({ id: row.id, name: row.name, ...row.data }));+}++export async function createMyResource(supabase, resource, userId) {+ const { id, name, ...rest } = resource;+ const { error } = await supabase+ .from('my_table')+ .insert({ id, user_id: userId, name, data: rest });+ if (error) throw error;+}+```++## Step 2: Add Service Functions (if external API calls needed)++In `backend/services/myPlatform.js`, add functions for external API calls. Keep business logic out of routes.++## Step 3: Create the Route File++```js+// backend/routes/myFeature.js+import { Hono } from 'hono';+import { getMyResources, createMyResource } from '../lib/db.js';++const router = new Hono();++router.get('/my-resources', async (c) => {+ const userId = c.get('userId');+ const supabase = c.get('supabase');+ try {+ const resources = await getMyResources(supabase, userId);+ return c.json(resources);+ } catch (err) {+ console.error('GET /my-resources:', err.message);+ return c.json({ error: err.message }, 500);+ }+});++router.post('/my-resources', async (c) => {+ const userId = c.get('userId');+ const supabase = c.get('supabase');+ const body = await c.req.json();+ const { name } = body;+ if (!name) return c.json({ error: 'Missing required field: name' }, 400);+ try {+ const id = Date.now().toString(36) + Math.random().toString(36).slice(2);+ await createMyResource(supabase, { id, name }, userId);+ return c.json({ success: true, id }, 201);+ } catch (err) {+ console.error('POST /my-resources:', err.message);+ return c.json({ error: err.message }, 500);+ }+});++export default router;+```++## Step 4: Mount in server.js++```js+// backend/server.js+import myFeatureRouter from './routes/myFeature.js';+// ...+api.route('/', myFeatureRouter);+```++## Step 5: Add Frontend API Methods++```js+// frontend/src/services/api.js+export const api = {+ // ... existing methods+ getMyResources: () => request('/my-resources'),+ createMyResource: (data) => request('/my-resources', { method: 'POST', body: JSON.stringify(data) }),+};+```++## Step 6: Update Documentation++Add the new routes to `docs/architecture/backend/ROUTES.md`.++## Security Checklist++- [ ] Route is mounted under `api` (protected by `requireAuth`)+- [ ] Route handler reads `userId` from `c.get('userId')` — not from request body+- [ ] All DB queries include `.eq('user_id', userId)` for user-scoped data+- [ ] Any account data in the response passes through `safeAccount()` if it contains tokens+- [ ] Input validation returns 400 for missing required fields+- [ ] Errors are caught and return JSON with appropriate status code++## Testing++```bash+# Local test+cd backend && wrangler dev++# Test with curl (replace TOKEN)+curl http://localhost:8787/api/my-resources \+ -H "Authorization: Bearer TOKEN"++curl -X POST http://localhost:8787/api/my-resources \+ -H "Authorization: Bearer TOKEN" \+ -H "Content-Type: application/json" \+ -d '{"name":"test"}'+```diff --git a/docs/features/NEW_DATABASE_TABLE.md b/docs/features/NEW_DATABASE_TABLE.mdnew file mode 100644index 0000000..80daf23--- /dev/null+++ b/docs/features/NEW_DATABASE_TABLE.md@@ -0,0 +1,147 @@+# Guide: Adding a New Database Table++## When You Need a New Table++Before creating a new table, consider whether the data fits the existing jsonb pattern:+- If it's platform-specific configuration for an account → add fields to `accounts.data` jsonb+- If it's per-user settings → use the `settings` table with a new `key`+- If it's a new entity with its own lifecycle and queryable status → new table++## Steps++### Step 1: Define the Schema++Decide the column structure. Follow the existing conventions:+- Include `id text NOT NULL PRIMARY KEY` (client-generated)+- Include `user_id uuid NOT NULL` (FK to auth.users)+- Use `data jsonb` for flexible platform-specific fields+- Use dedicated columns for fields you'll query/filter on (status, timestamps, foreign keys)++Example schema for a hypothetical `content_drafts` table:+```sql+CREATE TABLE content_drafts (+ id text PRIMARY KEY,+ user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,+ account_id text NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,+ platform text NOT NULL,+ status text NOT NULL DEFAULT 'draft',+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ data jsonb+);++CREATE INDEX content_drafts_user_id_idx ON content_drafts(user_id);+CREATE INDEX content_drafts_status_idx ON content_drafts(status);+```++### Step 2: Create the Table in Supabase++Option A: Supabase Dashboard → SQL Editor → paste and run the SQL above++Option B: Supabase Dashboard → Table Editor → create visually++There is currently no migration tool configured. SQL is applied directly. **Document the SQL in this guide for future reference** if it needs to be recreated.++### Step 3: Add Row-Level Security (Optional)++The backend uses the service-role key which bypasses RLS. However, enabling RLS with a permissive policy is good defense-in-depth:++```sql+ALTER TABLE content_drafts ENABLE ROW LEVEL SECURITY;++-- The backend uses service-role key which bypasses RLS.+-- This policy would apply only if the anon key were used.+CREATE POLICY "Users can manage their own drafts"+ ON content_drafts+ FOR ALL+ USING (user_id = auth.uid());+```++### Step 4: Add Query Functions to `lib/db.js`++Follow the established pattern exactly:++```js+// backend/lib/db.js++// ── Content Drafts ────────────────────────────────────────────────────────────++export async function getDrafts(supabase, userId) {+ const { data, error } = await supabase+ .from('content_drafts')+ .select('id, account_id, platform, status, created_at, updated_at, data')+ .eq('user_id', userId)+ .order('created_at', { ascending: false });+ if (error) throw error;+ return (data || []).map(row => ({+ id: row.id,+ accountId: row.account_id,+ platform: row.platform,+ status: row.status,+ createdAt: row.created_at,+ updatedAt: row.updated_at,+ ...(row.data || {}),+ }));+}++export async function createDraft(supabase, draft, userId) {+ const { id, accountId, platform, ...rest } = draft;+ const { error } = await supabase.from('content_drafts').insert({+ id,+ user_id: userId,+ account_id: accountId,+ platform,+ data: rest,+ });+ if (error) throw error;+}++export async function updateDraft(supabase, id, updates, userId) {+ // Merge data fields with existing (never replace the whole data object)+ const current = await getDraftById(supabase, id, userId);+ if (!current) throw new Error('Draft not found: ' + id);+ const colUpdates = { updated_at: new Date().toISOString() };+ if (updates.status) colUpdates.status = updates.status;+ // merge data fields+ const { status: _, accountId: __, ...dataUpdates } = updates;+ if (Object.keys(dataUpdates).length > 0) {+ const { id: _id, accountId: _aid, platform: _p, status: _s, createdAt: _c, updatedAt: _u, ...currentData } = current;+ colUpdates.data = { ...currentData, ...dataUpdates };+ }+ let q = supabase.from('content_drafts').update(colUpdates).eq('id', id);+ if (userId) q = q.eq('user_id', userId);+ const { error } = await q;+ if (error) throw error;+}++export async function deleteDraft(supabase, id, userId) {+ let q = supabase.from('content_drafts').delete().eq('id', id);+ if (userId) q = q.eq('user_id', userId);+ const { error } = await q;+ if (error) throw error;+}+```++### Step 5: Document the Schema++Update `docs/architecture/database/SCHEMA.md` with:+- Table name and purpose+- All columns with types, constraints, and descriptions+- The `data` jsonb shape+- Recommended indexes++### Step 6: Wire Up the Feature++Follow the guides for:+- `docs/features/NEW_API_ENDPOINT.md` — add backend routes+- `docs/features/NEW_REACT_PAGE.md` — add frontend page+- `docs/features/NEW_API_ENDPOINT.md` — add frontend api.js methods++## Naming Conventions for New Tables++- Table names: `snake_case`, plural — `content_drafts`, `webhook_configs`+- All tables must have `user_id uuid NOT NULL`+- If table relates to an account: also include `account_id text NOT NULL`+- Status columns: text, with documented enum values+- Timestamp columns: `timestamptz` with `DEFAULT now()`+- jsonb data column: always name it `data` (consistent with existing tables)diff --git a/docs/features/NEW_INTEGRATION.md b/docs/features/NEW_INTEGRATION.mdnew file mode 100644index 0000000..00c884b--- /dev/null+++ b/docs/features/NEW_INTEGRATION.md@@ -0,0 +1,261 @@+# Guide: Adding a New Platform Integration++A "platform integration" is a new social or content platform (e.g., Reddit, Twitter/X, TikTok, LinkedIn). This guide walks through every layer that needs to change.++## Decision Checklist Before Starting++Before implementing, answer these questions:++1. **Auth method**: OAuth 2.0 / OAuth 1.0a / API key / Cookie-based?+2. **What we do with it**: Publish only? Fetch analytics only? Both?+3. **Media types**: Images? Video? Text-only? Carousels?+4. **API tier**: Does it require an approved developer app? What are the rate limits?+5. **Secret requirements**: What credentials need to be stored as Worker secrets?++Document the answers in `DECISIONS.md` as a new ADR before writing any code.++## File Checklist++| Layer | File | Action |+|---|---|---|+| Backend | `backend/services/{platform}.js` | Create |+| Backend | `backend/routes/{platform}.js` | Create |+| Backend | `backend/lib/db.js` | Extend (if needed) |+| Backend | `backend/lib/cache.js` | Extend |+| Backend | `backend/server.js` | Mount router |+| Backend | `wrangler.toml` | Add secrets |+| Frontend | `frontend/src/services/api.js` | Add methods |+| Frontend | `frontend/src/features/` | Create page(s) |+| Frontend | `frontend/src/App.jsx` | Add routes |+| Frontend | `frontend/src/layout/Sidebar.jsx` | Add nav links |+| Frontend | `frontend/src/context/AppContext.jsx` | Add normalization |+| Config | `.github/workflows/deploy-backend.yml` | Add new secret |+| Docs | `DECISIONS.md` | Add ADR |+| Docs | `CHANGELOG.md` | Add entry |+| Docs | `docs/architecture/backend/SERVICES.md` | Document service |+| Docs | `docs/architecture/backend/ROUTES.md` | Document routes |+| Docs | `docs/architecture/backend/CACHING.md` | Document cache keys |++## Step 1: Create the Service File++```js+// backend/services/twitter.js++// API client wrapper+async function twitterFetch(path, accessToken, method = 'GET', body = null) {+ const options = {+ method,+ headers: {+ 'Authorization': `Bearer ${accessToken}`,+ 'Content-Type': 'application/json',+ },+ };+ if (body) options.body = JSON.stringify(body);+ const res = await fetch(`https://api.twitter.com/2${path}`, options);+ if (!res.ok) {+ const err = await res.json().catch(() => ({ title: res.statusText }));+ throw new Error(`Twitter API ${res.status}: ${err.title || err.detail || res.statusText}`);+ }+ return res.json();+}++// Account-level functions+export async function getTwitterProfile(accessToken) {+ const { data } = await twitterFetch('/users/me?user.fields=public_metrics,profile_image_url', accessToken);+ return data;+}++export async function getTwitterTweets(userId, accessToken) {+ const { data } = await twitterFetch(+ `/users/${userId}/tweets?max_results=100&tweet.fields=public_metrics,created_at`,+ accessToken+ );+ return data || [];+}++// Analytics computation (pure function — easy to test)+export function computeTwitterAnalytics(tweets, profile) {+ const totalLikes = tweets.reduce((sum, t) => sum + (t.public_metrics?.like_count || 0), 0);+ const totalRetweets = tweets.reduce((sum, t) => sum + (t.public_metrics?.retweet_count || 0), 0);+ const totalReplies = tweets.reduce((sum, t) => sum + (t.public_metrics?.reply_count || 0), 0);+ const avgEngagement = tweets.length > 0+ ? ((totalLikes + totalRetweets + totalReplies) / tweets.length).toFixed(2)+ : 0;++ return {+ profile: {+ username: profile.username,+ name: profile.name,+ followers: profile.public_metrics.followers_count,+ following: profile.public_metrics.following_count,+ tweetCount: profile.public_metrics.tweet_count,+ },+ totals: { totalLikes, totalRetweets, totalReplies, avgEngagement },+ tweets: tweets.slice(0, 50),+ };+}++// Strip access token before sending to frontend+export function safeTwitterAccount(account) {+ const safe = { ...account };+ delete safe.accessToken;+ delete safe.refreshToken;+ return safe;+}++// Publishing (if applicable)+export async function postTweet(text, accessToken) {+ return twitterFetch('/tweets', accessToken, 'POST', { text });+}+```++## Step 2: Create Cache Functions++```js+// Additions to backend/lib/cache.js++export async function getTwitterCache(redis, userId, accountId) {+ if (!redis) return null;+ try { return (await redis.get(`twitter:${userId}:${accountId}`)) || null; } catch { return null; }+}++export async function setTwitterCache(redis, userId, accountId, data) {+ if (!redis) return;+ try { await redis.set(`twitter:${userId}:${accountId}`, data); } catch { /* non-fatal */ }+}++export async function deleteTwitterCache(redis, userId, accountId) {+ if (!redis) return;+ try { await redis.del(`twitter:${userId}:${accountId}`); } catch { /* non-fatal */ }+}+```++## Step 3: Create Route File++```js+// backend/routes/twitter.js+import { Hono } from 'hono';+import { getAccountById } from '../lib/db.js';+import { getTwitterCache, setTwitterCache } from '../lib/cache.js';+import { getTwitterProfile, getTwitterTweets, computeTwitterAnalytics, safeTwitterAccount, postTweet } from '../services/twitter.js';++const router = new Hono();++// Analytics+router.get('/accounts/:id/twitter-analytics', async (c) => {+ const id = c.req.param('id');+ const userId = c.get('userId');+ const supabase = c.get('supabase');+ const redis = c.get('redis');+ try {+ const account = await getAccountById(supabase, id, userId);+ if (!account) return c.json({ error: 'Account not found' }, 404);++ const cached = await getTwitterCache(redis, userId, id);+ if (cached) return c.json(cached);++ const profile = await getTwitterProfile(account.accessToken);+ const tweets = await getTwitterTweets(profile.id, account.accessToken);+ const analytics = computeTwitterAnalytics(tweets, profile);++ await setTwitterCache(redis, userId, id, analytics);+ return c.json(analytics);+ } catch (err) {+ console.error(`GET /accounts/${id}/twitter-analytics:`, err.message);+ return c.json({ error: err.message }, 500);+ }+});++// Post a tweet+router.post('/accounts/:id/tweet', async (c) => {+ const id = c.req.param('id');+ const userId = c.get('userId');+ const supabase = c.get('supabase');+ const body = await c.req.json();+ if (!body.text) return c.json({ error: 'Missing text' }, 400);+ try {+ const account = await getAccountById(supabase, id, userId);+ if (!account) return c.json({ error: 'Account not found' }, 404);+ const result = await postTweet(body.text, account.accessToken);+ return c.json({ success: true, tweetId: result.data?.id });+ } catch (err) {+ console.error(`POST /accounts/${id}/tweet:`, err.message);+ return c.json({ error: err.message }, 500);+ }+});++export default router;+```++## Step 4: Mount in server.js++```js+// backend/server.js+import twitterRouter from './routes/twitter.js';+api.route('/', twitterRouter);+```++## Step 5: Add Cache Invalidation on Account Delete++In `backend/routes/accounts.js`, add the cache delete alongside existing ones:++```js+await deleteTwitterCache(redis, userId, id);+```++## Step 6: Declare New Secrets++```toml+# wrangler.toml+[vars]+# (no vars for platform-specific secrets — use secrets)+```++```bash+# Add the secrets to the Worker+wrangler secret put TWITTER_CLIENT_ID+wrangler secret put TWITTER_CLIENT_SECRET+```++Add corresponding secrets to GitHub Actions if the CI/CD pipeline needs them.++## Step 7: Account Normalization in AppContext++The frontend `normalizeAccount()` function in `AppContext.jsx` maps raw DB rows to a consistent shape. Add normalization for the new platform:++```js+// frontend/src/context/AppContext.jsx+function normalizeAccount(raw) {+ // ...existing platforms...+ if (raw.platform === 'twitter') {+ return {+ id: raw.id,+ platform: 'twitter',+ title: raw.data?.username ? `@${raw.data.username}` : 'Twitter Account',+ username: raw.data?.username,+ profileImage: raw.data?.profileImage,+ };+ }+ // ...+}+```++## Step 8: Add Frontend Pages++Follow `docs/features/NEW_REACT_PAGE.md` and `docs/features/NEW_ANALYTICS_PAGE.md`.++## Step 9: OAuth Flow (if applicable)++If the platform uses OAuth:+- Backend: add `GET /auth/{platform}/start` and `GET /auth/{platform}/callback` routes+- Use the HMAC-signed state pattern (see `docs/architecture/backend/CACHING.md` and `ADR-006` in `DECISIONS.md`)+- Store tokens in `accounts.data` — never in a separate table+- Delete cache on every token refresh++## Security Checklist++- [ ] Access token never returned in any API response (use `safeTwitterAccount()` or equivalent)+- [ ] Access token read from `account.accessToken` on the backend — never passed from frontend+- [ ] OAuth callback validates HMAC state before accepting code+- [ ] New Worker secrets added with `wrangler secret put` — not stored in `wrangler.toml` plaintext+- [ ] New secrets added to GitHub Actions repository secrets if needed by CIdiff --git a/docs/features/NEW_REACT_PAGE.md b/docs/features/NEW_REACT_PAGE.mdnew file mode 100644index 0000000..7b4eedf--- /dev/null+++ b/docs/features/NEW_REACT_PAGE.md@@ -0,0 +1,144 @@+# Guide: Adding a New React Page++Read `frontend/src/features/analytics/channel/ChannelAnalytics.jsx` as a reference implementation before starting.++## Files to Create or Modify++| Action | File |+|---|---|+| Create | `frontend/src/features/myFeature/MyPage.jsx` |+| Modify | `frontend/src/App.jsx` (add lazy import + route) |+| Modify | `frontend/src/layout/Sidebar.jsx` (add nav link if needed) |+| Modify | `frontend/src/services/api.js` (add API methods) |+| Update | `docs/architecture/frontend/REACT_ARCHITECTURE.md` |++## Step 1: Create the Page Component++```jsx+// frontend/src/features/myFeature/MyPage.jsx+import { useState, useEffect, useCallback } from 'react';+import { useParams } from 'react-router-dom';+import { useAppContext } from '../../context/AppContext';+import { api } from '../../services/api';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { Skeleton } from '@/components/ui/skeleton';++export default function MyPage() {+ const { id } = useParams(); // if the page has a dynamic segment+ const { accounts, showToast } = useAppContext();+ const [data, setData] = useState(null);+ const [loading, setLoading] = useState(true);++ const account = accounts.find(a => a.id === id); // find from global accounts++ const loadData = useCallback(async () => {+ if (!account) return;+ try {+ const result = await api.getMyData(id);+ setData(result);+ } catch (err) {+ showToast(err.message, 'error');+ } finally {+ setLoading(false);+ }+ }, [id, account, showToast]);++ useEffect(() => {+ loadData();+ }, [loadData]);++ if (loading) {+ return (+ <div className="p-6 space-y-4">+ <Skeleton className="h-8 w-48" />+ <Skeleton className="h-48 w-full" />+ </div>+ );+ }++ if (!account) {+ return <div className="p-6 text-muted-foreground">Account not found.</div>;+ }++ return (+ <div className="p-6 space-y-6">+ <h1 className="text-2xl font-bold">{account.title}</h1>+ <Card>+ <CardHeader>+ <CardTitle>My Data</CardTitle>+ </CardHeader>+ <CardContent>+ {/* content */}+ </CardContent>+ </Card>+ </div>+ );+}+```++## Step 2: Add the Route in App.jsx++```jsx+// frontend/src/App.jsx+const MyPage = lazy(() => import('./features/myFeature/MyPage'));++// In the router definition, inside the children array:+{ path: 'my-page/:id', element: <MyPage /> },+```++## Step 3: Add Navigation in Sidebar.jsx++If the page appears in the sidebar (e.g., once per account):++```jsx+// In Sidebar.jsx, inside the per-account link generation+{+ title: 'My Feature',+ url: `/my-page/${account.id}`,+ icon: IconName,+}+```++## Step 4: Add API Methods++```js+// frontend/src/services/api.js+getMyData: (id) => request(`/accounts/${id}/my-data`),+```++## Conventions++- Use `useAppContext()` — don't re-fetch the accounts list, use what's in context+- Always handle loading and error states+- Use `Skeleton` components for loading state (not spinners — shadcn's Skeleton matches the page layout)+- Use semantic HTML for the page structure+- Wrap content in `className="p-6"` padding (matches existing pages)+- Use `space-y-6` or `space-y-4` for vertical rhythm between sections++## Page That Doesn't Need an Account Parameter++For pages that show aggregate data across all accounts (like Overview):++```jsx+export default function MyAggregatePage() {+ const { accounts, loading: accountsLoading } = useAppContext();+ // accounts is already loaded — no need to fetch++ const summary = useMemo(() => {+ return accounts.reduce((sum, a) => sum + (a.viewCount || 0), 0);+ }, [accounts]);++ return (+ <div className="p-6">+ <p>Total views: {summary}</p>+ </div>+ );+}+```++## Accessibility Requirements++- The main heading (`h1`) should describe the page, not just "Details"+- Tables must have `<thead>` with column headers+- Loading state must be announced (Skeleton is visually recognizable; add `aria-busy` if needed)+- Interactive elements must be reachable by keyboarddiff --git a/docs/features/NEW_SCHEDULED_TASK.md b/docs/features/NEW_SCHEDULED_TASK.mdnew file mode 100644index 0000000..1804d04--- /dev/null+++ b/docs/features/NEW_SCHEDULED_TASK.md@@ -0,0 +1,170 @@+# Guide: Adding a New Scheduled Task++## When You Need a New Scheduled Task++A scheduled task runs on a recurring schedule without user interaction. Options in this project:++| Mechanism | When to use |+|---|---|+| **Cloudflare Worker cron** | Low latency, needs access to Supabase/Redis, runs every 15 min minimum |+| **GitHub Actions workflow** | Needs Node.js APIs (file system, npm packages), long-running, can run on custom schedule |++For most tasks: use the Cloudflare Worker cron first. It's simpler and doesn't require managing GitHub secrets.++## Option A: Add a New Worker Cron Handler++### Step 1: Write the handler function++Add a new export in `backend/cron.js` (or a new file in `backend/cron/`):++```js+// backend/cron.js+export async function autoRefreshRedditTokens(env) {+ const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_SERVICE_KEY);+ const { data: accounts, error } = await supabase+ .from('accounts')+ .select('id, user_id, data')+ .eq('platform', 'reddit');+ if (error) { console.error('cron/reddit-refresh:', error.message); return; }++ for (const account of accounts) {+ try {+ const refreshed = await refreshRedditCookies(account.data.cookies);+ await supabase.from('accounts').update({ data: { ...account.data, cookies: refreshed } })+ .eq('id', account.id);+ } catch (err) {+ console.error(`cron/reddit-refresh account ${account.id}:`, err.message);+ }+ }+}+```++### Step 2: Register the Trigger in `wrangler.toml`++```toml+[triggers]+crons = [+ "*/15 * * * *", # existing: processScheduledPosts+ "0 2 * * *", # existing: autoRefreshInstagramTokens+ "30 3 * * *" # new: autoRefreshRedditTokens (runs at 3:30 AM UTC daily)+]+```++**Important:** Cloudflare routes cron triggers to the `scheduled()` handler in `worker.js` by trigger index. When you add a new cron string, you must also handle it in the worker's `scheduled()` function.++### Step 3: Dispatch in `worker.js`++```js+// backend/worker.js+export default {+ // ... fetch handler+ async scheduled(event, env, ctx) {+ if (event.cron === '*/15 * * * *') {+ ctx.waitUntil(processScheduledPosts(env));+ } else if (event.cron === '0 2 * * *') {+ ctx.waitUntil(autoRefreshInstagramTokens(env));+ } else if (event.cron === '30 3 * * *') {+ ctx.waitUntil(autoRefreshRedditTokens(env));+ }+ },+};+```++Or match by the cron expression string — the `event.cron` property contains the exact cron string from `wrangler.toml`.++### Step 4: Test Locally++```bash+cd backend && wrangler dev --test-scheduled+# Trigger manually:+curl "http://localhost:8787/__scheduled?cron=30+3+*+*+*"+```++### Step 5: Deploy++```bash+cd backend && wrangler deploy+```++Cron triggers deploy with the Worker. Verify in the Cloudflare dashboard → Workers → Triggers → Cron.++---++## Option B: Add a New GitHub Actions Workflow++Use this when:+- The task requires npm packages not bundled in the Worker+- The task runs infrequently (daily or less) and GitHub's 5-minute minimum interval is fine+- The task needs to run long (Worker CPU limit is 50ms per request; cron CPU limit is up to 30 seconds)++### Step 1: Write the script++Create `scripts/my-task.js`:++```js+// scripts/my-task.js+import { createClient } from '@supabase/supabase-js';++const SUPABASE_URL = (process.env.SUPABASE_URL || '').replace(/[^\x20-\x7E]/g, '').trim();+const SUPABASE_SERVICE_KEY = (process.env.SUPABASE_SERVICE_KEY || '').replace(/[^\x20-\x7E]/g, '').trim();++if (!SUPABASE_URL || !SUPABASE_SERVICE_KEY) {+ console.error('Fatal: Missing SUPABASE_URL or SUPABASE_SERVICE_KEY');+ process.exit(1);+}++const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);++// ... task logic++console.log('Task complete.');+```++### Step 2: Create the workflow file++Create `.github/workflows/my-task.yml`:++```yaml+name: My Scheduled Task++on:+ schedule:+ - cron: '0 4 * * *' # 4 AM UTC daily+ workflow_dispatch: # allow manual trigger++jobs:+ run:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '20'+ - run: npm install @supabase/supabase-js+ - name: Run task+ env:+ SUPABASE_URL: ${{ secrets.SUPABASE_URL }}+ SUPABASE_SERVICE_KEY: ${{ secrets.SUPABASE_SERVICE_KEY }}+ run: node scripts/my-task.js+```++### Step 3: Add Required Secrets++If the task requires secrets not already in GitHub Actions:++1. GitHub → Settings → Secrets and variables → Actions+2. Add `New repository secret`+3. Name must match what the workflow references++### Step 4: Test++GitHub → Actions → "My Scheduled Task" → "Run workflow" → watch the logs.++---++## Documentation After Adding++- Update `docs/architecture/cloudflare/CRON.md` with the new trigger+- Update `docs/architecture/cloudflare/CI_CD.md` if a new GitHub Actions workflow was added+- Update `CHANGELOG.md` under Unreleased+- If the task adds new secrets, update `docs/architecture/cloudflare/WORKERS.md` (env bindings table)diff --git a/docs/guidelines/API_CONVENTIONS.md b/docs/guidelines/API_CONVENTIONS.mdnew file mode 100644index 0000000..05bb645--- /dev/null+++ b/docs/guidelines/API_CONVENTIONS.md@@ -0,0 +1,112 @@+# API Conventions++## Response Shapes++### Success responses++Most endpoints return the data directly as a JSON object or array:++```json+// List response+[{ "id": "...", "platform": "youtube", "title": "..." }]++// Single object response+{ "id": "...", "channelId": "UC...", "analytics": { ... } }++// Action response (create/update/delete)+{ "success": true }+{ "success": true, "id": "newly-created-id" }+{ "success": true, "accounts": [...] } // when action returns updated data+```++### Error responses++All errors return a JSON object with an `error` key:++```json+{ "error": "Account not found" }+{ "error": "Missing required field: scheduledAt" }+{ "error": "Instagram API: (#10) Application does not have permission" }+```++The `request()` function in `frontend/src/services/api.js` reads `data.error` and throws it as the error message.++## Status Codes++| Code | When to use |+|---|---|+| `200` | Successful GET, PUT, DELETE |+| `201` | Successful POST that creates a resource |+| `400` | Bad request — missing fields, invalid input |+| `401` | Authentication required or token invalid (returned by `requireAuth`) |+| `403` | Authenticated but not authorized (wrong user for this resource) |+| `404` | Resource not found |+| `500` | Unexpected server error |++## Request Bodies++POST and PUT handlers read the request body via:++```js+const body = await c.req.json();+```++Always validate required fields and return 400 for missing ones:++```js+const { scheduledAt, accountId, mediaUrl } = body;+if (!scheduledAt || !accountId || !mediaUrl) {+ return c.json({ error: 'Missing required fields: scheduledAt, accountId, mediaUrl' }, 400);+}+```++## URL Parameters++Access route params via `c.req.param('name')`:++```js+router.delete('/accounts/:id', async (c) => {+ const id = c.req.param('id');+ // ...+});+```++Access query params via `c.req.query('name')`:++```js+router.get('/ig-container/:id/status', async (c) => {+ const containerId = c.req.param('id');+ const accountId = c.req.query('accountId');+ // ...+});+```++## Authentication Header++The frontend always sends: `Authorization: Bearer <supabase-access-token>`++The backend extracts and verifies it in `requireAuth`. Route handlers access the verified `userId` via `c.get('userId')`.++## Route Naming++- Resource collections: plural noun — `/accounts`, `/scheduled-posts`+- Single resources: `/:id` suffix — `/accounts/:id`+- Sub-resources: nested — `/accounts/:id/analytics`, `/accounts/:id/ig-media`+- Actions on resources: verb-noun — `/accounts/refresh-all`, `/accounts/:id/refresh`+- Non-resource actions: verb noun — `/resolve-channel`, `/process-scheduled`++## Frontend `api.js` Conventions++Each method in the `api` object corresponds to one backend endpoint:++```js+// Pattern: {verb}{Noun}(params) where params match what the endpoint needs+getAccounts: () => request('/accounts'),+addAccount: (input) => request('/accounts', { method: 'POST', body: JSON.stringify({ input }) }),+deleteAccount: (id) => request(`/accounts/${id}`, { method: 'DELETE' }),+refreshAccount: (id) => request(`/accounts/${id}/refresh`, { method: 'POST' }),+getAnalytics: (id) => request(`/accounts/${id}/analytics`),+createScheduledPost: (data) => request('/scheduled-posts', { method: 'POST', body: JSON.stringify(data) }),+```++Name frontend methods to describe what they do from the user's perspective, not the HTTP method: `addAccount` not `postAccount`, `deleteAccount` not `removeAccount`.diff --git a/docs/guidelines/CLOUDFLARE_WORKERS.md b/docs/guidelines/CLOUDFLARE_WORKERS.mdnew file mode 100644index 0000000..572b7f4--- /dev/null+++ b/docs/guidelines/CLOUDFLARE_WORKERS.md@@ -0,0 +1,134 @@+# Cloudflare Workers Standards++## Environment Access++Access environment variables and secrets via `c.env` (in Hono handlers) or `env` (in the `scheduled` cron handler). Never use `process.env` — it does not exist in the Workers runtime.++```js+// In a Hono handler or middleware:+const apiKey = c.env.YOUTUBE_API_KEY;+const url = c.env.SUPABASE_URL;++// In the cron handler:+export default {+ async scheduled(event, env, ctx) {+ const supabase = getSupabase(env);+ }+};+```++## No Node.js APIs++The Workers runtime does not have Node.js built-ins. These are unavailable:+- `fs` — no file system+- `Buffer` — use `Uint8Array`, `TextEncoder`, `TextDecoder`+- `path` — no file system paths+- `process` — no `process.env`, `process.exit`, etc.+- `crypto` module — use Web Crypto API (`crypto.subtle`)+- `require()` — use ESM `import`++**Web APIs available in Workers:**+- `fetch()` — for HTTP calls+- `crypto.subtle` — for HMAC, hashing+- `TextEncoder` / `TextDecoder` — for string/buffer conversion+- `URL`, `URLSearchParams` — for URL construction+- `btoa()` / `atob()` — for base64+- `ReadableStream`, `WritableStream` — for streaming++## `ctx.waitUntil()`++In cron handlers, use `ctx.waitUntil()` to keep the Worker alive for async background work:++```js+async scheduled(event, env, ctx) {+ ctx.waitUntil(myAsyncJob(env));+}+```++Without `ctx.waitUntil()`, the Worker isolate may terminate before the promise resolves.++Do not use `ctx.waitUntil()` in HTTP request handlers — just `await` the work normally.++## Stateless Requests++The Workers runtime does not guarantee a persistent process between requests. Do not rely on module-level variables to persist state:++```js+// BAD — will not work reliably+let cachedData = null;+export default { fetch: async (request, env) => {+ if (cachedData) return Response.json(cachedData); // unreliable+ cachedData = await fetchData(env);+ return Response.json(cachedData);+}};++// GOOD — use Redis or Supabase for persistence+const cached = await redis.get('my-key');+if (cached) return c.json(cached);+const fresh = await fetchData(env);+await redis.set('my-key', fresh);+return c.json(fresh);+```++## Bundle Size++The Worker is bundled as a single ESM file by Wrangler. Large dependencies increase cold-start time and may exceed Workers bundle size limits. The current backend has minimal dependencies:++- `hono` — ~15KB gzipped+- `@supabase/supabase-js` — larger; mostly used for auth.getUser()+- `@upstash/redis` — small REST client++Avoid adding large dependencies. If a library is only needed for one small utility, consider implementing that utility directly.++## Crypto (HMAC)++Use the native Web Crypto API for cryptographic operations:++```js+async function hmacSign(secret, message) {+ const key = await crypto.subtle.importKey(+ 'raw',+ new TextEncoder().encode(secret),+ { name: 'HMAC', hash: 'SHA-256' },+ false,+ ['sign'],+ );+ const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message));+ return btoa(String.fromCharCode(...new Uint8Array(sig)))+ .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+}+```++This pattern is used in `backend/lib/cache.js` for OAuth state tokens.++## Local Development++```bash+cd backend+wrangler dev # reads .dev.vars for secrets+```++The Worker runs at `http://localhost:8787` during local development.++## Deployment++```bash+cd backend+wrangler deploy+```++Or push to `main` with changes in `backend/` — GitHub Actions deploys automatically via `deploy-backend.yml`.++## CORS++The current CORS configuration (`cors()` with no options) allows all origins. For a more restrictive policy, pass the `FRONTEND_URL` as the allowed origin:++```js+app.use('*', cors({+ origin: c.env.FRONTEND_URL,+ allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],+ allowHeaders: ['Content-Type', 'Authorization'],+}));+```++This change would need to be applied carefully — it would break requests from local development (`localhost:5173`) unless the allowed origin list includes it.diff --git a/docs/guidelines/ERROR_HANDLING.md b/docs/guidelines/ERROR_HANDLING.mdnew file mode 100644index 0000000..dff47d6--- /dev/null+++ b/docs/guidelines/ERROR_HANDLING.md@@ -0,0 +1,124 @@+# Error Handling Standards++## Layer-by-Layer Rules++### External API Calls (services/)++Throw descriptive errors immediately when the external API returns an error object. Let the caller decide what to do:++```js+const data = await res.json();+if (data.error) throw new Error(data.error.message);+```++For HTTP-level errors (non-200 but no error body):+```js+if (!res.ok) throw new Error(`YouTube API ${res.status}: ${await res.text()}`);+```++### Database Calls (lib/db.js)++Check the Supabase `error` field and throw:++```js+const { data, error } = await supabase.from('accounts').select('*').eq('user_id', userId);+if (error) throw error;+```++Supabase errors are objects with `message`, `code`, and `details`. Throwing the error object directly passes the message through cleanly.++### Cache Operations (lib/cache.js)++Always catch and silently ignore — cache failures must never surface to users:++```js+try {+ return (await redis.get(key)) || null;+} catch {+ return null;+}+```++The empty `catch` block is intentional. Do not log cache errors — they create noise for transient Redis connection issues.++### Route Handlers (routes/)++Wrap the main logic in try/catch, log the error, and return a JSON error response:++```js+router.get('/accounts/:id/analytics', async (c) => {+ const id = c.req.param('id');+ const userId = c.get('userId');+ const supabase = c.get('supabase');+ try {+ const account = await getAccountById(supabase, id, userId);+ if (!account) return c.json({ error: 'Account not found' }, 404);+ const analytics = await getAnalytics(account, c.env);+ return c.json(analytics);+ } catch (err) {+ console.error(`GET /accounts/${id}/analytics:`, err.message);+ return c.json({ error: err.message }, 500);+ }+});+```++**Status codes:**+- `400` — bad request (missing required fields, invalid input)+- `401` — unauthorized (handled by `requireAuth`, not route handlers)+- `403` — forbidden (account belongs to another user)+- `404` — resource not found+- `500` — unexpected server error++### Frontend API Calls++Catch in the component or handler, show a toast, and handle loading state:++```jsx+const [loading, setLoading] = useState(false);+const { showToast } = useAppContext();++async function handleSubmit() {+ setLoading(true);+ try {+ await api.doSomething(data);+ showToast('Saved successfully!');+ } catch (err) {+ showToast(err.message, 'error');+ } finally {+ setLoading(false);+ }+}+```++The `api.js` `request()` function already extracts the error message from `{ error: '...' }` backend responses, so `err.message` will be the backend's error string.++### Global Error Handler (server.js)++The Hono global error handler catches any uncaught errors that bubble up past route handlers:++```js+app.onError((err, c) => {+ console.error('Worker error:', err.message);+ return c.json({ error: 'Internal server error' }, 500);+});+```++This is the last resort. Route handlers should not rely on it.++## Logging++Use `console.error()` for errors in route handlers — Cloudflare Workers captures these in the dashboard logs.++Format: `console.error('METHOD /path:', err.message)` — includes the route for easy filtering.++Do not log sensitive values: access tokens, API keys, user emails, Supabase URLs.++Do not use `console.log()` in production code paths except for cron job status messages (these are useful for monitoring scheduled tasks).++## User-Facing Error Messages++Backend errors should be descriptive but not expose implementation details:+- Good: `'Account not found'`, `'Instagram API rate limit exceeded'`, `'Missing required field: scheduledAt'`+- Bad: `'supabase error: duplicate key value violates unique constraint accounts_pkey'`++When the Supabase or Instagram API returns a message that is end-user readable, pass it through. When it is technical (e.g., PostgreSQL constraint violation), translate it.diff --git a/docs/guidelines/HONO.md b/docs/guidelines/HONO.mdnew file mode 100644index 0000000..e38694b--- /dev/null+++ b/docs/guidelines/HONO.md@@ -0,0 +1,128 @@+# Hono Guidelines++## Route Handler Structure++Every route handler follows this exact shape:++```js+router.METHOD('/path', async (c) => {+ const userId = c.get('userId'); // from requireAuth middleware+ const supabase = c.get('supabase'); // from client injection middleware+ const redis = c.get('redis'); // may be null — always guard++ // 1. Read inputs+ const id = c.req.param('id');+ const body = await c.req.json(); // POST/PUT only++ // 2. Validate inputs early+ if (!body.name) return c.json({ error: 'Missing required field: name' }, 400);++ // 3. Execute business logic (in try/catch)+ try {+ const result = await doSomething(supabase, userId, id);+ return c.json(result);+ } catch (err) {+ console.error('METHOD /path:', err.message);+ return c.json({ error: err.message }, 500);+ }+});+```++## Context Values++Access these via `c.get()` — never reconstruct them inside handlers:++| Key | Type | Notes |+|---|---|---|+| `userId` | string (UUID) | Set by `requireAuth`. Always present on protected routes |+| `userEmail` | string | Set by `requireAuth`. May be undefined on older JWTs |+| `supabase` | SupabaseClient | Set by client injection middleware |+| `redis` | Redis \| null | Set by client injection middleware. Null if not configured |++## Reading Request Data++```js+// URL params (/accounts/:id)+const id = c.req.param('id');++// Query string (?limit=10)+const limit = c.req.query('limit');++// JSON body (POST/PUT)+const body = await c.req.json();++// Headers+const auth = c.req.header('Authorization');+```++Never destructure `c.req` directly — always call the method.++## Returning Responses++```js+// JSON success+return c.json(data); // 200+return c.json(data, 201); // 201 Created++// JSON error+return c.json({ error: 'message' }, 400); // client error+return c.json({ error: err.message }, 500); // server error++// Early return (validation fail)+if (!id) return c.json({ error: 'Missing id' }, 400);+```++Always return `c.json()`. Never use `return new Response()` inside app route handlers (that is for the Worker's `fetch()` export).++## Router Organization++```js+// backend/routes/myFeature.js+import { Hono } from 'hono';++const router = new Hono();++router.get('/my-resources', async (c) => { ... });+router.post('/my-resources', async (c) => { ... });+router.delete('/my-resources/:id', async (c) => { ... });++export default router;+```++Mount in `server.js`:++```js+import myFeatureRouter from './routes/myFeature.js';+api.route('/', myFeatureRouter);+```++## Middleware++Middleware uses `async (c, next) => { ... await next(); }`. Never skip `next()` unless intentionally short-circuiting:++```js+// Short-circuit (returns early without calling next)+app.use('/api/*', async (c, next) => {+ const token = c.req.header('Authorization')?.replace('Bearer ', '');+ if (!token) return c.json({ error: 'Unauthorized' }, 401);+ // set context, then continue+ c.set('userId', userId);+ await next();+});+```++## Error Handling Rules++- Always wrap external calls (Supabase, platform APIs) in try/catch+- Log with `console.error('VERB /path:', err.message)` — include the route in the log+- Never throw from a route handler — catch and return `c.json({ error }, status)`+- 400 for client errors (missing fields, invalid format, resource not found)+- 500 for server errors (DB failures, external API failures)+- Never expose stack traces in the response body++## What Not To Do++- Do not import `env` directly — access it via `c.env` or via the middleware-injected clients+- Do not use `c.env` directly in route handlers — always use `c.get('supabase')` / `c.get('redis')`+- Do not build Supabase clients inside route handlers — the middleware does this once per request+- Do not use `app.use()` for business logic — that is for cross-cutting middleware onlydiff --git a/docs/guidelines/JAVASCRIPT.md b/docs/guidelines/JAVASCRIPT.mdnew file mode 100644index 0000000..0363df3--- /dev/null+++ b/docs/guidelines/JAVASCRIPT.md@@ -0,0 +1,130 @@+# JavaScript Standards++This project is plain JavaScript — no TypeScript, no Babel transpilation beyond what Vite handles. These rules apply to both the backend (Cloudflare Worker) and the frontend (Vite + React).++## Module System++- **Backend:** ES modules only (`"type": "module"` in `backend/package.json`). Use `import`/`export`. No `require()`.+- **Frontend:** ES modules via Vite. Same rules.+- Never mix `import` and `require()` in the same file.++## File Conventions++- **Backend files:** `camelCase.js` — `server.js`, `auth.js`, `instagram.js`, `db.js`+- **Frontend utility/service files:** `camelCase.js` — `api.js`, `formatters.js`+- **Frontend React files:** `PascalCase.jsx` — `Overview.jsx`, `AppContext.jsx`+- **shadcn generated files:** `kebab-case.jsx` — do not rename these++## Comments Policy++Write no comments by default. Add a comment only when the WHY is non-obvious and cannot be expressed in naming alone: a hidden constraint, a surprising invariant, a workaround for a specific bug.++**Do not write:**+- Comments explaining what the code does (naming does that)+- Comments referencing the task or PR ("added for issue #123")+- Multi-line comment blocks+- JSDoc++**Do write (sparingly):**+```js+// userId=null means service-level — used by cron handlers that scan all users+export async function getAccounts(supabase, userId = null) { ... }++// Redis HMAC state: base64url(userId:timestamp).HMAC-SHA256-sig — see cache.js+```++## Naming++- Functions: `camelCase` — `getAccounts`, `computeVideoAnalytics`, `publishToInstagram`+- Variables: `camelCase` — `accountId`, `scheduledAt`, `accessToken`+- Constants: `SCREAMING_SNAKE_CASE` only for true global constants (rare)+- React components: `PascalCase` — `ChannelAnalytics`, `AppProvider`++Prefer names that describe intent, not implementation:+- `getVideosCache` not `redisGetVideos`+- `requireAuth` not `jwtMiddleware`+- `safeAccount` not `stripToken`++## Error Handling++In **route handlers**, always catch and return JSON errors:+```js+try {+ const data = await someOperation();+ return c.json(data);+} catch (err) {+ console.error('GET /my-route:', err.message);+ return c.json({ error: err.message }, 500);+}+```++In **service functions**, throw descriptive errors — let the caller decide how to handle:+```js+if (data.error) throw new Error(data.error.message);+```++In **cache functions**, always catch and silently ignore — cache failures must never bubble up:+```js+try { return await redis.get(key); } catch { return null; }+```++In **frontend components**, catch API errors and show toasts:+```js+try {+ const result = await api.doThing();+ showToast('Done!');+} catch (err) {+ showToast(err.message, 'error');+}+```++## Async/Await++Use `async/await` everywhere. Do not use `.then()/.catch()` chains except in brief one-liners where the chain is clearer.++```js+// Good+const data = await api.getAnalytics(id);++// Avoid+api.getAnalytics(id).then(data => ...).catch(err => ...);+```++## Variable Declarations++Use `const` by default. Use `let` only when the variable is reassigned. Never use `var`.++## Equality++Always use `===` and `!==`. Never `==` or `!=`.++## String Formatting++Use template literals for all string interpolation:+```js+const url = `${SUPABASE_URL}/rest/v1/accounts?id=eq.${accountId}`;+```++## Object Patterns++Prefer destructuring:+```js+const { id, platform, ...data } = account;+const { data: { session } } = await supabase.auth.getSession();+```++Use optional chaining:+```js+const token = session?.access_token;+const name = account?.data?.username;+```++Use nullish coalescing:+```js+const limit = params.limit ?? 500;+const accounts = data ?? [];+```++## No Unused Code++Do not leave unused variables, unused imports, or commented-out code blocks. Remove them.diff --git a/docs/guidelines/NAMING.md b/docs/guidelines/NAMING.mdnew file mode 100644index 0000000..b5007f0--- /dev/null+++ b/docs/guidelines/NAMING.md@@ -0,0 +1,63 @@+# Naming Conventions++## Files++| Location | Convention | Examples |+|---|---|---|+| Backend routes | `camelCase.js` | `accounts.js`, `scheduledPosts.js`, `instagramAuth.js` |+| Backend services | `camelCase.js` | `instagram.js`, `youtube.js` |+| Backend lib | `camelCase.js` | `db.js`, `cache.js`, `supabase.js`, `redis.js` |+| Backend middleware | `camelCase.js` | `auth.js` |+| Frontend pages | `PascalCase.jsx` | `Login.jsx`, `Overview.jsx` |+| Frontend feature components | `PascalCase.jsx` | `ChannelAnalytics.jsx`, `AccountManager.jsx` |+| Frontend contexts | `PascalCaseContext.jsx` | `AuthContext.jsx`, `AppContext.jsx` |+| Frontend layout | `PascalCase.jsx` or `index.jsx` | `Sidebar.jsx`, `Header.jsx`, `index.jsx` |+| Frontend hooks | `use-kebab-case.js` | `use-mobile.js` |+| Frontend utilities | `camelCase.js` | `formatters.js`, `api.js`, `utils.js` |+| shadcn components | `kebab-case.jsx` | `button.jsx`, `card.jsx` (generated — do not rename) |+| Documentation | `SCREAMING_SNAKE_CASE.md` | `OVERVIEW.md`, `JAVASCRIPT.md`, `SCHEMA.md` |++## Functions++- Backend route handlers: `camelCase` verb + noun — `getAnalytics(c)`, `createAccount(c)`, `deletePost(c)`+- Backend service functions: `camelCase` verb + noun — `fetchChannelData()`, `computeVideoAnalytics()`, `publishIGContainer()`+- Backend db functions: `camelCase` verb + noun — `getAccounts()`, `createPost()`, `updateAccount()`, `deletePost()`+- Frontend API methods: `camelCase` verb + noun — `getAnalytics()`, `createScheduledPost()`, `deleteAccount()`+- React event handlers: `handle` + PascalCase noun/event — `handleSubmit()`, `handleDeleteClick()`, `handleInputChange()`+- React custom hooks: `use` + PascalCase noun — `useAppContext()`, `useIsMobile()`++## Variables++- `camelCase` throughout — `accountId`, `scheduledAt`, `accessToken`, `uploadPlaylistId`+- Boolean variables: `is`/`has`/`can` prefix — `isLoading`, `hasError`, `canPublish`+- IDs: always `{entity}Id` suffix — `accountId`, `userId`, `containerId`, `mediaId`+- Timestamps: `{action}At` suffix — `scheduledAt`, `publishedAt`, `createdAt`+- Counts: `{entity}Count` suffix — `subscriberCount`, `viewCount`, `mediaCount`+- Collections/arrays: plural noun — `accounts`, `videos`, `posts`, `hashtags`++## Constants++- True global constants: `SCREAMING_SNAKE_CASE` — `API`, `DEFAULT_KEYS`+- Environment-derived values at module top: `SUPABASE_URL`, `SUPABASE_SERVICE_KEY` (from env)+- Named groupings: prefer an object over multiple constants++## Database++- Table names: `snake_case`, plural — `accounts`, `settings`, `scheduled_posts`+- Column names: `snake_case` — `user_id`, `account_id`, `scheduled_at`, `access_token` (inside jsonb)+- jsonb field names: `camelCase` — these are JavaScript objects embedded in JSON, so they follow JS conventions: `accessToken`, `subscriberCount`, `publishedAt`++## Routes++- REST convention: noun-first, plural — `/accounts`, `/scheduled-posts`+- Resource nesting: `/accounts/:id/ig-analytics` (not `/ig-analytics/:accountId`)+- Kebab-case multi-word paths — `/refresh-all`, `/ig-publish`, `/process-scheduled`++## Supabase Cache Keys++`{entity}:{userId}:{accountId}` — `videos:abc-123:def-456`, `ig:abc-123:def-456`++## Environment Variables++- Backend Worker secrets: `SCREAMING_SNAKE_CASE` — `SUPABASE_URL`, `YOUTUBE_API_KEY`+- Frontend Vite variables: `VITE_` prefix + `SCREAMING_SNAKE_CASE` — `VITE_API_URL`, `VITE_SUPABASE_URL`diff --git a/docs/guidelines/REACT.md b/docs/guidelines/REACT.mdnew file mode 100644index 0000000..21f7807--- /dev/null+++ b/docs/guidelines/REACT.md@@ -0,0 +1,123 @@+# React Standards++## Component Rules++**Function components only.** No class components.++```jsx+export default function ChannelAnalytics() {+ // ...+ return <div>...</div>;+}+```++**One component per file.** Small helper sub-components can live in the same file if they are only used in that one file and are not exported.++**No prop-types.** This project does not use PropTypes or TypeScript types. Descriptive prop names are the documentation.++## Hooks++Use hooks at the top level of the component, never inside conditions or loops:++```jsx+// Good+function MyComponent({ id }) {+ const [data, setData] = useState(null);+ const { showToast } = useAppContext();+ // ...+}++// Bad+function MyComponent({ id }) {+ if (id) {+ const [data, setData] = useState(null); // ❌ conditional hook+ }+}+```++**Custom hooks** go in `frontend/src/hooks/`. Name them `use-kebab-case.js`. Export a single function named `useSomething`.++## State Management++**Prefer local state** for data that only one component needs. Use `useState`.++**Use AppContext** for data that multiple components need: `accounts`, `showToast`.++**Do not add new keys to AppContext** without strong justification. Page-level state (loading, analytics data) belongs in the page component, not the global context.++See `docs/guidelines/STATE_MANAGEMENT.md` for detailed guidance.++## Data Fetching Pattern++Fetch data in `useEffect` on component mount:++```jsx+const [data, setData] = useState(null);+const [loading, setLoading] = useState(true);+const { showToast } = useAppContext();++useEffect(() => {+ let cancelled = false;+ async function load() {+ try {+ const result = await api.getAnalytics(id);+ if (!cancelled) setData(result);+ } catch (err) {+ if (!cancelled) showToast(err.message, 'error');+ } finally {+ if (!cancelled) setLoading(false);+ }+ }+ load();+ return () => { cancelled = true; };+}, [id, showToast]);+```++The `cancelled` flag prevents state updates on unmounted components (important for pages that navigate away during loading).++## JSX Rules++**Conditional rendering:**+```jsx+// For if/else with significant content:+{loading ? <Skeleton /> : <DataTable data={data} />}++// For optional rendering:+{error && <ErrorBanner message={error} />}+```++**Lists always need `key`:**+```jsx+{accounts.map(account => (+ <AccountCard key={account.id} account={account} />+))}+```++**Event handlers** are named `handle{Event}` by convention:+```jsx+function handleSubmit(e) { ... }+function handleDeleteClick() { ... }+function handleInputChange(e) { ... }+```++## Lazy Loading++All pages are lazy-loaded via `React.lazy()` in `App.jsx`. Do not import pages directly — always use lazy imports for new pages.++```jsx+const MyNewPage = lazy(() => import('./features/myFeature/MyNewPage'));+```++## Accessibility++- All interactive elements must be keyboard-accessible+- `<button>` for actions, `<a>` for navigation+- Images need `alt` attributes (empty string for decorative images)+- Use semantic HTML: `<main>`, `<nav>`, `<section>`, `<article>` where appropriate+- shadcn components handle most ARIA attributes automatically — use them as provided++## Performance++- Avoid large computations in render — move to `useMemo` if expensive+- Avoid re-creating functions in render that are passed as props — use `useCallback`+- The analytics computation functions (`computeVideoAnalytics`) run on the backend, not the frontenddiff --git a/docs/guidelines/SHADCN.md b/docs/guidelines/SHADCN.mdnew file mode 100644index 0000000..17f64e9--- /dev/null+++ b/docs/guidelines/SHADCN.md@@ -0,0 +1,106 @@+# shadcn/ui Standards++## Configuration++```json+// frontend/components.json+{+ "style": "base-nova",+ "rsc": false,+ "tsx": false,+ "tailwind": { "cssVariables": true },+ "aliases": { "components": "@/components", "utils": "@/lib/utils" }+}+```++Style: `base-nova`. CSS variables: enabled. No TypeScript (tsx: false).++## Import Pattern++Always import from the local `@/components/ui/` path:++```jsx+import { Button } from '@/components/ui/button';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { Badge } from '@/components/ui/badge';+```++Never import from `shadcn/ui` directly — the components are copied into the project.++## Adding a New Component++```bash+cd frontend+npx shadcn@latest add <component-name>+```++This copies the component source into `frontend/src/components/ui/`. After adding, verify the generated file uses `.jsx` (not `.tsx`). The `components.json` configuration should handle this automatically.++## Composition Rules++shadcn components are composed using their named export variants. Read the component file in `frontend/src/components/ui/` to understand the available props before using them.++```jsx+// Card composition+<Card>+ <CardHeader>+ <CardTitle>Title</CardTitle>+ <CardDescription>Subtitle</CardDescription>+ </CardHeader>+ <CardContent>+ {/* content */}+ </CardContent>+ <CardFooter>+ {/* actions */}+ </CardFooter>+</Card>+```++## Common Components in Use++| Component | Import | Use case |+|---|---|---|+| `Button` | `@/components/ui/button` | All action buttons; use `variant` prop: `default`, `outline`, `ghost`, `destructive` |+| `Card`, `CardHeader`, `CardContent`, `CardFooter` | `@/components/ui/card` | Content containers |+| `Badge` | `@/components/ui/badge` | Status labels, platform tags |+| `Avatar` | `@/components/ui/avatar` | Channel/account avatars |+| `Table`, `TableHeader`, etc. | `@/components/ui/table` | Data tables |+| `Tabs`, `TabsList`, `TabsTrigger`, `TabsContent` | `@/components/ui/tabs` | View switching |+| `Dialog`, `DialogContent`, etc. | `@/components/ui/dialog` | Modals |+| `Select`, `SelectTrigger`, etc. | `@/components/ui/select` | Dropdown selects |+| `Tooltip`, `TooltipContent`, etc. | `@/components/ui/tooltip` | Hover tooltips |+| `Skeleton` | `@/components/ui/skeleton` | Loading placeholders |+| `Alert`, `AlertTitle`, `AlertDescription` | `@/components/ui/alert` | Info/warning/error banners |+| `Input` | `@/components/ui/input` | Text inputs |+| `Label` | `@/components/ui/label` | Form labels |++## `cn()` Utility++Always use `cn()` from `@/lib/utils` to combine class names — it handles conditional classes and tailwind-merge conflicts:++```jsx+import { cn } from '@/lib/utils';++<div className={cn('base-class', isActive && 'active-class', className)}>+```++## StatCard Component++A custom component at `frontend/src/components/ui/StatCard.jsx` is a KPI tile used across all analytics pages. Use it for metric display:++```jsx+import StatCard from '@/components/ui/StatCard';++<StatCard+ title="Total Views"+ value={fmtNum(analytics.totalViews)}+ icon={Eye}+ description="Lifetime channel views"+/>+```++## Theme++The project uses `next-themes` with `attribute="class"`. Dark mode is applied by adding the `dark` class to `<html>`. All shadcn components respond to this automatically via CSS variables defined in `frontend/src/index.css`.++Do not hardcode colors in components — use Tailwind semantic classes (`text-muted-foreground`, `bg-card`, `border-border`, etc.) that reference CSS variables.diff --git a/docs/guidelines/STATE_MANAGEMENT.md b/docs/guidelines/STATE_MANAGEMENT.mdnew file mode 100644index 0000000..3a3a2f6--- /dev/null+++ b/docs/guidelines/STATE_MANAGEMENT.md@@ -0,0 +1,93 @@+# State Management++## Decision Tree++```+Is the data needed by only one component?+ → useState in that component++Is the data needed by a few sibling/child components?+ → useState in the closest common ancestor, passed as props++Is the data needed across many unrelated pages?+ → AppContext (accounts, showToast)++Is the data auth-related (session, user)?+ → AuthContext+```++## Component-Level State (`useState`)++Default choice. Use it for:+- Loading states (`isLoading`, `isSaving`)+- Form field values+- UI state (open/closed, selected tab, active filter)+- Page-specific fetched data (analytics results, video list)++```jsx+const [analytics, setAnalytics] = useState(null);+const [loading, setLoading] = useState(true);+const [selectedTab, setSelectedTab] = useState('overview');+```++## AppContext — What Belongs Here++`AppContext` currently provides:++| State | Type | Why global |+|---|---|---|+| `accounts` | `Account[]` | Needed by Sidebar (nav links), Overview (dashboard), all analytics pages (lookup by ID), AccountManager (CRUD), Header (refresh button) |+| `loading` | `boolean` | The global refresh spinner in Header |+| `showToast` | `function` | Toast notifications from anywhere — avoids threading Sonner's `toast` import everywhere |++**Do not add** page-specific data to `AppContext`. If only one or two pages need a piece of data, keep it local.++## AuthContext — What Belongs Here++Only auth state:+- `session` — the Supabase session object+- `user` — shorthand for `session.user`+- `signIn`, `signUp`, `signOut` — auth actions++Feature pages should not need to read `AuthContext`. If a feature page needs the user's email or ID, reconsider — in most cases, the backend handles user scoping via the JWT, so the frontend doesn't need to know the userId.++## Derived State++Prefer computing derived values at render time rather than storing them in state:++```jsx+// Good — derive from existing state+const youtubeAccounts = accounts.filter(a => a.platform === 'youtube');+const totalViews = accounts.reduce((sum, a) => sum + (a.viewCount || 0), 0);++// Bad — storing derived data in extra state+const [youtubeAccounts, setYoutubeAccounts] = useState([]);+useEffect(() => {+ setYoutubeAccounts(accounts.filter(a => a.platform === 'youtube'));+}, [accounts]);+```++If the derivation is expensive (e.g., sorting 500 videos), use `useMemo`:++```jsx+const sortedVideos = useMemo(+ () => [...videos].sort((a, b) => b.viewCount - a.viewCount),+ [videos]+);+```++## URL as State++For filterable/sortable pages (VideoExplorer, ReelsExplorer), consider putting filter state in the URL as search params. This makes the view shareable and preserves state on back navigation. Current implementation uses local state; this is a potential improvement.++## Refs (`useRef`)++Use `useRef` for:+- Referencing DOM elements (`ref={inputRef}; inputRef.current.focus()`)+- Storing mutable values that should not trigger re-renders (e.g., a timer ID, a cancelled flag)++Do not use `useRef` as a workaround for stale closures — fix the closure instead.++## No External State Library++The project does not use Redux, Zustand, Jotai, or any external state management library. The combination of `useState` + `AppContext` + `AuthContext` is sufficient for this application's complexity.diff --git a/docs/guidelines/SUPABASE.md b/docs/guidelines/SUPABASE.mdnew file mode 100644index 0000000..16d3eb1--- /dev/null+++ b/docs/guidelines/SUPABASE.md@@ -0,0 +1,116 @@+# Supabase Standards++## Two Clients, Two Purposes++| Client | Key used | Created by | Purpose |+|---|---|---|---|+| Service client | `SUPABASE_SERVICE_KEY` | `getSupabase(env)` in `lib/supabase.js` | All DB operations (bypasses RLS) |+| Auth client | `SUPABASE_ANON_KEY` | `getSupabaseAuth(env)` in `lib/supabase.js` | JWT verification only (`auth.getUser(token)`) |+| Frontend client | `VITE_SUPABASE_ANON_KEY` | `lib/supabase.js` in frontend | Supabase Auth (sign in/out, session) — no DB queries |++**Rule:** The service client is the only client used for database queries. The auth client is used exclusively in `requireAuth` middleware. The frontend client is used only for Supabase Auth, never for database access.++## Query Pattern++All Supabase queries are in `backend/lib/db.js`. Route handlers never call `supabase.from()` directly.++```js+// In lib/db.js:+export async function getAccounts(supabase, userId = null) {+ let q = supabase.from('accounts').select('id, platform, data');+ if (userId) q = q.eq('user_id', userId);+ const { data, error } = await q;+ if (error) throw error;+ return (data || []).map(row => ({ id: row.id, platform: row.platform, ...row.data }));+}++// In route handler:+import { getAccounts } from '../lib/db.js';++router.get('/accounts', async (c) => {+ const supabase = c.get('supabase');+ const userId = c.get('userId');+ const accounts = await getAccounts(supabase, userId);+ return c.json(accounts);+});+```++## Error Handling++Always check the `error` field from Supabase responses and throw:++```js+const { data, error } = await supabase.from('accounts').select('*');+if (error) throw error;+```++Do not silently ignore errors. Route handlers will catch the thrown error and return a 500 JSON response.++## Upserts++Use `onConflict` to specify the conflict resolution key:++```js+await supabase+ .from('settings')+ .upsert(+ { user_id: userId, key: 'api_keys', value: keys },+ { onConflict: 'user_id,key' }+ );+```++## jsonb Data Column Pattern++The `data` jsonb column stores platform-specific fields for accounts and post metadata for scheduled posts. The pattern for reading and updating:++```js+// Reading: spread data into the returned object+return { id: row.id, platform: row.platform, ...row.data };++// Updating: merge new fields with existing data (don't replace the whole object)+const current = await getAccountById(supabase, id, userId);+const { id: _, platform: currentPlatform, ...currentData } = current;+await supabase.from('accounts').update({+ data: { ...currentData, ...updates } // merge, not replace+}).eq('id', id);+```++**Never replace the entire `data` object** without first reading the current value — you'll lose fields that aren't in the update.++## Row Isolation++Every user-scoped query must include `.eq('user_id', userId)`. Functions that intentionally omit this (for cron use) should document it with a comment:++```js+export async function getDuePosts(supabase) {+ // No userId filter — used by cron scheduler to process all users' posts+ const { data, error } = await supabase+ .from('scheduled_posts')+ .select(...)+ .eq('status', 'pending')+ .lte('scheduled_at', new Date().toISOString());+ ...+}+```++## Client Lifecycle++Supabase clients are created fresh per request in the Worker — they are stateless HTTP clients and safe to create on each request. Do not cache client instances in module-level variables; they would hold references to a specific request's `env` bindings.++```js+// lib/supabase.js+export function getSupabase(env) {+ return createClient(env.SUPABASE_URL, env.SUPABASE_SERVICE_KEY);+}+```++## Frontend — No DB Access++The frontend's Supabase client (`frontend/src/lib/supabase.js`) is used only for:+- `supabase.auth.signInWithPassword()`+- `supabase.auth.signUp()`+- `supabase.auth.signOut()`+- `supabase.auth.getSession()`+- `supabase.auth.onAuthStateChange()`++The frontend never queries Supabase tables directly. All data comes through the Cloudflare Worker API.diff --git a/docs/guidelines/TAILWIND.md b/docs/guidelines/TAILWIND.mdnew file mode 100644index 0000000..c8725c6--- /dev/null+++ b/docs/guidelines/TAILWIND.md@@ -0,0 +1,105 @@+# Tailwind CSS v4 Guidelines++## Version++This project uses **Tailwind CSS v4**. The v4 API is substantially different from v3:+- Configuration is done via CSS `@theme` instead of `tailwind.config.js`+- No `tailwind.config.js` exists — do not create one+- Use `@import "tailwindcss"` in the main CSS entry point+- Utility classes are the same as v3 in most cases++## Token References++Design tokens are defined in the CSS file (check `frontend/src/index.css` or `frontend/src/app.css` for the `@theme` block). Use these tokens via their utility class names — never use hardcoded hex values in class names.++Common token utilities:+- `bg-background` / `text-foreground` — page background and main text+- `bg-card` / `text-card-foreground` — card surfaces+- `bg-muted` / `text-muted-foreground` — subdued backgrounds and secondary text+- `border-border` — default border color+- `bg-primary` / `text-primary-foreground` — primary action color+- `bg-destructive` / `text-destructive-foreground` — error/delete actions++## Layout++### Page wrapper++```jsx+<div className="p-6 space-y-6">+ {/* page content */}+</div>+```++### Grid layouts++```jsx+<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">+ {/* stat cards */}+</div>+```++### Flex rows++```jsx+<div className="flex items-center gap-2">+ {/* icon + label */}+</div>+```++## Spacing System++Use the spacing scale consistently. Common patterns in this project:+- `p-6` — standard page padding+- `p-4` — card inner padding+- `gap-4` — grid column gap+- `gap-2` — inline icon+label gap+- `space-y-6` — vertical rhythm between major sections+- `space-y-4` — vertical rhythm within a card+- `mb-4` / `mb-6` — heading bottom margin++## Typography++```jsx+<h1 className="text-2xl font-bold">Page Title</h1>+<h2 className="text-lg font-semibold">Section</h2>+<p className="text-sm text-muted-foreground">Secondary info</p>+```++Avoid using `text-xs` for anything the user needs to read comfortably. Use `text-sm` as the minimum for content.++## Responsive++Mobile-first. Most pages in this app are designed primarily for desktop (analytics dashboards), but keep them usable on mobile:+- Use `grid-cols-1 md:grid-cols-2 lg:grid-cols-4` for stat card rows+- Use `overflow-x-auto` on table wrappers+- Use `hidden md:flex` to hide elements that don't fit on mobile++## Dark Mode++This project uses shadcn's theme system, which manages light/dark via CSS custom properties — not Tailwind's `dark:` variant. Do not use `dark:` variants. Use token-based colors (`bg-card`, `text-muted-foreground`) which automatically respond to the theme.++If you need to add a custom dark-mode variant for non-token colors, add a CSS custom property to the `@theme` block instead.++## The `cn()` Utility++Use `cn()` (from `@/lib/utils`) for conditional class merging:++```jsx+import { cn } from '@/lib/utils';++<div className={cn(+ 'base-class',+ isActive && 'bg-primary text-primary-foreground',+ className // allow parent to override+)} />+```++Never use template literals for conditional classes — they won't be properly merged and can produce duplicate or conflicting utilities.++## What Not To Do++- Do not use `style={{}}` for values that can be expressed as Tailwind utilities+- Do not hardcode colors in class names (`text-[#ff0000]`) — use design token utilities+- Do not use `!important` (`!text-red-500`) unless debugging a specificity conflict+- Do not create a `tailwind.config.js` — configuration lives in the CSS `@theme` block in v4+- Do not use `dark:` prefix variants — theme is token-based, not class-baseddiff --git a/docs/mcp/CONTEXT7.md b/docs/mcp/CONTEXT7.mdnew file mode 100644index 0000000..a53180c--- /dev/null+++ b/docs/mcp/CONTEXT7.md@@ -0,0 +1,76 @@+# MCP: Context7 — Library Documentation++## Purpose++Context7 fetches current, version-accurate documentation for libraries and APIs. Use it whenever you need to look up:+- Method signatures and parameters+- API field names and enum values+- Configuration options+- Migration differences between versions+- Framework-specific patterns++## When to Use++✅ **Use Context7 for:**+- Instagram Graph API — container creation params, field names, error codes+- YouTube Data API v3 — endpoint params, quota costs, response shapes+- Hono v4 — middleware API, context methods, routing+- Supabase JS — client methods, query builder, auth API+- Cloudflare Workers — runtime APIs, `ctx.waitUntil()`, env bindings+- Recharts v3 — component props, data shapes, chart configuration+- shadcn/ui components — available props, slot composition+- React 19 — hooks API, new features+- React Router v7 — `createBrowserRouter`, `Outlet`, nested routes++❌ **Do not use Context7 for:**+- Debugging business logic (read the code instead)+- Code review+- Architecture decisions (use Sequential Thinking)+- General programming questions++## Workflow++1. `resolve-library-id` with the library name and your specific question+2. Review results — pick the ID with the most relevant description and highest score+3. `query-docs` with the selected ID and your full question+4. Apply the documentation to the implementation++## Example Queries++### Instagram Graph API++```+resolve-library-id: "instagram graph api media publish"+query-docs: "What parameters are required to create a Reels media container?+ What is the field name for the video URL and share_to_feed?"+```++### Supabase upsert++```+resolve-library-id: "supabase javascript client"+query-docs: "How do I use upsert with onConflict to specify composite primary key columns?"+```++### Hono middleware context++```+resolve-library-id: "hono cloudflare workers"+query-docs: "How do I set and get values on the Hono context using c.set() and c.get()?+ What is the TypeScript interface for custom context variables?"+```++### Recharts area chart++```+resolve-library-id: "recharts"+query-docs: "How do I create an AreaChart with multiple data series,+ custom tooltips, and a responsive container?"+```++## Tips++- Be specific in your query — include the exact method name or concept+- If the first result doesn't match, try alternate names (e.g., "next.js" not "nextjs", "hono.js" not "honojs")+- Use version-specific IDs when the project is on a specific version and the API has changed recently+- The Supabase library has multiple IDs — prefer the one specifically for the JavaScript clientdiff --git a/docs/mcp/FILESYSTEM.md b/docs/mcp/FILESYSTEM.mdnew file mode 100644index 0000000..00e33b2--- /dev/null+++ b/docs/mcp/FILESYSTEM.md@@ -0,0 +1,76 @@+# MCP: Filesystem — Codebase Navigation++## Purpose++Filesystem MCP provides advanced file operations: recursive search, directory trees, file reading, and moving files. Use it for exploration tasks that require looking at multiple files or the full directory structure.++## When to Use++✅ **Use Filesystem for:**+- Finding all files that import a specific module+- Getting a directory tree to understand project structure+- Searching for all uses of a function or variable name+- Moving or renaming files and updating all imports+- Reading multiple related files simultaneously++❌ **Do not use Filesystem when:**+- You know the exact file path (use Read tool directly)+- You're looking for a single string (use Grep tool directly)+- You're searching for a file by pattern (use Glob tool directly)++## Common Workflows++### Find all callers of a function++```+filesystem: search_files+pattern: "safeAccount"+path: backend/+```++Better: Use the built-in Grep tool for this — it's faster for string search.++### Get directory structure++```+filesystem: directory_tree+path: frontend/src/features/+```++### Find all route files++```+filesystem: list_directory+path: backend/routes/+```++### Find all components that use AppContext++```+filesystem: search_files+pattern: "useAppContext"+path: frontend/src/+```++## When to Use Grep/Glob Instead++The built-in Grep and Glob tools are faster for most search tasks:++- `Grep pattern="useAppContext"` — faster than filesystem search for string patterns+- `Glob pattern="backend/routes/*.js"` — faster than filesystem for file patterns+- `Read file_path="..."` — faster than filesystem for single file reads++Use Filesystem MCP when you need its specific features: recursive directory trees, multi-file reads in one call, or file move operations.++## Refactoring Workflow++When renaming a function or moving a file:++1. Filesystem: find all files that reference the old name+2. Edit each file+3. Verify with Grep that no old references remain++Example: renaming `safeAccount` to `stripSensitiveFields`:+1. `search_files pattern="safeAccount" path="backend/"` → list of files+2. Edit each file+3. `Grep pattern="safeAccount"` → should return emptydiff --git a/docs/mcp/OVERVIEW.md b/docs/mcp/OVERVIEW.mdnew file mode 100644index 0000000..32bf606--- /dev/null+++ b/docs/mcp/OVERVIEW.md@@ -0,0 +1,60 @@+# MCP Usage — Decision Guide++Four MCP servers are available. Each has a specific purpose. Using the wrong one wastes time and produces worse results than using the right one.++## Quick Decision Tree++```+Need API docs, library reference, or framework docs?+ → Context7++Need to find a file, symbol, or understand the codebase?+ → Filesystem (or direct Grep/Glob tools first)++Need to plan a complex feature, debug a hard problem, or think through architecture?+ → Sequential Thinking++Need to research UX patterns, browser compat, competing products, or best practices?+ → Parallel Search+```++## When Each MCP is the Right Choice++| MCP | Use it for | Do not use it for |+|---|---|---|+| **Context7** | Hono API, Supabase JS methods, Instagram Graph API params, Cloudflare Workers API, Recharts props, shadcn component props | Writing code, debugging business logic, code review, general programming |+| **Filesystem** | Finding where a function is defined, locating all files that import a module, moving/renaming across multiple files | Writing code, understanding architecture (read the docs instead), large-scale analysis |+| **Sequential Thinking** | Planning a multi-step feature before implementing, architecture decisions, debugging when root cause is not obvious | Lookups (use Context7), simple one-step tasks |+| **Parallel Search** | UX research for a new feature, browser API compatibility, finding how competitors handle a UI problem, finding accessibility guidelines | Library docs (use Context7), codebase exploration (use Filesystem) |++## Workflow Examples++### Adding Instagram Reels support to the publisher++1. **Sequential Thinking** — plan the full implementation (backend params, frontend UI changes, DB schema changes if any)+2. **Context7** — look up Instagram Graph API Reels container params (`media_type=REELS`, required fields)+3. **Parallel Search** — research UX patterns for Reels upload interfaces+4. Implement++### Debugging a Supabase query that returns wrong data++1. **Filesystem** — find all callers of the function to understand the context+2. **Context7** — look up Supabase `select()`, `eq()`, `single()` semantics if the issue might be a library API misunderstanding+3. **Sequential Thinking** — if the root cause is still unclear, walk through the data flow step by step++### Adding a new shadcn component++1. **Context7** — get the exact props and composition for the component+2. Direct implementation — no other MCP needed++### Deciding whether to add a new npm dependency++1. **Sequential Thinking** — analyze the trade-offs (bundle size, alternatives, maintenance)+2. **Parallel Search** — check if there is a lightweight alternative or a Web API equivalent++## Detailed Docs++- `docs/mcp/CONTEXT7.md` — when, how, and example queries+- `docs/mcp/FILESYSTEM.md` — file search, symbol location, refactoring+- `docs/mcp/SEQUENTIAL_THINKING.md` — planning and debugging+- `docs/mcp/PARALLEL_SEARCH.md` — research workflowsdiff --git a/docs/mcp/PARALLEL_SEARCH.md b/docs/mcp/PARALLEL_SEARCH.mdnew file mode 100644index 0000000..ffb53f8--- /dev/null+++ b/docs/mcp/PARALLEL_SEARCH.md@@ -0,0 +1,71 @@+# MCP: Parallel Search — Research++## Purpose++Parallel Search fetches current web content for research tasks: UX patterns, browser compatibility, best practices, competing implementations, and up-to-date API behavior when Context7 doesn't have it.++## When to Use++✅ **Use Parallel Search for:**+- UX patterns for a feature you're designing ("how do social media schedulers handle bulk post editing?")+- Browser/platform compatibility ("does Instagram Graph API support carousel posts on all account types?")+- Recent API changes not yet in Context7 ("Instagram Graph API v21 vs v25 container creation changes")+- Accessibility guidelines ("WCAG criteria for data table accessibility")+- Competitor analysis ("how does Buffer/Hootsuite handle the scheduling queue UI?")+- Current events ("is Upstash Redis still recommended for Cloudflare Workers in 2025?")++❌ **Do not use Parallel Search for:**+- Library API docs with stable method signatures (use Context7)+- Codebase exploration (use Filesystem)+- Architecture planning (use Sequential Thinking)+- When you already know the answer from existing docs++## Research Workflow++### UX Research for a New Feature++1. Identify what you're designing (e.g., a post scheduling calendar view)+2. Use Parallel Search with 2-3 queries:+ - "social media scheduling calendar UX patterns 2024"+ - "how Hootsuite implements scheduling calendar"+ - "time slot selection UI accessibility"+3. Extract the patterns relevant to this project's constraints (mobile-first, React)+4. Apply the patterns — document sources in a code comment if the pattern is non-obvious++### API Behavior Research++When Instagram/YouTube API behavior is unclear or seems different from Context7 docs:++1. Search for recent issues or changelogs+2. Check the official API changelog (graph.facebook.com/changelog, developers.google.com/youtube/v3/revision_history)+3. Look for Stack Overflow or GitHub issues with the specific error/behavior++### Accessibility Research++Before building any interactive feature:++1. Search "WCAG 2.1 {feature type}" — e.g., "WCAG 2.1 date picker accessibility"+2. Check MDN for the correct ARIA roles and attributes+3. Apply what you find — shadcn components already include correct ARIA in most cases++## Multiple Search Queries++Parallel Search can issue multiple queries at once. When researching a feature, batch related queries:++```+Search queries:+1. "instagram graph api reels container creation required fields 2025"+2. "instagram graph api video processing status polling best practices"+3. "instagram reels api error codes"+```++This returns results faster than sequential searches.++## Integration with Implementation++Research findings should inform the implementation but not be pasted verbatim into code. Extract:+- The pattern or API contract+- Any constraints or gotchas+- The recommended approach++Then implement using the project's own style and conventions.diff --git a/docs/mcp/SEQUENTIAL_THINKING.md b/docs/mcp/SEQUENTIAL_THINKING.mdnew file mode 100644index 0000000..af8b50f--- /dev/null+++ b/docs/mcp/SEQUENTIAL_THINKING.md@@ -0,0 +1,87 @@+# MCP: Sequential Thinking — Planning and Debugging++## Purpose++Sequential Thinking enables structured, step-by-step reasoning for complex problems. Use it before implementing anything non-trivial to produce a verified plan — not a list of guesses.++## When to Use++✅ **Use Sequential Thinking for:**+- Planning a new feature that touches more than 3 files+- Architecture decisions with multiple viable approaches+- Debugging when the root cause is not immediately obvious+- Multi-step database migrations+- Features that require coordinating frontend + backend + DB changes+- Evaluating trade-offs between approaches++❌ **Do not use Sequential Thinking for:**+- Simple, well-understood tasks (adding a route that follows an existing pattern exactly)+- Library API lookups (use Context7)+- File searches (use Filesystem or Grep)++## Trigger Conditions++Consider Sequential Thinking when any of these are true:+- The feature requires changes to more than one layer (backend + frontend, or DB + backend)+- You're not sure which of two approaches is better+- You've read the code but the bug still isn't obvious+- The feature interacts with a security boundary (auth, token handling, RLS)+- You need to ensure a data flow is correct before implementing it++## Typical Reasoning Sequence for a New Feature++```+1. What is the user-visible goal?+2. What data does it need? (new? existing?)+3. Does the DB schema need to change?+4. What new backend routes are needed?+5. What does each route do? (DB queries, API calls, cache operations)+6. What new API methods does the frontend need?+7. What UI changes are needed? (new page? new component on existing page?)+8. What context or state changes are needed?+9. What are the security implications? (user isolation, token handling)+10. What can break? (cache invalidation, error states, missing data)+11. Ordered implementation steps+```++## Typical Debugging Sequence++```+1. What is the exact error message and stack trace?+2. What file and line does the error originate from?+3. What is the function doing at that line?+4. What are the inputs at that point? (log or inspect)+5. What does the function expect vs. what is it receiving?+6. Where is that input set? Trace backwards.+7. Is this a data shape mismatch, a timing issue, or a logic error?+8. What is the minimal change that fixes the root cause (not the symptom)?+```++## Examples++### Planning Reddit integration++Sequential Thinking would work through:+- Cookie-based auth vs OAuth (trade-offs, ToS risk)+- Which endpoints to call (`/user/{username}/submitted.json`, etc.)+- How to store credentials (in `accounts.data` jsonb alongside Instagram pattern)+- Token refresh strategy (poll `Set-Cookie` header on each API call)+- New cache keys to add to `cache.js`+- New routes to add to backend+- New analytics page structure+- How the sidebar/nav changes++### Debugging double-publishing++Sequential Thinking would walk through:+- The `getDuePosts()` query — what exactly does it return?+- The `status = 'publishing'` update — is it atomic?+- The race condition window between SELECT and UPDATE+- Whether Supabase/PostgreSQL guarantees isolation at the right level+- Whether the GitHub Actions workflow and Worker cron can actually overlap++## Integration with Other MCPs++Sequential Thinking + Context7: Plan first, then look up specific API details for the steps that require them.++Sequential Thinking + Parallel Search: Plan the technical approach, then research UX patterns for the user-facing parts.diff --git a/docs/philosophy/ARCHITECTURE.md b/docs/philosophy/ARCHITECTURE.mdnew file mode 100644index 0000000..df26386--- /dev/null+++ b/docs/philosophy/ARCHITECTURE.md@@ -0,0 +1,61 @@+# Architectural Principles++## Core Principles++### 1. Fetch at the edge, not in the client++The Cloudflare Worker sits at the edge, close to the user. All data fetching — from Supabase, from external platform APIs, from Redis — happens in the Worker. The React client fetches from the Worker only. The client never talks to Supabase or platform APIs directly.++**Why:** Keeps credentials server-side. Enables caching at the edge. Single point of auth enforcement.++### 2. One source of auth truth++Authentication is Supabase JWTs. The Worker verifies the JWT on every protected request. `userId` derived from the verified JWT is the only identity that matters. No session state. No cookies. The JWT is verified by checking its signature against the Supabase JWT secret — not by calling Supabase on every request.++**Why:** Stateless auth scales to zero infrastructure. JWTs are self-verifying.++### 3. Application-layer isolation instead of RLS++Every DB query appends `.eq('user_id', userId)` where `userId` comes from the verified JWT. The Worker uses the service-role key (which bypasses RLS). RLS is not relied upon for security.++**Why:** RLS adds complexity without benefit when the application layer already enforces isolation. The service-role key is needed for admin operations (cron jobs, token refresh) that run without a user JWT. See `ADR-011`.++**Constraint:** Never relax the `.eq('user_id', userId)` pattern. If you write a query without it, you have a data exposure bug.++### 4. Fail silently on the cache++Redis is optional infrastructure. The cache layer always catches errors and returns `null` on failure. The application falls through to the source of truth (Supabase / platform API). A Redis outage is invisible to users.++**Why:** Cache is a performance optimization, not a correctness requirement. Making it optional makes the system more resilient. See `ADR-008`.++### 5. Credentials stay in the Worker++Platform API credentials (Instagram app secret, YouTube API key) are Worker secrets — not in code, not in the database, not in the frontend. The only credential that goes near the frontend is the Supabase anon key, which is public by design.++User-specific tokens (Instagram access tokens, GitHub PATs) live in `accounts.data` in the database. They are read by the Worker and never returned to the frontend. See `ADR-004`.++### 6. Schemas bend before tables multiply++New platform-specific fields go into the `data jsonb` column on `accounts` or `scheduled_posts`. Adding a new table requires a clear reason: the data has a lifecycle of its own, or it needs to be queried/filtered by a column that can't be in jsonb. See `ADR-005`.++### 7. No TypeScript anywhere++This is a deliberate constraint, not an oversight. See `ADR-010` and `docs/guidelines/JAVASCRIPT.md`.++## What This Architecture Is Not++**Not a microservices architecture.** One Worker serves all backend routes. One Hono app. One entry point.++**Not a real-time system.** There are no WebSockets, no Server-Sent Events. Analytics pages refresh on load. Scheduled post status updates on poll.++**Not a multi-tenant platform.** Every user has their own credentials, their own accounts. There is no concept of organizations, teams, or shared accounts at the data layer. (This is a known constraint — see ROADMAP.md.)++## When to Break These Rules++These principles guide the initial implementation. Breaking them requires an explicit ADR:+- Adding a second Worker: write `ADR-013` explaining why one Worker is insufficient+- Enabling RLS: write an ADR explaining why application-layer isolation failed+- Adding TypeScript: write an ADR with clear measurable benefit+- Adding a state management library: write an ADR showing that context + local state is insufficient++The cost of documenting the decision is intentionally low. The point is to make the tradeoff visible, not to prevent evolution.diff --git a/docs/philosophy/PERFORMANCE.md b/docs/philosophy/PERFORMANCE.mdnew file mode 100644index 0000000..1042441--- /dev/null+++ b/docs/philosophy/PERFORMANCE.md@@ -0,0 +1,73 @@+# Performance Model++## Caching Strategy++### Two layers of cache++```+Request+ → Redis (hot cache, ~1ms) ← check first+ hit: return immediately+ miss: fall through+ → Platform API / Supabase ← cold path+ → populate Redis+ → return result+```++### Cache keys and TTLs++| Resource | Cache key | TTL | Note |+|---|---|---|---|+| YouTube analytics | `videos:{userId}:{accountId}` | None set (bug — see ROADMAP) | Should be 1 hour |+| Instagram analytics | `ig:{userId}:{accountId}` | None set (bug — see ROADMAP) | Should be 1 hour |+| OAuth state | `oauth_ig:{state}` | 10 minutes | Security-critical — do not extend |++Cache invalidation happens on:+- Account deletion (explicit `redis.del()`)+- Token refresh (explicit `redis.del()`)+- Manual "Refresh" action in the UI (calls the API which skips cache)++There is no time-based expiration for analytics caches yet (known issue). Until TTLs are set, users see stale analytics until they explicitly refresh.++### Adding TTLs++When fixing the known TTL issue, use the Upstash Redis `EX` option:++```js+await redis.set(key, data, { ex: 3600 }); // expire after 1 hour+```++## Edge Deployment++The Cloudflare Worker runs at the edge — in a data center close to the user. This means:+- Low first-byte latency for API responses+- Supabase queries go from the Worker (edge) to Supabase (centralized), so DB round-trips are fast but not zero+- Platform API calls (Instagram, YouTube) happen from the Worker — not from the user's browser — eliminating client-side rate limit attribution++## Bundle Size++The React frontend is built with Vite. All page components are lazy-loaded. The main bundle includes only:+- React runtime+- React Router+- Supabase JS client (for auth)+- Shared context providers++Analytics libraries (Recharts) and heavy page components are loaded on demand when the user navigates to the relevant page.++**Rule:** Never import a heavy library in a non-lazy component. If you need Recharts on a page, the page must be lazy-loaded.++## Worker CPU Budget++Cloudflare Workers have a CPU time limit of 50ms per request (on the free tier; up to 30 seconds on paid). Expensive operations to be aware of:+- HMAC computation: negligible+- Multiple sequential Supabase queries: watch for N+1 patterns+- Large JSON serialization: analytics response objects can be large — profile them++If a route feels slow, add Redis caching first before optimizing the underlying query.++## What We Don't Optimize (Yet)++- **Database indexes:** The `accounts` and `scheduled_posts` tables have only a primary key index. If query performance degrades as the table grows, add an index on `user_id`. See ROADMAP.+- **Response compression:** Cloudflare automatically compresses Worker responses with gzip/brotli — no code needed.+- **Image optimization:** Cloudinary handles image resizing and format conversion for Instagram posts. No custom image optimization in the app layer.+- **Frontend rendering performance:** The app is not a high-frequency update scenario. No virtualization, no memoization beyond standard React patterns. If analytics tables get large (1000+ rows), add pagination.diff --git a/docs/philosophy/SECURITY.md b/docs/philosophy/SECURITY.mdnew file mode 100644index 0000000..d995eb0--- /dev/null+++ b/docs/philosophy/SECURITY.md@@ -0,0 +1,101 @@+# Security Model++## Key Hierarchy++| Credential | Where stored | Who reads it | Exposed to client? |+|---|---|---|---|+| Supabase anon key | `VITE_SUPABASE_ANON_KEY` (env var in frontend build) | Frontend (Supabase JS auth) | **Yes — intentionally public** |+| Supabase service role key | Worker secret | Worker only | **Never** |+| Instagram App ID | Worker secret | Worker only | **Never** |+| Instagram App Secret | Worker secret | Worker only | **Never** |+| YouTube API key | Worker secret | Worker only | **Never** |+| Cloudinary credentials | Worker secrets | Worker only | **Never** |+| User's Instagram access token | `accounts.data.accessToken` in DB | Worker only | **Never** |+| User's GitHub PAT | `settings` table in DB | Worker only | **Never** |+| Supabase JWT secret | Supabase (internal) | Supabase JWT verification | **Never** |++## The Service Role Key++The service role key bypasses Supabase Row-Level Security and has full read/write access to the database. It is the most sensitive credential in the system.++**Rules:**+- Only lives in Worker secrets and local `.dev.vars` (gitignored)+- Never referenced in frontend code+- Never returned in any API response+- Never logged+- The `.dev.vars` file must remain in `.gitignore` — verify before every commit that touches the backend++## User Access Token Protection++Instagram access tokens grant posting authority on behalf of users. They must be treated with the same care as passwords.++**Rules:**+- Stored in `accounts.data.accessToken` (jsonb field, not a dedicated column — intentional)+- Never selected and returned to the frontend. The `safeAccount()` function strips them before responses+- When updating an account, the token field must survive the jsonb merge — never replace the whole `data` object with a subset+- When deleting an account, the token becomes inaccessible because the row is deleted++## User Row Isolation++The Worker uses the service role key and is therefore responsible for its own access control.++**The invariant:** Every user-data query must include `.eq('user_id', userId)` where `userId` comes exclusively from the verified Supabase JWT.++**What this prevents:** User A querying user B's accounts, posts, or settings by guessing an account ID.++**What to verify when adding new queries:**+```js+// Correct: userId from JWT, not from request body or params+const userId = c.get('userId');+const { data } = await supabase+ .from('accounts')+ .select('*')+ .eq('user_id', userId) // ← always present+ .eq('id', accountId); // ← narrows to specific account++// Wrong: no user_id filter+const { data } = await supabase.from('accounts').select('*').eq('id', accountId);+```++## OAuth State Verification++The Instagram OAuth flow uses a self-verifying HMAC state token to prevent CSRF:++1. On OAuth start: state = `base64url(userId:timestamp)` + `.` + `HMAC-SHA256(secret, payload)`+2. Stored in Redis with a TTL of 10 minutes+3. On OAuth callback: verify HMAC before accepting the `code` parameter++If the HMAC check fails, the callback returns 400 and discards the code. An attacker cannot forge a valid state without the `INSTAGRAM_APP_SECRET`.++## Input Validation++The backend validates:+- Required fields: `if (!field) return c.json({ error: 'Missing: field' }, 400)`+- Platform enum: only known `platform` values are accepted when creating accounts+- File types: Cloudinary upload accepts only image and video MIME types++The backend does not validate:+- URL formats in user-provided content (the platform API will reject invalid URLs)+- Text length in scheduled posts (the platform API enforces limits)+- Future scheduled times (a post scheduled in the past is harmlessly treated as due)++## What the Frontend Can Trust++The frontend trusts the backend. It does not need to re-validate data received from the API (it came from our own authenticated endpoints). It validates only user input before sending it to the API.++The frontend must never:+- Build Supabase service-role queries+- Hardcode platform credentials+- Store sensitive tokens in localStorage or sessionStorage+- Log JWT tokens or access tokens to the console++## Secrets Rotation++If a credential is compromised:+1. Worker secrets: `wrangler secret put SECRET_NAME` then `wrangler deploy`+2. GitHub Actions secrets: update in repository Settings → Secrets+3. Instagram App Secret: rotate in Meta Developer dashboard, then update Worker secret+4. Supabase service role key: rotate in Supabase project Settings → API+5. User Instagram tokens: user must reconnect their account via the OAuth flow++There is no automated secrets rotation. This is a known gap.diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.mdnew file mode 100644index 0000000..ed1ce69--- /dev/null+++ b/docs/workflows/DEPLOYMENT.md@@ -0,0 +1,125 @@+# Deployment Workflow++## Automatic Deployment (Normal Path)++Push to `main` → GitHub Actions deploys automatically.++| What changed | Workflow that runs | What it deploys |+|---|---|---|+| `backend/**` | `deploy-backend.yml` | Cloudflare Worker |+| `frontend/**` | `deploy-frontend.yml` | Cloudflare Pages |+| Both | Both workflows | Both (in parallel) |+| `docs/`, `scripts/`, `*.md` | Neither | Nothing deployed |++Monitor deployment status at:+`https://github.com/spacesdrive/twiligent/actions`++## Manual Deployment (Local)++### Backend (Cloudflare Worker)++```bash+cd backend+wrangler deploy+```++Requires Cloudflare CLI (`wrangler`) and authenticated with `wrangler login`.++### Frontend (Cloudflare Pages)++```bash+cd frontend+npm ci+npm run build+wrangler pages deploy dist --project-name=twiligent+```++## Setting Worker Secrets++Secrets must be set before the first deploy or when adding new ones:++```bash+wrangler secret put SUPABASE_URL+wrangler secret put SUPABASE_SERVICE_KEY+wrangler secret put SUPABASE_ANON_KEY+wrangler secret put YOUTUBE_API_KEY+wrangler secret put INSTAGRAM_APP_ID+wrangler secret put INSTAGRAM_APP_SECRET+wrangler secret put CLOUDINARY_CLOUD_NAME+wrangler secret put CLOUDINARY_UPLOAD_PRESET+wrangler secret put BACKEND_URL+wrangler secret put FRONTEND_URL+wrangler secret put UPSTASH_REDIS_REST_URL # optional+wrangler secret put UPSTASH_REDIS_REST_TOKEN # optional+```++Each command prompts for the value (no echo — the value is not shown).++## Setting GitHub Actions Secrets++Required for `deploy-frontend.yml` and `publish-scheduled.yml`:++1. GitHub → repository → Settings → Secrets and variables → Actions+2. Click "New repository secret" for each:++**For frontend deploy:**+- `CLOUDFLARE_API_TOKEN`+- `CLOUDFLARE_ACCOUNT_ID`+- `VITE_SUPABASE_URL`+- `VITE_SUPABASE_ANON_KEY`+- `VITE_API_URL`++**For backend deploy:**+- `CLOUDFLARE_API_TOKEN`+- `CLOUDFLARE_ACCOUNT_ID`++**For scheduled publisher only:**+- `SUPABASE_URL`+- `SUPABASE_SERVICE_KEY`++**Windows / PowerShell note:** When setting GitHub secrets via PowerShell, use UTF-8 without BOM encoding to avoid the `ByteString` error. Write to a temp file using `[System.Text.UTF8Encoding]::new($false)` then pipe to `gh secret set`. See `scripts/publish-scheduled.js` for the defensive `.replace(/[^\x20-\x7E]/g, '').trim()` pattern that handles any remaining BOM.++## Deployment Verification++**Backend:**+```bash+curl https://twiligent.ujjwalkrai.workers.dev/api/health+# Expected: {"status":"ok","timestamp":"2025-..."}+```++**Frontend:**+Open `https://twiligent.pages.dev` → verify login page loads → sign in → verify accounts load.++**Scheduled publisher:**+GitHub Actions → "Instagram Scheduled Publisher" → "Run workflow" → check run output.++## Rollback++**Backend:** Deploy a specific previous version:+```bash+# List recent deployments+wrangler deployments list++# Roll back to a specific deployment+wrangler rollback <deployment-id>+```++**Frontend:** Cloudflare Pages → deployments list → "Rollback to this deployment" on a previous build.++## First-Time Setup++For a fresh deployment from this repo:++1. Create Cloudflare account+2. Create Supabase project (get URL + keys)+3. Create Upstash Redis database (optional)+4. Create Cloudinary account + upload preset+5. Create Meta/Facebook Developer app with Instagram Graph API product+6. `wrangler login`+7. Set all Worker secrets (see above)+8. Set all GitHub Actions secrets (see above)+9. `wrangler deploy` (first manual deploy)+10. Verify health endpoint+11. `cd frontend && npm run build && wrangler pages deploy dist --project-name=twiligent`+12. Verify frontend loads+13. Add a YouTube channel via AccountManager to verify the full flowdiff --git a/docs/workflows/FEATURE_DEVELOPMENT.md b/docs/workflows/FEATURE_DEVELOPMENT.mdnew file mode 100644index 0000000..f6efb7b--- /dev/null+++ b/docs/workflows/FEATURE_DEVELOPMENT.md@@ -0,0 +1,164 @@+# Feature Development Workflow++Every feature — large or small — follows this sequence. Steps that don't apply to a specific feature can be skipped, but must be consciously skipped (not forgotten).++---++## Phase 1: Understand++**Step 1 — Read CLAUDE.md**+Confirm you have the project context and know which docs to load.++**Step 2 — Load relevant documentation**+Based on what the feature touches:+- Backend change → read `docs/architecture/backend/`+- Frontend change → read `docs/architecture/frontend/`+- DB change → read `docs/architecture/database/SCHEMA.md`+- New integration → read `docs/guidelines/API_CONVENTIONS.md`, relevant data flow doc++**Step 3 — Read the existing code in the affected area**+Read every file you will modify. Read sibling files to understand the established pattern. Do not start implementing until you understand the code you are about to change.++**Step 4 — Search for existing implementations**+Is there already something that does part of what you need?+- `Grep` for relevant function names, component names, or patterns+- Look for a similar feature in the codebase to use as a template++---++## Phase 2: Research++**Step 5 — Look up official API documentation (Context7)**+For any external API you'll call (Instagram, YouTube, Supabase, Cloudflare), use Context7 to confirm:+- Required parameters+- Response field names and types+- Error codes and their meanings+- Rate limits or quotas++**Step 6 — Research UX patterns (Parallel Search)**+For user-facing features:+- How do established tools handle this interaction?+- What are the accessibility requirements?+- What edge cases do users encounter?++**Step 7 — Research accessibility requirements**+Any new interactive UI must be keyboard-accessible and screen-reader compatible:+- Buttons trigger on Enter/Space+- Modals trap focus+- Dynamic content updates are announced via ARIA live regions+- shadcn components handle most of this automatically++**Step 8 — Plan with Sequential Thinking**+For features touching more than one layer (backend + frontend, DB + backend), use Sequential Thinking to produce an ordered plan before writing any code.++---++## Phase 3: Design++**Step 9 — Design the implementation**+Determine:+- Which files will be created or modified+- What new DB columns or tables are needed+- What new backend routes are needed+- What new frontend pages or components are needed+- What security implications exist++**Step 10 — Identify reuse opportunities**+Before creating new patterns, check:+- Is there a db.js function that almost does what you need? Extend it.+- Is there a service function you can call? Use it.+- Is there a shadcn component that fits? Use it.+- Is there a formatting function in formatters.js? Use it.++---++## Phase 4: Implement++**Step 11 — Implement in this order:**+1. DB schema changes (if any) — see `docs/features/NEW_DATABASE_TABLE.md`+2. Backend: `lib/db.js` additions (new query functions)+3. Backend: `services/` additions (new external API calls)+4. Backend: `routes/` additions (new route handlers)+5. Backend: `server.js` mounting (if new router)+6. Frontend: `services/api.js` additions (new API methods)+7. Frontend: new page/feature component+8. Frontend: `App.jsx` routing (if new page)+9. Frontend: `Sidebar.jsx` navigation (if new page needs nav entry)++**Step 12 — Eliminate duplication**+After implementing, look for logic that duplicates something that already existed. Extract it into the appropriate shared location (`lib/db.js`, `services/`, `utils/formatters.js`, shared components).++---++## Phase 5: Verify++**Step 13 — Build verification**+```bash+# Backend+cd backend && wrangler dev # should start without errors++# Frontend+cd frontend && npm run build # should build without errors+cd frontend && npm run dev # should start without errors+```++**Step 14 — Lint**+```bash+cd frontend && npm run lint+```++**Step 15 — Manual testing — golden path**+Test the main success case end-to-end:+- Backend routes: verify with `curl` or the frontend+- Frontend pages: navigate to the page, perform the action, verify the result++**Step 16 — Manual testing — edge cases**+- Empty state (no accounts, no data)+- Error state (backend unavailable, API error)+- Loading state (spinner shows during async operations)+- Invalid input (missing required fields)+- Unauthorized access (try accessing another user's resource ID)++**Step 17 — Accessibility verification**+- Tab through the new UI — all interactive elements must be reachable+- Activate buttons with Enter key+- Verify focus is visible on all interactive elements+- Open Chrome DevTools → Accessibility tree — verify structure makes sense++**Step 18 — Responsive layout verification**+Test at 375px (mobile), 768px (tablet), 1280px (desktop):+- Content doesn't overflow horizontally+- Tables scroll within their container (not the page)+- Touch targets are large enough on mobile++**Step 19 — Performance check**+- Does the new page load in reasonable time?+- Are API responses cached where appropriate?+- Is there unnecessary re-fetching on every render?++**Step 20 — Console error check**+Open browser DevTools → Console. Verify no errors or warnings during normal usage.++---++## Phase 6: Document and Commit++**Step 21 — Update documentation**+Based on what changed (see `claude.md` Documentation Maintenance Policy):+- New route → `docs/architecture/backend/ROUTES.md`+- New DB column/table → `docs/architecture/database/SCHEMA.md`+- New env var → `docs/architecture/cloudflare/WORKERS.md`+- New page → `docs/architecture/frontend/REACT_ARCHITECTURE.md`+- Architecture decision → `DECISIONS.md`++**Step 22 — Update CHANGELOG.md**+Add an entry under `[Unreleased]` describing what was added, changed, or fixed.++**Step 23 — Update ROADMAP.md**+If the feature was on the roadmap, move it to the completed list. If it opened new follow-up work, add that.++**Step 24 — Commit**+Follow the Git workflow in `docs/workflows/GIT.md`.++**Step 25 — Deploy (if ready)**+Follow `docs/workflows/DEPLOYMENT.md`.diff --git a/docs/workflows/GIT.md b/docs/workflows/GIT.mdnew file mode 100644index 0000000..daf05b7--- /dev/null+++ b/docs/workflows/GIT.md@@ -0,0 +1,204 @@+# Git Workflow++## Repository++- URL: https://github.com/spacesdrive/twiligent+- Author name: spacesdrive+- Author email: [email protected]+- Default branch: main++Commits must use the spacesdrive author identity. The local git config is set to this. Never override it per-commit with a different author.++Do not add "Co-Authored-By" lines referencing AI tools. Commits should show only the project author.++---++## Commit Cadence++Commit after every meaningful, self-contained change. Do not accumulate unrelated changes into one large commit. Do not leave work uncommitted between sessions.++A meaningful change is one that:+- Adds a working feature (even a small one)+- Fixes a bug+- Updates documentation to reflect a real change+- Refactors without changing behavior++Do not commit work-in-progress that breaks the build. Use a feature branch if the work spans multiple sessions.++---++## Commit Message Format++Use Conventional Commits with an optional scope:++```+type(scope): short description in present tense++Optional body explaining WHY, not WHAT. Wrap at 72 characters.+Reference which docs were updated if any.+```++### Types++| Type | When to use |+|---|---|+| `feat` | New feature or capability |+| `fix` | Bug fix |+| `docs` | Documentation only |+| `refactor` | Code restructuring, no behavior change |+| `style` | Formatting or whitespace, no logic change |+| `perf` | Performance improvement |+| `chore` | Maintenance, dependency updates, tooling |+| `release` | Version bump and changelog update |++### Scope (optional)++Use scope to name the area affected:++- `feat(instagram):`+- `fix(scheduler):`+- `docs(routing):`+- `chore(deps):`++### Subject line rules++- Present tense: "add" not "added", "fix" not "fixed"+- No period at the end+- Under 72 characters total including type and scope+- Lowercase after the colon+- No emojis++### Examples++```+feat(reddit): add cookie-based analytics integration++fix(scheduler): strip non-ASCII characters from env vars to prevent ByteString error++docs(architecture): document dual-scheduler mutex pattern in SCHEDULING.md++refactor(instagram): extract token refresh into standalone service function++chore(deps): update @supabase/supabase-js to latest++release: v1.1.0 - Reddit integration+```++---++## What to Commit Together++### Always group these in a single commit:+- A new route + its db.js functions + its api.js method+- A new page + its route in App.jsx + its Sidebar entry+- A bug fix + updated docs if the fix changes documented behavior+- A new feature + CHANGELOG.md update + relevant architecture doc updates++### Never commit:+- `backend/.dev.vars`+- `backend/data/`+- `node_modules/`+- `.env` files with real credential values+- Cloudflare API tokens or Supabase service keys+- Editor or OS metadata files (`.DS_Store`, `Thumbs.db`)++---++## Documentation in Commits++Every feature commit must include documentation updates. A feature is not complete until:+- `CHANGELOG.md` is updated (Unreleased section)+- Relevant architecture docs reflect the change (see `claude.md` Documentation Maintenance Policy)++Include in the commit body which docs were updated:++```+feat(schedule): add bulk CSV post scheduling++Users can now upload a CSV file to schedule multiple posts at once.+Each row in the CSV maps to one scheduled_post record.++Docs updated: ROUTES.md, SCHEDULING.md, CHANGELOG.md.+```++---++## Release Tagging++Tag releases after shipping a meaningful set of changes.++### Version numbering++| Change type | Version bump | Example |+|---|---|---|+| Bug fix | Patch: x.x.N+1 | v1.0.4 -> v1.0.5 |+| New feature | Minor: x.N+1.0 | v1.0.5 -> v1.1.0 |+| Breaking change | Major: N+1.0.0 | v1.1.0 -> v2.0.0 |++### Release process++1. Update `CHANGELOG.md`: move Unreleased section to the new version number with today's date+2. Commit: `release: v1.1.0 - short description of release`+3. Tag: `git tag -a v1.1.0 -m "v1.1.0 - short description"`+4. Push: `git push origin main --tags`++```bash+# Example release+git add CHANGELOG.md+git commit -m "release: v1.1.0 - Reddit analytics integration"+git tag -a v1.1.0 -m "v1.1.0 - Reddit analytics integration"+git push origin main --tags+```++---++## Branch Strategy++All work goes directly to `main` for small changes and fixes. GitHub Actions deploys automatically on push to `main`.++For larger features that span multiple sessions or commits before they are ready to deploy, use a feature branch:++```bash+git checkout -b feat/reddit-integration+# work, commit incrementally+git push origin feat/reddit-integration+# merge to main when ready+git checkout main+git merge feat/reddit-integration+git push origin main+```++Delete the branch after merging:+```bash+git push origin --delete feat/reddit-integration+git branch -d feat/reddit-integration+```++---++## Pre-Commit Checklist++Run before every commit:++1. `cd frontend && npm run build` - frontend must build without errors+2. `cd frontend && npm run lint` - no lint errors+3. `git status` - verify only intended files are staged+4. `git diff --staged` - review the full diff before committing+5. Check no secrets or credentials appear in the diff+6. Verify CHANGELOG.md is updated if the commit adds a feature or fix++---++## Post-Commit++After pushing to `main`, monitor GitHub Actions:++- `backend/` changes trigger `deploy-backend.yml`+- `frontend/` changes trigger `deploy-frontend.yml`+- `scripts/` changes do not trigger automatic deployment++If a deployment workflow fails:+1. Read the failure log at https://github.com/spacesdrive/twiligent/actions+2. Fix the issue locally+3. Create a new commit (never amend a published commit)+4. Push the fixdiff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.mdnew file mode 100644index 0000000..cab5e1a--- /dev/null+++ b/docs/workflows/TESTING.md@@ -0,0 +1,137 @@+# Testing Strategy++## Current State++This project has no automated test suite. Testing is currently manual. This is a known gap — see ROADMAP.md.++The testing workflow documented here describes what should run before shipping any change.++## Pre-Deployment Checklist++### 1. Build Verification++```bash+# Frontend must build without errors+cd frontend && npm run build++# Backend must be valid ESM (wrangler validates on deploy)+cd backend && wrangler deploy --dry-run # if available+```++A broken build is a hard blocker. Do not deploy if build fails.++### 2. Lint++```bash+cd frontend && npm run lint+```++Fix all lint errors. ESLint is configured via `frontend/eslint.config.js`. The rules enforce:+- React hooks rules (no conditional hooks)+- Unused variable detection+- Import/export correctness++### 3. Manual API Verification (Backend)++For any backend change, verify the affected routes directly:++```bash+# Health check (should always work)+curl https://twiligent.ujjwalkrai.workers.dev/api/health++# Authenticated route (replace TOKEN with a real Supabase JWT)+curl -H "Authorization: Bearer TOKEN" https://twiligent.ujjwalkrai.workers.dev/api/accounts+```++For local testing:+```bash+cd backend && wrangler dev+# then curl http://localhost:8787/api/...+```++### 4. Manual Frontend Verification++Open the app in a browser. For each changed area, test:++**Authentication:**+- [ ] Login with valid credentials → lands on Overview+- [ ] Login with invalid credentials → error message shown+- [ ] Sign out → redirects to login++**Accounts:**+- [ ] Add a YouTube channel by URL → appears in sidebar+- [ ] Delete an account → removed from sidebar+- [ ] Connect Instagram via OAuth → OAuth popup, returns to accounts page++**Analytics:**+- [ ] Overview page loads with correct totals+- [ ] Channel analytics page loads for a YouTube account+- [ ] Instagram analytics page loads for an Instagram account+- [ ] Video explorer shows all videos, filtering works++**Publishing (if changed):**+- [ ] Upload to Cloudinary works+- [ ] Container creation succeeds+- [ ] Status polling shows progress for video+- [ ] Publish succeeds → media ID shown++**Scheduling (if changed):**+- [ ] Create a scheduled post → appears in queue+- [ ] Manual trigger processes due posts correctly+- [ ] Failed posts show error in UI++### 5. Error State Testing++- [ ] What happens with no accounts? (empty state)+- [ ] What happens when the backend is unreachable? (error toast)+- [ ] What happens when an Instagram token is expired? (descriptive error)+- [ ] What happens when YouTube API quota is exceeded? (error propagated)++### 6. Console Error Verification++Open browser DevTools → Console. Navigate through all changed pages.+- No JavaScript errors+- No failed network requests (red in Network tab)+- No React warnings about missing keys, prop types, etc.++### 7. Accessibility Verification++For any new UI:+- Tab through all interactive elements — all must be reachable+- Press Enter on buttons — they should activate+- Press Space on buttons and checkboxes — they should activate+- Check for visible focus ring on focused elements+- Use Chrome's built-in Accessibility tab (DevTools → Elements → Accessibility) to verify ARIA structure++### 8. Responsive Layout Verification++Resize the browser to test at:+- 375px (iPhone SE — smallest common mobile)+- 768px (tablet)+- 1280px (laptop)+- 1920px (desktop)++Verify:+- No horizontal scrolling on the page body+- Data tables scroll within their container+- All content is readable+- Navigation is usable++### 9. Scheduled Publisher Verification++After any change to `scripts/publish-scheduled.js` or `publish-scheduled.yml`:++1. GitHub Actions → "Instagram Scheduled Publisher" → "Run workflow"+2. Watch the run output+3. Verify: "No posts due for publishing" (if no scheduled posts) or successful publish++If you have a test post scheduled in the near future, use `GET /api/process-scheduled` to trigger the Worker cron manually.++## Future Test Infrastructure++When automated tests are added, this document will be updated. Priority order for adding tests:++1. **Unit tests for `computeVideoAnalytics()` and `computeInstagramAnalytics()`** — pure functions with complex logic, easy to test+2. **Unit tests for `lib/db.js` functions** — using a Supabase test project+3. **Integration tests for backend routes** — using `miniflare` or similar Workers test runner+4. **End-to-end tests** — Playwright for the full login → view analytics → publish flow