MiniGames Platform Roadmap¶
Status: Active suite-wide sequencing and delivery record.
Audience: Product, engineering, and operations leads deciding what is next or what has landed.
Documentation snapshot: Branch jm/string-repetition at a12ff3b. This branch includes the
compact lexical identity, metadata, Reverse Cross puzzle-schema v2, and feature-gated play-schema
v2 work described in Data Layout and Persistence. That statement
does not imply merge to main or deployment to production.
Turn the single-player, always-regenerated LetterGolf PoC into a persistent, multi-game platform: daily puzzles, user stats and streaks, friend groups, moderated word content, and difficulty/par tuning.
Each phase is a branch, independently mergeable to main. Update the status boxes as work
lands.
| Phase | Branch | Status |
|---|---|---|
| 0. Secrets, CORS, repo hygiene | chore/security-baseline |
Merged to main |
| 1. Linux backend + modernization | chore/linux-and-modernize |
Merged to main |
| 2. Terraform + managed identity | infra/backend-and-cosmos |
Merged to main |
| Fix: Letter Golf generation (Phase 3 prerequisite) | fix/lettergolf-generation |
Merged to main |
| 3a. Daily puzzles (MVP) | feat/daily-puzzles |
Merged to main |
| 4. Player stats and streaks | feat/player-stats |
Merged to main |
| 5. Groups and social | feat/groups-social |
Merged to main (backend + feat/groups-social-ui frontend) |
| Cross-cutting: observability | feat/obs-start |
Merged to main; Tier 1 deployed to prod and verified |
| Advertising: AdSense compliance prep | feat/adsense-release-prep |
Account review script prepared; deployment and resubmission pending |
| Brand and navigation rollout | feat/prep-adsense |
Merged to main |
| Reverse Cross generation (Reverse Cross phases 1-3D) | Multiple branches | Implementation complete; production validation and rollout pending |
| Stats Sharing persistent implementation (backend + frontend hookup) | feat/stats-sharing-2 |
Complete locally (2026-09-12); not merged or deployed |
| Account deletion (GDPR/EEA erasure workflow) | Current branch | Implemented locally; not pushed/deployed; final validation pending |
| Compact identities and Reverse Cross persistence v2 | jm/string-repetition |
Implemented and validated on branch; not yet merged to main |
| 6. Content governance | feat/content-governance |
Not started |
| 7. Difficulty, par, courses | feat/courses-and-difficulty |
Not started |
| 8+. Social & platform backlog (poke, push notifications, PWA, real identity, i18n) | TBD | Not started — not yet sequenced |
| Cross-cutting: testing | Multiple branches | Frontend Vitest foundation and broad regression coverage in place |
Note: in practice Phase 2's Terraform + Cosmos managed identity work landed as commits on
chore/linux-and-modernize rather than its own branch (see 303cd1f, 92715ed). Treat the
branch column as intent, not a strict boundary already enforced in history.
Locked decisions¶
- Identity: anonymous-first. Keep the
userIdcookie fromsrc/middleware.tsas durable device identity. Model everything on a realuserIdstring so real auth can be added later and identities merged. - Cosmos: one shared database, few multi-game containers, discriminated by
gameType, with shared autoscale throughput at the database level. - Daily puzzles: pre-generated by a scheduled Container Apps Job. Keep the lazy on-first-request path viable as a fallback by making generation idempotent.
- Infra: bring Cosmos and the backend API into Terraform; replace the account key with managed identity.
- Backend moves to Linux containers early, for cost, alongside upgrading .NET, Node, Next.js, TypeScript, and base images to latest stable.
- APIM is retired. Container App ingress becomes the public endpoint.
- Cutover is parallel-run, not in-place replace.
Phase 0 — Secrets, CORS, and repo hygiene¶
Branch: chore/security-baseline
Secret exposure: assessed, not as bad as feared¶
The hardcoded Cosmos connection string in Program.cs was never committed. It existed
only in the working tree, applied from a stash. Verified with git log --all -S. The one
historical AccountKey match is an ARM listKeys() template expression in a generated
service-dependency file, which is a deploy-time function rather than a literal.
No history rewrite is required. Rotating the key remains cheap insurance if it was ever shared outside git, but it is not an emergency.
Work items¶
- Remove the hardcoded connection string; bind
CosmosOptionsfrom configuration. Endpoint lives inappsettings.json(not a secret); the key comes from user secrets locally andCosmos__AccountKeyin hosted environments. Startup fails fast with an actionable message when either is missing. - CORS driven by configuration. One policy built from
Cors:AllowedOriginswithAllowCredentials()andSetPreflightMaxAge.AllowAnyOriginis gone. In Development only, any loopback origin is allowed viaSetIsOriginAllowedso contributors can use whatever port is free. Outside Development, an empty origin list allows nothing — failing closed is deliberate. - Move
UseCorsbefore endpoint mapping; it previously ran afterMapControllers. - Remove the no-op
UseAuthorization()— there is no authentication scheme, so it only implied protection that did not exist. - Frontend
API_BASE_URLreadsNEXT_PUBLIC_API_BASE_URLwith the current value as fallback, so contributors repoint the backend from a gitignored.env.localinstead of editing a tracked file. - Fix the pre-commit hook, which ran
dotnet formatagainst the whole solution and so let pre-existing formatting debt block every commit. Now scoped to staged files. - Add secret scanning to CI (gitleaks, or GitHub secret scanning with push protection).
Why CORS was wrong before¶
The commented-out production policy and blanket AllowAnyOrigin existed so a colleague could
iterate locally. That is a configuration problem being solved in code. Origins are now
configuration: a contributor sets Cors__AllowedOrigins__2=http://his-ip:3000 in his
environment, and no tracked file changes.
This also matters later: once identity cookies are sent cross-origin in Phase 4,
AllowAnyOrigin combined with AllowCredentials is invalid per the CORS spec, so enumerated
origins become mandatory regardless.
Deferred decision: same-origin proxy¶
Adding an async rewrites() to next.config.ts mapping /api/:path* to the backend would
make the browser talk only to its own origin, eliminating CORS entirely, and would let the
Phase 4 cookie use SameSite=Lax.
The tradeoff is an extra hop in production and a frontend container that can no longer scale to zero while proxying. Given the cost goal, this is not being done yet.
Contributor setup ladder¶
| Scenario | What is required |
|---|---|
| Frontend only | .env.local plus an origin in the dev API's allowlist. No Azure account. |
| Runs backend locally | Cosmos emulator, which uses a well-known key. No Azure credentials. |
| Backend against real Azure data | One-time az login plus a data-plane role assignment. |
Only the last row involves credentials.
Known debt, deliberately not fixed here¶
CommonWordsSource.cs and several other files have CRLF committed while .editorconfig
requires LF. Normalizing repo-wide would bury this branch's security review under a
whitespace diff, so it belongs on its own chore/line-endings branch. The hook fix stops it
blocking commits in the meantime.
.gitattributes also carries stale Git LFS rules referencing an unrelated project
(src/IdRamp.Passport.Mobile.*). Harmless, but worth deleting during that same cleanup.
Phase 1 — Linux backend and platform modernization¶
Branch: chore/linux-and-modernize
This is a full replatform, not a Docker target change. The backend currently runs on a
Windows App Service — the publish profile targets RuntimeIdentifier=win-x86,
SelfContained=true, WebPublishMethod=ZipDeploy. The Dockerfile is already Linux-correct;
the gap is that the backend has no infrastructure-as-code at all.
The publish profile also wires an Azure API Management instance (MiniGamesBackEndapi,
UpdateApiOnPublish=true), which is absent from tf/ — unmanaged, exactly like Cosmos was.
Decision: retire it.
Cutover runbook (parallel-run)¶
Every delete and DNS change below requires explicit approval before execution.
- Inventory, read-only. Confirm no external consumer holds an APIM subscription key or
depends on APIM-only policies; if one does, revisit the retire decision.
Answered 2026-07-27:
api.verbolus.comis a CNAME straight to the legacy App Service (minigamesbackend20250302132848-b4h7esdjarenf0ca.canadacentral-01.azurewebsites.net), confirmed viaResolve-DnsName. It does not route through APIM. APIM's own backend ("Web service URL") also targets that same App Service, confirming APIM is fully disconnected from the Container Apps already in production — safe to retire per plan. The App Service is currently stopped, soapi.verbolus.comreturns a fast 403 (Site Disabled) rather than hanging; it is not being used by production traffic today (the frontend callsminigame-api's Container App FQDN directly viaNEXT_PUBLIC_API_BASE_URL). The App Insights componentMiniGamesBackEnd20250302132848attached to that App Service was also confirmed safe to delete (Portal-auto-created,Redfield/App-Service-only instrumentation, shared Log Analytics workspace, zero alert rules) whenever step 4 runs. - Stand up the new path with zero production impact: deploy the Phase 2
minigame-apiContainer App without binding the custom domain. - Smoke-test in parallel against the default
*.azurecontainerapps.ioFQDN, diffing/health/ready,/v1/letter-golf, and/v1/verify-wordagainst the live App Service. - Cut the domain over. Add
api.verbolus.comto the Container App environment — this needs a validation TXT record and a managed certificate, so provision it ahead of the window, as issuance is not instant. Then flip DNS and confirm propagation. - Retire, only after a bake period confirms zero traffic to the old host: delete APIM,
the App Service and its plan (confirm the plan is not shared), the
.pubxmlfiles, and theApiResourceId/UpdateApiOnPublishwiring. Done 2026-07-28: APIM instance, the Windows App Service, and its plan were deleted in the Portal after a one-day bake period confirmed zero traffic to the old host. The tracked.pubxml,apis1.arm.json/profile.arm.jsonservice-dependency files, andserviceDependencies.jsonwere removed from source alongside (seeinfra/backend-and-cosmos).
Other work¶
- Harden the Dockerfile: pinned digest, non-root, expose only 8080, TLS terminating at
ingress, and a
HEALTHCHECK. Keep globalization enabled — this is a word game. - Add
/health/liveand/health/ready, the latter including a Cosmos ping. - Upgrades, verifying latest stable at execution time rather than assuming: .NET 9 to
.NET 10 LTS; Cosmos SDK off preview onto stable; Node, Next.js, React, TypeScript, Tailwind,
and ESLint to latest stable via
npx @next/codemod@latest upgrade. - Remove
Microsoft.EntityFrameworkCore(unused) andSystem.Linq4.3.0 (a .NET Framework-era package with no purpose on modern .NET). - Enable
TreatWarningsAsErrorsand analyzers, then fix the fallout. The build currently emits nullability warnings inCommonWordsSource,ServiceProviderExtensions, andTestLetterGolfGenerator.
Phase 2 — Terraform and managed identity¶
Branch: infra/backend-and-cosmos. Depends on Phase 1.
- New
tf/backend/module mirroringtf/frontend/conventions:minigame-apiContainer App, user-assigned identity withAcrPull, probes wired to the health endpoints. Prefermin_replicas = 0plus a Container Apps Job for scheduled work, rather than an always-warm replica running a change-feed processor. - New
tf/data/module: import the existingminigames-dbaccount rather than recreating it. Oneminigamesdatabase with shared autoscale starting at 1000 RU/s max,local_authentication_disabled = true, andminimal_tls_version = Tls12. - Done 2026-07-28: both custom domains (
verbolus.com,api.verbolus.com) brought under Terraform asazurerm_container_app_custom_domain+azurerm_container_app_environment_managed_certificate, imported rather than recreated since both were already bound live via the Portal during the Phase 1 cutover.certificate_binding_type/container_app_environment_certificate_idare inignore_changesper the provider's documented managed-certificate pattern, since Azure mutates them asynchronously outside Terraform (auto-renewal). Without this,planwould show perpetual drift or attempt to recreate the binding on every apply. - Done 2026-07-28:
disable_local_authflipped totrue(default) after confirming managed-identity auth had run stably in production for a full day post-cutover — see the 2026-07-27 session log entry below. The Cosmos account key is no longer valid for any client; every path (local dev, CI, Container Apps) must authenticate viaDefaultAzureCredential. - Done 2026-07-28:
azurermprovider bumped from the pinned4.28.0to4.81.0— the custom-domain resources above don't exist in4.28.0. Applied and verified working (see session log). Pending: the plan/apply run emitted a deprecation warning thatlocal_authentication_disabledonazurerm_cosmosdb_accountis renamed tolocal_authentication_enabledand will be removed in providerv5.0. Not urgent —v5.0is a breaking major version per its own upgrade guide, so this is deliberately deferred to its own reviewed branch rather than folded into this one, but don't let it linger indefinitely.
Cosmos has two independent permission systems¶
Conflating them is the usual failure mode:
- Control plane (Azure RBAC,
azurerm_role_assignment): create databases and containers, read keys. Used by Terraform only. - Data plane (Cosmos-specific,
azurerm_cosmosdb_sql_role_assignment): CRUD on documents. Used by the API only. Built-in...0002is Data Contributor, which deliberately cannot create containers — keeping structure under Terraform's control.
Subscription Owner grants zero data-plane access, and these assignments do not appear in the portal's IAM blade.
Where the credential comes from¶
CosmosClient(endpoint, new DefaultAzureCredential()) resolves differently per environment:
managed identity in Container Apps, the developer's own Entra user locally, and OIDC
federation in CI. No secret exists on disk anywhere.
Gotchas, in priority order:
AZURE_CLIENT_IDis mandatory for a user-assigned identity. Without it the credential probes for a system-assigned identity and fails with a misleading 401. Most common failure.local_authentication_disabled = trueis what makes "key gone" enforceable rather than aspirational — otherwise a rotated key still works and a connection string quietly returns.- The Cosmos emulator does not support Entra auth, so the client factory needs a
UseEmulatorswitch. Phase 3 integration tests depend on it. - Role assignments propagate with a delay of minutes. An apply immediately followed by a deploy can 403 spuriously. Not a real bug.
CI runs fmt, validate, and plan on PRs with the plan as an artifact. Never
auto-apply. Images push to ACR via workload identity federation, not stored credentials.
Phase 3 — Data model and real daily puzzles¶
Branch: feat/daily-puzzles. Depends on Phase 2.
Containers (database minigames, shared autoscale)¶
| Container | Partition key | Purpose |
|---|---|---|
puzzles |
/puzzleKey |
Every game's puzzles, all scopes |
players |
/userId |
Profile, settings, plays, stats, streaks, memberships |
groups |
/groupId |
Group metadata, members, leaderboards |
content |
/contentKey |
Deny and allow lists, curated word lists, par tables |
lookups |
/lookupKey |
Join code to group id, name uniqueness. Point-read only |
puzzleKey is {gameType}|{scope}|{yyyy-MM-dd}, for example lettergolf|global|2026-07-26
or lettergolf|group:{groupId}|2026-07-26. The daily fetch becomes a point read of roughly
1 RU instead of the current cross-partition query. Puzzle solution stays server-side and
is never serialized into the client DTO.
players deliberately holds both plays and stats. A submission must atomically write the
play, update aggregates, and advance the streak. Same partition key in the same container
makes that a single TransactionalBatch — no dual-write repair, no change-feed dependency,
and no orphaned stats. It also means no always-warm replica is needed, which keeps
min_replicas = 0 viable.
Bugs to fix¶
- ~~
MVPLetterGolfStoragedaily path builds a LINQ query then iterates into an empty loop body and returns nothing. Replace with a point read.~~ Fixed in Phase 3a:CosmosPuzzleStorereplaces the dummyMVPLetterGolfStorageand implements real point reads viaGetLetterGolfByKeyAsync(), backed by thepuzzlesCosmos container. - ~~
GameIdis hardcoded to1, making it a useless partition key.~~ Fixed in Phase 3a:LetterGolfnow usesPuzzleKey(format:{gameType}|{scope}|{yyyy-MM-dd}) as both the documentidand Cosmos partition key, withGameTypeandScopeas separate fields. - ~~
IsSolvableAsyncaccounting is wrong...~~ Fixed onfix/lettergolf-generation. Generation was rewritten to be solution-first: a real dictionary word is picked first, and the puzzle's letters are set to that word's exact letter-count signature, which guarantees a hole-in-one by construction instead of relying on a solvability check to discover one by luck. The old buggyIsSolvableAsync(distinct-letter presence instead of per-letter counts, one wildcard per missing distinct letter instead of per missing occurrence) is deleted entirely. New types:LetterSignature(the corrected, multiplicity- aware coverage check, see its doc-comment for a full worked example of the old bug),WordSignatureIndex(a count-trie replacing full-dictionary scans — see its doc-comment for why a tree instead of a flat hashmap, and its relationship to subset-sum DP),IGraphemeSegmenter(language-aware letter-unit splitting, only trivial en-US shipped),LetterFrequencyTable(corpus-derived letter rarity), andIWordListProvider(deny/curated list scaffolding, in-memory now,// TODO(Phase 6):seams marking the future Cosmos swap). Also fixed in the same pass: wildcards were hardcoded to3regardless of the caller's requested value — now driven byLetterGolfGenerationOptions.NumWildcards, one of several independently tunable difficulty knobs (see that type) rather than derived from a difficulty tier.LetterGolfgainedHasHoleInOne(real, computed),ParandDifficultyScore(nullable placeholders for Phase 7). - ~~Generation fetches 50,000 words per attempt and scans the full dictionary per solvability
check...~~ Fixed alongside the above.
WordSignatureIndex.FindPlayableWordsreplaces the per-attempt full rescan with a single tree traversal with branch-and-bound pruning. Confirmed in production 2026-07-27 (before this fix): the bounded-retry fix (commit7aef5cf,MAX_GENERATION_ATTEMPTS = 200) stopped the indefinite hang, but each retry still rescanned the word bank, so an unlucky draw could still take 15-30+ seconds end to end. Local smoke test after this fix (2026-07-30): 30 consecutive/v1/letter-golfcalls, first call ~11s (one-time index build over the full aggregated dictionary, cached for the process lifetime), every call after that 160-540ms,HasHoleInOne: trueon all 30. The frontend'sapiFetchtimeout (frontend/minigames/src/app/api.ts, currently 30s) can likely come back down now that the root cause is fixed rather than just bounded — not yet done as part of this change, left as a follow-up once this is deployed and observed under real load.
Work completed in Phase 3a¶
- Introduced
Storage/withIPuzzleStore(andCosmosPuzzleStoreimplementation). Narrowed wire contract from Cosmos entity toLetterGolfPuzzleResponseDTO (additive:Id,PuzzleKey,Puzzle,NumWildcards,HasHoleInOne,HasStrictHoleInOne,Par,DifficultyScore— no breaking changes to frontend contract). - Created
puzzlesCosmos container, partition key/puzzleKey, shared autoscale at database level. - Reworked
LetterGolfentity:PuzzleKey,GameType,Scope,PuzzleType(nowenum),PuzzleDateTimereplace the old dummyGameId=1scheme. - Implemented
LetterGolfDailyPuzzleProviderfor idempotent lazy daily-puzzle generation.GetOrCreateDailyAsync()performs a point read bypuzzleKey; on cache miss, generates and persists the puzzle topuzzlescontainer; on subsequent requests that same day, returns the persisted copy. Day boundary is UTC (computed viaDateOnly.FromDateTime(TimeProvider.GetUtcNow().UtcDateTime), invariantyyyy-MM-dd). - Added
GET /v1/letter-golf/dailyendpoint returningLetterGolfPuzzleResponse.
Work completed in Phase 3b — server-authoritative scoring and play persistence (branch feat/daily-puzzles-2)¶
- Server-authoritative play scoring. New
LetterGolfPlayEvaluator(pure, stateless) computes valid state, victory condition, and score from puzzle targets, wildcards, and submitted words. Guarantees that leaderboard/stat builds later can trust submission outcomes rather than client-provided scores. - Play persistence and save/resume. New
playsCosmos container (partition key/playKey, 180-day TTL) persists in-progress and completed Letter Golf plays viaIPlayStore/CosmosPlayStore.PlayEntityholds userId, puzzle key, word list, play status (InProgress or Completed), and — when Completed — the server-computed score, wildcards used, victory flag, and remaining unsatisfied targets. New endpoints: -GET /v1/letter-golf/{puzzleKey}/play— fetch saved play state (restore on page load). -PUT /v1/letter-golf/{puzzleKey}/play— autosave in-progress words (debounced 2s client-side). -POST /v1/letter-golf/{puzzleKey}/submit— validate and score a completed play, return authoritative result. - Per-IP rate limiting. Both play endpoints and
/v1/verify-wordare rate-limited:play-endpointsat 20/minute,verify-wordat 60/minute, keyed by remote IP afterForwardedHeadersOptionswith clearedKnownIPNetworks/KnownProxiesfor Azure Container Apps ingress. Prevents dictionary brute-forcing and play-spam abuse. - User identity via httpOnly cookie only. New
HttpContextExtensions.GetUserId()extension resolves user identity exclusively from theuserIdcookie (not from headers), preventing trivial IDOR by direct API callers. Server-side (Next.js) play fetches forward the realCookieheader, not a custom header, ensuring identity stays cookie-only end-to-end. - Frontend save/restore workflow.
game.tsxrestores saved words on mount, performs debounced (2s) autosave on word changes, and submits on victory (once via ref guard).VictoryOverlayreconciles to server-authoritative score/wildcards oncesubmitPlay()resolves, falling back to client-computed optimistic values while the request is in flight.proxy.tssetsuserIdcookie withdomain: ".verbolus.com"in production for cross-subdomain recognition.
Work completed in Phase 3c — playtesting fixes (branch feat/daily-puzzles-2)¶
- Anti-repeat for daily puzzles.
LetterGolfgained a persisted-onlySeedWordfield (deliberately absent fromLetterGolfPuzzleResponse, so the answer never leaks to the client).IPuzzleStore.GetRecentSeedWordsAsync()queries the last 60 daily seed words (parameterized Cosmos query,SELECT TOP, ordered bypuzzleDateTime DESC); the daily provider passes these to generation asLetterGolfGenerationOptions.ExcludedSeedWordsso a puzzle can't resurface too soon. - Fixed deterministic vowel-first letter reveal. Revealed letters were previously
OrderBy(RarityOf).Take(N)- since letter rarity is a global per-letter statistic (independent of the seed word), this deterministically revealed the same handful of globally-common letters (vowels plus T/N/S/R) for almost every puzzle. Replaced with weighted random sampling without replacement (Efraimidis-Spirakis method,LetterGolfGenerator.WeightedPickRevealedLetters) - still favors common letters (avoids handing the player a rare, distinctive letter like Q or Z) but the exact revealed subset now varies puzzle to puzzle. - Tuned
MinTotalLetterOccurrencesdown from12to11after playtesting felt too restrictive at12. - Confirmed the frontend score remains word-count based. Completed one-word plays score
1; all other plays scorewordCount + wildcardsUsed.LetterGolf.Paritself remains an unpopulated Phase 7 placeholder.
Deferred beyond Phase 3c¶
- Scheduled Container Apps Job for pre-generating daily puzzles. ~~Not built yet~~ Built and shipped on branch
jm/past-future-puzzles(see the 2026-08-17 Session log entry below for details);LetterGolfDailyPreGenerator(14-day rolling horizon, idempotent, safe to re-run) tops off global daily puzzles ahead of time, with a scheduled Container Apps Job calling a new admin endpoint daily at 09:00 UTC. The lazy-on-first-request fallback viaLetterGolfDailyPuzzleProvider.GetOrCreateDailyAsyncremains the permanent backup and continues to work if pre-generation ever falls behind. - Remaining four Cosmos containers (
players,groups,lookups,contentfrom the containers table in Phase 3's data model section) — not created yet. Out of scope until their owning phases (Phase 4 for players, Phase 5 for groups, Phase 6 for content).
Work in progress in Phase 3d — practice puzzles and admin debug endpoints (branch feat/daily-puzzles-3)¶
Practice mode needs a puzzle that isn't tied to a calendar date, and operators need a way to unblock a stuck personal play or check a puzzle's solutions without touching Cosmos directly.
- Practice puzzles now persist with a real
puzzleKey(lettergolf|practice|{shortid}), unlike the old stateless ad-hocGET /v1/letter-golf.POST /v1/letter-golf/practicealways generates and saves a brand-new puzzle, so it interoperates with the existing play autosave/resume/submit endpoints with zero special-casing. Rate-limited under the existingplay-endpointspolicy (20/min/IP). - Two secret-gated, self-service debug endpoints:
POST /v1/letter-golf/{puzzleKey}/play/reset(deletes only the caller's own play, scoped by theiruserIdcookie — never an arbitrary user) andGET /v1/letter-golf/{puzzleKey}/solutions(lists every dictionary word solving a puzzle, via the existingWordSignatureIndex.FindPlayableWords). Both require a constant-time-comparedX-Admin-Keyheader and fail closed (404, not 401/403) on any missing/wrong/unconfigured key, under a new, tighterdebug-endpointsrate limit (10/min/IP). - Terraform for the admin secret and puzzle TTL is written, validated, and applied:
tf/data/cosmos.tfsetsdefault_ttl = -1on thepuzzlescontainer (enables per-item TTL — only documents that set their ownttl, i.e. practice puzzles, expire; daily puzzles never do); a newadmin_debug_keyTerraform variable (sensitive, no default) threads throughtf/main.tfinto a Container Apps nativesecretblock (tf/backend/container_app.tf), exposed to the API asAdmin__DebugKey. Deployment steps taken: 1. Generated a strong random secret viaopenssl rand -base64 32— this is theX-Admin-Keyheader value for the two debug endpoints above. 2. Supplied it via an untrackedtf/local_secrets.auto.tfvarsfile (gitignored via the existing*.tfvarspattern intf/.gitignore) when runningterraform apply. 3. Stored it securely (password manager) — it's needed again for the helper scripts that call these debug endpoints (scripts/letter-golf-admin.env, gitignored). 4. The value now lives in Terraform state (expected for this Container Apps secret pattern); state remains in the existing encrypted, access-restricted remote backend. 5. Rotating the secret later requires a newterraform apply, not just an env var change. - Daily/Practice mode switch in the frontend UI. New
ModeSwitchclient component implements WAI-ARIA Tabs pattern (role=tablist/tab, aria-selected, roving tabindex, arrow/home/end key navigation, aria-controls/id linking to tabpanel). Exported frommode-switch.tsx. Ingame.tsx, addedmodestate ("daily" | "practice", default "daily") andactivePuzzlestate. Switching to Practice fetches a brand-new, persisted practice puzzle (puzzleKey=lettergolf|practice|{shortid}) and clears the board. Switching away from in-progress (unsaved, not-yet-won) Practice puzzles asks for nativewindow.confirm()(no new dependency). Switching back to Daily restores the original SSR-provided daily puzzle and its saved play state (or clears the board if no saved play). AsubmittedPuzzleKeyRef(keyed by puzzleKey, not a single boolean) prevents re-submitting an already-completed puzzle when revisiting after switching modes. In Daily mode only, a live "Resets in HH:MM:SS" countdown to the next Pacific-time midnight is displayed (client-computed, matching the backend'sDailyResetTimeZoneId).ga_eventcalls for level_start/level_end now include the mode in the level id (e.g.letter-golf-practice-{id}).page.tsxis unchanged — stays SSR-Daily-only; Practice mode is entirely client-initiated after hydration, no new route. - Helper scripts for calling the two debug endpoints.
scripts/reset-daily-play.ps1/.shandscripts/get-solutions.ps1/.sh(paired PowerShell/POSIX-sh, matching the existingsetup-githooksconvention). Both readAPI_BASE/USER_ID/ADMIN_DEBUG_KEYfrom an untrackedscripts/letter-golf-admin.env(template committed asscripts/letter-golf-admin.env.example; the real file is explicitly.gitignored, not just relying on the existing.env.*pattern, since it doesn't start with a dot). The reset scripts defaultpuzzleKeyto today's Pacific-time daily puzzle if omitted (matching the backend's daily reset boundary); the solutions scripts require an explicitpuzzleKeyargument (works for daily, practice, or any future key unmodified). Neither script ever prints the admin key value. - Cleanup: retire the dead ad-hoc
GET /v1/letter-golfroute. The production generator naming half of this item is complete: the formerTestLetterGolfGeneratorand"TestLetterGolfGen"registration are nowLetterGolfGeneratorand the centralizedConsts.LetterGolfGeneratorServiceKey. The rename preserved the keyed test-substitution seam and did not change behavior. The bare route predates the real Daily/Practice data model (nopuzzleKey, nothing persisted, always returnspuzzleKey: null) and is no longer called by the frontend; remove it separately with endpoint-contract review rather than hiding that behavior change inside the ownership refactor.
Phase 4 — Player stats and streaks¶
Branch: feat/player-stats
- Promote the
userIdcookie toHttpOnly,Secure,SameSite=Lax, signed. Include alinkedIdentitiesarray so a future real login can absorb an anonymous device identity. Done (Chunk 0 + Chunk 0b, see session log below):proxy.ts'sinitializeCookies()setshttpOnly,secure(production), andsameSite: "lax"on theuserIdcookie, and now also signs it (HMAC-SHA256 viaCOOKIE_SIGNING_KEY/Cookie__SigningKey, threaded through Terraform mirroringadmin_debug_key). Legacy unsigned cookies already issued to real users remain accepted and are opportunistically upgraded in place rather than forcing re-identification.linkedIdentitiesitself is scaffolded in Chunk 1 below, alongside the newplayerscontainer.
The global daily's day boundary is Pacific time (America/Los_Angeles), not UTC — fixed
in an earlier session (Consts.DailyResetTimeZoneId) and documented in doc/lettergolf.md.
This section previously carried a stale "recommend UTC" open question; the decision has
already been made and shipped, so it's removed here rather than left contradicting the code.
Remaining work: chunk plan¶
Everything below stays on feat/player-stats, in the same small-independently-reviewable-
commit style as Chunk 0/0b: a chunk that touches more than one surface (Terraform, backend,
frontend) lands as separate commits per surface, and any Cosmos/Terraform change is written
and reviewed before it's applied, never bundled into the same commit as apply.
Architecture note — deviating from Phase 3's original data-model bullet. Phase 3's locked
decision assumed plays, stats, and streaks would all live in one players partition so a
submission could be a single TransactionalBatch. Phase 3b shipped plays as its own
container instead (partition /playKey, 180-day TTL), for a reason that only became clear in
hindsight: play records are ephemeral, TTL'd session/resume data, while stats and streaks
are permanent aggregates that must never expire — conflating their lifecycles in one partition
would force both to share one TTL policy, which they can't. Rather than migrate plays back
into players purely for atomicity, this plan keeps them as separate containers and uses
idempotent patch retries instead of a transactional batch: SubmitPlay already durably
flips PlayEntity.Status to Completed exactly once; stats/streak updates read-modify-patch
the players doc with IfMatchEtag, retrying on a 412 conflict, and are only ever applied
once per play because they're gated on that same Completed transition never re-firing for an
already-completed play. Simpler than a schema migration, consistent with YAGNI — flag before
Chunk 2 starts if this tradeoff should be revisited instead.
Chunk 1 — players Cosmos container and player profile scaffold¶
- Terraform: new
playerscontainer intf/data/cosmos.tf, partition key/userId, no TTL (permanent — individual sub-documents like settings/stats never expire on their own). - Backend:
PlayerEntity(id/userIddoubling as document id and partition key,linkedIdentities: string[]— empty until a real future-auth login flow populates it —createdAt),IPlayerStore/CosmosPlayerStore(point read; upsert-if-absent "ensure player exists"; patch withIfMatchEtag). - New endpoint:
GET /v1/players/me— point read (creating the doc on first read if absent) the caller's own player doc, identity resolved from the cookie only, via the existingHttpContextExtensions.GetUserId()convention (never a header). - No stats/settings/streaks shape decided yet in this chunk — just the container, the entity skeleton, and one read endpoint proving the round trip end to end.
- Commits: (1) Terraform (container, left unapplied until reviewed), (2) backend entity +
store + endpoint + tests, (3) apply the Terraform once the backend that reads/writes
playersis deployed — mirrors Chunk 0's write-then-apply-later split.
Chunk 2 — Stats and streaks, advanced on submit¶
- Stats shape: an open, additive counters map (new stat = new key, no migration) —
gamesPlayed,wins,totalScore(average is computed astotalScore / gamesPlayed, never stored),bestScore,longestWordLength,holeInOnes— plus ascoreHistogrammap and a reserved-for-futurehighlightsmap. Deviations from the plan above, made with the user's explicit sign-off before implementation: - Stats and streaks are keyed by gameType (stats["lettergolf"],streaks["lettergolf:global:daily"]), not a single flat structure — Reverse Cross is a real, near-term second game (not speculative), so per-game isolation avoids a migration the moment it ships. -scoreHistogrambuckets by absolute score ("1"/"2"/"3"/"4+"), not golf terms (eagle/birdie/par/bogey) — no puzzle computes or stores aparbaseline anywhere today, so golf-term banding had no data to key off of. -mostPointsRemovedInOneWordwas dropped — it needs per-word evaluator output thatLetterGolfPlayEvaluatordoesn't currently produce. Left out rather than half-built;PlayerStats.Highlights(an unpopulatedDictionary<string,string>) exists so a future non-numeric stat like this can be added additively. -longestWordbecamelongestWordLength(an int counter, consistent with the rest of the additive counters map) rather than storing the literal word text. - Streak keys are"{gameType}:{scope}:{kind}"(trailingdaily), not"{gameType}:{scope}"— reserves room for a future non-calendar streak kind (e.g. consecutive tournament/group wins) without colliding with or migrating this one. - Wire into
SubmitPlay: once the play is durablyCompleted(idempotent per the architecture note above), compute the stat/streak delta and patch theplayersdoc, retrying the whole read-modify-patch loop on anIfMatchEtag412 conflict (bounded, 5 attempts, no delay/jitter — contention on a single user's own doc is rare). A stats update failure is logged and swallowed, never fails the player-facing submit response — the play itself is already durablyCompletedby the time this runs. A durable local retry queue for exhausted updates is a known, explicitly-flagged gap, not built this chunk. - Tests: unit tests for the pure delta-computation function (
PlayerStatsCalculatorTests, no Cosmos) — counters, hole-in-ones, best-score/longest-word "only improve" semantics, score histogram bucketing, streak creation/consecutive-day/gap-reset/same-day-idempotent/ out-of-order-date protection, per-gameType isolation, and puzzle-key date parsing. Plus integration tests inPlayEndpointsTestsproving a duplicate submit of an already-completed play never double-counts, a global daily win creates/increments a streak, and a stats-update failure never fails the submit response. - Commits: (1) stats/streak entity shape + pure computation logic + unit tests, (2) wire into
SubmitPlay+ integration tests. Frontend surfacing (originally planned as this chunk's 3rd commit) shipped in Phase 4b (the/mescorecard page and the in-game streak badge/ recap), on branchfeat/stats-settings-ui— see the 2026-08-07 Phase 4b entry below.
Chunk 3 — Per-user settings¶
- Settings sub-document on
PlayerEntity:notifications,displayName,locale,theme,difficultyLevel. -
GET/PATCH /v1/players/me/settings(HTTP method is PATCH, not PUT — more semantically correct for a partial-merge patch; PUT would imply full replacement) — partial-update patch semantics (not full overwrite), sameIfMatchEtagoptimistic concurrency as stats. - Frontend: a minimal settings surface reading and writing the new endpoint, following
globalization.instructions.mdforlocale(real locale identifiers, not free text) andaccessibility.instructions.mdfor the form. Shipped in Phase 4b as the/settingspage, on branchfeat/stats-settings-ui— see the 2026-08-07 Phase 4b entry below. - Commits: (1) backend settings shape + endpoints + tests, (2) frontend settings UI + typecheck/lint.
Chunk 4 — Export and delete-my-data¶
-
GET /v1/players/me/export: full JSON dump of the caller's ownplayersdoc. Not a single-partition operation onceplaysis included —playsis partitioned byplayKey, notuserId(see the architecture note above) — so export must also cross-partition queryplaysby itsuserIdfield and fold matching records in. This contradicts this phase's original "single-partition delete" assumption, as a direct consequence of that same architecture note. -
POST /v1/players/me/delete(POST, notDELETE, to avoid an accidental cache/prefetch-triggered deletion): deletes theplayersdoc plus every matchingplaysdoc for thatuserId. Idempotent — an already-deleted account returns success, not 404, so a retried request is safe. - Both endpoints stay identity-gated the same way as everything else (cookie-only
userId, no admin key) — a caller can only ever export or delete their own data. - Commits: (1) both endpoints' implementation (commit
07a79f1), (2) test coverage for both (commit6e1d21e) — implemented together rather than split by endpoint, since export and delete share the same cross-partitionplaysquery shape and were reviewed as one unit. Done.
Sequencing and validation¶
Each chunk runs the same checks as Chunk 0/0b before its final commit: dotnet build/dotnet
test; tsc --noEmit/eslint for any frontend commit; terraform fmt -check/validate for
any Terraform commit, with apply only after explicit review, same as this phase's cookie
signing and container rename. Update this section's checkboxes and the phase status table as
each chunk lands, and add a dated session-log entry per chunk the same way Chunk 0/0b did.
Phase 5 — Groups and social¶
Branch: feat/groups-social (the roadmap table previously said feat/groups; the actual
working branch is feat/groups-social).
Design principles¶
Source: user-provided design notes (referred to here as "the Terra notes") plus a mobile mock of a group detail page.
- Preserve the golf-vocabulary hierarchy:
Play(one attempt at one puzzle) →Hole(one Letter Golf puzzle) →Round(9 or 18 holes) →Tournament(several rounds on a schedule) →Group(the people/context scores are compared within).PlayEntity's doc comment already anticipated this: "Named 'Play' rather than 'Round' to avoid colliding with real golf's 'round' (9/18 holes), which Phase 5/7 courses and tournaments will need." Phase 5 only buildsGroup;Round/Tournament/Courseare Phase 7 (see that section below). - Groups are a competition context, not a friend feed. Do not build a general "follow a friend's lifetime stats" feature. The only questions a group answers: did my friends finish today's puzzle, what did they score, where do I rank in this group's current round, can I share a spoiler-free result. "Friends" is simply "people who share a group with me" — no separate follower graph.
- A group has a Today page, not a feed. The default (and, for Phase 5, only) shared activity is the global Daily. Members see completion state and final score only; submitted words, partial scores, and solutions are never shown to other members.
- Completion-state vocabulary, used consistently everywhere a member's status is shown: Completed (score visible), Playing (no words, no partial score, just a neutral in-progress indicator), Not played (neutral, never a red/shame-y state).
- Comparison copy stays relative and light, never a lifetime-stats dump: "You're 2nd of 6
today", "6 of 9 members finished", "Your score: 3 · Group median: 3", "Maya has a 12-day
streak". Deeper scorecard sharing remains group-private and user-controlled. The current
product direction is detailed sharing enabled by default, with per-game opt-out and coarse
per-group overrides (see
doc/stats-sharing-implementation-handoff.md).
Group page structure¶
Groups ← landing page (list + create + join)
├── Word Club
│ ├── Today ← shared global Daily + standings (built in Phase 5)
│ └── Members ← names, owner badge (built in Phase 5)
└── Friday Scrabblers
├── Today
└── Members
An Events tab (9/18-hole Rounds, Tournaments) is the conceptual insertion point for Phase 7
and is deliberately not built or stubbed in Phase 5 — a disabled future-nav item makes the
product feel unfinished. When Phase 7 lands, "Today" becomes one kind of event among several
rather than needing a redesign; a future group event header can read Saturday Nine · Hole 4
of 9 · Word Club or Summer Open · Round 2 of 4.
Global versus group-specific puzzle formats¶
| Format | Puzzle source | Phase |
|---|---|---|
| Global Daily | One shared global puzzle | Phase 5 |
| Group Daily | Global puzzle format, but a private puzzle just for the group | Future, opt-in (not Phase 5) |
| Group Round | Ordered 9/18-hole set assigned to a group | Phase 7 |
| Tournament | Scheduled rounds across several days | Phase 7 |
Phase 5 ships Global Daily only — every group's Today tab is the same worldwide daily
puzzle, with a private per-group leaderboard layered on top. This avoids N-times puzzle
generation cost and keeps the header unambiguous: GLOBAL DAILY · ENGLISH (US) · RESETS IN
08:42. A future private "Group Daily" puzzle is documented as a deliberate, explicit
group-owner setting ("Puzzle source: ○ Global Daily — compare with the whole world / ○ Group
Daily — a puzzle only for this group"), never a silent per-player toggle, and never mixed with
the global leaderboard in the same standings.
Multilingual note¶
Puzzle language belongs to the group/event, not the player. For Phase 5 the puzzle
language is a fixed fact (en-US, the only playable language today) shown on the group header
rather than a selector that would misleadingly imply choice. When multiple puzzle languages
exist later, a group owner chooses one explicit language for the group/event; different
languages are never compared in the same leaderboard.
Data model¶
New containers in the shared minigames database, mirroring the puzzles/plays/players
pattern already in tf/data/cosmos.tf:
| Container | Partition key | Purpose |
|---|---|---|
groups |
/groupId |
Group metadata + members (permanent) and per-day materialized standings docs (7-day TTL), same partition so both are cheap point reads/writes |
lookups |
/lookupKey |
Join code → groupId, point-read/write only, uniqueness enforced by CreateItemAsync 409 |
PlayerEntity gains groupMemberships: string[] (group IDs only — no denormalized group
name/status; those come from a point read of the group doc itself, bounded by the per-user cap
below).
Membership is dual-written across the groups and players containers and therefore not
atomic. Both writes are idempotent (joining twice is a no-op), so a partial failure leaves a
group missing from a player's own list at worst — it self-heals the next time they use the
join code again. A dedicated reconciliation job is deliberately not built for this MVP (see
Scope exclusions); the group doc is always the authoritative membership record.
Standings update model¶
Standings are materialized per group per day ({groupId}|standings|{puzzleKey}, 7-day
TTL), fanned out best-effort from the existing Letter Golf play endpoints — mirroring
PlayerStatsUpdater's idempotent, ETag-retried, log-and-swallow-on-failure pattern so one
group's Cosmos hiccup never affects another group or the player-facing response:
- First autosave of a global-daily play (
PUT /v1/letter-golf/{puzzleKey}/play, only the transition from no-play toInProgress) flips the caller's entry in each joined group's standings doc to Playing. This intentionally does not re-fire on every 2-second-debounced autosave. - Submit (
POST /v1/letter-golf/{puzzleKey}/submit) flips the entry to Completed with the server-authoritative score, alongside the existing best-effortPlayerStatsUpdatercall (kept as a separate try/catch — a group-standings failure must never affect the player's own stats update or vice versa). - Practice-scope plays never touch any group's standings (same
Scope == Consts.GlobalScopegate already used for player stats/streaks).
Caps and rate limits¶
MaxGroupsPerUser = 10,MaxMembersPerGroup = 50— plain constants, tunable without a schema change, chosen for MVP cost/abuse control rather than a measured limit.- Join codes are 6-character alphanumeric (~2.1 billion combinations).
POST /v1/groups/joingets its own tighter rate-limit policy (10/min/IP, matching the existingdebug-endpointsstrictness) rather than the looserplay-endpointspolicy, since a guessable code is worth blunting brute-force attempts on. GET /v1/groups/{groupId}returns 404 for a nonexistent group and 403 for a non-member — a group's existence and membership are never revealed to non-members; this is a private lens, not a public directory.
Roles¶
Creator becomes the group's owner: can rename the group, regenerate the join code, and remove members. Any member can leave at any time. If the owner leaves and other members remain, ownership auto-transfers to the earliest-joined remaining member — there is no separate "delete group" flow, and a group is never left ownerless while members remain.
Sharing¶
Share strings stay client-side and spoiler-free. Plain share URLs with Open Graph metadata, no third-party social SDKs.
What not to build yet¶
- No
Rounds,Tournaments,Courses, orEventstabs — not even disabled placeholders. - No group-specific/private puzzles (see the format table above — documented, not built).
- No deeper scorecard sharing between members in the completed Phase 5 slice.
- No dedicated reconciliation job for the dual-write membership pattern.
- No "Groups" section on the personal
/mescorecard yet (natural follow-up once Phase 5 UI ships, per this section's own group-page-structure note).
Scope boundary: Letter Golf only, for now¶
Phase 5 (backend and frontend both) is wired to Letter Golf specifically, not games in general, even though other games are in the pipeline:
GroupEndpoints.GetMyGroups/GetGroupDetailcompute "today's puzzle" by callingLetterGolfDailyPuzzleProvider.GetTodayGlobalPuzzleKeydirectly;GroupResponsehas nogameTypefield, so a group cannot yet represent any other game's standings.- The standings fan-out is only called from
LetterGolfEndpoints' save/submit handlers. At this phase, Reverse Cross did not yet have an equivalent hook to wire in. - The frontend Today tab's copy and CTAs, and the post-victory "View standings" prompt, are
hardcoded to
/games/letter-golf.
What's already generic, so this isn't a rewrite later: IGroupStore/GroupStandingsUpdater
take an opaque puzzleKey/score/displayName with no Letter Golf types, and reuse the same
{gameType}|{scope}|{date} key convention and per-game-keyed stats/streaks (stats["lettergolf"])
that Phase 4 deliberately chose with Reverse Cross in mind. Extending groups to a second game
will still need: a gameType on Group/GroupResponse, that game's own daily/persistence
layer, its endpoints wired into GroupStandingsUpdater, and a game-aware Today tab/victory
hook on the frontend — not planned for this push, flagged here so it's a tracked follow-up
rather than a surprise.
Implementation notes¶
Backend is merged to main and its Terraform has been applied: the groups/lookups
Cosmos containers are live. Frontend UI (feat/groups-social-ui) is also merged to main:
landing page, create/join forms, per-group Today/Members tabs, owner actions (rename/
regenerate code/remove member), and a post-victory "View standings" link on Daily wins. A
follow-up fix (fix/groups-standings-backfill) closed a gap where a member who completed or
started today's puzzle before joining the group never showed up in standings — see the Session
log for details.
- Cosmos containers (
tf/data/cosmos.tf, applied):groups, partition key/groupId,default_ttl = -1— holds both the permanent group-metadata document (id = groupId) and per-day standings documents (id = "{groupId}|standings|{puzzleKey}") in the same partition, the latter setting its own 604800-second (7-day) itemttl, mirroring thepuzzlescontainer's per-item-TTL pattern.lookups, partition key/lookupKey,default_ttl = -1— join-code → groupId documents (id = "joincode|{CODE}"), created viaCreateItemAsyncso a code collision throws a native Cosmos 409 instead of a separate check-then-write race. - Endpoints, both new families under
/v1/groups(MiniGamesBackEnd/Endpoints/GroupEndpoints.cs):POST /v1/groups,GET /v1/groups/mine,GET /v1/groups/{groupId},POST /v1/groups/join,POST /v1/groups/{groupId}/leave, and the owner-onlyPOST /v1/groups/{groupId}/rename,POST /v1/groups/{groupId}/regenerate-code,POST /v1/groups/{groupId}/members/{userId}/remove.joinhas its own tighter rate-limit policy; the rest use the existingplay-endpointspolicy. - Best-effort fan-out is wired into the existing Letter Golf endpoints, not a new endpoint:
SavePlay's first autosave (global scope only) marks the caller Playing in each joined group's standings;SubmitPlaymarks them Completed with the server-computed score. Both calls run in their own try/catch, independent of the existingPlayerStatsUpdaterbest-effort block, so a group-standings failure never affects stats or the play response. - Known/accepted MVP gaps (already documented above, restated here for a quick scan): no
reconciliation job for the dual-write
groups/playersmembership update — both writes are idempotent, so a partial failure self-heals the next time the player rejoins or is re-read; and no "Groups" section on the personal/mescorecard yet.
Frontend testing plan (deferred)¶
No frontend test framework is installed yet (package.json has no test script or test
dependencies). This plan is deferred until the team adopts a framework. Per
.github/instructions/testing.instructions.md, the intended future stack is Vitest +
React Testing Library for component tests and Playwright for end-to-end journeys.
Component tests (Vitest + React Testing Library):
- Practice-mode puzzle loading:
GET /v1/letter-golf/{puzzleKey}endpoint loads the exact puzzle by key; verify navigating to/games/letter-golf?mode=practice&puzzle={key}restores that puzzle and any saved progress instead of defaulting to Daily. - Expired/invalid practice puzzle handling: verify unknown or TTL-expired puzzle key shows the "expired" UI with functional "New practice puzzle" and "Play today's Daily" action buttons.
- Victory overlay context-awareness: Practice-mode victory shows title "Practice complete", no share buttons, and both action buttons ("Start new practice", "Switch to Daily"); Daily-mode victory is unchanged (title "Victory", share buttons present, single "Close" button).
- Victory overlay dismiss-state regression: verify
victoryVisiblecorrectly resets when a new practice puzzle is started after a previous one was won and closed; winning two different practice puzzles in a row both show the overlay (regression test for the key-remount fix). - Best Daily score label on Practice-mode win: verify label reads "Best Daily score: X" on a Practice-mode victory (not "Your best score") — uses shared Daily-only stat until practice-scoped stats exist.
lib/groups.tsfetchers (fetchMyGroups,fetchGroup,createGroup,joinGroup,leaveGroup,renameGroup,regenerateJoinCode,removeMember): mockfetch, verify HTTP method/URL/body shape, verify error status propagation (400/403/404/409) and error-response parsing.- Groups landing page: empty state when no groups, populated list with group names and one-line today status ("You scored N", "Playing", "Not played").
- Create form: name input validation, success navigation to group detail, distinct error messages for "name required", "already have max groups", "server error".
- Join form: reads
?code=search param to pre-fill, fallback manual entry, success navigation, distinct error messages for "invalid code", "already a member", "group full", "server error". GroupOwnerMenu(rename/regenerate-code flow): only visible to owner, dialog opens/closes correctly, dialog form resets when opened, rename success refreshes the page, regenerate success shows new code and updates the copy-to-clipboard target.RemoveMemberButton: only visible to owner, callsremoveMemberwith correctgroupIdanduserId, success removes the member from the UI, error shows/dismisses gracefully.- Today tab completion-status CTA: verifies
NotPlayedstate shows a link to/games/letter-golf,PlayingandCompletedstates hide that link, standings table sorts correctly by status then score. - Members tab: displays member names with owner badge, only owner sees the remove button per member, non-owners never see a remove button.
End-to-end tests (Playwright):
- Create a group, get a shareable join link with
?code=pre-filled, open the link in a second browser context, join successfully from that context. - Both contexts play the global Daily to completion, verify standings show both members with
Completedstatus and correct scores. - One context plays a practice puzzle, verify that play never appears in the group's Today standings.
- Non-member context tries to access
GET /v1/groups/{groupId}(or navigates to the detail page), verify 403 rejection (no 404 information leakage). - Owner-only actions (rename, regenerate code, remove member): verify hidden/disabled for non-owners, verify they fail with 403 if a non-owner tries the API directly.
Accessibility testing (keyboard + screen reader, per
.github/instructions/accessibility.instructions.md):
- Keyboard-only walkthrough: navigate the Today/Members tabs (now plain links with
aria-current, not a tablist) and all form controls in create/join flows. Verify focus order is logical and all controls are reachable. - Screen-reader spot checks: tab labels and current-page indicator, form labels and error messages, button/action affordances (e.g., remove button contextual to each member row), and visual-only affordances (e.g., owner badge) have accessible alternatives.
Cross-cutting: observability¶
Branch: feat/obs-start. Inserted here, after Phase 5, as a deliberate pause before Phase 6/7 feature work
to get a baseline of telemetry, tracing, and feature-flag/alpha-beta targeting in place —
not a numbered phase, same as "Cross-cutting: testing" below, so Phase 6/7/8+ numbering (and
their existing code-comment cross-references) stays untouched.
Decisions¶
- System telemetry/APM: Application Insights via OpenTelemetry, attached to the existing
azurerm_log_analytics_workspace.www(tf/frontend/analytics.tf) rather than a new workspace. Covers request/dependency traces, exceptions with call stacks, and Live Metrics for both the ASP.NET Core backend and the Next.js frontend. - Feature flags and alpha/beta targeting: Azure App Configuration Feature Management, not
PostHog and not a homegrown allowlist. The concrete need — "these two specific people see this
button, nobody else" — maps directly onto Feature Management's
TargetingFilterkeyed on the existing durableuserId(Phase 4's anonymous-first identity). - PostHog deliberately deferred, not rejected. Revisit once real A/B experiment result analysis, click heatmaps, or session replay are actually wanted — Azure App Configuration alone only gives on/off/targeted flags, no experiment analytics. PostHog's free tier (~1M events/mo) would cover all of that in one tool if/when that's worth the extra integration.
- Google Analytics (GA4) stays, demoted to marketing/traffic-only. New product-behavior
events (button clicks, feature usage) move to Application Insights custom
trackEventcalls instead of the existingga_event()wrapper.
Current state (confirmed before this phase started)¶
- GA4 (
G-1Y5XWM30YM) already wired inlayout.tsx/analytics.ts/cookie-banner.tsx, consent-gated (denied by default), tracking"share"and a global"exception"event. - No Application Insights/OpenTelemetry anywhere yet (
MiniGamesBackEnd.csproj,Program.cs,appsettings*.json, and frontendpackage.jsonall confirmed clean of it). - Backend
ILoggercalls already use proper structured message templates (e.g.logger.LogWarning(ex, "...{GroupId}...{UserId}...", ...)) — a sink is all that's missing. - Health checks are solid:
/health/live+/health/ready(Cosmos ping viaCosmosHealthCheck.cs) on the backend,/healthon the frontend, both wired into DockerHEALTHCHECKand Container Apps startup/readiness/liveness probes. - 5 rate-limit policies (
verify-word,play-endpoints,warmup-endpoints,debug-endpoints,group-join) already guard abuse; no feature-flag framework exists (only placeholder comments inproxy.ts); no crash-reporting service (Sentry/etc.) is integrated. - Known pain point worth an early custom trace: cold starts. Backend
min_replicas = 0, downloads/builds ~1M-word in-memory dictionaries on scale-from-zero;cooldown_period_in_seconds = 1800reduces frequency, not the cold-start latency itself. Mitigation added 2026-08-19: a rendered Letter Golf board starts the rate-limited/v1/letter-golf/validation/warmuprequest so Daily validation initialization overlaps play; browser and backend single-flight tasks prevent duplicate work, and submission waits for an already-started warm-up while retaining its original fallback behavior on failure. This does not eliminate scale-from-zero or guarantee warming every one of the maximum two replicas.
Tier 1 — build now (low-hanging fruit)¶
Status: merged to main (17293bb); terraform apply has run and the production Container
Apps have been redeployed with this code. Application Insights and App Configuration exist
in Azure, their connection string/endpoint reached the backend Container App's env vars, and
both the backend and frontend images were rebuilt/pushed and deployed — see the 2026-08-15
session log entry. Confirmed working in production.
Backend (MiniGamesBackEnd/)¶
- Add
Azure.Monitor.OpenTelemetry.AspNetCore; wirebuilder.Services.AddOpenTelemetry().UseAzureMonitor(...)inProgram.cs, connection string fromApplicationInsightsOptions.ConnectionString(ApplicationInsights:ConnectionStringconfig section), fail-soft (skip, no throw) if unset in Development, fail-fast (throw) if unset outside Development — a missing value there means the Container App secret wiring is broken, not that telemetry should silently go missing. - Terraform:
azurerm_application_insights.wwwintf/frontend/analytics.tf, workspace-based mode,workspace_idpointing at the existingazurerm_log_analytics_workspace.www— no new workspace. Connection string exposed as a sensitive module output, passed into the backend module the same waycookie_signing_keyalready is (seetf/main.tf). - Wired the connection string into the backend Container App's secrets/env vars
(
app-insights-connection-stringsecret →ApplicationInsights__ConnectionStringenv, same pattern as the existing Cosmos endpoint/key wiring) intf/backend/container_app.tf. - Confirmed existing structured
ILoggercalls and Cosmos SDK calls need no code change — both auto-instrument once the exporter is wired. - Hand-instrumented three
System.Diagnostics.Activityspans via a sharedTelemetry.ActivitySource(MiniGamesBackEnd/Telemetry.cs):WordList.ColdStartLoad(MultiDict.InternalInitAsync),LetterGolf.DailyPuzzleGeneration(LetterGolfDailyPuzzleProvider.GetOrCreateDailyAsync), andGroups.StandingsBackfill(GroupStandingsUpdater.GetStandingsWithBackfillAsync).
Frontend (frontend/minigames/)¶
- Added
@microsoft/applicationinsights-web(src/app/app-insights.ts): the SDK auto-collects page-load timing and unhandled JS errors/promise rejections once initialized (no manualwindow.addEventListenerneeded — the existing GA exception listeners inlayout.tsxare left as-is, this augments rather than replaces them). AtrackEventhelper is exported for future button-press instrumentation (mode switch, regenerate puzzle, share, group actions) — not wired to any specific button yet, since no concrete "which clicks matter" decision has been made. -
enableCorsCorrelation: trueset inapp-insights.ts's config; W3C trace-context propagation is the SDK's v2 default, no extra config needed. - Gated behind the existing cookie-consent gate:
components/app-insights-provider.tsxonly callsinitAppInsights()oncegetStoredConsent() === "granted", reacting tocookie-banner.tsx's newCONSENT_CHANGE_EVENTso a same-session consent grant (not just a page reload) enables telemetry. - Research spike first, then implement if viable: Next.js server-side (SSR/Server Action)
tracing via
@azure/monitor-opentelemetry+instrumentation.ts. Verify Next.js 16's current instrumentation API before writing this — do not assume an experimental config flag name from third-party guidance still applies to this repo's version. Not started.
Feature flags¶
- Terraform:
azurerm_app_configuration.apiin newtf/backend/feature_flags.tf(Free tier: 1 store/subscription, 1,000 requests/day),local_auth_enabled = false(RBAC-only, matching the Cosmos account'sdisable_local_authpattern), plus anazurerm_role_assignmentgranting the API's existing user-assigned identity "App Configuration Data Reader" (read-only — flag values are never written by the API itself). - Backend packages ended up named
Microsoft.FeatureManagement+Microsoft.Extensions.Configuration.AzureAppConfiguration(theMicrosoft.FeatureManagement.AspNetCore/Microsoft.Azure.AppConfiguration.AspNetCorenames guessed during planning were for MVC-specific extras this API doesn't use). Wiredbuilder.Configuration.AddAzureAppConfiguration(...).UseFeatureFlags()plusAddFeatureManagement().WithTargeting<HttpUserIdTargetingContextAccessor>()inProgram.cs; the newHttpUserIdTargetingContextAccessor.csresolvesTargetingContextfrom the same userId cookie every other endpoint uses (HttpContextExtensions.GetUserId). - Added
GET /v1/features, evaluated server-side viaIFeatureManagerfor the calling request's userId — returns a{flagName: bool}map, so the targeted audience list is never exposed client-side. Now consumed by the frontend: a hidden "god-view" section in the hamburger menu (lib/features.ts,use-god-view.ts,god-view-dialogs.tsx) conditionally renders up to three items, each gated by its own flag. - First concrete flags shipped, per the runbook below:
PuzzleMetadata(raw puzzle metadata — id, wildcards, hole-in-one flags, par, difficulty score),DebugSolutions(gatesGET /v1/letter-golf/{puzzleKey}/debug-solutionsfor per-puzzle solutions, requires the caller to have already completed a non-practice puzzle; also gates the new date-scopedGET /v1/letter-golf/daily/{date}/debug-solutionsfor browsing any date's daily solutions with spoiler-tracking consequences, no completion-required gate — see the 2026-08-17 Session log entry for details), andResetDaily(lets a targeted user delete and retry their own daily play, alongside the existing admin-key bypass onResetPlay— still only ever the caller's own play, never an arbitrary userId). - Manual runbook for adding a userId to a flag's audience — see below.
Feature flag targeting runbook¶
Use the cross-platform operator commands in
doc/feature-flag-operator-runbook.md. They accept
canonical user IDs only, merge recipients without replacing the existing targeting audience, use
the App Configuration REST data plane to avoid the known Windows CLI JSON-quoting bug, and
announce the accepted write to active API replicas. The former portal/CLI-only procedure is now
historical: it can still change a flag, but it does not create the durable refresh announcement
and therefore may wait for the one-day missed-notification poll fallback.
Tier 2 — professional/in-depth (documented backlog, not built)¶
- Live Metrics Stream as a regular during-deploy/during-playtest habit.
- Application Insights availability/synthetic ping test.
- Azure Monitor alert rules (error rate/latency thresholds) piped to the existing Slack deploy
webhook already used in
update_image.sh. - PostHog reconsideration for real A/B experiment result analysis, click heatmaps, session replay.
- Correlating KEDA scale events with request latency to see cold-start impact directly.
- Ingestion sampling/cost tuning if telemetry volume grows enough to matter.
Tier 3 — overkill (documented backlog, not built)¶
- Multi-region/geo-distributed tracing.
- SLO/error-budget dashboards.
- Synthetic multi-step user-journey monitors.
- Grafana on top of the Azure Monitor data source.
- Long-term (beyond 30-day) cold-storage log retention pipeline.
- Per-endpoint sampling strategy tuning.
- Load/performance testing harness (k6 or Azure Load Testing) wired into CI for load-time regression detection.
Advertising: AdSense compliance prep¶
Original branch: feat/prep-adsense; current release preparation: feat/adsense-release-prep. Not a
numbered phase — a one-off compliance/plumbing effort so the
site can eventually apply to Google AdSense, requested and scoped in conversation rather than
in doc/roadmap.md from the start. Detailed placement rules, provider research, feature-flag
design, and the staged experiment sequence live in doc/advertising-strategy.md; broader
player-trust context lives in doc/engagement-platform-plan.md. This section only tracks what
has actually shipped versus what remains.
Baseline confirmed before starting: no live AdSense integration exists — only a dormant
google-adsense-account meta tag (ca-pub-4876907375472591) in layout.tsx and existing GA4
analytics. No ads.txt, no certified consent management platform (CMP), no way to reopen
consent from Settings, and an inaccurate Privacy Policy claiming no PII is collected.
Update (2026-08-16): the old publisher ID belonged to an account Jon can no longer access, so
it was removed from layout.tsx and ads.txt. The new @verbolus.com AdSense account now exists;
commit ed7c620 publishes its account meta tag and root seller record for ownership verification.
At that point the AdSense JavaScript runtime remained deliberately absent, so the ownership change
did not serve or request ads.
Stage 0 — content and compliance foundation (doc/advertising-strategy.md)¶
- Corrected
/privacyto accurately describe the identifier cookie, stored player data, analytics, and (once applicable) advertising — seeapp/privacy/page.tsx. - Expanded the advertising section with Google's cookie, web-beacon, IP-address, identifier,
purpose, partner-data, certified-CMP, and state-law sharing disclosures (
337bd2c), then updated it to distinguish the active account-level review script from future ad-unit requests. Review it again against the live behavior beforeAdsEnabledis enabled. - Added a preferences surface that reopens and changes consent: a new "Privacy" section
in
app/settings/settings-form.tsx, backed by a sharedsetStoredConsent()helper moved intoapp/analytics.ts(also now the single home forCONSENT_CHANGE_EVENT, previously exported fromcookie-banner.tsx). - Removed the stale
google-adsense-accountmeta tag fromlayout.tsxand the staleads.txtentry (both referencedpub-4876907375472591, an account nobody can access anymore). - Added the new account's
google-adsense-accountmeta tag and Google seller record for ownership verification (ed7c620). No AdSense runtime script or ad request was added. - Added the exact account-level AdSense script to the submitted homepage entry point and
existing placement boundaries for site review. It is present on both launched game routes,
both How-to-Play guides, and substantial Update articles, but not on prohibited or other
non-placement routes. No ad unit markup, slot ID, or
adsbygoogle.pushcall was added; Auto Ads remains disabled account-side. - Decided the audience/age posture: general-audience, not directed at children under 13. Reflected in the privacy policy's new "Children's Privacy" section.
- Published explicit
/robots.txtand/sitemap.xml, and excluded/ads.txtfrom the application identity proxy so seller-record crawler requests remain static (550aa5d). - Added scalable, crawlable homepage discovery content with separate Play and How-to-Play
links; placed Letter Golf first and presented playable Reverse Cross as launched
(
3193865,9c8bfdc). - Added public Terms of Service covering guest/accounts, games, acceptable use, user content,
and prospective payments/subscriptions (
1fb5f6d). - Added distinct public metadata and canonical URLs, no-index boundaries for personal and
prototype surfaces, and shared sitemap generation from the public metadata catalog
(
9005768). - Added game-shaped initial loading states, one useful rules sentence, visible How-to-Play
links, and full-document retry recovery for both games (
848a54a,b517aaa). - Added focused regression coverage for crawl metadata, loading-route wiring, skeleton
semantics, full-reload recovery, and key Terms clauses (
a4809e9). - Select and configure a consent-management platform. Google requires a certified,
IAB-TCF-integrated CMP before serving personalized ads in the EEA (since 16 Jan 2024),
UK (same date), and Switzerland (since 31 Jul 2024) — see
support.google.com/adsense/answer/13554116.
The existing custom cookie banner is Consent Mode only, not TCF, and is not sufficient
for this. Recommended path: Google's own free, pre-certified "Privacy & messaging" tool
in the AdSense/Ad Manager dashboard — it has built-in EEA/UK/Switzerland region
detection, so no separate server-side GeoIP work is needed. Ad loading should gate on
"has the CMP responded" (e.g. the
__tcfapicallback), not on a home-grown geo check — this is the basis of the "disable ads for Europe" kill switch and is not yet built. - Complete AdSense site-ownership verification.
- Get through Google's site review (Ready status). The first review was unsuccessful
without a specific policy reason; the dashboard returned to Requires review, separately
showed
ads.txtas Not found, and the Policy Center listed no issue even though the correct seller record was publicly reachable. Deploy and verify the account-script change, then followdoc/adsense-site-review-runbook.mdbefore requesting re-review. - Before the first live Stage 2 placement, add the CMP and one centrally managed manual-unit
coordinator. Gate every ad-unit request—not the account-level review script—on
AdsEnabled, the placement flag, ad-free entitlement, eligible surface/viewport, and the applicable CMP/consent result. Auto Ads remains deferred.
Stage 1 — house-ad layout trial (placed, internal cohort only)¶
AdPreviewEnabled now covers every implemented preview surface for its targeted cohort. The
placementFlag identifies whether that location has instead been selected for live advertising:
when both AdsEnabled and that placement flag are true, the preview yields only that location to
the live-ad path. Preview flags do not control the centralized account-level site-review script,
and the preview component never requests an ad unit.
- Content pages (
AdsContentPages) — added after a complete instructional section, before strategy tips, on the new How to Play pages for both games (games/letter-golf/how-to-play,games/reverse-cross/how-to-play), each linked from a "How to Play" action next to that game's header. Also added to substantial/updatesarticles only (see below) — never on the/updatesindex itself, which is just a list. - Desktop gameplay rail (
AdsDesktopGameplayRail) — sharedGameplayAdLayoutkeeps both games centered and renders one non-sticky, neutral 300×600 preview rail only at viewports of at least 1,600 CSS pixels. Its 300/150/600/150/300 geometry preserves a 150px game-to-ad gutter and removes the rail when viewport width or browser zoom cannot preserve it (0ed0451). - Post-completion (
AdsPostCompletion) — rendered below the game board once the puzzle is completed, explicitly outside theVictoryoverlay component itself (which stays ad-free per the strategy doc), in both games. - New
/updatespage: a hand-maintained, hardcoded list of dated entries (app/updates/updates-data.ts), newest first, each with its own/updates/{slug}article route. Asubstantial: booleanper entry controls whether that article's page carries a content-page ad slot — short release notes don't get one. The homepage now surfaces a "New for {date}: {title}" teaser linking to the newest entry. - Product/UX judgment calls (Sol's placement recommendations, adopted as-is): Privacy and About stay permanently ad-free (legal/trust surface and a brand/credibility page, respectively — a "Support Verbolus" link belongs on About instead of an ad unit); How to Play is the strongest initial surface since it's genuinely useful original content; Updates only carries an ad on individual substantial articles, never on the index.
Feature flags (AdsEnabled, AdPreviewEnabled, AdsContentPages, AdsDesktopGameplayRail, AdsPostCompletion)¶
- No backend or Terraform change was needed:
GET /v1/featuresalready enumerates every flag present in Azure App Configuration generically (see the Cross-cutting: observability section above), and the frontend'sfetchFeatures()/Featurestype are already an untypedRecord<string, boolean>. Any new flag name works without a code change. - Created both flags in
minigame-api-config, per the runbook above (AdPreviewEnabled's--filter-parametershit the same Windows CLI JSON-quoting bug documented there, worked around with the same direct REST PUT).AdPreviewEnabledis enabled and targeted at the same four userIds already used forPuzzleMetadata/DebugSolutions/ResetDaily(Jon and Justin's god-view cohort) — everyone else still getsfalse. The route-scoped account script is independent of this flag.AdsEnabledwas created withstate: offand no audience — nobody gets live ads yet; it will start getting used once manual ad-unit integration begins later in this AdSense phase. - Created
AdsContentPages,AdsDesktopGameplayRail, andAdsPostCompletion, eachstate: onwith no targeting filter. These are live-placement switches; they do not limit which previews appear. WhileAdsEnabledremains off, Jon/Justin'sAdPreviewEnabledcohort sees all implemented previews. Before a selective live rollout, make the placement flags targeted rather than globally on soAdsEnabledcan activate only the intended live locations for each cohort.
Brand and navigation rollout¶
Branch: feat/prep-adsense. A scoped rollout of shared identity and navigation components across public and account routes, bundled on the same branch as the AdSense compliance work (see "Advertising: AdSense compliance prep" above). This is not a numbered phase — it's a brand/UX effort requested in conversation. Asset inventory and master design files live in frontend/minigames/brand/, with detailed review criteria and theme guidance in frontend/minigames/brand/README.md. All work is frontend-only; no backend or contract changes.
Stage 1 — Home-link primitives and menu grouping (fd24e8e)¶
- Introduced
BrandMark(theme-aware Verbolus mark, CSS-driven light/dark toggle without JS flicker) andBrandHomeLink(mark + live "Verbolus" text, 44px touch target) as shared identity primitives (src/app/components/brand-{mark,home-link}.tsx). - Refactored
header-menu.tsx: both mobile Sheet and desktop DropdownMenu now open with a branded home link; both menu triggers gained explicitaria-label="Open navigation menu"since the icon-only buttons had no accessible name before. - Replaced image-presence-based link grouping hack with explicit
groupfield (play/player/company) inlinks.ts; added the previously-missing Privacy link to the company group. - Added pure-logic coverage:
links.test.tsnow tests group membership, link integrity, and the new Privacy entry. - Why: establishes the canonical home link and accessible menu affordance; lays groundwork for shared header/footer in Stage 2.
Stage 2 — Shared header/footer and route migration (0ac2fcd)¶
- Created shared
SiteHeader(BrandHomeLink + hamburger trigger) andSiteFooter(quiet trust links: How to Play, Updates, About, Contact, Privacy) components (src/app/components/site-{header,footer}.tsx). - Migrated About, Contact, Privacy, both How-to-Play pages, Updates index/detail, Scorecard, Settings, and Groups (list, create, join, detail layout) onto
SiteHeader, removing redundant PageNav home links. Landing page header/greeting restructured to useSiteHeaderwith a narrower, non-pressuring width constraint (w-full max-w-* instead of w-[50%] min-w-[380px]) and a footer that scrolls naturally instead of pinned to fixed height. - Extracted groups/create's client form into
create-group-form.tsxso the page itself stays a Server Component wrapped bySiteHeader. - Active game routes intentionally left untouched:
GameHeaderkeeps its compact 3-column layout; noSiteHeader/footer wraps the board during play. - Why: ensures consistent, accessible navigation and branding across all public/account pages without adding chrome to the focused game experience.
Stage 3 — Favicon, Apple touch icon, and PWA manifest (1f3e647)¶
- Replaced
src/app/favicon.icowith the approved brand favicon (single authoritative icon, no competing icon declarations). - Added Apple touch icon entry to root metadata in
layout.tsx, pointing at/brand/icons/apple-touch-icon-180.png. - Created
src/app/manifest.ts, served at/manifest.webmanifest, with: - Standard 192/512 icons (purpose: any) and maskable 192/512 icons (purpose: maskable) as separate entries per spec.
- Background/theme color set to the fixed navy (#101C28) used in the approved app icon.
- Three shortcuts: "Play Letter Golf" (/games/letter-golf), "Play Reverse Cross" (/games/reverse-cross), and "Groups" (/groups).
- Deliberately omitted: a "Practice Letter Golf" shortcut (practice puzzles require a client-generated UUID key with no stable deep-link URL, so adding it would risk shipping a broken/misleading shortcut) and Open Graph/social share image (no approved export exists yet — deferred for future brand campaigns).
- Why: establishes the canonical icon suite for web, PWA, and future app store listings; enables installed app shortcuts and adaptive icon support on modern browsers and Android.
Stage 3 wired the manifest and icons but intentionally stops short of a real installable PWA: no service worker exists yet, so browsers will not surface an install prompt from this alone. The next step (service worker, install-prompt UX, offline scoping) is tracked as its own item — see "PWA (installable web app)" under "Phase 8+ — social and platform backlog" below — rather than folded into this rollout, since it needs its own design decisions (caching/offline strategy, update lifecycle) independent of the brand/navigation work above.
Reverse Cross foundation and generation - phases 1 through 3¶
Reverse Cross Phases 1 and 2 are complete. Phase 3A-3D design and implementation are also complete, with production-container/load validation and progressive feature-flag rollout intentionally remaining in Reverse Cross Phase 10.
The dedicated Reverse Cross roadmap records the implementation and evidence:
- Complete: extract a compatibility-preserving shared lexical catalog, normalization/moderation pipeline, and per-game eligibility/index boundaries. Production Letter Golf now uses the shared catalog/index; deterministic integration proves a Reverse Cross view can retain the same snapshot and entries.
- Complete: rebuild the hardcoded Reverse Cross fixtures as a validated vertical slice over shared services and forward-compatible public/private contracts.
- Implementation complete: add bounded deterministic mask construction and positional MRV
fill, then compose generation behind the default-off
ReverseCrossGenerationfeature flag with fixture fallback, bounded concurrency, replay-derived IDs, and safe telemetry.
This ad hoc phase deliberately moves shared architectural seams ahead of full content governance so Phase 6 can build its versioned content store and ingestion workflow on the right boundaries. The Reverse Cross roadmap is authoritative for its acceptance criteria, execution history, and subsequent phases. Lexical and Game Architecture is the durable design reference for the shared catalog, game-owned layers, physical layout, and compatibility migration. Merging or deploying Phase 3 does not enable generated serving: the flag remains absent from checked-in configuration. Production startup, memory, representative load, tail behavior, replica sizing, and progressive enablement remain explicit release gates.
Phase 6 — Content governance¶
Branch: feat/content-governance
- Deny lists, allow lists, curated and themed word lists in
content, withappliesTo: ["*"]for suite-wide or specific game types. - Two enforcement points: filter at dictionary ingestion so a denied word can never appear in a generated puzzle, and reject at submit. Today the only filter is "no hyphen, no space".
- Never return the deny list to the client and never echo a matched term. Log a counter, not content.
- Replace the never-invalidated in-memory word cache with a versioned snapshot. Today the first request after a cold start downloads roughly a million words from five GitHub repos.
- Seed via a CLI or job, not a public write endpoint.
Phase 7 — Difficulty, par, courses, tournaments¶
Branch: feat/courses-and-difficulty
- Compute hardness at generation time — distinct solution count, minimum stroke count, letter
rarity, hole-in-one existence — and store it on the puzzle. This makes the hole-in-one
guarantee explicit and validated instead of an emergent property of a buggy check.
Forward reference (
fix/lettergolf-generation, landed ahead of this phase): the hole-in-one guarantee, letter rarity, and alternate-solution counting already exist —LetterGolf.HasHoleInOneis real and computed,WordSignatureIndex.FindPlayableWords+LetterFrequencyTablealready produce the raw signals this phase needs to tune.ParandDifficultyScoreare nullable placeholder fields onLetterGolf, unpopulated by that branch's generation rewrite — this phase's job is the actual tuning/formula work and wiringLetterGolfGenerationOptions' difficulty knobs (wildcards, seed-pool bias, alternate- solution bounds, guaranteed sub-par word count) to real presets, not building the mechanism. - Par tables and letter distributions live in
content, tunable without a deploy. - Courses need no schema change:
scope=course:{id}with:h{n}in the id. - Tournaments are a time-boxed course plus Phase 5 leaderboards.
- Backfill golf terminology into the UI and update
doc/lettergolf.md, which currently lists par as an open question.
Rounds and tournaments — forward-looking preview (not actionable yet)¶
Captured now (from the same user-provided design notes as Phase 5) so this design isn't re-derived from scratch when this phase starts. Nothing below is built, and no work item above depends on it.
A Round should look like a real golf scorecard, but avoid par language until this phase's par work is trustworthy — raw score totals, lower is better:
Saturday Nine
Hole 4 of 9 · closes Sunday
Your total: 14
Rank: 3rd of 8
1 2 3 4 5 6 7 8 9
2 1 3 — — — — — —
A Tournament (a time-boxed course plus Phase 5 leaderboards, per the bullet above) becomes an event dashboard:
Summer Open
Round 2 of 4 · Hole 7 of 18
Ends Friday, 8:00 PM PT
Your tournament total: 41
Current position: 12th of 46
[ Continue round ] [ Leaderboard ] [ Scorecard ]
Deliberate UX decision, not yet built: never show a player's provisional rank mid-hole. Reveal rank only after a completed hole or round — competitive comparison mid-attempt reads as anxiety-inducing rather than fun, which cuts against the goal of staying fun for players who don't care about golf at all (see Phase 5's design principles).
Once there's real round/tournament data, the personal /me scorecard gains matching sections,
e.g. Active play → Saturday Nine · Word Club → Hole 4 of 9 · You're 3rd of 8 → [ Continue ].
Cross-cutting: testing¶
Branch: test/foundation. Start alongside Phase 1.
There are zero tests in the repo today, and Controllers/, Contracts/, and
WordSources/ are empty folders.
MiniGamesBackEnd.Tests/xUnit project covering scoring, solvability, streaks, puzzle keys.- Integration tests against the Linux Cosmos emulator via Testcontainers, never the live account.
- Contract tests pinning the OpenAPI document.
- Vitest for the Zustand stores; Playwright for the LetterGolf happy path.
Code coverage reporting (2026-08-21)¶
- Coveralls deliberately deferred, not rejected. Free tier is OSS-only; this is a private repo, so it'd be a paid tool for something we can home-roll (see PR coverage comment + Azure Monitor plan below).
- SonarQube Community Build deferred, not rejected. Self-hosted (e.g. one container on the existing infra) and free for unlimited private repos, unlike Coveralls/Codecov. Gives proper coverage/quality-gate badges via its own webhook/callback model — real candidate if coverage enforcement becomes important enough to justify running and maintaining a server. Revisit if the home-rolled PR-comment + Application Insights approach stops being enough.
Implementation (jm/ci-cd-2): reusable-backend-test.yml/reusable-frontend-test.yml
collect coverage during the existing test step (dotnet test --collect:"XPlat Code
Coverage" / vitest run --coverage) and upload a single coverage-pct.txt per project as
a build artifact. ci.yml's coverage-report job then:
- On
pull_request: downloads both artifacts, reads the gist's current values as the "before" baseline (.github/scripts/coverage-comment.sh), and posts/updates one PR comment with a before/after/Δ table. WARNING (<80%) / FAILURE (>2-point drop) styling is informational only — nothing here fails the job yet; tuneWARN_THRESHOLD/FAIL_DROPor add anexit 1once real per-project targets are agreed. (Current baseline snapshot, 2026-08-21: backend ~61%, frontend ~74% — useful context for picking those targets.) - On
pushtomain: publishes the fresh numbers to the coverage gist (.github/scripts/coverage-publish.sh, badge JSON, shields.io endpoint format) and pushes aCodeCoveragecustom metric to the existing Application Insights resource (.github/scripts/coverage-metrics.sh), tagged withproject/branch/shadimensions, ready for a Portal-side Workbook/dashboard.
Required GitHub Actions secrets (repo secrets, never committed):
GIST_TOKEN— classic PAT,gistscope only (fine-grained PATs can't use the Gists API). Used only to write the two badge files in the coverage gist.APPINSIGHTS_CONNECTION_STRING— the same connection string already used by the app (azurerm_application_insights.wwwintf/frontend/analytics.tf); copy it from the Azure Portal (Application Insights resource → Overview → "Connection String") orterraform output -raw application_insights_connection_stringif that output exists. Ingestion authenticates via the instrumentation key embedded in the string — no Azure AD role assignment needed.
GITHUB_TOKEN (posting the PR comment) is the automatic per-run token and needs no setup
beyond the coverage-report job's permissions: pull-requests: write.
Frontend component and integration tests (deferred — awaiting jsdom + Testing Library setup)¶
Once test/foundation introduces component-testing infrastructure (jsdom, React Testing Library, or similar), add:
- BrandMark: correct light/dark asset shown based on resolved theme; decorative accessibility attributes (
alt="",aria-hidden="true"). - BrandHomeLink: accessible name is "Verbolus"; href is "/"; 44px min touch target; focus-visible ring.
- HeaderMenu (mobile Sheet and desktop DropdownMenu): both triggers have
aria-label; Sheet and DropdownMenu open/close/Escape behavior; focus return after dismiss; keyboard navigation through Play/Player/Company groups and god-view section; links use client-side navigation (no full page reloads). - SiteHeader/SiteFooter: rendered exactly once per route (no duplicate landmarks); footer links resolve without error; safe-area padding does not break layout on notch/unsafe-area devices.
- Manifest: GET
/manifest.webmanifestreturns valid JSON with expected icons and shortcuts; each shortcut URL loads successfully; maskable icon safe-area preview renders. - Journey (Playwright): Home → open menu → navigate to a Player or Company link → Settings → Back link returns correctly without page reload or lost scroll state.
Note: these are documented requirements, not built yet. Implement alongside or after test/foundation lands.
Out of scope¶
ReverseCross and WordSpin persistence (containers are multi-game ready, but no work is planned); multi-region Cosmos; rewriting the word-source downloaders beyond the Phase 6 caching and filtering changes.
Real authenticated identity and notification delivery were previously listed here as out of scope outright. They are no longer permanently excluded — see "Phase 8+ — social and platform backlog" below for early, not-yet-sequenced planning notes.
Phase 8+ — social and platform backlog¶
Branch: TBD. Captured now, at the user's request, so these ideas aren't re-derived from scratch later — nothing below is designed in depth, sequenced into a specific phase number, or actionable yet. Treat this like Phase 7's tournament preview: a landing spot for decisions already made in conversation, not a spec.
- Poke/nudge a friend. A lightweight, group-scoped social interaction — e.g. nudge a group member who hasn't played today's puzzle yet. Deliberately scoped to existing group membership, consistent with Phase 5's "groups are a competition context, not a friend feed" principle — this is not a new follower/social graph. Needs anti-harassment limits (e.g. one poke per pair per day) and a delivery surface: in-app notification first, push notification once that groundwork exists (below).
- Push notifications. Candidate triggers: daily puzzle reminder, "you've been poked," group
activity digest. Needs a per-notification-type opt-in model (extending the existing Phase 4
Settings page), the Web Push API plus a service worker to receive pushes, and a backend
delivery worker/queue. Depends on the PWA item below for the service worker, and benefits
from real identity (below) for cross-device delivery to the same person. This is PR 5 in the
brand/navigation rollout's PR sequence (notification identity: 96px monochrome badge export,
service-worker notification icon/badge usage, click/deep-link validation, platform test
matrix), and it must not ship without the fuller notification design already written in
doc/engagement-platform-plan.md— notification taxonomy and safe defaults, the/settings/notificationsUI, the Daily/streak-at-risk and group-nudge journeys, and campaign administration. That document also flags a shortcut-naming gap worth resolving before PR 5: it specifies manifest shortcuts forPlay DailyandPractice, while the manifest shipped in Stage 3 above usesPlay Letter Golf/Play Reverse Crossand omits Practice (no stable deep-link URL exists for a practice puzzle yet). - PWA (installable web app). The baseline manifest, icons, and shortcuts already shipped in
"Brand and navigation rollout" Stage 3 (
1f3e647); what remains is the runtime half: - A narrowly scoped service worker: precache the app shell/static assets, decide deliberately what (if anything) works offline (e.g., cache a fetched daily puzzle so it's replayable offline, but don't claim general offline support until it's actually tested end to end), and an update lifecycle so a new deploy doesn't strand users on stale cached JS.
- iOS-specific meta tags (
apple-mobile-web-app-capable,apple-mobile-web-app-status-bar-style,apple-touch-startup-image) since iOS Safari mostly ignores the web manifest for install/splash behavior. - A custom "Add to Home Screen" prompt: capture
beforeinstallprompt, suppress the default mini-infobar, and surface the prompt at an earned moment (e.g., after a completed puzzle or a return visit), not on first load. - Standalone-mode testing on real iOS/Android devices: safe-area insets
(
env(safe-area-inset-top)) on the game header/menu so content doesn't collide with notches/status bars when launched standalone. - Prerequisite for push notifications (below), since Web Push delivery needs the service worker to receive pushes; likely also improves perceived performance on repeat visits via app-shell caching.
- Do not add a service worker merely to make an installability audit turn green — scope, invalidation, and offline behavior need real design, not a checkbox.
- Real user identity / authenticated accounts. Today's anonymous
userIdcookie (the Phase 4 "anonymous-first" locked decision) needs an upgrade path to optional real accounts (e.g. email magic link or OAuth) that merges an anonymous identity into a real account rather than replacing it, preserving existing stats/streaks/group history. Unlocks cross-device continuity (today a streak is tied to one browser's cookie) and is likely a prerequisite for meaningfully targeted push notifications. The full technical design — identity provider choice, session/cookie architecture, the promote-vs-merge workflow, and a paid-subscription/ad-free-entitlement design (Stripe/Paddle, webhook handling, a newbillingcontainer) — is written up indoc/accounts-and-subscriptions-plan.md, including a proposed 8a/8b/8c sub-phase split and the open questions (IdP choice, payment processor, pricing, age policy) that must be resolved before this gets a numbered phase. - Other languages (i18n/l10n). Two independent efforts, not one: UI string localization
(framework choice, e.g.
next-intl) versus puzzle-content localization, already flagged in Phase 5's Multilingual note (puzzle language belongs to the group/event, not the player; needs alangfacet on word sources/dictionaries). Which ships first — localized UI chrome or non-English puzzles — is an open decision. - About page bios.
app/about/page.tsxcurrently only credits Jon and Justin by name. Jon and Justin each want to add a photo and a short bio about doing Wordle in ~5 languages a day and loving word puzzles, grammar, linguistics, and etymology — not yet written or designed.
Session log¶
2026-08-23 — AdSense first-review follow-up and resubmission hardening (bug/adsense-review-2)¶
The first AdSense site review did not approve Verbolus and supplied no specific policy/content
reason. The dashboard returned to Requires review, separately reported ads.txt as Not
found, and showed no Policy Center issue even though the correct root seller record was publicly
reachable. Site ownership remains verified. This evidence does not establish whether crawler
timing, content, headers, routing, cold start, or another factor caused the outcome.
Nine focused implementation commits prepared a materially improved resubmission surface:
scalable/crawlable homepage game discovery (3193865), accurate launched-game presentation
(9c8bfdc), public Terms (1fb5f6d), public/private metadata and indexing boundaries (9005768),
game-shaped loading states (848a54a), useful load/failure content with full-document retry
(b517aaa), regression coverage for the public recovery/legal flows (a4809e9), conditional
Google advertising disclosures (337bd2c), and the shared 150px gameplay-rail rehearsal
(0ed0451). The previously merged crawler fix (550aa5d) supplies explicit robots/sitemap
metadata and keeps /ads.txt outside the player-cookie proxy. Frontend validation after the latest
implementation passed 425/425 tests across 48 files, lint, TypeScript, and a production build.
This branch is not yet merged or deployed. Before re-review, deploy the reviewed revision and
follow doc/adsense-site-review-runbook.md; record production response headers/content, deployment
revision, dashboard timestamps, and the new review request. The AdSense runtime and certified CMP
remain deliberately deferred, AdsEnabled remains off, and this work does not serve ads.
2026-08-22 — Settings/Account UX consolidation, sign-out confirmation, password-change entry point, and auth telemetry (feat/account-management-ux)¶
Five commits implementing the frontend UX/discoverability follow-up to feat/auth-review, on branch feat/account-management-ux (0312c29, 6442b3c, fd737df, b91fe62, b2cac7e, f444552). Spec is doc/accounts-identity-ux-implementation-plan.md section 20 (handoff from design). Not yet merged to main, not deployed. Frontend-only; no backend or OpenAPI changes. Frontend 404/404 passing across 38 files; lint and tsc --noEmit both clean.
IA decision (section 20.2): /account remains the full identity/session manager; Settings > Account is now a concise status summary plus a link to /account, with account deletion staying at the bottom of Settings. No rename of "Settings", no "Security" heading, no direct sign-out command added to the hamburger menu — sign-out lives only on /account.
Password-change OIDC transaction (6442b3c): OidcTransactionPurpose gained a fifth value, "password". New GET /api/auth/password/start route mirrors reauth/start (same PKCE/state/nonce setup) but requires an already-verified session and defaults returnTo to /account. The callback route's new purpose === "password" branch re-proves control of the currently-signed-in account via the same real-browser-cookie /link call used by reauth, then appends a neutral passwordReturn=1 query flag on success (never a "Password changed." claim — a successful OIDC round trip is not proof Entra's hosted SSPR flow was actually used) and a new password_mismatch error code on any mismatch. The full browser-delegated Entra SSPR journey must be manually verified against the live tenant before this branch merges — this is a required human verification step, not automatable.
Auth telemetry contract (6442b3c, new frontend/minigames/src/lib/auth-telemetry.ts): single low-cardinality trackAuthEvent() covering entry surface, intent, terminal outcome, and an optional reason code, dual-emitting through both existing GA and App Insights pipes. Explicitly excludes any PII (email, display name, issuer/subject, tokens, cookies, free-form provider errors). Wired at every account-affecting action across Settings and /account: delete-account (confirm/cancel/success/failure), sign-out (confirm/cancel/success/failure), and OIDC-callback terminal outcomes (add-method, change-password, and the shared account_changed/mismatch error paths).
Callback authIntent hint (fd737df): the account_changed error code is shared across the link/reauth/password purposes' boundPlayerId mismatch check, which would otherwise leave client-side telemetry guessing which action was in progress. redirectWithError now accepts an optional intentHint appended as authIntent on the redirect, so /account's status region can log the correct intent without ambiguity.
Settings Account section (b91fe62): new server-derived SettingsAccountViewModel (settings/page.tsx) computes guest/verified/expired status, feature-flag gating, and a client-safe sign-in-methods summary (only providerCategory/maskedLabel ever reach the browser) independently of the AccountsUi flag, so the guest-vs-verified deletion wording fix applies to everyone. settings-form.tsx now renders per-status copy (expired hides methods and deletion entirely; guest/verified render a flag-gated summary plus an always-visible "Danger zone"), and a verified session with a failed or empty methods fetch shows "Sign-in methods are temporarily unavailable." rather than silently looking like a guest. New shared frontend/minigames/src/lib/identity-providers.ts (getProviderCategoryLabel) removes a duplicated label switch from sign-in-methods.tsx.
/account region refactor (b2cac7e): new client component account-status.tsx owns the one-time success/error notice below the heading — reads the callback's query flags, fires the matching telemetry event exactly once per mount, and strips the transient query params via router.replace so a refresh doesn't repeat a stale message. sign-in-methods.tsx fixed a real bug (handleSignOut previously redirected without checking response.ok) and replaced the bare sign-out button with a confirmation dialog (neutral outline styling, not destructive-red; "Your Verbolus account and saved progress will remain..." copy; disabled/pending state while in flight; never navigates before the response succeeds). The method list gained an independent "unavailable" state that never hides the Add/Switch/Sign-out actions below it. The Local method row gained a "Change password" link to the new password-start route; other provider rows are unaffected.
Explicitly deferred, per the design handoff (not implemented this round):
- Contextual guest prompting / discovery ladder (spec section 20.7). A staged nudge toward account creation for guest players, explicitly not a first-visit home banner: (1) persistent-but-quiet — Account already in the menu/Settings, done; (2) intentional — a small guest-status card on Scorecard/Groups pages, not built; (3) contextual — one dismissible prompt after a completed puzzle/streak/group activity, shown at a natural pause and never over the game board ("Keep your progress across devices" / "Create account or sign in" / "Not now"), not built; (4) required-later — only subscription checkout would ever force sign-in, not applicable yet. Must never trigger off cookie age/page-views/a timer, and verified users must never see it. Deferred because Sol's spec says "do not block the branch on a first-home banner" — pick this up once the Settings/
/accountmanagement surfaces (this branch) have been live for a while. - The header's
AccountsUi-flag-driven brief Account-link flash on load (section 20.8) — accepted as a tradeoff during targeted rollout, no code change planned.
Testing (f444552): new account/sign-in-methods.test.tsx (14 tests: label/link rendering per provider category, unavailable-state independence from Add/Switch/Sign-out, full sign-out confirm/cancel/success/failure telemetry and dialog-state assertions, only-method Remove-disabled invariant) and account/account-status.test.tsx (7 tests: each query-flag branch's message/role/telemetry, authIntent hint honored vs. its fallback, no-op render with no PII in asserted telemetry payloads). Extended settings/settings-form.test.tsx with 5 new cases covering guest/verified/verified-with-unavailable-methods/expired renders and the feature-flag-gated summary vs. always-visible danger zone.
2026-08-22 — Sign-in ownership enforcement, cascading account deletion/export across merge-alias closures, and boundPlayerId session-binding (feat/auth-review)¶
Six commits hardening backend identity trust boundaries and closing a frontend session-binding gap, on branch feat/auth-review (backend: c06eb65, bee738d, d16ccfb; frontend: 96651c6, df85e29, 28d65d1). Not yet merged to main, not deployed.
Backend — sign-in commit ownership enforcement (c06eb65): IdentitySignInService.CommitAsync now requires a callerUserId argument and throws a new IdentityAttemptOwnershipMismatchException when it doesn't match the attempt's original SourceUserId. InternalIdentityEndpoints's Commit handler maps that exception to 404 Not Found (not 403), so a mismatched caller can't distinguish "wrong owner" from "attempt doesn't exist." Closes a gap where any caller who could guess/observe an attemptId could previously commit someone else's sign-in attempt.
Backend — cascading account deletion and export across merge-alias closures (c06eb65, d16ccfb): New AccountDeletionService.DeleteAccountAsync resolves the caller to its canonical root, then deletes every play, external-identity lookup, and player document for the entire merge-alias closure (root plus every alias merged into it) — not just the caller's own document. PlayerEndpoints.ExportMe now aggregates plays across that same closure, with each PlayExportEntry tagged with a new OwnerUserId so exports show which alias a given play actually belongs to. PlayerExportResponse also gained SignInMethods (reusing the existing masked SignInMethodSummary DTO). Both features previously would have needed their own closure-resolution logic; d16ccfb consolidated it into a single PlayerMergeService.ResolveAliasClosureAsync (alongside the existing ResolveCanonicalRootAsync) so deletion and export can never disagree about which users make up an account.
Frontend (96651c6, df85e29, 28d65d1):
- Desktop dropdown menu (
header-menu.tsx) now right-aligns (align="end") instead of overflowing off-screen. - Legacy host-only-domain (
domain=verbolus.com, no leading dot) cookie cleanup now runs unconditionally at the top ofproxy.ts'sinitializeCookies, fixing a bug where it was placed after an early return and so never ran for the majority of returning users with an already-valid signed cookie. - New
boundPlayerIdenforcement on the OIDC callback route:purpose=linkandpurpose=reauthcallbacks now verify the current session cookie'sPlayerIdmatches the OIDC transaction'sboundPlayerId(captured at/link/start//reauth/start), redirecting withauthError=account_changedif the session is absent or belongs to a different player. This is defense-in-depth against the session cookie changing mid-flow (e.g. a second tab signing out/in); the field was previously captured but never enforced. Newaccount_changederror message added to/account.
Testing: Backend — IdentitySignInServiceTests.CommitAsync_CallerDoesNotMatchSourceUserId_Throws, InternalIdentityEndpointsTests.Commit_CallerDoesNotMatchAttemptSourceUserId_ReturnsNotFound, PlayerDataExportEndpointsTests.ExportMe_MergeAliasClosure_AggregatesPlaysWithOwnerUserId, PlayerDataExportEndpointsTests.DeleteMe_MergeAliasClosure_CascadesDeleteAcrossAllAliasesAndRemovesLookup. Frontend — four new callback/route.test.ts cases covering the boundPlayerId mismatch/absent-session scenarios for both link and reauth purposes. Backend 460/461 passing (1 pre-existing unrelated flaky test, TestLetterGolfGeneratorTests.GetLetterGolfAsync_MinTotalLetterOccurrences_RejectsShortWords, documented in /memories/repo/known-flaky-tests.md); frontend 378/378 passing across 35 files; lint and tsc --noEmit both clean.
2026-08-22 — Accounts: multiple sign-in methods and session management (feat/accounts-methods-sessions)¶
Three commits implementing Phase 3 "multiple sign-in methods" and Phase 4 "sessions, sign-out, switch, recovery" foundations on branch feat/accounts-methods-sessions. Not yet merged to main, not deployed. Covers account UI, sign-in-method management, session-aware routing, and comprehensive test coverage. Backend 456/457 tests pass (1 unrelated pre-existing flaky test); frontend 371/371 passing, lint and typecheck clean.
Backend (commit 00cba2c): new IdentityDisplayHelpers service categorizes OIDC issuer into friendly categories (Local/Google/Microsoft/Facebook/Other) and masks personally-identifying info for safe frontend display (e.g., maya@example.com → m***@example.com, mayaRodriguez → ma***). Extended SignInMethodSummary contract with non-masked Issuer and Subject fields (stable OIDC identifiers used for targeting specific identities in remove/unlink operations). New POST /v1/internal/identity/unlink endpoint deletes a linked external identity; returns 200 on success, 400 with {Removed:false, Error:"last_method"} if it's the player's only remaining sign-in method (guard, not an error), 404 if issuer/subject not linked to caller. Enhanced PlayerMergeService to power unlink/link/merge operations with ETag-based idempotent retries.
Frontend (commit ce071ae): new OIDC transaction cookie field purpose: "sign-in" | "link" | "reauth" | "switch" routes callback logic through /api/auth/callback/route.ts branches. Four new purposes (link/reauth/switch beyond the existing sign-in):
- link: add additional sign-in method to current account. If identity already linked to different account, redirect to new
/account/link-conflictpage (merge preview with play/group counts, confirm/cancel). - reauth: re-prove identity control (required before removing a method if session older than 15 minutes). Mints fresh session cookie with new IssuedAt on success.
- switch: sign in as different account without guest-data carryover. Uses synthetic never-persisted cookie for backend calls.
- New routes:
/api/auth/link/start,/api/auth/reauth/start,/api/auth/switch/start,/api/auth/sign-out,/api/auth/unlink,/api/auth/link/merge. - New account UI (behind
AccountsUifeature flag, per-userId Azure App Configuration targeting): Sign-in methods section on/accountlisting linked methods with Remove button (disabled when only remaining), Add/Switch/Sign out buttons;/account/link-conflictpage for merge preview; nav hamburger menu conditionally shows Account link. - Extended
auth-flow-cookies.tsandsession-cookie.tsfor new transaction fields (purpose,boundPlayerId,isRecentlyAuthenticated) with backward-compatible decoding of legacy cookies.
Testing (commit ae30ad3): new IdentityDisplayHelpersTests.cs (123 lines) covering display-helper logic. Enhanced InternalIdentityEndpointsTests.cs (136 new lines) covering /unlink endpoint's 401/403/400/404/200 outcomes. Extended PlayerMergeServiceTests.cs (125 new lines) covering unlink happy path, last-method guard, not-linked case, and ETag-conflict retry. Frontend added auth-flow-cookies.test.ts (82 lines) and session-cookie.test.ts (39 lines) testing new cookie fields and backward compatibility, plus new callback/route.test.ts (215 lines) covering purpose-based branching (link/reauth/switch outcomes) with mocked OIDC and internal-identity-client dependencies — closes previous complete test-coverage gap on callback routing, the most risk-laden new logic in this phase.
Explicitly not done this phase, per the plan:
- Phase 3 "change password/email handoffs" — not implemented.
- Phase 3 "account-collision merge" — handled via link-conflict page redirect instead of failing silently, but the full dual-account merge experience awaits Phase 5's deletion/export/privacy work.
- Phase 3 "billing-aware canonical selection" — no billing system exists; "inactive/default state" acceptable per plan.
- Phase 4 "password/provider recovery copy and session-expiry UX" — not done.
boundPlayerIdfield captured on OIDC transaction at/link/startand/reauth/startis write-only; not yet enforced/read in callback routing. Not a security gap (backend always derives acting player from real session cookie, never client state), but known follow-up.- Not merged, not deployed, not pushed.
2026-08-17 — 14-day puzzle pre-generation and god-view date-browse spoiler deterrent¶
14-day rolling-horizon puzzle pre-generation plus a date-scoped debug-solutions endpoint with spoiler-tracking consequences, merged on jm/past-future-puzzles (backend commits e7e698e, 72939a0, 04ecc32, 7c8e8a9; frontend commit 3bc2aa2; tests 814df8d; docs 61c84b4). Not yet deployed to production — Terraform apply requires separate explicit approval per AGENTS.md.
Feature 1: 14-day puzzle pre-generation. New LetterGolfDailyPreGenerator service (14-day horizon, idempotent, skips dates already generated, continues past per-date failures) keeps the next 14 calendar days of global daily puzzles pre-generated, so an admin can preview/playtest upcoming puzzles via god-view before they go live. Triggered manually via a new POST /v1/letter-golf/daily/pregenerate endpoint (X-Admin-Key gated, 404 on auth failure, no completion-required gate) as an operator escape hatch, and automatically via a new scheduled Azure Container Apps Job (tf/backend/pregeneration_job.tf, daily at 09:00 UTC via curl) that calls the endpoint. Response shape: {horizonDays: 14, successCount: N}. The existing lazy-on-first-request LetterGolfDailyPuzzleProvider.GetOrCreateDailyAsync remains the permanent fallback if pre-generation ever falls behind — both paths write the same puzzles container schema, so the fallback is transparent to the client.
Feature 2: God-view date-browse with spoiler deterrent. New date-scoped endpoint GET /v1/letter-golf/daily/{date}/debug-solutions (date param format: yyyy-MM-dd) lets a DebugSolutions-flag-gated user preview any date's daily puzzle solutions without a prior-completion requirement (unlike the existing per-puzzle GET /v1/letter-golf/{puzzleKey}/debug-solutions). Returns LetterGolfSolutionsResponse (same shape as the existing solutions endpoints: puzzleKey, seedWord, solutions), or 404 if the flag is off OR the date hasn't been pre-generated. Spoiler consequence: browsing another date's solutions before completing that date's daily play sets PlayEntity.SolutionsViewedBeforeCompletion = true on the caller's play (creating a pre-spoiled stub if none exists yet), which causes PlayerStatsCalculator/PlayerStatsUpdater to exclude that play from personal stats/streaks entirely when/if it's later completed — same treatment as practice-scope plays. Group standings are explicitly NOT affected by this flag (deliberate design constraint to keep group competition clean). Frontend god-view-dialogs.tsx shows Previous/Next day buttons (daily mode only, not practice) with a one-time-per-dialog-session window.confirm() warning before the first navigation, that explains the stats consequence to the tester.
Backend test files added: GetDebugSolutionsForDateEndpointTests.cs (endpoint gating, date parsing, spoiler flag creation/idempotency), LetterGolfDailyPreGeneratorTests.cs (14-day horizon generation, skip already-generated, continue past failures), PreGenerateDailyEndpointTests.cs (admin-key gating, response shape), and additions to PlayerStatsCalculatorTests.cs (exclusion of spoiled plays from stats/streaks). Manual QA plan documented in doc/godview-date-browse-test-plan.md.
2026-08-16 — Brand and navigation rollout (PR 1-3) completed on feat/prep-adsense¶
Documentation-only pass. Three frontend-only commits implementing shared identity and navigation components, shipped on the same branch as the AdSense compliance work: home-link primitives and menu regrouping (PR 1, fd24e8e), shared header/footer and route migration (PR 2, 0ac2fcd), and favicon/Apple touch icon/PWA manifest wiring (PR 3, 1f3e647). All work frontend-only; no backend, contract, or Terraform changes. This work was later merged to main.
2026-08-15 — Group Today standings now show every member; group-scoped member detail page¶
Frontend-only, jm/ui-fixups; no backend/contract change (GroupResponse already had both
members and todayStandings.entries). Prompted by user-provided design notes (referred to as
"the Terra notes" like the rest of this Phase 5 section) pointing out that a member with no
standings entry yet (hasn't started today) was silently missing from the list entirely, instead
of reading as a neutral "Not played".
src/lib/standings.ts(new, pure logic, unit-tested):buildStandingsRows(members, entries)builds one row per current group member — not per standings entry — defaulting a missing entry toNotPlayed/no score. Sorts Completed ahead of Playing ahead of Not played, and assigns skip-style ranks (ties share a rank; the next distinct score resumes at its true position, e.g. 1, 1, 3) to Completed rows only — Playing/Not played members are never ranked.summarizeStandingsanddescribeOrdinalback the "1 of 3 members finished"/"Tied for 1st" copy. 17 Vitest cases cover all-members-render, missing-entry-defaults, score sorting, and the never-ranked-unless-Completed rule.event-standings.tsx(new): the reusable rendering component, deliberately generic (label/languageprops, not a Daily-specific name) so a future Hole/Round/Tournament event can reuse it without a rewrite — Today just passeslabel="Global Daily". Each row is a link to the new member detail route (not a public profile), shows rank-or-em-dash, name, "(you)", and text status (never color alone), with amin-h-11touch target.groups/[groupId]/page.tsx: replaced the old sparse standings block (which only rendered members with a materialized entry) withEventStandings; the "you finished with N" card is gone since the component's own viewer-relative summary line now covers it, leaving only the actionable Play/Resume CTA for non-Completed viewers.groups/[groupId]/members/[userId]/page.tsx(new route): group-scoped member detail — access gated purely by group membership (fetchGroupalready 403s/404s a non-member; no public/users/[userId]profile exists to fall back to). Shows only data already on the group response: display name, today's Completed/Playing/Not played state, and group context ("TestGroup2 · Global Daily"). At the time, a "Group-visible stats" placeholder deliberately avoided inventing a numeric streak from data the API did not supply. The 2026-09-10 increment below replaced that placeholder with the selected game's current Daily streak; games played, average score, word history, and the person's own/mescorecard remain private unless a future sharing design says otherwise.nudge-member-button.tsx(new, not imported anywhere): scaffolds the future "Nudge Maya to play" affordance's props/shape per the Terra notes' nudge design, rendered disabled with an explanatorytitle. Deliberately not wired into the member detail page — there's noPOST /v1/groups/{groupId}/events/{eventKey}/members/{userId}/nudgeendpoint, one-per-event enforcement, or recipient opt-out setting yet, and a button that claims to notify someone with none of that behind it would be actively misleading.- Testing infra: this is the first frontend test in the repo, so added
vitest(pure-logicnodeenvironment only — no jsdom/React Testing Library yet, since nothing here needs to render a component) as a devDependency and annpm testscript, pertesting.instructions.md's existing guidance to prefer Vitest when adding frontend tests.
Deliberately not done, per the Terra notes' own scope boundary: no Events/Rounds/
Tournaments tab or generic event API — EventStandings is shaped to be reusable later but
Phase 5 still only ever calls it with the Global Daily. The Members tab (full roster with
Owner badge/remove button) is unchanged; only the Today standings rows link to the new member
detail route.
2026-08-15 — Cross-cutting observability Tier 1 applied; god-view debug menu shipped; merged to main¶
terraform apply run for Tier 1 (approved): 3 resources added
(azurerm_application_insights.www, azurerm_app_configuration.api, the API's App
Configuration Data Reader role assignment), 1 changed (backend Container App picked up the new
ApplicationInsights__ConnectionString/AppConfig__Endpoint env vars), 0 destroyed.
Granted the developer's own Entra identity two ad hoc (not Terraform-managed) data-plane roles
needed to create/target flags and look up userIds by hand: Cosmos DB "Data Reader" scoped to
/dbs/minigames, and App Configuration "Data Owner" scoped to minigame-api-config. Same
control-plane/data-plane split documented in Phase 2 — subscription-level Owner/Contributor
grants neither.
Created and targeted the first three real flags per the runbook above — PuzzleMetadata,
DebugSolutions, ResetDaily — aimed at four userIds. Hit a Windows-only
az appconfig feature filter add --filter-parameters bug where embedded JSON double quotes get
silently stripped regardless of escaping strategy (backslash-escaped, single-quoted variable,
.ps1 file); worked around by calling the App Configuration data-plane REST API directly
(PUT {endpoint}/kv/{key}?api-version=2023-11-01 with a Bearer token from
az account get-access-token --resource https://azconfig.io). Documented in repo memory as the
go-to method until the CLI bug is fixed upstream.
Shipped the first concrete consumers of those three flags:
- Backend (
79217ef):GET /v1/letter-golf/{puzzleKey}/debug-solutions(gated onDebugSolutions, requires the caller to have already completed a non-practice puzzle, 403 otherwise) and aResetDaily-gated bypass on the existing admin-key-onlyResetPlay(still only ever deletes the caller's own play). - Frontend (
7eb83ff): a hidden "god-view" section in the hamburger menu —lib/features.ts(fetchFeatures, never throws),use-god-view.ts(dialog/reset state),god-view-dialogs.tsx(metadata + solutions modals) — with up to three items (Puzzle metadata, Debug solutions, Reset today's play) each independently gated by its own flag fromGET /v1/features, invisible to everyone else.
Both commits merged to main via 17293bb. The backend and frontend images were rebuilt,
pushed to ACR, and deployed to their Container Apps via update_image.ps1 (run from Windows
PowerShell — the WSL Bash equivalents needed docker exposed via Docker Desktop's WSL
integration and apt install git-lfs for git push, both since resolved locally). Confirmed
working in production the same day: telemetry and feature-flag evaluation are live, and the
god-view menu behaves correctly for targeted users.
2026-08-14 — Cross-cutting observability Tier 1 implemented (feat/obs-start)¶
Follow-up to the same-day docs-only planning pass below — implemented Tier 1 on
feat/obs-start. Not yet applied/deployed: Terraform has been written and validated
(terraform validate, fmt) but not run (terraform apply needs explicit approval per
AGENTS.md), so none of this sends real telemetry or evaluates real flags until that happens.
Backend: added Azure.Monitor.OpenTelemetry.AspNetCore, Microsoft.FeatureManagement, and
Microsoft.Extensions.Configuration.AzureAppConfiguration NuGet packages. Program.cs wires
UseAzureMonitor (fail-soft in Development, fail-fast elsewhere if the connection string is
missing) and Azure App Configuration + Feature Management with a TargetingFilter keyed on the
existing userId cookie (HttpUserIdTargetingContextAccessor.cs). Added GET /v1/features
(server-side flag evaluation only — never exposes the targeted audience list). Hand-instrumented
three Activity spans via a new shared Telemetry.ActivitySource
(WordList.ColdStartLoad, LetterGolf.DailyPuzzleGeneration, Groups.StandingsBackfill). All
227 existing backend tests still pass; dotnet build clean.
Terraform: azurerm_application_insights.www added to tf/frontend/analytics.tf
(workspace-based, attached to the existing Log Analytics workspace, connection string exposed as
a sensitive module output). New tf/backend/feature_flags.tf adds
azurerm_app_configuration.api (Free tier, local_auth_enabled = false) plus an
azurerm_role_assignment granting the API's identity read-only "App Configuration Data Reader".
Both wired into the backend Container App's secrets/env vars in tf/backend/container_app.tf.
terraform fmt/validate clean (pre-existing azurerm_log_analytics_workspace deprecation
warning aside); no plan/apply run.
Frontend: added @microsoft/applicationinsights-web. New src/app/app-insights.ts
(initAppInsights/trackEvent, connection string baked in at Docker build time via a new
NEXT_PUBLIC_APPLICATIONINSIGHTS_CONNECTION_STRING build-arg, empty/no-op until the Terraform
above is applied) and components/app-insights-provider.tsx, mounted in layout.tsx next to
CookieBanner. Gated behind the existing cookie-consent gate: cookie-banner.tsx now broadcasts
a CONSENT_CHANGE_EVENT on grant/deny (a small refactor extracting getStoredConsent() into
analytics.ts, shared by GA and Application Insights) so a same-session consent grant enables
telemetry without a page reload, not just a future page load. The SDK auto-collects page-load
timing and unhandled errors once initialized, so the existing GA exception listeners were left
alone rather than duplicated. lint, tsc --noEmit, and next build all clean.
Deliberately not done, per the plan's own scope: Next.js SSR/Server Action tracing (still
flagged as a research spike — Next.js 16's instrumentation API needs verification before writing
that code); frontend consumption of GET /v1/features (no concrete gated button/feature exists
yet to justify it — add it alongside the first real flag); anything in Tier 2/Tier 3.
2026-08-14 — Cross-cutting observability phase written down¶
Docs-only pass, main. Phase 5 confirmed merged/done — a deliberate pause here before Phase 6/7
feature work, to give room for an offline feature-planning meeting, playtesting, and competitive
analysis, and to get a telemetry/feature-flag baseline in before more surface area ships.
Researched current state first: GA4 was already wired (G-1Y5XWM30YM, consent-gated, tracks
share/exception events) — the "Google Analytics Terraform file" half-remembered turned out to
be tf/frontend/analytics.tf, which actually provisions an Azure Log Analytics workspace
(workspace-larmingsn15), unrelated to GA4. Confirmed no Application Insights/OpenTelemetry, no
feature-flag framework, and no crash-reporting service exist yet, but health checks, structured
ILogger calls, and rate limiting are already solid.
Added a new "Cross-cutting: observability" section (table row placed right after Phase 5,
alongside the existing "Cross-cutting: testing" pattern) instead of a numbered phase —
renumbering Content governance(6)/Difficulty(7)/backlog(8+) would also require editing ~15
hardcoded // TODO(Phase 6): / "Phase 7" code comments in IWordListProvider.cs, Program.cs,
LetterGolf.cs, and TestLetterGolfGenerator.cs, not just roadmap headings — not worth the diff
for a label, confirmed with the user.
Locked decisions: Application Insights via OpenTelemetry for system telemetry (backend +
frontend), attached to the existing Log Analytics workspace rather than a new one; Azure App
Configuration Feature Management (not PostHog, not a homegrown allowlist) for feature flags and
alpha/beta targeting, using its TargetingFilter keyed on the existing durable userId to gate
a feature to specific people; GA4 demoted to marketing/traffic-only, with new product-behavior
events (clicks, feature usage) moving to Application Insights custom trackEvent calls instead.
PostHog was explicitly deferred, not rejected — flagged as the tool to revisit once real A/B
experiment analysis, click heatmaps, or session replay are actually wanted.
Structured the new section into three tiers: Tier 1 (build now — App Insights OTel wiring
for backend and frontend with correlated tracing, hand-instrumented spans around known slow
operations like cold starts and puzzle generation, click tracking via trackEvent, and Azure App
Configuration + TargetingFilter + a new GET /v1/features endpoint for flags), Tier 2
(professional backlog, not built: Live Metrics habit, availability tests, Azure Monitor alert
rules piped to the existing Slack deploy webhook, PostHog reconsideration, KEDA/latency
correlation, sampling tuning), and Tier 3 (overkill backlog, not built: multi-region tracing,
SLO dashboards, synthetic journey monitors, Grafana, long-term log retention, load-testing harness
in CI). Tier 1's actual implementation (NuGet/npm packages, Terraform resources, code) is a
future coding session — nothing beyond this roadmap doc changed.
2026-08-08 — Groups standings backfill, UI polish batch, scorecard-loading flicker, image/tag cleanup¶
Several small, independent fixes landed in quick succession after the Phase 5 UI merge, closing
out this push. Branches fix/groups-standings-backfill and inline fixes on main.
- Groups standings backfill (
GroupStandingsUpdater.GetStandingsWithBackfillAsync): standings were only ever written by live fan-out from autosave/submit events, so a member who completed (or started) today's puzzle before joining the group — or before the group even existed — never showed up, with no way to self-correct. For any member missing a standings entry, point-read their own play (IPlayStore.GetAsync("{puzzleKey}|{userId}")) and synthesize+persist a Completed/Playing entry through the same bounded ETag-retry write path the live fan-out already uses; an existing entry is never overwritten, and a member with no play at all correctly stays absent. Wired into bothGetGroupDetailandGetMyGroups. Cost self-amortizes: only the first load per group per day pays for the extra point reads, since later loads see the entry already persisted. New unit and end-to-end coverage. - Three UI layout fixes, all root-caused via code tracing rather than guesswork:
- Owner's "⋮" group menu floated centered between the group name and hamburger menu instead
of sitting next to the hamburger — it was being passed through
Header'schildrenprop, which is deliberately centered (used elsewhere for things like the mode-switch row). Added a new right-alignedactionsprop toHeader, distinct from the centeredchildrenslot, and movedGroupOwnerMenuonto it. - The Letter Golf Victory overlay used
fixed inset-8with no max-width, border, or backdrop, so it read as a rendering glitch on large desktop monitors (near-fullscreen with no visual separation from the page behind it) despite looking fine on phones. Restructured into afixed inset-0semi-transparent backdrop (bg-black/40) containing a centered card capped atmax-w-md/max-h-[85vh], with a themed border (border-gray-300 dark:border-gray-600, matching the convention used elsewhere) and a shadow. Phone rendering is essentially unchanged sincemax-w-mdstill nearly fills a typical phone viewport. - The practice-mode "regenerate puzzle" icon button looked vertically misaligned against the
Daily/Practice mode switch next to it — caused by a redundant
mb-4onModeSwitch's own root div (on top of the parent row's own bottom margin), which inflated its flex margin-box height relative to the sibling button underitems-center. Removed the redundant margin. - Scorecard loading flicker: the
/meloading skeleton showed a plain gray "← My scorecard" placeholder that didn't match the real page's blue, underlinedBackLink("← Back"), so the Suspense-fallback-to-real-content swap caused a jarring color/text/spacing jump. Made the skeleton's placeholder match the real link's classes and text exactly. - Image/tag cleanup chore (
update_image.sh, both backend and frontend deploy scripts): after each deploy, remove the just-pushed image's local Docker tags (already pushed to ACR and deployed, so no longer needed locally), prune the Buildx cache down to a 2 GB cap, and delete old ACR repository images beyond the five newest (viaaz acr repository show-tags--queryJMESPath sorting, avoiding ajqdependency). Keeps local disk and the remote registry from growing unbounded across repeated deploys.
2026-08-08 — UI fixes batch (bugfix/ui-fixes)¶
Merged to main. Grab-bag of small, independent frontend fixes plus one perf fix, found while
using the app during the Phase 5 UI work above.
- Homepage greeting moved client-side (
greeting.tsx): the player-name fetch was Suspense-wrapped on the server, but Next still had to flush that boundary's fallback before sending any HTML, so a cold-starting backend (loading its word lists) delayed the entire homepage shell. Moving the fetch into a client component makes the server response and game cards fully independent of backend latency — the greeting always renders "Verbolus" first and swaps in the display name only if/when the client fetch resolves. - Practice-mode loading skeleton no longer shifts the header to mid-screen: the game view's
outer container used
justify-center, vertically centering the whole flex column (Header, mode tabs, countdown, board) as a group. During real play the board fills the viewport so this had no visible effect, but the much shorter loading/expired states got pulled toward the vertical middle instead of staying pinned at the top. Also widened the practice-loading skeleton frommax-w-mdtomax-w-[600px]to match the real board width, avoiding a resize when the skeleton is replaced. Headeralways spans full width: it only stretched full-width when a caller passedclassName="w-full ..."(as game views do). Pages renderingHeaderwithout a className (/groups,/groups/create,/groups/join,/groups/[groupId]) got a shrink-to-fit box, so the absolutely-positioned title and menu button collapsed toward each other and overlapped. Madew-fullunconditional onHeaderitself.- Removed duplicated header buttons on the empty Groups state: with zero groups, both the header's own "+ New group"/"Join a group" buttons and a second, bigger pair in the centered empty-state message showed the same two actions stacked on top of each other. The header actions now only render once there's at least one group.
- Added an icon to the practice-mode "regenerate puzzle" button (previously text-only/unclear).
2026-08-08 — Stale letter-animation fixes and DisplayName surfacing (bugfix/stale-letter-animations)¶
Merged to main.
- Stale-target-count flash and duplicate-key remount corruption (Letter Golf board):
TargetLetteranimates by diffing its count prop against a remembered previous count, so switching puzzles (Daily↔Practice, or a new practice puzzle) needs a full remount — otherwise the old puzzle's target counts briefly looked like a just-played word. Two compounding bugs: (1) the store'sinitialize()for the new puzzle only ran in auseEffectafter the remount committed, so a freshly-mountedTargetLetterstill saw the old puzzle's counts for one render; fixed by callinginitialize()synchronously alongsidesetActivePuzzle. (2)GameV1ViewandVictoryOverlayare siblings that both usedkey={activePuzzle.puzzleKey}— duplicate sibling keys are undefined behavior in React and were confirmed to cause a stale, already-mounted board/victory pair to stick around alongside the new one (a duplicated board and a spurious Victory overlay when switching back to Daily). Fixed with distinctboard-/victory-key prefixes. - Scorecard/Settings back link respects real navigation history:
/meand/settings's back affordance was a hardcodedLinkto/, so opening either page from inside a game (or anywhere reachable via the header menu) and clicking "back" always dumped the user on the landing page. NewBackLinkcomponent callsrouter.back()when same-tab history exists, falling back to a plainLinkto/(still works with JS disabled) otherwise. DisplayNamesurfaced throughGET /v1/players/me: it was previously only readable via the settings endpoint, so nothing outside the Settings form itself could greet a player by name. Added toPlayerResponse(no extra Cosmos read — sourced from the same entity already loaded forGetMe), covered by two new integration tests. Frontend: homepage greeting and the Letter Golf Victory overlay headline are personalized when set. (Groups already showed aDisplayName, but as a snapshot copied onto the group/standings entity at join/play time, independent of this change.)
2026-08-08 — Phase 5 frontend UI merged to main (feat/groups-social-ui); URL-addressable practice puzzles¶
- Groups/Social frontend UI (Phase 5 step 3): landing page, create/join forms, per-group
Today/Members tabs, owner actions (rename/regenerate join code/remove member), and a
post-victory "View standings" link on Daily wins.
lib/groups.tsmirrors the backendGroupResponse/GroupSummaryResponse/GroupStandingsResponsecontracts, following the sameapiFetch/cookie-forwarding pattern aslib/players.ts. Today/Members navigation uses plain links witharia-currentrather than a WAI-ARIA tablist, since each "tab" is a real route, not a JS panel swap. No backend/contract changes — consumes the/v1/groups/*API merged in the prior backend chunk. - URL-addressable practice puzzles and context-aware Victory overlay: added a public
GET /v1/letter-golf/{puzzleKey}endpoint (unauthenticated by design, matching the existing pattern that puzzle letters/wildcards/par aren't secret) so a practice puzzle survives a page refresh via?mode=practice&puzzle={puzzleKey}instead of reverting to Daily. An expired or invalid practice puzzle now shows a friendly message with actions to start a new one or play Daily, instead of a dead end. The Victory overlay is context-aware for Practice: title "Practice complete", no share buttons (a recipient can't play the same practice puzzle), and two actions (start another practice puzzle, or switch to Daily); the Practice-win stat label was also corrected from the misleading "Your best score" to "Best Daily score", since Practice plays don't yet update that counter. - Practice mode shows a loading skeleton while switching: fetching a fresh practice puzzle
(on-demand generation, or a cold-started backend) previously gave no feedback and looked hung.
Added a spinner/shimmer skeleton matching
/me's loading look, disabled the mode-switch tabs for the fetch's duration, and guardedstartNewPracticeagainst re-entrancy directly. - Infra: raised the backend Container App's scale-to-zero cooldown from 5 to 30 minutes
(
tf/backend/container_app.tf) — this API builds large in-memory word-list dictionaries on startup, so every scale-from-zero is a slow cold start, increasingly painful while playtesting with more people. Trades a bit more idle compute for fewer cold starts; not yet applied viaterraform applyas part of that commit. Min/max replica counts (0/2) are unchanged.
2026-08-08 — Phase 5 design written down (Groups and social)¶
Branch feat/groups-social, docs-only commit before any backend/frontend work starts.
Expanded this roadmap's Phase 5 section from four bullets into the full design worked out with
the user from external ("Terra") design notes plus a group-detail mock screenshot: the
Play/Hole/Round/Tournament/Group hierarchy to preserve, the groups-as-competition-context (not
a friend feed) principle, the Today-page-not-feed structure, completion-state vocabulary, the
global-vs-group-specific puzzle format table (Phase 5 ships global-daily-only), the concrete
groups/lookups container schema and best-effort standings fan-out model (mirroring
PlayerStatsUpdater's idempotent/ETag-retry pattern), caps/rate-limit decisions, owner/member
roles, and an explicit "what not to build yet" list. Also added a forward-looking,
non-actionable preview of Rounds/Tournaments to Phase 7 so that design isn't re-derived from
scratch when that phase starts. No code changed in this pass — backend plumbing (new Cosmos
containers, entities, endpoints) is the next chunk, pending the user's go-ahead.
2026-09-10 — Group-visible current streak (private groups)¶
Branch feat/stats-sharing-1. First increment of cross-member stats visibility in groups.
Implements current Global Daily streak as a group-shared projection for Letter Golf and
Reverse Cross, visible only to group members within private-group contexts.
- API contract: authorized
GET /v1/groups/{groupId}detail responses now include asharedStats.currentDailyStreakDaysfield (nullableint?) per member. A streak is active only when played today or yesterday on the Pacific Daily calendar; stale stored counters project as zero. Null is reserved for a future visibility choice that hides the metric. - Data access: one bounded Cosmos read-many request (up to 50 group members across their player partitions) avoids N+1 queries across all members' player documents.
- Frontend standings: positive streak displays as subdued secondary-line text in the Player
cell, e.g.,
12-day streakbeneathMaya. One row/link per member preserved; Score and Time remain focused on today's event. - Frontend member detail:
/groups/[groupId]/members/[userId]shows the current streak alongside completed/playing/not-played state; renders a neutral no-active-streak indicator for visible zero. - Boundaries: no public
/users/[userId]profile created. Games played, average score, longest streak, word history, full scorecard, and other lifetime stats remain private. Next expansion requires explicit toggleable visibility. The subsequent 2026-09-12 design chose per-game sharing enabled by default with opt-out and coarse per-group overrides. - Open decision resolved: group-visible by default within private groups (closed on 2026-09-10); broader stats sharing mechanics deferred.
2026-09-12 — Persistent Stats Sharing (feat/stats-sharing-2)¶
Complete on the branch; not yet merged to main or deployed. This increment replaces the frontend-preview design with an authoritative end-to-end implementation:
- Player settings persist per-game detailed-scorecard defaults and coarse per-group overrides; authenticated GET/PATCH endpoints return the complete effective state and PATCH accepts sparse changes.
- Account merge, export, and deletion paths preserve or handle the new settings consistently.
- A dedicated group-member scorecard endpoint authorizes group membership, evaluates the target member's settings, and returns only allow-listed Letter Golf or Reverse Cross aggregate fields.
- Group member pages render that privacy-filtered projection rather than sample data or another
player's
/meresponse. /settings/stats-sharingserver-loads authoritative settings and real groups without caching, then applies sparse per-control optimistic updates with duplicate prevention, rollback, and accurate success/failure toasts.- Authorized group Today pages show a dismissible
New: shared game scorecardsnotice above the game picker. It links to/settings/stats-sharing; its versioned local-storage marker records presentation state only and remains usable when browser storage is unavailable. - The Privacy Policy and newest update article describe the player-owned, persisted, server-enforced sharing choices and the group-only data boundary without implying public profiles or play-history access.
- Main Settings links to the new route. No public profile, play history, submitted-word list, puzzle answer, partial progress, or arbitrary statistics surface was added.
- Phase 5 focused validation passed 26 tests across five files. Phase 6 added a stateful Playwright journey covering persisted settings, override precedence, privacy ownership, announcement behavior, both game scorecards, keyboard navigation, and responsive overflow on Desktop Chrome and Pixel 7. Final local validation passed 784 frontend tests across 84 files, ESLint, TypeScript, the production build, whitespace checks, and the full Playwright matrix (51 passed, 1 skipped).
- Stats Sharing has no feature-specific runtime flag; rollout uses additive backend-first deployment followed by the frontend and target-environment verification. Manual screen-reader, focus/status-announcement, light/dark/forced-colors, 200%-zoom, long-word, and Reverse Cross 5×5–9×9 reflow checks, plus non-production smoke checks, remain pending before rollout.
2026-08-08 — Stats/streak evaluator bugfix and scorecard polish¶
Follow-up to Phase 4b, on main after merge. Two parts: a real backend correctness bug found
via a fresh player debug export, and a round of scorecard UI/copy polish (including review
notes from a separate Codex pass).
- Root-caused the "stats/streak never update" bug:
LetterGolfPlayEvaluator'sremainingTargetsdictionary used the default case-sensitive string comparer, but persisted puzzle target keys are lowercase (e.g."a") whileAccumulateLetterCountsalways uppercases submitted letters (e.g."A"). EveryTryGetValuelookup missed, so every submitted letter was wrongly treated as a non-target letter consuming a wildcard —IsValid/Victorycame back wrong for essentially every real submission, silently preventingApplyCompletedPlayfrom ever running. Fixed withnew Dictionary<string, int>(targets, StringComparer.OrdinalIgnoreCase), plus a regression test reproducing the exact failure with real lowercase-keyed targets. Confirmed viagit log --followthis predates Phase 4 entirely (present since the originalfeat: server-authoritative round scoringcommit) — unrelated to the Phase 4b UI work. - Longest word text:
PlayerStats.Highlights(previously reserved/unused) now stores the literal text of the longest winning word alongside the existinglongestWordLengthcounter, additive per the original Phase 4 design.CompletedPlayStatsInputgained an optionalLongestWordfield (defaults to""so old call sites/tests didn't need touching); the submit endpoint picks the longest word from the completed play's word list. - Hole-in-one naming: added a new
laxHoleInOnescounter (any hole-in-one, wildcards allowed) alongside the existing strict one, so the scorecard can show both "Hole-in-ones" and "Strict Hole-in-ones" instead of only the strict variant with no lax counterpart. - Copy/UI polish (
/meand the in-game recap), addressing Codex's review notes: formatDayCount()helper inlib/streak.tsfixes "1 days" → "1 day" everywhere a streak length is shown.- Streak card relabeled as an explicit two-column scorecard (current streak + label on the left, "Best" + value on the right, status line below) instead of an unlabeled number stacked over a "Best: N days" caption.
- "Longest Word" renamed "Longest word length" (still the number), with the literal word
shown alongside it when known, e.g.
8 | apparent, in the same card per explicit direction to keep it together rather than as a separate card. - Score-distribution bars now show the count once (to the right of the bar) instead of duplicating it inside the bar fill when there was room.
- Roadmap forward-look — future stats (not built yet, captured here per explicit request before more stat types accumulate ad hoc):
- More counters/highlights are cheap and additive — the existing
Counters(numeric) andHighlights(text) maps onPlayerStatsalready support this pattern with no schema migration; e.g. a future "Highest Scrabble word score" is just another counter plus aHighlightsentry for the word itself, computed the same wayLongestWordis today. - "First to use word X this week"-style overlays are a different shape of feature than
per-player counters: they're inherently cross-player/global (a race, not a personal best),
so they likely need their own small store (e.g. a
weeklyFirstUsedoc per game+week, updated via an optimistic-concurrency compare-and-swap similar to how puzzle documents are updated today) rather than living inPlayerStats. Likely needs a lightweight event/ notification surface too (a toast/overlay triggered "you were first," not just a stat visible only on your own scorecard) — open design question for whenever this is picked up. - A "top N most-used words" view implies tracking per-word frequency, which is a
fundamentally different data shape from today's small, fixed set of well-known counters —
an open (word → count) map per player, unbounded in principle. Options to weigh later:
cap it (e.g. top 20 tracked client-of-truth style, evicting the least-used) vs. a separate
Cosmos container keyed for this exact query pattern vs. deferring exact counts and instead
sampling/approximating. Needs its own dedicated design pass, not a quick add to
PlayerStats.Counters. - No commitment yet on exact UI treatment (new tab vs. new
/mesection vs. standalone view) for any of the above — captured here so future stat additions have a documented starting point instead of being designed from scratch each time.
2026-08-07 — Phase 4b: Streaks/Stats/Settings UI (frontend)¶
Branch feat/stats-settings-ui, not yet merged to main. Closes out the two frontend
surfaces Phase 4 Chunk 2 and Chunk 3 explicitly deferred: the stats/streak scorecard and the
settings UI. Five commits:
- Foundation:
src/lib/players.ts(typed fetchers forGET /v1/players/me,GET/PATCH /v1/players/me/settings,GET /v1/players/me/export,POST /v1/players/me/delete) andsrc/lib/streak.ts(Pacific-time streak status helper), plus shadcn-styledialog.tsx/input.tsx/label.tsxUI primitives. - Nav: new
My scorecard(/me) andSettings(/settings) nav-only entries inlinks.ts, visually separated from game links inheader-menu.tsx; the homepage gained a lightweight top bar with the header menu and a newdeleted-toast.tsxClient Component that shows a dismissible "Your Verbolus data has been deleted." toast when visited with?deleted=1. /mescorecard page: a Server Component showing the Letter Golf daily streak, all-time stat counters (games played, average/best score, longest word, strict hole-in-ones), and a score-distribution histogram, with an empty state before the player's first completed puzzle./settingspage: a Server Component wrapping a Client Component form for editing display name (persisted viaPATCH), choosing a theme, downloading a JSON data export, and deleting the player's account/data behind a confirmation dialog.- In-game surface: the Letter Golf page best-effort fetches the player's profile alongside
the puzzle; the game view shows a 🔥 daily-streak badge in the header (linking to
/me) and a post-victory recap (daily streak or practice best-score, plus a "View scorecard" link) in the victory overlay. - Key decisions: theme selection applies immediately via
next-themesin addition to being persisted, so the UI doesn't wait on a round-trip to reflect the choice. The account-deletion confirmation dialog explains the anonymous-first re-creation model — deleting data doesn't delete the "account"; playing again just creates a fresh anonymous player profile. The in-game streak badge/recap does a best-effort client-side refetch of the player profile right after a successful submit, so it reflects the play that just happened rather than stale pre-play data. The homepage stayed a Server Component (searchParamsread via the async Next.js 16 pattern) with a small dedicated Client Component owning the dismissible post-delete toast's state. - Testing: no frontend test tooling exists in this repo yet (no Jest/Vitest/Playwright/ RTL). This phase intentionally shipped UI-only with no new tests — an explicit product decision, not an oversight. The frontend testing strategy remains open, deferred to a future, separate discussion.
2026-08-07 — Phase 4 Chunk 4: export/delete-my-data, and phase wrap-up¶
Branch feat/player-stats. Fifth and final chunk of Phase 4, adding self-service data
export/deletion, plus closing out the phase for merge.
GET /v1/players/me/export: full JSON dump of the caller's ownplayersdoc, folded together with a cross-partition query of every matchingplaysdoc for thatuserId(the two containers can't be read in one partition-scoped query — see the architecture note above).POST /v1/players/me/delete: deletes theplayersdoc plus every matchingplaysdoc; idempotent (an already-deleted account returns success, not 404). Both resolve identity from theuserIdcookie only, same as every other endpoint in this phase — a caller can only ever export or delete their own data.- Implemented as one commit (
07a79f1) with shared test coverage as a second (6e1d21e), rather than split per-endpoint, since export and delete share the same cross-partitionplaysquery shape and were reviewed together. Docs landed in a third commit (27e050d,.httprequest examples for both endpoints). - Process note: review caught an IDOR-pattern bug in the first draft of the new tests —
they asserted identity via a raw
Headers.Add("userId", ...)instead of theCookieheader, which silently defeated the cookie-only identity check and made 5/7 new tests pass for the wrong reason. Fixed before merge. - Also added
scripts/sign-cookie.ps1(commitcace778), a small self-documenting helper that computes a signeduserIdcookie value matchingCookieSigner.cs's HMAC-SHA256 scheme, for manually testing cookie-gated endpoints without a browser session. - Verified:
dotnet buildclean, 0 warnings/errors. Fulldotnet testsuite passes aside from the same pre-existing, unrelated flakyTestLetterGolfGeneratorTests.GetLetterGolfAsync_MinTotalLetterOccurrences_RejectsShortWordsdocumented in every prior chunk of this phase. - Phase 4 wrap-up: all four chunks' backend work is complete and merged. Two frontend
surfaces remain deliberately deferred, tracked as follow-up rather than blocking this
merge: Chunk 2's stats/streak display (at least
gamesPlayed/streak) and Chunk 3's settings UI. Neither has a placement decided yet; pick them up in Phase 5 or a small standalone follow-up branch. TheplayersCosmos container Terraform (9db5a70, Chunk 1) is still unapplied — now that both frontend and backend are released, it's unblocked; apply it with a reviewedterraform planbefore Phase 5 starts writing to that container.
2026-08-06 — Phase 4 Chunk 3: per-user settings¶
Branch feat/player-stats. Fourth chunk of Phase 4, completing the per-player customization
layer with settings for notifications, display name, locale, theme, and difficulty hint.
- Backend domain logic: new
PlayerSettingsCalculator(pure, no I/O) validates incoming settings updates and applies them as a partial/patch merge to aPlayerEntity.Settingssub-document. Validation is centralized:Validate()checks enum constraints (theme, difficultyLevel), displayName length (max 32 characters), and locale membership against a staticKnownCultureNamesset built once fromCultureInfo.GetCultures(). The latter is critical:CultureInfo.GetCultureInfo(locale)does not throw for syntactically-shaped but unregistered tags like "xx-ZZ-invalid" — it silently builds a "custom culture" (LCID 4096) — so a try/catch is insufficient; direct membership check is required. - Backend storage:
PlayerSettings(sub-document nested underPlayerEntity.Settings, persisted with[JsonProperty]camelCase names) holds the five settings fields with sensible defaults (notifications enabled, theme "system", difficulty "normal"). Added toPlayerEntityvia a newSettings: PlayerSettingsproperty (initialized on first read). - Backend wiring: new
PlayerSettingsUpdaterperforms the read-modify-patch retry loop (read, validate, apply, save withIfMatchEtag, retry on 412 up to 5 attempts) and is called from newGET/PATCH /v1/players/me/settingsendpoint handlers inPlayerEndpoints.cs.GETreturns the player's current settings;PATCHaccepts a partial request, validates it, applies it viaApplySettingsUpdate(), and returns the merged result. Both resolve identity from cookie only, ensuring IDOR prevention. Validation errors return 400; concurrent-update conflicts return 409 Conflict. - Contract: new DTOs
PlayerSettingsResponse(read response),UpdatePlayerSettingsRequest(patch body), andPlayerSettingsMappingExtensions(ToResponse converter) added toContracts/PlayerSettingsResponse.cs, mapped through to responses with persistence-entity isolation maintained. - Design deviation from the original plan: the endpoint HTTP method is PATCH, not PUT. PATCH semantics (partial merge of supplied fields, leaving unspecified fields untouched) are more accurate here than PUT (full replacement), so the verb was corrected from the original checklist. Partial-update semantics already drive the implementation (optional-nullable request fields, merge-in-place apply logic), so this is a documentation-and-HTTP-semantics fix, not a behavior change.
- Process note — bug found during review:
PlayerSettingsCalculator.Validate's original locale-validation logic wrappedCultureInfo.GetCultureInfo(locale)in a try/catch forCultureNotFoundException, expecting to catch invalid BCP-47 tags. This was insufficient: on this platform,GetCultureInfodoes not throw for syntactically-shaped-but-unregistered tags like "not-a-locale" or "xx-ZZ-invalid" — it silently builds a custom culture (LCID 4096) instead, so garbage locale strings were being silently accepted. This was caught by 3 failing test cases during the full suite run (not caught by any isolated build). The fix replaces the try/catch with a membership check against a staticKnownCultureNamesset constructed once fromCultureInfo.GetCultures(CultureTypes.AllCultures)(case-insensitive comparison). This set is now aprivate static readonlyfield onPlayerSettingsCalculator. - Verified:
dotnet buildclean, 0 warnings/errors.dotnet test— full suite 169/170 pass (1 pre-existing flaky test,TestLetterGolfGeneratorTests.GetLetterGolfAsync_MinTotalLetterOccurrences_RejectsShortWords, expected and unrelated). NewPlayerSettingsCalculatorTests(pure unit tests) and newPlayerSettingsEndpointsTests(integration tests for GET/PATCH) all pass. - Next steps: Chunk 3's frontend settings UI is deferred (not yet built). Chunk 4 (export/delete-my-data) is next.
2026-08-06 — Phase 4 Chunk 2: stats and streaks, wired into submit¶
Branch feat/player-stats. Third chunk of Phase 4, closing the loop from a completed play to
a permanent per-game stat/streak aggregate on the player's profile.
- Backend domain logic: new
PlayerStatsCalculator(pure, no I/O) computes the stat/streak delta for one completed play and applies it to aPlayerEntityin place.PlayerStatKeyscentralizes the counter-key constants so nothing hardcodes them ad hoc.TryParseDailyPuzzleDateextracts the calendar date embedded in a global daily puzzle key, returningnullfor practice-scope puzzles (which have no daily cadence). - Backend storage:
PlayerStats(Counters,ScoreHistogram,Highlights) andStreakEntry(Current,Longest,LastPlayedDate) added toPlayerEntity.Stats/.Streaks, both dictionaries keyed as described in the Chunk 2 checklist above. - Backend wiring: new
PlayerStatsUpdaterperforms the read-modify-patch retry loop (GetOrCreateAsync→PlayerStatsCalculator.ApplyCompletedPlay→SaveAsyncwithIfMatchEtag, retrying on a Cosmos 412 up to 5 attempts) and is called fromLetterGolfEndpoints.SubmitPlayexactly once, on the branch where this request's own save of the newly-Completedplay just succeeded (not on the idempotent-replay path, and not on the reread-after-conflict path, since a concurrent request that won that race owns its own stats update). Failures are logged and swallowed — never fail the submit response. - Contract:
GET /v1/players/menow also returnsstats/streaks, mapped through newPlayerStatsResponse/StreakResponseDTOs (kept separate from the storage entities per this repo's persistence-entity-isolation convention). - Design deviations from the original Chunk 2 plan, made with the user's explicit
direction before implementation started (game-type-keyed stats/streaks, absolute
score-band histogram instead of golf terms, dropped
mostPointsRemovedInOneWord,longestWordLengthinstead of literal word text,:daily-suffixed streak keys) — see the updated checklist above for the full list and reasoning. - Verified:
dotnet buildclean, 0 warnings/errors.dotnet test— full suite 132/133 pass (the 1 failure is the pre-existing, unrelated flakyTestLetterGolfGeneratorTests.GetLetterGolfAsync_MinTotalLetterOccurrences_RejectsShortWords, confirmed via isolated rerun). NewPlayerStatsCalculatorTests(pure unit tests) and the newPlayEndpointsTestsstats/streak integration tests all pass. - Process note: this chunk surfaced two real bugs during review that are worth recording
precisely because they'd otherwise have shipped silently: (1)
SubmitPlay's newPlayerStatsUpdaterdependency was never registered inProgram.cs's DI container — every test file's ownConfigureTestServiceshappened to register it independently, fully masking the gap, so the full suite passed while the real app would have failed at startup (minimal API validates all endpoint DI at host-build time); (2) adding that one new endpoint dependency broke DI resolution in everyWebApplicationFactory<Program>-based test file, not just ones exercisingSubmitPlaydirectly, requiring the same fake registrations added acrossPlayerEndpointsTests,CookieSigningEndpointsTests, andPracticeAndDebugEndpointsTeststoo. Both are recorded in repo memory to catch faster next time a required endpoint dependency is added. - Next steps: Chunk 2's originally-planned 3rd commit (frontend surfacing of at least
gamesPlayed/streak) is deferred, placement not yet decided. Chunk 3 (per-user settings) is next.
2026-08-06 — Phase 4 Chunk 1: players container and profile scaffold¶
Branch feat/player-stats. Second major chunk of Phase 4, completing the foundational player
infrastructure announced in Chunk 0/0b.
- Terraform: new
playerscontainer written totf/data/cosmos.tf(partition key/userId, no TTL — permanent storage for player profiles and future aggregates). Validated but not yet applied, per the deferred pattern: the backend code must deploy successfully first, so the container exists when traffic hits it. - Backend storage layer: new
PlayerEntitywith skeleton fields (Id,UserId,LinkedIdentities,CreatedAt).linkedIdentitiesis seeded empty; it's a migration path for Phase 5+ auth flows to absorb anonymous device identities.IPlayerStore/CosmosPlayerStoreimplement point read byuserId, lazy upsert-on-first-read (GetOrCreateAsync), and ETag-gated patch (SaveAsync) for future stats/streak updates. Race-safe: concurrent first requests to the same brand-new userId both succeed. - New endpoint:
GET /v1/players/mereturns the current user's player profile (creating it if absent). Identity resolved fromuserIdcookie only (no header trust), using the existingHttpContextExtensions.GetUserId()convention established in Phase 3b. Rate-limited under the existingplay-endpointspolicy (20/min/IP). - Integration: new
PlayerEndpoints.csand corresponding test suite inMiniGamesBackEnd.Tests/PlayerEndpointsTests.cs. Wired inProgram.csalongside the existing play/puzzle stores and endpoints. - Verified:
dotnet buildclean;dotnet test— full suite 110 tests pass (109 passing plus 1 pre-existing flaky test,TestLetterGolfGeneratorTests.GetLetterGolfAsync_MinTotalLetterOccurrences_RejectsShortWords, known and unrelated); newPlayerEndpointsTests4/4 passing.terraform fmt -checkandterraform validatepass (same pre-existinglocal_authentication_disableddeprecation warning, unrelated). - Next steps: apply the Terraform once this backend code is deployed to production,
coordinating the container creation with the container app's ability to write to it. Chunk 2
(stats/streaks) is next, wiring the
SubmitPlayflow into read-modify-patch updates of the player doc.
2026-08-06 — Phase 4 Chunk 0b: userId cookie signing¶
Branch feat/player-stats. Follow-up to Chunk 0's cookie-hardening discovery: implements the
last remaining piece, an HMAC signature over the userId cookie value.
- Backend:
CookieSigningOptions(Configuration/CookieSigningOptions.cs) mirrorsAdminOptions— aCookie:SigningKeyconfig section, absent fromappsettings*.jsonby design (fails closed/unsigned in dev unless the secret is supplied out-of-band).CookieSigner(CookieSigner.cs) computes/verifies an HMAC-SHA256 signature, base64url encoded, appended as"{value}.{signature}", usingCryptographicOperations.FixedTimeEqualsfor constant-time comparison (same convention asValidateAdminKey).HttpContextExtensions.GetUserId()gained an optionalcookieSigningKeyparameter (defaultnull, so all existing zero-arg call sites keep compiling unchanged): when a key is configured, cookie values containing a.are fully verified (never trusted on failure); values with no.(legacy, pre-signing cookies) are still accepted as-is, so real users with existing anonymous UUID cookies don't lose saved plays. The fourLetterGolfEndpoints.cshandlers that resolve identity (GetPlay,SavePlay,SubmitPlay,ResetPlay) now takeIOptions<CookieSigningOptions>and passSigningKeythrough. Registered inProgram.csalongsideAdminOptions. - Frontend:
proxy.ts'sinitializeCookies()is now async. A cookie value already containing a.is left untouched; otherwise the existing raw value (if any) or a freshcrypto.randomUUID()is signed via a newsignCookieValue()/base64UrlEncode()pair using the Web Crypto API (crypto.subtle, available in both the Edge and Node runtimes, unlike Node'scryptomodule) and set as the cookie. Reusing the existing raw value when upgrading a legacy cookie (rather than minting a new id) is what makes the rollout non-destructive for already-anonymous users. Falls back to leaving the cookie unsigned whenCOOKIE_SIGNING_KEYisn't set, so local dev keeps working without the shared secret. - Terraform: new
cookie_signing_keyvariable (top-leveltf/vars.tf,tf/backend/vars.tf,tf/frontend/vars.tf), sensitive with no default, mirroringadmin_debug_key's out-of-band-only sourcing. Wired into bothazurerm_container_appresources as a native Container Apps secret (cookie-signing-key), exposed to the backend asCookie__SigningKeyand to the frontend asCOOKIE_SIGNING_KEY— the same key value must reach both for signatures to verify. Not applied — the real secret value still needs to be added to the gitignoredtf/local_secrets.auto.tfvars(or supplied viaTF_VAR_cookie_signing_key) beforeterraform apply, and this should be coordinated with a deploy of both the backend and frontend images together. - Verified:
dotnet build/dotnet test— 106 backend tests pass (addedCookieSignerTests, newHttpContextExtensionsTestscases, and a newCookieSigningEndpointsTestscovering the wiring end-to-end through the real endpoints);tsc --noEmitandeslintclean on the frontend;terraform fmt -checkandterraform validatepass (same pre-existinglocal_authentication_disableddeprecation warning as Chunk 0, unrelated). No frontend unit test was added forproxy.ts— the repo has no Vitest harness yet (see "Cross-cutting: testing" below), so build/lint/typecheck is the same level of verification priorproxy.tschanges have had. - Next step if picking this back up: generate the real HMAC key (e.g. 32 random bytes,
base64-encoded) and set it via
TF_VAR_cookie_signing_keyortf/local_secrets.auto.tfvars, review/apply the Terraform, then deploy backend+frontend together. Still outstanding from Chunk 0: review/approve therounds→playsCosmos container renameapply.
2026-08-06 — Phase 4 Chunk 0: Round → Play rename, admin scripts, Terraform (not applied)¶
Branch feat/player-stats. First slice of Phase 4, split out as its own chunk per the plan:
naming cleanup and cookie hardening, no behavior change.
- Renamed the single-puzzle-attempt concept from "Round" to "Play" across the whole stack,
to avoid colliding with real golf's "round" (9/18 holes), which Phase 5/7 courses and
tournaments will need. Backend:
RoundEntity/IRoundStore/CosmosRoundStore→PlayEntity/IPlayStore/CosmosPlayStore;LetterGolfRoundEvaluator→LetterGolfPlayEvaluator;SubmitRoundRequest/SubmitRoundResponse/RoundStateResponse→SubmitPlayRequest/SubmitPlayResponse/PlayStateResponse; routesGET/PUT /v1/letter-golf/{puzzleKey}/round→/play,POST .../round/reset→/play/reset; rate-limit policyround-endpoints→play-endpoints;Consts.RoundsContainerName→PlaysContainerName("rounds"→"plays"). Frontend:RoundState→PlayState,fetchRound/saveRound/submitRound→fetchPlay/savePlay/submitPlayinapi.ts,game.tsx, andpage.tsx. Scripts:reset-daily-round.ps1/.sh→reset-daily-play.ps1/.sh, calling the renamed/play/resetroute. Terraform: theroundsCosmos container →plays, partition key path/roundKey→/playKey. - File renames landed as their own commit first (
git mv, 100% similarity, zero content diff), before any content edits — so git records clean renames instead of delete+add pairs. Content edits followed as separate commits per surface (backend, frontend, scripts, Terraform), each independently reviewable. - Verified:
dotnet build/dotnet test— all 89 backend tests pass;tsc --noEmitandeslintclean on the frontend;terraform fmt -checkandterraform validatepass (pre-existing, unrelatedlocal_authentication_disableddeprecation warning only). - Terraform container rename is written but NOT applied. Renaming/re-keying a live Cosmos
container is destructive (implies destroy + recreate of the
rounds/playscontainer), soterraform applyneeds explicit review and approval, coordinated with deploying the backend commit that already points atPlaysContainerName = "plays". - Cookie hardening discovery: the Phase 4 plan called for promoting the
userIdcookie toHttpOnly/Secure/SameSite=Lax/signed.proxy.ts'sinitializeCookies()already sets the first three — only signing remains. Signing needs a new shared secret threaded through Terraform (mirroring the existingadmin_debug_keypattern) plus coordinated frontend and backend changes, which is a bigger, coordinated deploy than the rest of this chunk's pure renaming groundwork — deferred to its own follow-up chunk rather than folded in here. - Also fixed a stale Phase 4 line recommending UTC for the daily day boundary; the actual
decision (Pacific time,
Consts.DailyResetTimeZoneId) was already made and shipped in an earlier session and documented indoc/lettergolf.md. - Next step if picking this back up: review and approve the Terraform
plan/applyfor the Cosmos container rename (coordinate with a backend deploy soPlaysContainerNameand the actual container name switch together), decide whether cookie signing is its own Chunk 0b or gets folded into a later Phase 4 chunk, then continue documenting/building the remaining Phase 4 chunks (players container, stats, streaks, settings, export/delete).
2026-08-01 — Letter Golf: fixed puzzle size and restored difficulty¶
Branch fix/lettergolf-difficulty.
- Puzzles now always show a fixed
TargetVisibleLetterCount(default 5) distinct letters, replacing the accidental variable-size behavior (3-8, whatever the seed word's distinct-letter count happened to be). AddedMinTotalLetterOccurrencesto reject trivially short/common seed words (e.g. "first") that made the hole-in-one an obvious giveaway. Letters beyond the visible count stay playable via the wildcard budget, not shown as targets. - Added
HasStrictHoleInOne(visible letters only, zero wildcards, not guaranteed) alongside the existingHasHoleInOne, now documented as the "lax" guarantee (visible letters + wildcards, guaranteed on every puzzle by construction). - Doc/comment pass: updated
doc/lettergolf.md(fixed 5-letter default, new "Hole-in-one" subsection, resolved the "count of letters" open question) and refreshed stale comments inLetterGolfGenerationOptions,LetterGolf,TestLetterGolfGenerator, and their tests to match the new semantics.
2026-07-30 — Letter Golf generation rewrite: guaranteed hole-in-one, count-trie verification¶
Branch fix/lettergolf-generation. Addresses the Phase 3 "Bugs to fix" solvability and
latency items ahead of Phase 3 itself, since daily puzzles shouldn't be built on top of the
old buggy/slow generation.
- Root-caused the exact solvability bug via full code read:
IsSolvableAsynctestedword.Contains(c)per distinct puzzle letter and spent one wildcard per missing distinct letter, never accounting for multiplicity (e.g. a puzzle needing 2 A's could be wrongly satisfied by a word with 0 A's, charging only 1 wildcard for the whole 2-letter deficit). Also found, not previously documented:NumWildcardswas hardcoded to3in the puzzle constructor regardless of the caller's requested value. - Investigated whether any trie/prefix-tree/DAWG already existed in the codebase to build on
(frontend or backend) — confirmed none did. The only real prefix tree in the repo is
usr/jonsheller/spinsolve.py'sPrefixTreeNode, a standalone offline tool solving a different problem (fixed-position prefix lookup for a word square), not wired into any game. - Rewrote generation to be solution-first: pick a real dictionary word, derive the puzzle's letters from its exact signature. Guarantees a hole-in-one by construction instead of the old "guess random letters, hope a word solves them" retry loop.
- New
LetterSignature(corrected, multiplicity-aware coverage check — replaces the buggy logic) andWordSignatureIndex(a count-trie over the ~1M-word dictionary, replacing per-attempt full linear scans with a single pruned tree traversal). Both carry detailed doc-comments with worked examples, since the count-trie's relationship to subset-sum DP and to a simpler flat anagram hashmap took some back-and-forth to land on clearly. - New
IGraphemeSegmenterseam so the trie's depth is language-dependent (M "atomic letter units") rather than hardcoded to 26 — only the trivial en-US (one Unicode char = one letter) segmenter ships; real digraph/grapheme handling for other languages (e.g. Spanish "ll"/"rr"/ "ñ") is deliberately left as a future extension point, not built here. - New
LetterFrequencyTable, derived from the live dictionary (one pass over every loaded word) rather than a fixed Scrabble-style table, so rarity stays consistent with whatever word sources are actually loaded; recomputed via the newRefreshAsync()seam added toIWords/AbstractWords/MultiDict(a manually-triggered no-op today, real background refresh is future work). - New
IWordListProvider/InMemoryWordListProvider(deny/curated list scaffolding), wired into both seed-word selection and a rewritten/v1/verify-word, with explicit// TODO(Phase 6):comments marking where a future Cosmos-backedIContentStoreswaps in. - New
LetterGolfGenerationOptions: every difficulty knob (wildcards, seed-word length, common-word bias, alternate-solution bounds, guaranteed sub-par word count) is independently tunable — deliberately not a single difficulty enum/tier, per explicit direction that e.g. wildcards must be tunable separately from other factors, not derived from a rigid "Difficulty=Hard ⇒ Wildcards=1" mapping. LetterGolfgainedHasHoleInOne(real, computed at generation time — never just assumed), and nullablePar/DifficultyScoreplaceholders for Phase 7's tuning work.- Widened
LetterGolf.PuzzlefromDictionary<char,int>toDictionary<string,int>so it can hold multi-character grapheme units — matches the frontend's already-string-keyedRecord<string, number>puzzle shape, so no frontend contract change was needed. - New
MiniGamesBackEnd.TestsxUnit project (first tests in the repo) — 18 tests covering signature/index correctness (including the exact old-bug repro case), generation regression (every puzzle has a real hole-in-one, wildcards honor the caller's request, deny list rejection), and a cross-check that the trie's pruned traversal returns exactly the same results as calling the naive per-word check directly. - Manual smoke test after implementation: 30 consecutive local
/v1/letter-golfcalls — first call ~11s (one-time index build over the full aggregated dictionary, cached for the process lifetime thereafter), every subsequent call 160-540ms,HasHoleInOne: trueon all 30./v1/verify-wordspot-checked unaffected (cat→ true, nonsense → false). - Next step if picking this back up: review/merge this branch, then consider whether the
frontend's 30s
apiFetchtimeout (frontend/minigames/src/app/api.ts) can safely come back down now that generation latency's root cause is fixed rather than just bounded — watch real production request timing first rather than assuming the local smoke-test numbers transfer directly. After that, Phase 3 (data model + daily puzzles) is next up.
2026-07-28 — Phase 2 wrap-up: custom domains into Terraform, key auth disabled, APIM/App Service retired¶
Branch infra/backend-and-cosmos.
- Custom domains imported into Terraform.
verbolus.com(frontend) andapi.verbolus.com(backend) already had managed certificates and domain bindings live in Azure — bound manually through the Portal during the Phase 1 cutover. Addedazurerm_container_app_environment_managed_certificateandazurerm_container_app_custom_domainresources totf/frontend/custom_domain.tfandtf/backend/custom_domain.tf, with matchingimportblocks intf/imports.tf.certificate_binding_typeandcontainer_app_environment_certificate_idare inignore_changesper the azurerm provider's documented managed-certificate pattern, since Azure's auto-renewal mutates those fields outside Terraform. Not yet applied — needsterraform planreviewed (no local Terraform CLI in this session;az containerapp show/az containerapp env certificate listwere used instead to confirm the exact resource IDs, subject names, and validation methods to import). disable_local_authflipped totrue(default) intf/data/vars.tf. Managed-identity Cosmos auth had been live and stable for a full day post-cutover (see the 2026-07-27 entry below), clearing the bar the variable's own comment set for this change. Also not yet applied. Once it is, the Cosmos account key stops working everywhere — see the "what this means" note the assistant gave the user in the same session for the local-dev and deploy-script implications (no code or script changes needed;DefaultAzureCredentialwas already the only path other than the emulator).- APIM and the Windows App Service retired. The user deleted the APIM instance
(
MiniGamesBackEndapi), the App Service (MiniGamesBackEnd20250302132848), and its plan directly in the Portal after the one-day bake period referenced in the 2026-07-27 entry confirmed zero production traffic to the old host. Removed the now-dead tracked files that referenced them: the.pubxmlpublish profile,apis1.arm.json/profile.arm.jsonservice dependencies, andserviceDependencies.json. Completes cutover-runbook step 4 in Phase 1. - Next step if picking this back up: run
terraform -chdir=tf initandplan, review the diff carefully (imports plus thedisable_local_authflip touch production auth and DNS), thenapplyonly after explicit approval. After that, Phase 2 is fully done and Phase 3 (data model + daily puzzles) is next up.
2026-07-28 — Phase 2 applied: custom domains imported, Cosmos key auth disabled¶
Continuation of the entry above, same day, same branch. Terraform CLI wasn't installed at the
start of this session; installed via winget install Hashicorp.Terraform (already present,
just not on PATH for the session — refreshed from the registry instead of reinstalling).
- Bumping
azurermto4.81.0surfaced an unrelated, unintended diff onazurerm_container_app_environment.www: the shared Container Apps environment already has a live system-assigned identity and a default "Consumption" workload profile in Azure, neither ever declared intf/frontend/container_app.tf. Newer provider versions read/track more attributes than4.28.0did, so this was pre-existing drift the old provider simply couldn't see, not something introduced by this branch's changes. Nothing in this repo's Terraform uses that system-assigned identity — the frontend app has its own separate user-assignedwww_pullidentity for ACR pulls — but deleting live infrastructure that predates this branch was out of scope. Addedidentity,workload_profile, andlog_analytics_workspace_id(cosmetic resource-ID casing only) to that resource'signore_changesrather than letplanpropose removing them. - Reviewed plan after that fix:
4 to import, 0 to add, 1 to change, 0 to destroy— exactly the custom-domain imports and thedisable_local_authflip, nothing else. - Applied. All 4 imports succeeded with no attribute drift (confirms the HCL matched live Azure
exactly). The Cosmos
Modifying...step forlocal_authentication_disabledtook about 1m22s. - Smoke-tested immediately after:
https://api.verbolus.com/health/ready(pings Cosmos) andhttps://api.verbolus.com/v1/letter-golfboth returned200, confirming managed-identity auth works end-to-end with the account key fully disabled. - Phase 2 is done. Local
tf/phase2.tfplanwas single-use and is gitignored, nothing to clean up. Remaining open item, tracked in the Phase 2 section above rather than blocking this branch: the deprecation warning to eventually move offlocal_authentication_disabledwhen this repo takes on theazurermv5.0upgrade.
2026-07-27 — production deploy of frontend fixes, Letter Golf latency incident¶
Not roadmap feature work; operational follow-up on chore/linux-and-modernize after the
retry-bound fix (7aef5cf) landed. Recorded here so it isn't lost.
- Shipped three small frontend fixes to
minigame-www(Container App, single-revision mode):apiFetchrequest timeout (frontend/minigames/src/app/api.ts), aLetterGolfErrorboundary (frontend/minigames/src/app/games/letter-golf/error.tsx), and the remainingDropdownMenuItemmissingasChildin the desktop header dropdown (frontend/minigames/src/app/components/header-menu.tsx— the7aef5cfcommit had already fixed a different nested-Linkinstance, this was a second one it missed). - First deploy used a 15s
apiFetchtimeout and immediately regressed/games/letter-golfto a hard 500, because the backend's Letter Golf generation latency (see the Phase 3 bug note above) routinely exceeds 15s. Rolled back within minutes to the prior image (frontend:7aef5cf-directapi) sinceminigame-wwwis single-revision-mode (traffic-weight splitting isn't available there; rollback =az containerapp revision copywith the old image tag). - Redeployed with the timeout raised to 30s (image
frontend:7aef5cf-longtimeout, revisionminigame-www--0000045). Verified healthy: 6 consecutive requests to/games/letter-golfall returned 200 in 1.2-2.1s. This is currently live and stable, but it's a stopgap, not a fix — see the Phase 3 note above for the real fix (precompute solvability instead of rescanning the word bank per generation attempt). - Also used this investigation to close the open Phase 1 cutover-runbook question (DNS
routing of
api.verbolus.com) and to confirm the legacy Application Insights resource is safe to delete — both folded into the Phase 1 section above rather than duplicated here. - Committed locally (not yet pushed) alongside this roadmap update.
- Next step if picking this back up: implement the Phase 3 letter-multiset precompute so Letter Golf generation stops rescanning tens of thousands of words per retry attempt, then the frontend timeout can likely come back down from 30s.
2026-08-01 — Phase 3a complete: real Cosmos data model and daily Letter Golf puzzles¶
Branch feat/daily-puzzles. Depends on fix/lettergolf-generation and infra/backend-and-cosmos.
This branch implements the real data model and daily puzzle persistence that were planned as Phase 3 but are now split: Phase 3a (done now, this branch) covers the daily-puzzle MVP needed for launch, and Phase 3b (deferred) covers server-authoritative scoring, rate-limiting, and round-state persistence for future play-session tracking.
Data model work:
- Created the
puzzlesCosmos container (/puzzleKeypartition key, shared autoscale) — the only container needed for Phase 3a. The other four (players,groups,lookups,content) remain unbuilt, deferred to their owning phases. - Reworked the
LetterGolfentity to usePuzzleKey(format:{gameType}|{scope}|{yyyy-MM-dd}, e.g."lettergolf|global|2026-08-01") as the documentidand Cosmos partition key, replacing the old uselessGameId=1hardcoding. - Populated
Contracts/withLetterGolfPuzzleResponseDTO, narrowing the wire boundary from the internal Cosmos entity. Response shape is additive (new:puzzleKey, populated:HasStrictHoleInOnealongside the existingHasHoleInOne) — no breaking frontend changes.
Daily puzzle persistence:
- Implemented
IPuzzleStore(withCosmosPuzzleStorebackend) replacing the brokenMVPLetterGolfStorage.GetDailyAsync()that returned nothing.GetLetterGolfByKeyAsync()performs a point read bypuzzleKey— roughly 1 RU instead of a cross-partition scan. - Implemented
LetterGolfDailyPuzzleProviderwithGetOrCreateDailyAsync()providing idempotent lazy-generation semantics: first request of each day (UTC) generates and persists a puzzle; every subsequent request that calendar day returns the identical stored puzzle. Day boundary is UTC not client-local time (computed viaDateOnly.FromDateTime(TimeProvider.GetUtcNow().UtcDateTime), invariant culture). - Added
GET /v1/letter-golf/dailyendpoint. Both it and the existing ad-hocGET /v1/letter-golfreturn the sameLetterGolfPuzzleResponseshape — no frontend changes needed beyond consuming the new endpoint.
Deferred explicitly:
- Scheduled Container Apps Job for pre-generating daily puzzles (~~no longer planned to build~~ built and shipped on
jm/past-future-puzzles— see the 2026-08-17 Session log entry for implementation details; lazy-on-first-request remains the permanent fallback). - Server-authoritative scoring,
/v1/verify-wordrate-limiting, in-progress round state persistence — all Phase 3b scope, not built this pass.
Testing and verification:
- New unit tests in
MiniGamesBackEnd.Testscover cache hit/miss, the concurrent-conflict- returns-winner race,puzzleKeyformat, and an idempotency regression test (calling the daily path twice the same day returns the samepuzzleKey) — all against a hand-written in-memory fakeIPuzzleStore, since no Cosmos emulator is wired into this repo's test project yet.CosmosPuzzleStoreitself is not covered by an automated integration test this pass; wiring a real emulator into CI is future testing work, not blocking here. - Not yet verified against a live Cosmos account — that happens as part of this branch's own deploy/merge, not during this docs-only pass.
Next steps:
- Merge and deploy this branch, then monitor Cosmos RU consumption for the daily point-read path (expected to be small — single point reads instead of a scan — but not yet measured against a live account).
- Once Phase 3a is live, Phase 3b (scoring, rate-limiting, resume state) becomes the next work item — not required for the MVP daily-puzzle feature but essential before leaderboards.
Account Deletion (GDPR/EEA Erasure Workflow)¶
Date: 2026-09-13
Branch: fix/better-activity-report
Implementation commits: 5535760, 4ae1bf2
Status: Implemented locally; not merged or deployed.
Overview¶
Account deletion software intended to support GDPR/EEA erasure workflows. It is not legal advice or a compliance certification. The implementation is a multi-phase, durable orchestrator that:
- Resolves the caller to their canonical user identity and discovers all merged aliases.
- Snapshots external identities and affected groups before any destructive work.
- Deletes in deterministic phase order (revocations → groups → plays → identity lookups → player docs) with ETag-based optimistic concurrency and bounded retry on 412 errors.
- Issues session revocation markers (32-day TTL) that cause stale sessions to receive 401
session_deleted. - Supports safe resumption from any phase via stored operation snapshots.
- Is idempotent: a retry resumes from the last durable checkpoint, and already-applied destructive operations can be replayed safely.
Scope¶
Verbolus account data:
- Canonical user ID and all merged alias user IDs.
- All game plays, player profile documents, and cumulative stats.
- External identity lookup links (issuer + subject pairs).
- Group memberships, standings entries, and empty-group cascading deletion.
- Revocation markers block stale identities; the completing browser rotates its own application identity cookie.
Explicit non-deletions (handled separately or outside scope):
- Identity provider accounts (Google, Microsoft, etc.) remain with their respective providers.
- Billing and financial records are subject to separate retention policies.
- Audit and compliance logs may be retained per provider retention settings.
Implementation artifacts¶
Backend (MiniGamesBackEnd/):
AccountDeletionService.cs— Multi-phase orchestrator with ETag-guarded checkpoints and deterministic phase ordering.AccountDeletionGroupCleanup.cs— Group removal, ownership transfer, standings scrubbing, empty-group cascading deletion.Configuration/AccountDeletionSessionMiddleware.cs— Revocation-marker check; allows retry-permitted deletion endpoint through.Storage/AccountDeletionOperationEntity.cs— Durable operation state, phase tracking, sensitive-data snapshots.IAccountDeletionStore,IAccountDeletionGroupStore— Cosmos storage layer with optimistic concurrency.
Frontend (frontend/minigames/):
src/lib/auth-session-rotation.ts— Generates fresh anonymous userId, clears OIDC cookies, sets new shared-domain session cookie.- Account-delete and session-recovery BFF routes — Handle 401
session_deletedresponse, invoke rotation.
Operator tools (scripts/):
repair-account-deletions.mjs— Admin batch repair utility: dry-run (default) or apply mode (requiresAPI_BASEandADMIN_DEBUG_KEYenv vars); up to 50 distinct user IDs per invocation; count-only output; no direct Cosmos mutation.
Documentation:
doc/account-deletion-runbook.md— Comprehensive operator/developer runbook covering scope, erasure details, phase model, session behavior, retention caveats, repair utility usage, safe procedures, failure modes, and rollback warnings.
Testing evidence¶
Backend tests (MiniGamesBackEnd.Tests/):
AccountDeletionServiceTests.cs— Phase ordering, idempotency, ETag retry logic, snapshot behavior.AccountDeletionGroupCleanupTests.cs— Member removal, ownership transfer, empty group deletion, standings scrubbing, retry on 412.AccountDeletionSessionMiddlewareTests.cs— Revocation check, retry-permitted paths, 401session_deleted, no sensitive logging.CosmosAccountDeletionStoreTests.cs— Revocation markers, operation snapshot, ETag handling.
Frontend tests (in frontend/minigames/):
src/app/api/auth/account-delete/route.test.ts— Successful deletion rotation and backend failure handling.src/app/api/auth/session-recovery/route.test.tsandsrc/app/api.test.ts— 401 recovery routing and one-attempt recovery behavior.
Repair utility tests (scripts/repair-account-deletions.test.mjs):
- Argument parsing, dry-run behavior, apply mode validation, environment variable handling, batch size limits, error conditions.
Known constraints¶
- Maximum 50 distinct user IDs per repair-utility invocation (for bounded memory and API batch size).
- Session revocation marker TTL is 32 days (approximately one month, not exactly 30).
- Completed operation metadata (after sensitive arrays are cleared) has a 24-hour TTL; after expiration, the operation record is removed.
- Cosmos automatic backups may contain deleted data; restoration requires documented re-erasure and reconciliation.
- There is no application-level rollback; deletion is intentionally destructive.
Before any release decision¶
- Complete the repository formatter, lint, build, unit, frontend, and browser checks.
- Obtain privacy/legal review of the full data inventory, retention policy, backup restoration procedure, and operator approvals.
- Review the target, rollout, monitoring, and rollback constraints before any separately approved push or deployment.
Pending work in this branch¶
- Final repair-utility and runbook documentation commit (hash not yet created).
- Final broad repository validation.
- Privacy/legal review and any operator training required before release.