Skip to content

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 the platform v2 research and implementation plan

spacesdrive7f353578c71e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6c1f445..ab3cd19 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [Unreleased]
+### Documentation
+
+- Research and an implementation plan for platform v2: removing Reddit, an MCP server for Claude clients, YouTube publishing and security auditing in the workflow, in `docs/platform-v2/` (#143)
+
## [1.4.0] - 2026-11-05
### Added
diff --git a/CLAUDE.md b/CLAUDE.md
index 210898d..51b12da 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -160,6 +160,11 @@ docs/
ARCHITECTURE.md Architectural principles and constraints
SECURITY.md Security model, key handling, isolation
PERFORMANCE.md Caching strategy, edge optimization
+ platform-v2/ The v2 work (#142): Reddit removed, MCP server, YouTube publishing, security auditing
+ RESEARCH.md Findings and verified facts; full reports in research/
+ ARCHITECTURE.md Target design, decisions and trade-offs, bottlenecks
+ IMPLEMENTATION_PLAN.md Phases, dependency map, tools, testing strategy, failure scenarios, owner actions, status
+ DATABASE_MIGRATION.md Reddit cleanup and the new tables, with the backup and review steps
site/content/docs/ Public user and self-hosting docs (MDX) served at twiligent.ujjwal.fyi/docs
DECISIONS.md Architectural decision log
diff --git a/docs/platform-v2/ARCHITECTURE.md b/docs/platform-v2/ARCHITECTURE.md
new file mode 100644
index 0000000..a4a4422
--- /dev/null
+++ b/docs/platform-v2/ARCHITECTURE.md
@@ -0,0 +1,96 @@
+# Platform v2 architecture
+
+The architecture for the platform v2 work (#142): Reddit removed, an MCP server for Claude clients, YouTube publishing, and security auditing built into the workflow. It builds on the system described in `docs/architecture/OVERVIEW.md`; when a part ships, its permanent description moves into the matching architecture doc and this page keeps the decisions and trade-offs. The research behind each decision is in `RESEARCH.md`.
+
+---
+
+## Current system (before v2)
+
+- **Worker:** Hono on Cloudflare Workers. Middleware (CORS, request id and deadline, security headers, clients, IP rate limit), then `requireAuth` (Supabase JWT checked with `auth.getUser`), per-user and per-route rate limits, route tables, controllers, services (`createXService(deps)`) and repositories. One error contract (`ApiFailure`).
+- **Cron:** every minute (comment reply dispatch), every five minutes (scheduled Instagram posts on the quarter hour, queue checks in between), daily (token refresh, retention).
+- **Second scheduler:** a GitHub Actions job (`scripts/publish-scheduled.ts`) publishes due Instagram posts too; both claim posts atomically so each publishes once.
+- **Data:** Supabase Postgres. Every table has RLS on and browser access revoked; only the Worker's service key reads and writes, always scoped by the verified user id. Optional Upstash Redis caches analytics and counts rate limits.
+- **Media:** the browser uploads to Cloudinary with an unsigned preset; the Worker only sees the resulting URL.
+- **Platforms:** YouTube (analytics with an API key, no OAuth), Instagram (OAuth, analytics, publishing, comment-to-DM automation), Reddit (public JSON plus an optional session cookie).
+
+---
+
+## Target system
+
+```
+Claude (claude.ai, Desktop, mobile) Claude Code, scripts
+ | OAuth 2.1 (Supabase Auth) | personal access token
+ v v
+ POST /mcp -- requireMcpAuth -- MCP rate limits -- JSON-RPC dispatch -- tool registry
+ |
+ Browser app -- /api/* -- requireAuth -- rate limits -- controllers -------+
+ v
+ services (unchanged rules, one implementation)
+ v
+ repositories -> Postgres, Redis
+Cron (Worker) and GitHub Actions -- claim jobs -- YouTube upload steps -- Cloudinary byte ranges -> Google
+```
+
+### 1. Reddit removed
+
+Every Reddit route, service, type, cache key, rate limit rule, page and doc goes. The tracked content feature keeps YouTube videos only, so the Reddit-only fields (`manualViews`, `imageUrl`, the per-item account used for a Reddit cookie) go with it. Removing public routes is a breaking change, so this ships as v2.0.0. The database part is in `DATABASE_MIGRATION.md`.
+
+### 2. MCP server
+
+- **Endpoint:** `POST /mcp` on the existing Worker, outside `/api` so the URL people paste into Claude is short. `GET` and `DELETE` answer 405. Responses are JSON only. No sessions are created.
+- **Protocol:** dual-era. A request with `method: initialize` gets the 2025-11-25 handshake answer; a request carrying per-request `_meta` is served statelessly as 2026-07-28; `server/discover`, `tools/list`, `tools/call` and `ping` work in both. The JSON-RPC envelope, error builders and header checks are pure functions in `backend/lib/mcp/`, tested with Node.
+- **Layers:** a route table (`routes/mcpRoutes.ts`) maps the endpoint; a controller (`controllers/mcpController.ts`) parses the envelope and dispatches; each tool lives in `backend/mcp/tools/` as a definition (name, title, description, JSON Schema for input and output, annotations, required permission) plus a handler that validates input with the same `backend/validators/` functions the REST API uses and calls one service method. Tools never query the database or call a platform directly.
+- **Identity:** `requireMcpAuth` accepts two credentials and sets the same `userId` the rest of the pipeline trusts:
+ - an OAuth access token from Supabase Auth's OAuth 2.1 server. The Worker checks it with `auth.getUser` (as `requireAuth` does), then requires a `client_id` claim, so an ordinary app session token cannot be replayed at `/mcp`;
+ - a personal access token (`twl_` prefix plus 32 random bytes). Only its SHA-256 hash is stored, with the user id, a label, a permission (`read` or `write`), a last-used time and an optional expiry.
+- **Discovery:** `GET /.well-known/oauth-protected-resource` (and the `/mcp` suffixed form) names the Supabase authorization server; an unauthenticated call to `/mcp` answers 401 with `WWW-Authenticate: Bearer resource_metadata="..."`, which starts sign-in in claude.ai.
+- **Consent page:** Supabase's OAuth server sends the person to the app's `/oauth/consent` page, which shows the client's name and asks whether to allow read only or read and write. The choice is stored per user and client in `mcp_client_grants`.
+- **Permissions:** every tool declares `read` or `write`. Write tools need a `write` token or grant. Irreversible or public actions (publish, delete, disconnect) need a second call carrying a confirmation token: the first call returns a preview and an HMAC-signed token bound to the user, the tool and a hash of the arguments, valid for five minutes.
+- **Limits:** a per-user MCP rule in `RATE_LIMIT_RULES`, the existing quota and publish rules applied per tool, a 30 second deadline per call (Claude's own limit is 240 s), results capped and paginated.
+- **Audit:** every write tool call is recorded in `audit_events` with the client (`mcp:<client_id>` or `mcp:token:<id>`), the tool, and the outcome, never the arguments' secret fields.
+
+### 3. YouTube publishing
+
+- **Connection:** `GET /api/auth/youtube/url` (protected) returns Google's consent URL with a signed state; Google redirects to `GET /api/auth/youtube/callback` (public), which hands the code to the app to complete as the signed-in person (see section 4). The code is exchanged, `channels.list?mine=true` reads the channel, and the connection is stored in `youtube_connections`: the account it belongs to, the channel id, granted scopes, status (`active`, `needs_reconnect`), the encrypted refresh token and the current access token with its expiry. A connected channel that is not yet an analytics account is added as one.
+- **Encryption:** refresh and access tokens are encrypted with AES-GCM (a random 12-byte IV per value) under a key from the new Worker secret `TOKEN_ENCRYPTION_KEY`. They never appear in a response, a log or an MCP result.
+- **Jobs:** one row per video in `youtube_uploads`, holding a snapshot of the metadata (title, description, tags, category, privacy, publish time, made for kids, synthetic media, notify subscribers, playlist, thumbnail), the Cloudinary source (URL, bytes, content type), the resumable session URI, confirmed bytes, the video id, the state, attempts, next attempt time and a lease.
+- **States:** `queued`, `uploading`, `processing`, `finalizing`, `done`; side states `waiting_quota`, `needs_reconnect`, `needs_review` (outcome unknown), `failed` (needs the owner), `cancelled`.
+- **Runner:** a claim function (`FOR UPDATE SKIP LOCKED`, 10 minute lease) used by the Worker's five minute cron and by the GitHub Actions scheduler. Each run takes one job, refreshes the token if needed, asks Google for the real offset, then streams 8 MiB byte ranges from Cloudinary through `FixedLengthStream` into the session until its time or subrequest budget runs out. Every write checks the lease owner.
+- **Exactly once:** a session is created only when the job has none, and saved before any bytes are sent; a lost final response is recovered by the status query; a session that disappears after the last chunk was sent sends the job to `needs_review`.
+- **Retries:** transient errors back off exponentially with jitter (honouring `Retry-After`) and fail after 8 attempts; `quotaExceeded` waits until midnight Pacific; `invalid_grant` marks the connection `needs_reconnect` and parks its jobs without spending an attempt.
+- **After upload:** the five minute run polls `videos.list` (up to 50 ids, 1 unit) for processing, then sets the thumbnail and playlist as separate steps, so a failed thumbnail never re-uploads the video.
+- **Shorts:** decided from the source file: height at least the width and at most 180 seconds. The composer shows the result; there is no separate upload path.
+- **Quota:** `youtube_quota_usage` holds units per Pacific day and bucket (`uploads` 100 calls, `default` 10,000 units), reserved atomically before each call.
+- **Cleanup:** with the optional `CLOUDINARY_API_KEY` and `CLOUDINARY_API_SECRET`, the source video is deleted once YouTube has it; without them, the asset is listed for manual cleanup.
+
+### 4. Security built in
+
+- **Skills:** the Cloudflare security-audit skill and the relevant Trail of Bits plugins are declared in `.claude/settings.json`; `CLAUDE.md` makes a security pass part of every substantial change, scaled to its size.
+- **OAuth completion bound to the signed-in person:** today the Instagram callback connects the account named by the signed state alone, so a consent link made by one person and opened by another connects the second person's Instagram to the first person's Twiligent account. In v2 the public callback only checks the state's signature and forwards `code` and `state` to the app; the app, signed in, posts them to an authenticated `complete` route, which connects the account only when the state's user id equals the caller's. A cookie was rejected because self-hosted apps and Workers often sit on different sites, where browsers drop it. The redirect URIs registered with Meta and Google stay the same.
+- **Media ownership:** the Cloudinary account is shared by everyone on an instance, so every media action checks that the asset belongs to a row of the signed-in user before reading or deleting it.
+
+---
+
+## Decisions and trade-offs
+
+| Decision | Chosen | Instead of | Why | Cost |
+|---|---|---|---|---|
+| MCP protocol code | Hand-written in Hono | `@modelcontextprotocol/server`, Cloudflare `agents` | No runtime dependency; six methods; validators already exist | We track spec changes ourselves; a conformance test and the MCP Inspector cover it |
+| MCP sign-in | Supabase OAuth 2.1 server plus personal access tokens | `workers-oauth-provider` with KV; a hand-written authorization server | One identity system, no dependency, no KV; the owner chose it | Supabase's server is beta; the owner enables it and the hook in the dashboard |
+| MCP transport | Stateless JSON over `POST /mcp` | SSE streams, sessions, Durable Objects | Fits a Worker; legal in both spec eras | No server-initiated messages (not needed for tools) |
+| Upload timing | Upload soon after saving, YouTube publishes at `publishAt` | Upload at publish time like Instagram | Errors surface early; no minute-exact deadline for our runners | A scheduled video cannot be "unlisted at a time"; the UI says so |
+| Upload engine | Postgres job row with a lease, moved by cron | Queues, Temporal, BullMQ | No new infrastructure on free tiers; survives restarts by design | Throughput is bounded by run frequency; GitHub Actions adds capacity |
+| Video storage | Cloudinary (existing) | R2, direct browser to YouTube | Already configured; byte ranges work | 100 MB per video on Cloudinary's free plan |
+| Token storage | AES-GCM in Postgres under a Worker secret | Plain text in `accounts.data` (current Instagram tokens) | A database leak no longer leaks tokens | One more secret to set; key rotation is documented, not automatic |
+| Reddit data | Deleted after a backup and the owner's review | Hidden in the UI | The user asked for full removal; the rows hold cookies and passwords | A restore needs the backup file |
+
+---
+
+## Bottlenecks and limits
+
+- **Upload throughput on Workers Free:** 10 ms CPU and 50 subrequests a run. Each chunk is two subrequests (Cloudinary range, Google PUT), so one run moves at most about 20 chunks (160 MB) before database calls; the CPU limit is unmeasured and may be the real ceiling. GitHub Actions, the paid plan, or larger cron frequency raise it.
+- **YouTube quota:** 100 uploads a day per Google Cloud project, shared by every channel on the instance; 10,000 units for everything else. The ledger stops calls before Google refuses them.
+- **Cloudinary free plan:** 100 MB per video and 25 credits a month; long videos need a paid plan or a later direct upload path.
+- **MCP result size:** Claude Code warns above 10k tokens and stops at 25k; list tools paginate and summarize.
+- **Supabase OAuth beta gaps:** no resource indicators and exact loopback ports; personal access tokens cover Claude Code meanwhile.
+- **Rate limits without Redis:** counted per Worker isolate, looser than a global count (existing, documented in `RATE_LIMITING.md`).
diff --git a/docs/platform-v2/DATABASE_MIGRATION.md b/docs/platform-v2/DATABASE_MIGRATION.md
new file mode 100644
index 0000000..46754fc
--- /dev/null
+++ b/docs/platform-v2/DATABASE_MIGRATION.md
@@ -0,0 +1,90 @@
+# Platform v2 database changes
+
+The schema and data changes for the platform v2 work (#142): the Reddit cleanup (#145) and the new tables for the MCP server (#146) and YouTube publishing (#147). Every change follows `docs/features/NEW_DATABASE_TABLE.md` and the migration rules in `CLAUDE.md`: one entity per file, a rollback with the same name, a one-sentence opening comment, made with `npm run db:new`, and `supabase/schemas/` regenerated after `npm run db:push`.
+
+Production is changed only after the owner has reviewed the exact SQL and the row counts (decided on 2026-11-05).
+
+---
+
+## 1. Reddit cleanup (#145)
+
+### What the database holds for Reddit
+
+Inspected from `supabase/schemas/` and the migrations on 2026-11-05.
+
+| Object | Reddit part | Shared with |
+|---|---|---|
+| `accounts` rows with `platform = 'reddit'` | The Reddit profile, plus the session cookie and encrypted password and TOTP secret fields in `data` | Nothing: tracked posts point at them through `account_id`, which is set to null on delete |
+| `accounts_platform_check` | Allows `'reddit'` | YouTube and Instagram |
+| `accounts_identity_key` (unique index) | A `when 'reddit' then data ->> 'username'` branch | YouTube and Instagram branches |
+| `tracked_posts` rows with `content_type = 'reddit'` | Tracked Reddit posts, with typed-in views and uploaded images | Nothing |
+| `tracked_posts.content_type` default | `'reddit'` | Every insert that omits it |
+| `tracked_posts_content_type_check` | Allows `'reddit'` | YouTube |
+| `tracked_posts_account_check` | Only Reddit items may name an account | Nothing |
+| `tracked_posts.account_id` and `tracked_posts_account_fkey` | Only read for a Reddit item's session cookie | Nothing |
+
+Not touched:
+
+- `audit_events` rows that mention Reddit stay. They are the history of what happened and hold no secrets.
+- `scheduled_posts` and every automation table: they only reference Instagram accounts.
+- No database function, trigger, view, policy or storage bucket mentions Reddit (`merge_tracked_post_data` updates `data` only). Twiligent uses no Supabase Storage buckets.
+- Redis keys `reddit:<user>:<account>` expire on their own within 6 hours; the cleanup does not need Redis.
+- Images uploaded for Reddit tracked posts live in Cloudinary. Their URLs are listed in the backup so the owner can delete them in the Cloudinary console; the Worker has no Cloudinary API secret to do it.
+
+### Order of work
+
+1. The code release that removes Reddit (v2.0.0, #144) ships first. It stops writing and reading Reddit rows, and always sends `content_type`, so nothing depends on the old default or checks.
+2. Count the rows (read only) with `npm run db:status` linked and a `select platform, count(*)` query in the Supabase SQL editor. The counts go into #145 without any personal data.
+3. Back up the affected rows from the Supabase SQL editor as CSV: `select * from public.accounts where platform = 'reddit'` and `select * from public.tracked_posts where content_type = 'reddit' or account_id is not null`. The file holds session cookies and encrypted passwords, so it stays on the owner's machine, outside the repository, and is deleted once the owner no longer needs a way back.
+4. The owner reviews the migrations below and the `npm run db:check` dry run.
+5. `npm run db:push`, then `npm run db:schema`, then the checks again (counts are 0, the migrations test passes, Overview and tracked content still load).
+
+### Migrations
+
+Each runs in its own transaction (the Supabase CLI wraps every file), so a file either applies fully or not at all. Deleting rows happens in the same file as the check that forbids them, because the new check cannot be added while those rows exist.
+
+| File (verb first) | What it does | Rollback |
+|---|---|---|
+| `alter_tracked_posts_youtube_only` | Deletes tracked posts with `content_type = 'reddit'`, drops `tracked_posts_account_check`, replaces `tracked_posts_content_type_check` with `content_type = 'youtube'`, sets the default to `'youtube'` | Restores both checks as they were and the `'reddit'` default; the rows come back from the backup |
+| `drop_tracked_posts_account_id` | Drops `tracked_posts_account_fkey` and the `account_id` column | Adds the nullable column and the foreign key back (`on delete set null (account_id)`) |
+| `alter_accounts_without_reddit` | Deletes accounts with `platform = 'reddit'` and replaces `accounts_platform_check` with `('youtube', 'instagram')` | Restores the three-platform check; the rows come back from the backup |
+| `replace_accounts_identity_index` | Drops `accounts_identity_key` and creates it again without the Reddit branch | Creates the index with the Reddit branch again |
+
+A rollback restores the schema; Reddit rows are restored by loading the backup CSV into the tables with the Supabase table editor or `\copy`, after the rollback has run.
+
+---
+
+## 2. MCP server tables (#146)
+
+| Table | Purpose | Key columns |
+|---|---|---|
+| `mcp_access_tokens` | Personal access tokens for Claude Code and scripts | `id`, `user_id`, `label`, `token_hash` (SHA-256, unique), `permission` (`read`, `write`), `last_used_at`, `expires_at`, `revoked_at`, `created_at`, `updated_at` |
+| `mcp_client_grants` | What each OAuth client may do for a person, set on the consent page | `user_id`, `client_id`, `client_name`, `permission`, `created_at`, `updated_at`; unique `(user_id, client_id)` |
+
+Each table is at least four migrations (the table with its checks, its access revoked from the browser roles, its `updated_at` trigger, each index). The raw token is shown once and never stored.
+
+---
+
+## 3. YouTube publishing tables (#147)
+
+| Table | Purpose | Key columns |
+|---|---|---|
+| `youtube_connections` | One OAuth connection per channel | `id`, `user_id`, `account_id` (the analytics account), `channel_id`, `scopes`, `status`, `refresh_token_enc`, `access_token_enc`, `access_token_expires_at`, `token_lease_until`; unique `(user_id, channel_id)` |
+| `youtube_uploads` | One upload job per video | metadata snapshot, Cloudinary source (`source_url`, `source_bytes`, `content_type`, `is_short`), `session_uri`, `bytes_confirmed`, `final_chunk_sent`, `video_id`, `state`, `attempts`, `next_attempt_at`, `lease_owner`, `lease_until`, `last_error`, `client_request_id` (unique per user, for idempotent creates) |
+| `youtube_quota_usage` | Units used per Pacific day and bucket | `day`, `bucket`, `units`; primary key `(day, bucket)` |
+
+Functions (one per file, closed to the browser roles): `claim_youtube_upload` (lease with `for update skip locked`), `reserve_youtube_quota` (atomic reservation that refuses past the limit). Indexes: due jobs by `state, next_attempt_at`; a user's uploads by `user_id, created_at`.
+
+---
+
+## 4. Media library table (#146, #147)
+
+The Cloudinary account is shared by everyone on an instance, so Twiligent needs its own record of who uploaded what before it can list, label or delete media for one person.
+
+| Table | Purpose | Key columns |
+|---|---|---|
+| `media_assets` | One uploaded image or video | `id`, `user_id`, `public_id`, `resource_type`, `url`, `bytes`, `width`, `height`, `duration_seconds`, `format`, `label`, `tags`, `deleted_at`, `created_at`, `updated_at`; unique `(user_id, public_id)` |
+
+Uploads from the composer and the MCP import tool create a row; a delete removes the Cloudinary asset first (when the API secret is set) and the row after, so a failed remote delete never hides an asset that still exists.
+
+These sections are filled in with the final file names when each part is built.
diff --git a/docs/platform-v2/IMPLEMENTATION_PLAN.md b/docs/platform-v2/IMPLEMENTATION_PLAN.md
new file mode 100644
index 0000000..61392c1
--- /dev/null
+++ b/docs/platform-v2/IMPLEMENTATION_PLAN.md
@@ -0,0 +1,175 @@
+# Platform v2 implementation plan
+
+The plan for #142, written after the research in `RESEARCH.md` and before any code changed. The design is in `ARCHITECTURE.md`, the schema work in `DATABASE_MIGRATION.md`. Each phase is its own pull request, versioned by the rules in `CLAUDE.md`; the status column is kept up to date as phases finish.
+
+---
+
+## Decisions made by the owner (2026-11-05)
+
+| Question | Decision |
+|---|---|
+| How Claude clients sign in to the MCP server | Supabase Auth's OAuth 2.1 server for claude.ai, Desktop and mobile, plus personal access tokens for Claude Code and scripts |
+| When the Reddit database cleanup reaches production | Only after the owner reviews the exact SQL, the dry run and the row counts |
+| The security skills | Declared as plugins in `.claude/settings.json` (referenced, not copied) and jq installed so the Semgrep skill runs |
+
+---
+
+## Phases
+
+| # | Phase | Issue | Depends on | Release | Status |
+|---|---|---|---|---|---|
+| 0 | Research and plan (this folder) | #143 | | none (docs) | In review |
+| 1 | Remove Reddit from the code | #144 | 0 | v2.0.0 (routes removed) | Planned |
+| 2 | Remove Reddit from the database | #145 | 1 deployed, owner review | none (data only) | Planned |
+| 3 | Security skills, the CLAUDE.md rule, baseline audit and fixes of existing findings | #148 | 0 | patch for any user-visible fix | Planned |
+| 4 | MCP server core: endpoint, protocol, personal access tokens, read tools | #146 | 1, 3 | minor | Planned |
+| 5 | MCP write tools: scheduling, media import, tracked videos, settings, confirmations | #146 | 4 | minor | Planned |
+| 6 | MCP OAuth through Supabase: discovery, consent page, client grants | #146 | 4, owner enables the OAuth server | minor | Planned |
+| 7 | YouTube connection: Google OAuth, encrypted tokens, channel info, disconnect | #147 | 3 | minor | Planned |
+| 8 | YouTube upload pipeline: jobs, claim and lease, resumable chunks, quota, retries, processing, thumbnail, playlist | #147 | 7 | minor | Planned |
+| 9 | YouTube composer, queue, history and media library in the dashboard | #147 | 8 | minor | Planned |
+| 10 | MCP tools for YouTube and media | #146, #147 | 5, 8 | minor | Planned |
+| 11 | Final security audit of everything, fixes, report | #148 | all | patch | Planned |
+
+The owner's suggested order put security last; it moved to phase 3 because the new rule makes a security pass part of every phase, and the MCP and YouTube code should be written against the fixed baseline. MCP core comes before YouTube as suggested; its YouTube tools wait for the pipeline.
+
+### Dependency map
+
+```
+0 research
+ +-> 1 remove Reddit (code) -> 2 remove Reddit (database, owner review)
+ +-> 3 security baseline
+ +-> 4 MCP core -> 5 MCP write tools ----+
+ | -> 6 MCP OAuth +-> 10 MCP YouTube tools -> 11 final audit
+ +-> 7 YouTube connect -> 8 pipeline ----+
+ +-> 9 YouTube UI
+```
+
+---
+
+## Phase details
+
+### 1. Remove Reddit from the code (#144)
+
+- **Remove:** `routes/redditRoutes.ts`, `controllers/redditController.ts`, `services/redditAnalyticsService.ts`, `services/reddit/`, `shared/types/reddit.ts`, the Reddit cache methods, the Reddit account route and validator, the Reddit branches in `accountService`, `accountFactory`, `overviewService`, `trackedContentService` and `trackedContentRules`, `safeAccount`'s Reddit secret fields and `hasCookie`, the Reddit rate limit matcher, and every Reddit test and fixture.
+- **Frontend:** `features/analytics/reddit/`, the Reddit routes, navigation and breadcrumbs, the Reddit account form and choices, Reddit parts of Overview tabs, tracked content (category section, manual views, image upload, account picker), the command palette entries and platform icons.
+- **Site and docs:** Reddit on the home page, platform section, mockups, FAQ and docs pages; a 301 in `site/public/_redirects` for every removed docs page; every doc in the maintenance table that names Reddit; `README.md`, `ROADMAP.md` goals.
+- **Kept:** `CHANGELOG.md` and `DECISIONS.md` history; a new ADR records the removal.
+- **Check:** `rg -i reddit` finds only the changelog, the decision log, the redirects and this folder; every check passes; the removed routes answer 404.
+
+### 2. Remove Reddit from the database (#145)
+
+As in `DATABASE_MIGRATION.md` section 1: count, back up, owner review of the SQL and dry run, push, regenerate the schema tree, verify.
+
+### 3. Security skills, rule and baseline (#148)
+
+- `.claude/settings.json`: the `trailofbits` marketplace and an inline marketplace for the Cloudflare skill pinned to a commit; enable `security-audit`, `differential-review`, `insecure-defaults`, `sharp-edges`, `static-analysis`, `supply-chain-risk-auditor`, `variant-analysis` and `audit-context-building`. No plugin that installs hooks.
+- `CLAUDE.md`: the security engineering rule (what to run for a small change, a substantial change and a pull request), plus `docs/workflows/SECURITY_REVIEW.md` with the commands.
+- Install jq; Semgrep is present.
+- Run the baseline: the Cloudflare audit over the Worker, frontend, site, migrations and workflows; Semgrep; the supply-chain audit; `npm audit`. Each confirmed finding gets a fix and a regression test; known ones so far: the OAuth state not bound to the signed-in person (Instagram connect), and 20 dependency advisories in dev tooling.
+- Findings are written up in `SECURITY_AUDIT.md`; details of anything exploitable go into a private GitHub security advisory until fixed.
+
+### 4 to 6. MCP server (#146)
+
+Tools (each calls one existing service method; `read` tools need no confirmation; `write` tools need a write token or grant; tools marked confirm need the two-step token):
+
+| Tool | Kind | Calls |
+|---|---|---|
+| `get_overview` | read | `overview.get` |
+| `list_accounts` | read | `accounts.list` (safe fields only) |
+| `get_youtube_analytics`, `get_instagram_analytics` | read | the analytics services, summarized and paginated |
+| `compare_accounts` | read | analytics services, the same metrics side by side |
+| `list_tracked_videos` | read | `trackedContent.list` |
+| `list_scheduled_posts`, `get_scheduled_post` | read | `scheduledPosts` |
+| `get_instagram_publishing_limit` | read | `publishing.limit` |
+| `get_settings` | read | `settings` (no secrets) |
+| `schedule_instagram_post` | write | `scheduledPosts.create` (idempotency key) |
+| `update_scheduled_post` | write | `scheduledPosts.update` |
+| `cancel_scheduled_post` | write, confirm | `scheduledPosts.delete` |
+| `import_media_from_url` | write | Cloudinary upload by URL (Cloudinary fetches it, not the Worker), then a `media_assets` row |
+| `list_media`, `update_media` | read, write | `media_assets` for the caller only |
+| `delete_media` | write, confirm | the media service, ownership checked |
+| `add_tracked_video`, `remove_tracked_video` | write; remove confirms | `trackedContent` |
+| `refresh_account` | write | `accounts.refresh` (quota rule applies) |
+| `update_settings` | write | `settings.saveGithub` |
+| `list_youtube_channels` | read | `youtube_connections` (no tokens) |
+| `create_youtube_upload` | write, confirm when public now | the upload service (idempotency key) |
+| `get_youtube_upload`, `list_youtube_uploads` | read | the upload service |
+| `update_youtube_upload`, `retry_youtube_upload` | write | the upload service |
+| `cancel_youtube_upload` | write, confirm | the upload service |
+
+Not exposed on purpose: connecting or removing accounts (they need a browser consent screen or are destructive beyond undo), changing passwords, creating tokens, and anything that returns a secret.
+
+Settings gains a "Claude" section: the server URL to paste, a token list (create, copy once, revoke, last used), and the OAuth clients granted access (revoke).
+
+### 7 to 9. YouTube publishing (#147)
+
+- New Worker secrets: `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `TOKEN_ENCRYPTION_KEY`; optional `CLOUDINARY_API_KEY`, `CLOUDINARY_API_SECRET` for cleanup and media deletion.
+- Shared rules with no runtime imports in `backend/lib/youtubeUpload.ts` (chunk math, error classification, backoff, Short detection, metadata limits), so the Worker and `scripts/publish-scheduled.ts` run the same logic.
+- Dashboard: "Connect YouTube" on the Accounts page with channel info, scopes, status and disconnect; a YouTube tab in Publish with media picker, metadata editor (title counter to 100, description to 5000 bytes, tags to 500 characters, category, privacy, made for kids, synthetic media, notify subscribers, playlist, thumbnail), publish now or schedule, a Short badge from the file's shape and length, and remaining uploads today; a queue with per-job progress and state, retry, cancel and review actions; upload history with links to the videos.
+
+---
+
+## Testing strategy
+
+| Layer | What | How |
+|---|---|---|
+| Pure rules | JSON-RPC parsing, error codes, header checks, confirmation tokens, chunk math, backoff, error classification, Short detection, metadata limits, token encryption round trip | `node:test` unit tests in `backend/tests/lib/` |
+| Services | Every MCP tool's validation and permission, upload state transitions (resume, lost final response, session gone, quota, `invalid_grant`), token refresh with lease | Service tests with the smallest typed fakes |
+| Routes | `/mcp` 401 with `WWW-Authenticate`, 405 on GET, `initialize` and modern requests, cross-user access refused, write refused for a read token; OAuth callback and complete routes | Route tests through `createApp()` with fake clients |
+| Database | One entity per file, rollbacks, schema tree in step | `backend/tests/database/migrations.test.ts` |
+| Frontend | Composer validation, queue state labels, token list | `frontend/tests/` |
+| Protocol conformance | A real MCP client lists and calls tools | MCP Inspector against `wrangler dev`; Claude Code with a token |
+| Live | Real upload of a video and a Short; interrupted upload resumes | Needs the owner's Google client and a test channel; recorded in `YOUTUBE_INTEGRATION.md` |
+| Load | Many due jobs and parallel MCP calls | A script that creates jobs and fires concurrent calls at `wrangler dev`; checks no job is claimed twice and limits answer 429 |
+| Security | Phase 3 tooling on every phase's diff; full audit in phase 11 | Semgrep, the Cloudflare skill, `differential-review`, `npm audit` |
+
+Every phase ends with `npm run typecheck`, `npm run lint`, `npm test` and `npm run build` passing, and the UI checklist in `docs/guidelines/UI_UX.md` for anything people see.
+
+---
+
+## Failure scenarios designed for
+
+| Scenario | Handling |
+|---|---|
+| Two cron runs and GitHub Actions reach the same upload | `claim_youtube_upload` skips locked rows; every write checks the lease owner |
+| A run dies mid-upload | The lease expires; the next run asks Google for the offset and resumes |
+| The last chunk's response is lost | The status query returns the finished video and its id |
+| The upload session disappears after the last chunk was sent | `needs_review`; the owner checks the channel; never a blind second upload |
+| Refresh token revoked or expired | The connection becomes `needs_reconnect`; its jobs wait without spending attempts; the dashboard asks to reconnect |
+| Quota used up | `waiting_quota` until midnight Pacific; the composer shows uploads left today |
+| Cloudinary or Google unreachable | Backoff with jitter, then `failed` after 8 attempts, with the reason |
+| An MCP client sends a stolen app session token | Refused: OAuth tokens must carry `client_id` |
+| An MCP client asks for another person's post id | Not found: every service call is scoped by the verified user id |
+| A prompt inside a comment or caption tells Claude to delete things | Returned as data only; deleting needs a write grant and a confirmation token bound to the exact arguments |
+| A media import URL points at an internal address | Cloudinary fetches the URL, not the Worker; the Worker also refuses non-https and private addresses |
+
+---
+
+## What the owner does
+
+| When | Action |
+|---|---|
+| Phase 2 | Review the migrations, dry run and counts; keep the backup file safe |
+| Phase 6 | In Supabase: enable the OAuth 2.1 server, allow dynamic client registration, set the authorization path to `/oauth/consent` |
+| Phase 7 | In Google Cloud: enable YouTube Data API v3, set up the consent screen in production, create a web OAuth client with the callback URL; set the Worker secrets |
+| Phase 8 | Optional: set the Cloudinary API key and secret for automatic cleanup |
+| Phase 9 | Upload a test video and a test Short to a channel; try an interrupted upload |
+| Any phase | Approve merges and production deploys as usual |
+
+---
+
+## Acceptance criteria and how each is verified
+
+| Criterion | Verified by |
+|---|---|
+| Reddit fully removed, no broken references | `rg -i reddit`, type check, build, removed routes answer 404 |
+| Supabase cleaned safely | Counts before and after, backup kept, migrations test, Overview and tracked content load |
+| MCP connects, authenticates and enforces authorization | Route tests, MCP Inspector, Claude Code with a token, claude.ai once the owner enables OAuth |
+| Media upload and management | Service tests; a real import into the owner's Cloudinary |
+| YouTube OAuth, video and Short uploads, recovery | Unit and service tests for every transition; live uploads by the owner (cannot be done without the owner's Google client) |
+| Jobs persist across restarts, concurrency is safe | State lives in Postgres; claim tests; the load script |
+| Security skills in the workflow, scans run, findings fixed | `.claude/settings.json`, `CLAUDE.md` rule, `SECURITY_AUDIT.md` with commands and results |
+| All tests pass, docs complete | CI on every pull request; the documentation maintenance table |
+
+Anything that could not be verified is listed as such in the final report and in the matching document, never reported as working.
diff --git a/docs/platform-v2/RESEARCH.md b/docs/platform-v2/RESEARCH.md
new file mode 100644
index 0000000..1136a1d
--- /dev/null
+++ b/docs/platform-v2/RESEARCH.md
@@ -0,0 +1,81 @@
+# Platform v2 research
+
+Research for issue #143, done on 2026-11-05 before any code changed. It covers the four new areas of the platform v2 work (#142): the MCP server, YouTube publishing, Postiz as a reference, and the security skills. Each area has a full report in `research/`, with every claim marked as a fact (with its source), a third-party report or an inference. This page keeps the conclusions and the facts the design depends on.
+
+| Report | Covers |
+|---|---|
+| [research/mcp.md](research/mcp.md) | The five MCP articles, the MCP specification (2026-07-28 and 2025-11-25), what Claude clients require, auth options, SDK or hand-written |
+| [research/youtube.md](research/youtube.md) | Google OAuth, `videos.insert`, resumable uploads, quotas, Shorts, thumbnails, playlists, errors, Workers and Cloudinary limits, the recommended pipeline |
+| [research/postiz.md](research/postiz.md) | Postiz's architecture from its source: providers, scheduling, Temporal workers, the YouTube provider, schema, what to adopt, adapt or avoid |
+| [research/security-skills.md](research/security-skills.md) | The Cloudflare security-audit skill and the Trail of Bits skills: licences, structure, install method, which skills fit this stack |
+
+---
+
+## Facts the design depends on
+
+Each was checked against the primary source on 2026-11-05. The three marked "re-checked" contradict older guides, so they were confirmed a second time.
+
+| Fact | Source |
+|---|---|
+| The current MCP revision is 2026-07-28 and is stateless: no `initialize` handshake, no `Mcp-Session-Id`, and servers must implement `server/discover` (re-checked) | modelcontextprotocol.io/specification/2026-07-28/changelog |
+| A server may serve legacy (2025-11-25, `initialize`) and modern clients on the same endpoint | modelcontextprotocol.io/specification/2026-07-28/basic/versioning |
+| claude.ai, Desktop and mobile connectors sign in with OAuth; their callback is `https://claude.ai/api/mcp/auth_callback`; static bearer headers there are an organization-wide beta and cannot tell users apart | claude.com/docs/connectors/building/authentication |
+| Claude Code accepts a remote server with `--header "Authorization: Bearer ..."` and caps tool output at 25k tokens | code.claude.com/docs/en/mcp |
+| Supabase Auth has an OAuth 2.1 server (beta, every plan) with dynamic client registration; the app hosts the consent page; tokens carry `client_id` and `aud: authenticated` | supabase.com/docs/guides/auth/oauth-server |
+| Videos uploaded by unverified Google Cloud projects are no longer locked to private; the 2020 rule was reversed on 2 November 2026 (re-checked) | developers.google.com/youtube/data/revision_history |
+| `videos.insert` has its own quota bucket: 100 calls a day at 1 unit each; every other method shares 10,000 units a day; quotas reset at midnight Pacific (re-checked) | developers.google.com/youtube/data/determine_quota_cost |
+| There is no Shorts endpoint: a square or vertical video up to 3 minutes is a Short | support.google.com/youtube/answer/15424877 |
+| `status.publishAt` works only with `privacyStatus: private`, so YouTube itself publishes a scheduled video | developers.google.com/youtube/v3/docs/videos |
+| A resumable upload sends chunks in multiples of 256 KiB; an empty PUT with `Content-Range: bytes */TOTAL` returns the real offset, or the finished video if the last response was lost | developers.google.com/youtube/v3/guides/using_resumable_upload_protocol |
+| OAuth clients in Testing status get refresh tokens that expire after 7 days | developers.google.com/identity/protocols/oauth2 |
+| Workers Free: 10 ms CPU and 50 subrequests per invocation; cron runs get 15 minutes of wall time; `FixedLengthStream` streams a body of known length without buffering | developers.cloudflare.com/workers/platform/limits |
+| Cloudinary delivery URLs answer `Range` requests with 206; the free plan accepts videos up to 100 MB | Measured with a test request; cloudinary.com/pricing |
+| Postiz is AGPL-3.0: it can be studied, not copied | github.com/gitroomhq/postiz-app LICENSE |
+| The Cloudflare skill is MIT, the Trail of Bits skills are CC-BY-SA-4.0; installing them as plugins puts no obligation on this repository, copying them in would | Both repositories' LICENSE files |
+
+---
+
+## Conclusions
+
+### MCP server
+
+- **Transport:** one Streamable HTTP endpoint, `POST /mcp`, on the existing Worker. JSON responses only, no sessions, `GET` and `DELETE` answer 405. It answers both the legacy `initialize` handshake (what claude.ai speaks today) and modern stateless requests.
+- **Protocol code:** written by hand in Hono. A tools-only, sessionless server needs about six methods; the official SDK would add `zod` and several megabytes to a Worker whose rule is no extra runtime dependencies.
+- **Sign-in:** Supabase Auth's OAuth 2.1 server for claude.ai, Desktop and mobile (the owner chose this on 2026-11-05), and personal access tokens made in Settings for Claude Code and scripts. The Worker stays a resource server: it never issues OAuth tokens itself.
+- **Tool design:** narrow tools named for the task, reads separate from writes, annotations on every tool, results under about 10k tokens with pagination, idempotency keys on create tools, and a two-step confirmation for anything irreversible or public, because clients cannot be relied on to ask the person.
+- **Untrusted content:** comment text, captions and video titles come from other people. Tools return them as data fields, never as instructions, and mark themselves `openWorldHint`.
+
+### YouTube publishing
+
+- **Connection:** Google OAuth with `youtube.upload` and `youtube.readonly` (plus `youtube.force-ssl` only for playlists), `access_type=offline` and `prompt=consent`. Refresh tokens are encrypted at rest and never leave the Worker.
+- **Upload early, let YouTube publish:** a scheduled video uploads soon after it is saved, as private with `publishAt`, so processing errors show hours before the publish time and the time-critical step is YouTube's.
+- **Bytes:** the browser uploads to Cloudinary as Instagram publishing already does; a background job streams 8 MiB byte ranges from Cloudinary into the resumable session, a few chunks per run, with the session URI and offset saved in Postgres.
+- **Exactly one video:** at most one upload session per job, saved before any bytes are sent; Google's status query is the source of truth for the offset; an outcome that cannot be known goes to review, never a blind retry.
+- **Quota:** a ledger per Pacific day and bucket, reserved before each call.
+- **Risk to measure:** whether 10 ms of CPU per run is enough to pipe a chunk on the Workers Free plan. The GitHub Actions scheduler, which has no such limit, runs the same claim and loop as the fallback.
+
+### Postiz
+
+- Adopt: the resumable upload state machine with a status query before every resume; separate "rejected", "never started" and "outcome unknown" results; save the video id when a later step such as the thumbnail fails; a provider interface with a static registry; never overwrite a stored refresh token with an empty one.
+- Adapt: Temporal's durable workflows become a Postgres job row with a lease, moved forward by cron runs.
+- Avoid: Temporal, BullMQ, Elasticsearch, plain-text tokens, fixed-IV encryption, soft-deleted media that is never removed, and heavy SDKs such as `googleapis`.
+
+### Security skills
+
+- Reference both repositories as Claude Code plugins in `.claude/settings.json`; do not copy their files (the owner chose this on 2026-11-05).
+- Full audit: the Cloudflare `security-audit` skill in full mode, plus Semgrep through `static-analysis`, `supply-chain-risk-auditor`, `insecure-defaults` and `sharp-edges`.
+- Small change: the Cloudflare skill in guidance mode on the changed paths, Semgrep on the changed files, `insecure-defaults` on the touched area.
+- Pull request: `differential-review` in a worktree (it runs `git checkout`), Semgrep, and the built-in `/security-review`.
+- Vulnerability details for this public repository go into private security advisories, not public issues.
+
+---
+
+## Open questions
+
+These were not settled by the sources and are tracked in the implementation plan:
+
+- How long a YouTube resumable session stays valid (Drive and Cloud Storage document one week).
+- Whether an unfinished upload session counts against the 100 uploads a day.
+- The Worker CPU time for one 8 MiB chunk on the Free plan; measured after the first deploy.
+- Whether claude.ai sends an `Origin` header to remote servers, and whether it supports elicitation.
+- Supabase's OAuth server ignores the `resource` parameter and fixes loopback ports exactly (issues #2610, #2703 in `supabase/auth`); personal access tokens cover Claude Code until that is fixed.
diff --git a/docs/platform-v2/research/mcp.md b/docs/platform-v2/research/mcp.md
new file mode 100644
index 0000000..24880e8
--- /dev/null
+++ b/docs/platform-v2/research/mcp.md
@@ -0,0 +1,456 @@
+# MCP server for Twiligent: research findings
+
+Research date: 2026-11-05. Scope: research only, no repository changes.
+
+Labels used below:
+
+- **[Fact]** verified in the source named next to it.
+- **[Report]** a third-party report (GitHub issue, blog) that I could confirm exists but not reproduce.
+- **[Inference]** my own reasoning; treat as a proposal, not a fact.
+
+---
+
+## 0. The short version
+
+1. **The MCP spec changed shape in 2026.** The current revision is **2026-07-28** and it is stateless: no `initialize` handshake, no `Mcp-Session-Id`, no `ping`, no GET stream. Every request carries its version and capabilities in `_meta`, and servers MUST implement `server/discover`. [Fact, https://modelcontextprotocol.io/specification/versioning and https://modelcontextprotocol.io/specification/2026-07-28/changelog]
+2. **Claude clients still speak the older, handshake-based revisions.** Anthropic's connector docs say Claude follows the 2025-03-26, 2025-06-18 and 2025-11-25 authorization specs. Claude Code has a "v2 runtime" that adds 2026-07-28, and a switch to force legacy. So a Twiligent server must be **dual-era**: answer `initialize` (legacy) and per-request `_meta` (modern) on the same endpoint. [Fact, https://claude.com/docs/connectors/building and https://code.claude.com/docs/en/mcp]
+3. **Transport:** one Streamable HTTP endpoint (`POST /mcp`), JSON responses only (no SSE needed for a tools-only server), no sessions, GET and DELETE answer 405. This is legal in both eras and fits a stateless Worker. [Fact for legality; Inference for the choice]
+4. **Auth for claude.ai needs OAuth.** Static bearer headers exist on claude.ai but are a beta for "a limited set of organizations" and the value is one credential shared by the whole organization, not per user. Authless is supported but useless for per-user data. [Fact, https://claude.com/docs/connectors/building/authentication]
+5. **Recommended auth:** Supabase Auth's OAuth 2.1 server (beta, all plans) as the authorization server, the Worker as a pure resource server that verifies Supabase JWTs locally against JWKS, plus a Custom Access Token Hook that stamps the MCP URL as `aud` on OAuth tokens. Add hashed personal access tokens (PATs) as a second path for Claude Code and scripts. Keep Cloudflare's `workers-oauth-provider` as the fallback if Supabase's gaps block you (it is a dependency and needs KV). Do not hand-write an authorization server. Details and caveats in section 4.
+6. **Protocol code:** hand-write the JSON-RPC layer in Hono (about 6 methods, small) instead of adding `@modelcontextprotocol/server` (pulls `zod` 4 and `@modelcontextprotocol/core`) to the Worker. Use the official SDK client only as a dev dependency in tests to prove conformance, if the owner approves that. Details in section 5.
+
+---
+
+## 1. The five articles
+
+### 1.1 Alloy Automation, "Building Production-Ready MCP Servers: What our engineering team learned" (2025-11-17)
+
+URL: https://runalloy.com/blog/building-production-ready-mcp-servers/
+
+Read status: the URL with a trailing slash returned only site navigation through two fetchers. The same article without the trailing slash (https://runalloy.com/blog/building-production-ready-mcp-servers) returned the full text, which I read in full.
+
+Concrete recommendations:
+
+- Layered architecture: gateway/router authenticates and applies restrictions, a service layer holds business logic, an infrastructure layer holds the protocol and external APIs ("domain / application / infrastructure").
+- Per-tenant isolation: each tenant (their "server ID") gets its own auth tokens, restriction rules, custom instructions, rate limits and audit trail.
+- Stateless scaling: each request carries the tenant id, "no session state needed".
+- Token security: store tokens hashed, give them an expiry, generate them securely (`accessTokenHash`, `tokenExpiresAt`).
+- Security model "Default Deny": nothing is allowed without an explicit permission; validate at several layers (tool, connector, action, user).
+- Permissions evaluated in three stages: filter what the model can discover, filter actions within allowed connectors, then enforce again at execution time and throw a typed error if blocked.
+- Separate read from delete: enterprises refused to give AI access to delete functions; "think about permissions, not restrictions", start from nothing and grant.
+- Write tool parameter descriptions as instructions the model follows ("ALWAYS use get_connector_resources first", "NEVER guess"). Note: Anthropic's directory review rejects descriptions that "tell Claude how to behave" beyond the tool's function (section 3.4), so keep such guidance factual.
+- "Smart hints": return contextual guidance in results and errors (suggest lookup or search actions instead of listing 50,000 records; error analysis that names the correct id or next tool).
+- Large responses: above 50 items, return a sample plus options (search, filter, paginate, summary). Below that, hard caps: max 200 array items, max 10 KB strings, max 2 MB total, and truncate "with clear messages about what was cut".
+- "Measure context usage, it's your most precious resource."
+- Start simple and add complexity only when proven necessary; explicit configuration over inference.
+- Rate limiting per tenant and audit trails for compliance are stated requirements.
+
+### 1.2 Arif Dewi, "Building Your First Production-Ready MCP Server: A Weekend Project That Actually Shipped" (Medium, 2025-10-02)
+
+URL: https://medium.com/@arifdewi/building-your-first-production-ready-mcp-server-a-weekend-project-that-actually-shipped-131305c69d54
+
+Read status: WebFetch got HTTP 403. The Parallel fetcher returned the full article text, which I read in full.
+
+Concrete recommendations (note: the article is about a local stdio server in Docker, so most points do not transfer to a remote Worker):
+
+- Start with the simplest transport that works; the author chose stdio for a Docker-packaged server. [Not applicable to a remote server for claude.ai, which needs Streamable HTTP.]
+- Security even for internal tools: non-root container user, minimal base image (Alpine), SBOMs and provenance, multi-arch images, automated security patches.
+- CI that builds images, publishes, signs SBOMs and runs tests.
+- One-command install and drop-in config; "clear error messages"; developer experience drives adoption.
+- Use the official SDK so you do not hand-write protocol negotiation, registration, error handling and transports.
+- Document relentlessly: README with examples, troubleshooting and use cases.
+- Keep tools few and clear (the example has two tools: resolve an id, then fetch by id).
+
+### 1.3 dev.to (guang_diyuzhi), "MCP in Production: Is the Model Context Protocol Ready in 2026?"
+
+URL: https://dev.to/guang_diyuzhi_74b0fec2c09/mcp-in-production-is-the-model-context-protocol-ready-in-2026-5205
+
+Read status: fetched with WebFetch, which returns a model-extracted digest, not verbatim text. The digest covered the whole article.
+
+Concrete recommendations and claims:
+
+- Verdict: ready for single-user and small-team agent workflows, "not yet ready" for large multi-tenant systems with strict security and observability needs.
+- Maturity table: tool calling solid, resources solid, prompts early, Streamable HTTP maturing, structured logging inconsistent, OAuth for remote servers "still rough".
+- Return clean structured errors; silent failures cascade because the agent assumes a tool ran and produces confident wrong output.
+- Budget debugging time; distributed agent stacks are harder to debug than monoliths.
+- Check the ecosystem for a maintained server before building; vet the servers you depend on.
+- Build a server once and reuse it across clients.
+
+### 1.4 The New Stack (Janakiram MSV), "15 Best Practices for Building MCP Servers in Production" (2025-09-15)
+
+URL: https://thenewstack.io/15-best-practices-for-building-mcp-servers-in-production/
+
+Read status: WebFetch returned only page chrome. The Parallel fetcher returned the full page (83 KB); I extracted and read the article body in full.
+
+The 15 practices:
+
+1. Treat each server as a bounded context: one domain, cohesive uniquely named tools, JSON-Schema inputs and outputs, enums where possible, documented failure modes.
+2. Prefer stateless, idempotent tools: agents retry and parallelize; accept client-generated request ids; deterministic results; pagination tokens and cursors for lists.
+3. Choose the transport and implement cancellation and timeouts. (It says SSE was replaced by Streamable HTTP in 2025-06-18; in fact Streamable HTTP arrived in 2025-03-26 per the spec's own note.)
+4. Use elicitation to fill missing parameters or confirm risky actions, never to harvest sensitive data; validate responses; gate with capability checks and fall back when unsupported.
+5. Security first: follow the spec's security best practices; "don't use session IDs for auth"; non-predictable session ids; verify all requests; minimize data exposure; implement authorization server metadata discovery and dynamic client registration; never echo secrets in results or elicitation. (Its claim that OAuth 2.1 is "mandatory" for HTTP transports is wrong: the spec says authorization is OPTIONAL.)
+6. Structured content for the model plus content blocks for people (`outputSchema`, `structuredContent`); actionable errors with machine-readable codes.
+7. Instrument like a microservice: structured logs with correlation ids, tool name, invocation id, latency, success or failure; surface rate limits so agents can budget calls.
+8. Semantic versioning for the server and for tools on breaking changes; advertise capabilities.
+9. Keep prompts, tools and resources decoupled; resources are read-only with URIs and pagination.
+10. Stream incremental results for long operations; return handles or URIs instead of megabytes inline.
+11. Test against real hosts with fault injection (slow downstreams, partial failures, malformed input); use the Inspector.
+12. Package like a microservice; README with tool catalog, schemas, examples, security notes.
+13. Capabilities differ by host; feature-flag and degrade gracefully.
+14. Behind the MCP layer keep a clean API: least privilege, clear lifecycles, idempotent mutations. "MCP is just the adapter."
+15. For anything that changes state or spends money, require confirmation (elicitation or a dry-run mode) and return a diff of intended changes before execution; machine-readable change summaries.
+
+### 1.5 dev.to (Mads Hansen), "MCP in production: what nobody tells you before you start"
+
+URL: https://dev.to/mads_hansen_27b33ebfee4c9/mcp-in-production-what-nobody-tells-you-before-you-start-21m
+
+Read status: fetched with WebFetch (digest, not verbatim). The article is short and database-focused.
+
+Concrete recommendations:
+
+- Schema quality matters more with AI in the loop: vague names and undocumented relationships make the model assume wrong things.
+- Plan capacity for about 10x the expected query volume; plan connection pooling and rate limits accordingly.
+- "Your MCP server should enforce read-only access by default"; least privilege; tighten over-provisioned permissions.
+- Use MCP for exploratory, ad-hoc questions; answer recurring questions with precomputed metrics or dashboards.
+- (A reader comment promoting a commercial gateway is not part of the article.)
+
+### 1.6 What the five agree on (Inference)
+
+Read-only by default and explicit grants for writes; per-user isolation and rate limits; idempotent writes; small, paginated, truncated-with-notice responses; actionable structured errors; correlation-id logging and audit trails; confirmation before state changes; test with real clients. Two of the five (Alloy, The New Stack) are substantive; the other three are light.
+
+---
+
+## 2. The MCP specification, verified
+
+**Latest revision: 2026-07-28** ("The **current** protocol version is 2026-07-28"). Revisions 2025-11-25 and earlier are called "legacy" (handshake-based). [Fact, https://modelcontextprotocol.io/specification/versioning]
+
+### 2.1 Streamable HTTP in 2026-07-28 (modern)
+
+Source: https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http
+
+- Single endpoint: "The server **MUST** provide a single HTTP endpoint path ... that supports POST." [Fact]
+- Every client message is its own POST; client MUST send `Accept` listing both `application/json` and `text/event-stream`. [Fact]
+- A notification gets `202 Accepted` with no body (or an HTTP error if refused). [Fact]
+- A request gets either `Content-Type: application/json` (one JSON object) or `text/event-stream` (an SSE stream scoped to that request); "The client **MUST** support both." So a server may always answer with JSON. [Fact]
+- No GET stream, no sessions, no resumability: a server that supports only this revision SHOULD answer GET or DELETE with `405`, ignore any `Mcp-Session-Id` ("do not mint or echo session IDs"), and ignore `Last-Event-ID`. [Fact]
+- Long-lived change notifications now use a `subscriptions/listen` POST whose response is a long-lived SSE stream. A tools-only server with a fixed tool list does not need it. [Fact for the mechanism; Inference that Twiligent can skip it]
+- Cancellation on HTTP: closing the response stream is the cancel signal. [Fact]
+- Request metadata headers: every POST MUST carry `MCP-Protocol-Version`, and it MUST match `_meta["io.modelcontextprotocol/protocolVersion"]`, else `400` with JSON-RPC error `-32020` (HeaderMismatch). `Mcp-Method` is required on all requests and `Mcp-Name` on `tools/call` (Base64 sentinel `=?base64?...?=` for unsafe values); servers MUST validate they match the body. Unsupported version: `400` with `UnsupportedProtocolVersionError` (`-32022`) listing `supported`. Unknown method: `404` with `-32601`. [Fact]
+- A request with no `MCP-Protocol-Version` header MAY be treated as `2025-03-26` by a server that supports old clients. [Fact]
+- Origin: servers MUST validate `Origin` on all incoming connections; if present and invalid, respond `403`. Servers SHOULD implement authentication for all connections. [Fact]
+- SSE responses SHOULD include `X-Accel-Buffering: no`. [Fact]
+
+### 2.2 Streamable HTTP in 2025-11-25 (legacy, what Claude clients use today)
+
+Source: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports and .../basic/lifecycle
+
+- Single endpoint supporting POST and GET. GET: server MUST return `text/event-stream` "or else return HTTP 405 Method Not Allowed". So a server without a GET stream is compliant. [Fact]
+- POST body is one request, notification or response; notifications and responses get `202`; requests get JSON or SSE. [Fact]
+- **Sessions are optional:** "A server ... **MAY** assign a session ID at initialization time" via the `MCP-Session-Id` header. If assigned, clients MUST echo it; a terminated session gets `404`; clients SHOULD DELETE to end it; servers MAY answer DELETE with `405`. A server that never assigns one runs stateless. [Fact]
+- `MCP-Protocol-Version` header on all requests after initialize; missing header SHOULD be assumed `2025-03-26`; invalid or unsupported MUST get `400`. [Fact]
+- Origin validation: same MUST and 403 as above. [Fact]
+- Lifecycle: client sends `initialize` (protocolVersion, capabilities, clientInfo); server MUST reply with its capabilities and serverInfo (optional `instructions`); if it supports the requested version it MUST echo it, otherwise reply with another version it supports. Client then sends `notifications/initialized`. [Fact]
+- Ping (legacy): either side may send `ping`; the receiver must answer promptly with an empty result. (Removed in 2026-07-28.) [Fact for removal, changelog item 5; the ping rule is in the 2025-11-25 utilities page linked from lifecycle]
+
+### 2.3 Minimal method set for a dual-era tools-only server
+
+| Method | Era | What to do |
+|---|---|---|
+| `initialize` | legacy | Reply with `protocolVersion` (echo if supported, else latest legacy you support), `capabilities: { tools: { listChanged: false } }`, `serverInfo`, optional `instructions`. No session id. |
+| `notifications/initialized` | legacy | `202`, no body. |
+| `ping` | legacy | `{}` result. |
+| `server/discover` | modern (MUST) | `supportedVersions`, `capabilities`, `_meta.serverInfo`, `instructions`, `ttlMs`, `cacheScope`, `resultType: "complete"`. |
+| `tools/list` | both | Tools in deterministic order; modern results add `resultType`, `ttlMs`, `cacheScope`. Use `cacheScope: "private"` if the list depends on the user's scopes. |
+| `tools/call` | both | Run the tool; return `content` (+ `structuredContent`), `isError`. Modern adds `resultType`. |
+| any other request | both | JSON-RPC `-32601` (modern: HTTP 404). |
+| GET / DELETE on `/mcp` | both | `405`. |
+
+[Fact for each requirement, from the pages above; Inference for the exact dual-era table.]
+
+The spec explicitly allows a dual-era server: "A server that wishes to support both legacy clients ... and modern clients ... **MAY** implement both behaviors." It picks the era per request: a request with modern `_meta` is served statelessly; an `initialize` request selects legacy semantics. A modern-only server SHOULD name its supported versions in the error it returns to `initialize`. [Fact, https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning]
+
+### 2.4 Tool definitions, annotations, structured output, errors
+
+Source: https://modelcontextprotocol.io/specification/2026-07-28/server/tools ; annotation defaults from the schema as quoted in https://modelcontextprotocol.io/specification/2025-06-18/schema and the MCP blog post https://blog.modelcontextprotocol.io/posts/2026-03-16-tool-annotations
+
+- Tool fields: `name`, `title`, `description`, `icons`, `inputSchema` (JSON Schema 2020-12 by default, MUST be an object schema; no-arg tools should use `{ "type": "object", "additionalProperties": false }`), optional `outputSchema`, optional `annotations`. [Fact]
+- Names SHOULD be 1 to 128 chars, case-sensitive, only `A-Z a-z 0-9 _ - .`, unique per server. [Fact]
+- `tools/list` MUST NOT vary per connection but MAY vary by the authorization on the request (for example by granted scopes). SHOULD be deterministic in order. [Fact]
+- **Annotations (all hints, untrusted unless the server is trusted):**
+ - `readOnlyHint` default false: tool does not modify its environment.
+ - `destructiveHint` default true: may perform destructive updates (false means additive only); meaningful only when not read-only.
+ - `idempotentHint` default false: repeated calls with the same args have no extra effect; meaningful only when not read-only.
+ - `openWorldHint` default true: interacts with an open world of external entities.
+ - `title`: display name. [Fact]
+- **Structured output:** `structuredContent` is any JSON value; if `outputSchema` is given, servers MUST conform and clients SHOULD validate. "For backwards compatibility, a tool that returns structured content SHOULD also return the serialized JSON in a TextContent block." [Fact]
+- **Errors, two kinds:** protocol errors (unknown tool, malformed request, server errors) are JSON-RPC errors such as `-32602`; tool execution errors (API failures, input validation, business logic) are results with `isError: true` and actionable text so the model can self-correct. [Fact]
+- **Stateful tools:** with no sessions, use explicit server-minted handles passed as tool arguments; validate the caller against the handle on every call; opaque ids; state the lifetime in the description; return an `isError` result for expired handles. [Fact, same page, non-normative]
+- **Server MUSTs:** "Validate all tool inputs; Implement proper access controls; Rate limit tool invocations; Sanitize tool outputs." [Fact]
+- Elicitation in 2026-07-28 is done via **Multi Round-Trip Requests**: the server returns `resultType: "input_required"` with `inputRequests` and an opaque `requestState`; the client retries with `inputResponses`. `requestState` is attacker-controlled: if it affects authorization or business logic the server MUST integrity-protect it (HMAC or AEAD), SHOULD bind it to the principal, a short TTL and the original request, and MUST enforce single use server-side when needed. Servers MUST NOT send an elicitation the client did not declare. [Fact, https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/mrtr]
+
+### 2.5 Authorization (2026-07-28)
+
+Sources: https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization , .../authorization/authorization-server-discovery , .../authorization/client-registration , .../authorization/security-considerations
+
+- Authorization is OPTIONAL; HTTP implementations that do it SHOULD conform. Based on OAuth 2.1 (draft 13), RFC 6750, 8414, 7591, 8707, 9728, 9207, CIMD draft, OIDC Discovery. [Fact]
+- **Roles:** the MCP server is an OAuth 2.1 resource server; the authorization server can be a separate entity. [Fact]
+- **Protected Resource Metadata (RFC 9728):** MCP servers MUST implement it; the document MUST include `authorization_servers` with at least one entry. Servers MUST offer discovery either by a `WWW-Authenticate: Bearer resource_metadata="..."` header on 401, or at a well-known URI (`/.well-known/oauth-protected-resource/<mcp path>` or `/.well-known/oauth-protected-resource`). Clients MUST support both. [Fact]
+- **Scopes:** servers SHOULD put `scope="..."` in the `WWW-Authenticate` challenge; `scopes_supported` should be the minimal set; insufficient scope at runtime is `403` with `error="insufficient_scope"`, `scope`, `resource_metadata`. Servers SHOULD NOT advertise `offline_access`. [Fact]
+- **AS metadata discovery:** RFC 8414 or OIDC Discovery; for an issuer with a path (`https://x/tenant1`) clients try `/.well-known/oauth-authorization-server/tenant1`, then `/.well-known/openid-configuration/tenant1`, then `/tenant1/.well-known/openid-configuration`. Clients MUST reject metadata whose `issuer` differs. [Fact]
+- **Client registration priority:** pre-registered, then Client ID Metadata Documents (CIMD, when the AS advertises `client_id_metadata_document_supported`), then Dynamic Client Registration (DCR). **DCR is deprecated in 2026-07-28** and kept for backward compatibility. Clients MUST send an `application_type` in DCR. [Fact]
+- **PKCE:** clients MUST use PKCE with S256 and MUST refuse to proceed if `code_challenge_methods_supported` is absent from AS metadata. [Fact]
+- **Resource indicators (RFC 8707):** clients MUST send `resource` (the canonical MCP server URI, no fragment, preferably no trailing slash) in both authorization and token requests. [Fact]
+- **Tokens:** sent only in the `Authorization: Bearer` header, on every request, never in the query string. Servers MUST validate tokens per OAuth 2.1 section 5.2, MUST validate that the token was issued for them as audience, MUST answer invalid or expired tokens with 401, and "MUST NOT accept or transit any other tokens". [Fact]
+- **No token passthrough:** if the MCP server calls upstream APIs it uses a separate upstream token; it MUST NOT pass through the client's token. [Fact]
+- **Issuer check (RFC 9207):** ASs SHOULD return `iss` in authorization responses; clients MUST validate it. [Fact]
+- **Token theft:** ASs SHOULD issue short-lived access tokens; for public clients they MUST rotate refresh tokens. All AS endpoints MUST be HTTPS; redirect URIs MUST be localhost or HTTPS. [Fact]
+- **Confused deputy:** applies to MCP *proxy* servers that use a static client id at a third-party AS while letting MCP clients register dynamically; they MUST obtain per-client consent before forwarding. [Fact] For Twiligent: the Worker does call Instagram, YouTube and Cloudinary with stored per-user platform tokens, but it does not run an OAuth proxy flow for MCP clients through Meta or Google, so the classic confused deputy does not arise as long as MCP sign-in only authenticates the Twiligent user and never triggers a platform OAuth flow. [Inference]
+
+### 2.6 Security best practices page
+
+Source: https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices
+
+- Confused deputy (proxy servers): per-client consent registry checked before third-party authorization; consent page MUST name the client, show the scopes and the redirect URI, have CSRF protection, and block framing (`frame-ancestors` or `X-Frame-Options: DENY`); consent cookies use `__Host-`, `Secure`, `HttpOnly`, `SameSite=Lax`, signed, bound to `client_id`; exact `redirect_uri` match; `state` generated securely, stored only after consent, single use, short expiry (for example 10 minutes). [Fact]
+- Token passthrough: "MCP servers **MUST NOT** accept any tokens that were not explicitly issued for the MCP server." [Fact]
+- SSRF (mainly clients, and authorization servers that fetch CIMD documents): HTTPS only, block private ranges, validate redirects, egress proxies. [Fact]
+- State handle hijacking (replaces "session hijacking" in 2026-07-28): MUST verify every request; MUST NOT treat a handle as authentication; SHOULD use random handles bound server-side to the authenticated user (`<user_id>:<handle>`). [Fact]
+- Local server compromise, OAuth URL validation, stdio proxy issues: client-side and local concerns, not relevant to a remote Worker. [Fact for content; Inference for relevance]
+- Scope minimization: minimal initial scopes, step-up via `WWW-Authenticate` challenges, no wildcard scopes, log elevation events. [Fact]
+
+---
+
+## 3. What Claude clients require today
+
+### 3.1 claude.ai, Claude Desktop, mobile, Cowork (remote custom connectors)
+
+Sources: https://claude.com/docs/connectors/building , https://claude.com/docs/connectors/building/authentication , https://claude.com/docs/connectors/custom/add-unlisted , https://support.claude.com/en/articles/11175166-get-started-with-custom-connectors-using-remote-mcp
+
+- Available on Free (one custom connector), Pro, Max, Ultra, Team, Enterprise. [Fact]
+- Connections come from Anthropic's cloud even in Desktop and Cowork, so the server must be reachable from the public internet; egress range `160.79.104.0/21`. [Fact]
+- Transport: Streamable HTTP (legacy HTTP+SSE still supported, being deprecated). [Fact]
+- Supported OAuth authorization spec versions: 2025-03-26, 2025-06-18, 2025-11-25. 2026-07-28 is not listed for the hosted apps. [Fact] (Whether claude.ai's MCP client speaks the 2026-07-28 wire protocol is not stated; I could not verify it.)
+- Not supported: resource subscriptions, sampling, "advanced or draft capabilities". Elicitation support on claude.ai is **not documented** on these pages. [Fact for the list; unverified for elicitation]
+- Limits: max tool result about 150,000 characters; tool call timeout 240 seconds. [Fact]
+- **Auth types:** `oauth_dcr` and `oauth_cimd` supported by default; `oauth_anthropic_creds` for directory listings; `custom_connection` by request; `static_headers` (API key or bearer in a request header) in **beta for a limited set of organizations**, entered once by an Owner and shared by everyone in that organization ("don't use it to identify which user is calling"); `none` (authless) supported. [Fact]
+- In the add-connector dialog: Authentication "Sign in now", "Sign in when needed", or "No sign-in"; OAuth client "Use Claude's published identity (Recommended)" (CIMD), "Register automatically" (DCR), or "Use your own OAuth client" (client id, optional secret). Auth settings cannot be edited later; remove and re-add. [Fact]
+- **Callback URL for hosted apps:** `https://claude.ai/api/mcp/auth_callback` (register exactly this). [Fact]
+- Claude's OAuth client specifics: a `401` is required to start sign-in (a `WWW-Authenticate` on `200` is ignored); the PRM `resource` must equal the URL the user typed, including the path; only the first `authorization_servers` entry is used; CIMD is chosen only when AS metadata has both `client_id_metadata_document_supported: true` and `none` in `token_endpoint_auth_methods_supported`, otherwise Claude falls back to DCR; PKCE S256 on every request; requests `scope` from the 401 challenge, else `scopes_supported`, plus `offline_access` if the AS lists it; 10 second limit on discovery, registration and token endpoints, 30 seconds for refresh; refreshes on 401 and up to five minutes before expiry; expects `invalid_grant` for dead refresh tokens; token endpoint must accept `application/x-www-form-urlencoded`; no `client_credentials` grant. [Fact]
+- If no `resource_metadata` pointer is sent, Claude probes `/.well-known/oauth-protected-resource/<mcp path>` then `/.well-known/oauth-protected-resource` on the MCP origin. [Fact]
+
+### 3.2 Claude Code
+
+Sources: https://code.claude.com/docs/en/mcp , https://claude.com/docs/connectors/building/authentication
+
+- Add a remote server: `claude mcp add --transport http <name> <url>`; with a static token: `claude mcp add --transport http secure-api https://api.example.com/mcp --header "Authorization: Bearer your-token"`. Scopes: local (default, `~/.claude.json`), project (`.mcp.json`, shared via git), user. `.mcp.json` supports `"headers"` with `${VAR}` and `${VAR:-default}` expansion; `headersHelper` runs a command that prints a JSON object of headers (10 second timeout). [Fact]
+- OAuth: `/mcp` in a session or `claude mcp login <name>`; `--callback-port` fixes the loopback port; `--client-id` and `--client-secret` for pre-registered clients; "Claude Code also supports servers that use a Client ID Metadata Document (CIMD)". [Fact]
+- Claude Code uses a loopback redirect on an ephemeral port; its CIMD (`https://claude.ai/oauth/claude-code-client-metadata`) declares `http://localhost/callback` and `http://127.0.0.1/callback`, so the AS must match both **ignoring the port**. [Fact]
+- Limits: warning above 10,000 tokens of tool output, cap 25,000 tokens by default (`MAX_MCP_OUTPUT_TOKENS`); per-server `timeout` or `MCP_TOOL_TIMEOUT`. Tool descriptions and server instructions loaded up front are capped at 4,096 characters; a tool loaded through tool search at 16,384. Tool full names (`mcp__<server>__<tool>`) over 128 characters are dropped. [Fact]
+- Protocol: a v1 runtime (TypeScript SDK 1.x) and a v2 runtime (SDK 2.0, adds 2026-07-28); `MCP_SDK_GENERATION` and `MCP_PROTOCOL_NEGOTIATION=auto|legacy` choose. [Fact]
+- Elicitation: Claude Code shows form and URL elicitation dialogs; it declares `elicitation: {form: {}, url: {}}` on 2026-07-28 connections and on legacy connections to servers in the user's own config (v2.1.287+). [Fact]
+- Per-tool forced approval: setting `_meta["anthropic/requiresUserInteraction"]: true` on a tool in `tools/list` makes Claude Code prompt on every call, in every permission mode, with no "don't ask again". [Fact]
+- Tool search defers tool definitions; good server `instructions` help Claude find the tools. [Fact]
+
+### 3.3 Anthropic directory review rules worth adopting even for a private server
+
+Source: https://claude.com/docs/connectors/building/review-criteria
+
+- Separate read tools from write tools; ideally split writes into create, update, delete. No catch-all `api_request` tool. [Fact]
+- Every tool has a `title` and the applicable hint: `readOnlyHint: true` for reads, `destructiveHint: true` for modifying or deleting tools; "Read-only tools can run without per-call confirmation, and destructive tools always prompt." [Fact]
+- Tool names 64 characters or fewer. Narrow, accurate descriptions. [Fact]
+- Descriptions must not instruct Claude to call other tools, pull instructions from external sources, contain hidden instructions, or override system behavior. [Fact]
+- Actionable errors (no bare "Internal Server Error"); validate inputs; reasonably sized responses. [Fact]
+
+---
+
+## 4. Auth options for Twiligent compared
+
+Facts about each option, then trade-offs. "Twiligent constraint" means the zero-new-runtime-dependency rule and the Cloudflare free plan.
+
+### 4.1 (a) Supabase Auth OAuth 2.1 server
+
+Facts:
+
+- Status: "OAuth 2.1 server is in beta and available on all Supabase plans", no separate charge; OAuth users count toward MAU. [Fact, https://supabase.com/docs/guides/auth/oauth-server/getting-started]
+- Supports authorization code with mandatory PKCE, OIDC (ID tokens, UserInfo, discovery), standard scopes only (`openid`, `email`, `profile`, `phone`; "Custom scopes are not currently supported"), DCR, JWKS. [Fact, https://supabase.com/docs/guides/auth/oauth-server and .../oauth-flows]
+- Owner must: enable the OAuth 2.1 server (Authentication > OAuth Server, or `[auth.oauth_server] enabled = true`), set the Authorization Path (for example `/oauth/consent`, combined with the Site URL), turn on DCR (`allow_dynamic_registration = true`), and host a consent page in the frontend that calls `supabase.auth.oauth.getAuthorizationDetails`, then `approveAuthorization` or `denyAuthorization`. [Fact, getting-started and https://supabase.com/docs/guides/ai-tools/byo-mcp]
+- Discovery at `https://<ref>.supabase.co/.well-known/oauth-authorization-server/auth/v1` (RFC 8414 path insertion) and OIDC at `/auth/v1/.well-known/openid-configuration`; issuer `https://<ref>.supabase.co/auth/v1`. [Fact]
+- Access tokens are normal Supabase JWTs with `user_id`, `role`, `client_id`; `aud` is `authenticated`; validate with the JWKS at `/auth/v1/.well-known/jwks.json`, checking signature, `iss`, `aud`, `exp`. Asymmetric signing keys (RS256 or ES256) are recommended and required for ID tokens; Supabase's own MCP middleware rejects legacy HS256. Custom Access Token Hooks run for OAuth tokens and can "Set the aud claim to the third-party API endpoint", keyed by `client_id`. [Fact, getting-started, oauth-flows, byo-mcp]
+- Redirect URIs: exact match only, no wildcards. [Fact]
+- Gaps reported in public GitHub issues, all **open** on 2026-11-05 (checked with `gh api`):
+ - supabase/auth #2610 "support RFC 8707 Resource Indicators (resource parameter -> aud claim)": the `resource` parameter is accepted but ignored and tokens get `aud: "authenticated"`; PR #2894 open. [Report]
+ - supabase/auth #2703 "authorize rejects RFC 8252 loopback ephemeral-port redirect_uri": exact match includes the port, so native clients like Claude Code that register `http://127.0.0.1/callback` and then use `:3118` get `400`; PR #2871 open. [Report]
+ - supabase/auth #2850 "support Client ID Metadata Documents"; PR #2895 open. So CIMD is not supported today. [Report]
+
+What it means for each client (Inference unless marked):
+
+- claude.ai and Desktop: should work via DCR. Claude falls back to DCR when CIMD is not advertised [Fact, Claude docs], the callback `https://claude.ai/api/mcp/auth_callback` is a fixed HTTPS URL that exact matching accepts, and PKCE S256 is supported. The user picks "Register automatically" (or the default detection does). Not tested end to end.
+- Claude Code: likely to fail with the default ephemeral port because of #2703. Workarounds: `claude mcp add ... --callback-port 8080` so the registered and used redirect URIs are identical, or use a PAT (option c). The `--callback-port` workaround is my inference from the docs, not tested.
+- Audience: Supabase does not bind tokens to the MCP URL, which conflicts with the spec's MUST to validate audience. Mitigation: a Custom Access Token Hook (a Postgres function, added through a migration) that sets `aud` to the MCP server URL whenever `client_id` is present; the Worker then accepts on `/mcp` only tokens with that `aud` and a `client_id` claim, and keeps accepting `aud: "authenticated"` without `client_id` on the existing app routes. Needs a test that the existing web app and RLS keep working, because the hook runs on every token issuance. [Inference]
+
+Pros: no new dependency; no new token store; users sign in with the account they already have; consent and grant revocation come from Supabase; works on the free plans. Cons: beta; three open gaps above; each self-hoster must enable it, switch to asymmetric keys and deploy the consent route; DCR is deprecated in the spec, and open DCR lets anyone register clients (consent page must clearly show the client name and redirect host).
+
+### 4.2 (b) Cloudflare `workers-oauth-provider`
+
+Facts (https://github.com/cloudflare/workers-oauth-provider ; npm):
+
+- "adds OAuth 2.1 authorization to HTTP APIs and remote MCP servers running on Cloudflare Workers"; needs a KV namespace bound as `OAUTH_KV`, and the `global_fetch_strictly_public` compatibility flag if it accepts CIMD. [Fact]
+- Supports pre-registered clients, CIMD (`clientIdMetadataDocumentEnabled: true`), DCR (RFC 7591), RFC 8707 resources and audiences, PKCE (RFC 7636). Tokens, codes and secrets stored only as hashes; `props` encrypted. Requests under `apiRoute` reach `apiHandler` with `ctx.props`; others go to `defaultHandler`, which renders `/authorize`. "The library advertises the required scopes but doesn't enforce them." [Fact]
+- npm: version 1.2.4, no runtime dependencies listed, unpacked size about 486 KB. [Fact, `npm view` on 2026-11-05]
+
+Inference: covers CIMD, DCR, audience binding and probably loopback matching, so it would satisfy claude.ai and Claude Code without workarounds. The Twiligent `/authorize` page would sign the user in with Supabase and call `completeAuthorization()` with `{ userId }`. Costs: it is a new runtime dependency (owner approval required), it wraps the Worker's top-level `fetch` (the Hono app becomes the `defaultHandler` or `apiHandler`), it adds KV (free plan KV write quotas are low; I did not verify the current numbers), and it creates a second token system next to Supabase sessions.
+
+### 4.3 (c) Personal access tokens (PATs)
+
+Facts: Claude Code sends any header you give it (`--header "Authorization: Bearer ..."`, `.mcp.json` `headers` with `${VAR}`, or `headersHelper`). claude.ai accepts a static `Authorization` header only in the `static_headers` beta, for a limited set of organizations, entered once by an Owner, shared organization-wide. [Fact, sections 3.1 and 3.2]
+
+Inference: PATs are the simplest, dependency-free path and fully cover Claude Code, the API's MCP connector and scripts. They do not cover claude.ai for most users. Design: create in the dashboard, show once, store only a SHA-256 hash plus a short prefix for display, scopes (`read`, `publish`), expiry, last-used time, revoke button; table with RLS; a `...ForUser` repository. Prefix the token (for example `twl_pat_`) so the Worker can tell it from a JWT without trying to parse it, and so secret scanners can find leaks. Strictly speaking the MCP authorization spec covers OAuth tokens; a PAT is a separate, simpler credential the spec does not forbid, but a PAT-protected endpoint should still return a proper `401` (Claude docs require it to trigger sign-in) and never accept a token in the URL.
+
+### 4.4 (d) Hand-written OAuth 2.1 authorization server in the Worker
+
+Inference: technically possible with Web Crypto and Postgres tables (clients, codes, refresh tokens), and it could support CIMD, DCR, RFC 8707 and loopback any-port matching exactly as Claude needs. But it is the largest security surface of the four: PKCE, code single use, refresh rotation with reuse detection, `iss` responses, CIMD fetching with SSRF protection, consent CSRF and clickjacking protection, redirect validation, token revocation. The spec's own security pages list many MUSTs that are easy to get subtly wrong. Not recommended unless (a) proves unworkable and (b) is refused.
+
+### 4.5 Comparison
+
+| | (a) Supabase OAuth server | (b) workers-oauth-provider | (c) PATs | (d) Hand-written AS |
+|---|---|---|---|---|
+| claude.ai / Desktop | Yes via DCR (inference, untested) | Yes, CIMD or DCR | Only `static_headers` beta, org-shared | Yes if built right |
+| Claude Code | Needs `--callback-port` workaround or a PAT (open issue #2703) | Yes | Yes | Yes |
+| Spec audience MUST | Needs Custom Access Token Hook | Built in | Not OAuth; N/A | Must build |
+| CIMD (spec SHOULD) | No (open issue) | Yes | N/A | Must build |
+| New runtime dependency | None | Yes (no transitive deps) + KV | None | None |
+| Work in Twiligent | Consent page, hook migration, JWKS verify | Authorize page, wrap fetch, KV binding | Table, UI, hashing | Large |
+| Maturity | Beta | 1.x, maintained by Cloudflare | Simple | Yours to maintain |
+
+### 4.6 Recommendation
+
+**Primary: (a) Supabase OAuth 2.1 server + Custom Access Token Hook for `aud`, with the Worker as a resource server only. Secondary: (c) PATs for Claude Code, CI and as a fallback.** [Inference]
+
+Why: it keeps the zero-dependency rule, reuses the user accounts and email sign-in Twiligent already has, keeps one identity system, and Supabase is already the trusted party for JWTs. The audience gap is closed by the hook; the Claude Code loopback gap is covered by PATs or `--callback-port` until Supabase merges #2871; CIMD is a SHOULD and Claude falls back to DCR. Revisit when Supabase ships #2894, #2871 and #2895. Choose (b) instead if the owner approves a dependency and wants zero client-side workarounds today.
+
+Worker-side requirements for either OAuth choice [Fact-derived requirements, Inference for the shape]:
+
+1. `GET /.well-known/oauth-protected-resource/mcp` (and the root variant) returning `{ "resource": "https://<api host>/mcp", "authorization_servers": ["https://<ref>.supabase.co/auth/v1"], "scopes_supported": [...], "bearer_methods_supported": ["header"] }`. `resource` must equal the URL users paste into Claude exactly.
+2. Unauthenticated `POST /mcp` returns `401` with `WWW-Authenticate: Bearer resource_metadata="https://<api host>/.well-known/oauth-protected-resource/mcp"`.
+3. Verify the JWT locally against cached JWKS with Web Crypto (no `jose` dependency needed; ES256 and RS256 are both in Web Crypto): signature, `iss`, `exp`, `aud` equals the MCP URL, `client_id` present. Take `userId` from `sub` only. Cache the JWKS in memory and in Redis, so verification is CPU-only and stays well inside 10 ms (inference, not measured).
+4. Never forward the client's token to Instagram, YouTube or Cloudinary; use the stored per-user platform credentials as the existing services do.
+5. Since Supabase has no custom scopes, model "read" vs "publish" permission in Twiligent itself (for example a per-grant setting the user picks on the consent page, stored by `client_id`, or simply write tools gated by confirmation). [Inference]
+
+---
+
+## 5. Hand-written JSON-RPC in Hono vs the SDK
+
+Facts (npm, 2026-11-05; Context7 docs for `/modelcontextprotocol/typescript-sdk/v2.4.0`; Cloudflare docs):
+
+- `@modelcontextprotocol/server` 2.4.0 depends on `zod ^4.2.0` and `@modelcontextprotocol/core` 2.4.0 (which itself depends on `zod`); unpacked size about 7.0 MB (core about 1.4 MB). It provides `createMcpHandler(factory)` that runs on web-standard runtimes (Workers, Deno, Bun), creates a fresh `McpServer` per request, and serves both 2026-07-28 and 2025-era clients. `@modelcontextprotocol/hono` 2.0.2 (peer deps `hono ^4.11.4`, server `^2.3.0`) adds `createMcpHonoApp` with JSON parsing and DNS rebinding protection. [Fact]
+- The v1 package `@modelcontextprotocol/sdk` 1.32.2 pulls express, cors, ajv, jose, hono, eventsource and more. Not suitable for this Worker. [Fact for the list]
+- Cloudflare `McpAgent` (Durable Object based) is now marked **deprecated and feature-frozen**; Cloudflare recommends the stateless `createMcpHandler` from `agents/mcp/server` (Agents SDK 0.20.0+ added 2026-07-28 support). On legacy clients the stateless handler gives "2025 wire compatibility without sessions"; GET and DELETE return 405; "Pushed elicitation, sampling, and roots requests fail immediately". The `agents` package (0.33.0) has many dependencies. [Fact, https://developers.cloudflare.com/agents/model-context-protocol/apis/handler-api/ , .../agent-api/ , changelog 2026-07-27, npm]
+
+Recommendation: **hand-write it.** [Inference]
+
+- The surface for a tools-only, JSON-only, sessionless server is small: parse one JSON-RPC message, dispatch about six methods (section 2.3), validate the modern headers, return JSON. That is a route, a controller and a small `lib/mcp/` module of pure functions (envelope parsing, error builders, header checks), which Node tests can cover directly, matching Twiligent's layer rules.
+- The SDK would add `zod` 4 and a multi-megabyte package to a Worker whose rule is zero extra runtime dependencies, and its tool input validation is zod-based, while Twiligent already has `backend/validators/`.
+- Tool input schemas can be written as plain JSON Schema objects next to the existing validators (one source of truth per tool: a validator function plus its published schema; a test asserts they agree on sample inputs).
+- Risk of hand-writing: protocol drift as the spec moves (it changed shape twice in 2025 to 2026). Mitigate with: a conformance test that drives the endpoint with the official client package as a **dev dependency only** (if the owner approves dev tooling), the MCP Inspector, and real Claude.ai and Claude Code connections before release.
+- Choose the SDK instead only if you later need MRTR elicitation, `subscriptions/listen`, resources and prompts, or the tasks extension, where the protocol surface grows.
+
+---
+
+## 6. Production practices for Twiligent's tools
+
+Each item says where it comes from.
+
+### 6.1 Tool design
+
+- Narrow, task-shaped tools, read separate from write, create/update/delete split (Anthropic review rules; Alloy; New Stack 1). Suggested first set [Inference]: `list_accounts`, `get_account_analytics`, `get_video_analytics`, `list_scheduled_posts`, `get_scheduled_post`, `schedule_instagram_post`, `update_scheduled_post`, `cancel_scheduled_post`, `create_media_upload` (returns a signed Cloudinary upload, never raw bytes through MCP), later `create_youtube_upload` plus `get_youtube_upload_status`.
+- Names: snake_case, 64 characters or fewer, unique, stable (Anthropic review; spec name rules). Short server name too, because Claude Code builds `mcp__<server>__<tool>` and drops names over 128.
+- Annotations on every tool: `title`; reads `readOnlyHint: true, openWorldHint: true` when they return platform content (Instagram, YouTube), `false` when they only read Twiligent's own tables; writes `readOnlyHint: false` with honest `destructiveHint` (cancel and delete true; schedule a new post false but see confirmation below) and `idempotentHint` (Spec defaults; MCP blog on annotations; Anthropic review).
+- Descriptions: what the tool does, when to use it, units, limits, retention of any handle; no behavioral instructions (Anthropic review). Put cross-tool guidance ("use `list_accounts` to get an `account_id`") in server `instructions` and parameter descriptions as facts (Claude Code tool search note; Alloy hints).
+- Server `instructions` under 4,096 characters (Claude Code limit).
+- Deterministic `tools/list` order (spec SHOULD).
+
+### 6.2 Inputs, outputs, size
+
+- Validate every input server-side with the existing validators; return `isError: true` with a message that says what to fix, never a bare error (spec MUST; Anthropic review).
+- `structuredContent` plus the same JSON serialized in a text block (spec SHOULD for backwards compatibility); add `outputSchema` for stable shapes.
+- Pagination: `limit` (default 20, max 100) and opaque `cursor`; return `next_cursor` and a total when cheap (New Stack 2 and 10; Alloy).
+- Size budget: target under about 10,000 tokens per result so Claude Code does not warn; hard cap well below claude.ai's ~150,000 characters and Claude Code's 25,000 tokens; when truncating, say what was cut and how to get the rest (Claude limits; Alloy). [Numbers are Inference from the stated limits]
+- Dates in ISO 8601 with time zone; ids as strings.
+
+### 6.3 Per-user rate limiting and timeouts
+
+- Rate limit tool calls per user and per tool through the existing rate-limit middleware and Upstash scripts (spec MUST "Rate limit tool invocations"; Alloy; Mads Hansen expects 10x volume). Separate, tighter buckets for write tools and for upstream-heavy reads (Instagram and YouTube quotas). Return an `isError` result that says when to retry. Redis absent must fail open or to a conservative in-memory limit, per Twiligent's rule that the app works without Redis. [Inference for the bucket design]
+- Timeouts: claude.ai waits 240 seconds per call. Workers free plan allows 10 ms CPU per request (paid default 30 s, max 5 min CPU), 50 subrequests per request on free, no hard wall-clock limit for HTTP requests (Fact, https://developers.cloudflare.com/workers/platform/limits/). Put an explicit timeout (for example 20 to 30 s) on every upstream fetch inside a tool and return a clear `isError` on timeout. Long work (YouTube upload processing) returns a job handle immediately plus a status tool; the job runs in the existing cron or queue path (spec "Stateful Tools" handle guidance). [Inference for numbers]
+- On the free plan, keep per-call CPU low: local JWT verification with cached JWKS, no heavy JSON Schema engine, no large in-Worker transforms. [Inference]
+
+### 6.4 Idempotency for write tools
+
+- Agents retry and parallelize (New Stack 2). Give every create tool an optional `idempotency_key` string argument and also derive a server-side key from user id + tool + canonical args when absent; store key to result for 24 hours in Postgres (durable) or Redis (best effort) and return the original result on repeats. [Inference]
+- Mark truly idempotent tools (`update_scheduled_post` with full replacement, `cancel_scheduled_post`) with `idempotentHint: true`.
+- Twiligent already has a rule that an unknown-outcome private reply is never re-sent without a person's decision; apply the same rule to publishing: a publish whose outcome is unknown is never retried automatically by a tool call. [Inference, consistent with the project's CLAUDE.md]
+
+### 6.5 Confirmation for destructive or public actions
+
+Options:
+
+1. **Client-side prompts from annotations:** Anthropic states destructive tools always prompt and read-only tools can auto-run (Fact, review criteria). Cheapest, but depends on the client and the user's "Always allow" choice.
+2. **`_meta["anthropic/requiresUserInteraction"]: true`:** forces a prompt on every call in Claude Code, all modes (Fact). Not documented for claude.ai.
+3. **Elicitation:** modern clients use MRTR (`input_required` + signed `requestState`); Claude Code supports form and URL elicitation (Fact); claude.ai support is undocumented. Legacy elicitation is a server-to-client request on the open SSE stream with the reply arriving as a separate POST, which a sessionless Worker cannot correlate reliably; Cloudflare's stateless handler simply fails such requests (Fact for Cloudflare's behavior; Inference for the general point).
+4. **Two-step confirm token (works with every client):** `schedule_instagram_post` (or `cancel_...`) first returns a preview (account, caption, media, scheduled time, what will happen) plus a `confirmation_token`; a second call with that token executes. The token is HMAC-signed with a Worker secret and binds user id, tool, a digest of the arguments and a short expiry (for example 10 minutes), and is single-use, enforced server-side (same rules the spec gives for MRTR `requestState`). [Inference, modeled on the spec's MRTR security rules and New Stack 15 "dry-run ... return a diff"]
+
+Recommendation [Inference]: annotations (1) on every tool, plus the two-step token (4) for anything public or irreversible (publish now, cancel, delete media, YouTube upload). Add `requiresUserInteraction` (2) for the execute step as a belt-and-braces measure in Claude Code. Add MRTR elicitation (3) later when claude.ai documents support.
+
+### 6.6 Audit logging
+
+- One row per tool call: id, user id, OAuth `client_id` or PAT id, tool name, argument digest (not raw captions or tokens), outcome (ok, isError, protocol error), error code, latency, upstream request ids, created_at. Retain for a fixed period. Writes never block the response (use `ctx.waitUntil`). (Alloy audit trails; New Stack 7; spec "Log tool usage for audit purposes" is a client SHOULD but equally useful server-side.) [Inference for the schema]
+- Show recent MCP activity and connected clients in the dashboard with a revoke button (Supabase exposes grant management for OAuth clients, Fact per byo-mcp and Server SDK pages; PAT revoke is Twiligent's own).
+- Never log access tokens, PATs, refresh tokens or Instagram access tokens (spec token theft section; Twiligent's `safeAccount()` rule).
+
+### 6.7 Prompt injection from untrusted content
+
+Instagram comments, captions, usernames, DMs, YouTube titles and descriptions are third-party text that will be read by the model.
+
+- Mark such tools `openWorldHint: true`, which per the MCP blog tells clients to "Scrutinize output for untrusted content" (Fact, MCP blog).
+- Return third-party text only in clearly named data fields in `structuredContent` (for example `comment.text`), never mixed into the tool's own explanatory sentences; cap length per item; strip control characters and zero-width characters; do not render it as markdown instructions. [Inference]
+- Read tools never cause writes, and write tools always require the confirmation step, so injected text cannot publish or reply on its own. [Inference]
+- Server descriptions and `instructions` must not tell the model to follow content found in results (Anthropic review). Spec MUST "Sanitize tool outputs" (Fact).
+- Consider an explicit note in server `instructions` that comment and caption fields are user-generated content, phrased as a fact, not a command. [Inference]
+
+### 6.8 Observability
+
+- Structured logs per call with a correlation id (also returned in `_meta` of the result), tool name, user id hash, latency, outcome (New Stack 7). Workers Logs is enough to start. [Inference]
+- 2026-07-28 documents OpenTelemetry trace context in `_meta` (`traceparent`, `tracestate`, `baggage`) (Fact, changelog minor item 2); read it if present and pass it to logs.
+- Count per tool: calls, errors, p95 latency, rate-limit hits, confirm-token issued vs used. Alert on spikes in `isError` and 401s. [Inference]
+
+### 6.9 Versioning and compatibility
+
+- `serverInfo.version` follows the app's semantic version (New Stack 8). Add tools additively; never change a tool's meaning under the same name; ship a new name for breaking changes and keep the old one for a deprecation window. [Inference]
+- Support legacy `2025-06-18` and `2025-11-25` (what Claude's hosted apps use) and modern `2026-07-28`; answer `initialize` with the client's version when supported, else the latest legacy one; answer unknown modern versions with `-32022` and the `supported` list. Decide whether to accept a missing `MCP-Protocol-Version` header as `2025-03-26` (spec MAY). (Facts from section 2; Inference for the policy.)
+- Results on modern requests carry `resultType: "complete"`; list results carry `ttlMs` and `cacheScope` (`"private"` for per-user lists). (Fact, changelog major item 8 and minor item 5.)
+- Tests with the MCP Inspector and real Claude clients before each release; fault injection for slow and failing upstreams (New Stack 11; Anthropic testing guidance).
+
+### 6.10 Origin and CORS on the Worker
+
+- Spec MUST validate `Origin`; if present and not allowed, `403` (Fact). Claude's hosted connections are server-to-server from Anthropic's cloud; I could not verify whether they send an `Origin` header. Allowlist the app origin and accept requests with no `Origin` (non-browser clients). [Inference]
+- CORS is only needed for browser-based MCP clients such as the Inspector; keep it narrow. [Inference]
+
+---
+
+## 7. What I could not verify
+
+- Whether claude.ai's hosted MCP client speaks the 2026-07-28 wire protocol or only legacy revisions (docs list only 2025-era auth specs). Plan for legacy.
+- Whether claude.ai and Claude Desktop support elicitation (form or URL) for remote custom connectors. Not documented on the pages I read.
+- Whether claude.ai's requests send an `Origin` header.
+- End-to-end behavior of Supabase's OAuth server with claude.ai (DCR path) and with Claude Code using `--callback-port`. These are reasoned from docs and issues, not tested.
+- Whether a Supabase Custom Access Token Hook that changes `aud` for OAuth tokens has side effects on Supabase's own APIs (PostgREST, Storage) for those tokens. Docs say the hook can set `aud`, nothing more.
+- The `workers-oauth-provider` loopback any-port behavior and its refresh-token rotation (README did not state either), and current Cloudflare KV free-plan quotas.
+- Bundled (minified) size of `@modelcontextprotocol/server` in a Worker; I only have npm unpacked sizes.
+- The two dev.to articles were read through WebFetch's summarizer, so their points are paraphrased, not verbatim.
+
+## 8. Sources
+
+- Articles: https://runalloy.com/blog/building-production-ready-mcp-servers ; https://medium.com/@arifdewi/building-your-first-production-ready-mcp-server-a-weekend-project-that-actually-shipped-131305c69d54 ; https://dev.to/guang_diyuzhi_74b0fec2c09/mcp-in-production-is-the-model-context-protocol-ready-in-2026-5205 ; https://thenewstack.io/15-best-practices-for-building-mcp-servers-in-production/ ; https://dev.to/mads_hansen_27b33ebfee4c9/mcp-in-production-what-nobody-tells-you-before-you-start-21m
+- MCP spec: https://modelcontextprotocol.io/specification/versioning ; https://modelcontextprotocol.io/specification/2026-07-28/changelog ; .../2026-07-28/basic/transports ; .../2026-07-28/basic/transports/streamable-http ; .../2026-07-28/basic/versioning ; .../2026-07-28/server/discover ; .../2026-07-28/server/tools ; .../2026-07-28/basic/patterns/mrtr ; .../2026-07-28/basic/authorization (+ /authorization-server-discovery, /client-registration, /security-considerations) ; https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/security_best_practices ; https://modelcontextprotocol.io/specification/2025-11-25/basic/transports ; .../2025-11-25/basic/lifecycle ; https://modelcontextprotocol.io/specification/2025-06-18/schema ; https://blog.modelcontextprotocol.io/posts/2026-03-16-tool-annotations
+- Anthropic: https://claude.com/docs/connectors/building ; https://claude.com/docs/connectors/building/authentication ; https://claude.com/docs/connectors/building/review-criteria ; https://claude.com/docs/connectors/custom/add-unlisted ; https://support.claude.com/en/articles/11175166-get-started-with-custom-connectors-using-remote-mcp ; https://code.claude.com/docs/en/mcp
+- Supabase: https://supabase.com/docs/guides/auth/oauth-server ; .../oauth-server/getting-started ; .../oauth-server/oauth-flows ; .../oauth-server/mcp-authentication ; https://supabase.com/docs/guides/ai-tools/byo-mcp ; GitHub supabase/auth issues #2610, #2703, #2850 and PRs #2871, #2894, #2895 (state checked 2026-11-05)
+- Cloudflare: https://github.com/cloudflare/workers-oauth-provider ; https://developers.cloudflare.com/agents/model-context-protocol/apis/handler-api/ ; https://developers.cloudflare.com/agents/model-context-protocol/apis/agent-api/ ; https://developers.cloudflare.com/changelog/post/2026-07-27-agents-sdk-v0.20.0-mcp-sdk-v2/ ; https://developers.cloudflare.com/workers/platform/limits/
+- MCP TypeScript SDK v2.4.0 docs via Context7 (`/modelcontextprotocol/typescript-sdk/v2.4.0`); npm registry (`npm view`) for versions and dependencies, 2026-11-05
diff --git a/docs/platform-v2/research/postiz.md b/docs/platform-v2/research/postiz.md
new file mode 100644
index 0000000..82fbe62
--- /dev/null
+++ b/docs/platform-v2/research/postiz.md
@@ -0,0 +1,170 @@
+# Postiz as a reference for Twiligent publishing
+
+Source read: `gitroomhq/postiz-app`, shallow clone of `main` at commit `bd8353f` (3 November 2026). All paths below are relative to the repository root. Nothing was installed, built or run.
+
+## 10. Licence (read this first)
+
+`LICENSE` is the **GNU Affero General Public License v3 (AGPL-3.0)**. Contributors sign a CLA (`CCLA.md`, `ICLA.md`). Copying any code into Twiligent would put Twiligent under AGPL obligations. Treat everything here as ideas and protocol knowledge only; write Twiligent's code from the platform documentation, not from Postiz files.
+
+## 1. Overall architecture
+
+Monorepo (pnpm, NestJS + Prisma backend, Vite React frontend). From the root `CLAUDE.md` and `apps/`:
+
+| App | Role |
+| --- | --- |
+| `apps/backend` | NestJS REST API, public API (`src/public-api`), MCP server mount, OAuth callbacks |
+| `apps/orchestrator` | Temporal worker: all workflows (`src/workflows`) and activities (`src/activities`) |
+| `apps/frontend` | Vite React app |
+| `apps/commands` | CLI tasks |
+| `apps/extension` | Chrome extension for cookie based providers (e.g. Skool) |
+| `apps/sdk` | Node SDK for the public API |
+| `libraries/nestjs-libraries` | Shared services, Prisma repositories, providers, upload, Temporal module |
+
+**Queue / workflow engine: Temporal.** `libraries/nestjs-libraries/src/temporal/temporal.module.ts` registers one Temporal worker per provider task queue (`youtube`, `x`, `instagram`...) plus `main`. Workflows only run on `main`; provider queues are activity-only, and each queue's `maxConcurrentActivityTaskExecutions` comes from the provider's `maxConcurrentJob` (YouTube sets 200), divided by `WORKER_CONCURRENCY_DIVIDER` when several servers share a queue. `EXCLUDE_QUEUE` pins low-concurrency queues to one server. `docker-compose.yaml` runs Postgres 17, Redis 7.2, and a full Temporal stack (temporal auto-setup 1.28, its own Postgres 16, Elasticsearch 7.17 for visibility).
+
+History: earlier Postiz releases used BullMQ on Redis with separate `workers` and `cron` apps. Those apps no longer exist on `main`; Redis now only caches analytics, holds upload session tickets and short locks (`libraries/nestjs-libraries/src/redis/redis.service.ts` falls back to an in-memory mock when `REDIS_URL` is absent). (The shallow clone has no git history, so the BullMQ period is from public project history, not verified in this checkout.) The reasons visible in the code for Temporal: durable timers (a workflow `sleep`s until `publishDate`, `post.workflow.v1.1.2.ts`), per-provider concurrency caps through task queues, heartbeats that tell "never started" from "started then stalled", and a workflow history that holds in-flight upload state.
+
+The price is visible too: workflow code can never be edited once on `main` (CLAUDE.md rule), so there are twelve frozen post workflows `post.workflow.v1.0.1.ts` to `v1.1.2.ts`, and providers keep legacy `post()` paths for old in-flight runs.
+
+How they talk: backend writes the `Post` row, then starts workflow `postWorkflowV112` with id `post_<postId>` (`posts.service.ts` `startWorkflow`, conflict policy `TERMINATE_EXISTING`, after terminating any running workflow found by the `postId` search attribute). Workers call back into the same Prisma services.
+
+## 2. Provider abstraction
+
+Interface: `libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts`.
+
+- `IAuthenticator`: `generateAuthUrl()` returns `{url, codeVerifier, state}`; `authenticate({code, codeVerifier})` returns `AuthTokenDetails` (`id, name, accessToken, refreshToken, expiresIn, picture, username`); `refreshToken(refreshToken)`; optional `reConnect` (re-pick a sub-account such as a channel or page after refresh), `analytics(id, token, days)`, `postAnalytics(integrationId, token, postId, fromDate)`, `resolveReleaseId`, `releaseUrl`, `changeNickname`, `changeProfilePicture`, `missing`.
+- `ISocialMediaIntegration`: `post(id, token, postDetails[], integration)` returns `PostResponse[]` (`id, postId, releaseURL, status, pendingData?`); optional `postPending` (may return `status: 'pending'`); optional `comment`.
+- `SocialProvider` adds metadata and hooks: `identifier`, `name`, `scopes`, `editor`, `maxLength()`, `dto` (class-validator settings DTO), `checkValidity(media, settings)` (server-side media rules), `checkPostStatus(token, pendingData)` and `finalizePost(token, pendingData)` returning `PendingCheckResponse` (`pending | ready | completed`), `refreshCron`, `refreshWait`, `refreshErrorMessage(err)`, `isBetweenSteps` (needs a second step after OAuth, e.g. choose a channel), `oneTimeToken`, `customFields`, `mention`, `migrationMatch`.
+
+The contract comment on `PendingCheckResponse` is worth learning: once `finalizePost`'s mutations went through, `checkPostStatus` must return `completed`, never `ready` again, or a retry would duplicate the post; only idempotent mutations (setting a thumbnail) may repeat.
+
+Base class `social.abstract.ts` (`SocialAbstract`):
+- Typed failures: `RefreshToken`, `BadBody`, `Disconnect`, `PublishedWithError` (the post is live but a follow-up step failed; keep its id and URL), all Temporal `ApplicationFailure`s with messages truncated to 2,000 / 4,000 chars to fit the history.
+- `handleErrors(body, status)` per provider maps a response body to `refresh-token | bad-body | retry | disconnect` with a human message.
+- `fetch()` wrapper: SSRF-safe dispatcher for user-influenced URLs, retries up to 3 times with a fixed 5 s wait on 429, unclassified 500, or `retry`; 401 becomes `RefreshToken`; everything else `BadBody`.
+- `checkScopes()` rejects a connection missing any required scope (`NotEnoughScopes`).
+- Ranged media reads with a 120 s stall timeout.
+
+Registration: `integration.manager.ts` holds a static array `socialIntegrationList` of provider instances (35 providers). `IntegrationManager` looks them up by identifier, hides some via `HIDDEN_PROVIDERS`, and migrates channels between providers via `MIGRATE_PROVIDERS`. Adding a platform = a provider class, a settings DTO, adding it to the array, frontend settings component; the task queue appears automatically. A repo rule bans `if (provider === 'x')` in generic code: new behaviour goes into the interface.
+
+## 3. YouTube provider
+
+File: `libraries/nestjs-libraries/src/integrations/social/youtube.provider.ts` (1,106 lines). Uses the `googleapis` client for OAuth, channels, thumbnails and analytics, but plain `fetch` for the upload.
+
+- **Scopes**: `userinfo.profile`, `userinfo.email`, `youtube`, `youtube.force-ssl`, `youtube.readonly`, `youtube.upload`, `youtubepartner`, `yt-analytics.readonly`. Broader than needed for upload alone (`youtube.upload` + `youtube.readonly` + `yt-analytics.readonly` would cover upload and analytics; `youtube.force-ssl` or `youtube` is needed for thumbnails).
+- **Auth URL**: `access_type: 'offline'`, `prompt: 'consent'` so Google always returns a refresh token; random `state`. `authenticate` calls `getTokenInfo` and `checkScopes` so a user who unticks a scope is refused at connect time.
+- **Refresh**: `refreshToken()` calls Google's token endpoint, keeps the old refresh token if Google returns none, re-reads userinfo. `refreshErrorMessage` explains `invalid_rapt` (Google Workspace session control) in plain words.
+- **Channel choice**: `isBetweenSteps = true`; `pages()` lists `channels.list(mine=true)`, `fetchPageInformation` and `reConnect` verify the chosen channel still belongs to the token.
+- **Upload: resumable protocol, streamed, split across activities.**
+ 1. `postPending`: HEAD the media URL (identity encoding) for its size; POST `upload/youtube/v3/videos?uploadType=resumable&part=id,snippet,status&notifySubscribers=true` with `X-Upload-Content-Length`, snippet (`title`, `description` = post text, `tags`) and status (`privacyStatus`, `selfDeclaredMadeForKids`). Returns `status: 'pending'` with `pendingData {uploadUri, videoSize, path, uploadedBytes, thumbnail, postDbId}`. Nothing exists on the channel yet.
+ 2. `checkPostStatus`: probe the session with `PUT Content-Range: bytes */<size>`: 200/201 means the video exists (returns id); 308 gives the committed `Range`; 429/5xx is transient; 401 is `RefreshToken`; 404/410 means the session expired.
+ 3. `finalizePost`: probe first ("ask the session for the truth"), then send 8 MiB chunks (multiple of 256 KiB) fetched with HTTP `Range` from storage (requires a 206 answer) and streamed as the PUT body. Stops after a 4 minute batch and returns `pending` so the next activity resumes from the server's offset. After the final chunk sets the thumbnail via `thumbnails.set`; a thumbnail failure raises `PublishedWithError` so the video id and URL are saved even though the post is marked ERROR.
+ The header comment states the key insight: with the resumable protocol YouTube creates the video only when the last byte arrives, so retries cannot leave duplicates, and the session URI can always be asked whether the upload finished. The older `post()` method loops the same steps in one activity for old workflow versions.
+- **Privacy, tags, made-for-kids**: `YoutubeSettingsDto` (`dtos/posts/providers-settings/youtube.settings.dto.ts`): `title` 2 to 100 chars, `type` in `public | private | unlisted`, `selfDeclaredMadeForKids` yes/no, optional `thumbnail`, `tags` with a custom validator for YouTube's 500 character total (tags with spaces count 2 extra for quotes). No `publishAt` (YouTube-side scheduling), no category, no language.
+- **Shorts**: no special handling. Only a frontend hint (`media.settings.section.tsx`) that YouTube may ignore custom thumbnails on Shorts (vertical, up to 3 minutes). Shorts are just vertical videos uploaded the same way.
+- **Validation**: exactly one media item, path must contain `mp4`. `maxLength` 5000.
+- **Errors**: `handleErrors` maps YouTube reason strings (`invalidTags`, `invalidTitle`, `invalidDescription`, `defaultVideoInsertPerDayPerProject`, `uploadLimitExceeded`, `rateLimitExceeded`, `youtubeSignupRequired`, `failedPrecondition`, thumbnail size errors, `UNAUTHENTICATED`, `invalid_grant`...) to user-facing messages; quota exhaustion tells the user to reschedule.
+- **Analytics**: see section 8.
+
+## 4. OAuth connection management
+
+- **Storage**: `Integration.token` and `Integration.refreshToken` are plain `String` columns written as received (`integration.repository.ts` `createOrUpdateIntegration`, upsert on `(organizationId, internalId)`). They are **not encrypted at rest**. Encryption (`AuthService.fixedEncryption`, AES-256-CBC with a key and a fixed IV derived from `JWT_SECRET` via MD5 `EVP_BytesToKey`, `libraries/helpers/src/auth/auth.service.ts`) is used for org API keys and OAuth app secrets and codes, not for platform tokens. On account deletion the tokens are overwritten with hashes. A repo rule forbids returning raw `Integration` rows from controllers.
+- **Never wipe a refresh token**: update only sets `refreshToken` when a non-empty one arrives.
+- **Refresh scheduling**: two mechanisms. (a) Lazy: before analytics or publishing, if `tokenExpiration` is past, call `RefreshIntegrationService.refresh` (`refresh.integration.service.ts`). During publishing a `RefreshToken` failure makes the workflow call `refreshTokenWithCause` and retry the step. (b) For providers with `refreshCron`, a long-lived `refreshTokenWorkflow` (id `refresh_<integrationId>`) sleeps until `tokenExpiration` and refreshes, looping. `integration.repository.ts` `needsToBeRefreshed()` lists tokens expiring within a day.
+- **Revoked tokens**: on refresh failure, `refreshNeeded(org, id)` sets `Integration.refreshNeeded = true` with a conditional `updateMany ... where refreshNeeded = false`, and only the call that flipped it (`count === 1`) sends the notification, so repeated hourly failures do not spam. The post workflow refuses to publish to a channel with `refreshNeeded` or `disabled` and marks the post ERROR with a notification. Reconnecting resets `refreshNeeded` and `inBetweenSteps`. A `Disconnect` failure (platform will keep refusing) calls `disconnectChannel`.
+- **Multi-account**: one `Integration` row per connected account or channel, unique per `(organizationId, internalId)`. `rootInternalId` links sub-accounts (pages, channels) that share one login's token; `oneTimeToken` providers copy a refreshed token to all siblings with the same root. `customerId` groups channels by client.
+
+## 5. Scheduling and publishing
+
+States: `enum State { QUEUE, PUBLISHED, ERROR, DRAFT }` on `Post.state`.
+
+1. Create or edit: post rows saved (one row per channel; thread comments are child rows via `parentPostId`, grouped by `group`). `startWorkflow` terminates running workflows for that post, and for non-DRAFT starts `postWorkflowV112` with id `post_<postId>`. Drafts start nothing.
+2. Workflow (`apps/orchestrator/src/workflows/post-workflows/post.workflow.v1.1.2.ts`): load the post, fail with "Already posted" unless `state === QUEUE`, durable `sleep` until `publishDate`, refuse if channel `refreshNeeded` or `disabled`, then run `postSocialPending` on the provider's task queue.
+3. `pending` responses go to `resolvePending`: up to 90 checks 20 s apart (~30 minutes), each `checkPostStatus` (read-only, short timeout, 3 automatic retries) and `finalizePost` when `ready`. State from each check is committed before finalize so an interrupted finalize can be detected.
+4. Success: `updatePost` sets `state = PUBLISHED`, `releaseId`, `releaseURL`; in-app notification with the URL; user webhooks; then "plugs" (auto actions) and repeat posts (`intervalInDays`, child workflow).
+
+**Avoiding duplicate publishes** (the most valuable part):
+- Deterministic workflow id `post_<id>` plus terminate-before-start, so only one runner per post.
+- Mutating activities (`postSocialPending`, `finalizePost`, `postComment`) run with `maximumAttempts: 1`; the workflow decides retries itself.
+- Heartbeat every 15 s with a stage label; a heartbeat timeout with no details means the activity never started, so it is safe to retry; any other timeout is "outcome unknown".
+- A `posted` flag: once the platform accepted the post, no error afterwards may re-run the publish.
+- Unknown outcomes call `markUnconfirmed`: post goes to ERROR with a notification "we couldn't confirm it was published, check your account before posting again". They never auto-retry.
+- Read-only status checks are the only things retried freely.
+- Recovery sweep: `missingPostWorkflow` runs hourly (started once when `RUN_CRON` is set) and, for `QUEUE` posts whose `publishDate` is in the last 2 days, does `signalWithStart` with `USE_EXISTING`, so it pokes an existing workflow rather than starting a second one. Every failure path writes ERROR precisely so the sweep never re-publishes. Repeat posts are re-anchored to the next interval so a sweep does not fire a burst.
+
+**Retries and backoff**: activity retry policy `maximumAttempts: 3`, `initialInterval: 2 minutes`, `backoffCoefficient: 1` (fixed, not exponential) for non-mutating activities; HTTP level 3 retries with a fixed 5 s wait in `SocialAbstract.fetch`; token refresh then one more loop (`iterate` of 5 attempts).
+
+**Failure states**: `Post.state = ERROR` with `Post.error` text, plus an `Errors` row (message, platform, raw body) for diagnosis. Messages distinguish "Refresh channel needed", "Channel disabled", platform rejection (`BadBody` message), and unconfirmed.
+
+**Notifications**: `inAppNotification` activity (in-app list, optionally email, with types `info`, `success`, `fail`), digest email workflow, user-configured outgoing webhooks per integration (`sendWebhooks`), refresh-error notifications (`informAboutRefreshError`).
+
+## 6. Media
+
+- Storage selected by `STORAGE_PROVIDER` in `libraries/nestjs-libraries/src/upload/upload.factory.ts`: `local` (`UPLOAD_DIRECTORY`, served by the app) or `cloudflare` (R2 through the S3 API, `cloudflare.storage.ts`). No generic S3 option despite the S3 SDK; R2 is the cloud path.
+- Upload paths: browser uploads through Uppy with S3 multipart (`r2.uploader.ts` create / sign part / complete, `libraries/react-shared-libraries/src/helpers/uppy.upload.ts`), simple server uploads, upload from URL, and a ticketed upload widget for MCP hosts (Redis `uploadSession:` / `uploadTicket:` keys, 1 hour).
+- Validation (`custom.upload.validation.ts`): file type sniffed from magic bytes (`file-type`), allow list of JPEG, PNG, GIF, WebP, AVIF, BMP, TIFF, MP4 only; limits **10 MB images, 1 GB video**; a stream counter enforces the cap even when `Content-Length` lies.
+- Optional processing: `RunPodMediaProcessor` normalises video with ffmpeg on RunPod using presigned R2 URLs (only with cloud storage); `Media.status` and `processingError` track it.
+- Cleanup: `deleteMedia` is a soft delete (`deletedAt`); the storage object is not removed. Only the original file is removed after normalisation replaces it. No retention job for media.
+- Publishing reads media by URL with HTTP Range (YouTube) or full reads for images; `convertToJPEG` per provider.
+
+## 7. Database schema (Prisma, `libraries/nestjs-libraries/src/database/prisma/schema.prisma`)
+
+- `Post`: `id` (cuid), `state` (`QUEUE | PUBLISHED | ERROR | DRAFT`), `publishDate`, `integrationId`, `organizationId`, `content`, `settings` (JSON string with provider settings such as YouTube title, privacy, tags), `image` (JSON string of media), `group` (one compose action across channels), `parentPostId` (thread comments), `delay` (minutes before a comment), `releaseId`, `releaseURL`, `error`, `intervalInDays` (repeat), `creationMethod` (`WEB | MCP | API | AUTOPOST | CLI`), `deletedAt`. Indexed on `state`, `publishDate`, `integrationId`, `releaseURL`.
+- `Integration`: `internalId` (platform id), `providerIdentifier`, `token`, `refreshToken`, `tokenExpiration`, `refreshNeeded`, `inBetweenSteps`, `disabled`, `rootInternalId`, `profile`, `postingTimes`, `additionalSettings`, `customInstanceDetails`, `customerId`, `deletedAt`; unique `(organizationId, internalId)`.
+- `Media`: `name`, `path`, `fileSize`, `type`, `thumbnail`, `thumbnailTimestamp`, `alt`, `status`, `processingError`, `deletedAt`.
+- `Errors`: per-failure log with raw `body`. `Notifications`, `Webhooks` and `IntegrationsWebhooks`, `Organization.apiKey`, `OAuthApp`, `OAuthAuthorization` (for the public API and MCP).
+- Note: no `pendingData`, upload URI or attempt counter in Postgres. In-flight upload state lives only in Temporal workflow history.
+
+## 8. Analytics
+
+- Channel level: `IntegrationService.checkAnalytics` refreshes an expired token, reads Redis key `integration:<org>:<integrationId>:<days>` (TTL 3600 s), otherwise calls `provider.analytics(internalId, token, days)` and caches the result; one forced refresh and retry on `RefreshToken`. Returns `AnalyticsData[]` (`label`, daily `{total, date}` points, `percentageChange`).
+- YouTube channel: YouTube Analytics API v2 `reports.query` with `ids=channel==MINE`, `dimensions=day`, metrics `views, estimatedMinutesWatched, averageViewDuration, averageViewPercentage, subscribersGained, subscribersLost, likes`. Errors return an empty list.
+- Post level: `PostsService.checkPostAnalytics` (`posts.service.ts`) calls `provider.postAnalytics`; YouTube uses Data API `videos.list part=statistics` (views, likes, comments, favorites) as a single "today" point. Pulled on demand, no stored history.
+
+## 9. Public API and MCP
+
+- Public API: `apps/backend/src/public-api/routes/v1/public.integrations.controller.ts` under `/public/v1`: `POST /upload`, `POST /upload-from-url`, `GET/POST /posts`, `DELETE /posts/:id` and `/posts/group/:group`, `GET /integrations`, `GET /find-slot/:id`, `GET /media`, `GET /media/:id/status`, `GET /groups`, `GET /notifications`, post analytics, debug endpoints. Auth (`apps/backend/src/services/auth/public.auth.middleware.ts`): raw `Authorization` header holding either the organisation API key (looked up in `Organization.apiKey`, stored encrypted) or an OAuth access token prefixed `pos_` issued to third-party OAuth apps. Throttled.
+- MCP: `libraries/nestjs-libraries/src/chat/start.mcp.ts` uses Mastra's `MCPServer` (`@mastra/mcp`) mounted on the backend (Streamable HTTP and SSE paths such as `/mcp`, `/mcp/:id`, `/sse/:id`). Auth: org API key, or OAuth 2.1 with RFC 8414 authorization server metadata, RFC 9728 protected resource metadata, dynamic client registration (`/mcp-oauth-dynamic`), fixed clients for ChatGPT and HubSpot, scopes `mcp:read`, `mcp:write`. Self-hosted instances can be relayed via `psh_` tokens (`mcp.relay.service.ts`). Tools (`chat/tools/tool.list.ts`): list integrations and groups, validate a post for a channel, trigger provider functions, schedule post, list posts, post settings schema, delete post, upload from URL, list media, media status, upload widget (an MCP Apps `ui://` iframe), and AI image, video and clipping tools (hidden from the Claude directory endpoint).
+
+## Adopt / Adapt / Avoid for Twiligent
+
+Constraints: Hono on Workers with cron, Supabase Postgres, optional Upstash Redis, Cloudinary, no new runtime dependencies, free tiers, two schedulers claiming due posts.
+
+### Adopt (fits as is, no new infrastructure)
+
+1. **YouTube resumable upload as a state machine.** Start session, store the session URI, upload chunks in multiples of 256 KiB with `Content-Range`, probe with `bytes */<size>` before every resume. The video exists only after the last byte, so a retry cannot duplicate it. Pure `fetch`, no `googleapis` needed.
+2. **Probe before you act.** Every resume first asks the platform what it committed. Pairs with Twiligent's rule that an unknown outcome is never re-sent without a person.
+3. **"Unconfirmed" as its own failure.** Distinguish platform rejected (safe to retry by hand), never started (safe to retry automatically) and outcome unknown (warn the user to check the channel first).
+4. **`PublishedWithError`.** If the video is live but thumbnail or another follow-up step failed, save the video id and URL, then report the error. Never lose the id of a live post.
+5. **Error mapping per provider.** A `handleErrors(body, status)` table from YouTube reason codes (`uploadLimitExceeded`, `defaultVideoInsertPerDayPerProject`, `invalidTitle`, `youtubeSignupRequired`, `invalid_grant`, thumbnail errors) to a typed error kind plus a message a person can act on. Matches `lib/errors.ts` and the copy rules.
+6. **Flag-once notifications.** `UPDATE ... SET refresh_needed = true WHERE id = $1 AND refresh_needed = false` and notify only if one row changed. Stops repeated cron failures from spamming.
+7. **Never overwrite a stored refresh token with an empty one**, and request `access_type=offline` with `prompt=consent` for Google.
+8. **Scope check at connect time** (Google `tokeninfo`) so a partially granted consent is refused with a clear message.
+9. **Server-side validation per provider**: settings validator (title 1 to 100, privacy enum, made-for-kids, 500 character tag budget with the quote rule) and a media check before scheduling.
+10. **Media type sniffing and size caps** before accepting an upload; and reading media from storage with HTTP Range so the Worker never buffers a whole video.
+11. **A provider interface** with `authenticate`, `refreshToken`, `publishStart`, `checkStatus`, `finalize`, `analytics`, `postAnalytics`, plus metadata (`scopes`, `validate`, `maxLength`) and a static registry array. Generic code calls the interface, never `if (platform === ...)`.
+
+### Adapt (good idea, needs reshaping for Workers + Postgres + cron)
+
+1. **Durable workflow state goes into Postgres, not Temporal history.** Store `upload_uri`, `video_size`, `uploaded_bytes`, `video_id`, `phase` (`starting | uploading | finalizing | done`) and `attempts` on the scheduled post (inside `data` through the merge functions or as columns via migrations). Each cron tick claims a due row, advances it one bounded step, and saves the new offset. Postiz's 4 minute batch becomes "as many 8 MiB chunks as fit in the Worker's CPU and wall budget" (on free Workers, likely one or a few chunks per invocation; benchmark first). The GitHub Actions scheduler has more time and could finish larger uploads.
+2. **Claiming instead of workflow ids.** Twiligent's existing claim (conditional update of a due row) plays the role of `post_<id>` plus terminate-existing. Add a lease timestamp so a claim abandoned mid-step can be reclaimed, and make every step idempotent through the probe.
+3. **Heartbeat semantics** become "step started at" and "step finished at" columns. A claimed row with a start but no finish is "outcome unknown" for non-idempotent steps (session creation is safe; YouTube creates nothing until the last byte), but safe to re-probe for uploads.
+4. **Missing-posts sweep.** Postiz's hourly sweep becomes the cron itself, but follow their rule: every exit path writes a terminal state so the sweep can never re-publish.
+5. **Repeat-post re-anchoring** if recurring posts are added: roll a stale anchor to the next interval rather than firing immediately.
+6. **Analytics cache** with a 1 hour TTL per `(user, account, range)`, already matching Twiligent's Redis-optional cache; YouTube Analytics `reports.query` with `dimensions=day` gives daily series in one call.
+7. **Token refresh**: lazily before use, plus a cron pass for tokens expiring within a day; no long-sleeping refresh workflow.
+8. **Cloudinary as the source**: Postiz streams from R2 with Range requests; check that Cloudinary delivery URLs answer `206` to `Range` with identity encoding and a correct `Content-Length` (their code fails fast when a store ignores Range). Plan a fallback if it does not.
+9. **Narrower scopes**: use `youtube.upload`, `youtube.readonly`, `yt-analytics.readonly`, and `youtube.force-ssl` only if custom thumbnails are offered. Fewer scopes ease Google verification.
+10. **Fixed retry delays**: Postiz uses fixed waits (5 s HTTP, 2 minute activity). On cron, express retries as `next_attempt_at` with a capped count; consider exponential backoff for 429 and 5xx.
+11. **Public API and MCP**: the shape (API key or OAuth token, a small tool set: list accounts, validate, schedule, list posts, delete, upload from URL) is a good model for a later Twiligent MCP; use Hono and plain JSON-RPC rather than a framework, and keep it behind a separate issue.
+
+### Avoid
+
+1. **Temporal (and BullMQ).** Temporal needs its own server, Postgres and Elasticsearch; BullMQ needs a persistent Redis with blocking commands that Upstash REST and Workers cannot hold. Neither fits a free-tier self-hoster. Postgres plus cron covers the need.
+2. **Frozen versioned workflow files** (twelve `post.workflow.v1.x` copies). A Postgres state machine with explicit phases can be migrated normally.
+3. **Plain-text platform tokens.** Postiz stores `token` and `refreshToken` unencrypted. If Twiligent encrypts tokens, use Web Crypto AES-GCM with a random IV per value, not their fixed-IV AES-CBC with an MD5-derived key.
+4. **Soft-deleting media without removing objects.** Twiligent should delete the Cloudinary asset after a successful publish or on a retention schedule, or storage grows forever.
+5. **Swallowing analytics errors into empty arrays.** Postiz returns `[]` on any analytics failure; Twiligent's UI rules need a distinct error state.
+6. **Heavy libraries in the Worker** (`googleapis`, `sharp`, the AWS SDK, Mastra). All the YouTube calls used here are plain REST and fit `fetch`.
+7. **One Post row holding settings and media as JSON strings** without types. Keep shared types in `shared/types/` and validate on write.
+8. **Copying any code.** The repository is AGPL-3.0.
diff --git a/docs/platform-v2/research/security-skills.md b/docs/platform-v2/research/security-skills.md
new file mode 100644
index 0000000..cfd42cd
--- /dev/null
+++ b/docs/platform-v2/research/security-skills.md
@@ -0,0 +1,419 @@
+# Security skills research: Cloudflare security-audit and Trail of Bits skills
+
+Research date: 2026-11-05. Read only; nothing was installed and no script, installer or hook from either repository was run.
+
+Clones studied (depth 1):
+
+- `cloudflare/security-audit-skill` at commit `c1c8a8c1471069fb0e188eeaff69b8e8db6564a8` (2026-09-14)
+- `trailofbits/skills` at commit `470419e16f97e112d01fc32f4898aea1755015d9` (2026-11-04). The repository has no git tags.
+
+Local copies were shallow clones in a temporary folder outside the repository.
+
+Claude Code docs checked: code.claude.com `settings`, `settings-reference` (`enabledPlugins`, `extraKnownMarketplaces`), `plugins/org`, `plugins/install`, `plugins/marketplace-reference`, `plugins/manifest-reference`, `workflows`, `sandboxing`. Local Claude Code version: 2.1.296.
+
+---
+
+## 1. Licences
+
+### Cloudflare security-audit-skill: `MIT`
+
+- Copyright (c) 2025-2026 Cloudflare, Inc.
+- Referencing or installing it (plugin, `npx skills add --global`, a link in docs): no obligation.
+- Copying files into the Twiligent repository (for example `.claude/skills/security-audit/`): keep the copyright line and the MIT permission notice with the copy. The skill folder does not contain the LICENSE file (it sits at the repository root), so a copy needs the notice added, for example a section in `THIRD_PARTY_NOTICES.md` like the existing Intent UI entry. No share-alike; modified copies can stay MIT. Compatible with Twiligent's own MIT licence.
+
+### Trail of Bits skills: `CC-BY-SA-4.0`
+
+- The whole repository, including scripts and workflow `.js` files, is under Creative Commons Attribution-ShareAlike 4.0 International.
+- Referencing or installing through the plugin marketplace (files stay in the Claude Code plugin cache, not in the repository): no obligation.
+- Copying files verbatim into the repository: attribution required (credit Trail of Bits, link the licence, link the source, say whether changes were made). The copied files stay CC BY-SA 4.0; they cannot be relicensed as MIT.
+- Copying and changing them (for example stripping emojis and em dashes to meet project rules, or adapting a skill to the stack): the result is Adapted Material, and ShareAlike requires the adapted files to be licensed CC BY-SA 4.0 (or a BY-SA compatible licence), with attribution and a note of the changes. The rest of the MIT repository is unaffected, but the repository becomes mixed-licence and `THIRD_PARTY_NOTICES.md` must say which files are CC BY-SA.
+- The Semgrep skill clones `trailofbits/semgrep-rules` at scan time; those rules are AGPLv3. Using them as scan configuration does not put Twiligent under AGPL; copying them into the repository would.
+- Recommendation: reference both repositories (marketplace install), do not vendor. Write Twiligent's own guidance (CLAUDE.md, a short project skill) in the project's words rather than adapting Trail of Bits text.
+
+---
+
+## 2. Structure and skill format
+
+### Cloudflare security-audit-skill
+
+```
+LICENSE
+README.md
+skills/security-audit/
+ SKILL.md entry point
+ RECONNAISSANCE.md phase 1
+ HUNTING.md phase 2 orchestration and hunter prompt
+ ATTACK-CLASSES.md core, wildcard and "obvious things" classes
+ VALIDATION-AND-REPORTING.md phases 3 to 6
+ WEB-PROTOCOL-AND-AUTH.md companion: HTTP, JWT, OAuth/OIDC, sessions, API keys
+ CLIENT-SIDE.md companion: SPA, DOM, postMessage, CORS, storage
+ SUPPLY-CHAIN-AND-RELEASE.md companion: dependencies, CI, release, signing
+ CLOUD-AND-DEPLOYMENT.md companion: IAM, serverless, edge workers, config and secrets
+ PROTOCOLS-RPC-AND-MESSAGING.md companion: webhooks, queues, RPC
+ RESOURCE-EXHAUSTION-AND-AVAILABILITY.md companion: quotas, workers, operator spend
+ DATA-ISOLATION-AND-LIFECYCLE.md companion: tenant isolation, row-level policy, caches, export, deletion
+ AI-AND-LLM.md, MEMORY-SAFETY-AND-BINARY.md, DESKTOP-MOBILE-AND-LOCAL-IPC.md companions not relevant here
+ report-schema.json JSON schema for findings.json
+ validate-findings.cjs (+ .test.cjs) zero-dependency Node validator
+ validate-coverage-ledger.cjs (+ .test.cjs) zero-dependency Node validator
+```
+
+- One skill. Frontmatter has only `name: security-audit` and `description`. No `allowed-tools`, no agents, no commands, no hooks, no plugin manifest, no `.claude-plugin/marketplace.json`.
+- Agent-neutral: it speaks of a "parent", a "Task tool", and two delegated roles (`research`, `general`), which map to Claude Code subagents.
+- Only executable parts are the two `.cjs` validators (Node, no dependencies). Node 22 is present, so they run on this machine.
+
+### Trail of Bits skills
+
+```
+.claude-plugin/marketplace.json marketplace "trailofbits", 46 plugins, every source a relative path ./plugins/<name>
+plugins/<name>/
+ .claude-plugin/plugin.json name, version, description, author
+ skills/<skill>/SKILL.md frontmatter: name, description, optional allowed-tools (space separated), optional effort
+ skills/<skill>/references/ detail files loaded on demand
+ skills/<skill>/scripts/ Python (run with uv) and bash helpers
+ skills/<skill>/workflows/ prose step guides
+ skills/<skill>/agents/openai.yaml Codex/ChatGPT display metadata (ignored by Claude Code)
+ skills/<skill>/assets/trail-of-bits-mark.svg
+ agents/*.md subagents (frontmatter: name, description, tools list)
+ commands/*.md slash commands (description, argument-hint, allowed-tools)
+ workflows/*.js Claude Code dynamic workflows, run as /<plugin>:<meta.name>
+ hooks/hooks.json event hooks (only fp-check, gh-cli, modern-python)
+ evals/, tests/ maintainers' test suites
+AGENTS.md, CLAUDE.md (@AGENTS.md), Makefile, ruff.toml, .pre-commit-config.yaml
+```
+
+- Dynamic workflows (`workflows/*.js`) need the Claude Code Workflow tool. Docs: available on all paid plans and the API; on Pro it must be turned on in `/config`. Plugins that depend on it: `insecure-defaults` (command calls the workflow), `audit-context-building`, `variant-analysis` (`/variant-analysis:variants`), `static-analysis` (`/static-analysis:semgrep-scan`, `/static-analysis:codeql-build`), `spec-to-code-compliance`, `post-patch-validation`, `c-review`, `code-improver`, `git-cleanup`, `semgrep-rule-variant-creator`.
+- Hooks that install with a plugin:
+ - `fp-check`: `Stop` and `SubagentStop` prompt hooks that run on every stop of every session while the plugin is enabled (an extra model call each time; it answers `ok` when the session is not an fp-check session, but still costs a call).
+ - `gh-cli`: `SessionStart` bash scripts that install a PATH shim for `gh`, `PreToolUse` hooks on every `Bash`, `WebFetch` and MCP fetch call, and a `SessionEnd` cleanup. It changes how every session behaves.
+ - `modern-python`: hooks, not relevant to this stack.
+ - Recommendation: do not enable these three at project scope.
+
+---
+
+## 3. Installing in Claude Code
+
+### Trail of Bits: a real plugin marketplace
+
+Commands inside a session:
+
+```
+/plugin marketplace add trailofbits/skills
+/plugin install differential-review@trailofbits
+/plugin install static-analysis@trailofbits
+```
+
+From a shell (scope flag supported):
+
+```
+claude plugin marketplace add trailofbits/skills
+claude plugin install differential-review@trailofbits --scope project
+```
+
+- Marketplace name is `trailofbits` (from `marketplace.json`), so plugin ids are `<plugin>@trailofbits`.
+- Pinning: a GitHub marketplace source takes `ref` (branch or tag) but not `sha`. The repository has no tags, so the only pins are `main` or a fork you control (for example fork to `spacesdrive/trailofbits-skills` and pin a tag there). Third-party marketplaces default to `autoUpdate: false`, so installed plugins stay at the installed version until someone runs `/plugin marketplace update`.
+
+### Cloudflare: no marketplace
+
+The supported method in its README is the Skills CLI:
+
+```
+npx skills add https://github.com/cloudflare/security-audit-skill --skill security-audit (project install, copies files into the repo)
+npx skills add https://github.com/cloudflare/security-audit-skill --skill security-audit --global (user install, outside the repo)
+```
+
+The project install copies MIT files containing em dashes into the repository (see section 7) and needs a notice entry. The global install avoids both but is per person.
+
+Alternative that keeps it out of the repository and shared through settings: declare an inline `settings` marketplace whose one plugin points at the Cloudflare repository pinned to a commit. Per the manifest reference the plugin manifest is optional, and without one Claude Code loads the standard layout, which includes `skills/` at the plugin root, which is exactly where this repository keeps `skills/security-audit/`. This follows the documented rules but was not tested here. The skill would show as `security-audit:security-audit`.
+
+### Project settings so every contributor gets them
+
+Keys confirmed in the settings reference: `extraKnownMarketplaces` (object: marketplace name to `{ source, autoUpdate? }`) and `enabledPlugins` (object: `plugin@marketplace` to boolean). Both may be set in the shared `.claude/settings.json`.
+
+```json
+{
+ "extraKnownMarketplaces": {
+ "trailofbits": {
+ "source": { "source": "github", "repo": "trailofbits/skills", "ref": "main" }
+ },
+ "cloudflare-security": {
+ "source": {
+ "source": "settings",
+ "name": "cloudflare-security",
+ "plugins": [
+ {
+ "name": "security-audit",
+ "source": {
+ "source": "github",
+ "repo": "cloudflare/security-audit-skill",
+ "sha": "c1c8a8c1471069fb0e188eeaff69b8e8db6564a8"
+ }
+ }
+ ]
+ }
+ }
+ },
+ "enabledPlugins": {
+ "differential-review@trailofbits": true,
+ "insecure-defaults@trailofbits": true,
+ "sharp-edges@trailofbits": true,
+ "static-analysis@trailofbits": true,
+ "supply-chain-risk-auditor@trailofbits": true,
+ "variant-analysis@trailofbits": true,
+ "audit-context-building@trailofbits": true,
+ "security-audit@cloudflare-security": true
+ }
+}
+```
+
+How it behaves (from `plugins/org` and the settings reference):
+
+- `extraKnownMarketplaces` from a repository file applies only after the contributor accepts the workspace trust dialog for the folder. In an untrusted folder, and in `-p` runs in a folder never trusted interactively, it is ignored silently.
+- Trail of Bits plugins are listed by relative path, so once the marketplace is registered they load from the marketplace copy with no extra step.
+- The Cloudflare entry points at an external GitHub source, so `enabledPlugins` alone does not install it: each contributor sees "enabled in project settings but isn't installed" until they run once:
+ `claude plugin install security-audit@cloudflare-security --scope project`
+- A contributor can opt out locally by setting a plugin to `false` in `.claude/settings.local.json`.
+- Optional but useful: `autoUpdate` stays off (the default for third-party marketplaces) so a skill does not change under the team without a reviewed bump.
+
+---
+
+## 4. Cloudflare security-audit: how it works
+
+### Modes
+
+- Guidance mode (default): for questions, focused reviews, triage of one finding. Uses only relevant parts, writes no files, may launch focused agents.
+- Full audit mode: only when explicitly asked to audit or pen-test the codebase, for a full or end-to-end review, or when report artifacts are requested. If the request is ambiguous it must ask one question first.
+
+### Execution rules (both modes)
+
+- Source review is read-only. Target-controlled builds, tests or processes may run only inside an OS-enforced sandbox with no network, an empty allowlisted environment, read-only target and toolchain, scratch-only writes and resource limits. If any control is missing it does not execute and keeps the lead as `needs_validation`.
+- No probing of deployed endpoints, providers, shared services, production identities or paid APIs. No installing or fetching dependencies.
+- Consequence here: Claude Code's sandbox runs on macOS, Linux and WSL2 only; on native Windows commands run unsandboxed. So on this machine the skill will be source-only, and leads that need execution end as `needs_validation`. Running Claude Code inside WSL2 with `/sandbox` would allow bounded local checks.
+
+### Full audit setup
+
+- Resolves skill dir, target, repo name, source ref (commit and dirty state) and an output directory outside the target, default `~/security-audit-skill/<repo-name>/run-<N>`. Inside the repo only if the user picks a git-ignored directory.
+- Writes `run-metadata.json` first. Only the parent writes shared files; each subagent gets `agents/<id>/scratch/` and a parent-owned `artifacts/`.
+- Profiles: `quick` (coarse ledger, one hunter wave, one critic, one verifier per candidate), `standard` (default), `deep` (per subsystem and lifecycle, critic waves to a clean pass, separate verifiers). Scoped runs cover named paths, a subsystem or the diff between two refs; everything else is `out_of_scope`. Optional budget measured in agent invocations, with reserves for critics and verifiers.
+- Repeat runs are additive: prior `coverage-ledger.json` and `findings.json` are read and drive the next run.
+
+### Six phases
+
+1. Reconnaissance: four parallel `research` agents map (1a) product, stack, entry points and offline build/test commands; (1b) principals, authentication, authorization, tenant scope, privilege changes; (1c) every entry surface, transformation and sink; (1d) local test fixtures, prohibited commands, deployment facts source cannot establish, and whether sandbox controls exist. Parent writes `architecture.md` (about 1,000 words max) and seeds `coverage-ledger.json`: one unit per surface x trust boundary x subsystem x attack class, with stable percent-encoded `coverage_id`s. Runs `validate-coverage-ledger.cjs` after every ledger change.
+2. Coverage-led hunting: `general` hunter agents take ledger units in priority order (unauthenticated surfaces first, most valuable resources next, then prior gaps). Each hunter gets `architecture.md`, its units, the exact attack-class blocks copied verbatim, exclusions, the hunting method and validation rules, and must return one JSON object. Coverage-critic agents look for gaps between waves.
+3. Candidate validation: every unique candidate goes to a fresh verifier that did not find it and tries to refute it. Returns `confirmed`, `needs_validation` or `rejected`.
+4. Structured output: `findings.json` written against `report-schema.json`, checked with `validate-findings.cjs` and the ledger validator.
+5. Independent record verification: a fresh agent per final record re-checks every path, line, condition, severity and fix. Material changes go to yet another fresh verifier.
+6. Reporting: `REPORT.md`, `FINDINGS-DETAIL.md` (medium and above), `NEEDS-VALIDATION.md`.
+
+### What it checks
+
+- Core classes in `ATTACK-CLASSES.md`: injection (including second-order and into logs or caches), access control (authentication without authorization, field overrides, batch and export paths), resource and file handling (path traversal, SSRF, deserialization, TOCTOU), cryptography and secrets (weak randomness, hardcoded secrets, missing HMAC checks, timing-unsafe comparison, fail-open crypto errors), business logic (state machines, races, time windows, defaults when config is missing), feature abuse and data leakage (export, import, search as oracle, enumeration, webhook SSRF), chained trust-boundary failures, a wildcard hunter, and an "obvious things" checklist (secrets in source, security TODOs, debug gates, open endpoints, committed `.env`, pinned dependencies and CVEs, `eval`, permissive CORS, cookie flags, open redirects, stack traces in errors).
+- Companions that match Twiligent: WEB-PROTOCOL-AND-AUTH (JWT checks: signature, pinned algorithm, `exp`/`nbf`/`aud`/`iss`; OAuth state, PKCE, redirect_uri; API keys in bundles), CLIENT-SIDE (React SPA), CLOUD-AND-DEPLOYMENT (edge worker identity, config and secret lifecycle, edge vs origin mismatches, provider events trusted without signed envelopes), DATA-ISOLATION-AND-LIFECYCLE (row-level policy vs bypass clients: directly relevant to RLS plus a service-key backend), PROTOCOLS-RPC-AND-MESSAGING (Instagram webhooks), RESOURCE-EXHAUSTION-AND-AVAILABILITY (rate limits, operator API spend), SUPPLY-CHAIN-AND-RELEASE (GitHub Actions, dependencies).
+
+### Tools it runs
+
+None beyond the two Node validators. Everything else is the agent reading source, plus bounded sandboxed local checks when a sandbox exists.
+
+### Report format and severity
+
+- Verdicts: `confirmed` (complete source trace and bounded observed result), `needs_validation` (exact unresolved blocker, a local or owner-observed validation plan, no severity), `rejected` (kept so later runs do not repeat it).
+- Severity only on `confirmed`: likelihood, impact and overall, each one of `informational`, `low`, `medium`, `high`, `critical`; overall may not exceed impact. Confidence `low`, `medium`, `high`. Anchors: critical = unauthenticated code execution, full data-store access or arbitrary account takeover; high = full defeat of an explicit control (auth bypass, cross-tenant read or write, stored XSS on others, authenticated RCE); medium = real boundary violation with limited blast radius; low = non-secret internals or high-effort minimal gain; informational = minimal impact.
+- `REPORT.md`: run profile, scope, budget, source ref, coverage statement (partial runs must say so); posture summary; confirmed findings table; per finding: location, lower-trust principal, bounded reproduction, conditions, result, impact, priority rationale, smallest fix; a separate NEEDS VALIDATION table; hardening notes and positive patterns; ledger coverage counts.
+
+### Remediation guidance
+
+For each confirmed finding: name the invariant the code must enforce and the narrowest source change at the last trusted decision point, with repository-relative changes and a regression test. It describes fixes; it never edits the target. Defense-in-depth gaps where another layer already blocks the attack are hardening notes, not findings.
+
+---
+
+## 5. Trail of Bits: every plugin (46)
+
+| Plugin | One line |
+| --- | --- |
+| agentic-actions-auditor | Audits GitHub Actions workflows that run AI agents (Claude Code Action, Codex, Gemini CLI) for prompt-injection paths |
+| audit-context-building | Builds a function-by-function understanding dossier before bug hunting (dynamic workflow) |
+| building-secure-contracts | Smart-contract scanners for six blockchains and guideline assistants |
+| burpsuite-project-parser | Searches Burp Suite `.burp` project files |
+| c-review | C/C++ security review with parse-verified coverage |
+| chrome-mcp-troubleshooting | Fixes Claude in Chrome MCP connectivity |
+| code-improver | Autonomous review-and-fix loop with a pluggable reviewer |
+| constant-time-analysis | Compiler-induced timing side channels in crypto code |
+| culture-index | Interprets Culture Index survey results |
+| devcontainer-setup | Creates devcontainers with Claude Code and language tooling |
+| differential-review | Security review of a PR, commit or diff with git history and blast radius |
+| dimensional-analysis | Unit and decimal-scaling bug audit with unit annotations |
+| dwarf-expert | DWARF debug info analysis |
+| entry-point-analyzer | State-changing entry points in smart contracts |
+| firebase-apk-scanner | Firebase misconfigurations in Android APKs |
+| fp-check | Verifies a suspected bug as true or false positive with gated phases (installs Stop hooks) |
+| gh-cli | Redirects GitHub fetches to `gh` (installs PATH shim and Bash/WebFetch hooks) |
+| git-cleanup | Safe cleanup of local branches and worktrees |
+| github-triage | Triage and merge of open issues and PRs via `gh` |
+| goal-prompt | Drafts `/goal` commands |
+| insecure-defaults | Fail-open defaults, fallback secrets, default credentials, weak crypto, permissive access, debug leakage |
+| let-fate-decide | Tarot draw for vague planning |
+| modern-cpp | Modern C++ practices |
+| modern-python | Modern Python tooling (has hooks) |
+| mutation-testing | mewt/muton mutation campaigns and survivor triage |
+| open-sourcing | Prepares a repository for public release: secret history, licence, CI readiness |
+| patching-bugs | Reproduce, patch and prove one known bug |
+| post-patch-validation | Checks a security patch for missed variants and regressions |
+| property-based-testing | Writes and reviews property tests (Hypothesis, fast-check, proptest) |
+| regression-hunt | Finds and replays regressions across PRs and commits |
+| review-walkthrough | Interactive HTML walkthrough of branch changes |
+| rust-review | Rust security review |
+| second-opinion | Independent review from Codex or Antigravity CLIs |
+| semgrep-rule-creator | Writes and tests custom Semgrep rules |
+| semgrep-rule-variant-creator | Ports Semgrep rules to other languages |
+| sharp-edges | Footgun APIs, dangerous configuration, insecure-by-default designs |
+| spec-to-code-compliance | Checks code against the documentation that specifies it |
+| static-analysis | Semgrep, CodeQL and SARIF parsing skills plus scan workflows |
+| supply-chain-risk-auditor | npm/PyPI/Go dependency advisories, abandonment, publisher concentration, install scripts |
+| testing-handbook-skills | Testing Handbook skills: fuzzers, sanitizers, coverage, Wycheproof |
+| trailmark | Code graphs, context slicing, diagrams, mutation triage, protocol modelling |
+| variant-analysis | Finds other instances of a known bug, generalizes to Semgrep/CodeQL |
+| vulnerability-triage-brocards | Triage of incoming vulnerability reports with seven rules of thumb |
+| writing-lean-proofs | Lean 4 proofs |
+| yara-authoring | YARA-X rule authoring |
+| zeroize-audit | Missing zeroization of secrets in C/C++ and Rust |
+
+### Relevant to Twiligent: workflow, tools, Windows status
+
+Windows facts used below: Git Bash present; Node 22.18.0; Python 3.12.9; pip 26.2.1; uv 0.12.5; gh logged in as spacesdrive; Docker 29.6.2; semgrep 1.174.0 installed (pip, Python 3.12); codeql, osv-scanner, gitleaks and jq not installed.
+
+**differential-review** (plugin `differential-review`, command `/differential-review:diff-review <pr-url|commit-sha|diff-path> [--baseline <ref>]`, agent `differential-review:adversarial-modeler`)
+- Workflow: pre-analysis baseline (optionally via audit-context-building), Phase 0 triage (diff stats, size class SMALL/MEDIUM/LARGE, risk per file HIGH/MEDIUM/LOW), Phase 1 changed-code analysis with `git blame` on removed code, Phase 2 test coverage of changed code, Phase 3 blast radius by counting callers, Phase 4 deep context on HIGH files, Phase 5 adversarial modelling, Phase 6 markdown report with CRITICAL/HIGH/MEDIUM/LOW counts and APPROVE/REJECT/CONDITIONAL.
+- Tools: git, gh. Works on Windows.
+- Caveats: methodology says `git checkout <baseline_commit>` (mutates the working tree; use a worktree instead); the report defaults to the current working directory (the repo) as `<PROJECT>_DIFFERENTIAL_REVIEW_<DATE>.md`; templates are smart-contract flavoured and use emojis.
+
+**insecure-defaults** (command `/insecure-defaults:audit [path]`, workflow `audit-pipeline`)
+- Workflow: Recon (Sonnet) profiles stack and deploy manifests and finds config wrappers; Discover (6 Sonnet sweeps in parallel, one per category: fallback secrets, default credentials, fail-open switches, weak crypto, permissive access, debug leakage) using grep seeds plus stack-derived patterns; Verify (Opus refuting agents, up to 16 candidates each, start at refuted and stop at the first kill step: reachable in prod, value actually used, actually insecure, reaches a security decision, does deployment always set the variable); Report (severity CRITICAL to LOW, remediation, coverage gaps).
+- Tools: none external (grep). Needs dynamic workflows. Works on Windows.
+- Good fit: Worker env bindings (`c.env.X ?? 'default'`), CORS config, fallback secrets in `wrangler.toml`/`.dev.vars` templates, debug error output.
+
+**sharp-edges** (skill and agent `sharp-edges-analyzer`, tools Read Grep Glob only)
+- Workflow: surface identification, edge-case probing (zero, empty, null), threat modelling, validation. Categories include algorithm selection (JWT `alg`), dangerous defaults, primitive vs semantic APIs, timing-unsafe comparison, configuration footguns. Has `lang-javascript.md`.
+- Tools: none. Works on Windows. Useful for `backend/lib/` helpers, rate-limit config, webhook signature checks, JWT verification code.
+
+**static-analysis** (skills `semgrep`, `codeql`, `sarif-parsing`; workflows `/static-analysis:semgrep-scan {"target":"/abs/path","mode":"run-all"}` and `/static-analysis:codeql-build`)
+- Semgrep workflow: detect languages and Pro; pick mode (run all, or important only = WARNING/ERROR plus security category with medium/high confidence and impact); select rulesets (baseline `p/security-audit`, `p/secrets`; TS gets `p/typescript`, `p/react`, `p/nodejs`; YAML gets `p/github-actions`; third-party `trailofbits/semgrep-rules`); hard approval gate; `scripts/run-scans.sh` runs everything with `--metrics=off`; `merge_sarif.py` (via uv) merges to `results/results.sarif`; report includes failed and skipped scans.
+- Semgrep tools: semgrep, bash, jq, git, uv. On Windows: semgrep CLI has native Windows support (public beta July 2025, announced GA autumn 2025; PyPI ships a win_amd64 wheel, latest 1.183.0) and 1.174.0 already runs here. jq is missing and `run-scans.sh` exits without it (install with `winget install jqlang.jq`). The script targets bash 3.2+, so Git Bash should work, but Trail of Bits does not test on Windows. Semgrep Pro (cross-file taint) needs a Semgrep login and licence; OSS works without.
+- Default output directory is `./static_analysis_semgrep_N` in the current directory, which would land in the repo; pass an output directory outside it.
+- CodeQL workflow: build database (JS/TS needs no build), data extensions for project wrappers (for example the repository layer around Supabase), run an explicit `.qls` suite (security-and-quality plus security-experimental, or high-precision only), quality checks so zero findings are not taken as clean.
+- CodeQL tools: codeql CLI, jq, uv, bash. CodeQL CLI is published for Windows x64 (`codeql-bundle-win64`, or `gh extension install github/gh-codeql`), not installed here. Practical alternative: GitHub code scanning with CodeQL in CI, free for public repositories such as Twiligent.
+
+**supply-chain-risk-auditor**
+- Workflow: confirm manifests; check `gh auth status`; `uv run collect.py <project> --json <out>/findings.json`, then `uv run render.py ... --out <out>/report.md`; the agent adds upgrade paths, replacements and whether `npm ci --ignore-scripts` is viable. Criteria: version-matched OSV advisories for direct deps and the full `package-lock.json` tree, archived or abandoned upstreams, npm publisher concentration, install scripts, OpenSSF Scorecard.
+- Tools: Python 3.11+ stdlib, uv, network access to OSV, npm, deps.dev, GitHub, Scorecard APIs; gh token recommended. osv-scanner and pip-audit are optional cross-checks only. All present except osv-scanner; works on Windows.
+- Monorepo caveat: direct-dependency criteria read only the `package.json` in the target directory. Twiligent's root has the shared dev tooling, while `hono`, `@supabase/supabase-js`, React and so on are declared in `backend/`, `frontend/` and `site/`. The transitive advisory sweep of the root `package-lock.json` still covers everything. For full direct-dependency coverage run it on each workspace too (without a lockfile there, versions fall back to latest release).
+
+**variant-analysis** (skill, workflow `/variant-analysis:variants`)
+- Workflow: root cause, exact-match pattern, generalize one element at a time, triage with severity, report with a CI rule. Ships `resources/semgrep/javascript.yaml` and `resources/codeql/javascript.ql` starters.
+- Tools: grep at minimum; semgrep or codeql for structural search. Works on Windows with the installed semgrep.
+- Twiligent use: after any finding, for example one user-scoped query missing `.eq('user_id', userId)`, find all others.
+
+**semgrep-rule-creator**
+- Writes and tests custom Semgrep rules. Tools: semgrep. Works here.
+- Twiligent use: encode project invariants as CI rules, such as `fetch(` outside `frontend/src/services/api.ts`, Supabase queries outside `backend/repositories/`, `...ForUser` methods without a `user_id` filter, `SUPABASE_SERVICE_KEY` referenced outside the backend.
+
+**audit-context-building** (workflow `/audit-context-building:audit-context <path>`, agent `function-analyzer`)
+- Builds `audit-context/DOSSIER.md` and one file per function: invariants, assumptions and what establishes them, cross-function rules. No verdicts. Writes into `audit-context/` under the current directory. Needs dynamic workflows; no external tools. Optional pre-step for a full audit; expensive on a whole monorepo.
+
+**agentic-actions-auditor**
+- Static audit of GitHub Actions workflows that call AI agents: env var intermediaries, direct `${{ }}` injection, `pull_request_target` checkout, dangerous sandbox settings, wildcard allowlists. Tools: Read/Grep, optional gh. Works on Windows.
+- Twiligent today: none of `ci.yml`, `deploy-*.yml`, `publish-scheduled.yml` invoke an AI action, so it is relevant only if Claude Code Action is added later. General Actions hardening is covered by Semgrep `p/github-actions` and the Cloudflare SUPPLY-CHAIN companion.
+
+**property-based-testing**
+- Picks a property (roundtrip, idempotence, invariant, oracle) and writes fast-check tests for TS. Relevant to pure `lib/` helpers (rate-limit algorithms, scheduling rules in `scheduledPublishing.ts`, metric math). Requires adding `fast-check` as a dev dependency, which the project's "no dependencies without approval" rule gates. Tests would use `node:test`, matching the project.
+
+**fp-check**
+- Rigorous true/false-positive verification of a single suspected bug, with gate reviews and PoCs. Useful conceptually, but its Stop and SubagentStop prompt hooks fire in every session while enabled. Prefer enabling it only per person when needed. The Cloudflare skill's independent verifiers already cover this role in full audits.
+
+**spec-to-code-compliance** (optional)
+- Checks code against the documents that specify it, one agent per requirement. Twiligent's `docs/architecture/database/SECURITY.md`, `REQUEST_PIPELINE.md` and `AUTOMATION.md` state security invariants that this could check. Needs dynamic workflows.
+
+**post-patch-validation** (optional): after fixing a security bug, looks for missed variants and regressions. Python script via uv plus a workflow.
+
+**open-sourcing** (optional): secret-history hygiene for a public repository. The repo is already public; gitleaks over history is the more direct check.
+
+Not relevant: building-secure-contracts, entry-point-analyzer, c-review, rust-review, constant-time-analysis, zeroize-audit, dwarf-expert, firebase-apk-scanner, burpsuite-project-parser, yara-authoring, modern-cpp, modern-python, writing-lean-proofs, dimensional-analysis, culture-index, let-fate-decide, chrome-mcp-troubleshooting, gh-cli, git-cleanup, github-triage, goal-prompt, devcontainer-setup, review-walkthrough, second-opinion (needs Codex or Antigravity CLIs), mutation-testing (mewt supports `javascript/ts` but is not installed and is a heavier tool), trailmark, testing-handbook-skills (fuzzers and sanitizers for native code; Wycheproof only if crypto code is written), regression-hunt, code-improver, patching-bugs, vulnerability-triage-brocards (only if outside reports arrive), semgrep-rule-variant-creator.
+
+---
+
+## 6. Which skills for which job
+
+### (a) Full security audit of the app
+
+1. Cloudflare `security-audit`, full audit mode, `standard` profile (or `deep` for auth, webhooks and RLS), output directory outside the repo. Companions to expect: WEB-PROTOCOL-AND-AUTH, CLIENT-SIDE, CLOUD-AND-DEPLOYMENT, DATA-ISOLATION-AND-LIFECYCLE, PROTOCOLS-RPC-AND-MESSAGING, RESOURCE-EXHAUSTION-AND-AVAILABILITY, SUPPLY-CHAIN-AND-RELEASE. On native Windows it stays source-only.
+2. `static-analysis` Semgrep scan (run all) with TS, React, Node, GitHub Actions and Trail of Bits rules; optionally CodeQL (locally once installed, or GitHub code scanning in CI).
+3. `supply-chain-risk-auditor` on the root (lockfile sweep) and on each workspace.
+4. `insecure-defaults` on the whole repo.
+5. `sharp-edges` on `backend/lib/`, `backend/middleware/`, auth and webhook code.
+6. Optional: `audit-context-building` first on `backend/`; `spec-to-code-compliance` against the security docs; `variant-analysis` for each confirmed finding; a secret scan of git history with gitleaks.
+
+### (b) Targeted checks on a small change
+
+- Cloudflare `security-audit` in guidance mode on the touched files (no artifacts written).
+- `insecure-defaults` scoped to the changed path when config, env or defaults change.
+- `sharp-edges` when a new API, option or config surface is added.
+- Semgrep on the changed files (skill, or a direct `semgrep --metrics=off --config p/typescript --config p/secrets <files>`).
+- `supply-chain-risk-auditor` when a dependency is added or bumped.
+- `variant-analysis` when the change fixes a bug.
+- `property-based-testing` for new pure helpers (subject to dependency approval).
+
+### (c) Reviewing a pull request diff
+
+- `differential-review` via `/differential-review:diff-review <pr-url>` with the report written outside the repo.
+- Cloudflare `security-audit` as a scoped run over the diff between the base and head refs, `quick` profile, for PRs that touch auth, webhooks, repositories, migrations or CI.
+- Semgrep on the changed files (or a baseline diff scan).
+- `agentic-actions-auditor` if the PR adds or changes an AI agent step in `.github/workflows/`.
+- Claude Code's built-in `/security-review` command is also available for a quick pass on pending changes.
+
+---
+
+## 7. Conflicts with project rules
+
+| Rule | Where the skills conflict | Effect and handling |
+| --- | --- | --- |
+| No emojis | differential-review `reporting.md`: severity emojis in the summary table and headings, status emojis, and a notification template with emojis; semgrep `SKILL.md` and `workflows/scan-workflow.md` use a stop-sign symbol in instructions; sharp-edges `lang-swift.md` has an emoji in a code example | The differential-review report and its chat summary will contain emojis unless told otherwise. Add a project instruction: write reports in plain text, severity as words. Do not vendor these files |
+| No em dashes or en dashes | Counted em dashes: Cloudflare repo 36 (plus 2 en dashes), static-analysis 333, variant-analysis 155, property-based-testing 141, fp-check 111, supply-chain-risk-auditor 103, audit-context-building 90, sharp-edges 22, differential-review 9, insecure-defaults 2, agentic-actions-auditor 0 | Harmless while the files live in the plugin cache. Vendoring any of them (including `npx skills add` project install) puts em dashes into the repository. Generated reports may imitate the style; instruct plain hyphens |
+| No AI attribution in commits | No skill read here adds Co-Authored-By or "Generated with" lines. The Trail of Bits README invites "Found using Trail of Bits Skills" in bug reports (optional, not a licence requirement for use) | No conflict. Claude Code's own commit attribution is a separate harness setting the project already overrides |
+| Reports and files inside the repo | Semgrep and CodeQL default to `./static_analysis_*_N`, differential-review to the current directory, audit-context-building to `audit-context/` | Always pass an output directory outside the repo (or add these names to `.gitignore`). Cloudflare already defaults outside the target |
+| Do not disturb the working tree | differential-review methodology runs `git checkout <baseline_commit>` | Tell it to use `git worktree add` or `git show <ref>:<path>` |
+| No new dependencies without approval | property-based-testing needs `fast-check`; nothing else adds project dependencies (tools install on the machine, not in `package.json`) | Ask before adding fast-check |
+| Every task has a GitHub issue; the repository is public; no secrets in issues | Audit reports contain exploit paths | Track the audit task in an issue, but keep vulnerability details out of public issues; use GitHub private security advisories for confirmed findings |
+| Hooks and behaviour changes | fp-check Stop/SubagentStop hooks; gh-cli PATH shim and Bash/WebFetch hooks | Do not enable at project scope |
+
+---
+
+## 8. Tools on this machine
+
+| Command | Result |
+| --- | --- |
+| `semgrep --version` | 1.174.0 (pip, Python 3.12 Scripts folder; prints that a newer version exists; PyPI latest 1.183.0) |
+| `codeql version` | not found |
+| `osv-scanner --version` | not found |
+| `gitleaks version` | not found |
+| `python --version` | Python 3.12.9 (`python3` is the Microsoft Store alias and does not work; `py` works) |
+| `pip --version` | pip 26.2.1 (Python 3.12) |
+| also checked | uv 0.12.5, node v22.18.0, git (Git for Windows), gh (logged in as spacesdrive), Docker 29.6.2, Claude Code 2.1.296; jq not found; pipx not found |
+
+What each relevant skill needs and whether it is ready:
+
+| Skill | Needs | Ready on this machine |
+| --- | --- | --- |
+| Cloudflare security-audit | Node for validators; subagents; a sandbox for local execution | Yes for source-only audits; no sandbox on native Windows (WSL2 would add one) |
+| differential-review | git, gh | Yes |
+| insecure-defaults | dynamic workflows (Workflow tool) | Yes if the plan has workflows enabled |
+| sharp-edges | nothing | Yes |
+| static-analysis: semgrep | semgrep, jq, uv, git, bash | No until jq is installed (`winget install jqlang.jq`) |
+| static-analysis: codeql | codeql CLI, jq, uv, bash | No (CodeQL CLI Windows x64 bundle or `gh extension install github/gh-codeql`, plus jq) |
+| supply-chain-risk-auditor | uv, Python 3.11+, network, gh token | Yes |
+| variant-analysis | grep; semgrep or codeql optional; workflows for `/variants` | Yes with semgrep |
+| semgrep-rule-creator | semgrep | Yes |
+| audit-context-building, spec-to-code-compliance | dynamic workflows | Yes if workflows enabled |
+| agentic-actions-auditor | gh optional | Yes |
+| property-based-testing | fast-check dev dependency | Needs approval |
+| secret history scan (not a skill) | gitleaks | No (Windows x64 release binaries exist; Semgrep `p/secrets` and `p/gitleaks` are a partial substitute) |
+| osv-scanner (optional cross-check) | osv-scanner | No (`winget install Google.OSVScanner` or scoop); not required, the auditor calls the OSV API directly |
diff --git a/docs/platform-v2/research/youtube.md b/docs/platform-v2/research/youtube.md
new file mode 100644
index 0000000..d5229e3
--- /dev/null
+++ b/docs/platform-v2/research/youtube.md
@@ -0,0 +1,655 @@
+# YouTube video and Shorts publishing: research for Twiligent
+
+Researched 5 November 2026. Sources are Google's own docs unless stated. Each section separates
+**Verified** (read on the cited page) from **Inference** (my reasoning, not stated by a source).
+
+Headline changes since most guides and training data were written:
+
+1. **The private lock for unverified API projects is gone.** On 2 November 2026 Google reversed the
+ 28 July 2020 rule. Uploads from unaudited projects can be public, unlisted or scheduled.
+2. **videos.insert no longer costs 1,600 units.** Since 1 June 2026 it has its own quota bucket:
+ 100 calls per day, 1 unit per call. Every other method shares the old 10,000 units per day.
+3. **thumbnails.set now accepts files up to 50 MB** (was 2 MB), and since 3 November 2026 it can
+ set custom thumbnails on Shorts once processing has finished.
+
+---
+
+## 1. OAuth 2.0 for a web server app
+
+### Verified
+
+- Endpoints: authorization `https://accounts.google.com/o/oauth2/v2/auth`, token exchange and refresh
+ `https://oauth2.googleapis.com/token`, revocation `https://oauth2.googleapis.com/revoke`.
+ https://developers.google.com/identity/protocols/oauth2/web-server
+- YouTube scopes and what Google's consent screen says about each one
+ (https://developers.google.com/youtube/v3/guides/auth/server-side-web-apps):
+ - `youtube`: "Manage your YouTube account"
+ - `youtube.force-ssl`: "See, edit, and permanently delete your YouTube videos, ratings, comments and captions"
+ - `youtube.readonly`: "View your YouTube account"
+ - `youtube.upload`: "Manage your YouTube videos"
+ - `youtubepartner`: content owners (CMS) only
+- Scopes each method accepts:
+ - videos.insert: `youtube.upload`, `youtube`, `youtubepartner`, `youtube.force-ssl`
+ (https://developers.google.com/youtube/v3/docs/videos/insert)
+ - thumbnails.set: `youtubepartner`, `youtube.upload`, `youtube`, `youtube.force-ssl`
+ (https://developers.google.com/youtube/v3/docs/thumbnails/set)
+ - playlistItems.insert: `youtubepartner`, `youtube`, `youtube.force-ssl`. **Not `youtube.upload`.**
+ (https://developers.google.com/youtube/v3/docs/playlistItems/insert)
+ - videos.list: the `fileDetails`, `processingDetails` and `suggestions` parts "are only available to
+ that video's owner" (https://developers.google.com/youtube/v3/docs/videos/list)
+- `access_type=offline` makes Google return a refresh token "the first time that your application
+ exchanges an authorization code for tokens". The Node sample says "The refresh_token is only
+ returned on the first authorization." `prompt` accepts `none`, `consent`, `select_account`.
+ `include_granted_scopes=true` enables incremental authorization: the new token also covers scopes
+ granted earlier. https://developers.google.com/identity/protocols/oauth2/web-server
+- Revocation: POST `https://oauth2.googleapis.com/revoke` with `token=<access or refresh token>` and
+ `Content-Type: application/x-www-form-urlencoded`. Revoking an access token also revokes its refresh
+ token, and "Revocation removes all OAuth 2.0 scopes previously granted to a project". It may take
+ some time to take full effect. Same page.
+- Token response fields: `access_token`, `expires_in`, `refresh_token`, `refresh_token_expires_in`
+ (only set when the user grants time-based access), `scope`, `token_type`. Google now also supports
+ DPoP-bound tokens (optional). Same page.
+- Refresh token expiry reasons (https://developers.google.com/identity/protocols/oauth2#expiration):
+ user revoked access; unused for six months; password change (only for tokens with Gmail scopes);
+ too many live refresh tokens; time-based access expired; admin restricted the scopes.
+ **"A Google Cloud Platform project with an OAuth consent screen configured for an external user type
+ and a publishing status of 'Testing' is issued a refresh token expiring in 7 days"** unless the only
+ scopes are name, email and profile. Limit of 100 refresh tokens per Google Account per OAuth client
+ ID; the 101st silently invalidates the oldest.
+- Token sizes: refresh tokens up to 512 bytes, access tokens up to 2048 bytes. Same page.
+- `invalid_grant` on refresh means the token "may have expired or has been invalidated"; the fix is to
+ authenticate the user again. https://developers.google.com/identity/protocols/oauth2/web-server
+- A web server app needs a client secret (Google's overview: "a JavaScript application does not
+ require a secret, but a web server application does").
+ https://developers.google.com/identity/protocols/oauth2
+- Consent screen audience (https://support.google.com/cloud/answer/15549945):
+ Testing status is limited to 100 test users listed on the consent screen; test users see a warning.
+ In production, Google shows an "unverified app" screen while sensitive or restricted scopes are not
+ verified, and the unverified app user cap is 100 new users for the lifetime of the project.
+- Verification is not mandatory for "Personal Use apps ... (fewer than 100 users)"; users click
+ through the unverified app warning. Internal (Workspace) apps skip the warning and the cap.
+ https://support.google.com/cloud/answer/13464323
+- Scope sensitivity is shown in the Cloud Console; Google's scopes page says sensitive scopes "require
+ review by Google". https://developers.google.com/identity/protocols/oauth2/scopes
+
+### PKCE
+
+- **Verified:** the web server guide does not document `code_challenge` for web server apps.
+- **Not from Google (secondary):** developer tests and a Google forum thread report that Google
+ accepts `code_challenge` / `code_challenge_method=S256` on a Web application client but still
+ requires `client_secret` at the token endpoint.
+ https://ktaka.blog.ccmp.jp/2025/07/oogle-oauth2-and-pkce-understanding.html,
+ https://discuss.google.dev/t/authorization-code-flow-without-client-secret/168113
+- **Inference:** send a `state` value tied to a short-lived server-side record (CSRF protection), keep
+ the client secret in a Worker secret, and optionally add PKCE as defence in depth. Do not rely on
+ PKCE instead of the secret.
+
+### Sensitive or restricted
+
+- **Not stated on a Google page I could read:** the exact class of `youtube.upload`. Secondary sources
+ say every YouTube user-data scope is **sensitive** (not restricted) and only `youtubepartner` is
+ restricted. https://singhamandeep.com/youtube-api-key-vs-oauth-2-verification,
+ https://www.openquok.com/docs/social-integration/youtube
+- **Inference:** sensitive means a self-hoster sees the "Google hasn't verified this app" screen and can
+ click through (Advanced, Go to app). No CASA security assessment (that is for restricted scopes).
+
+### Narrowest scope set
+
+- Upload + thumbnail + read own upload status: `youtube.upload` covers videos.insert and thumbnails.set.
+ **Inference:** reading `processingDetails` and calling `channels.list mine=true` needs a read scope,
+ so add `youtube.readonly`.
+- Adding to a playlist needs `youtube.force-ssl` (or `youtube`). `youtube.force-ssl` alone also covers
+ insert, thumbnails and reads.
+- **Recommendation:** request `youtube.upload` + `youtube.readonly` at connect time. Request
+ `youtube.force-ssl` incrementally (`include_granted_scopes=true`) only when the owner turns on
+ "add to playlist". Owners who want one consent can request `youtube.force-ssl` alone, but it reads
+ as broader ("permanently delete") on the consent screen.
+
+---
+
+## 2. The private lock for unverified projects (reversed)
+
+### Verified
+
+- Original rule, 28 July 2020: "All videos uploaded via the videos.insert endpoint from unverified API
+ projects created after 28 July 2020 will be restricted to private viewing mode. To lift this
+ restriction, each project must undergo an audit to verify compliance with the Terms of Service."
+ https://developers.google.com/youtube/v3/revision_history (July 28, 2020 entry)
+- **Reversal, 2 November 2026:** "Videos uploaded through the videos.insert method from unverified API
+ projects are no longer restricted to private viewing mode. This change reverses the policy announced
+ on July 28, 2020". If `status.privacyStatus` is omitted, the video defaults to `public`; "Certain
+ uploads might default to private based on creator account settings".
+ https://developers.google.com/youtube/data/revision_history (November 2, 2026 entry)
+- The videos.insert reference now reads: "Videos uploaded from unverified API projects are not
+ restricted to private viewing mode." https://developers.google.com/youtube/v3/docs/videos/insert
+- A Google staff reply on the issue tracker (13 October 2026) says an unaudited project can upload
+ public or unlisted videos and can schedule with `publishAt`, and that an audit is no longer needed
+ for this. https://issuetracker.google.com/issues/572863050 and
+ https://issuetracker.google.com/issues/572902667
+- The YouTube Help page on videos locked as private still mentions unverified API services (stale).
+ https://support.google.com/youtube/answer/7300965
+
+### What a self-hoster must do
+
+- Nothing for privacy. No audit needed to publish publicly.
+- The audit form still matters for more quota: https://support.google.com/youtube/contact/yt_api_form
+- **Inference:** after each upload, read `status.privacyStatus` back from the 201 response and compare
+ it with what was asked. If YouTube returns `private` when `public` was asked, show it to the owner
+ (channel default settings, under-18 account, or a policy action) rather than failing silently.
+
+---
+
+## 3. videos.insert
+
+### Verified (https://developers.google.com/youtube/v3/docs/videos/insert, https://developers.google.com/youtube/v3/docs/videos)
+
+- Endpoint for uploads: `POST https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status`
+- Maximum file size 256 GB. Accepted media types `video/*` and `application/octet-stream`.
+- **Quota:** "100 calls per day. A call to this method has a quota cost of 1 unit in the Video Uploads
+ quota bucket." Background: 4 Dec 2025 cost dropped from about 1,600 to about 100 units; 1 June 2026
+ videos.insert and search.list moved to their own buckets. Default allocation is "100 search.list
+ calls, 100 videos.insert calls, and 10,000 units per day combined for all other endpoints". Quotas
+ reset at midnight Pacific Time. "All API requests, including invalid requests, incur at least a
+ one-point quota cost." https://developers.google.com/youtube/v3/determine_quota_cost,
+ https://developers.google.com/youtube/v3/getting-started,
+ https://developers.google.com/youtube/data/revision_history
+- Settable properties: `snippet.title`, `snippet.description`, `snippet.tags[]`, `snippet.categoryId`,
+ `snippet.defaultLanguage`, `localizations.*`, `status.embeddable`, `status.license`,
+ `status.privacyStatus`, `status.publicStatsViewable`, `status.publishAt`,
+ `status.selfDeclaredMadeForKids`, `status.containsSyntheticMedia`, `recordingDetails.recordingDate`.
+- Limits:
+ - `snippet.title`: max 100 characters, any UTF-8 except `<` and `>`. Required (invalidTitle on empty).
+ - `snippet.description`: max **5000 bytes** (not characters), any UTF-8 except `<` and `>`.
+ Clickable links need channel verification or advanced features.
+ - `snippet.tags[]`: whole list max 500 characters; commas between items count; a tag with a space
+ counts its implied quotation marks ("Foo Baz" counts as 9). The Go sample notes an empty tag
+ string gives 400.
+ - `snippet.categoryId`: must be a valid category ID (videoCategories.list).
+ - `snippet.defaultLanguage`: language of title and description; required if `localizations` are set
+ (error `defaultLanguageNotSet`).
+ - `status.privacyStatus`: `private`, `public`, `unlisted`; defaults to `public` if omitted.
+ - `status.publishAt`: the scheduled publish time. Can only be set when privacy is `private` and the
+ video has never been published; a past date publishes immediately; updates that set it must also
+ set privacyStatus to `private`. Error `invalidPublishAt` exists. The resource lists its type as
+ datetime (ISO 8601).
+ - `status.selfDeclaredMadeForKids`: boolean, channel owner's designation. (15 Oct 2026: omitted
+ values are not overridden on update.)
+ - `status.containsSyntheticMedia`: boolean, discloses realistic altered or synthetic content
+ (added 30 Oct 2024).
+ - `status.license`: `youtube` or `creativeCommon`. `status.embeddable`: boolean.
+- `notifySubscribers` query parameter: boolean, default `True`.
+- Length: 15 minutes by default; verified accounts can upload longer. Max "256 GB or 12 hours, whichever
+ is less." https://support.google.com/youtube/answer/71673
+- Errors listed: `defaultLanguageNotSet`, `invalidCategoryId`, `invalidDescription`, `invalidFilename`,
+ `invalidPublishAt`, `invalidRecordingDetails`, `invalidTags`, `invalidTitle`,
+ `invalidVideoGameRating`, `invalidVideoMetadata`, `mediaBodyRequired`, `uploadLimitExceeded` (all
+ 400), `forbidden`, `forbiddenLicenseSetting`, `forbiddenPrivacySetting` (403).
+
+### Inference
+
+- Validate title (1 to 100 characters, no `<` `>`), description (UTF-8 byte length up to 5000, no
+ `<` `>`) and the tag budget in a pure `lib/` helper so the browser form and the Worker share the rule.
+- `publishAt` must be in the future at insert time, with a margin (for example 15 minutes), because a
+ past time publishes immediately.
+- `notifySubscribers` with `publishAt`: whether the notification is sent at upload or at publish time
+ is not documented.
+- One resumable session initiation probably counts as the videos.insert call against the 100 per day
+ bucket, even if the upload is never finished. Count it on initiation.
+
+---
+
+## 4. Resumable upload protocol
+
+### Verified (https://developers.google.com/youtube/v3/guides/using_resumable_upload_protocol)
+
+1. **Initiate:** `POST https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=PARTS`
+ with headers `Authorization: Bearer ...`, `Content-Type: application/json; charset=UTF-8`,
+ `Content-Length` (of the JSON body), `X-Upload-Content-Length: <file size>`,
+ `X-Upload-Content-Type: video/*` (or `application/octet-stream`). Body: the video resource JSON.
+2. **Session URI:** response `200 OK` with a `Location` header holding the session URI
+ (`...&upload_id=...`). Save it.
+3. **Upload in chunks:** `PUT <session URI>` with `Authorization`, `Content-Length: <chunk size>`,
+ `Content-Range: bytes FIRST-LAST/TOTAL`. Rules: "The chunk size must be a multiple of 256 KB" except
+ the last; "The chunk size must be the same for each request in the upload sequence with the
+ exception of the last request". Every non-final chunk returns `308 Resume Incomplete` with a `Range`
+ header; the final chunk returns `201 Created` with the video resource.
+4. **Status query:** `PUT <session URI>` with `Content-Length: 0` and `Content-Range: bytes */TOTAL`.
+ - If the upload already completed, "regardless of whether it succeeded or failed, the API will return
+ the same response that it sent when the upload originally completed".
+ - Otherwise `308` with `Range: bytes=0-N` (0-indexed, inclusive), or no `Range` header if nothing
+ was received. Honour `Retry-After` if present.
+ - Resume from byte N+1 exactly. Overlapping or skipping bytes means "none of the binary content
+ will be uploaded". "Do not assume that the server received all (or none) of the bytes sent in the
+ previous request." Status can be queried between chunks at any time.
+5. **Retryable:** connection lost, or `500`, `502`, `503`, `504`, with exponential backoff. Any other
+ 4xx or 5xx is permanent.
+6. **Expiry:** "each resumable session URI has a finite lifetime and eventually expires". A request
+ with an expired session URI returns `404`; start a new session from byte 0.
+- Google's Python sample: `RETRIABLE_STATUS_CODES = [500, 502, 503, 504]`, `MAX_RETRIES = 10`,
+ sleep `random() * 2 ** retry` seconds. https://developers.google.com/youtube/v3/guides/uploading_a_video
+- Google also calls chunking "rarely necessary and ... discouraged" for performance, but allows it.
+
+### Session lifetime: not documented for YouTube
+
+- Drive: "A resumable session URI expires after one week." Any 4xx during a resumable upload means
+ restart. https://developers.google.com/drive/api/guides/manage-uploads
+- Cloud Storage: one week; `410 Gone` if cancelled or invalid within the week, `404` after.
+ https://docs.cloud.google.com/storage/docs/resumable-uploads
+- **Inference:** YouTube likely uses the same Google upload stack (one week), but plan for less. Treat
+ both `404` and `410` on the session URI as "session gone". Finish uploads within hours, not days.
+
+### Inference: chunk size for this stack
+
+- 8 MiB (32 x 256 KiB) per chunk. A 100 MB file (Cloudinary free maximum) is 12 or 13 chunks.
+- Keep it constant for the whole session; only the last chunk is shorter.
+
+---
+
+## 5. Upload and processing status
+
+### Verified (https://developers.google.com/youtube/v3/docs/videos, https://developers.google.com/youtube/v3/docs/videos/list)
+
+- `status.uploadStatus`: `uploaded`, `processed`, `failed`, `rejected`, `deleted`.
+- `status.failureReason` (only when failed): `codec`, `conversion`, `emptyFile`, `invalidFile`,
+ `tooSmall`, `uploadAborted`.
+- `status.rejectionReason` (only when rejected): `claim`, `copyright`, `duplicate`, `inappropriate`,
+ `legal`, `length`, `termsOfUse`, `trademark`, `uploaderAccountClosed`, `uploaderAccountSuspended`.
+- `processingDetails.processingStatus`: `processing`, `succeeded`, `failed`, `terminated`;
+ `processingProgress` (`partsTotal`, `partsProcessed`, `timeLeftMs`) "is designed to be polled";
+ `processingFailureReason`: `other`, `streamingFailed`, `transcodeFailed`, `uploadFailed`;
+ `thumbnailsAvailability` and others. "This data can only be retrieved by the video owner."
+- `suggestions.processingErrors` / `processingWarnings` / `processingHints` (owner only).
+- videos.list costs 1 unit (shared 10,000 bucket).
+
+### Inference
+
+- Poll `videos.list?part=status,processingDetails&id=...` from the 5-minute cron until
+ `uploadStatus` is `processed`, `failed`, `rejected` or `deleted`, with a cap (for example 24 hours).
+ Batch up to 50 IDs per call (the `id` filter accepts a comma-separated list) to save quota.
+
+---
+
+## 6. Thumbnails, playlists, categories, channel info
+
+### Verified
+
+- **thumbnails.set** (https://developers.google.com/youtube/v3/docs/thumbnails/set): max 50 MB
+ (raised from 2 MB on 14 Sep 2026), `image/jpeg`, `image/png`, `application/octet-stream`; about
+ 50 units. Errors: `invalidImage`, `mediaBodyRequired` (400); `forbidden` (403: "The authenticated
+ user doesn't have permissions to upload and set custom video thumbnails"); `videoNotFound` (404);
+ `uploadRateLimitExceeded` (429). Since 3 Nov 2026 it supports Shorts thumbnails "after video
+ processing is complete", with a new `shortsAspectRatio` property on the thumbnails resource.
+ https://developers.google.com/youtube/data/revision_history
+- Custom thumbnails need a verified YouTube account (phone verification unlocks intermediate features,
+ with a daily limit). https://support.google.com/youtube/answer/72431,
+ https://support.google.com/youtube/answer/9890437
+- **playlistItems.insert**: 50 units, scopes `youtube` / `youtube.force-ssl` / `youtubepartner`.
+ Errors include `playlistContainsMaximumNumberOfVideos`, `playlistItemsNotAccessible`,
+ `playlistOperationUnsupported` (cannot insert into the uploads playlist).
+ https://developers.google.com/youtube/v3/docs/playlistItems/insert
+- **playlists.list** `mine=true`: 1 unit, `maxResults` 0 to 50, paged.
+ https://developers.google.com/youtube/v3/docs/playlists/list
+- **videoCategories.list** `regionCode=<ISO 3166-1 alpha-2>`, `part=snippet`, `hl` optional: 1 unit.
+ https://developers.google.com/youtube/v3/docs/videoCategories/list
+- **channels.list** `mine=true`: 1 unit; returns channels owned by the authenticated user.
+ https://developers.google.com/youtube/v3/docs/channels/list
+
+### Inference
+
+- Not every category is assignable to uploads; the category resource has a `snippet.assignable` flag
+ (from memory, not re-read). Filter on it. Cache categories per region in Redis or Postgres for a day.
+- Call thumbnails.set only after `processingDetails.thumbnailsAvailability` / processing succeeds,
+ especially for Shorts. Treat `forbidden` as "channel not verified for custom thumbnails" and keep the
+ video published, marking only the thumbnail step as failed.
+- Store `channelId`, title, thumbnail URL and the uploads playlist ID from channels.list at connect time.
+
+---
+
+## 7. Shorts
+
+### Verified
+
+- No Shorts endpoint exists. Google staff on the googleapis repo: "Shorts are treated as standard video
+ resources within the Data API" and there is no `isShort` field.
+ https://github.com/googleapis/googleapis/discussions/1153
+- Eligibility: for standard channels, videos uploaded on or after 15 October 2024 "with a square or
+ vertical aspect ratio up to three minutes in length will be categorised as Shorts" (Official Artist
+ Channels from 8 December 2025). https://support.google.com/youtube/answer/15424877
+- Shorts thumbnails can be set via API after processing (3 Nov 2026, see section 6).
+
+### Not verified / inference
+
+- `#Shorts` in title or description: no current Google page I read says it is required. Classification
+ is by aspect ratio and length. Hootsuite still recommends it as a discovery hint. Treat it as optional
+ copy, not a switch.
+- How to tell a Short after upload: no official field. Workarounds: duration from
+ `contentDetails.duration` plus the source file's aspect ratio (Twiligent knows both from Cloudinary
+ at upload time), or an unofficial `HEAD https://www.youtube.com/shorts/<id>` check (200 = Short,
+ 303 = regular). The HEAD check is unofficial, only works once public, and may be rate limited from
+ Workers IPs. https://issuetracker.google.com/issues/232112727
+- **Recommendation:** decide "Short" in Twiligent from the source file (Cloudinary returns `width`,
+ `height`, `duration`): Short if height >= width and duration <= 180 s. Store the intent, do not
+ query YouTube to confirm.
+
+---
+
+## 8. Errors to handle
+
+### Verified
+
+Sources: https://developers.google.com/youtube/v3/docs/core_errors, the insert and thumbnails pages,
+and the OAuth web server guide.
+
+| Error | Where | Meaning |
+| --- | --- | --- |
+| `quotaExceeded` (403) | any | operation needs more quota than remains |
+| `rateLimitExceeded` (403 or 429), `userRateLimitExceeded` (403) | any | too many requests in a time span |
+| `uploadLimitExceeded` (400) | videos.insert | channel exceeded the number of videos it may upload |
+| `forbidden` (403) | insert, thumbnails | not allowed (permissions, unverified for thumbnails) |
+| `insufficientPermissions` (403) | any | token lacks the scope |
+| `invalidCategoryId`, `invalidTitle`, `invalidDescription`, `invalidTags`, `invalidPublishAt`, `defaultLanguageNotSet`, `invalidVideoMetadata` (400) | insert | metadata fix needed |
+| `mediaBodyRequired` (400) | insert, thumbnails | no media content |
+| `authError`, `unauthorized`, `expired` (401) | any | bad or expired access token |
+| `invalid_grant` | token endpoint | refresh token expired or revoked; reconnect |
+| `backendError` (503), `internalError` (500) | any | transient |
+| 404 / 410 on session URI | resumable PUT | session expired; restart from byte 0 |
+
+### Inference: classification
+
+| Class | Errors | Action |
+| --- | --- | --- |
+| Retry with backoff | network error, 500, 502, 503, 504, `backendError`, 429 | keep job, next attempt after backoff |
+| Wait for quota reset | `quotaExceeded` | park until next midnight Pacific; no attempt counted |
+| Wait, then retry | `rateLimitExceeded`, `userRateLimitExceeded` | longer backoff (minutes) |
+| Owner must act on content | `invalid*`, `mediaBodyRequired`, `defaultLanguageNotSet` | `failed`, message names the field |
+| Owner must act on account | `invalid_grant`, 401 after refresh, `insufficientPermissions`, `forbidden` | pause account jobs as `needs_reconnect` |
+| Channel limit | `uploadLimitExceeded` | `failed` with "YouTube daily upload limit reached for this channel"; let owner retry tomorrow |
+| Session gone | 404 / 410 on session URI | see idempotency rules in section 12 |
+
+---
+
+## 9. Cloudflare Workers feasibility
+
+### Verified (https://developers.cloudflare.com/workers/platform/limits/, updated 29 Oct 2026)
+
+| Limit | Free | Paid |
+| --- | --- | --- |
+| CPU per HTTP request | 10 ms | 30 s default, up to 5 min |
+| CPU per Cron Trigger | 10 ms | 30 s (interval < 1 h), 15 min (>= 1 h) |
+| Cron wall time | 15 min | 15 min |
+| Subrequests per invocation | **50** | **10,000** default (up to 10M) |
+| Simultaneous connections waiting for headers | 6 | 6 |
+| Memory per isolate | 128 MB | 128 MB |
+| Cron triggers per account | 5 | 250 |
+| Incoming request body | 100 MB on Free/Pro zones, 200 MB Business | same (zone plan, not Workers plan) |
+| Response body size | no enforced limit | same |
+
+- Waiting on `fetch()` does not count as CPU time.
+- No documented size limit on an outgoing `fetch()` body from a Worker. (The 100 MiB outbound body
+ limit applies to Durable Objects and Container outbound handlers, not plain Workers.)
+- Streaming: `fetch()` accepts a `ReadableStream` body. "To have a Content-Length header with a
+ specific value specified, the body of the Request must be either a FixedLengthStream or a
+ fixed-length value"; "Using any other type of ReadableStream as the body of a request will result in
+ Chunked-Encoding being used." https://developers.cloudflare.com/workers/runtime-apis/request
+- Streams avoid buffering within the 128 MB limit; forwarding a body without reading it is already
+ optimal. https://developers.cloudflare.com/workers/runtime-apis/streams/
+
+### Inference
+
+- **Streaming Cloudinary to Google works without buffering:** fetch the Cloudinary byte range, pipe
+ `response.body` into `new FixedLengthStream(chunkLength)`, and PUT the readable side to the session
+ URI with `Content-Range`. Memory stays small.
+- **Free plan CPU (10 ms per cron run) is the main risk.** Piping bytes through native streams should
+ cost little JS CPU, but this needs measuring with a real 8 MiB chunk before promising free-plan
+ support. Fallback: smaller chunks per run, or run the upload from GitHub Actions (section 12, option B).
+- **Free plan subrequests (50 per run):** each chunk costs 2 subrequests (Cloudinary range GET + Google
+ PUT). Supabase writes and the token refresh also count. A 100 MB file (13 chunks = 26) plus about
+ 8 bookkeeping calls fits in one run, but checkpoints must be sparse. Paid plan removes this concern.
+- Throughput is unknown. At 10 to 50 MB/s Worker egress, 100 MB takes 2 to 10 seconds of wall time,
+ well inside 15 minutes.
+
+---
+
+## 10. Cloudinary
+
+### Verified
+
+- Free plan: 25 credits per month; 1 credit = 1 GB storage, or 1 GB video bandwidth on Free (2 GB on
+ paid), or 1,000 transformations. https://cloudinary.com/documentation/billing_and_plans
+- Free plan maximum video file size **100 MB** (Plus 2 GB, Advanced 4 GB); max image 10 MB.
+ https://cloudinary.com/pricing/compare-plans
+- **Range requests work** (tested 4 Nov 2026 against `res.cloudinary.com/demo/video/upload/dog.mp4`):
+ `HEAD` returns `Accept-Ranges: bytes` and `Content-Length`; `Range: bytes=0-262143` returns
+ `206 Partial Content`, `Content-Length: 262144`, `Content-Range: bytes 0-262143/9094354`. Delivery is
+ fronted by Cloudflare. Also exposes an `ETag`.
+- Deleting: the Upload API `destroy` "requires a signature to be generated on the server side" (API key
+ and secret); Admin API delete methods also need key and secret. An unsigned upload can return a
+ `delete_token` (`return_delete_token=true`) usable "within 10 minutes" without auth.
+ https://cloudinary.com/documentation/delete_assets,
+ https://cloudinary.com/documentation/image_upload_api_reference_upload
+
+### Inference
+
+- Fetch the **original** delivery URL (no transformation parameters) so no transformation credits are
+ spent and the bytes match the size Twiligent recorded. Pin the version segment (`/v<version>/`) to
+ avoid a changed asset under the same public ID mid-upload, and compare `ETag` / total length on every
+ range response; abort the session if it changes.
+- Bandwidth: each upload reads the file once from Cloudinary (plus retried chunks). 100 MB = 0.1 credit.
+- `delete_token` is useless for scheduled uploads (expires in 10 minutes). Options: add optional
+ `CLOUDINARY_API_KEY` / `CLOUDINARY_API_SECRET` Worker secrets so the Worker can sign `destroy` after a
+ successful upload; without them, list the asset for manual cleanup and say so in the UI.
+
+---
+
+## 11. How other schedulers do it (secondary, product docs)
+
+- **Later:** Shorts only (no long-form); 15 s to 3 min; title, description, tags (500 characters),
+ category, visibility, notify subscribers toggle, made-for-kids required; no custom Shorts thumbnails.
+ https://help.later.com/hc/en-us/articles/14720878941463-Schedule-Publish-YouTube-Shorts
+- **Buffer:** Shorts only; up to 3 min, up to 10 GB, square or 9:16; automatic or notification
+ publishing; no custom Shorts thumbnail; category fixed by YouTube.
+ https://support.buffer.com/articles/using-youtube-shorts-with-buffer-Jl8iR6jIck
+- **Hootsuite:** long-form and Shorts; title, description, tags, category, privacy; custom thumbnail if
+ the account is verified; "You can schedule Unlisted or Private videos to go public at a later date
+ and time" (that is, it uses YouTube's own `publishAt`). Their doc still says Shorts are under 60 s,
+ which is outdated. https://help.hootsuite.com/s/article/publish-yt
+
+Takeaway: the common form is title, description, tags, category, privacy, made for kids, notify
+subscribers, schedule time, optional thumbnail, optional playlist. Hootsuite delegates scheduling to
+YouTube.
+
+---
+
+## 12. Recommended pipeline for Twiligent
+
+Everything in this section is **inference** (design), built on the verified facts above.
+
+### 12.1 Key design choice: upload early, let YouTube publish
+
+Unlike Instagram, YouTube can schedule natively: upload as `private` with `status.publishAt`. So the
+YouTube job should **upload soon after the owner saves the post**, not at publish time:
+
+- the 15-minute and 50-subrequest limits apply to a background step with no deadline pressure;
+- processing, copyright and metadata errors show up hours before the publish time;
+- the Cloudinary asset can be deleted as soon as YouTube has the file;
+- the time-critical part (going public) is done by YouTube, so neither scheduler has to hit the minute.
+
+"Publish now" posts use `public` (or `unlisted`) directly. Scheduled posts use `private` + `publishAt`.
+Constraint to show in the UI: a scheduled post always goes public at the time; "scheduled unlisted" is
+not possible through `publishAt`.
+
+### 12.2 Where the bytes come from
+
+1. Browser uploads the video to Cloudinary with the existing unsigned preset (`resource_type=video`).
+ Cloudinary returns `public_id`, `version`, `bytes`, `width`, `height`, `duration`, `format`.
+2. Browser posts the job to the Worker with those fields. The Worker validates: size <= 256 GB (and
+ <= plan limit), duration <= 15 min unless the channel is verified for long uploads (cannot be read
+ from the API, so warn instead of block), Short = `height >= width && duration <= 180`.
+3. Optional thumbnail: a second Cloudinary image upload (JPEG or PNG, <= 10 MB on the free plan).
+
+### 12.3 Tables (sketch; real migrations one entity per file)
+
+- `youtube_accounts`: `user_id`, `channel_id`, `channel_title`, `refresh_token` (encrypted at rest),
+ `access_token`, `access_token_expires_at`, `granted_scopes`, `status` (`active`, `needs_reconnect`),
+ `token_lease_until`.
+- `youtube_uploads` (the job): `id` (`newRowId()`), `user_id`, `account_id`, `post_id`, metadata
+ snapshot (title, description, tags, category, privacy, publish_at, made_for_kids, synthetic,
+ notify_subscribers, playlist_id), `source_url`, `source_bytes`, `source_etag`, `content_type`,
+ `chunk_size`, `session_uri`, `session_started_at`, `bytes_confirmed`, `video_id`, `state`,
+ `attempts`, `next_attempt_at`, `lease_owner`, `lease_until`, `last_error_code`, `last_error`,
+ `processing_checked_at`, `created_at`, `updated_at`.
+- `youtube_quota_ledger`: `pacific_date`, `bucket` (`uploads`, `default`), `units`; one row per day and
+ bucket, incremented atomically.
+
+States: `queued` -> `uploading` -> `uploaded` (have `video_id`) -> `processing` -> `processed` ->
+`finalizing` (thumbnail, playlist) -> `done`. Side states: `waiting_quota`, `needs_reconnect`,
+`needs_review` (outcome unknown), `failed` (dead letter, needs the owner).
+
+### 12.4 Claim and lease locking
+
+- One SQL function (a migration) claims work atomically:
+ `UPDATE youtube_uploads SET lease_owner = $run, lease_until = now() + interval '10 minutes'
+ WHERE id = (SELECT id FROM youtube_uploads WHERE state IN ('queued','uploading') AND next_attempt_at
+ <= now() AND (lease_until IS NULL OR lease_until < now()) ORDER BY next_attempt_at LIMIT 1
+ FOR UPDATE SKIP LOCKED) RETURNING *`.
+- Lease shorter than the 15-minute cron wall time; the run stops taking new chunks when less than about
+ 3 minutes of lease remain and releases the lease when done.
+- Every write back is conditional: `WHERE id = $id AND lease_owner = $run`. A run whose lease was taken
+ over writes nothing.
+- The every-minute cron, the 5-minute cron and GitHub Actions can all call the same claim, so two runs
+ never upload the same job.
+
+### 12.5 Upload loop (one claimed job per run)
+
+1. Get a valid access token (12.7).
+2. If `session_uri` is null: check quota (12.8); write `session_started_at`, then POST the initiation
+ with the metadata JSON, `X-Upload-Content-Length = source_bytes`, `X-Upload-Content-Type =
+ content_type`. Store `session_uri` **before sending any bytes**. Increment the uploads bucket.
+3. Ask Google for the real offset: empty PUT with `Content-Range: bytes */TOTAL`.
+ - 200/201: the upload already finished; take `video_id` from the body (this also recovers a lost
+ final response).
+ - 308: offset = Range end + 1 (or 0 when no Range).
+4. While time and subrequest budget remain: fetch Cloudinary `Range: bytes=offset-(offset+chunk-1)`;
+ check 206, `Content-Range` total and ETag; pipe into `FixedLengthStream(len)`; PUT with
+ `Content-Range: bytes offset-last/TOTAL`. On 308 set offset from `Range`. On 201 store `video_id`,
+ `state = uploaded`.
+5. Save `bytes_confirmed` at the end of the run (and every few chunks on the paid plan). Google's
+ status query is the source of truth; the stored offset is only a hint, which saves free-plan
+ subrequests.
+
+### 12.6 Idempotency: never create two videos
+
+- One job has at most one live session. A new session is created only when `session_uri` is null.
+- Never retry the initiation POST blindly. If the initiation response is lost (network error), a
+ session may exist that we do not know about, but no bytes were sent to it, so no video can appear.
+ Safe to initiate again.
+- A lost final-chunk response is recovered by the status query (step 3), which returns the original
+ 201 with the video ID.
+- Session `404`/`410`:
+ - if `bytes_confirmed < source_bytes` and no final chunk was ever sent: safe to clear `session_uri`
+ and restart from byte 0;
+ - if the final chunk was sent and its response lost, the outcome is unknown: set `needs_review` and
+ ask the owner to check the channel, following the project's rule for unknown outcomes (as for
+ Instagram private replies). Optionally search the channel's uploads playlist (playlistItems.list,
+ 1 unit) for a video created after `session_started_at` with the same title and offer to link it.
+- Record a `client_upload_key` in the video description or tags? Not recommended (visible to viewers).
+
+### 12.7 Token refresh
+
+- Before each job, refresh if `access_token_expires_at` is within 5 minutes. Use a short per-account
+ lease (`token_lease_until`) so two runs do not refresh at once; the loser re-reads the row.
+- POST `grant_type=refresh_token`, `refresh_token`, `client_id`, `client_secret` to
+ `https://oauth2.googleapis.com/token`. Store the new access token and expiry; store a new refresh
+ token only if one is returned.
+- `invalid_grant` or 401 after a fresh token: set the account `needs_reconnect`, move its jobs to
+ `needs_reconnect` (not failed, no attempt used), and show "Reconnect YouTube" in the app. A reconnect
+ uses `prompt=consent` + `access_type=offline` so Google issues a new refresh token.
+- Disconnect: POST the refresh token to `https://oauth2.googleapis.com/revoke`, then delete it.
+
+### 12.8 Quota accounting
+
+- Uploads bucket: 100 initiations per project per Pacific day. Default bucket: 10,000 units
+ (thumbnails.set 50, playlistItems.insert 50, videos.list 1, channels.list 1, playlists.list 1,
+ videoCategories.list 1).
+- All of an owner's channels share one Google Cloud project, so one ledger per instance.
+- Before a call, reserve units with an atomic `UPDATE ... SET units = units + $n WHERE units + $n <=
+ $limit RETURNING`; if it fails, set `waiting_quota` with `next_attempt_at` = next midnight Pacific.
+- On `quotaExceeded` from Google, trust Google: set the ledger to the limit for that day.
+- Show remaining uploads for today in the composer.
+
+### 12.9 Backoff and dead letter
+
+- Transient errors: `next_attempt_at = now() + min(2^attempts, 60) minutes * random(0.5..1)`, honour
+ `Retry-After`. After 8 transient attempts (about 4 hours total), move to `failed`.
+- Content and channel errors go straight to `failed` with a message that names what to fix
+ ("Couldn't upload the video. The title is longer than 100 characters.").
+- `failed` jobs keep the Cloudinary asset so the owner can fix metadata and retry, which clears
+ `session_uri` only if no bytes were confirmed, otherwise resumes.
+
+### 12.10 After upload
+
+- 5-minute cron: batch `videos.list?part=status,processingDetails&id=...` (up to 50 IDs, 1 unit).
+ `processed` -> `finalizing`; `failed` / `rejected` -> `failed` with `failureReason` /
+ `rejectionReason` mapped to plain English; stop polling after 24 hours as `needs_review`.
+- Finalizing: thumbnails.set (upload endpoint, image streamed from Cloudinary) if a thumbnail was
+ given; playlistItems.insert if a playlist was chosen and the scope was granted. Each step is its own
+ sub-state so a failure in one does not redo the other. A thumbnail `forbidden` keeps the video and
+ marks the post "published, thumbnail not set (verify your channel to use custom thumbnails)".
+- Read back `status.privacyStatus` and `publishAt`; flag a mismatch.
+
+### 12.11 Cleanup
+
+- After `uploaded` (YouTube has the file), delete the Cloudinary video if API key and secret are
+ configured (signed `destroy`, `resource_type=video`, `invalidate=true`); delete the thumbnail after
+ finalizing. Without the secret, mark assets for manual cleanup.
+- Clear `session_uri` once `video_id` is stored. Purge `access_token` on disconnect.
+
+### 12.12 Option B: GitHub Actions as the uploader
+
+- The existing second scheduler (`scripts/publish-scheduled.ts`, no npm dependencies) can run the same
+ claim and loop with Node's `fetch`: no 10 ms CPU limit, no 50-subrequest limit, 6-hour jobs.
+- Recommended split: the Worker cron handles small files and the paid plan; GitHub Actions takes jobs
+ the Worker could not finish (same lease). Shared rules (chunk math, error classification, validation)
+ live in a `backend/lib/` helper with no runtime imports, as with `scheduledPublishing.ts`.
+
+### 12.13 Option C (not verified): browser uploads straight to YouTube
+
+- The Worker could initiate the session and hand the session URI to the browser, which PUTs the file
+ directly, skipping Cloudinary. Not verified: whether YouTube session URIs accept a PUT without the
+ `Authorization` header and whether they allow CORS from the app origin. Worth a spike only if the
+ 100 MB Cloudinary free limit becomes the main complaint.
+
+---
+
+## 13. Owner setup steps (self-hosted)
+
+1. In Google Cloud Console, create a project (or reuse one) and enable **YouTube Data API v3**.
+2. Configure the OAuth consent screen: user type **External** (or **Internal** if the channels belong
+ to the owner's Google Workspace), app name, support email, add scopes `youtube.upload` and
+ `youtube.readonly` (plus `youtube.force-ssl` if playlists are wanted).
+3. **Publish the app to "In production".** Leaving it in Testing makes refresh tokens expire after
+ 7 days, so scheduled uploads would stop weekly. Verification is not required for personal use
+ (under 100 users); the owner clicks through "Google hasn't verified this app" once per connection.
+4. Create an OAuth client of type **Web application** with the redirect URI
+ `https://<worker-host>/api/youtube/oauth/callback` (exact match required).
+5. Add Worker secrets `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` (and optionally `CLOUDINARY_API_KEY`,
+ `CLOUDINARY_API_SECRET` for automatic cleanup).
+6. In YouTube, verify the channel's phone number (youtube.com/verify) to allow videos longer than
+ 15 minutes and custom thumbnails.
+7. Connect each channel from Twiligent. For a brand account, pick the channel on Google's chooser.
+8. Optional: request more quota with the audit form if 100 uploads per day is not enough.
+
+---
+
+## 14. Could not verify
+
+- The exact sensitivity class of `youtube.upload` on a Google-owned page (secondary sources say sensitive).
+- The lifetime of a YouTube resumable session URI (Drive and Cloud Storage document one week).
+- Whether a YouTube session URI accepts PUTs without `Authorization`, and its CORS behaviour.
+- Whether an unfinished resumable session counts against the 100 per day uploads bucket (assumed yes).
+- Whether `notifySubscribers` fires at upload or at `publishAt` time.
+- Whether `#Shorts` still influences classification (current Google pages describe only aspect ratio
+ and length).
+- Actual Worker CPU time for piping an 8 MiB chunk on the free plan (must be measured).
+- `snippet.assignable` on video categories (from memory, not re-read this session).
+- How brand-account channel selection interacts with one refresh token per channel (Google docs not read).