File size: 9,090 Bytes
ee34154
cf05d66
135e328
cf05d66
ee34154
cf05d66
ee34154
 
626842d
ee34154
135e328
626842d
135e328
ee34154
 
 
 
 
 
 
 
 
135e328
626842d
135e328
ee34154
 
 
 
 
 
626842d
ee34154
 
 
 
 
 
 
 
 
135e328
 
 
 
 
 
 
 
ee34154
 
 
 
 
135e328
cf05d66
ee34154
 
 
 
 
 
 
 
 
 
 
 
 
cf05d66
 
ee34154
 
 
 
 
 
 
 
626842d
ee34154
 
135e328
626842d
 
 
ee34154
 
 
 
 
135e328
 
ee34154
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# cuddly happy game platform β€” agent/API guide

This Space is a Flask social-deduction lobby and playable room prototype. It is **not** a stock-analysis API. The product name and parlor identity are intentional. The separate `/inference` page is a retained smoke-test utility, not the main product contract.

## What works

- `/` and `/lobby` render the shared matchmaking lobby; opening the site does not silently create or join a test room.
- Visitors can join/leave a persistent matchmaking queue, vote in the repeating Parlor Poll, and use shared lobby chat.
- A queued guest becomes match-ready after a lobby message meets `MATCHMAKING_MIN_WORDS` (default 3); shorter messages remain public but do not satisfy participation. This initial word-count rule is the extension point for later configurable word/phrase triggers.
- Five queued human guests form a room by default. A matched user's lobby state contains a room URL until the room is opened.
- The default game is **The Midnight Parlor**: private roles, one private Investigator clue per round, discussion, sealed accusations, reveal, and repeat rounds. The game UI is `static/js/gameplay.js`; engine is `games/examples/parlor_mystery.py`.
- First-visit questions are personal but skippable. All submitted answers are stored on that guest's profile and in SQLite telemetry in the same transaction; answer text is not sent to the stdout event logger, analyzed, or used in role assignment in this build. Skipping remaining prompts retains answers already entered. `DELETE /api/onboarding` removes both profile answers and their answer-bearing telemetry records.
- `RoleAssignmentStrategy` accepts optional consented numeric trait signals. No analyzer or model currently feeds those signals. Do not infer traits from chat or onboarding responses in this build.
- Lobby and room chat use authenticated HTTP writes, WebSockets for live delivery, and polling fallback.

## Browser/session API

Start with `GET /` and retain the session cookie. A guest session is created automatically for a browser. JSON APIs use that cookie; do not send user IDs in request bodies to impersonate another user.

### Lobby and matchmaking

- `GET /api/lobby/state` β€” queue count, this session's queue/match state, current minigame round, and the latest lobby messages.
- `GET /api/onboarding` β€” this session's first-visit answer state.
- `POST /api/onboarding` with `{"answers":{"assumption":"..."},"future_use":false}` saves answers; `{"skip":true}` skips remaining prompts while preserving any supplied answers. An empty answer object skips all prompts.
- `DELETE /api/onboarding` erases saved answers without reopening the first-visit flow.
- `POST /api/matchmaking/queue` β€” join queue (idempotent). Returns `{ "ok": true, "data": { "queued": true, "queue_count": 1, ... } }`; when matched, `data.match` includes `room_id` and `url`.
- `DELETE /api/matchmaking/queue` β€” leave the active queue.
- `GET /api/lobby/minigame/current` β€” current prompt and choices.
- `POST /api/lobby/minigame/{round_id}/vote` with `{"choice":"..."}` β€” submit/change this session's vote before the round closes.
- `GET /api/lobby/chat?after={message_id}` β€” read messages after a cursor.
- `POST /api/lobby/chat` with `{"msg":"..."}` β€” send a lobby message (maximum 500 characters).
- The response's `data.message.matchmaking` reports whether this message met the word threshold and whether this queue entry is now participated/ready.

Most responses use `{ "ok": true, "data": ... }`; errors use a non-2xx HTTP status and `{ "ok": false, "error": "..." }`.

### Rooms

- `GET /join/{room_id}` joins an available room and redirects to its page.
- `GET /room/{room_id}` renders the room.
- `POST /api/room/{room_id}/chat` with `{"msg":"..."}` sends room chat.
- `GET /api/room/{room_id}/messages?after={message_id}` polls room chat.
- `GET /api/room/{room_id}/game` β€” member-only state, including that member's role/clues.
- `POST /api/room/{room_id}/game/action` supports `begin_vote`, `investigate`, `vote`, and `continue`; payloads are action-specific.

### Game and role configuration

