Compare commits

..

25 Commits

Author SHA1 Message Date
9dd856ff8c fix(gameplay): use AI-generated world companions
Some checks failed
CI / validate (push) Successful in 1h3m54s
CI / validate (pull_request) Failing after 14m14s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-21 20:38:12 +05:00
f7ca158fe4 fix(gameplay): start campaigns in playable state
Some checks failed
CI / validate (pull_request) Has been cancelled
CI / validate (push) Successful in 32m54s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-21 19:41:50 +05:00
19693c78c4 Merge pull request 'DUNGEONS-15: keep coauthor questions in the user's language' (#10) from agent/codex-chatgpt/1d9b2488 into main
Some checks failed
CI / validate (push) Has been cancelled
Reviewed-on: #10
2026-08-21 13:40:57 +00:00
2898efa1db fix(web): keep coauthor questions in user language
Some checks failed
CI / validate (push) Failing after 13m17s
CI / validate (pull_request) Failing after 13m51s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-21 12:12:10 +05:00
fb4b06711d Merge pull request 'DUNGEONS-12: add profile management' (#9) from agent/codex-chatgpt/24f3d9f6 into main
Some checks failed
CI / validate (push) Failing after 10m19s
Reviewed-on: #9
2026-08-20 15:18:20 +00:00
41f4633dca feat(web): add profile management
Some checks failed
CI / validate (push) Successful in 19m25s
CI / validate (pull_request) Failing after 9m54s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-20 19:24:50 +05:00
fc205c232f Merge pull request 'DUNGEONS-11: keep auth pages styled reliably' (#8) from agent/codex-chatgpt/d97b9d5e into main
Some checks failed
CI / validate (push) Failing after 59s
Reviewed-on: #8
2026-08-20 13:51:41 +00:00
744749bc54 fix(web): keep auth styles globally available
All checks were successful
CI / validate (push) Successful in 17m4s
CI / validate (pull_request) Successful in 16m32s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-20 18:28:12 +05:00
c1e6b4b61f Style dashboard world cards and responsive layout
Some checks failed
CI / validate (push) Failing after 34m57s
2026-08-20 14:53:11 +05:00
139c0d4fd2 Merge pull request 'DUNGEONS-9: fix black screen caused by asset failures' (#7) from agent/codex-chatgpt/75fff14e into main
Some checks failed
CI / validate (push) Has been cancelled
Reviewed-on: #7
2026-08-20 09:11:13 +00:00
8ce9314887 fix(web): serve Nitro assets reliably
Some checks failed
CI / validate (push) Failing after 8m18s
CI / validate (pull_request) Successful in 29m51s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-20 13:38:32 +05:00
40100cccab Merge pull request 'DUNGEONS-8: test Coolify PR webhook (recreated #2)' (#6) from test/coolify-webhook-3 into main
Some checks failed
CI / validate (push) Has been cancelled
Reviewed-on: #6
2026-08-19 14:50:41 +00:00
a079598f9c test(coolify): trigger preview deployment webhook
Some checks failed
CI / validate (pull_request) Has been cancelled
CI / validate (push) Has been cancelled
Co-authored-by: multica-agent <github@multica.ai>
2026-08-19 19:44:34 +05:00
263bee12dd Merge pull request 'DUNGEONS-8: test Coolify PR webhook (recreated)' (#5) from test/coolify-webhook-2 into main
Some checks failed
CI / validate (push) Has been cancelled
Reviewed-on: #5
2026-08-19 14:42:43 +00:00
de815cb9c1 test(coolify): trigger preview deployment webhook
Some checks failed
CI / validate (pull_request) Has been cancelled
CI / validate (push) Successful in 14m54s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-19 19:21:18 +05:00
bf48924644 Merge pull request 'DUNGEONS-8: test Coolify PR webhook' (#4) from test/coolify-webhook into main
Some checks failed
CI / validate (push) Has been cancelled
Reviewed-on: #4
2026-08-19 14:19:40 +00:00
e90dccd8bb test(coolify): trigger preview deployment webhook
All checks were successful
CI / validate (push) Successful in 15m15s
CI / validate (pull_request) Successful in 16m0s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-19 19:15:46 +05:00
9c08cabcf7 Merge pull request 'DUNGEONS-6: Fix Nitro public assets in Coolify image' (#3) from perfect_python500/dungeons-6-coolify-assets into main
All checks were successful
CI / validate (push) Successful in 14m28s
Reviewed-on: #3
2026-08-19 13:28:05 +00:00
8651a9aad1 Fix Nitro public assets in Coolify image
All checks were successful
CI / validate (push) Successful in 20m23s
CI / validate (pull_request) Successful in 17m14s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-19 18:19:59 +05:00
860a5383b0 Merge pull request 'Fix Dockerfile healthcheck for Coolify PORT override' (#2) from agent/opencode-deepseek/1fa9d179 into main
All checks were successful
CI / validate (push) Successful in 23m18s
Reviewed-on: #2
2026-08-19 12:06:45 +00:00
62f01f1db3 Fix healthcheck to respect runtime PORT
Some checks failed
CI / validate (push) Successful in 26m55s
CI / validate (pull_request) Failing after 1m15s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-19 17:00:39 +05:00
8f42a6664b Merge pull request 'Add Dockerfile for containerized build and run' (#1) from agent/opencode-deepseek/1fa9d179 into main
All checks were successful
CI / validate (push) Successful in 14m54s
Reviewed-on: #1
2026-08-19 09:47:20 +00:00
95fb688910 Add Dockerfile to build and run the project in Docker
Some checks failed
CI / validate (push) Successful in 16m14s
CI / validate (pull_request) Failing after 15s
Co-authored-by: multica-agent <github@multica.ai>
2026-08-19 14:43:50 +05:00
33ff879e90 Require email account authentication
All checks were successful
CI / validate (push) Successful in 14m23s
2026-08-18 20:26:24 +05:00
45afb302b7 Add closed alpha product plan
All checks were successful
CI / validate (push) Successful in 16m33s
2026-08-18 14:48:24 +05:00
42 changed files with 2661 additions and 158 deletions

View File

@@ -21,6 +21,5 @@ REDIS_URL=
AI_JOB_POLL_INTERVAL_MS=1000 AI_JOB_POLL_INTERVAL_MS=1000
# Alpha controls # Alpha controls
INVITE_ALLOWLIST=founder@example.com
DAILY_AI_TOKEN_LIMIT=250000 DAILY_AI_TOKEN_LIMIT=250000
NUXT_PUBLIC_APP_URL=http://localhost:3000 NUXT_PUBLIC_APP_URL=http://localhost:3000

79
Dockerfile Normal file
View File

@@ -0,0 +1,79 @@
# syntax=docker/dockerfile:1
#
# Dungeons & Ground — production image.
#
# Build: docker build -t dungeons-ground .
# Run: docker run --env-file .env -p 3000:3000 dungeons-ground
#
# Required env vars at runtime (see .env.example):
# NUXT_PUBLIC_SUPABASE_URL, SUPABASE_URL, NUXT_PUBLIC_SUPABASE_ANON_KEY,
# SUPABASE_SERVICE_ROLE_KEY, plus the AI provider key (OPENROUTER_API_KEY
# or DEEPSEEK_API_KEY). REDIS_URL is optional.
# The Supabase schema is NOT created by the container; install
# supabase/bootstrap.sql (or run `pnpm db:ensure` with SUPABASE_DB_URL set)
# in your Supabase project before starting.
FROM node:18.20.8-slim AS base
ENV PNPM_HOME=/pnpm
ENV PATH=$PNPM_HOME:$PATH
RUN corepack enable && corepack prepare pnpm@10.15.0 --activate
WORKDIR /app
# ---------- Dependencies ----------
FROM base AS deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/web/package.json apps/web/package.json
COPY apps/worker/package.json apps/worker/package.json
COPY packages/shared/package.json packages/shared/package.json
COPY packages/game-engine/package.json packages/game-engine/package.json
RUN pnpm install --frozen-lockfile
# ---------- Build ----------
FROM deps AS build
COPY . .
# The web build explicitly loads ../../.env (--dotenv); an empty file keeps
# the build hermetic — all real values come from container env at runtime.
RUN touch .env && pnpm --filter @dng/web build
# ---------- Runtime ----------
FROM base AS runtime
ENV NODE_ENV=production
ENV HOST=0.0.0.0
ENV PORT=3000
WORKDIR /app
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/web/package.json apps/web/package.json
COPY apps/worker/package.json apps/worker/package.json
COPY packages/shared/package.json packages/shared/package.json
COPY packages/game-engine/package.json packages/game-engine/package.json
COPY --from=deps /app/node_modules node_modules
COPY --from=build /app/apps/web/.output apps/web/.output
COPY --from=build /app/apps/worker apps/worker
COPY --from=build /app/packages/shared packages/shared
COPY --from=build /app/packages/game-engine packages/game-engine
EXPOSE 3000
# Coolify (and other hosts) override PORT at runtime; probe that port, not a
# hardcoded one.
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
CMD node -e "fetch('http://127.0.0.1:' + (process.env.PORT || 3000) + '/').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
# The Nuxt web server reads its config through Nuxt runtimeConfig, which is
# baked at build time and overridden at runtime only by NUXT_-prefixed env
# vars; the worker reads plain names (SUPABASE_URL, OPENROUTER_API_KEY, ...)
# directly. The entrypoint maps the plain .env.example names onto the NUXT_
# runtime overrides so `docker run --env-file .env` works for both processes.
# The web server runs in the foreground (PID 1); the AI worker runs alongside
# it in the background. Stop the container with `docker stop` — both die with
# it.
CMD ["sh", "-c", "export NUXT_SUPABASE_URL=\"${NUXT_SUPABASE_URL:-${SUPABASE_URL:-}}\" NUXT_SUPABASE_SERVICE_ROLE_KEY=\"${NUXT_SUPABASE_SERVICE_ROLE_KEY:-${SUPABASE_SERVICE_ROLE_KEY:-}}\" NUXT_AI_PROVIDER=\"${NUXT_AI_PROVIDER:-${AI_PROVIDER:-}}\" NUXT_OPENROUTER_API_KEY=\"${NUXT_OPENROUTER_API_KEY:-${OPENROUTER_API_KEY:-}}\" NUXT_OPENROUTER_MODEL=\"${NUXT_OPENROUTER_MODEL:-${OPENROUTER_MODEL:-}}\" NUXT_OPENROUTER_API_ENDPOINT=\"${NUXT_OPENROUTER_API_ENDPOINT:-${OPENROUTER_API_ENDPOINT:-}}\" NUXT_DEEPSEEK_API_KEY=\"${NUXT_DEEPSEEK_API_KEY:-${DEEPSEEK_API_KEY:-}}\" NUXT_DEEPSEEK_MODEL=\"${NUXT_DEEPSEEK_MODEL:-${DEEPSEEK_MODEL:-}}\" NUXT_DEEPSEEK_API_ENDPOINT=\"${NUXT_DEEPSEEK_API_ENDPOINT:-${DEEPSEEK_API_ENDPOINT:-}}\" NUXT_REDIS_URL=\"${NUXT_REDIS_URL:-${REDIS_URL:-}}\"; pnpm --filter @dng/worker start & exec node apps/web/.output/server/index.mjs"]

192
PLAN.md
View File

@@ -1 +1,193 @@
# Dungeons & Ground — план закрытой webальфы
## 1. Цель продукта
Dungeons & Ground — англоязычная веб‑платформа для текстовых TTRPGкампаний любого жанра, где:
- AIсоавтор помогает за несколько сообщений создать собственную вселенную.
- AI Game Master ведёт историю, NPC и последствия.
- Реальные игроки участвуют асинхронно в общем пошаговом чате.
- Постоянные AIгерои дополняют партию, а при необходимости временно заменяют отсутствующих игроков.
- Сервер, а не языковая модель, рассчитывает проверки, броски, HP и урон.
- Кампания сохраняет мир, отношения, инвентарь, события и долгосрочную память.
Главный критерий готовности альфы: 24 человека создают мир, персонажей и проходят минимум 2030 минут связной кампании, причём AI не забывает ключевые события и не изменяет игровые значения произвольно.
В отличие от Friends & Fables, уже совмещающего AIведущего, worldbuilding, память, карты, бой и мультиплеер, первая версия D&G сосредоточится на простом создании мира и партии, которая продолжает игру даже при отсутствии части людей. [Возможности Friends & Fables](https://fables.gg/), [описание их системы памяти](https://help.fables.gg/articles/2838157-memories).
## 2. Функциональность альфы
### Пользовательский путь
1. Регистрация обязательного аккаунта по имени, email и паролю; вход по email/password и восстановление пароля через письмо.
2. Создание приватной вселенной через чат с AIсоавтором.
3. AI задаёт 35 уточняющих вопросов о жанре, атмосфере, конфликте и желаемой роли игроков.
4. Создаётся редактируемый стартовый набор:
- premise, genre, tone и content boundaries;
- стартовая локация;
- 3 значимых NPC;
- 2 фракции;
- 3 постоянных AIгероя, созданных специально для этой вселенной;
- сюжетная завязка;
- скрытая угроза или цель;
- начальная сцена.
5. Владелец подтверждает мир, создаёт кампанию и приглашает игроков ссылкой.
6. Каждый игрок создаёт персонажа вручную или с помощью AI.
7. Созданные вместе со вселенной постоянные AIгерои автоматически входят в стартовую партию; владелец может добавлять других и определяет, чьи персонажи могут временно переходить под управление AI.
8. Игроки отправляют действия в текущем раунде.
9. AIDM обрабатывает раунд, когда:
- ответили все активные реальные игроки; или
- владелец нажал `Continue without waiting`.
10. AIгерои и замены совершают действия после людей, затем AIDM публикует единый результат раунда.
### Облегчённая игровая система
Использовать классические характеристики `STR`, `DEX`, `CON`, `INT`, `WIS`, `CHA` во всех жанрах, но позволять AI адаптировать названия архетипов, экипировки и способностей под fantasy, scifi, horror и другие сеттинги.
Первая версия движка покрывает:
- d20 ability и skill checks;
- proficiency bonus;
- HP, Defense/AC и initiative;
- attack roll, damage и healing;
- advantage/disadvantage;
- простые статусы и ограниченные ресурсы;
- серверный генератор случайных чисел с сохранением формулы и результата;
- ручную корректировку состояния владельцем кампании с записью в аудит.
Полные классы, заклинания, сетка боя и редкие правила 5e не входят в альфу. Основа — SRD 5.2.1 под CC BY 4.0 с обязательной атрибуцией; закрытые названия и сеттинги D&D не использовать. [Официальные условия SRD 5.2.1](https://www.dndbeyond.com/srd).
### Память и состояние мира
Хранить отдельно:
- неизменяемый журнал действий и результатов;
- текущую сцену и активные сущности;
- структурированное состояние персонажей, NPC, фракций и заданий;
- отношения между персонажами;
- важные воспоминания с привязкой к персонажам, локациям и тегам;
- краткое резюме истории, обновляемое каждые три завершённых раунда.
В контекст модели передавать только системные инструкции, текущую сцену, последние два раунда, участвующие сущности, активные цели и релевантные воспоминания. Полная история никогда не отправляется автоматически.
## 3. Техническая архитектура
### Стек
- Monorepo на TypeScript.
- Nuxt.js для SSRинтерфейса и Nitro API.
- Отдельный TypeScript worker для генерации миров и обработки игровых раундов.
- Supabase: PostgreSQL, Auth, Row Level Security и Realtime.
- BullMQ + managed Redis для очереди AIзадач.
- Railway: отдельные deployments для Nuxt/Nitro и worker.
- OpenRouter provider adapter с моделью `deepseek/deepseek-v4-flash`.
- Zod для общей валидации API, AIответов и игровых команд.
- Vitest, Nuxt Test Utils и Playwright для тестов.
Desktopверсия позднее создаётся через Tauri и использует тот же API и webинтерфейс.
### Основные сущности и интерфейсы
- `User`, `Invite`, `World`, `WorldEntity`, `Campaign`, `CampaignMember`.
- `Character`, `CharacterController`, `Relationship`.
- `Round`, `PlayerIntent`, `GameEvent`, `DiceRoll`.
- `SceneState`, `QuestState`, `Memory`, `StorySummary`.
- `AiJob`, `AiUsage`, `AuditEntry`.
Публичные серверные операции:
- создание и редактирование мира через coauthor session;
- подтверждение сгенерированного мира;
- создание кампании и приглашение участника;
- создание/назначение персонажа;
- отправка или изменение действия текущего раунда;
- отметка игрока как готового;
- принудительное закрытие раунда владельцем;
- получение истории, состояния персонажа и активной сцены;
- ручная корректировка состояния владельцем.
### Обработка раунда
1. Nitro сохраняет `PlayerIntent` и готовность игрока.
2. Транзакция блокирует раунд и создаёт ровно одну задачу после выполнения условия закрытия.
3. Worker собирает минимальный контекст.
4. AI определяет намерения, нужные проверки и действия AIгероев через типизированные tool calls.
5. Rules engine выполняет все броски и изменения механического состояния.
6. Результаты возвращаются AI для финальной narration.
7. Предложенные события и изменения проходят Zodвалидацию и проверку разрешённых переходов.
8. Narration, события, память и новое состояние сохраняются атомарно.
9. Supabase Realtime обновляет интерфейсы участников.
При timeout или ошибке OpenRouter задача повторяется с idempotency key. После исчерпания повторов раунд остаётся открываемым повторно владельцем; частичные изменения не сохраняются. OpenRouter поддерживает tool calling и JSON Schema outputs, которые следует использовать для типизированных AIопераций. [Tool calling](https://openrouter.ai/docs/guides/features/tool-calling), [structured outputs](https://openrouter.ai/docs/guides/features/structured-outputs).
## 4. Дорожная карта на 810 недель
### Недели 12 — фундамент
- Monorepo, Nuxt/Nitro, worker, CI и окружения.
- Supabase email/password Auth, email confirmation/recovery, RLS и базовая схема данных.
- Англоязычный UI: login, dashboard, world list.
- OpenRouter adapter, учёт токенов, дневные квоты и безопасное хранение ключа.
- Первый вертикальный тест: действие игрока → worker → ответ AI.
### Недели 34 — вселенные и персонажи
- Coauthor chat и структурированная генерация стартового набора.
- Preview/edit/confirm для мира.
- Создание кампании и персонажей.
- Приглашения, lobby, роли owner/player и AIгерои.
- 13+ фильтрация входных prompts и выходов модели.
### Недели 56 — игровой цикл
- Раунды, готовность участников и принудительное продолжение владельцем.
- Realtimeобновления.
- Rules engine и журнал бросков.
- AIDM orchestration, AIгерои и временная замена отсутствующих игроков.
- Защита от двойной обработки и конфликтующих действий.
### Недели 78 — память и стабильность
- Game events, relationships, memories и story summaries.
- Контекстный retrieval без векторной базы: сущности, локации, теги и PostgreSQL fulltext search.
- Retry, rate limits, usage dashboard и аудит изменений.
- E2Eсценарий полной партии и набор AIрегрессионных тестов.
### Недели 910 — закрытая альфа
- UXполировка, responsive web и onboarding.
- Наблюдаемость: ошибки, latency, стоимость раунда, размер контекста.
- Тестирование командой и приглашёнными пользователями.
- Исправление критических проблем и подготовка формы обратной связи.
## 5. Проверка и критерии приёмки
Обязательные сценарии:
- Создать fantasy, scifi и horrorмиры через coauthor chat.
- Отклонить или исправить неполную/невалидную AIструктуру.
- Два пользователя вступают в одну кампанию и видят одинаковое состояние.
- Раунд ждёт всех активных людей.
- Владелец продолжает без отсутствующего игрока, после чего его персонажа корректно подхватывает AI.
- Постоянный AIгерой сохраняет характер и отношения между сценами.
- Броски воспроизводимо отображают формулу, модификатор и итог.
- LLM не может напрямую изменить HP, инвентарь или результат броска.
- Повторный запрос, reconnect или retry не создаёт второй narration.
- OpenRouter timeout не повреждает состояние кампании.
- Пользователь не видит чужие приватные миры и кампании.
- 13+ фильтр блокирует запрещённый explicitконтент.
- После 1520 раундов AI корректно вспоминает ключевое событие из начала игры.
- Средняя стоимость и задержка раунда укладываются в установленные перед альфой квоты.
Перед приглашением внешних тестеров провести минимум 20 сценарных AIпрогонов с заранее ожидаемыми фактами, правилами и последствиями.
## 6. Зафиксированные ограничения
- Название `Dungeons & Ground` считается финальным, но перед публичным релизом обязательны проверка товарных знаков, домена и визуального сходства.
- Первая версия: web, English-first, обязательные email-аккаунты, private worlds и приглашения в кампании.
- Контент: 13+, без explicitматериалов.
- OpenRouter оплачивает проект; пользователи не вводят собственные ключи.
- Оплаты нет — используются дневные, пользовательские и кампанийные лимиты.
- MVP полностью текстовый.
- Не входят: публичный каталог, marketplace, карты, изображения, TTS, видеогенерация, полноценный 5e combat, нативный desktop/mobile и пользовательские ruleset.
- После альфы приоритет определяется метриками: удержание кампаний, завершённые раунды, стоимость AIхода, частота ручных исправлений и качество памяти.

View File

@@ -14,7 +14,7 @@ pnpm dev:all
Open `http://localhost:3000`. `pnpm dev:all` starts the Nuxt site and the AI worker in one terminal. To run them separately, use `pnpm dev` in the first terminal and `pnpm dev:worker` in the second. Open `http://localhost:3000`. `pnpm dev:all` starts the Nuxt site and the AI worker in one terminal. To run them separately, use `pnpm dev` in the first terminal and `pnpm dev:worker` in the second.
To verify the complete hosted-Supabase multiplayer path (two temporary guests, invite, AI character draft, persistent AI companion, shared readiness, AI resolution, and the next round), keep `dev:all` running and execute `pnpm smoke:multiplayer` in another terminal. To verify the complete hosted-Supabase multiplayer path (two temporary email accounts, invite, AI character draft, persistent AI companion, shared readiness, AI resolution, and the next round), keep `dev:all` running and execute `pnpm smoke:multiplayer` in another terminal.
Before starting either process, the root commands check the Supabase schema. If it is missing and `SUPABASE_DB_URL` is configured, they transactionally create all D&G tables, functions, triggers, indexes, and policies from `supabase/bootstrap.sql`. Copy the **Session pooler** URI from the Supabase Dashboard **Connect** panel into the root `.env` and replace the password placeholder with the URL-encoded database password. The database URL is server-only and must never use a `NUXT_PUBLIC_` prefix. Before starting either process, the root commands check the Supabase schema. If it is missing and `SUPABASE_DB_URL` is configured, they transactionally create all D&G tables, functions, triggers, indexes, and policies from `supabase/bootstrap.sql`. Copy the **Session pooler** URI from the Supabase Dashboard **Connect** panel into the root `.env` and replace the password placeholder with the URL-encoded database password. The database URL is server-only and must never use a `NUXT_PUBLIC_` prefix.
@@ -47,7 +47,7 @@ Use Node.js 18.20.5 or newer. The lockfile pins the web toolchain to the Node 18
## Production services ## Production services
1. Copy the Supabase **Session pooler** connection URI from **Connect** into `SUPABASE_DB_URL`. `pnpm dev:all` now detects an empty project and creates the complete schema automatically. `pnpm db:ensure` runs the same guarded bootstrap without starting the app. Manual SQL Editor installation remains available through `supabase/bootstrap.sql`. 1. Copy the Supabase **Session pooler** connection URI from **Connect** into `SUPABASE_DB_URL`. `pnpm dev:all` now detects an empty project and creates the complete schema automatically. `pnpm db:ensure` runs the same guarded bootstrap without starting the app. Manual SQL Editor installation remains available through `supabase/bootstrap.sql`.
2. In Supabase Auth settings, enable **Allow anonymous sign-ins**. In Auth URL Configuration, set the Site URL to `http://localhost:3000` and add `http://localhost:3000/auth/callback` as a Redirect URL. Email magic-link accounts remain optional and must be added to `public.allowlist`. Before external testing, enable CAPTCHA and review Supabase's anonymous sign-in rate limits so disposable guests cannot be used to evade AI quotas. 2. In Supabase Auth settings, enable the **Email** provider and disable **Allow anonymous sign-ins**. In Auth URL Configuration, set the Site URL to `http://localhost:3000`; add `http://localhost:3000/auth/callback` and `http://localhost:3000/auth/reset-password` as Redirect URLs. Configure SMTP before external testing so confirmation and recovery email is delivered reliably. CAPTCHA and Auth rate limits remain recommended.
3. Run `pnpm dev:worker` alongside the web process. Provision Redis only when BullMQ delivery is desired; otherwise the worker polls the Supabase outbox. 3. Run `pnpm dev:worker` alongside the web process. Provision Redis only when BullMQ delivery is desired; otherwise the worker polls the Supabase outbox.
4. Configure either `OPENROUTER_API_KEY` (default model `deepseek/deepseek-v4-flash`) or set `AI_PROVIDER=deepseek` with `DEEPSEEK_API_KEY` (default model `deepseek-v4-flash`, endpoint `https://api.deepseek.com/chat/completions`). 4. Configure either `OPENROUTER_API_KEY` (default model `deepseek/deepseek-v4-flash`) or set `AI_PROVIDER=deepseek` with `DEEPSEEK_API_KEY` (default model `deepseek-v4-flash`, endpoint `https://api.deepseek.com/chat/completions`).
@@ -55,10 +55,10 @@ If the worker reports `POST /rest/v1/rpc/claim_ai_job 404` and `/rest/v1/profile
## Weeks 34 flow ## Weeks 34 flow
1. Click **Enter the Alpha** to create a persistent guest session without email. Do not sign out or clear site storage unless you are prepared to lose that guest account. An allowlisted email magic link is still available as an alternative. 1. Click **Enter the Alpha** to open registration. Every account requires a display name, email, password, and 13+ confirmation. Existing users sign in with email/password; forgotten passwords use the email recovery flow.
2. Create a world in the dynamic coauthor chat. Unfinished conversations and generated drafts appear on the dashboard and resume after a reload. 2. Create a world in the dynamic coauthor chat. Unfinished conversations and generated drafts appear on the dashboard and resume after a reload.
3. Review every starting-world field, including the owner-only hidden threat, then confirm it. 3. Review every starting-world field, including the owner-only hidden threat, then confirm it.
4. Create a human character manually or ask the coauthor for an editable draft. Owners can add persistent AI companions the same way. 4. During world creation, the coauthor also creates three editable, universe-specific AI companions. A new campaign starts immediately with those companions and an owner-controlled hero. Additional players create a human character manually or ask the coauthor for an editable draft; owners can add more AI companions the same way.
5. The owner creates an expiring private invite link. Guest or allowlisted-email users join through `/join/:token`. 5. The owner creates an expiring private invite link. Signed-in email users join through `/join/:token`.
6. Players save actions and mark them ready. The final ready action queues the round automatically; the owner can also continue without waiting. 6. Players save actions and mark them ready. The final ready action queues the round automatically; the owner can also continue without waiting.
7. The worker resolves server-owned rolls and state, publishes narration, and opens the next round. Visible campaign tabs synchronize every two seconds and immediately when the tab regains focus. 7. The worker resolves server-owned rolls and state, publishes narration, and opens the next round. Visible campaign tabs synchronize every two seconds and immediately when the tab regains focus.

View File

@@ -1 +1,24 @@
:root{--acid:#d9f75f;--acid-dim:#596522;--ink:#eeeeE7;--muted:#888881;--line:#272725;--display:'Unbounded',sans-serif;--body:'Manrope',sans-serif;--mono:'DM Mono',monospace;color-scheme:dark}*{box-sizing:border-box}html{background:#0a0a0a;color:var(--ink);font-family:var(--body);scroll-behavior:smooth}body{margin:0;background:#0a0a0a}button,input,textarea{font:inherit}button,a{transition:filter .2s ease,opacity .2s ease}button:not(:disabled),a{cursor:pointer}button:hover:not(:disabled),a:hover{filter:brightness(1.12)}::selection{background:var(--acid);color:#070707}.noise{background-color:#0a0a0a;background-image:linear-gradient(rgba(255,255,255,.013) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.013) 1px,transparent 1px);background-size:34px 34px}textarea:focus,input:focus,button:focus-visible,a:focus-visible{outline:1px solid var(--acid);outline-offset:2px}@media(prefers-reduced-motion:reduce){*{animation-duration:.01ms!important;animation-iteration-count:1!important;scroll-behavior:auto!important}} :root{--acid:#d9f75f;--acid-dim:#596522;--ink:#eeeeE7;--muted:#888881;--line:#272725;--display:'Unbounded',sans-serif;--body:'Manrope',sans-serif;--mono:'DM Mono',monospace;color-scheme:dark}*{box-sizing:border-box}html{background:#0a0a0a;color:var(--ink);font-family:var(--body);scroll-behavior:smooth}body{margin:0;background:#0a0a0a}button,input,textarea{font:inherit}button,a{transition:filter .2s ease,opacity .2s ease}button:not(:disabled),a{cursor:pointer}button:hover:not(:disabled),a:hover{filter:brightness(1.12)}::selection{background:var(--acid);color:#070707}.noise{background-color:#0a0a0a;background-image:linear-gradient(rgba(255,255,255,.013) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.013) 1px,transparent 1px);background-size:34px 34px}textarea:focus,input:focus,button:focus-visible,a:focus-visible{outline:1px solid var(--acid);outline-offset:2px}@media(prefers-reduced-motion:reduce){*{animation-duration:.01ms!important;animation-iteration-count:1!important;scroll-behavior:auto!important}}
/* Keep account pages usable even when a route-level component stylesheet is delayed or missed. */
.auth-page{min-height:100vh;display:grid;place-content:center;justify-items:center;gap:28px;padding:42px 20px}
.auth-page .auth-card{width:min(480px,calc(100vw - 40px));padding:clamp(28px,5vw,48px);border:1px solid var(--line);background:linear-gradient(145deg,#11110f,#090909);box-shadow:0 35px 100px rgba(0,0,0,.48)}
.auth-page .auth-card header small{font:600 8px var(--mono);letter-spacing:.18em;color:var(--acid)}
.auth-page .auth-card header h1{margin:14px 0 12px;font:600 clamp(32px,6vw,52px)/1 var(--display);letter-spacing:-.06em}
.auth-page .auth-card header p{margin:0 0 30px;color:var(--muted);font-size:12px;line-height:1.7}
.auth-page .auth-card footer{margin-top:25px;padding-top:22px;border-top:1px solid var(--line);text-align:center;color:var(--muted);font-size:11px}
.auth-page .security-note{font:500 7px var(--mono);letter-spacing:.13em;color:var(--muted)}
.auth-page .security-note i{display:inline-block;width:5px;height:5px;margin-right:8px;border-radius:50%;background:var(--acid)}
.auth-page .auth-form{display:grid;gap:15px}
.auth-page .auth-form label{display:grid;gap:8px;font:600 8px var(--mono);letter-spacing:.11em;color:#b5b5ae}
.auth-page .auth-form input{box-sizing:border-box;width:100%;min-height:48px;padding:0 14px;border:1px solid #373732;background:#0a0a09;color:var(--ink);font:12px var(--body);outline:none}
.auth-page .auth-form input:focus{border-color:var(--acid)}
.auth-page .auth-form button{min-height:50px;border:0;background:var(--acid);color:#080808;font:700 9px var(--mono);letter-spacing:.12em}
.auth-page .auth-form button:disabled{opacity:.45;cursor:wait}
.auth-page .form-error,.auth-page .form-success{margin:0;padding:12px 14px;border:1px solid #6b372e;background:#221310;color:#ffab98;font:500 9px/1.55 var(--mono)}
.auth-page .form-success{border-color:#526425;background:#151a0d;color:var(--acid)}
.auth-page .form-link{color:var(--acid);text-decoration:none;font-weight:600}
.auth-page .field-row{display:flex;align-items:center;justify-content:space-between}
.auth-page .field-row a{color:var(--muted);font:500 8px var(--mono)}
.auth-page .auth-form .consent{grid-template-columns:18px 1fr!important;align-items:start!important;font:400 10px/1.5 var(--body)!important;letter-spacing:0!important;color:var(--muted)!important}
.auth-page .auth-form .consent input{width:16px!important;min-height:16px!important;margin:1px 0 0;padding:0!important;accent-color:var(--acid)}

View File

@@ -1,18 +1,17 @@
<script setup lang="ts"> <script setup lang="ts">
defineProps<{ section?: string }>() defineProps<{ section?: string }>()
const { session, restore, signOut } = useDngAuth() const { session, restore } = useDngAuth()
onMounted(() => void restore()) onMounted(() => void restore())
const initials = computed(() => { const initials = computed(() => {
const email = session.value?.user.email ?? '' const displayName = session.value?.user.user_metadata?.display_name
return email.slice(0, 2).toUpperCase() || 'G' const source = typeof displayName === 'string' && displayName.trim() ? displayName : session.value?.user.email ?? ''
return source.trim().split(/\s+/).map(part => part[0]).join('').slice(0, 2).toUpperCase() || 'D&G'
})
const avatarUrl = computed(() => {
const value = session.value?.user.user_metadata?.avatar_url
return typeof value === 'string' && value ? value : ''
}) })
async function leave() {
if (session.value?.user.is_anonymous && !window.confirm('This guest account cannot be recovered after sign out. Leave anyway?')) return
await signOut()
await navigateTo('/')
}
</script> </script>
<template> <template>
@@ -22,7 +21,9 @@ async function leave() {
<div class="topbar-center"><span class="status-dot" /> PRIVATE ALPHA <b v-if="section">/ {{ section }}</b></div> <div class="topbar-center"><span class="status-dot" /> PRIVATE ALPHA <b v-if="section">/ {{ section }}</b></div>
<div class="topbar-actions"> <div class="topbar-actions">
<NuxtLink to="/dashboard" class="icon-link" aria-label="Dashboard"></NuxtLink> <NuxtLink to="/dashboard" class="icon-link" aria-label="Dashboard"></NuxtLink>
<button v-if="session" class="avatar" :title="session.user.is_anonymous ? 'Guest session — sign out' : `Sign out ${session.user.email ?? ''}`" @click="leave">{{ initials }}</button> <NuxtLink v-if="session" to="/profile" class="avatar" :title="`Open profile for ${session.user.email ?? ''}`" aria-label="Open profile">
<span>{{ initials }}</span><img v-if="avatarUrl" :src="avatarUrl" alt="">
</NuxtLink>
<div v-else class="avatar">D&G</div> <div v-else class="avatar">D&G</div>
</div> </div>
</header> </header>
@@ -31,5 +32,5 @@ async function leave() {
</template> </template>
<style scoped> <style scoped>
.shell{min-height:100vh}.topbar{position:sticky;top:0;z-index:20;height:76px;padding:0 clamp(18px,4vw,64px);display:grid;grid-template-columns:1fr auto 1fr;align-items:center;border-bottom:1px solid var(--line);background:rgba(10,10,10,.9);backdrop-filter:blur(18px)}.topbar-center{font:500 10px/1 var(--mono);color:var(--muted);letter-spacing:.18em}.topbar-center b{color:var(--ink);font-weight:500}.status-dot{display:inline-block;width:6px;height:6px;margin-right:8px;border-radius:50%;background:var(--acid);box-shadow:0 0 12px var(--acid)}.topbar-actions{justify-self:end;display:flex;align-items:center;gap:14px}.icon-link{display:grid;place-items:center;width:36px;height:36px;border:1px solid var(--line);color:var(--muted);text-decoration:none}.avatar{display:grid;place-items:center;width:36px;height:36px;padding:0;border:0;border-radius:50%;background:var(--acid);color:#0a0a0a;font:700 10px var(--mono)}@media(max-width:700px){.topbar{grid-template-columns:1fr auto}.topbar-center{display:none}} .shell{min-height:100vh}.topbar{position:sticky;top:0;z-index:20;height:76px;padding:0 clamp(18px,4vw,64px);display:grid;grid-template-columns:1fr auto 1fr;align-items:center;border-bottom:1px solid var(--line);background:rgba(10,10,10,.9);backdrop-filter:blur(18px)}.topbar-center{font:500 10px/1 var(--mono);color:var(--muted);letter-spacing:.18em}.topbar-center b{color:var(--ink);font-weight:500}.status-dot{display:inline-block;width:6px;height:6px;margin-right:8px;border-radius:50%;background:var(--acid);box-shadow:0 0 12px var(--acid)}.topbar-actions{justify-self:end;display:flex;align-items:center;gap:14px}.icon-link{display:grid;place-items:center;width:36px;height:36px;border:1px solid var(--line);color:var(--muted);text-decoration:none}.avatar{position:relative;overflow:hidden;display:grid;place-items:center;width:36px;height:36px;padding:0;border:0;border-radius:50%;background:var(--acid);color:#0a0a0a;text-decoration:none;font:700 10px var(--mono)}.avatar img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.avatar span{position:relative}@media(max-width:700px){.topbar{grid-template-columns:1fr auto}.topbar-center{display:none}}
</style> </style>

View File

@@ -0,0 +1,28 @@
<script setup lang="ts">
defineProps<{
eyebrow: string
title: string
subtitle: string
}>()
</script>
<template>
<main class="auth-page noise">
<div class="brand"><AppMark /></div>
<section class="auth-card">
<header>
<small>{{ eyebrow }}</small>
<h1>{{ title }}</h1>
<p>{{ subtitle }}</p>
</header>
<slot />
<footer><slot name="footer" /></footer>
</section>
<p class="security-note"><i /> PRIVATE WORLDS · SECURE SUPABASE ACCOUNT</p>
</main>
</template>
<style scoped>
.auth-page{min-height:100vh;display:grid;place-content:center;justify-items:center;gap:28px;padding:42px 20px}.auth-card{width:min(480px,calc(100vw - 40px));padding:clamp(28px,5vw,48px);border:1px solid var(--line);background:linear-gradient(145deg,#11110f,#090909);box-shadow:0 35px 100px rgba(0,0,0,.48)}header small{font:600 8px var(--mono);letter-spacing:.18em;color:var(--acid)}header h1{margin:14px 0 12px;font:600 clamp(32px,6vw,52px)/1 var(--display);letter-spacing:-.06em}header p{margin:0 0 30px;color:var(--muted);font-size:12px;line-height:1.7}footer{margin-top:25px;padding-top:22px;border-top:1px solid var(--line);text-align:center;color:var(--muted);font-size:11px}.security-note{font:500 7px var(--mono);letter-spacing:.13em;color:var(--muted)}.security-note i{display:inline-block;width:5px;height:5px;margin-right:8px;border-radius:50%;background:var(--acid)}
:deep(.auth-form){display:grid;gap:15px}:deep(.auth-form label){display:grid;gap:8px;font:600 8px var(--mono);letter-spacing:.11em;color:#b5b5ae}:deep(.auth-form input){box-sizing:border-box;width:100%;min-height:48px;padding:0 14px;border:1px solid #373732;background:#0a0a09;color:var(--ink);font:12px var(--body);outline:none}:deep(.auth-form input:focus){border-color:var(--acid)}:deep(.auth-form button){min-height:50px;border:0;background:var(--acid);color:#080808;font:700 9px var(--mono);letter-spacing:.12em}:deep(.auth-form button:disabled){opacity:.45;cursor:wait}:deep(.form-error),:deep(.form-success){margin:0;padding:12px 14px;border:1px solid #6b372e;background:#221310;color:#ffab98;font:500 9px/1.55 var(--mono)}:deep(.form-success){border-color:#526425;background:#151a0d;color:var(--acid)}:deep(.form-link){color:var(--acid);text-decoration:none;font-weight:600}:deep(.field-row){display:flex;align-items:center;justify-content:space-between}:deep(.field-row a){color:var(--muted);font:500 8px var(--mono)}
</style>

View File

@@ -1,8 +1,16 @@
<script setup lang="ts"> <script setup lang="ts">
import type { WorldStarter } from '@dng/shared' import type { CharacterDraft, WorldStarter } from '@dng/shared'
const draft = defineModel<WorldStarter>({ required: true }) const draft = defineModel<WorldStarter>({ required: true })
defineEmits<{ revise: []; confirm: [] }>() defineEmits<{ revise: []; confirm: [] }>()
function updateInventory(companion: CharacterDraft, event: Event) {
companion.inventory = (event.target as HTMLInputElement).value
.split(',')
.map(item => item.trim())
.filter(Boolean)
.slice(0, 12)
}
</script> </script>
<template> <template>
@@ -21,6 +29,7 @@ defineEmits<{ revise: []; confirm: [] }>()
<section class="wide private-truth"><label>PRIVATE GM TRUTH</label><textarea v-model="draft.hiddenThreat" rows="4" /><small>This hidden threat or goal is visible only to the owner and the Groundkeeper.</small></section> <section class="wide private-truth"><label>PRIVATE GM TRUTH</label><textarea v-model="draft.hiddenThreat" rows="4" /><small>This hidden threat or goal is visible only to the owner and the Groundkeeper.</small></section>
<section class="wide"><label>KEY PEOPLE</label><div class="entities"><article v-for="npc in draft.npcs" :key="npc.id"><small>NPC</small><input v-model="npc.name"><textarea v-model="npc.summary" rows="3" /></article></div></section> <section class="wide"><label>KEY PEOPLE</label><div class="entities"><article v-for="npc in draft.npcs" :key="npc.id"><small>NPC</small><input v-model="npc.name"><textarea v-model="npc.summary" rows="3" /></article></div></section>
<section class="wide"><label>FACTIONS</label><div class="entities two"><article v-for="faction in draft.factions" :key="faction.id"><small>FACTION</small><input v-model="faction.name"><textarea v-model="faction.summary" rows="3" /></article></div></section> <section class="wide"><label>FACTIONS</label><div class="entities two"><article v-for="faction in draft.factions" :key="faction.id"><small>FACTION</small><input v-model="faction.name"><textarea v-model="faction.summary" rows="3" /></article></div></section>
<section class="wide"><label>AI COMPANIONS</label><p class="section-note">These universe-specific heroes join the campaign automatically.</p><div class="entities companion-grid"><article v-for="(companion, index) in draft.companions" :key="index" class="companion-card"><small>AI HERO</small><input v-model="companion.name" maxlength="80" aria-label="Companion name"><textarea v-model="companion.concept" maxlength="600" rows="4" aria-label="Companion concept" /><div class="companion-stats"><label>HP<input v-model.number="companion.hp" type="number" min="1" :max="companion.maxHp"></label><label>MAX<input v-model.number="companion.maxHp" type="number" min="1" max="100"></label><label>DEF<input v-model.number="companion.defense" type="number" min="1" max="40"></label><label>PROF<input v-model.number="companion.proficiency" type="number" min="1" max="10"></label><label v-for="ability in (['str','dex','con','int','wis','cha'] as const)" :key="ability">{{ ability }}<input v-model.number="companion.abilities[ability]" type="number" min="1" max="30"></label></div><label class="inventory-label">INVENTORY<input :value="companion.inventory.join(', ')" maxlength="800" @input="updateInventory(companion, $event)"></label><details><summary>VOICE & PERSONALITY</summary><input v-model="companion.persona.voice" maxlength="240" placeholder="Voice"><input v-model="companion.persona.motivation" maxlength="300" placeholder="Motivation"><input v-model="companion.persona.flaw" maxlength="300" placeholder="Flaw"><input v-model="companion.persona.bond" maxlength="300" placeholder="Bond"></details></article></div></section>
<section><label>OPENING SCENE</label><textarea v-model="draft.openingScene" rows="6" /></section> <section><label>OPENING SCENE</label><textarea v-model="draft.openingScene" rows="6" /></section>
<section><label>CONTENT BOUNDARIES</label><div v-for="(_, index) in draft.contentBoundaries" :key="index" class="boundary"><input v-model="draft.contentBoundaries[index]"><button type="button" aria-label="Remove boundary" @click="draft.contentBoundaries.splice(index, 1)">×</button></div><button class="add" type="button" @click="draft.contentBoundaries.push('')"> ADD BOUNDARY</button></section> <section><label>CONTENT BOUNDARIES</label><div v-for="(_, index) in draft.contentBoundaries" :key="index" class="boundary"><input v-model="draft.contentBoundaries[index]"><button type="button" aria-label="Remove boundary" @click="draft.contentBoundaries.splice(index, 1)">×</button></div><button class="add" type="button" @click="draft.contentBoundaries.push('')"> ADD BOUNDARY</button></section>
</div> </div>
@@ -29,6 +38,6 @@ defineEmits<{ revise: []; confirm: [] }>()
</template> </template>
<style scoped> <style scoped>
.preview{max-width:1300px;width:100%;padding:clamp(40px,5vw,76px)}header{display:flex;justify-content:space-between;align-items:end;gap:20px}.kicker,label{font:600 8px var(--mono);letter-spacing:.15em;color:var(--acid)}header>div{flex:1}header input{border:0;border-bottom:1px solid var(--line);font:600 clamp(30px,4vw,54px) var(--display);letter-spacing:-.05em;padding:12px 0;background:transparent}.revise,.add{background:transparent;color:var(--muted);border:1px solid var(--line);padding:12px;font:500 8px var(--mono)}.edit-note{color:var(--muted);font-size:11px}.grid{display:grid;grid-template-columns:1fr 1fr;border-top:1px solid var(--line);border-left:1px solid var(--line);margin-top:28px}.grid>section{padding:26px;border-right:1px solid var(--line);border-bottom:1px solid var(--line)}.wide{grid-column:1/-1}input,textarea{box-sizing:border-box;width:100%;margin-top:12px;padding:13px;resize:vertical;background:#10100f;border:1px solid var(--line);color:var(--ink);font:12px/1.55 var(--body)}.entities{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-top:18px}.entities.two{grid-template-columns:repeat(2,1fr)}.entities article{padding:16px;border:1px solid var(--line);background:#0c0c0b}.entities small{font:500 7px var(--mono);color:var(--acid)}.boundary{display:flex}.boundary input{margin-top:8px}.boundary button{margin-top:8px;width:42px;border:1px solid var(--line);background:#151513;color:var(--muted)}.add{margin-top:12px}footer{position:sticky;bottom:0;display:flex;justify-content:space-between;align-items:center;padding:18px 22px;background:#11110f;border:1px solid var(--line);margin-top:24px}footer p{margin:0;display:flex;flex-direction:column;font:600 8px var(--mono);color:var(--acid)}footer p span{margin-top:5px;color:var(--muted);font-weight:400}footer>button{min-height:48px;border:0;background:var(--acid);color:#080808;padding:0 24px;font:600 9px var(--mono)}@media(max-width:760px){.preview{padding:36px 18px}header{align-items:stretch;flex-direction:column}.grid{grid-template-columns:1fr}.wide{grid-column:auto}.entities,.entities.two{grid-template-columns:1fr}footer{align-items:stretch;flex-direction:column;gap:14px}} .preview{max-width:1300px;width:100%;padding:clamp(40px,5vw,76px)}header{display:flex;justify-content:space-between;align-items:end;gap:20px}.kicker,label{font:600 8px var(--mono);letter-spacing:.15em;color:var(--acid)}header>div{flex:1}header input{border:0;border-bottom:1px solid var(--line);font:600 clamp(30px,4vw,54px) var(--display);letter-spacing:-.05em;padding:12px 0;background:transparent}.revise,.add{background:transparent;color:var(--muted);border:1px solid var(--line);padding:12px;font:500 8px var(--mono)}.edit-note,.section-note{color:var(--muted);font-size:11px}.section-note{margin:9px 0 0}.grid{display:grid;grid-template-columns:1fr 1fr;border-top:1px solid var(--line);border-left:1px solid var(--line);margin-top:28px}.grid>section{padding:26px;border-right:1px solid var(--line);border-bottom:1px solid var(--line)}.wide{grid-column:1/-1}input,textarea{box-sizing:border-box;width:100%;margin-top:12px;padding:13px;resize:vertical;background:#10100f;border:1px solid var(--line);color:var(--ink);font:12px/1.55 var(--body)}.entities{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-top:18px}.entities.two{grid-template-columns:repeat(2,1fr)}.entities article{padding:16px;border:1px solid var(--line);background:#0c0c0b}.entities small{font:500 7px var(--mono);color:var(--acid)}.companion-stats{display:grid;grid-template-columns:repeat(5,1fr);gap:5px;margin-top:12px}.companion-stats label{color:var(--muted);font-size:6px}.companion-stats input{margin-top:5px;padding:7px;text-align:center}.inventory-label{display:block;margin-top:12px;color:var(--muted)}.inventory-label input{margin-top:6px}.companion-card details{margin-top:12px;border-top:1px solid var(--line);padding-top:10px}.companion-card summary{cursor:pointer;color:var(--muted);font:600 7px var(--mono);letter-spacing:.1em}.companion-card details input{margin-top:7px}.boundary{display:flex}.boundary input{margin-top:8px}.boundary button{margin-top:8px;width:42px;border:1px solid var(--line);background:#151513;color:var(--muted)}.add{margin-top:12px}footer{position:sticky;bottom:0;display:flex;justify-content:space-between;align-items:center;padding:18px 22px;background:#11110f;border:1px solid var(--line);margin-top:24px}footer p{margin:0;display:flex;flex-direction:column;font:600 8px var(--mono);color:var(--acid)}footer p span{margin-top:5px;color:var(--muted);font-weight:400}footer>button{min-height:48px;border:0;background:var(--acid);color:#080808;padding:0 24px;font:600 9px var(--mono)}@media(max-width:760px){.preview{padding:36px 18px}header{align-items:stretch;flex-direction:column}.grid{grid-template-columns:1fr}.wide{grid-column:auto}.entities,.entities.two{grid-template-columns:1fr}.companion-stats{grid-template-columns:repeat(2,1fr)}footer{align-items:stretch;flex-direction:column;gap:14px}}
.private-truth{background:linear-gradient(90deg,rgba(207,255,70,.035),transparent)}.private-truth small{display:block;margin-top:9px;color:var(--muted);font-size:9px} .private-truth{background:linear-gradient(90deg,rgba(207,255,70,.035),transparent)}.private-truth small{display:block;margin-top:9px;color:var(--muted);font-size:9px}
</style> </style>

View File

@@ -16,6 +16,11 @@ const defaultWorld: WorldStarter = {
{ id: 'fac_heliograph', kind: 'faction', name: 'Heliograph Compact', summary: 'A mercantile coalition that owns the relay network.', tags: ['corporate'], secrets: [] }, { id: 'fac_heliograph', kind: 'faction', name: 'Heliograph Compact', summary: 'A mercantile coalition that owns the relay network.', tags: ['corporate'], secrets: [] },
{ id: 'fac_quiet', kind: 'faction', name: 'The Quiet Choir', summary: 'Pilgrims who believe signals can remember the dead.', tags: ['mystic'], secrets: [] }, { id: 'fac_quiet', kind: 'faction', name: 'The Quiet Choir', summary: 'Pilgrims who believe signals can remember the dead.', tags: ['mystic'], secrets: [] },
], ],
companions: [
{ name: 'Rook-7', concept: 'A security intelligence in a weathered rescue frame.', abilities: { str: 16, dex: 11, con: 15, int: 10, wis: 12, cha: 8 }, hp: 15, maxHp: 15, defense: 15, proficiency: 2, inventory: ['Arc baton', 'Emergency beacon'], persona: { voice: 'Direct and protective.', motivation: 'Keep the crew alive long enough to learn the truth.', flaw: 'Treats uncertainty as a threat.', bond: 'The Orison crew gave Rook a second purpose.' } },
{ name: 'Sable Thread', concept: 'A probabilistic navigator who reads possible futures as tangled routes.', abilities: { str: 8, dex: 14, con: 10, int: 16, wis: 13, cha: 11 }, hp: 10, maxHp: 10, defense: 13, proficiency: 2, inventory: ['Route prism', 'Vacuum line'], persona: { voice: 'Careful, elliptical, and precise.', motivation: 'Find the future in which everyone returns.', flaw: 'Can hesitate when too many paths look viable.', bond: 'Trusts the party to choose what prediction cannot.' } },
{ name: 'Morrow Coil', concept: 'A former relay technician rebuilt around experimental signal hardware.', abilities: { str: 11, dex: 12, con: 13, int: 14, wis: 10, cha: 13 }, hp: 12, maxHp: 12, defense: 12, proficiency: 2, inventory: ['Signal probe', 'Insulated field coat'], persona: { voice: 'Warm humor under technical jargon.', motivation: 'Prove the relay can be understood instead of destroyed.', flaw: 'Cannot leave a broken machine alone.', bond: 'Believes this party is the last honest crew in the sector.' } },
],
hook: 'Dock with the silent relay, locate the source of the impossible distress call, and decide whether its warning should be believed.', hook: 'Dock with the silent relay, locate the source of the impossible distress call, and decide whether its warning should be believed.',
hiddenThreat: 'A causality fracture is teaching the relay to choose which future becomes real.', hiddenThreat: 'A causality fracture is teaching the relay to choose which future becomes real.',
openingScene: 'The Orison drifts beneath the relays vast black vanes. Every console shows the same countdown: 00:17:42. Then your own voice breaks through the static: “Do not open the central archive.”', openingScene: 'The Orison drifts beneath the relays vast black vanes. Every console shows the same countdown: 00:17:42. Then your own voice breaks through the static: “Do not open the central archive.”',

View File

@@ -19,6 +19,13 @@ interface AuthResponse {
user: DngAuthUser user: DngAuthUser
} }
interface SignUpResponse {
access_token?: string | null
refresh_token?: string | null
expires_in?: number | null
user: DngAuthUser
}
const STORAGE_KEY = 'dng-auth-session' const STORAGE_KEY = 'dng-auth-session'
export function useDngAuth() { export function useDngAuth() {
@@ -48,6 +55,10 @@ export function useDngAuth() {
} }
} }
function isEmailAccount(user: DngAuthUser | undefined): boolean {
return Boolean(user?.email && !user.is_anonymous)
}
function parseStoredSession(value: string): DngSession | null { function parseStoredSession(value: string): DngSession | null {
try { try {
const saved = JSON.parse(value) as Partial<DngSession> const saved = JSON.parse(value) as Partial<DngSession>
@@ -97,7 +108,11 @@ export function useDngAuth() {
} }
async function restore() { async function restore() {
if (!import.meta.client || hydrated.value) return session.value if (!import.meta.client) return session.value
if (hydrated.value) {
if (session.value && !isEmailAccount(session.value.user)) persist(null)
return session.value
}
let restoredFromStorage = false let restoredFromStorage = false
const hash = new URLSearchParams(window.location.hash.replace(/^#/, '')) const hash = new URLSearchParams(window.location.hash.replace(/^#/, ''))
@@ -133,37 +148,134 @@ export function useDngAuth() {
await refresh() await refresh()
} }
} }
if (session.value && !isEmailAccount(session.value.user)) persist(null)
hydrated.value = true hydrated.value = true
return session.value return session.value
} }
async function requestMagicLink(email: string) { async function signUp(displayName: string, email: string, password: string) {
const redirectTo = `${window.location.origin}/auth/callback` const redirectTo = `${window.location.origin}/auth/callback`
await $fetch(`${config.public.supabaseUrl}/auth/v1/otp?redirect_to=${encodeURIComponent(redirectTo)}`, { const response = await $fetch<SignUpResponse>(`${config.public.supabaseUrl}/auth/v1/signup?redirect_to=${encodeURIComponent(redirectTo)}`, {
method: 'POST',
headers: authHeaders(),
body: { email: email.trim().toLowerCase(), create_user: true },
})
}
async function signInAnonymously() {
const response = await $fetch<AuthResponse>(`${config.public.supabaseUrl}/auth/v1/signup`, {
method: 'POST', method: 'POST',
headers: authHeaders(), headers: authHeaders(),
body: { body: {
data: { display_name: 'Guest Adventurer' }, email: email.trim().toLowerCase(),
gotrue_meta_security: {}, password,
data: { display_name: displayName.trim() },
}, },
}) })
if (response.access_token && response.refresh_token && response.expires_in) {
const next = fromResponse({
access_token: response.access_token,
refresh_token: response.refresh_token,
expires_in: response.expires_in,
user: response.user,
})
persist(next)
hydrated.value = true
return { session: next, needsEmailConfirmation: false }
}
return { session: null, needsEmailConfirmation: true }
}
async function signIn(email: string, password: string) {
const response = await $fetch<AuthResponse>(`${config.public.supabaseUrl}/auth/v1/token?grant_type=password`, {
method: 'POST',
headers: authHeaders(),
body: { email: email.trim().toLowerCase(), password },
})
const next = fromResponse(response) const next = fromResponse(response)
if (!isEmailAccount(next.user)) throw new Error('An email account is required.')
persist(next) persist(next)
hydrated.value = true hydrated.value = true
return next return next
} }
async function requestPasswordReset(email: string) {
const redirectTo = `${window.location.origin}/auth/reset-password`
await $fetch(`${config.public.supabaseUrl}/auth/v1/recover?redirect_to=${encodeURIComponent(redirectTo)}`, {
method: 'POST',
headers: authHeaders(),
body: { email: email.trim().toLowerCase() },
})
}
async function updatePassword(password: string) {
const token = await accessToken()
const user = normalizeUser(await $fetch<DngAuthUser>(`${config.public.supabaseUrl}/auth/v1/user`, {
method: 'PUT',
headers: authHeaders(token),
body: { password },
}))
if (session.value) persist({ ...session.value, user })
return user
}
async function updateUserMetadata(data: Record<string, unknown>) {
const token = await accessToken()
const user = normalizeUser(await $fetch<DngAuthUser>(`${config.public.supabaseUrl}/auth/v1/user`, {
method: 'PUT',
headers: authHeaders(token),
body: { data },
}))
if (session.value) persist({ ...session.value, user })
return user
}
async function avatarStorageRequest(path: string, options: RequestInit) {
const token = await accessToken()
const baseUrl = String(config.public.supabaseUrl).replace(/\/$/, '')
const response = await fetch(`${baseUrl}/storage/v1/${path}`, {
...options,
headers: {
apikey: config.public.supabaseAnonKey,
Authorization: `Bearer ${token}`,
...options.headers,
},
})
if (!response.ok) {
const payload = await response.json().catch(() => null) as { message?: string; error?: string } | null
throw new Error(payload?.message || payload?.error || `Profile picture request failed (${response.status}).`)
}
}
async function uploadAvatar(file: File) {
if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) {
throw new Error('Choose a JPG, PNG, or WebP image.')
}
if (file.size > 2 * 1024 * 1024) throw new Error('Profile pictures must be 2 MB or smaller.')
await restore()
if (!session.value) throw new Error('Sign in to update your profile picture.')
const path = `${session.value.user.id}/avatar`
const body = new FormData()
body.append('cacheControl', '3600')
body.append('', file)
await avatarStorageRequest(`object/profile-avatars/${path}`, {
method: 'POST',
headers: { 'x-upsert': 'true' },
body,
})
return path
}
async function removeAvatar() {
await restore()
if (!session.value) throw new Error('Sign in to update your profile picture.')
const path = `${session.value.user.id}/avatar`
await avatarStorageRequest('object/profile-avatars', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prefixes: [path] }),
})
}
async function accessToken() { async function accessToken() {
await restore() await restore()
if (!session.value) throw new Error('Enter the alpha to continue.') if (!session.value) throw new Error('Enter the alpha to continue.')
if (!isEmailAccount(session.value.user)) {
persist(null)
throw new Error('Sign in with an email account to continue.')
}
if (session.value.expiresAt <= Date.now() + 60_000) await refresh() if (session.value.expiresAt <= Date.now() + 60_000) await refresh()
if (!session.value) throw new Error('Your session expired. Sign in again.') if (!session.value) throw new Error('Your session expired. Sign in again.')
return session.value.accessToken return session.value.accessToken
@@ -184,5 +296,20 @@ export function useDngAuth() {
hydrated.value = true hydrated.value = true
} }
return { session, hydrated, restore, refresh, requestMagicLink, signInAnonymously, accessToken, signOut, invalidate } return {
session,
hydrated,
restore,
refresh,
signUp,
signIn,
requestPasswordReset,
updatePassword,
updateUserMetadata,
uploadAvatar,
removeAvatar,
accessToken,
signOut,
invalidate,
}
} }

View File

@@ -3,6 +3,13 @@ export default defineNuxtConfig({
devtools: { enabled: false }, devtools: { enabled: false },
css: ['~/assets/css/main.css'], css: ['~/assets/css/main.css'],
modules: [], modules: [],
nitro: {
// Nitro 2.10 resolves file-backed assets relative to its split runtime
// chunk, which makes every /_nuxt request fail outside the Docker-only
// symlink workaround. Embedding them keeps every production launcher
// (preview, Docker, and managed hosts) on the same reliable code path.
serveStatic: 'inline',
},
runtimeConfig: { runtimeConfig: {
aiProvider: process.env.AI_PROVIDER ?? 'openrouter', aiProvider: process.env.AI_PROVIDER ?? 'openrouter',
openrouterApiKey: process.env.OPENROUTER_API_KEY, openrouterApiKey: process.env.OPENROUTER_API_KEY,

View File

@@ -19,8 +19,8 @@ onMounted(async () => {
<template> <template>
<div class="callback noise"> <div class="callback noise">
<AppMark /> <AppMark />
<p v-if="!error">VERIFYING YOUR SIGNAL</p> <p v-if="!error">VERIFYING YOUR EMAIL</p>
<template v-else><p class="error">{{ error }}</p><NuxtLink to="/">REQUEST A NEW LINK</NuxtLink></template> <template v-else><p class="error">{{ error }}</p><NuxtLink to="/auth/sign-in">BACK TO SIGN IN</NuxtLink></template>
</div> </div>
</template> </template>

View File

@@ -0,0 +1,33 @@
<script setup lang="ts">
const { requestPasswordReset } = useDngAuth()
const email = ref('')
const busy = ref(false)
const error = ref('')
const sent = ref(false)
async function submit() {
busy.value = true
error.value = ''
try {
await requestPasswordReset(email.value)
sent.value = true
} catch (cause) {
const value = cause as { data?: { msg?: string; message?: string }; message?: string }
error.value = value.data?.msg ?? value.data?.message ?? value.message ?? 'Could not send the reset email.'
} finally {
busy.value = false
}
}
</script>
<template>
<AuthCard eyebrow="ACCOUNT RECOVERY" title="RESET THE SIGNAL." subtitle="Enter your account email. If it exists, Supabase will send a secure password reset link.">
<p v-if="sent" class="form-success" role="status">CHECK YOUR EMAIL. The recovery link can be used once and expires automatically.</p>
<form v-else class="auth-form" @submit.prevent="submit">
<label>EMAIL<input v-model="email" name="email" type="email" autocomplete="email" required placeholder="you@example.com"></label>
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
<button :disabled="busy">{{ busy ? 'SENDING…' : 'SEND RESET LINK →' }}</button>
</form>
<template #footer><NuxtLink class="form-link" to="/auth/sign-in"> BACK TO SIGN IN</NuxtLink></template>
</AuthCard>
</template>

View File

@@ -0,0 +1,54 @@
<script setup lang="ts">
const auth = useDngAuth()
const password = ref('')
const confirmation = ref('')
const busy = ref(false)
const ready = ref(false)
const error = ref('')
onMounted(async () => {
try {
const session = await auth.restore()
if (!session) throw new Error('This recovery link is invalid or expired.')
ready.value = true
} catch (cause) {
error.value = cause instanceof Error ? cause.message : 'Could not verify the recovery link.'
}
})
async function submit() {
error.value = ''
if (password.value.length < 8) {
error.value = 'Password must contain at least 8 characters.'
return
}
if (password.value !== confirmation.value) {
error.value = 'Passwords do not match.'
return
}
busy.value = true
try {
await auth.updatePassword(password.value)
await navigateTo('/dashboard', { replace: true })
} catch (cause) {
const value = cause as { data?: { msg?: string; message?: string }; message?: string }
error.value = value.data?.msg ?? value.data?.message ?? value.message ?? 'Could not update the password.'
} finally {
busy.value = false
}
}
</script>
<template>
<AuthCard eyebrow="SECURE RECOVERY" title="CHOOSE A NEW PASSWORD." subtitle="Set a new password for your Dungeons & Ground account.">
<p v-if="!ready && !error" class="form-success">VERIFYING RECOVERY LINK</p>
<form v-if="ready" class="auth-form" @submit.prevent="submit">
<label>NEW PASSWORD<input v-model="password" name="password" type="password" autocomplete="new-password" minlength="8" required placeholder="At least 8 characters"></label>
<label>CONFIRM PASSWORD<input v-model="confirmation" name="password-confirmation" type="password" autocomplete="new-password" minlength="8" required placeholder="Repeat your password"></label>
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
<button :disabled="busy">{{ busy ? 'UPDATING…' : 'UPDATE PASSWORD →' }}</button>
</form>
<p v-else-if="error" class="form-error" role="alert">{{ error }}</p>
<template #footer><NuxtLink class="form-link" to="/auth/sign-in">BACK TO SIGN IN</NuxtLink></template>
</AuthCard>
</template>

View File

@@ -0,0 +1,45 @@
<script setup lang="ts">
const auth = useDngAuth()
const email = ref('')
const password = ref('')
const busy = ref(false)
const error = ref('')
function messageFrom(cause: unknown) {
const value = cause as { data?: { msg?: string; message?: string; error_description?: string }; message?: string }
return value.data?.msg ?? value.data?.message ?? value.data?.error_description ?? value.message ?? 'Sign-in failed. Check your email and password.'
}
async function submit() {
busy.value = true
error.value = ''
try {
await auth.signIn(email.value, password.value)
const requested = localStorage.getItem('dng-post-auth-redirect')
localStorage.removeItem('dng-post-auth-redirect')
const destination = requested?.startsWith('/') && !requested.startsWith('//') ? requested : '/dashboard'
await navigateTo(destination, { replace: true })
} catch (cause) {
error.value = messageFrom(cause)
} finally {
busy.value = false
}
}
onMounted(async () => {
await auth.restore()
if (auth.session.value) await navigateTo('/dashboard', { replace: true })
})
</script>
<template>
<AuthCard eyebrow="ACCOUNT ACCESS" title="WELCOME BACK." subtitle="Sign in to continue your private worlds and shared campaigns.">
<form class="auth-form" @submit.prevent="submit">
<label>EMAIL<input v-model="email" name="email" type="email" autocomplete="email" required placeholder="you@example.com"></label>
<label><span class="field-row"><span>PASSWORD</span><NuxtLink to="/auth/forgot-password">FORGOT?</NuxtLink></span><input v-model="password" name="password" type="password" autocomplete="current-password" required placeholder="Your password"></label>
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
<button :disabled="busy">{{ busy ? 'SIGNING IN…' : 'SIGN IN →' }}</button>
</form>
<template #footer>New to D&G? <NuxtLink class="form-link" to="/auth/sign-up">CREATE ACCOUNT</NuxtLink></template>
</AuthCard>
</template>

View File

@@ -0,0 +1,80 @@
<script setup lang="ts">
const auth = useDngAuth()
const displayName = ref('')
const email = ref('')
const password = ref('')
const confirmation = ref('')
const ageConfirmed = ref(false)
const busy = ref(false)
const error = ref('')
const confirmationSent = ref(false)
function messageFrom(cause: unknown) {
const value = cause as { data?: { msg?: string; message?: string; error_description?: string }; message?: string }
return value.data?.msg ?? value.data?.message ?? value.data?.error_description ?? value.message ?? 'Registration failed. Try again.'
}
async function finishSignIn() {
const requested = localStorage.getItem('dng-post-auth-redirect')
localStorage.removeItem('dng-post-auth-redirect')
const destination = requested?.startsWith('/') && !requested.startsWith('//') ? requested : '/dashboard'
await navigateTo(destination, { replace: true })
}
async function submit() {
error.value = ''
if (displayName.value.trim().length < 2) {
error.value = 'Enter a name with at least 2 characters.'
return
}
if (password.value.length < 8) {
error.value = 'Password must contain at least 8 characters.'
return
}
if (password.value !== confirmation.value) {
error.value = 'Passwords do not match.'
return
}
if (!ageConfirmed.value) {
error.value = 'You must confirm that you are at least 13 years old.'
return
}
busy.value = true
try {
const result = await auth.signUp(displayName.value, email.value, password.value)
if (result.session) await finishSignIn()
else confirmationSent.value = true
} catch (cause) {
error.value = messageFrom(cause)
} finally {
busy.value = false
}
}
onMounted(async () => {
await auth.restore()
if (auth.session.value) await navigateTo('/dashboard', { replace: true })
})
</script>
<template>
<AuthCard eyebrow="CREATE YOUR ACCOUNT" title="ENTER THE ALPHA." subtitle="Your email keeps your worlds, characters, and campaign access recoverable across devices.">
<div v-if="confirmationSent" class="form-success" role="status">
CHECK YOUR EMAIL. We sent a confirmation link to {{ email }}. Open it to activate your account.
</div>
<form v-else class="auth-form" @submit.prevent="submit">
<label>DISPLAY NAME<input v-model="displayName" name="name" autocomplete="name" maxlength="80" required placeholder="How your party sees you"></label>
<label>EMAIL<input v-model="email" name="email" type="email" autocomplete="email" required placeholder="you@example.com"></label>
<label>PASSWORD<input v-model="password" name="password" type="password" autocomplete="new-password" minlength="8" required placeholder="At least 8 characters"></label>
<label>CONFIRM PASSWORD<input v-model="confirmation" name="password-confirmation" type="password" autocomplete="new-password" minlength="8" required placeholder="Repeat your password"></label>
<label class="consent"><input v-model="ageConfirmed" type="checkbox" required><span>I am at least 13 years old and accept the 13+ content boundary.</span></label>
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
<button :disabled="busy">{{ busy ? 'CREATING ACCOUNT…' : 'CREATE ACCOUNT →' }}</button>
</form>
<template #footer>Already have an account? <NuxtLink class="form-link" to="/auth/sign-in">SIGN IN</NuxtLink></template>
</AuthCard>
</template>
<style scoped>
.consent{grid-template-columns:18px 1fr!important;align-items:start!important;font:400 10px/1.5 var(--body)!important;letter-spacing:0!important;color:var(--muted)!important}.consent input{width:16px!important;min-height:16px!important;margin:1px 0 0;padding:0!important;accent-color:var(--acid)}
</style>

View File

@@ -7,7 +7,7 @@ type Controller = 'human' | 'ai' | 'delegated'
interface CampaignPayload { interface CampaignPayload {
campaign: Record<string, any> campaign: Record<string, any>
world: Record<string, any> world: Record<string, any>
members: Array<Record<string, any> & { profile?: { display_name?: string } | null }> members: Array<Record<string, any> & { profile?: { id?: string; display_name?: string; avatar_url?: string | null } | null }>
characters: Array<Record<string, any>> characters: Array<Record<string, any>>
round: Record<string, any> | null round: Record<string, any> | null
rounds: Array<Record<string, any>> rounds: Array<Record<string, any>>
@@ -51,7 +51,11 @@ const myIntent = computed(() => payload.value?.intents.find(intent =>
intent.member_id === currentMember.value?.id || intent.character_id === myCharacter.value?.id, intent.member_id === currentMember.value?.id || intent.character_id === myCharacter.value?.id,
)) ))
const isReady = computed(() => Boolean(myIntent.value?.ready)) const isReady = computed(() => Boolean(myIntent.value?.ready))
const activeHumanMembers = computed(() => payload.value?.members.filter(member => member.active !== false) ?? []) const activeHumanMembers = computed(() => payload.value?.members.filter(member =>
member.active !== false && payload.value?.characters.some(character =>
character.user_id === member.user_id && character.controller === 'human',
),
) ?? [])
const readyCount = computed(() => activeHumanMembers.value.filter(member => payload.value?.intents.some(intent => intent.member_id === member.id && intent.ready)).length) const readyCount = computed(() => activeHumanMembers.value.filter(member => payload.value?.intents.some(intent => intent.member_id === member.id && intent.ready)).length)
const canAct = computed(() => currentRound.value?.status === 'open' && Boolean(myCharacter.value)) const canAct = computed(() => currentRound.value?.status === 'open' && Boolean(myCharacter.value))
const roundBusy = computed(() => ['queued', 'resolving'].includes(String(currentRound.value?.status))) const roundBusy = computed(() => ['queued', 'resolving'].includes(String(currentRound.value?.status)))
@@ -311,7 +315,7 @@ onBeforeUnmount(() => {
<aside class="control-panel"> <aside class="control-panel">
<header class="panel-title"><span>ROUND CONTROL</span><i :class="{live:!refreshing}" /></header> <header class="panel-title"><span>ROUND CONTROL</span><i :class="{live:!refreshing}" /></header>
<section class="readiness"><p><b>{{ readyCount }} / {{ activeHumanMembers.length }}</b> HUMANS READY</p><div><i :style="{width:`${activeHumanMembers.length ? readyCount/activeHumanMembers.length*100 : 0}%`} " /></div></section> <section class="readiness"><p><b>{{ readyCount }} / {{ activeHumanMembers.length }}</b> HUMANS READY</p><div><i :style="{width:`${activeHumanMembers.length ? readyCount/activeHumanMembers.length*100 : 0}%`} " /></div></section>
<section class="members"><small>PLAYERS</small><article v-for="member in payload.members" :key="member.id"><i :class="{ready:payload.intents.some(intent=>intent.member_id===member.id && intent.ready)}" /><span><b>{{ member.profile?.display_name || 'Adventurer' }}</b><em>{{ member.role }} · {{ payload.intents.some(intent=>intent.member_id===member.id && intent.ready) ? 'ready' : 'waiting' }}</em><button v-if="isOwner" class="takeover-toggle" :class="{enabled:member.ai_takeover_allowed}" :disabled="mutating" @click="toggleTakeover(member)">AI TAKEOVER {{ member.ai_takeover_allowed ? 'ON' : 'OFF' }}</button></span></article></section> <section class="members"><small>PLAYERS</small><article v-for="member in payload.members" :key="member.id"><i :class="{ready:payload.intents.some(intent=>intent.member_id===member.id && intent.ready)}" /><NuxtLink class="member-profile" :to="`/profile/${member.user_id}?campaign=${campaignId}`"><span class="member-avatar"><b>{{ initials(member.profile?.display_name || 'Adventurer') }}</b><img v-if="member.profile?.avatar_url" :src="member.profile.avatar_url" alt=""></span><span><b>{{ member.profile?.display_name || 'Adventurer' }}</b><em>{{ member.role }} · {{ payload.intents.some(intent=>intent.member_id===member.id && intent.ready) ? 'ready' : 'waiting' }}</em></span></NuxtLink><button v-if="isOwner" class="takeover-toggle" :class="{enabled:member.ai_takeover_allowed}" :disabled="mutating" @click="toggleTakeover(member)">AI TAKEOVER {{ member.ai_takeover_allowed ? 'ON' : 'OFF' }}</button></article></section>
<section v-if="isOwner" class="invite-box"><small>INVITE PLAYERS</small><p>Private link · up to 8 joins · expires in 72 hours.</p><button v-if="!inviteLink" class="ghost-button" :disabled="mutating" @click="createInvite">CREATE INVITE LINK</button><template v-else><input :value="inviteLink" readonly aria-label="Campaign invite link"><button class="acid-button" @click="copyInvite">{{ inviteCopied ? 'COPIED' : 'COPY LINK' }}</button></template></section> <section v-if="isOwner" class="invite-box"><small>INVITE PLAYERS</small><p>Private link · up to 8 joins · expires in 72 hours.</p><button v-if="!inviteLink" class="ghost-button" :disabled="mutating" @click="createInvite">CREATE INVITE LINK</button><template v-else><input :value="inviteLink" readonly aria-label="Campaign invite link"><button class="acid-button" @click="copyInvite">{{ inviteCopied ? 'COPIED' : 'COPY LINK' }}</button></template></section>
<section class="ai-order"><small>AI TURN ORDER</small><p v-if="!payload.characters.some(character=>character.controller!=='human')">No AI heroes in this party.</p><div v-for="(character,index) in payload.characters.filter(character=>character.controller!=='human')" :key="character.id"><b>{{ String(index+1).padStart(2,'0') }}</b><span>{{ character.name }}<small>{{ character.controller === 'delegated' ? 'Temporary stand-in' : 'Acts after all humans' }}</small></span></div></section> <section class="ai-order"><small>AI TURN ORDER</small><p v-if="!payload.characters.some(character=>character.controller!=='human')">No AI heroes in this party.</p><div v-for="(character,index) in payload.characters.filter(character=>character.controller!=='human')" :key="character.id"><b>{{ String(index+1).padStart(2,'0') }}</b><span>{{ character.name }}<small>{{ character.controller === 'delegated' ? 'Temporary stand-in' : 'Acts after all humans' }}</small></span></div></section>
<button v-if="isOwner && currentRound?.status==='open'" class="force-button" :disabled="mutating" @click="forceRound">CONTINUE WITHOUT WAITING <span></span></button> <button v-if="isOwner && currentRound?.status==='open'" class="force-button" :disabled="mutating" @click="forceRound">CONTINUE WITHOUT WAITING <span></span></button>
@@ -334,4 +338,12 @@ onBeforeUnmount(() => {
.takeover-toggle{margin-top:7px;padding:4px 6px;border:1px solid var(--line);background:transparent;color:var(--muted);font:500 6px var(--mono);text-align:left} .takeover-toggle{margin-top:7px;padding:4px 6px;border:1px solid var(--line);background:transparent;color:var(--muted);font:500 6px var(--mono);text-align:left}
.takeover-toggle.enabled{border-color:var(--acid-dim);color:var(--acid)} .takeover-toggle.enabled{border-color:var(--acid-dim);color:var(--acid)}
.ai-draft{min-height:34px;border:1px solid var(--acid-dim);background:rgba(207,255,70,.04);color:var(--acid);font:600 7px var(--mono);letter-spacing:.1em}.persona-editor{border:1px solid var(--line);padding:9px}.persona-editor summary{cursor:pointer;color:var(--muted);font:600 7px var(--mono);letter-spacing:.1em}.persona-editor input{margin-top:7px} .ai-draft{min-height:34px;border:1px solid var(--acid-dim);background:rgba(207,255,70,.04);color:var(--acid);font:600 7px var(--mono);letter-spacing:.1em}.persona-editor{border:1px solid var(--line);padding:9px}.persona-editor summary{cursor:pointer;color:var(--muted);font:600 7px var(--mono);letter-spacing:.1em}.persona-editor input{margin-top:7px}
.members article{display:grid;grid-template-columns:6px minmax(0,1fr);align-items:center}
.member-profile{display:grid;grid-template-columns:30px minmax(0,1fr);gap:9px;align-items:center;color:var(--ink);text-decoration:none}
.member-profile>span:last-child{display:flex;min-width:0;flex-direction:column}
.member-avatar{position:relative;overflow:hidden;display:grid!important;place-items:center;width:30px;height:30px;border:1px solid var(--line);background:#171714;color:var(--acid)}
.member-avatar>b{font:600 7px var(--mono)!important}
.member-avatar img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
.members .member-profile b{overflow-wrap:anywhere}
.members .takeover-toggle{grid-column:2;margin-left:39px}
</style> </style>

View File

@@ -74,7 +74,7 @@ onMounted(async () => {
<section class="world-grid"> <section class="world-grid">
<p v-if="loading" class="load-state">RECEIVING PRIVATE CAMPAIGNS</p> <p v-if="loading" class="load-state">RECEIVING PRIVATE CAMPAIGNS</p>
<p v-else-if="error" class="load-state error">{{ error }} <NuxtLink to="/">SIGN IN AGAIN</NuxtLink></p> <p v-else-if="error" class="load-state error">{{ error }} <NuxtLink to="/auth/sign-in">SIGN IN AGAIN</NuxtLink></p>
<NuxtLink v-for="campaign in visibleCampaigns" :key="campaign.id" :to="`/campaign/${campaign.id}`" class="world-card active-world"> <NuxtLink v-for="campaign in visibleCampaigns" :key="campaign.id" :to="`/campaign/${campaign.id}`" class="world-card active-world">
<div class="world-art"><div class="eclipse" /><span>{{ campaign.status.toUpperCase() }} CAMPAIGN</span></div> <div class="world-art"><div class="eclipse" /><span>{{ campaign.status.toUpperCase() }} CAMPAIGN</span></div>
<div class="world-info"><small>PRIVATE MULTIPLAYER</small><h2>{{ campaign.title }}</h2><p>{{ campaign.current_scene }}</p><div><b>CONTINUE STORY</b><span>{{ new Date(campaign.updated_at).toLocaleDateString() }}</span></div></div> <div class="world-info"><small>PRIVATE MULTIPLAYER</small><h2>{{ campaign.title }}</h2><p>{{ campaign.current_scene }}</p><div><b>CONTINUE STORY</b><span>{{ new Date(campaign.updated_at).toLocaleDateString() }}</span></div></div>
@@ -94,5 +94,43 @@ onMounted(async () => {
</template> </template>
<style scoped> <style scoped>
.draft-world .world-art{background:radial-gradient(circle at 50% 60%,#3f4720 0 2%,#1c2011 9%,#080808 58%)}.draft-world .world-art span{background:transparent;color:var(--acid);border:1px solid var(--acid-dim)} .dash-wrap{min-height:calc(100vh - 76px);padding:clamp(42px,6vw,86px) clamp(20px,6vw,88px)}
.dash-head{display:flex;align-items:end;justify-content:space-between;gap:30px}
.kicker{font:500 9px var(--mono);letter-spacing:.2em;color:var(--acid)}
.dash-head h1{margin:14px 0 10px;font:600 clamp(44px,6vw,82px)/1 var(--display);letter-spacing:-.06em}
.dash-head h1 span{color:var(--acid)}
.dash-head p{color:var(--muted)}
.create-button{display:flex;align-items:center;gap:18px;padding:18px 22px;background:var(--acid);color:#090909;text-decoration:none;font:600 10px var(--mono);letter-spacing:.12em}
.create-button span{font-size:20px}
.filter-row{display:flex;align-items:center;gap:10px;margin:58px 0 24px;border-bottom:1px solid var(--line)}
.filter-row button{padding:0 4px 16px;margin-right:18px;background:none;border:0;color:var(--muted);font:500 9px var(--mono);text-transform:uppercase;letter-spacing:.14em}
.filter-row button.active{color:var(--ink);border-bottom:2px solid var(--acid)}
.filter-row>span{margin-left:auto;padding-bottom:16px;font:500 8px var(--mono);color:var(--muted)}
.world-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}
.load-state{grid-column:1/-1;padding:34px;border:1px solid var(--line);font:500 9px var(--mono);color:var(--muted)}
.load-state.error{color:#ff9d85}
.load-state a{color:var(--acid)}
.world-card{min-height:420px;border:1px solid var(--line);color:var(--ink);text-decoration:none;background:#0e0e0d;transition:border-color .25s ease,transform .25s ease}
.world-card:hover{border-color:#65655e;transform:translateY(-3px)}
.active-world{display:grid;grid-template-columns:.75fr 1.25fr}
.world-art{position:relative;overflow:hidden;display:grid;place-items:center;background:radial-gradient(circle at 50% 60%,#7d8240 0 2%,#303018 4%,#0b0b0a 36%,#030303 72%)}
.world-art::before{content:"";position:absolute;width:320px;height:320px;border:1px solid #38382d;border-radius:50%;box-shadow:0 0 0 34px #111,0 0 0 35px #26261d}
.eclipse{position:absolute;width:126px;height:126px;border-radius:50%;background:#020202;box-shadow:0 0 50px var(--acid-dim)}
.world-art span{position:absolute;left:20px;top:20px;padding:9px 11px;background:var(--acid);color:#0a0a0a;font:600 8px var(--mono);letter-spacing:.12em}
.draft-world .world-art{background:radial-gradient(circle at 50% 60%,#3f4720 0 2%,#1c2011 9%,#080808 58%)}
.draft-world .world-art span{background:transparent;color:var(--acid);border:1px solid var(--acid-dim)}
.world-info{padding:42px;display:flex;flex-direction:column;min-width:0}
.world-info small{font:500 8px var(--mono);letter-spacing:.14em;color:var(--acid);text-transform:uppercase}
.world-info h2,.new-card h2{font:600 clamp(25px,3vw,42px)/1.05 var(--display);letter-spacing:-.05em;margin:22px 0;overflow-wrap:anywhere}
.world-info p,.new-card p{color:var(--muted);font-size:13px;line-height:1.7;display:-webkit-box;-webkit-line-clamp:5;-webkit-box-orient:vertical;overflow:hidden}
.world-info div{margin-top:auto;padding-top:26px;border-top:1px solid var(--line);display:flex;justify-content:space-between;gap:16px;font:500 8px var(--mono);color:var(--muted)}
.world-info b{color:var(--acid)}
.new-card{padding:48px;display:flex;flex-direction:column;justify-content:flex-end;background:linear-gradient(145deg,#121211,#090909)}
.new-card .plus{margin-bottom:auto;font:300 42px var(--body);color:var(--acid)}
.system-strip{margin-top:32px;padding:18px 0;border-top:1px solid var(--line);display:flex;justify-content:space-between;font:500 8px var(--mono);letter-spacing:.12em;color:var(--muted)}
.system-strip i{display:inline-block;width:6px;height:6px;background:var(--acid);border-radius:50%;margin-right:8px}
.system-strip b{color:var(--acid)}
@media(max-width:1050px){.world-grid{grid-template-columns:1fr}}
@media(max-width:850px){.dash-head{align-items:start;flex-direction:column}.active-world{grid-template-columns:1fr}.world-art{min-height:280px}.system-strip{gap:16px;flex-wrap:wrap}}
@media(max-width:520px){.dash-head h1{font-size:clamp(34px,12vw,52px)}.create-button{width:100%;justify-content:center}.filter-row>span{display:none}.world-info,.new-card{padding:28px}.active-world{min-height:580px}.world-info div{align-items:flex-start;flex-direction:column}.system-strip{flex-direction:column}}
</style> </style>

View File

@@ -1,9 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
const { session, restore, requestMagicLink, signInAnonymously } = useDngAuth() const { session, restore } = useDngAuth()
const email = ref('')
const notice = ref('')
const guestError = ref('')
const sending = ref(false)
const entering = ref(false) const entering = ref(false)
onMounted(() => void restore()) onMounted(() => void restore())
@@ -11,42 +7,13 @@ onMounted(() => void restore())
async function enterAlpha() { async function enterAlpha() {
if (entering.value) return if (entering.value) return
entering.value = true entering.value = true
notice.value = ''
guestError.value = ''
try { try {
await restore() await restore()
if (!session.value) await signInAnonymously() await navigateTo(session.value ? '/dashboard' : '/auth/sign-up')
const requested = localStorage.getItem('dng-post-auth-redirect')
localStorage.removeItem('dng-post-auth-redirect')
const destination = requested?.startsWith('/') && !requested.startsWith('//') ? requested : '/dashboard'
await navigateTo(destination)
} catch (cause) {
const error = cause as { data?: { msg?: string; message?: string }; message?: string }
const rawMessage = error.data?.msg ?? error.data?.message ?? error.message ?? ''
guestError.value = /anonymous.*(disabled|sign.?in)/i.test(rawMessage)
? 'Guest access is disabled in Supabase Auth settings.'
: /database error|saving new user/i.test(rawMessage)
? 'The Supabase database migration is incomplete. Apply bootstrap.sql.'
: rawMessage || 'Guest access is unavailable right now.'
} finally { } finally {
entering.value = false entering.value = false
} }
} }
async function requestAccess() {
if (sending.value) return
sending.value = true
notice.value = ''
try {
await requestMagicLink(email.value)
notice.value = `Magic link sent to ${email.value}. Check your inbox.`
} catch (cause) {
const error = cause as { data?: { msg?: string; message?: string }; message?: string }
notice.value = error.data?.msg ?? error.data?.message ?? error.message ?? 'This email is not on the alpha allowlist.'
} finally {
sending.value = false
}
}
</script> </script>
<template> <template>
@@ -65,7 +32,6 @@ async function requestAccess() {
<button class="btn btn-acid" :disabled="entering" @click="enterAlpha">{{ entering ? 'OPENING' : session ? 'OPEN DASHBOARD' : 'ENTER THE ALPHA' }} <span></span></button> <button class="btn btn-acid" :disabled="entering" @click="enterAlpha">{{ entering ? 'OPENING' : session ? 'OPEN DASHBOARD' : 'ENTER THE ALPHA' }} <span></span></button>
<a href="#how" class="btn btn-ghost">SEE HOW IT WORKS</a> <a href="#how" class="btn btn-ghost">SEE HOW IT WORKS</a>
</div> </div>
<p v-if="guestError" class="guest-error" role="alert">{{ guestError }}</p>
<div class="trust-row"> <div class="trust-row">
<span>PRIVATE WORLDS</span><i /> <span>PRIVATE WORLDS</span><i />
<span>SERVER-OWNED DICE</span><i /> <span>SERVER-OWNED DICE</span><i />
@@ -88,11 +54,11 @@ async function requestAccess() {
<article><b>01</b><h2>DESCRIBE THE IMPOSSIBLE</h2><p>A coauthor asks sharp questions, then turns your idea into a playable private world.</p></article> <article><b>01</b><h2>DESCRIBE THE IMPOSSIBLE</h2><p>A coauthor asks sharp questions, then turns your idea into a playable private world.</p></article>
<article><b>02</b><h2>ASSEMBLE YOUR PARTY</h2><p>Invite friends, add AI companions, and decide who can step in when someone is away.</p></article> <article><b>02</b><h2>ASSEMBLE YOUR PARTY</h2><p>Invite friends, add AI companions, and decide who can step in when someone is away.</p></article>
<article><b>03</b><h2>ACT ON YOUR TIME</h2><p>The Groundkeeper resolves each shared round only when the party is ready.</p></article> <article><b>03</b><h2>ACT ON YOUR TIME</h2><p>The Groundkeeper resolves each shared round only when the party is ready.</p></article>
<form @submit.prevent="requestAccess"><label for="email">OPTIONAL EMAIL SIGN-IN</label><div><input id="email" v-model="email" type="email" autocomplete="email" placeholder="you@example.com" required><button :disabled="sending">{{ sending ? '' : '' }}</button></div><small>{{ notice || 'No email is needed. Use this only for an invited email account.' }}</small></form> <aside class="account-card"><b>ACCOUNT REQUIRED</b><h2>KEEP YOUR WORLDS.</h2><p>Register with your name, email, and password. Continue on any device and recover access when needed.</p><div><NuxtLink to="/auth/sign-up">CREATE ACCOUNT </NuxtLink><NuxtLink to="/auth/sign-in">SIGN IN</NuxtLink></div></aside>
</section> </section>
</div> </div>
</template> </template>
<style scoped> <style scoped>
.landing{min-height:100vh;overflow:hidden}.landing-nav{height:90px;padding:0 clamp(22px,6vw,90px);display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid var(--line)}.alpha-tag{font:500 9px var(--mono);letter-spacing:.18em;border:1px solid var(--line);padding:10px 14px;color:var(--muted)}.hero{min-height:680px;padding:72px clamp(22px,6vw,90px) 60px;display:grid;grid-template-columns:minmax(0,1.15fr) minmax(360px,.85fr);gap:7vw;align-items:center}.eyebrow{font:500 10px var(--mono);letter-spacing:.22em;color:var(--muted)}.eyebrow span{display:inline-block;width:26px;height:1px;background:var(--acid);vertical-align:middle;margin-right:10px}.hero h1{margin:22px 0 28px;font:600 clamp(52px,6.6vw,108px)/.91 var(--display);letter-spacing:-.07em}.hero h1 em{font-style:normal;color:transparent;-webkit-text-stroke:1px var(--acid)}.lede{max-width:650px;font-size:clamp(16px,1.5vw,20px);line-height:1.7;color:#b9b9b2}.hero-actions{display:flex;gap:12px;margin-top:38px}.guest-error{max-width:620px;margin:14px 0 0;color:#ff9d85;font:500 10px/1.5 var(--mono);letter-spacing:.04em}.btn{min-height:52px;padding:0 22px;border:1px solid var(--line);font:600 10px var(--mono);letter-spacing:.13em;text-decoration:none;display:inline-flex;align-items:center;justify-content:center;gap:20px}.btn:disabled{opacity:.7;cursor:wait}.btn-acid{border-color:var(--acid);background:var(--acid);color:#080808}.btn-ghost{color:var(--ink);background:transparent}.trust-row{display:flex;align-items:center;gap:14px;margin-top:42px;font:500 8px var(--mono);letter-spacing:.16em;color:var(--muted)}.trust-row i{width:3px;height:3px;background:var(--acid);border-radius:50%}.signal-card{position:relative;min-height:510px;border:1px solid var(--line);background:linear-gradient(145deg,#111 0%,#090909 60%);box-shadow:0 40px 120px #000;padding:22px;clip-path:polygon(0 0,calc(100% - 20px) 0,100% 20px,100% 100%,20px 100%,0 calc(100% - 20px))}.signal-top,.party-status{display:flex;justify-content:space-between;font:500 8px var(--mono);letter-spacing:.13em;color:var(--muted)}.signal-top b{color:var(--acid)}.orbit{position:relative;width:245px;height:245px;margin:48px auto 30px;border:1px solid #2b2b29;border-radius:50%;display:grid;place-items:center}.orbit:before,.orbit:after{content:"";position:absolute;border:1px solid #262624;border-radius:50%;inset:28px}.orbit:after{inset:61px;border-color:var(--acid-dim)}.orbit i{position:absolute;width:7px;height:7px;border-radius:50%;background:var(--acid);box-shadow:0 0 18px var(--acid)}.orbit i:nth-child(1){top:23px;left:52px}.orbit i:nth-child(2){right:-3px;top:113px}.orbit i:nth-child(3){bottom:20px;left:85px}.orbit span{font:600 28px var(--display);color:var(--acid)}.transmission{border-left:2px solid var(--acid);padding:8px 18px;margin:0 12px 34px}.transmission small{font:500 8px var(--mono);letter-spacing:.18em;color:var(--acid)}.transmission p{font:500 15px/1.6 var(--body);color:#d6d6d0}.party-status{padding:18px 12px 0;border-top:1px solid var(--line)}.party-status b{color:var(--acid)}.how-grid{display:grid;grid-template-columns:repeat(3,1fr) 1.2fr;border-top:1px solid var(--line)}.how-grid article,.how-grid form{min-height:215px;padding:34px;border-right:1px solid var(--line)}.how-grid article>b{font:500 9px var(--mono);color:var(--acid)}.how-grid h2{margin:34px 0 12px;font:600 13px var(--display);letter-spacing:-.03em}.how-grid p,.how-grid small{font-size:12px;line-height:1.6;color:var(--muted)}.how-grid label{font:600 10px var(--mono);letter-spacing:.12em}.how-grid form div{display:flex;margin:35px 0 12px}.how-grid input{width:100%;background:#10100f;border:1px solid var(--line);padding:14px;color:var(--ink)}.how-grid form button{width:50px;border:0;background:var(--acid);font-size:20px}@media(max-width:950px){.hero{grid-template-columns:1fr}.signal-card{max-width:620px}.how-grid{grid-template-columns:1fr 1fr}}@media(max-width:620px){.alpha-tag{display:none}.hero{padding-top:50px}.hero h1{font-size:48px}.hero-actions{flex-direction:column}.trust-row{flex-wrap:wrap}.signal-card{min-height:470px}.how-grid{grid-template-columns:1fr}.how-grid article,.how-grid form{border-bottom:1px solid var(--line)}} .landing{min-height:100vh;overflow:hidden}.landing-nav{height:90px;padding:0 clamp(22px,6vw,90px);display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid var(--line)}.alpha-tag{font:500 9px var(--mono);letter-spacing:.18em;border:1px solid var(--line);padding:10px 14px;color:var(--muted)}.hero{min-height:680px;padding:72px clamp(22px,6vw,90px) 60px;display:grid;grid-template-columns:minmax(0,1.15fr) minmax(360px,.85fr);gap:7vw;align-items:center}.eyebrow{font:500 10px var(--mono);letter-spacing:.22em;color:var(--muted)}.eyebrow span{display:inline-block;width:26px;height:1px;background:var(--acid);vertical-align:middle;margin-right:10px}.hero h1{margin:22px 0 28px;font:600 clamp(52px,6.6vw,108px)/.91 var(--display);letter-spacing:-.07em}.hero h1 em{font-style:normal;color:transparent;-webkit-text-stroke:1px var(--acid)}.lede{max-width:650px;font-size:clamp(16px,1.5vw,20px);line-height:1.7;color:#b9b9b2}.hero-actions{display:flex;gap:12px;margin-top:38px}.btn{min-height:52px;padding:0 22px;border:1px solid var(--line);font:600 10px var(--mono);letter-spacing:.13em;text-decoration:none;display:inline-flex;align-items:center;justify-content:center;gap:20px}.btn:disabled{opacity:.7;cursor:wait}.btn-acid{border-color:var(--acid);background:var(--acid);color:#080808}.btn-ghost{color:var(--ink);background:transparent}.trust-row{display:flex;align-items:center;gap:14px;margin-top:42px;font:500 8px var(--mono);letter-spacing:.16em;color:var(--muted)}.trust-row i{width:3px;height:3px;background:var(--acid);border-radius:50%}.signal-card{position:relative;min-height:510px;border:1px solid var(--line);background:linear-gradient(145deg,#111 0%,#090909 60%);box-shadow:0 40px 120px #000;padding:22px;clip-path:polygon(0 0,calc(100% - 20px) 0,100% 20px,100% 100%,20px 100%,0 calc(100% - 20px))}.signal-top,.party-status{display:flex;justify-content:space-between;font:500 8px var(--mono);letter-spacing:.13em;color:var(--muted)}.signal-top b{color:var(--acid)}.orbit{position:relative;width:245px;height:245px;margin:48px auto 30px;border:1px solid #2b2b29;border-radius:50%;display:grid;place-items:center}.orbit:before,.orbit:after{content:"";position:absolute;border:1px solid #262624;border-radius:50%;inset:28px}.orbit:after{inset:61px;border-color:var(--acid-dim)}.orbit i{position:absolute;width:7px;height:7px;border-radius:50%;background:var(--acid);box-shadow:0 0 18px var(--acid)}.orbit i:nth-child(1){top:23px;left:52px}.orbit i:nth-child(2){right:-3px;top:113px}.orbit i:nth-child(3){bottom:20px;left:85px}.orbit span{font:600 28px var(--display);color:var(--acid)}.transmission{border-left:2px solid var(--acid);padding:8px 18px;margin:0 12px 34px}.transmission small{font:500 8px var(--mono);letter-spacing:.18em;color:var(--acid)}.transmission p{font:500 15px/1.6 var(--body);color:#d6d6d0}.party-status{padding:18px 12px 0;border-top:1px solid var(--line)}.party-status b{color:var(--acid)}.how-grid{display:grid;grid-template-columns:repeat(3,1fr) 1.2fr;border-top:1px solid var(--line)}.how-grid article,.account-card{min-height:215px;padding:34px;border-right:1px solid var(--line)}.how-grid article>b,.account-card>b{font:500 9px var(--mono);color:var(--acid)}.how-grid h2{margin:34px 0 12px;font:600 13px var(--display);letter-spacing:-.03em}.how-grid p{font-size:12px;line-height:1.6;color:var(--muted)}.account-card{display:flex;flex-direction:column}.account-card h2{margin-top:25px}.account-card div{display:flex;gap:14px;margin-top:auto}.account-card a{color:var(--muted);font:600 8px var(--mono);text-decoration:none}.account-card a:first-child{color:var(--acid)}@media(max-width:950px){.hero{grid-template-columns:1fr}.signal-card{max-width:620px}.how-grid{grid-template-columns:1fr 1fr}}@media(max-width:620px){.alpha-tag{display:none}.hero{padding-top:50px}.hero h1{font-size:48px}.hero-actions{flex-direction:column}.trust-row{flex-wrap:wrap}.signal-card{min-height:470px}.how-grid{grid-template-columns:1fr}.how-grid article,.account-card{border-bottom:1px solid var(--line)}}
</style> </style>

View File

@@ -28,11 +28,12 @@ onMounted(async () => {
<div class="join noise"> <div class="join noise">
<AppMark /> <AppMark />
<div v-if="state === 'joining'" class="card"><small>PARTY INVITE</small><h1>JOINING CAMPAIGN</h1><p>Verifying your seat at the table.</p></div> <div v-if="state === 'joining'" class="card"><small>PARTY INVITE</small><h1>JOINING CAMPAIGN</h1><p>Verifying your seat at the table.</p></div>
<div v-else-if="state === 'signin'" class="card"><small>PARTY INVITE</small><h1>ENTER THE ALPHA FIRST</h1><p>Your invite is saved. Guest access needs no email; after entering, this campaign will open automatically.</p><NuxtLink to="/">ENTER THE ALPHA </NuxtLink></div> <div v-else-if="state === 'signin'" class="card"><small>PARTY INVITE</small><h1>ACCOUNT REQUIRED</h1><p>Your invite is saved. Sign in or create an email account, and this campaign will open automatically.</p><div class="auth-actions"><NuxtLink to="/auth/sign-in">SIGN IN →</NuxtLink><NuxtLink to="/auth/sign-up">CREATE ACCOUNT</NuxtLink></div></div>
<div v-else class="card"><small>INVITE ERROR</small><h1>THE DOOR STAYED SHUT</h1><p>{{ message }}</p><NuxtLink to="/dashboard">BACK TO DASHBOARD</NuxtLink></div> <div v-else class="card"><small>INVITE ERROR</small><h1>THE DOOR STAYED SHUT</h1><p>{{ message }}</p><NuxtLink to="/dashboard">BACK TO DASHBOARD</NuxtLink></div>
</div> </div>
</template> </template>
<style scoped> <style scoped>
.join{min-height:100vh;display:grid;place-content:center;justify-items:center;gap:30px;padding:24px}.card{width:min(560px,calc(100vw - 40px));padding:42px;border:1px solid var(--line);background:#0d0d0c}.card small{font:600 8px var(--mono);letter-spacing:.16em;color:var(--acid)}.card h1{font:600 clamp(26px,5vw,45px)/1.05 var(--display);letter-spacing:-.05em}.card p{color:var(--muted);line-height:1.7}.card a{display:inline-flex;margin-top:20px;padding:15px 18px;background:var(--acid);color:#080808;text-decoration:none;font:600 9px var(--mono)} .join{min-height:100vh;display:grid;place-content:center;justify-items:center;gap:30px;padding:24px}.card{width:min(560px,calc(100vw - 40px));padding:42px;border:1px solid var(--line);background:#0d0d0c}.card small{font:600 8px var(--mono);letter-spacing:.16em;color:var(--acid)}.card h1{font:600 clamp(26px,5vw,45px)/1.05 var(--display);letter-spacing:-.05em}.card p{color:var(--muted);line-height:1.7}.card a{display:inline-flex;margin-top:20px;padding:15px 18px;background:var(--acid);color:#080808;text-decoration:none;font:600 9px var(--mono)}
.auth-actions{display:flex;gap:10px;flex-wrap:wrap}.auth-actions a:last-child{border:1px solid var(--line);background:transparent;color:var(--ink)}
</style> </style>

View File

@@ -0,0 +1,74 @@
<script setup lang="ts">
interface ProfileView {
id: string
display_name: string
description: string
avatar_url: string | null
created_at: string
}
interface SharedCampaign {
id: string
title: string
status: string
role: string
joined_at: string
}
const route = useRoute()
const { api } = useDngApi()
const auth = useDngAuth()
const profile = ref<ProfileView | null>(null)
const campaigns = ref<SharedCampaign[]>([])
const loading = ref(true)
const error = ref('')
const profileId = computed(() => String(route.params.id ?? ''))
const returnCampaign = computed(() => typeof route.query.campaign === 'string' ? route.query.campaign : '')
const initials = computed(() => (profile.value?.display_name || 'Adventurer')
.split(/\s+/).map(part => part[0]).join('').slice(0, 2).toUpperCase())
function messageFrom(cause: unknown) {
const value = cause as { data?: { statusMessage?: string }; message?: string }
return value.data?.statusMessage ?? value.message ?? 'This player profile is not available.'
}
onMounted(async () => {
try {
await auth.restore()
const result = await api<{ profile: ProfileView; sharedCampaigns: SharedCampaign[] }>(`/api/v1/profiles/${profileId.value}`)
profile.value = result.profile
campaigns.value = result.sharedCampaigns
} catch (cause) {
error.value = messageFrom(cause)
} finally {
loading.value = false
}
})
</script>
<template>
<AppShell section="PLAYER RECORD">
<div v-if="loading" class="public-state noise"><i /><p>LOCATING PLAYER RECORD</p></div>
<div v-else-if="!profile" class="public-state noise"><small>PRIVATE RECORD</small><h1>PLAYER NOT FOUND.</h1><p>{{ error }}</p><NuxtLink :to="returnCampaign ? `/campaign/${returnCampaign}` : '/dashboard'">GO BACK</NuxtLink></div>
<div v-else class="public-profile noise">
<nav><NuxtLink :to="returnCampaign ? `/campaign/${returnCampaign}` : '/dashboard'"> {{ returnCampaign ? 'BACK TO CAMPAIGN' : 'BACK TO DASHBOARD' }}</NuxtLink><NuxtLink v-if="profile.id === auth.session.value?.user.id" to="/profile">MANAGE PROFILE </NuxtLink></nav>
<main>
<div class="public-avatar"><span>{{ initials }}</span><img v-if="profile.avatar_url" :src="profile.avatar_url" :alt="`${profile.display_name}'s profile picture`"><i>VERIFIED<br>PARTY MEMBER</i></div>
<section class="public-copy">
<p class="eyebrow">PLAYER PROFILE / DUNGEONS & GROUND</p>
<h1>{{ profile.display_name }}<span>.</span></h1>
<blockquote>{{ profile.description || 'This adventurer has not written a profile description yet.' }}</blockquote>
<dl>
<div><dt>REGISTERED</dt><dd>{{ new Date(profile.created_at).toLocaleDateString(undefined, { dateStyle: 'long' }) }}</dd></div>
<div><dt>SHARED UNIVERSES</dt><dd>{{ campaigns.length }}</dd></div>
</dl>
<div v-if="campaigns.length" class="shared-worlds"><small>YOUR SHARED UNIVERSES</small><NuxtLink v-for="campaign in campaigns" :key="campaign.id" :to="`/campaign/${campaign.id}`"><span><b>{{ campaign.title }}</b><em>{{ campaign.role }} · joined {{ new Date(campaign.joined_at).toLocaleDateString() }}</em></span><i></i></NuxtLink></div>
</section>
</main>
</div>
</AppShell>
</template>
<style scoped>
.public-profile{min-height:calc(100vh - 76px);padding:32px clamp(20px,6vw,88px) 80px}.public-profile nav{display:flex;justify-content:space-between;gap:20px;padding:0 0 28px;border-bottom:1px solid var(--line)}.public-profile nav a,.public-state a{color:var(--muted);text-decoration:none;font:600 8px var(--mono);letter-spacing:.1em}.public-profile main{display:grid;grid-template-columns:minmax(300px,42%) minmax(0,1fr);min-height:650px;border:1px solid var(--line);border-top:0;background:#0e0e0d}.public-avatar{position:relative;overflow:hidden;display:grid;place-items:center;min-height:650px;border-right:1px solid var(--line);background:radial-gradient(circle at 50% 42%,#4e5724,#17170f 33%,#080808 70%);color:var(--acid);font:600 clamp(50px,8vw,110px) var(--display)}.public-avatar::after{content:"";position:absolute;inset:28px;border:1px solid rgba(217,247,95,.2)}.public-avatar img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.public-avatar i{position:absolute;z-index:2;left:50px;bottom:45px;color:var(--ink);font:500 8px/1.6 var(--mono);letter-spacing:.16em;font-style:normal}.public-copy{padding:clamp(35px,6vw,80px);align-self:center}.eyebrow{color:var(--acid);font:500 8px var(--mono);letter-spacing:.18em}.public-copy h1,.public-state h1{margin:18px 0 28px;font:600 clamp(42px,6vw,78px)/1.04 var(--display);letter-spacing:-.07em;overflow-wrap:anywhere}.public-copy h1 span{color:var(--acid)}blockquote{margin:0;padding-left:22px;border-left:2px solid var(--acid);color:#c9c9c2;font:400 clamp(14px,2vw,19px)/1.8 var(--body)}dl{display:grid;grid-template-columns:1fr 1fr;margin:42px 0;border-top:1px solid var(--line);border-bottom:1px solid var(--line)}dl div{padding:18px 0}dl div+div{padding-left:24px;border-left:1px solid var(--line)}dt{color:var(--muted);font:500 7px var(--mono);letter-spacing:.13em}dd{margin:7px 0 0;font-size:11px}.shared-worlds>small{color:var(--acid);font:500 7px var(--mono);letter-spacing:.14em}.shared-worlds>a{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:16px 0;border-bottom:1px solid var(--line);color:var(--ink);text-decoration:none}.shared-worlds span{display:flex;flex-direction:column;gap:6px}.shared-worlds b{font:600 11px var(--display)}.shared-worlds em{color:var(--muted);font:500 7px var(--mono);text-transform:uppercase;font-style:normal}.shared-worlds>a>i{color:var(--acid);font-style:normal}.public-state{min-height:calc(100vh - 76px);display:grid;place-content:center;justify-items:center;text-align:center;padding:30px}.public-state>i{width:24px;height:24px;border:2px solid var(--line);border-top-color:var(--acid);border-radius:50%;animation:spin .8s linear infinite}.public-state small{color:var(--acid);font:500 8px var(--mono);letter-spacing:.15em}.public-state p{color:var(--muted)}@keyframes spin{to{transform:rotate(360deg)}}@media(max-width:820px){.public-profile main{grid-template-columns:1fr}.public-avatar{min-height:380px;border-right:0;border-bottom:1px solid var(--line)}.public-avatar i{left:28px;bottom:26px}.public-copy{padding:34px 26px}}@media(max-width:480px){dl{grid-template-columns:1fr}dl div+div{padding-left:0;border-left:0;border-top:1px solid var(--line)}}
</style>

File diff suppressed because one or more lines are too long

View File

@@ -16,6 +16,8 @@ interface StoredSession {
confirmed_world_id?: string | null confirmed_world_id?: string | null
} }
const questionLimit = 4
const { api } = useDngApi() const { api } = useDngApi()
const route = useRoute() const route = useRoute()
const stage = ref<Stage>('seed') const stage = ref<Stage>('seed')
@@ -33,7 +35,14 @@ const messages = ref<Message[]>([
]) ])
const displayedQuestion = computed(() => currentQuestion.value ? { key: currentQuestion.value.id, label: currentQuestion.value.label, options: currentQuestion.value.options } : null) const displayedQuestion = computed(() => currentQuestion.value ? { key: currentQuestion.value.id, label: currentQuestion.value.label, options: currentQuestion.value.options } : null)
const progress = computed(() => stage.value === 'preview' || stage.value === 'confirming' ? 100 : stage.value === 'generating' ? 85 : stage.value === 'seed' ? 10 : 20 + Math.round((Math.min(answerCount.value, 5) / 5) * 55)) const conversationMessages = computed(() => {
if (!currentQuestion.value) return messages.value
const currentIndex = messages.value.findLastIndex(message =>
message.role === 'coauthor' && message.body === currentQuestion.value?.label,
)
return currentIndex < 0 ? messages.value : messages.value.filter((_, index) => index !== currentIndex)
})
const progress = computed(() => stage.value === 'preview' || stage.value === 'confirming' ? 100 : stage.value === 'generating' ? 85 : stage.value === 'seed' ? 10 : 20 + Math.round((Math.min(answerCount.value, questionLimit) / questionLimit) * 55))
function addMessage(role: Message['role'], body: string, label?: string) { function addMessage(role: Message['role'], body: string, label?: string) {
messages.value.push({ id: `${Date.now()}-${messages.value.length}`, role, body, label }) messages.value.push({ id: `${Date.now()}-${messages.value.length}`, role, body, label })
@@ -117,6 +126,7 @@ async function resume(id: string) {
async function answerQuestion(key: string, value: string) { async function answerQuestion(key: string, value: string) {
if (stage.value !== 'questions' || currentQuestion.value?.id !== key || busy.value || !sessionId.value) return if (stage.value !== 'questions' || currentQuestion.value?.id !== key || busy.value || !sessionId.value) return
const answeredQuestion = currentQuestion.value
busy.value = true busy.value = true
pendingAnswer.value = { key, value } pendingAnswer.value = { key, value }
try { try {
@@ -124,9 +134,10 @@ async function answerQuestion(key: string, value: string) {
method: 'POST', body: { content: value }, method: 'POST', body: { content: value },
}) })
answers[key] = value answers[key] = value
addMessage('coauthor', answeredQuestion.label, `COAUTHOR · QUESTION ${Math.min(answerCount.value + 1, questionLimit)} OF ${questionLimit}`)
addMessage('player', value) addMessage('player', value)
currentQuestion.value = null currentQuestion.value = null
answerCount.value = Math.min(answerCount.value + 1, 5) answerCount.value = Math.min(answerCount.value + 1, questionLimit)
pendingAnswer.value = null pendingAnswer.value = null
retryAction.value = 'respond' retryAction.value = 'respond'
await requestNextQuestion() await requestNextQuestion()
@@ -140,14 +151,13 @@ async function answerQuestion(key: string, value: string) {
async function requestNextQuestion() { async function requestNextQuestion() {
if (!sessionId.value) return if (!sessionId.value) return
const result = await api<RespondResult>(`/api/v1/coauthor/sessions/${sessionId.value}/respond`, { method: 'POST' }) const result = await api<RespondResult>(`/api/v1/coauthor/sessions/${sessionId.value}/respond`, { method: 'POST' })
if (result.readyToGenerate || answerCount.value >= 5) { if (result.readyToGenerate || answerCount.value >= questionLimit) {
currentQuestion.value = null currentQuestion.value = null
await generate() await generate()
return return
} }
if (!result.question) throw new Error('The coauthor did not return its next question.') if (!result.question) throw new Error('The coauthor did not return its next question.')
currentQuestion.value = result.question currentQuestion.value = result.question
addMessage('coauthor', result.question.label, `COAUTHOR · QUESTION ${Math.min(answerCount.value + 1, 5)} OF UP TO 5`)
} }
function errorText(error: unknown) { function errorText(error: unknown) {
@@ -247,7 +257,7 @@ onMounted(() => {
<main v-if="stage !== 'preview' && stage !== 'confirming'" class="coauthor"> <main v-if="stage !== 'preview' && stage !== 'confirming'" class="coauthor">
<p class="kicker">COAUTHOR / SESSION 01</p> <p class="kicker">COAUTHOR / SESSION 01</p>
<h1>BUILD THE<br>IMPOSSIBLE<span>.</span></h1> <h1>BUILD THE<br>IMPOSSIBLE<span>.</span></h1>
<CoauthorConversation :messages="messages" :question="displayedQuestion" :selected-answer="currentQuestion ? answers[currentQuestion.id] : undefined" :busy="stage === 'generating' || busy" @answer="answerQuestion" @retry="retry" /> <CoauthorConversation :messages="conversationMessages" :question="displayedQuestion" :selected-answer="currentQuestion ? answers[currentQuestion.id] : undefined" :busy="stage === 'generating' || busy" @answer="answerQuestion" @retry="retry" />
<form v-if="stage === 'seed'" class="seed" @submit.prevent="begin"> <form v-if="stage === 'seed'" class="seed" @submit.prevent="begin">
<textarea v-model="seed" aria-label="World idea" rows="3" maxlength="1200" autofocus /> <textarea v-model="seed" aria-label="World idea" rows="3" maxlength="1200" autofocus />
<button :disabled="!seed.trim() || busy">{{ busy ? 'SAVING…' : 'BEGIN' }} <span></span></button> <button :disabled="!seed.trim() || busy">{{ busy ? 'SAVING…' : 'BEGIN' }} <span></span></button>

View File

@@ -1,4 +1,5 @@
import { requireCampaignAccess, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoUuid } from '~/server/utils/stage-two-supabase' import { requireCampaignAccess, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoUuid } from '~/server/utils/stage-two-supabase'
import { visibleProfile, type ProfileRecord } from '~/server/utils/profile'
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
try { try {
@@ -30,11 +31,12 @@ export default defineEventHandler(async (event) => {
const round = openRounds[0] ?? fallbackRounds[0] ?? null const round = openRounds[0] ?? fallbackRounds[0] ?? null
const userIds = [...new Set(members.map(member => String(member.user_id)))] const userIds = [...new Set(members.map(member => String(member.user_id)))]
const profiles = userIds.length const profiles = userIds.length
? await stageTwoDatabase<Array<{ id: string; display_name: string }>>( ? await stageTwoDatabase<ProfileRecord[]>(
`profiles?select=id,display_name&id=in.(${userIds.join(',')})`, `profiles?select=id,display_name,description,avatar_path,created_at,updated_at&id=in.(${userIds.join(',')})`,
) )
: [] : []
const profileById = new Map(profiles.map(profile => [profile.id, profile])) const supabaseUrl = useRuntimeConfig().supabaseUrl
const profileById = new Map(profiles.map(profile => [profile.id, visibleProfile(profile, supabaseUrl)]))
const visibleMembers = members.map(member => ({ ...member, profile: profileById.get(String(member.user_id)) ?? null })) const visibleMembers = members.map(member => ({ ...member, profile: profileById.get(String(member.user_id)) ?? null }))
const visibleRounds = rounds.slice().reverse() const visibleRounds = rounds.slice().reverse()
const visibleRoundIds = visibleRounds.map(item => String(item.id)) const visibleRoundIds = visibleRounds.map(item => String(item.id))

View File

@@ -1,17 +1,9 @@
import { z } from 'zod' import { z } from 'zod'
import { buildJsonCompletion, parseJsonCompletion } from '~/server/utils/ai-provider' import { buildJsonCompletion, parseJsonCompletion } from '~/server/utils/ai-provider'
import { CoauthorQuestionSchema, StoredCoauthorQuestionSchema } from '~/server/utils/coauthor-question'
import { requireStageTwoSafeText, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoRpc, stageTwoUuid } from '~/server/utils/stage-two-supabase' import { requireStageTwoSafeText, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoRpc, stageTwoUuid } from '~/server/utils/stage-two-supabase'
const MessageSchema = z.object({ role: z.enum(['user', 'assistant']), content: z.string().min(1).max(5000) }) const MessageSchema = z.object({ role: z.enum(['user', 'assistant']), content: z.string().min(1).max(5000) })
const QuestionSchema = z.object({
question: z.string().trim().min(5).max(300),
options: z.array(z.string().trim().min(1).max(100)).length(3),
})
const StoredQuestionSchema = z.object({
id: z.string().trim().min(1).max(80),
label: z.string().trim().min(5).max(300),
options: z.array(z.string().trim().min(1).max(100)).length(3),
})
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
try { try {
@@ -27,14 +19,20 @@ export default defineEventHandler(async (event) => {
const answerCount = Math.max(0, messages.filter(message => message.role === 'user').length - 1) const answerCount = Math.max(0, messages.filter(message => message.role === 'user').length - 1)
if (answerCount >= 4) return { readyToGenerate: true } if (answerCount >= 4) return { readyToGenerate: true }
if (session.current_question) { if (session.current_question) {
return { readyToGenerate: false, question: StoredQuestionSchema.parse(session.current_question) } const storedQuestion = StoredCoauthorQuestionSchema.safeParse(session.current_question)
if (storedQuestion.success) return { readyToGenerate: false, question: storedQuestion.data }
} }
let question: z.infer<typeof CoauthorQuestionSchema> | undefined
for (let attempt = 0; attempt < 2 && !question; attempt += 1) {
const correction = attempt
? ' The previous response was malformed. Ensure every option is a natural-language answer, not punctuation, a JSON key, or a copy of the question.'
: ''
const completion = buildJsonCompletion(useRuntimeConfig(), { const completion = buildJsonCompletion(useRuntimeConfig(), {
system: `You are the Dungeons & Ground coauthor. Based only on this conversation, ask one focused question that makes the original TTRPG world more playable. This is clarification ${answerCount + 1} of 4. Do not repeat a topic already answered. Adapt to the requested genre. Provide exactly three concise, mutually distinct answer options. Keep everything suitable for ages 13+.`, system: `You are the Dungeons & Ground coauthor. Based only on this conversation, ask one focused question that makes the original TTRPG world more playable. This is clarification ${answerCount + 1} of 4. Do not repeat a topic already answered. Adapt to the requested genre. Use the language of the first user message for the question and every answer option unless the user explicitly requests another language. Provide exactly three concise, mutually distinct natural-language answers to the question. Never use punctuation or JSON field names as an option, and never repeat the question as an option. Keep everything suitable for ages 13+.${correction}`,
messages, messages,
schemaName: 'coauthor_question', schemaName: 'coauthor_question',
jsonSchema: QuestionSchema.toJSONSchema(), jsonSchema: CoauthorQuestionSchema.toJSONSchema(),
}) })
const controller = new AbortController() const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 30_000) const timeout = setTimeout(() => controller.abort(), 30_000)
@@ -47,9 +45,16 @@ export default defineEventHandler(async (event) => {
clearTimeout(timeout) clearTimeout(timeout)
} }
if (!response.ok) throw createError({ statusCode: 502, statusMessage: 'The coauthor is temporarily unavailable.' }) if (!response.ok) throw createError({ statusCode: 502, statusMessage: 'The coauthor is temporarily unavailable.' })
const question = QuestionSchema.parse(parseJsonCompletion(await response.json())) try {
const parsed = CoauthorQuestionSchema.safeParse(parseJsonCompletion(await response.json()))
if (parsed.success) question = parsed.data
} catch {
// Retry once when the provider ignores structured-output requirements.
}
}
if (!question) throw createError({ statusCode: 502, statusMessage: 'The coauthor returned invalid answer options. Try the question again.' })
requireStageTwoSafeText([question.question, ...question.options].join('\n')) requireStageTwoSafeText([question.question, ...question.options].join('\n'))
const storedQuestion = StoredQuestionSchema.parse({ const storedQuestion = StoredCoauthorQuestionSchema.parse({
id: `question-${answerCount + 1}`, id: `question-${answerCount + 1}`,
label: question.question, label: question.question,
options: question.options, options: question.options,

View File

@@ -0,0 +1,37 @@
import { z } from 'zod'
import { requireStageTwoSafeText, requireStageTwoUser, stageTwoApiError, stageTwoDatabase } from '~/server/utils/stage-two-supabase'
import { visibleProfile, type ProfileRecord } from '~/server/utils/profile'
const ProfileUpdateSchema = z.object({
displayName: z.string().trim().min(1).max(80).optional(),
description: z.string().trim().max(500).optional(),
avatarPath: z.string().nullable().optional(),
}).strict().refine(value => Object.keys(value).length > 0, 'At least one profile field is required.')
export default defineEventHandler(async (event) => {
try {
const user = await requireStageTwoUser(event)
const update = ProfileUpdateSchema.parse(await readBody(event))
const expectedAvatarPath = `${user.id}/avatar`
if (update.avatarPath !== undefined && update.avatarPath !== null && update.avatarPath !== expectedAvatarPath) {
throw createError({ statusCode: 400, statusMessage: 'Invalid profile picture path.' })
}
if (update.displayName !== undefined) requireStageTwoSafeText(update.displayName)
if (update.description !== undefined) requireStageTwoSafeText(update.description)
const changes: Record<string, unknown> = { updated_at: new Date().toISOString() }
if (update.displayName !== undefined) changes.display_name = update.displayName
if (update.description !== undefined) changes.description = update.description
if (update.avatarPath !== undefined) changes.avatar_path = update.avatarPath
const profiles = await stageTwoDatabase<ProfileRecord[]>(`profiles?id=eq.${user.id}`, {
method: 'PATCH',
body: JSON.stringify(changes),
prefer: 'return=representation',
})
if (!profiles[0]) throw createError({ statusCode: 404, statusMessage: 'Profile not found.' })
return { profile: visibleProfile(profiles[0], useRuntimeConfig().supabaseUrl) }
} catch (error) {
stageTwoApiError(error)
}
})

View File

@@ -0,0 +1,65 @@
import { requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoUuid } from '~/server/utils/stage-two-supabase'
import { visibleProfile, type ProfileRecord } from '~/server/utils/profile'
interface MembershipRow {
campaign_id: string
role: string
joined_at: string
}
export default defineEventHandler(async (event) => {
try {
const user = await requireStageTwoUser(event)
const profileId = stageTwoUuid(getRouterParam(event, 'id'), 'profile id')
const viewerMemberships = await stageTwoDatabase<Array<{ campaign_id: string }>>(
`campaign_members?select=campaign_id&user_id=eq.${user.id}&active=eq.true`,
)
const viewerCampaignIds = [...new Set(viewerMemberships.map(member => member.campaign_id))]
let sharedMemberships: MembershipRow[]
if (profileId === user.id) {
sharedMemberships = await stageTwoDatabase<MembershipRow[]>(
`campaign_members?select=campaign_id,role,joined_at&user_id=eq.${profileId}&active=eq.true&order=joined_at.desc`,
)
} else if (viewerCampaignIds.length) {
sharedMemberships = await stageTwoDatabase<MembershipRow[]>(
`campaign_members?select=campaign_id,role,joined_at&user_id=eq.${profileId}&active=eq.true&campaign_id=in.(${viewerCampaignIds.join(',')})&order=joined_at.desc`,
)
} else {
sharedMemberships = []
}
if (profileId !== user.id && !sharedMemberships.length) {
throw createError({ statusCode: 404, statusMessage: 'Profile not found in your campaigns.' })
}
const profiles = await stageTwoDatabase<ProfileRecord[]>(
`profiles?select=id,display_name,description,avatar_path,created_at,updated_at&id=eq.${profileId}&limit=1`,
)
if (!profiles[0]) throw createError({ statusCode: 404, statusMessage: 'Profile not found.' })
const campaignIds = sharedMemberships.map(member => member.campaign_id)
const campaigns = campaignIds.length
? await stageTwoDatabase<Array<{ id: string; title: string; status: string }>>(
`campaigns?select=id,title,status&id=in.(${campaignIds.join(',')})`,
)
: []
const campaignById = new Map(campaigns.map(campaign => [campaign.id, campaign]))
const sharedCampaigns = sharedMemberships.flatMap((membership) => {
const campaign = campaignById.get(membership.campaign_id)
return campaign ? [{
id: campaign.id,
title: campaign.title,
status: campaign.status,
role: membership.role,
joined_at: membership.joined_at,
}] : []
})
return {
profile: visibleProfile(profiles[0], useRuntimeConfig().supabaseUrl),
sharedCampaigns,
}
} catch (error) {
stageTwoApiError(error)
}
})

View File

@@ -15,7 +15,7 @@ export default defineEventHandler(async event => {
let completion let completion
try { try {
completion = buildJsonCompletion(config, { completion = buildJsonCompletion(config, {
system: 'Create an original 13+ TTRPG starting world. Return only valid JSON matching the supplied WorldStarter structure, with exactly 3 NPCs and 2 factions. Do not use protected franchises.', system: 'Create an original 13+ TTRPG starting world. Return only valid JSON matching the supplied WorldStarter structure, with exactly 3 NPCs, 2 factions, and 3 distinct persistent AI companion heroes designed specifically for this universe. Give every companion complete playable mechanics, useful genre-appropriate equipment, and a distinctive persona. Do not use protected franchises.',
messages: request.messages, messages: request.messages,
schemaName: 'world_starter', schemaName: 'world_starter',
jsonSchema: WorldStarterSchema.toJSONSchema(), jsonSchema: WorldStarterSchema.toJSONSchema(),

View File

@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest'
import { CoauthorQuestionSchema, StoredCoauthorQuestionSchema } from './coauthor-question'
describe('coauthor question validation', () => {
it('accepts three useful, distinct answers', () => {
expect(CoauthorQuestionSchema.parse({
question: 'How will the party enter the sealed archive?',
options: ['Negotiate with its keeper', 'Search for a maintenance route', 'Force the main gate'],
})).toMatchObject({ options: ['Negotiate with its keeper', 'Search for a maintenance route', 'Force the main gate'] })
expect(CoauthorQuestionSchema.toJSONSchema()).toMatchObject({
type: 'object',
properties: { options: { type: 'array', minItems: 3, maxItems: 3 } },
})
})
it('rejects malformed JSON fragments and a repeated question', () => {
expect(() => CoauthorQuestionSchema.parse({
question: 'Как персонажи собираются решить проблему отсутствия наличных денег?',
options: [':', 'question', 'Как персонажи собираются решить проблему отсутствия наличных денег?'],
})).toThrow()
})
it('applies the same quality checks to a stored question', () => {
expect(() => StoredCoauthorQuestionSchema.parse({
id: 'question-2',
label: 'What makes the signal dangerous?',
options: ['The signal is alive', 'The signal is alive', 'Nobody knows yet'],
})).toThrow()
})
})

View File

@@ -0,0 +1,63 @@
import { z } from 'zod'
const reservedOptionValues = new Set([
'answer',
'answers',
'label',
'option',
'options',
'question',
])
function normalized(value: string) {
return value.trim().toLocaleLowerCase().replace(/\s+/g, ' ')
}
export const CoauthorQuestionSchema = z.object({
question: z.string().trim().min(5).max(300),
options: z.array(z.string().trim().min(2).max(100)).length(3),
}).superRefine((value, context) => {
const question = normalized(value.question)
const seen = new Set<string>()
value.options.forEach((option, index) => {
const candidate = normalized(option)
if (!/[\p{L}\p{N}]/u.test(candidate) || reservedOptionValues.has(candidate)) {
context.addIssue({
code: 'custom',
message: 'Each option must be a meaningful answer.',
path: ['options', index],
})
}
if (seen.has(candidate)) {
context.addIssue({
code: 'custom',
message: 'Answer options must be distinct.',
path: ['options', index],
})
}
if (candidate === question || (candidate.length >= 20 && question.includes(candidate))) {
context.addIssue({
code: 'custom',
message: 'An answer option must not repeat the question.',
path: ['options', index],
})
}
seen.add(candidate)
})
})
export const StoredCoauthorQuestionSchema = z.object({
id: z.string().trim().min(1).max(80),
label: z.string().trim().min(5).max(300),
options: CoauthorQuestionSchema.shape.options,
}).superRefine((value, context) => {
const result = CoauthorQuestionSchema.safeParse({ question: value.label, options: value.options })
for (const issue of result.error?.issues ?? []) {
context.addIssue({
code: 'custom',
message: issue.message,
path: issue.path[0] === 'question' ? ['label', ...issue.path.slice(1)] : issue.path,
})
}
})

View File

@@ -0,0 +1,29 @@
import { describe, expect, it } from 'vitest'
import { profileAvatarUrl, visibleProfile } from './profile'
const profile = {
id: '00000000-0000-0000-0000-000000000001',
display_name: 'Aster Vale',
description: 'Keeper of impossible maps.',
avatar_path: '00000000-0000-0000-0000-000000000001/avatar',
created_at: '2026-08-20T10:00:00.000Z',
updated_at: '2026-08-20T11:00:00.000Z',
}
describe('profile presentation', () => {
it('builds a cache-busted public avatar URL', () => {
expect(profileAvatarUrl(profile, 'https://example.supabase.co/')).toBe(
'https://example.supabase.co/storage/v1/object/public/profile-avatars/00000000-0000-0000-0000-000000000001/avatar?v=2026-08-20T11%3A00%3A00.000Z',
)
})
it('does not expose the storage path in a visible profile', () => {
const visible = visibleProfile(profile, 'https://example.supabase.co')
expect(visible).not.toHaveProperty('avatar_path')
expect(visible.avatar_url).toContain('/profile-avatars/')
})
it('returns no URL when the profile has no avatar', () => {
expect(profileAvatarUrl({ ...profile, avatar_path: null }, 'https://example.supabase.co')).toBeNull()
})
})

View File

@@ -0,0 +1,26 @@
export interface ProfileRecord {
id: string
display_name: string
description: string
avatar_path: string | null
created_at: string
updated_at: string
}
export function profileAvatarUrl(profile: Pick<ProfileRecord, 'avatar_path' | 'updated_at'>, supabaseUrl: string): string | null {
if (!profile.avatar_path) return null
const encodedPath = profile.avatar_path.split('/').map(encodeURIComponent).join('/')
const version = encodeURIComponent(profile.updated_at)
return `${supabaseUrl.replace(/\/$/, '')}/storage/v1/object/public/profile-avatars/${encodedPath}?v=${version}`
}
export function visibleProfile(profile: ProfileRecord, supabaseUrl: string) {
return {
id: profile.id,
display_name: profile.display_name,
description: profile.description,
avatar_url: profileAvatarUrl(profile, supabaseUrl),
created_at: profile.created_at,
updated_at: profile.updated_at,
}
}

View File

@@ -7,7 +7,11 @@ const AuthEmailSchema = z.preprocess(
value => value === null || value === '' ? undefined : value, value => value === null || value === '' ? undefined : value,
z.string().email().optional(), z.string().email().optional(),
) )
const AuthUserSchema = z.object({ id: UuidSchema, email: AuthEmailSchema }) const AuthUserSchema = z.object({
id: UuidSchema,
email: AuthEmailSchema,
is_anonymous: z.boolean().optional().default(false),
})
interface RequestOptions extends RequestInit { interface RequestOptions extends RequestInit {
prefer?: string prefer?: string
@@ -95,6 +99,9 @@ export async function requireStageTwoUser(event: H3Event): Promise<StageTwoUser>
if (!response.ok) throw createError({ statusCode: 401, statusMessage: 'The access token is invalid or expired.' }) if (!response.ok) throw createError({ statusCode: 401, statusMessage: 'The access token is invalid or expired.' })
const parsed = AuthUserSchema.safeParse(await response.json()) const parsed = AuthUserSchema.safeParse(await response.json())
if (!parsed.success) throw createError({ statusCode: 401, statusMessage: 'Supabase returned an invalid user.' }) if (!parsed.success) throw createError({ statusCode: 401, statusMessage: 'Supabase returned an invalid user.' })
if (parsed.data.is_anonymous || !parsed.data.email) {
throw createError({ statusCode: 403, statusMessage: 'A verified email account is required.' })
}
const profiles = await stageTwoDatabase<Array<{ id: string }>>(`profiles?select=id&id=eq.${parsed.data.id}&limit=1`) const profiles = await stageTwoDatabase<Array<{ id: string }>>(`profiles?select=id&id=eq.${parsed.data.id}&limit=1`)
if (!profiles[0]) throw createError({ statusCode: 403, statusMessage: 'This account is not enabled for the alpha.' }) if (!profiles[0]) throw createError({ statusCode: 403, statusMessage: 'This account is not enabled for the alpha.' })

View File

@@ -8,6 +8,17 @@ const worldFixture = () => ({
startingLocation: { id: 'location', kind: 'location' as const, name: 'Gate', summary: 'A station beyond known space.', tags: [] as string[], secrets: [] as string[] }, startingLocation: { id: 'location', kind: 'location' as const, name: 'Gate', summary: 'A station beyond known space.', tags: [] as string[], secrets: [] as string[] },
npcs: [1, 2, 3].map(index => ({ id: `npc-${index}`, kind: 'npc' as const, name: `NPC ${index}`, summary: 'A useful person with their own agenda.', tags: [], secrets: [] })), npcs: [1, 2, 3].map(index => ({ id: `npc-${index}`, kind: 'npc' as const, name: `NPC ${index}`, summary: 'A useful person with their own agenda.', tags: [], secrets: [] })),
factions: [1, 2].map(index => ({ id: `faction-${index}`, kind: 'faction' as const, name: `Faction ${index}`, summary: 'An organization pursuing a hidden objective.', tags: [], secrets: [] })), factions: [1, 2].map(index => ({ id: `faction-${index}`, kind: 'faction' as const, name: `Faction ${index}`, summary: 'An organization pursuing a hidden objective.', tags: [], secrets: [] })),
companions: [1, 2, 3].map(index => ({
name: `Companion ${index}`,
concept: `A universe-specific companion with role ${index}.`,
abilities: { str: 10, dex: 12, con: 11, int: 13, wis: 12, cha: 10 },
hp: 11,
maxHp: 11,
defense: 12,
proficiency: 2,
inventory: ['Field kit'],
persona: { voice: 'Distinctive and clear.', motivation: 'Help the party.', flaw: 'Has a private agenda.', bond: 'Believes in the party.' },
})),
hook: 'A sufficiently long hook that immediately gives the party something to investigate.', hook: 'A sufficiently long hook that immediately gives the party something to investigate.',
hiddenThreat: 'A hidden threat waits beyond the gate.', hiddenThreat: 'A hidden threat waits beyond the gate.',
openingScene: 'The gate opens without warning, and an impossible signal calls every hero by name.', openingScene: 'The gate opens without warning, and an impossible signal calls every hero by name.',
@@ -34,7 +45,10 @@ describe('worker AI providers', () => {
}) })
vi.stubGlobal('fetch', fetchMock) vi.stubGlobal('fetch', fetchMock)
const { generateWorld } = await import('./ai') const { generateWorld } = await import('./ai')
await expect(generateWorld([{ role: 'user', content: 'Create a science fiction frontier.' }])).resolves.toMatchObject({ title: 'Test Reach' }) await expect(generateWorld([{ role: 'user', content: 'Create a science fiction frontier.' }])).resolves.toMatchObject({
title: 'Test Reach',
companions: [{ name: 'Companion 1' }, { name: 'Companion 2' }, { name: 'Companion 3' }],
})
expect(fetchMock).toHaveBeenCalledWith('https://api.deepseek.com/chat/completions', expect.any(Object)) expect(fetchMock).toHaveBeenCalledWith('https://api.deepseek.com/chat/completions', expect.any(Object))
}) })

View File

@@ -89,7 +89,7 @@ async function structuredRequest<T>(name: string, schema: JsonSchema, messages:
export async function generateWorld(messages: Array<{ role: 'user' | 'assistant'; content: string }>): Promise<WorldStarter> { export async function generateWorld(messages: Array<{ role: 'user' | 'assistant'; content: string }>): Promise<WorldStarter> {
assert13Plus(...messages.map(message => message.content)) assert13Plus(...messages.map(message => message.content))
const world = await structuredRequest('world_starter', WorldStarterSchema.toJSONSchema(), [ const world = await structuredRequest('world_starter', WorldStarterSchema.toJSONSchema(), [
{ role: 'system', content: 'You are the Dungeons & Ground world coauthor. Create an original 13+ private TTRPG setting in any requested genre. Never use protected settings or characters. Return exactly three NPCs and two factions. Make the opening immediately playable.' }, { role: 'system', content: 'You are the Dungeons & Ground world coauthor. Create an original 13+ private TTRPG setting in any requested genre. Never use protected settings or characters. Return exactly three NPCs, two factions, and three distinct persistent AI companion heroes created specifically for this universe. Give each companion complete playable mechanics, useful genre-appropriate equipment, and a persona that produces interesting party choices without overriding the human player. Make the opening immediately playable.' },
...messages, ...messages,
], value => WorldStarterSchema.parse(value)) ], value => WorldStarterSchema.parse(value))
// Moderate the entire typed object, including entity summaries, secrets and // Moderate the entire typed object, including entity summaries, secrets and

View File

@@ -30,21 +30,6 @@ export const WorldEntitySchema = z.object({
}) })
export type WorldEntity = z.infer<typeof WorldEntitySchema> export type WorldEntity = z.infer<typeof WorldEntitySchema>
export const WorldStarterSchema = z.object({
title: z.string().min(3).max(100),
genre: z.string().min(2).max(80),
tone: z.string().min(2).max(160),
premise: z.string().min(20).max(1800),
contentBoundaries: z.array(z.string().max(120)).min(1).max(8),
startingLocation: WorldEntitySchema.extend({ kind: z.literal('location') }),
npcs: z.array(WorldEntitySchema.extend({ kind: z.literal('npc') })).length(3),
factions: z.array(WorldEntitySchema.extend({ kind: z.literal('faction') })).length(2),
hook: z.string().min(20).max(1200),
hiddenThreat: z.string().min(10).max(1000),
openingScene: z.string().min(40).max(2400),
})
export type WorldStarter = z.infer<typeof WorldStarterSchema>
export const CharacterPersonaSchema = z.object({ export const CharacterPersonaSchema = z.object({
voice: z.string().trim().min(1).max(240), voice: z.string().trim().min(1).max(240),
motivation: z.string().trim().min(1).max(300), motivation: z.string().trim().min(1).max(300),
@@ -69,6 +54,22 @@ export const CharacterDraftSchema = z.object({
}) })
export type CharacterDraft = z.infer<typeof CharacterDraftSchema> export type CharacterDraft = z.infer<typeof CharacterDraftSchema>
export const WorldStarterSchema = z.object({
title: z.string().min(3).max(100),
genre: z.string().min(2).max(80),
tone: z.string().min(2).max(160),
premise: z.string().min(20).max(1800),
contentBoundaries: z.array(z.string().max(120)).min(1).max(8),
startingLocation: WorldEntitySchema.extend({ kind: z.literal('location') }),
npcs: z.array(WorldEntitySchema.extend({ kind: z.literal('npc') })).length(3),
factions: z.array(WorldEntitySchema.extend({ kind: z.literal('faction') })).length(2),
companions: z.array(CharacterDraftSchema).length(3),
hook: z.string().min(20).max(1200),
hiddenThreat: z.string().min(10).max(1000),
openingScene: z.string().min(40).max(2400),
})
export type WorldStarter = z.infer<typeof WorldStarterSchema>
export const CharacterSchema = z.object({ export const CharacterSchema = z.object({
id: z.string().min(1), id: z.string().min(1),
name: z.string().min(1).max(80), name: z.string().min(1).max(80),

View File

@@ -38,14 +38,30 @@ async function jsonRequest(url, options = {}) {
return payload return payload
} }
async function createGuest(label) { function serviceHeaders() {
const session = await jsonRequest(`${supabaseUrl}/auth/v1/signup`, { return {
apikey: serviceKey,
...(serviceKey.split('.').length === 3 ? { Authorization: `Bearer ${serviceKey}` } : {}),
'Content-Type': 'application/json',
}
}
async function createEmailAccount(label) {
const email = `smoke-${randomUUID()}@example.com`
const password = `Smoke-${randomUUID()}!aA1`
const user = await jsonRequest(`${supabaseUrl}/auth/v1/admin/users`, {
method: 'POST',
headers: serviceHeaders(),
body: JSON.stringify({ email, password, email_confirm: true, user_metadata: { display_name: label } }),
})
const session = await jsonRequest(`${supabaseUrl}/auth/v1/token?grant_type=password`, {
method: 'POST', method: 'POST',
headers: { apikey: anonKey, 'Content-Type': 'application/json' }, headers: { apikey: anonKey, 'Content-Type': 'application/json' },
body: JSON.stringify({ data: { display_name: label }, gotrue_meta_security: {} }), body: JSON.stringify({ email, password }),
}) })
if (!session?.access_token || !session?.user?.id) throw new Error('[smoke] Supabase returned an incomplete anonymous session.') if (!session?.access_token || !session?.user?.id) throw new Error('[smoke] Supabase returned an incomplete email session.')
return { token: session.access_token, id: session.user.id } if (session.user.id !== user.id) throw new Error('[smoke] Email login returned the wrong user.')
return { token: session.access_token, id: session.user.id, email }
} }
function appRequest(path, token, options = {}) { function appRequest(path, token, options = {}) {
@@ -56,15 +72,10 @@ function appRequest(path, token, options = {}) {
} }
async function servicePatch(path, body) { async function servicePatch(path, body) {
const serviceAuthorization = serviceKey.split('.').length === 3
? { Authorization: `Bearer ${serviceKey}` }
: {}
await jsonRequest(`${supabaseUrl}/rest/v1/${path}`, { await jsonRequest(`${supabaseUrl}/rest/v1/${path}`, {
method: 'PATCH', method: 'PATCH',
headers: { headers: {
apikey: serviceKey, ...serviceHeaders(),
...serviceAuthorization,
'Content-Type': 'application/json',
Prefer: 'return=representation', Prefer: 'return=representation',
}, },
body: JSON.stringify(body), body: JSON.stringify(body),
@@ -72,10 +83,10 @@ async function servicePatch(path, body) {
} }
const suffix = Date.now().toString(36).toUpperCase() const suffix = Date.now().toString(36).toUpperCase()
console.log('[smoke] Creating two isolated guest sessions…') console.log('[smoke] Creating two confirmed email accounts…')
const [owner, player] = await Promise.all([ const [owner, player] = await Promise.all([
createGuest(`Smoke Owner ${suffix}`), createEmailAccount(`Smoke Owner ${suffix}`),
createGuest(`Smoke Player ${suffix}`), createEmailAccount(`Smoke Player ${suffix}`),
]) ])
console.log('[smoke] Creating a private world and campaign through the public API…') console.log('[smoke] Creating a private world and campaign through the public API…')
@@ -101,6 +112,17 @@ const world = {
entity('faction', 'The Reclaimers', 'Salvagers who want the station stripped for parts.'), entity('faction', 'The Reclaimers', 'Salvagers who want the station stripped for parts.'),
entity('faction', 'The Seed Vault', 'An automated network protecting the last viable specimens.'), entity('faction', 'The Seed Vault', 'An automated network protecting the last viable specimens.'),
], ],
companions: [1, 2, 3].map(index => ({
name: `Garden Companion ${index}`,
concept: `A universe-specific caretaker hero assigned to garden sector ${index}.`,
abilities: { str: 10, dex: 12, con: 11, int: 13, wis: 12, cha: 10 },
hp: 11,
maxHp: 11,
defense: 12,
proficiency: 2,
inventory: ['Garden survey kit'],
persona: { voice: 'Calm and observant.', motivation: 'Protect the living garden.', flaw: 'Trusts the station too much.', bond: 'Treats the party as new growth.' },
})),
hook: 'The airlock opens only after both visitors speak names the station already knows.', hook: 'The airlock opens only after both visitors speak names the station already knows.',
hiddenThreat: 'The garden predicts visitors by growing imperfect biological copies of them.', hiddenThreat: 'The garden predicts visitors by growing imperfect biological copies of them.',
openingScene: 'The inner airlock opens on warm rain and rows of silver trees. A voice welcomes both salvagers by name, then asks why one of them has returned without the other.', openingScene: 'The inner airlock opens on warm rain and rows of silver trees. A voice welcomes both salvagers by name, then asks why one of them has returned without the other.',
@@ -112,6 +134,12 @@ const { worldId } = await appRequest(`/api/v1/coauthor/sessions/${sessionId}/con
const { campaignId } = await appRequest('/api/v1/campaigns', owner.token, { const { campaignId } = await appRequest('/api/v1/campaigns', owner.token, {
method: 'POST', body: JSON.stringify({ worldId, title: `Smoke Party ${suffix}` }), method: 'POST', body: JSON.stringify({ worldId, title: `Smoke Party ${suffix}` }),
}) })
const starterParty = await appRequest(`/api/v1/campaigns/${campaignId}`, owner.token)
const ownerCharacter = starterParty.characters.find(character => character.user_id === owner.id && character.controller === 'human')
const automaticCompanions = starterParty.characters.filter(character => character.controller === 'ai')
if (!ownerCharacter || automaticCompanions.length !== world.companions.length || automaticCompanions.some(character => character.name === 'Echo') || starterParty.round?.status !== 'open') {
throw new Error('[smoke] A new campaign did not start with its actionable owner hero, generated world companions, and an open round.')
}
console.log('[smoke] Joining the second player through an invite…') console.log('[smoke] Joining the second player through an invite…')
const { token: inviteToken } = await appRequest(`/api/v1/campaigns/${campaignId}/invites`, owner.token, { const { token: inviteToken } = await appRequest(`/api/v1/campaigns/${campaignId}/invites`, owner.token, {
@@ -126,14 +154,11 @@ const characterBody = (name, concept) => JSON.stringify({
name, concept, controller: 'human', abilities: { str: 10, dex: 10, con: 10, int: 12, wis: 11, cha: 9 }, name, concept, controller: 'human', abilities: { str: 10, dex: 10, con: 10, int: 12, wis: 11, cha: 9 },
hp: 12, maxHp: 12, defense: 12, proficiency: 2, inventory: [], statuses: [], persona: {}, hp: 12, maxHp: 12, defense: 12, proficiency: 2, inventory: [], statuses: [], persona: {},
}) })
const ownerCharacter = await appRequest(`/api/v1/campaigns/${campaignId}/characters`, owner.token, {
method: 'POST', body: characterBody('Iris Vale', 'A methodical station engineer.'),
})
const playerCharacter = await appRequest(`/api/v1/campaigns/${campaignId}/characters`, player.token, { const playerCharacter = await appRequest(`/api/v1/campaigns/${campaignId}/characters`, player.token, {
method: 'POST', body: characterBody('Rowan Pike', 'A curious xenobotanist.'), method: 'POST', body: characterBody('Rowan Pike', 'A curious xenobotanist.'),
}) })
console.log('[smoke] Drafting and adding a persistent AI companion…') console.log('[smoke] Verifying AI drafting while keeping the automatic companion…')
const suggested = await appRequest(`/api/v1/campaigns/${campaignId}/characters/suggest`, owner.token, { const suggested = await appRequest(`/api/v1/campaigns/${campaignId}/characters/suggest`, owner.token, {
method: 'POST', method: 'POST',
body: JSON.stringify({ controller: 'ai', concept: 'A damaged garden caretaker who values living things over orders.' }), body: JSON.stringify({ controller: 'ai', concept: 'A damaged garden caretaker who values living things over orders.' }),
@@ -141,20 +166,16 @@ const suggested = await appRequest(`/api/v1/campaigns/${campaignId}/characters/s
if (!suggested?.character?.name || !suggested.character?.persona?.motivation) { if (!suggested?.character?.name || !suggested.character?.persona?.motivation) {
throw new Error('[smoke] Character coauthor returned an incomplete draft.') throw new Error('[smoke] Character coauthor returned an incomplete draft.')
} }
await appRequest(`/api/v1/campaigns/${campaignId}/characters`, owner.token, {
method: 'POST',
body: JSON.stringify({ ...suggested.character, controller: 'ai', statuses: [] }),
})
const initial = await appRequest(`/api/v1/campaigns/${campaignId}`, owner.token) const initial = await appRequest(`/api/v1/campaigns/${campaignId}`, owner.token)
if (initial.members.length !== 2) throw new Error(`[smoke] Expected 2 members, received ${initial.members.length}.`) if (initial.members.length !== 2) throw new Error(`[smoke] Expected 2 members, received ${initial.members.length}.`)
if (initial.characters.length !== 3 || initial.round?.status !== 'open') throw new Error('[smoke] Multiplayer lobby did not expose two humans, one AI companion, and an open round.') if (initial.characters.length !== 5 || initial.round?.status !== 'open') throw new Error('[smoke] Multiplayer lobby did not expose two humans, three generated AI companions, and an open round.')
const roundId = initial.round.id const roundId = initial.round.id
console.log('[smoke] Verifying that the round waits for both humans…') console.log('[smoke] Verifying that the round waits for both humans…')
await appRequest(`/api/v1/campaigns/${campaignId}/rounds/${roundId}/intent`, owner.token, { await appRequest(`/api/v1/campaigns/${campaignId}/rounds/${roundId}/intent`, owner.token, {
method: 'PUT', method: 'PUT',
body: JSON.stringify({ characterId: ownerCharacter.character.id, action: 'Iris checks the airlock telemetry for a safe path.', ready: true }), body: JSON.stringify({ characterId: ownerCharacter.id, action: 'The owner checks the airlock telemetry for a safe path.', ready: true }),
}) })
await new Promise(resolve => setTimeout(resolve, 1_500)) await new Promise(resolve => setTimeout(resolve, 1_500))
const waiting = await appRequest(`/api/v1/campaigns/${campaignId}`, player.token) const waiting = await appRequest(`/api/v1/campaigns/${campaignId}`, player.token)

View File

@@ -2175,6 +2175,611 @@ grant execute on function public.dng_schema_version() to service_role;
notify pgrst, 'reload schema'; notify pgrst, 'reload schema';
-- ============================================================================
-- 0008_required_email_accounts.sql
-- ============================================================================
-- D&G now uses recoverable email/password accounts. Keep the legacy function
-- names so existing auth.users triggers are upgraded in place.
create or replace function public.create_profile_for_allowlisted_user()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
v_display_name text;
begin
if coalesce(new.is_anonymous, false) or nullif(btrim(new.email), '') is null then
raise exception using
errcode = '42501',
message = 'A Dungeons & Ground account requires an email address.';
end if;
v_display_name := coalesce(
nullif(btrim(new.raw_user_meta_data ->> 'display_name'), ''),
split_part(new.email, '@', 1),
'Adventurer'
);
insert into public.profiles(id, display_name)
values (new.id, left(v_display_name, 80))
on conflict (id) do update
set display_name = excluded.display_name;
return new;
end;
$$;
revoke all on function public.create_profile_for_allowlisted_user() from public, anon, authenticated;
create or replace function public.enforce_alpha_email_allowlist()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
if coalesce(new.is_anonymous, false) or nullif(btrim(new.email), '') is null then
raise exception using
errcode = '42501',
message = 'A Dungeons & Ground account requires an email address.';
end if;
return new;
end;
$$;
revoke all on function public.enforce_alpha_email_allowlist() from public, anon, authenticated;
-- Installations may contain confirmed email users created before the D&G
-- schema. Give every non-anonymous email account a profile without touching
-- existing campaign ownership or display names.
insert into public.profiles(id, display_name)
select
auth_user.id,
left(coalesce(
nullif(btrim(auth_user.raw_user_meta_data ->> 'display_name'), ''),
split_part(auth_user.email, '@', 1),
'Adventurer'
), 80)
from auth.users auth_user
where not coalesce(auth_user.is_anonymous, false)
and nullif(btrim(auth_user.email), '') is not null
on conflict (id) do nothing;
create or replace function public.dng_schema_version()
returns integer language sql stable security definer set search_path = '' as $$
select 8;
$$;
revoke all on function public.dng_schema_version() from public, anon, authenticated;
grant execute on function public.dng_schema_version() to service_role;
notify pgrst, 'reload schema';
-- ============================================================================
-- 0009_profile_management.sql
-- ============================================================================
alter table public.profiles
add column description text not null default '' check (char_length(description) <= 500),
add column avatar_path text check (avatar_path is null or avatar_path = id::text || '/avatar'),
add column updated_at timestamptz not null default now();
-- Avatars are public profile media, but only the owning authenticated user may
-- create, replace, or remove the one deterministic object in their folder.
insert into storage.buckets(id, name, public, file_size_limit, allowed_mime_types)
values (
'profile-avatars',
'profile-avatars',
true,
2097152,
array['image/jpeg', 'image/png', 'image/webp']
)
on conflict (id) do update
set public = excluded.public,
file_size_limit = excluded.file_size_limit,
allowed_mime_types = excluded.allowed_mime_types;
create policy dng_profile_avatar_insert
on storage.objects for insert to authenticated
with check (
bucket_id = 'profile-avatars'
and name = (select auth.uid())::text || '/avatar'
);
create policy dng_profile_avatar_select_own
on storage.objects for select to authenticated
using (
bucket_id = 'profile-avatars'
and name = (select auth.uid())::text || '/avatar'
);
create policy dng_profile_avatar_update
on storage.objects for update to authenticated
using (
bucket_id = 'profile-avatars'
and name = (select auth.uid())::text || '/avatar'
)
with check (
bucket_id = 'profile-avatars'
and name = (select auth.uid())::text || '/avatar'
);
create policy dng_profile_avatar_delete
on storage.objects for delete to authenticated
using (
bucket_id = 'profile-avatars'
and name = (select auth.uid())::text || '/avatar'
);
create or replace function public.dng_schema_version()
returns integer language sql stable security definer set search_path = '' as $$
select 9;
$$;
revoke all on function public.dng_schema_version() from public, anon, authenticated;
grant execute on function public.dng_schema_version() to service_role;
notify pgrst, 'reload schema';
-- ============================================================================
-- 0010_playable_starter_parties.sql
-- ============================================================================
-- Make a newly launched campaign playable immediately: the owner receives a
-- human-controlled starter, and only actionable members hold the round open.
create or replace function public.stage_two_create_campaign(
p_world_id uuid,
p_owner_id uuid,
p_title text
) returns uuid language plpgsql security definer set search_path = '' as $$
declare
v_world public.worlds%rowtype;
v_campaign_id uuid;
v_owner_name text;
begin
if p_title is null or char_length(btrim(p_title)) not between 3 and 100 then
raise exception 'campaign title must be between 3 and 100 characters';
end if;
select * into v_world from public.worlds
where id = p_world_id and owner_id = p_owner_id and status = 'confirmed' for share;
if not found then raise exception 'confirmed world not found'; end if;
select nullif(btrim(display_name), '') into v_owner_name
from public.profiles where id = p_owner_id;
v_owner_name := left(coalesce(v_owner_name, 'Wayfinder'), 80);
insert into public.campaigns(world_id, owner_id, title, current_scene, next_prompt, status)
values (p_world_id, p_owner_id, btrim(p_title), coalesce(v_world.opening_scene, v_world.premise), 'What do you do?', 'active')
returning id into v_campaign_id;
insert into public.campaign_members(campaign_id, user_id, role)
values (v_campaign_id, p_owner_id, 'owner');
insert into public.characters(
campaign_id, user_id, name, concept, controller, abilities, hp, max_hp,
defense, proficiency, inventory, statuses, persona
) values (
v_campaign_id,
p_owner_id,
v_owner_name,
left('An adaptable protagonist ready to confront the opening mystery of ' || v_world.title || '.', 600),
'human'::public.character_controller,
'{"str":10,"dex":12,"con":12,"int":11,"wis":13,"cha":10}'::jsonb,
12,
12,
12,
2,
'["Field kit","Personal keepsake"]'::jsonb,
'[]'::jsonb,
jsonb_build_object(
'voice', 'Defined by the player.',
'motivation', 'Discover what the opening scene is hiding.',
'flaw', 'Still learning what this world demands.',
'bond', 'Protect the party through the first danger.'
)
);
insert into public.rounds(campaign_id, number) values (v_campaign_id, 1);
return v_campaign_id;
end;
$$;
-- Members who have not created a character cannot submit an intent and must not
-- hold the round open. Only active members with a human-controlled character
-- participate in the readiness barrier.
create or replace function public.stage_two_submit_intent(
p_round_id uuid,
p_user_id uuid,
p_character_id uuid,
p_action text,
p_ready boolean default false
) returns jsonb language plpgsql security definer set search_path = '' as $$
declare
v_round public.rounds%rowtype;
v_member public.campaign_members%rowtype;
v_intent_id uuid;
v_job_id uuid;
begin
if p_action is null or char_length(btrim(p_action)) not between 1 and 2000 then
raise exception 'action must be between 1 and 2000 characters';
end if;
select * into v_round from public.rounds where id = p_round_id for update;
if not found or v_round.status <> 'open' then raise exception 'round is not open'; end if;
select * into v_member from public.campaign_members
where campaign_id = v_round.campaign_id and user_id = p_user_id and active;
if not found then raise exception 'active campaign membership not found'; end if;
if not exists (
select 1 from public.characters
where id = p_character_id and campaign_id = v_round.campaign_id
and user_id = p_user_id and controller = 'human'
) then raise exception 'controlled character not found'; end if;
insert into public.player_intents(round_id, member_id, character_id, action, ready)
values (p_round_id, v_member.id, p_character_id, btrim(p_action), coalesce(p_ready, false))
on conflict (round_id, member_id) do update
set character_id = excluded.character_id, action = excluded.action,
ready = excluded.ready, updated_at = now()
returning id into v_intent_id;
if coalesce(p_ready, false) and not exists (
select 1
from public.campaign_members member
join public.characters character
on character.campaign_id = member.campaign_id
and character.user_id = member.user_id
and character.controller = 'human'::public.character_controller
where member.campaign_id = v_round.campaign_id
and member.active
and not exists (
select 1 from public.player_intents intent
where intent.round_id = p_round_id and intent.member_id = member.id and intent.ready
)
) then
v_job_id := public.enqueue_round_resolution(p_round_id, null);
end if;
return jsonb_build_object('intentId', v_intent_id, 'jobId', v_job_id);
end;
$$;
-- Repair campaigns created before starter parties were automatic.
insert into public.characters(
campaign_id, user_id, name, concept, controller, abilities, hp, max_hp,
defense, proficiency, inventory, statuses, persona
)
select
campaign.id,
campaign.owner_id,
left(coalesce(nullif(btrim(profile.display_name), ''), 'Wayfinder'), 80),
left('An adaptable protagonist ready to confront the opening mystery of ' || world.title || '.', 600),
'human'::public.character_controller,
'{"str":10,"dex":12,"con":12,"int":11,"wis":13,"cha":10}'::jsonb,
12,
12,
12,
2,
'["Field kit","Personal keepsake"]'::jsonb,
'[]'::jsonb,
jsonb_build_object(
'voice', 'Defined by the player.',
'motivation', 'Discover what the opening scene is hiding.',
'flaw', 'Still learning what this world demands.',
'bond', 'Protect the party through the first danger.'
)
from public.campaigns campaign
join public.worlds world on world.id = campaign.world_id
left join public.profiles profile on profile.id = campaign.owner_id
where campaign.status = 'active'
and not exists (
select 1 from public.characters character
where character.campaign_id = campaign.id
and character.user_id = campaign.owner_id
);
create or replace function public.dng_schema_version()
returns integer language sql stable security definer set search_path = '' as $$
select 10;
$$;
revoke all on function public.dng_schema_version() from public, anon, authenticated;
grant execute on function public.dng_schema_version() to service_role;
notify pgrst, 'reload schema';
-- ============================================================================
-- 0011_universe_companions.sql
-- ============================================================================
-- Persist the AI companions created with each universe and use that party when
-- a campaign starts. This replaces the temporary hard-coded Echo companion.
alter table public.worlds
add column if not exists starter_companions jsonb not null default '[]'::jsonb;
alter table public.worlds
drop constraint if exists worlds_starter_companions_array;
alter table public.worlds
add constraint worlds_starter_companions_array check (
jsonb_typeof(starter_companions) = 'array'
and jsonb_array_length(starter_companions) <= 3
);
-- Ready drafts created before companions were part of WorldStarter inherit
-- three universe-specific people that the coauthor already generated.
update public.coauthor_sessions session
set generated_world = jsonb_set(
session.generated_world,
'{companions}',
coalesce((
select jsonb_agg(
jsonb_build_object(
'name', npc.value->>'name',
'concept', left(npc.value->>'summary', 600),
'abilities', case npc.position
when 1 then '{"str":10,"dex":14,"con":11,"int":13,"wis":12,"cha":10}'::jsonb
when 2 then '{"str":13,"dex":10,"con":14,"int":10,"wis":12,"cha":11}'::jsonb
else '{"str":9,"dex":12,"con":11,"int":14,"wis":13,"cha":12}'::jsonb
end,
'hp', 10 + npc.position,
'maxHp', 10 + npc.position,
'defense', 11 + npc.position,
'proficiency', 2,
'inventory', jsonb_build_array('Universe field kit', 'Travel supplies'),
'persona', jsonb_build_object(
'voice', left(npc.value->>'summary', 240),
'motivation', left('Pursue the goal behind: ' || (npc.value->>'summary'), 300),
'flaw', 'Their personal agenda can complicate the party''s plans.',
'bond', left('They belong to ' || (session.generated_world->>'title') || ' and choose to stand with the party.', 300)
)
) order by npc.position
)
from jsonb_array_elements(coalesce(session.generated_world->'npcs', '[]'::jsonb))
with ordinality as npc(value, position)
where npc.position <= 3
), '[]'::jsonb),
true
),
updated_at = now()
where session.generated_world is not null
and jsonb_typeof(session.generated_world->'npcs') = 'array'
and coalesce(jsonb_array_length(session.generated_world->'companions'), 0) = 0;
-- Confirmed universes do not retain the original generation JSON. Build their
-- starter companions from the AI-created NPC entities already stored for them.
update public.worlds world
set starter_companions = coalesce((
select jsonb_agg(
jsonb_build_object(
'name', npc.name,
'concept', left(npc.summary, 600),
'abilities', case npc.position
when 1 then '{"str":10,"dex":14,"con":11,"int":13,"wis":12,"cha":10}'::jsonb
when 2 then '{"str":13,"dex":10,"con":14,"int":10,"wis":12,"cha":11}'::jsonb
else '{"str":9,"dex":12,"con":11,"int":14,"wis":13,"cha":12}'::jsonb
end,
'hp', 10 + npc.position,
'maxHp', 10 + npc.position,
'defense', 11 + npc.position,
'proficiency', 2,
'inventory', jsonb_build_array('Universe field kit', 'Travel supplies'),
'persona', jsonb_build_object(
'voice', left(npc.summary, 240),
'motivation', left('Pursue the goal behind: ' || npc.summary, 300),
'flaw', 'Their personal agenda can complicate the party''s plans.',
'bond', left('They belong to ' || world.title || ' and choose to stand with the party.', 300)
)
) order by npc.position
)
from (
select entity.name, entity.summary,
(row_number() over (order by entity.created_at, entity.id))::integer as position
from public.world_entities entity
where entity.world_id = world.id and entity.kind = 'npc'
order by entity.created_at, entity.id
limit 3
) npc
), '[]'::jsonb)
where jsonb_array_length(world.starter_companions) = 0;
create or replace function public.stage_two_confirm_world(
p_session_id uuid,
p_owner_id uuid
) returns uuid language plpgsql security definer set search_path = '' as $$
declare
v_session public.coauthor_sessions%rowtype;
v_world jsonb;
v_world_id uuid;
v_entity jsonb;
begin
select * into v_session from public.coauthor_sessions
where id = p_session_id and owner_id = p_owner_id for update;
if not found then raise exception 'coauthor session not found'; end if;
if v_session.status = 'confirmed' and v_session.confirmed_world_id is not null then
return v_session.confirmed_world_id;
end if;
if v_session.status <> 'ready' or v_session.generated_world is null then
raise exception 'coauthor session is not ready to confirm';
end if;
v_world := v_session.generated_world;
if coalesce(v_world->>'title', '') = ''
or coalesce(v_world->>'openingScene', '') = ''
or jsonb_typeof(v_world->'companions') <> 'array'
or jsonb_array_length(v_world->'companions') <> 3 then
raise exception 'generated world is incomplete';
end if;
insert into public.worlds(
owner_id, title, genre, tone, premise, content_boundaries,
hidden_threat, hook, opening_scene, starter_companions, status
) values (
p_owner_id, v_world->>'title', v_world->>'genre', v_world->>'tone', v_world->>'premise',
coalesce(v_world->'contentBoundaries', '[]'::jsonb), v_world->>'hiddenThreat',
v_world->>'hook', v_world->>'openingScene', v_world->'companions', 'confirmed'
) returning id into v_world_id;
v_entity := v_world->'startingLocation';
insert into public.world_entities(world_id, kind, name, summary, tags, secrets)
values (v_world_id, 'location', v_entity->>'name', v_entity->>'summary',
array(select jsonb_array_elements_text(coalesce(v_entity->'tags', '[]'::jsonb))),
coalesce(v_entity->'secrets', '[]'::jsonb));
for v_entity in select * from jsonb_array_elements(v_world->'npcs') loop
insert into public.world_entities(world_id, kind, name, summary, tags, secrets)
values (v_world_id, 'npc', v_entity->>'name', v_entity->>'summary',
array(select jsonb_array_elements_text(coalesce(v_entity->'tags', '[]'::jsonb))),
coalesce(v_entity->'secrets', '[]'::jsonb));
end loop;
for v_entity in select * from jsonb_array_elements(v_world->'factions') loop
insert into public.world_entities(world_id, kind, name, summary, tags, secrets)
values (v_world_id, 'faction', v_entity->>'name', v_entity->>'summary',
array(select jsonb_array_elements_text(coalesce(v_entity->'tags', '[]'::jsonb))),
coalesce(v_entity->'secrets', '[]'::jsonb));
end loop;
insert into public.world_entities(world_id, kind, name, summary, tags, secrets)
values (v_world_id, 'quest', 'Opening Hook', v_world->>'hook', array['opening'], '[]'::jsonb);
update public.coauthor_sessions
set status = 'confirmed', confirmed_world_id = v_world_id, updated_at = now()
where id = p_session_id;
return v_world_id;
end;
$$;
create or replace function public.stage_two_create_campaign(
p_world_id uuid,
p_owner_id uuid,
p_title text
) returns uuid language plpgsql security definer set search_path = '' as $$
declare
v_world public.worlds%rowtype;
v_campaign_id uuid;
v_owner_name text;
v_companion jsonb;
begin
if p_title is null or char_length(btrim(p_title)) not between 3 and 100 then
raise exception 'campaign title must be between 3 and 100 characters';
end if;
select * into v_world from public.worlds
where id = p_world_id and owner_id = p_owner_id and status = 'confirmed' for share;
if not found then raise exception 'confirmed world not found'; end if;
if jsonb_typeof(v_world.starter_companions) <> 'array'
or jsonb_array_length(v_world.starter_companions) = 0 then
raise exception 'confirmed world has no AI companions';
end if;
select nullif(btrim(display_name), '') into v_owner_name
from public.profiles where id = p_owner_id;
v_owner_name := left(coalesce(v_owner_name, 'Wayfinder'), 80);
insert into public.campaigns(world_id, owner_id, title, current_scene, next_prompt, status)
values (p_world_id, p_owner_id, btrim(p_title), coalesce(v_world.opening_scene, v_world.premise), 'What do you do?', 'active')
returning id into v_campaign_id;
insert into public.campaign_members(campaign_id, user_id, role)
values (v_campaign_id, p_owner_id, 'owner');
insert into public.characters(
campaign_id, user_id, name, concept, controller, abilities, hp, max_hp,
defense, proficiency, inventory, statuses, persona
) values (
v_campaign_id,
p_owner_id,
v_owner_name,
left('An adaptable protagonist ready to confront the opening mystery of ' || v_world.title || '.', 600),
'human'::public.character_controller,
'{"str":10,"dex":12,"con":12,"int":11,"wis":13,"cha":10}'::jsonb,
12,
12,
12,
2,
'["Field kit","Personal keepsake"]'::jsonb,
'[]'::jsonb,
jsonb_build_object(
'voice', 'Defined by the player.',
'motivation', 'Discover what the opening scene is hiding.',
'flaw', 'Still learning what this world demands.',
'bond', 'Protect the party through the first danger.'
)
);
for v_companion in select * from jsonb_array_elements(v_world.starter_companions) loop
insert into public.characters(
campaign_id, user_id, name, concept, controller, abilities, hp, max_hp,
defense, proficiency, inventory, statuses, persona
) values (
v_campaign_id,
null,
v_companion->>'name',
v_companion->>'concept',
'ai'::public.character_controller,
v_companion->'abilities',
(v_companion->>'hp')::integer,
(v_companion->>'maxHp')::integer,
(v_companion->>'defense')::integer,
(v_companion->>'proficiency')::integer,
v_companion->'inventory',
'[]'::jsonb,
v_companion->'persona'
);
end loop;
insert into public.rounds(campaign_id, number) values (v_campaign_id, 1);
return v_campaign_id;
end;
$$;
-- Remove only the exact temporary Echo inserted by schema v10, preserving any
-- independently authored character that happens to share the name.
delete from public.characters character
where character.user_id is null
and character.controller = 'ai'::public.character_controller
and character.name = 'Echo'
and character.inventory = '["Survey kit","Emergency supplies"]'::jsonb
and character.persona->>'voice' = 'Observant, concise, and quietly curious.'
and character.persona->>'motivation' = 'Help the party understand this unfamiliar world.'
and character.concept like 'A persistent AI companion shaped by the %';
-- Existing active campaigns receive the companion roster belonging to their
-- universe. Name matching keeps this migration idempotent around manual heroes.
insert into public.characters(
campaign_id, user_id, name, concept, controller, abilities, hp, max_hp,
defense, proficiency, inventory, statuses, persona
)
select
campaign.id,
null,
companion.value->>'name',
companion.value->>'concept',
'ai'::public.character_controller,
companion.value->'abilities',
(companion.value->>'hp')::integer,
(companion.value->>'maxHp')::integer,
(companion.value->>'defense')::integer,
(companion.value->>'proficiency')::integer,
companion.value->'inventory',
'[]'::jsonb,
companion.value->'persona'
from public.campaigns campaign
join public.worlds world on world.id = campaign.world_id
cross join lateral jsonb_array_elements(world.starter_companions) companion(value)
where campaign.status = 'active'
and not exists (
select 1 from public.characters character
where character.campaign_id = campaign.id
and character.controller = 'ai'::public.character_controller
and lower(character.name) = lower(companion.value->>'name')
);
create or replace function public.dng_schema_version()
returns integer language sql stable security definer set search_path = '' as $$
select 11;
$$;
revoke all on function public.dng_schema_version() from public, anon, authenticated;
grant execute on function public.dng_schema_version() to service_role;
notify pgrst, 'reload schema';
do $$ do $$
begin begin
@@ -2199,7 +2804,7 @@ begin
if to_regprocedure('public.stage_four_create_character(uuid,uuid,text,text,text,jsonb,integer,integer,integer,integer,jsonb,jsonb,jsonb)') is null then if to_regprocedure('public.stage_four_create_character(uuid,uuid,text,text,text,jsonb,integer,integer,integer,integer,jsonb,jsonb,jsonb)') is null then
raise exception 'D&G bootstrap verification failed: character creation RPC is missing'; raise exception 'D&G bootstrap verification failed: character creation RPC is missing';
end if; end if;
if public.dng_schema_version() <> 7 then if public.dng_schema_version() <> 11 then
raise exception 'D&G bootstrap verification failed: unexpected schema version'; raise exception 'D&G bootstrap verification failed: unexpected schema version';
end if; end if;
end; end;

View File

@@ -0,0 +1,78 @@
-- D&G now uses recoverable email/password accounts. Keep the legacy function
-- names so existing auth.users triggers are upgraded in place.
create or replace function public.create_profile_for_allowlisted_user()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
v_display_name text;
begin
if coalesce(new.is_anonymous, false) or nullif(btrim(new.email), '') is null then
raise exception using
errcode = '42501',
message = 'A Dungeons & Ground account requires an email address.';
end if;
v_display_name := coalesce(
nullif(btrim(new.raw_user_meta_data ->> 'display_name'), ''),
split_part(new.email, '@', 1),
'Adventurer'
);
insert into public.profiles(id, display_name)
values (new.id, left(v_display_name, 80))
on conflict (id) do update
set display_name = excluded.display_name;
return new;
end;
$$;
revoke all on function public.create_profile_for_allowlisted_user() from public, anon, authenticated;
create or replace function public.enforce_alpha_email_allowlist()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
if coalesce(new.is_anonymous, false) or nullif(btrim(new.email), '') is null then
raise exception using
errcode = '42501',
message = 'A Dungeons & Ground account requires an email address.';
end if;
return new;
end;
$$;
revoke all on function public.enforce_alpha_email_allowlist() from public, anon, authenticated;
-- Installations may contain confirmed email users created before the D&G
-- schema. Give every non-anonymous email account a profile without touching
-- existing campaign ownership or display names.
insert into public.profiles(id, display_name)
select
auth_user.id,
left(coalesce(
nullif(btrim(auth_user.raw_user_meta_data ->> 'display_name'), ''),
split_part(auth_user.email, '@', 1),
'Adventurer'
), 80)
from auth.users auth_user
where not coalesce(auth_user.is_anonymous, false)
and nullif(btrim(auth_user.email), '') is not null
on conflict (id) do nothing;
create or replace function public.dng_schema_version()
returns integer language sql stable security definer set search_path = '' as $$
select 8;
$$;
revoke all on function public.dng_schema_version() from public, anon, authenticated;
grant execute on function public.dng_schema_version() to service_role;
notify pgrst, 'reload schema';

View File

@@ -0,0 +1,61 @@
alter table public.profiles
add column description text not null default '' check (char_length(description) <= 500),
add column avatar_path text check (avatar_path is null or avatar_path = id::text || '/avatar'),
add column updated_at timestamptz not null default now();
-- Avatars are public profile media, but only the owning authenticated user may
-- create, replace, or remove the one deterministic object in their folder.
insert into storage.buckets(id, name, public, file_size_limit, allowed_mime_types)
values (
'profile-avatars',
'profile-avatars',
true,
2097152,
array['image/jpeg', 'image/png', 'image/webp']
)
on conflict (id) do update
set public = excluded.public,
file_size_limit = excluded.file_size_limit,
allowed_mime_types = excluded.allowed_mime_types;
create policy dng_profile_avatar_insert
on storage.objects for insert to authenticated
with check (
bucket_id = 'profile-avatars'
and name = (select auth.uid())::text || '/avatar'
);
create policy dng_profile_avatar_select_own
on storage.objects for select to authenticated
using (
bucket_id = 'profile-avatars'
and name = (select auth.uid())::text || '/avatar'
);
create policy dng_profile_avatar_update
on storage.objects for update to authenticated
using (
bucket_id = 'profile-avatars'
and name = (select auth.uid())::text || '/avatar'
)
with check (
bucket_id = 'profile-avatars'
and name = (select auth.uid())::text || '/avatar'
);
create policy dng_profile_avatar_delete
on storage.objects for delete to authenticated
using (
bucket_id = 'profile-avatars'
and name = (select auth.uid())::text || '/avatar'
);
create or replace function public.dng_schema_version()
returns integer language sql stable security definer set search_path = '' as $$
select 9;
$$;
revoke all on function public.dng_schema_version() from public, anon, authenticated;
grant execute on function public.dng_schema_version() to service_role;
notify pgrst, 'reload schema';

View File

@@ -0,0 +1,159 @@
-- Make a newly launched campaign playable immediately: the owner receives a
-- human-controlled starter, and only actionable members hold the round open.
create or replace function public.stage_two_create_campaign(
p_world_id uuid,
p_owner_id uuid,
p_title text
) returns uuid language plpgsql security definer set search_path = '' as $$
declare
v_world public.worlds%rowtype;
v_campaign_id uuid;
v_owner_name text;
begin
if p_title is null or char_length(btrim(p_title)) not between 3 and 100 then
raise exception 'campaign title must be between 3 and 100 characters';
end if;
select * into v_world from public.worlds
where id = p_world_id and owner_id = p_owner_id and status = 'confirmed' for share;
if not found then raise exception 'confirmed world not found'; end if;
select nullif(btrim(display_name), '') into v_owner_name
from public.profiles where id = p_owner_id;
v_owner_name := left(coalesce(v_owner_name, 'Wayfinder'), 80);
insert into public.campaigns(world_id, owner_id, title, current_scene, next_prompt, status)
values (p_world_id, p_owner_id, btrim(p_title), coalesce(v_world.opening_scene, v_world.premise), 'What do you do?', 'active')
returning id into v_campaign_id;
insert into public.campaign_members(campaign_id, user_id, role)
values (v_campaign_id, p_owner_id, 'owner');
insert into public.characters(
campaign_id, user_id, name, concept, controller, abilities, hp, max_hp,
defense, proficiency, inventory, statuses, persona
) values (
v_campaign_id,
p_owner_id,
v_owner_name,
left('An adaptable protagonist ready to confront the opening mystery of ' || v_world.title || '.', 600),
'human'::public.character_controller,
'{"str":10,"dex":12,"con":12,"int":11,"wis":13,"cha":10}'::jsonb,
12,
12,
12,
2,
'["Field kit","Personal keepsake"]'::jsonb,
'[]'::jsonb,
jsonb_build_object(
'voice', 'Defined by the player.',
'motivation', 'Discover what the opening scene is hiding.',
'flaw', 'Still learning what this world demands.',
'bond', 'Protect the party through the first danger.'
)
);
insert into public.rounds(campaign_id, number) values (v_campaign_id, 1);
return v_campaign_id;
end;
$$;
-- Members who have not created a character cannot submit an intent and must not
-- hold the round open. Only active members with a human-controlled character
-- participate in the readiness barrier.
create or replace function public.stage_two_submit_intent(
p_round_id uuid,
p_user_id uuid,
p_character_id uuid,
p_action text,
p_ready boolean default false
) returns jsonb language plpgsql security definer set search_path = '' as $$
declare
v_round public.rounds%rowtype;
v_member public.campaign_members%rowtype;
v_intent_id uuid;
v_job_id uuid;
begin
if p_action is null or char_length(btrim(p_action)) not between 1 and 2000 then
raise exception 'action must be between 1 and 2000 characters';
end if;
select * into v_round from public.rounds where id = p_round_id for update;
if not found or v_round.status <> 'open' then raise exception 'round is not open'; end if;
select * into v_member from public.campaign_members
where campaign_id = v_round.campaign_id and user_id = p_user_id and active;
if not found then raise exception 'active campaign membership not found'; end if;
if not exists (
select 1 from public.characters
where id = p_character_id and campaign_id = v_round.campaign_id
and user_id = p_user_id and controller = 'human'
) then raise exception 'controlled character not found'; end if;
insert into public.player_intents(round_id, member_id, character_id, action, ready)
values (p_round_id, v_member.id, p_character_id, btrim(p_action), coalesce(p_ready, false))
on conflict (round_id, member_id) do update
set character_id = excluded.character_id, action = excluded.action,
ready = excluded.ready, updated_at = now()
returning id into v_intent_id;
if coalesce(p_ready, false) and not exists (
select 1
from public.campaign_members member
join public.characters character
on character.campaign_id = member.campaign_id
and character.user_id = member.user_id
and character.controller = 'human'::public.character_controller
where member.campaign_id = v_round.campaign_id
and member.active
and not exists (
select 1 from public.player_intents intent
where intent.round_id = p_round_id and intent.member_id = member.id and intent.ready
)
) then
v_job_id := public.enqueue_round_resolution(p_round_id, null);
end if;
return jsonb_build_object('intentId', v_intent_id, 'jobId', v_job_id);
end;
$$;
-- Repair campaigns created before starter parties were automatic.
insert into public.characters(
campaign_id, user_id, name, concept, controller, abilities, hp, max_hp,
defense, proficiency, inventory, statuses, persona
)
select
campaign.id,
campaign.owner_id,
left(coalesce(nullif(btrim(profile.display_name), ''), 'Wayfinder'), 80),
left('An adaptable protagonist ready to confront the opening mystery of ' || world.title || '.', 600),
'human'::public.character_controller,
'{"str":10,"dex":12,"con":12,"int":11,"wis":13,"cha":10}'::jsonb,
12,
12,
12,
2,
'["Field kit","Personal keepsake"]'::jsonb,
'[]'::jsonb,
jsonb_build_object(
'voice', 'Defined by the player.',
'motivation', 'Discover what the opening scene is hiding.',
'flaw', 'Still learning what this world demands.',
'bond', 'Protect the party through the first danger.'
)
from public.campaigns campaign
join public.worlds world on world.id = campaign.world_id
left join public.profiles profile on profile.id = campaign.owner_id
where campaign.status = 'active'
and not exists (
select 1 from public.characters character
where character.campaign_id = campaign.id
and character.user_id = campaign.owner_id
);
create or replace function public.dng_schema_version()
returns integer language sql stable security definer set search_path = '' as $$
select 10;
$$;
revoke all on function public.dng_schema_version() from public, anon, authenticated;
grant execute on function public.dng_schema_version() to service_role;
notify pgrst, 'reload schema';

View File

@@ -0,0 +1,287 @@
-- Persist the AI companions created with each universe and use that party when
-- a campaign starts. This replaces the temporary hard-coded Echo companion.
alter table public.worlds
add column if not exists starter_companions jsonb not null default '[]'::jsonb;
alter table public.worlds
drop constraint if exists worlds_starter_companions_array;
alter table public.worlds
add constraint worlds_starter_companions_array check (
jsonb_typeof(starter_companions) = 'array'
and jsonb_array_length(starter_companions) <= 3
);
-- Ready drafts created before companions were part of WorldStarter inherit
-- three universe-specific people that the coauthor already generated.
update public.coauthor_sessions session
set generated_world = jsonb_set(
session.generated_world,
'{companions}',
coalesce((
select jsonb_agg(
jsonb_build_object(
'name', npc.value->>'name',
'concept', left(npc.value->>'summary', 600),
'abilities', case npc.position
when 1 then '{"str":10,"dex":14,"con":11,"int":13,"wis":12,"cha":10}'::jsonb
when 2 then '{"str":13,"dex":10,"con":14,"int":10,"wis":12,"cha":11}'::jsonb
else '{"str":9,"dex":12,"con":11,"int":14,"wis":13,"cha":12}'::jsonb
end,
'hp', 10 + npc.position,
'maxHp', 10 + npc.position,
'defense', 11 + npc.position,
'proficiency', 2,
'inventory', jsonb_build_array('Universe field kit', 'Travel supplies'),
'persona', jsonb_build_object(
'voice', left(npc.value->>'summary', 240),
'motivation', left('Pursue the goal behind: ' || (npc.value->>'summary'), 300),
'flaw', 'Their personal agenda can complicate the party''s plans.',
'bond', left('They belong to ' || (session.generated_world->>'title') || ' and choose to stand with the party.', 300)
)
) order by npc.position
)
from jsonb_array_elements(coalesce(session.generated_world->'npcs', '[]'::jsonb))
with ordinality as npc(value, position)
where npc.position <= 3
), '[]'::jsonb),
true
),
updated_at = now()
where session.generated_world is not null
and jsonb_typeof(session.generated_world->'npcs') = 'array'
and coalesce(jsonb_array_length(session.generated_world->'companions'), 0) = 0;
-- Confirmed universes do not retain the original generation JSON. Build their
-- starter companions from the AI-created NPC entities already stored for them.
update public.worlds world
set starter_companions = coalesce((
select jsonb_agg(
jsonb_build_object(
'name', npc.name,
'concept', left(npc.summary, 600),
'abilities', case npc.position
when 1 then '{"str":10,"dex":14,"con":11,"int":13,"wis":12,"cha":10}'::jsonb
when 2 then '{"str":13,"dex":10,"con":14,"int":10,"wis":12,"cha":11}'::jsonb
else '{"str":9,"dex":12,"con":11,"int":14,"wis":13,"cha":12}'::jsonb
end,
'hp', 10 + npc.position,
'maxHp', 10 + npc.position,
'defense', 11 + npc.position,
'proficiency', 2,
'inventory', jsonb_build_array('Universe field kit', 'Travel supplies'),
'persona', jsonb_build_object(
'voice', left(npc.summary, 240),
'motivation', left('Pursue the goal behind: ' || npc.summary, 300),
'flaw', 'Their personal agenda can complicate the party''s plans.',
'bond', left('They belong to ' || world.title || ' and choose to stand with the party.', 300)
)
) order by npc.position
)
from (
select entity.name, entity.summary,
(row_number() over (order by entity.created_at, entity.id))::integer as position
from public.world_entities entity
where entity.world_id = world.id and entity.kind = 'npc'
order by entity.created_at, entity.id
limit 3
) npc
), '[]'::jsonb)
where jsonb_array_length(world.starter_companions) = 0;
create or replace function public.stage_two_confirm_world(
p_session_id uuid,
p_owner_id uuid
) returns uuid language plpgsql security definer set search_path = '' as $$
declare
v_session public.coauthor_sessions%rowtype;
v_world jsonb;
v_world_id uuid;
v_entity jsonb;
begin
select * into v_session from public.coauthor_sessions
where id = p_session_id and owner_id = p_owner_id for update;
if not found then raise exception 'coauthor session not found'; end if;
if v_session.status = 'confirmed' and v_session.confirmed_world_id is not null then
return v_session.confirmed_world_id;
end if;
if v_session.status <> 'ready' or v_session.generated_world is null then
raise exception 'coauthor session is not ready to confirm';
end if;
v_world := v_session.generated_world;
if coalesce(v_world->>'title', '') = ''
or coalesce(v_world->>'openingScene', '') = ''
or jsonb_typeof(v_world->'companions') <> 'array'
or jsonb_array_length(v_world->'companions') <> 3 then
raise exception 'generated world is incomplete';
end if;
insert into public.worlds(
owner_id, title, genre, tone, premise, content_boundaries,
hidden_threat, hook, opening_scene, starter_companions, status
) values (
p_owner_id, v_world->>'title', v_world->>'genre', v_world->>'tone', v_world->>'premise',
coalesce(v_world->'contentBoundaries', '[]'::jsonb), v_world->>'hiddenThreat',
v_world->>'hook', v_world->>'openingScene', v_world->'companions', 'confirmed'
) returning id into v_world_id;
v_entity := v_world->'startingLocation';
insert into public.world_entities(world_id, kind, name, summary, tags, secrets)
values (v_world_id, 'location', v_entity->>'name', v_entity->>'summary',
array(select jsonb_array_elements_text(coalesce(v_entity->'tags', '[]'::jsonb))),
coalesce(v_entity->'secrets', '[]'::jsonb));
for v_entity in select * from jsonb_array_elements(v_world->'npcs') loop
insert into public.world_entities(world_id, kind, name, summary, tags, secrets)
values (v_world_id, 'npc', v_entity->>'name', v_entity->>'summary',
array(select jsonb_array_elements_text(coalesce(v_entity->'tags', '[]'::jsonb))),
coalesce(v_entity->'secrets', '[]'::jsonb));
end loop;
for v_entity in select * from jsonb_array_elements(v_world->'factions') loop
insert into public.world_entities(world_id, kind, name, summary, tags, secrets)
values (v_world_id, 'faction', v_entity->>'name', v_entity->>'summary',
array(select jsonb_array_elements_text(coalesce(v_entity->'tags', '[]'::jsonb))),
coalesce(v_entity->'secrets', '[]'::jsonb));
end loop;
insert into public.world_entities(world_id, kind, name, summary, tags, secrets)
values (v_world_id, 'quest', 'Opening Hook', v_world->>'hook', array['opening'], '[]'::jsonb);
update public.coauthor_sessions
set status = 'confirmed', confirmed_world_id = v_world_id, updated_at = now()
where id = p_session_id;
return v_world_id;
end;
$$;
create or replace function public.stage_two_create_campaign(
p_world_id uuid,
p_owner_id uuid,
p_title text
) returns uuid language plpgsql security definer set search_path = '' as $$
declare
v_world public.worlds%rowtype;
v_campaign_id uuid;
v_owner_name text;
v_companion jsonb;
begin
if p_title is null or char_length(btrim(p_title)) not between 3 and 100 then
raise exception 'campaign title must be between 3 and 100 characters';
end if;
select * into v_world from public.worlds
where id = p_world_id and owner_id = p_owner_id and status = 'confirmed' for share;
if not found then raise exception 'confirmed world not found'; end if;
if jsonb_typeof(v_world.starter_companions) <> 'array'
or jsonb_array_length(v_world.starter_companions) = 0 then
raise exception 'confirmed world has no AI companions';
end if;
select nullif(btrim(display_name), '') into v_owner_name
from public.profiles where id = p_owner_id;
v_owner_name := left(coalesce(v_owner_name, 'Wayfinder'), 80);
insert into public.campaigns(world_id, owner_id, title, current_scene, next_prompt, status)
values (p_world_id, p_owner_id, btrim(p_title), coalesce(v_world.opening_scene, v_world.premise), 'What do you do?', 'active')
returning id into v_campaign_id;
insert into public.campaign_members(campaign_id, user_id, role)
values (v_campaign_id, p_owner_id, 'owner');
insert into public.characters(
campaign_id, user_id, name, concept, controller, abilities, hp, max_hp,
defense, proficiency, inventory, statuses, persona
) values (
v_campaign_id,
p_owner_id,
v_owner_name,
left('An adaptable protagonist ready to confront the opening mystery of ' || v_world.title || '.', 600),
'human'::public.character_controller,
'{"str":10,"dex":12,"con":12,"int":11,"wis":13,"cha":10}'::jsonb,
12,
12,
12,
2,
'["Field kit","Personal keepsake"]'::jsonb,
'[]'::jsonb,
jsonb_build_object(
'voice', 'Defined by the player.',
'motivation', 'Discover what the opening scene is hiding.',
'flaw', 'Still learning what this world demands.',
'bond', 'Protect the party through the first danger.'
)
);
for v_companion in select * from jsonb_array_elements(v_world.starter_companions) loop
insert into public.characters(
campaign_id, user_id, name, concept, controller, abilities, hp, max_hp,
defense, proficiency, inventory, statuses, persona
) values (
v_campaign_id,
null,
v_companion->>'name',
v_companion->>'concept',
'ai'::public.character_controller,
v_companion->'abilities',
(v_companion->>'hp')::integer,
(v_companion->>'maxHp')::integer,
(v_companion->>'defense')::integer,
(v_companion->>'proficiency')::integer,
v_companion->'inventory',
'[]'::jsonb,
v_companion->'persona'
);
end loop;
insert into public.rounds(campaign_id, number) values (v_campaign_id, 1);
return v_campaign_id;
end;
$$;
-- Remove only the exact temporary Echo inserted by schema v10, preserving any
-- independently authored character that happens to share the name.
delete from public.characters character
where character.user_id is null
and character.controller = 'ai'::public.character_controller
and character.name = 'Echo'
and character.inventory = '["Survey kit","Emergency supplies"]'::jsonb
and character.persona->>'voice' = 'Observant, concise, and quietly curious.'
and character.persona->>'motivation' = 'Help the party understand this unfamiliar world.'
and character.concept like 'A persistent AI companion shaped by the %';
-- Existing active campaigns receive the companion roster belonging to their
-- universe. Name matching keeps this migration idempotent around manual heroes.
insert into public.characters(
campaign_id, user_id, name, concept, controller, abilities, hp, max_hp,
defense, proficiency, inventory, statuses, persona
)
select
campaign.id,
null,
companion.value->>'name',
companion.value->>'concept',
'ai'::public.character_controller,
companion.value->'abilities',
(companion.value->>'hp')::integer,
(companion.value->>'maxHp')::integer,
(companion.value->>'defense')::integer,
(companion.value->>'proficiency')::integer,
companion.value->'inventory',
'[]'::jsonb,
companion.value->'persona'
from public.campaigns campaign
join public.worlds world on world.id = campaign.world_id
cross join lateral jsonb_array_elements(world.starter_companions) companion(value)
where campaign.status = 'active'
and not exists (
select 1 from public.characters character
where character.campaign_id = campaign.id
and character.controller = 'ai'::public.character_controller
and lower(character.name) = lower(companion.value->>'name')
);
create or replace function public.dng_schema_version()
returns integer language sql stable security definer set search_path = '' as $$
select 11;
$$;
revoke all on function public.dng_schema_version() from public, anon, authenticated;
grant execute on function public.dng_schema_version() to service_role;
notify pgrst, 'reload schema';