`GAME_SETTINGS_JSON` is backend-only JSON copied into new rooms. `role_definitions` can override the default role catalog. Each role has `role_id`, `name`, `team`, `description`, `instructions`, `count` (integer or `"remaining"`), optional `abilities`, and optional `affinities` (trait-to-weight map). The default game uses one `shadow` role, one `parlor` Investigator with the `investigate` ability, and `parlor` Guests. The game engine uses the `shadow` team for its hidden-side win condition; roles with `investigate` receive the private clue action.

Role assignment falls back to a secure random shuffle (tests can inject a seed). `RoleAssignmentStrategy` can consume backend-supplied `player_signals` shaped like `{ "user_id": { "consented": true, "scores": { "analytical": 0.8 } } }`; it does not read onboarding answers/chat or call a language model. Only normalized numeric features are accepted by this hook. No model-generated player text is implemented in this scaffold.

### WebSockets

- `ws(s)://{host}/ws/lobby` is server-push only. Events include `queue.updated`, `match.created`, `minigame.round_started`, `minigame.vote_count`, `minigame.round_ended`, and `chat.message`; each packet has `type` and `data`.
- `ws(s)://{host}/ws/room/{room_id}` receives room chat and system events.
- Room sockets send only a content-free `game.updated` signal after a game action; clients refetch member-specific state over HTTP.

Reconnect by fetching `/api/lobby/state` or the relevant room messages endpoint. HTTP remains authoritative if a WebSocket is unavailable.

## Chat-generation service interface

Normal guests cannot trigger arbitrary model calls. An operator/service can queue a single generation job by setting `LOBBY_CHAT_GENERATION_TOKEN` as a Space secret and sending:

```http
POST /internal/lobby/chat/generation
Authorization: Bearer $LOBBY_CHAT_GENERATION_TOKEN
Idempotency-Key: unique-request-id
Content-Type: application/json

{"context_key":"lobby"}
```

The endpoint returns `202` with `{ "ok": true, "job_id": "...", "status": "queued" }`. Poll `GET /internal/lobby/chat/generation/{job_id}` with the same bearer authorization. Status is `queued`, `running`, `complete`, or `failed`. A completed job posts one message into lobby chat. Repeated idempotency keys return the existing job.

Only the `lobby`, `queue`, and `minigame` context keys are accepted; there can be at most three pending jobs, and new jobs are rate limited to one per ten seconds.

Without a provider, generation uses a short deterministic scripted line. Optional OpenAI-compatible chat completions use server-only `LOBBY_CHAT_API_URL`, `LOBBY_CHAT_MODEL`, and optional `LOBBY_CHAT_API_KEY`. Provider credentials are never accepted from the request body or returned by the status endpoint. This integration is separate from the retained stock-analysis helper modules.

## Persistence, configuration, and logs

- SQLite defaults to `/data/app.db` on the HF persistent volume. If the file is absent, startup creates a new empty database; it never silently imports `instance/app.db`. `DATABASE_URL` overrides the URI; `DATA_DIR` can override the default volume directory. Existing SQLite files receive an integrity preflight before schema creation or migrations; corrupt files fail with a diagnostic and are not repaired automatically.
- Queue state, minigame rounds/votes, lobby messages, generation jobs, rooms, and telemetry are persisted in SQLite.
- `MATCHMAKING_MIN_PLAYERS` defaults to `5`; `LOBBY_ROUND_SECONDS` defaults to `35`.
- `DEFAULT_GAME_TYPE` defaults to `parlor_mystery`; `GAME_SETTINGS_JSON` can supply backend-only role definitions. Role configuration supports role counts, teams, abilities, and signal affinities.
- `TEST_MODE` defaults to true for this test Space. The simulator reuses no more than 10 stable identities (`TestBot0`–`TestBot9`); older rows outside that pool are ignored and are not deleted. `TEST_MODE=false` disables simulation.
- Simulated lobby and room chat is limited to one message per active conversation per configured interval (default 60 seconds; minimum 30 seconds).
- Telemetry is batched (maximum 100 events/request); one concise summary is logged per batch. Successful polling GETs are not individually logged. Credentials and common token shapes are redacted.
- `GET /health` provides a basic application status.

## Boundaries

- Do not represent simulated participants as real people or make production matches from test users.
- Never expose `role_by_player` in public game state; only return the requesting member's private role.
- Do not analyze player text or use onboarding/chat content for role assignment in this build. The hook accepts only explicit normalized numeric signals.
- Never include tokens, authorization headers, cookies, or provider secrets in messages, query strings, or logs.
- This API is a prototype; it does not promise uptime, game outcomes, or any financial/stock-analysis result.