From b21b2bc3783d790b87d97e7b6b7c8de5af9e2fad Mon Sep 17 00:00:00 2001 From: Quintine <15965533+Quintine@users.noreply.github.com> Date: Sun, 20 Sep 2026 16:30:37 +1000 Subject: [PATCH] Add one-use consent for a named player to start seat AI Let a human owner authorize another human in the started room to start a fixed difficulty once within 24 hours. The owner retains the seat, cookie, private hand, recovery setup and takeback control. Consent is explicit even while online; neither host status nor inactivity authorizes a takeover. Activation enters the existing paced private-view AI path without strategic changes. Add additive migration 0006, both exact session fences, owner/delegate-only metadata in the authenticated room snapshot, atomic CAS activation and consumption, expiry and terminal retry receipts. Replacement hides older consent; own AI changes invalidate unused consent. Recovery or handover of either bound seat invalidates the grant. Future-version guards prevent stale computed state from overwriting a racing action. Exact browser retry records retain the original operation/version across refresh and cannot rearm old consent. Shared HTTP continuation preserves coalescing across ordinary and control routes. Independent review found no material remaining issue. Revoke messaging accurately handles activation winning the race. Browser QA exercised grant/revoke, preserved consent after refresh, reciprocal fixed-profile activation, consumed receipts, keyboard takeback and private ownership. The panel now remains expanded after success and action buttons are at least 44px. Responsive screenshot acceptance remains open because the browser viewport override targeted a failed secondary-origin tab; desktop controls and no-overflow width were verified. The QA room is stopped at a genuine human setup decision with both seats taken back. Types, lint, all 4906 offline tests, production build and all 45 HTTP tests pass on the stable source fingerprint. Seven new offline cases cover client consent/retry validation and real SQLite privacy, restart, one-use races, future versions, takeback, expiry and both-seat recovery/handover; two new HTTP cases cover authentication, injection, fixed-profile continuation and takeback. The first broad run exposed 68 legacy VM fixtures missing the new production dependency; their mappings were updated and the real shared continuation remains exercised. The historical 0005 migration test verifies backfill before applying 0006 for current code. All 1174 original rooms, 2456 seats and every prior recovery/entry/handover/migration row remain unchanged. SQLite integrity and foreign keys pass; migration and QA added 88 rooms and 188 seats. No reset, server restart, usage check or automation was performed. The current Sites integration has no supported durable Cron/DO provisioning path. Document this platform blocker rather than adding an inert scheduled export; unattended resumption and broader network-failure acceptance remain unfinished. Full rules, component, AI strength and publication gates remain closed. Verified source tree: 2d86fc611e9ef4f5a10db10f96687a31db1ec238908ecf1e9333c50fac9ccaa8 --- README.md | 7 + app/api/rooms/[code]/control/route.ts | 41 ++ app/api/rooms/[code]/route.ts | 18 +- app/page.tsx | 22 +- components/seat-ai-delegation.tsx | 366 +++++++++++ db/room-continuation.ts | 17 + db/rooms.ts | 510 ++++++++++++++- db/schema.ts | 21 + docs/AUTOPILOT.md | 28 +- docs/CURRENT_STATUS.md | 31 +- docs/IMPLEMENTATION_STATUS.md | 15 + docs/MULTIPLAYER_AUDIT.md | 2 +- docs/SEAT_AI_PERMISSION.md | 65 ++ drizzle/0006_thick_imperial_guard.sql | 16 + drizzle/meta/0006_snapshot.json | 608 ++++++++++++++++++ drizzle/meta/_journal.json | 9 +- game/engine.ts | 4 +- game/reference.ts | 26 +- lib/seat-ai-delegation.ts | 102 +++ tests/auction-cancellation-recovery.test.ts | 2 + tests/automatic-response-recovery.test.ts | 8 + tests/base-setup-recovery.test.ts | 2 + tests/battle-aftermath-recovery.test.ts | 2 + tests/battle-discard-recovery.test.ts | 2 + tests/bg-karama-cancel-recovery.test.ts | 2 + tests/bg-karama-opportunity-recovery.test.ts | 2 + tests/bidding-end-recovery.test.ts | 2 + tests/bot-continuation.test.ts | 2 + tests/bot-pacing.test.ts | 9 + tests/box-discard-recovery.test.ts | 2 + tests/choam-auditor-recovery.test.ts | 2 + ...am-worthless-cancellation-recovery.test.ts | 2 + tests/combat-terminal-recovery.test.ts | 2 + tests/disaster-revival-recovery.test.ts | 2 + tests/distrans-recovery.test.ts | 2 + tests/ecaz-alliance-recovery.test.ts | 2 + tests/ecaz-collection-recovery.test.ts | 2 + tests/ecaz-duke-recovery.test.ts | 2 + tests/ecaz-entry-recovery.test.ts | 2 + tests/ecaz-occupy-recovery.test.ts | 2 + tests/ecaz-victory-recovery.test.ts | 2 + tests/fixture-nexus-room-store.ts | 2 + tests/fixture-room-continuation.ts | 37 ++ tests/fremen-ambassador-recovery.test.ts | 2 + tests/fremen-movement-recovery.test.ts | 2 + tests/ghola-lifecycle-recovery.test.ts | 2 + tests/grumman-collection-recovery.test.ts | 2 + tests/guild-ambassador-recovery.test.ts | 2 + .../guild-homeworld-shipment-recovery.test.ts | 2 + tests/guild-payment-recovery.test.ts | 2 + tests/homeworld-battle-recovery.test.ts | 2 + tests/homeworld-benefits-recovery.test.ts | 2 + tests/homeworld-collection-recovery.test.ts | 2 + tests/homeworld-grumman-recovery.test.ts | 2 + tests/homeworld-mobility-recovery.test.ts | 2 + .../homeworld-payment-income-recovery.test.ts | 2 + tests/homeworld-recovery.test.ts | 2 + ...eworld-revival-ambassador-recovery.test.ts | 2 + ...eworld-revival-deployment-recovery.test.ts | 2 + tests/homeworld-shipment-recovery.test.ts | 2 + ...eworld-spiritual-advisors-recovery.test.ts | 2 + tests/homeworld-tupile-sales-recovery.test.ts | 2 + ...rld-victory-reinforcement-recovery.test.ts | 2 + tests/juice-of-sapho-recovery.test.ts | 2 + tests/junction-transport-recovery.test.ts | 2 + .../multiplayer-discard-continuations.test.ts | 2 + tests/nullentropy-box-recovery.test.ts | 2 + tests/ordinary-card-discard-recovery.test.ts | 2 + tests/ornithopter-discard-recovery.test.ts | 2 + tests/ornithopter-recovery.test.ts | 2 + tests/paced-games.test.ts | 2 + ...ending-shipment-integrity-recovery.test.ts | 2 + tests/placement-cancellation-recovery.test.ts | 2 + tests/portable-snooper-recovery.test.ts | 2 + tests/residual-poison-recovery.test.ts | 2 + tests/restored-cancellation-recovery.test.ts | 2 + .../richese-allied-no-field-recovery.test.ts | 2 + tests/richese-auction-recovery.test.ts | 2 + tests/richese-gift-recovery.test.ts | 2 + tests/richese-no-field-recovery.test.ts | 2 + tests/room-entry-recovery.test.ts | 2 + tests/seat-ai-delegation-client.test.ts | 142 ++++ tests/seat-ai-delegation-http.test.ts | 233 +++++++ tests/seat-ai-delegation-recovery.test.ts | 527 +++++++++++++++ tests/seat-handover-store.test.ts | 70 +- tests/seat-recovery.test.ts | 2 + tests/shipment-promises-recovery.test.ts | 2 + tests/stone-burner-recovery.test.ts | 2 + tests/stronghold-recovery.test.ts | 2 + tests/terror-discard-recovery.test.ts | 2 + tests/truthtrance-discard-recovery.test.ts | 2 + tests/truthtrance-spice-recovery.test.ts | 2 + tests/tupile-intelligence-recovery.test.ts | 2 + 93 files changed, 2996 insertions(+), 72 deletions(-) create mode 100644 components/seat-ai-delegation.tsx create mode 100644 db/room-continuation.ts create mode 100644 docs/SEAT_AI_PERMISSION.md create mode 100644 drizzle/0006_thick_imperial_guard.sql create mode 100644 drizzle/meta/0006_snapshot.json create mode 100644 lib/seat-ai-delegation.ts create mode 100644 tests/fixture-room-continuation.ts create mode 100644 tests/seat-ai-delegation-client.test.ts create mode 100644 tests/seat-ai-delegation-http.test.ts create mode 100644 tests/seat-ai-delegation-recovery.test.ts diff --git a/README.md b/README.md index 815b0dfd..3d66ae3f 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,13 @@ Use **Protect your saved seat** to generate and privately save a recovery kit be If recovery receives no confirmed response, keep the page open and retry the same recovery request. The server recognizes the receipt and does not rotate twice. Replacing the recovery key invalidates the older kit. Host-initiated takeover remains unfinished. An owning human seat can enable or disable its own AI control during a started game. +For a planned absence, **Let a player start AI for your seat** grants one named +human player permission to start your chosen difficulty once within 24 hours. +They can activate it while you are online, but receive no private seat access. +You can revoke unused permission or take back control. Recovering or transferring +either seat invalidates the grant. See [AI permission](docs/SEAT_AI_PERMISSION.md) +for saved retries and limits. + New create/join requests save a private, tab-scoped retry record before sending. If the response is uncertain, keep the tab open and use the explicit retry; refresh preserves the same request. Confirmed success removes that record. Clearly rejected first requests return to the form for correction. A retry can recover the original room and seat without creating duplicates, but closing the tab or clearing its data can lose the proof. This record is separate from the long-term seat recovery kit. An uncertain saved-kit recovery keeps its exact retry details in memory and prevents conflicting navigation. If that recovery has become obsolete, deliberate abandonment releases the controls after explaining that it cannot undo a completed recovery. Keep a valid saved kit before discarding retry details. diff --git a/app/api/rooms/[code]/control/route.ts b/app/api/rooms/[code]/control/route.ts index 2f09f1ff..58d070ef 100644 --- a/app/api/rooms/[code]/control/route.ts +++ b/app/api/rooms/[code]/control/route.ts @@ -6,8 +6,15 @@ import { recoverSeat, SeatControlError, setRecoveryKey, + setSeatAiDelegate, + revokeSeatAiDelegate, + useSeatAiDelegate as activateSeatAiDelegate, + needsAutomaticRoomRecovery, } from '@/db/rooms'; import { RuleError } from '@/game/engine'; +import { validSeatAiDelegateRequest } from '@/lib/seat-ai-delegation'; +import { resumeRoom } from '@/db/room-continuation'; +import { waitUntil } from 'cloudflare:workers'; const noStore = { 'Cache-Control': 'no-store' }; export async function POST(req: Request) { try { @@ -47,6 +54,40 @@ export async function POST(req: Request) { .map((part) => part.trim()) .find((part) => part.startsWith(`dune_${code}=`)) ?.split('=')[1] ?? ''; + if ( + input.type === 'setSeatAiDelegate' || + input.type === 'revokeSeatAiDelegate' || + input.type === 'useSeatAiDelegate' + ) { + if (!validSeatAiDelegateRequest(input)) + throw new SeatControlError( + 'The AI permission request is invalid.', + 'INVALID_CONTROL_REQUEST', + 400, + ); + const auth = await authenticate(code, token); + const result = + input.type === 'setSeatAiDelegate' + ? await setSeatAiDelegate(code, auth, input.version, { + grantId: input.grantId, + delegateId: input.delegateId, + difficulty: input.difficulty, + }) + : input.type === 'revokeSeatAiDelegate' + ? await revokeSeatAiDelegate( + code, + auth, + input.version, + input.grantId, + ) + : await activateSeatAiDelegate(code, auth, input.version, { + ownerId: input.ownerId, + grantId: input.grantId, + }); + if (result.view.botsPending || needsAutomaticRoomRecovery(result.view)) + waitUntil(resumeRoom(code)); + return Response.json(result, { headers: noStore }); + } if ( input.type === 'setRecoveryKey' || input.type === 'createSeatHandover' || diff --git a/app/api/rooms/[code]/route.ts b/app/api/rooms/[code]/route.ts index 53a10add..765b5d65 100644 --- a/app/api/rooms/[code]/route.ts +++ b/app/api/rooms/[code]/route.ts @@ -4,29 +4,13 @@ import { joinRoom, act, RoomEntryError, - continueRoomBots, - continueRoomAutomatic, needsAutomaticRoomRecovery, type SeatAuth, } from '@/db/rooms'; import { RuleError } from '@/game/engine'; import type { FactionId } from '@/game/catalog'; import { waitUntil } from 'cloudflare:workers'; -// Coalesce overlapping polls inside this isolate. Database CAS still fences -// other isolates, restarts, seat recovery, and human actions. -const continuations = new Map>(); -function resumeRoom(code: string): Promise { - const existing = continuations.get(code); - if (existing) return existing; - const pending = (async () => { - await continueRoomAutomatic(code); - await continueRoomBots(code); - })().finally(() => { - if (continuations.get(code) === pending) continuations.delete(code); - }); - continuations.set(code, pending); - return pending; -} +import { resumeRoom } from '@/db/room-continuation'; const codeOf = (req: Request) => { const code = new URL(req.url).pathname.split('/').pop()!.toUpperCase(); diff --git a/app/page.tsx b/app/page.tsx index cb616d11..07170638 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -7,6 +7,7 @@ import { SeatHandoverClaim, } from '@/components/seat-handover'; import { HANDOVER_CLAIM_STORAGE_KEY } from '@/lib/seat-handover'; +import { SeatAiDelegation } from '@/components/seat-ai-delegation'; import { SeatRecoverySetup, SeatRecoveryClaim, @@ -80,6 +81,7 @@ export default function Home() { const [showEntryRecovery, setShowEntryRecovery] = useState(false); const [showHandover, setShowHandover] = useState(false); const [handoverPending, setHandoverPending] = useState(true); + const [aiPermissionPending, setAiPermissionPending] = useState(true); const [abandonAcknowledged, setAbandonAcknowledged] = useState(false); const f = faction(selected); const roomCode = game?.code; @@ -447,6 +449,7 @@ export default function Home() { function exitTable() { if ( handoverPending || + aiPermissionPending || mutationPending.current || reconnectPending.current || seatClaimUncertain.current @@ -454,6 +457,7 @@ export default function Home() { return; activeRoom.current = null; setHandoverPending(true); + setAiPermissionPending(true); activeSeat.current = null; ++epoch.current; recovery.current = null; @@ -590,6 +594,7 @@ export default function Home() { return; if (claim) { setHandoverPending(true); + setAiPermissionPending(true); activeRoom.current = view.code; activeSeat.current = view.me; ++epoch.current; @@ -667,7 +672,7 @@ export default function Home() { send={send} busy={busy || needsReconcile} onExit={exitTable} - exitDisabled={handoverPending} + exitDisabled={handoverPending || aiPermissionPending} />
{(entryAttempt || entryProblem) && ( @@ -678,7 +683,12 @@ export default function Home() {

{(notice || connection || needsReconcile || botRecovery) && ( diff --git a/components/seat-ai-delegation.tsx b/components/seat-ai-delegation.tsx new file mode 100644 index 00000000..ab82eefd --- /dev/null +++ b/components/seat-ai-delegation.tsx @@ -0,0 +1,366 @@ +'use client'; + +import { useEffect, useId, useRef, useState } from 'react'; +import type { GameView } from '@/game/engine'; +import { DIFFICULTIES, type Difficulty } from '@/game/bot-profiles'; +import { Button } from './ui/button'; +import { requestJson, requestMayHaveCompleted } from '@/lib/client-request'; +import { + parseSeatAiDelegateRequest, + seatAiDelegateStorageKey, + storeSeatAiDelegateRequest, + type SeatAiDelegateRequest, +} from '@/lib/seat-ai-delegation'; + +/** Mounted separately for each authenticated room/seat. No recipient gets a seat key. */ +export function SeatAiDelegation({ + game, + disabled, + onPending, + onUncertain, + onRestored, +}: { + game: GameView; + disabled: boolean; + onPending: (value: boolean) => void; + onUncertain: (value: boolean) => void; + onRestored: (view: GameView) => void; +}) { + const id = useId(); + const pending = useRef(false); + const [loaded, setLoaded] = useState(false); + const [expanded, setExpanded] = useState(false); + const [now, setNow] = useState(Date.now); + const [record, setRecord] = useState(null); + const [storageProblem, setStorageProblem] = useState(false); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(''); + const [abandon, setAbandon] = useState(false); + const [delegateId, setDelegateId] = useState(''); + const [difficulty, setDifficulty] = useState('Medium'); + const key = seatAiDelegateStorageKey(game.code, game.me); + useEffect(() => { + try { + const saved = sessionStorage.getItem(key); + if (saved !== null) { + // oxlint-disable-next-line react/react-compiler -- Restore this seat's exact pending request after SSR. + setRecord(parseSeatAiDelegateRequest(saved)); + setExpanded(true); + } + } catch { + setStorageProblem(true); + setExpanded(true); + setMessage( + 'The saved AI permission request could not be read. Restore access to tab storage and reload, or discard the record below.', + ); + } + setLoaded(true); + }, [key]); + useEffect(() => { + const timer = setInterval(() => setNow(Date.now()), 1000); + return () => clearInterval(timer); + }, []); + useEffect(() => { + onUncertain(!loaded || !!record || storageProblem); + }, [loaded, record, storageProblem, onUncertain]); + const own = game.players.find((player) => player.id === game.me); + const peers = game.players.filter( + (player) => player.id !== game.me && !player.bot, + ); + const grants = game.seatAiDelegations ?? []; + const ownGrant = grants.find((grant) => grant.ownerId === game.me); + const received = grants.filter((grant) => grant.delegateId === game.me); + const started = ['setup', 'playing'].includes(game.status); + const locked = disabled || busy || !loaded; + if (!own || own.bot) return null; + + function store(next: SeatAiDelegateRequest | null) { + storeSeatAiDelegateRequest(sessionStorage, key, next); + setRecord(next); + setStorageProblem(false); + } + async function submit(request: SeatAiDelegateRequest) { + if (locked || pending.current) return; + pending.current = true; + setBusy(true); + setExpanded(true); + setAbandon(false); + onPending(true); + let dispatched = false; + try { + store(request); + dispatched = true; + const result = await requestJson<{ view: GameView }>( + `/api/rooms/${game.code}/control`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(request), + }, + ); + if ( + result.view?.code !== game.code || + result.view?.me !== game.me || + !Number.isSafeInteger(result.view.version) || + result.view.version < request.version || + !Array.isArray(result.view.players) + ) + throw new Error( + 'The server did not confirm the AI permission request.', + ); + onRestored(result.view); + store(null); + const confirmedGrant = result.view.seatAiDelegations?.find( + (grant) => grant.grantId === request.grantId, + ); + setMessage( + request.type === 'setSeatAiDelegate' + ? confirmedGrant && + confirmedGrant.usedAt === null && + confirmedGrant.expiresAt > Date.now() + ? 'Permission saved. The named player can start the chosen AI once before its expiry.' + : 'The original permission request is confirmed. That permission has already been used, expired or invalidated; it was not renewed.' + : request.type === 'revokeSeatAiDelegate' + ? 'This permission can no longer start AI. If AI already started, use Take back control. Completed decisions remain.' + : 'The permission was used. Check the current AI state at the table; the owner keeps the seat and can take back control.', + ); + } catch (error) { + const uncertain = dispatched && requestMayHaveCompleted(error); + if (!dispatched) setStorageProblem(true); + if (dispatched && !uncertain) { + try { + store(null); + } catch { + setStorageProblem(true); + } + } + setMessage( + `${(error as Error).message}${ + uncertain + ? ' The outcome is uncertain. Retry the exact saved request; it cannot start AI a second time.' + : dispatched + ? ' No new attempt will be sent automatically. The current table shows any earlier completed change.' + : ' No request was sent.' + }`, + ); + } finally { + pending.current = false; + setBusy(false); + onPending(false); + } + } + const name = (playerId: string) => + game.players.find((player) => player.id === playerId)?.name ?? 'Player'; + return ( +
setExpanded(event.currentTarget.open)} + > + + Let a player start AI for your seat + +

+ Choose another human player who may start your chosen AI once, within 24 + hours. They can use this permission even while you are online. They get + no access to your hand or seat credentials. You keep your seat, recovery + kit and Take back control button. +

+

+ AI may spend spice, move forces and commit battle plans. Completed + decisions cannot be undone. Replacing or revoking permission, changing + your own AI control, or recovering or transferring either seat + invalidates unused permission. +

+ {record || storageProblem ? ( +
+

+ Confirm the saved request before granting another permission. + Refresh keeps the same request in this tab. +

+ {record && ( + + )} + + +
+ ) : ( +
+ {ownGrant && ( +
+

+ {name(ownGrant.delegateId)} · {ownGrant.difficulty} ·{' '} + {ownGrant.usedAt !== null + ? 'Already used' + : ownGrant.expiresAt <= now + ? 'Expired' + : 'Available once'} + . +

+

+ Expires {new Date(ownGrant.expiresAt).toLocaleString()}. +

+ {ownGrant.usedAt === null && ( + + )} +
+ )} + {started && !own.autopilot && peers.length > 0 && ( +
+ + + + + +
+ )} + {!started &&

Permission can be granted after the game starts.

} + {own.autopilot && ( +

+ Your AI is already running. Use Take back control at the table + before granting another permission. +

+ )} + {received.map((grant) => ( +
+

+ {name(grant.ownerId)} authorized you to start {grant.difficulty}{' '} + AI for their seat once. +

+

+ Expires {new Date(grant.expiresAt).toLocaleString()}. +

+ {grant.usedAt !== null ? ( +

Permission already used.

+ ) : grant.expiresAt <= now ? ( +

Permission expired.

+ ) : ( + + )} +
+ ))} +
+ )} + {message && {message}} +
+ ); +} diff --git a/db/room-continuation.ts b/db/room-continuation.ts new file mode 100644 index 00000000..ea218fa5 --- /dev/null +++ b/db/room-continuation.ts @@ -0,0 +1,17 @@ +import { continueRoomAutomatic, continueRoomBots } from './rooms'; + +// Coalesce polls and control requests inside this isolate. Database CAS fences +// other isolates, restarts, seat recovery and human actions. +const continuations = new Map>(); +export function resumeRoom(code: string): Promise { + const existing = continuations.get(code); + if (existing) return existing; + const pending = (async () => { + await continueRoomAutomatic(code); + await continueRoomBots(code); + })().finally(() => { + if (continuations.get(code) === pending) continuations.delete(code); + }); + continuations.set(code, pending); + return pending; +} diff --git a/db/rooms.ts b/db/rooms.ts index 6cb28b5c..3b94c22a 100644 --- a/db/rooms.ts +++ b/db/rooms.ts @@ -9,9 +9,19 @@ import { RuleError, type Action, type Game, + type GameView, } from '@/game/engine'; import type { FactionId } from '@/game/catalog'; +import type { Difficulty } from '@/game/bot-profiles'; import { runBots } from '@/game/bots'; +import { + validSeatAiGrantId, + validSetSeatAiDelegateInput, + validUseSeatAiDelegateInput, + type SeatAiDelegationView, + type SetSeatAiDelegateInput, + type UseSeatAiDelegateInput, +} from '@/lib/seat-ai-delegation'; export const ONLINE_BOT_INTERVAL_MS = 1500; /** Internal trusted dependency; never accepted from HTTP inputs. */ export type RoomsClock = { @@ -362,39 +372,93 @@ export async function act( const next = applyAction(current, id, action); queueRoomBots(next, current, clock.now()); next.version++; - const result = await db() + const now = clock.now(); + const update = db() .prepare( 'UPDATE rooms SET state = ?, version = version + 1, updated_at = ? WHERE code = ? AND version = ? AND EXISTS (SELECT 1 FROM seats WHERE room_code = ? AND player_id = ? AND token_hash = ? AND revoked = 0)', ) .bind( JSON.stringify(next), - clock.now(), + now, code, version, code, auth.playerId, auth.tokenHash, - ) - .run(); - if (result.meta.changes !== 1) + ); + const results = + action.type === 'setAutopilot' + ? await db().batch([ + update, + db() + .prepare( + 'UPDATE seat_ai_delegations SET revoked_at = ? WHERE room_code = ? AND owner_id = ? AND owner_session_hash = ? AND used_at IS NULL AND revoked_at IS NULL AND changes() = 1', + ) + .bind(now, code, auth.playerId, auth.tokenHash), + ]) + : [await update.run()]; + if (results[0].meta.changes !== 1) throw new RuleError( 'Another action arrived first. Your view has refreshed; try again.', ); - return viewGame(next, id); + return readSeatView(code, auth); } /** Check the credential and load its private state in one database statement. */ export async function readSeatView(code: string, auth: SeatAuth) { const row = await db() .prepare( - 'SELECT rooms.state, rooms.version FROM rooms JOIN seats ON seats.room_code = rooms.code WHERE rooms.code = ? AND seats.player_id = ? AND seats.token_hash = ? AND seats.revoked = 0', + `SELECT rooms.state, rooms.version, + CASE WHEN COUNT(delegations.grant_id) = 0 THEN NULL ELSE + json_group_array(json_object( + 'grantId', delegations.grant_id, + 'ownerId', delegations.owner_id, + 'delegateId', delegations.delegate_id, + 'difficulty', delegations.difficulty, + 'expiresAt', delegations.expires_at, + 'usedAt', delegations.used_at + )) END AS seat_ai_delegations + FROM rooms + JOIN seats AS viewer ON viewer.room_code = rooms.code + LEFT JOIN seat_ai_delegations AS delegations + ON delegations.room_code = rooms.code + AND (delegations.owner_id = viewer.player_id OR delegations.delegate_id = viewer.player_id) + AND delegations.revoked_at IS NULL + AND EXISTS ( + SELECT 1 FROM seats AS owner_session + WHERE owner_session.room_code = delegations.room_code + AND owner_session.player_id = delegations.owner_id + AND owner_session.token_hash = delegations.owner_session_hash + AND owner_session.revoked = 0 + ) + AND EXISTS ( + SELECT 1 FROM seats AS delegate_session + WHERE delegate_session.room_code = delegations.room_code + AND delegate_session.player_id = delegations.delegate_id + AND delegate_session.token_hash = delegations.delegate_session_hash + AND delegate_session.revoked = 0 + ) + WHERE rooms.code = ? AND viewer.player_id = ? + AND viewer.token_hash = ? AND viewer.revoked = 0 + GROUP BY rooms.code, rooms.state, rooms.version`, ) .bind(code, auth.playerId, auth.tokenHash) - .first<{ state: string; version: number }>(); + .first<{ + state: string; + version: number; + seat_ai_delegations: string | null; + }>(); if (!row) throw new RuleError('Your seat could not be verified.'); const g: Game = JSON.parse(row.state); g.version = row.version; - return viewGame(g, auth.playerId); + const view = viewGame(g, auth.playerId) as GameView; + if (row.seat_ai_delegations) { + const delegations = JSON.parse( + row.seat_ai_delegations, + ) as SeatAiDelegationView[]; + if (delegations.length) view.seatAiDelegations = delegations; + } + return view; } /** Scheduling hint only; the engine remains the authority on whether a choice exists. */ @@ -412,7 +476,10 @@ export function needsAutomaticRoomRecovery( !!state.pendingTreacheryDiscard || !!state.response || !!state.richeseAuction || - (!state.decision && !state.response && state.battle?.revealed === true && state.battle.territory.startsWith('homeworld:')) || + (!state.decision && + !state.response && + state.battle?.revealed === true && + state.battle.territory.startsWith('homeworld:')) || state.decision?.kind === 'choamMarket' || state.decision?.kind === 'choamAudit' || state.decision?.kind === 'choamAuditPayment' || @@ -518,6 +585,425 @@ function controlVersion(value: unknown): asserts value is number { ); } +export const SEAT_AI_DELEGATION_TTL_MS = 24 * 60 * 60 * 1000; +type ControlClock = Pick; +type SeatAiDelegationRow = Readonly<{ + room_code: string; + owner_id: string; + grant_id: string; + delegate_id: string; + difficulty: string; + owner_session_hash: string; + delegate_session_hash: string; + expires_at: number; + used_at: number | null; + revoked_at: number | null; +}>; +const invalidDelegation = (message: string, code = 'INVALID_AI_DELEGATION') => + new SeatControlError( + message, + code, + code === 'AI_DELEGATION_EXPIRED' ? 410 : 409, + ); +async function seatAiDelegation(grantId: string) { + return db() + .prepare( + 'SELECT room_code,owner_id,grant_id,delegate_id,difficulty,owner_session_hash,delegate_session_hash,expires_at,used_at,revoked_at FROM seat_ai_delegations WHERE grant_id = ?', + ) + .bind(grantId) + .first(); +} +async function delegationSessionsActive(row: SeatAiDelegationRow) { + return !!(await db() + .prepare( + `SELECT 1 AS present + FROM seats AS owner_session + JOIN seats AS delegate_session ON delegate_session.room_code = owner_session.room_code + WHERE owner_session.room_code = ? + AND owner_session.player_id = ? AND owner_session.token_hash = ? AND owner_session.revoked = 0 + AND delegate_session.player_id = ? AND delegate_session.token_hash = ? AND delegate_session.revoked = 0`, + ) + .bind( + row.room_code, + row.owner_id, + row.owner_session_hash, + row.delegate_id, + row.delegate_session_hash, + ) + .first()); +} + +export async function setSeatAiDelegate( + code: string, + auth: SeatAuth, + version: unknown, + input: SetSeatAiDelegateInput, + clock: ControlClock = roomsClock, +) { + controlVersion(version); + if (!validSetSeatAiDelegateInput(input)) + throw invalidDelegation( + 'Choose one human seat, an AI difficulty and a fresh delegation identifier.', + ); + const existing = await seatAiDelegation(input.grantId); + if (existing) { + const same = + existing.room_code === code && + existing.owner_id === auth.playerId && + existing.delegate_id === input.delegateId && + existing.difficulty === input.difficulty && + existing.owner_session_hash === auth.tokenHash; + if (!same) + throw invalidDelegation( + 'This delegation identifier is already bound to different consent.', + 'AI_DELEGATION_CHANGED', + ); + if (!(await delegationSessionsActive(existing))) + throw invalidDelegation( + 'A seat credential changed after this delegation was created.', + 'AI_DELEGATION_INVALIDATED', + ); + return { view: await readSeatView(code, auth), replayed: true }; + } + const current = await readRoom(code); + if (current.version !== version) + throw invalidDelegation( + 'The table changed. Reconnect before saving this consent.', + 'STALE_VERSION', + ); + const owner = current.players.find((player) => player.id === auth.playerId); + const delegate = current.players.find( + (player) => player.id === input.delegateId, + ); + if ( + (current.status !== 'setup' && current.status !== 'playing') || + !owner || + owner.bot || + owner.autopilot || + !delegate || + delegate.id === owner.id || + delegate.bot + ) + throw invalidDelegation( + 'A started human seat without active AI may authorize one different human seat.', + 'AI_DELEGATION_UNAVAILABLE', + ); + const delegateSession = await db() + .prepare( + 'SELECT MIN(token_hash) AS token_hash, COUNT(*) AS count FROM seats WHERE room_code = ? AND player_id = ? AND revoked = 0', + ) + .bind(code, delegate.id) + .first<{ token_hash: string | null; count: number }>(); + if (!delegateSession?.token_hash || delegateSession.count !== 1) + throw invalidDelegation( + 'The delegate must have one current authenticated session.', + 'AI_DELEGATION_UNAVAILABLE', + ); + const now = clock.now(); + const expiresAt = now + SEAT_AI_DELEGATION_TTL_MS; + const results = await db().batch([ + db() + .prepare( + `UPDATE rooms SET version = version + 1, updated_at = ? + WHERE code = ? AND version = ? + AND EXISTS (SELECT 1 FROM seats WHERE room_code = ? AND player_id = ? AND token_hash = ? AND revoked = 0) + AND EXISTS (SELECT 1 FROM seats WHERE room_code = ? AND player_id = ? AND token_hash = ? AND revoked = 0) + AND NOT EXISTS (SELECT 1 FROM seat_ai_delegations WHERE grant_id = ?)`, + ) + .bind( + now, + code, + version, + code, + owner.id, + auth.tokenHash, + code, + delegate.id, + delegateSession.token_hash, + input.grantId, + ), + db() + .prepare( + `INSERT INTO seat_ai_delegations( + room_code,owner_id,grant_id,delegate_id,difficulty, + owner_session_hash,delegate_session_hash,expires_at,used_at,revoked_at + ) + SELECT ?,?,?,?,?,?,?,?,NULL,NULL WHERE changes() = 1`, + ) + .bind( + code, + owner.id, + input.grantId, + delegate.id, + input.difficulty, + auth.tokenHash, + delegateSession.token_hash, + expiresAt, + ), + db() + .prepare( + `UPDATE seat_ai_delegations SET revoked_at = ? + WHERE room_code = ? AND owner_id = ? AND grant_id != ? + AND revoked_at IS NULL + AND changes() = 1 + AND EXISTS ( + SELECT 1 FROM seat_ai_delegations AS current_grant + WHERE current_grant.room_code = ? AND current_grant.owner_id = ? + AND current_grant.grant_id = ? + )`, + ) + .bind(now, code, owner.id, input.grantId, code, owner.id, input.grantId), + ]); + if (results[0].meta.changes !== 1 || results[1].meta.changes !== 1) { + const won = await seatAiDelegation(input.grantId); + if ( + won && + won.room_code === code && + won.owner_id === owner.id && + won.delegate_id === delegate.id && + won.difficulty === input.difficulty && + won.owner_session_hash === auth.tokenHash && + won.delegate_session_hash === delegateSession.token_hash && + (await delegationSessionsActive(won)) + ) + return { view: await readSeatView(code, auth), replayed: true }; + throw invalidDelegation( + 'The table, owner or delegate changed. Reconnect before saving this consent.', + 'STALE_VERSION', + ); + } + return { view: await readSeatView(code, auth), replayed: false }; +} + +export async function revokeSeatAiDelegate( + code: string, + auth: SeatAuth, + version: unknown, + grantId: unknown, + clock: ControlClock = roomsClock, +) { + controlVersion(version); + if (!validSeatAiGrantId(grantId)) + throw invalidDelegation('Choose the current AI delegation identifier.'); + const existing = await seatAiDelegation(grantId); + if ( + existing?.room_code === code && + existing.owner_id === auth.playerId && + existing.owner_session_hash === auth.tokenHash && + (existing.revoked_at !== null || existing.used_at !== null) + ) + return { view: await readSeatView(code, auth), replayed: true }; + if ( + !existing || + existing.room_code !== code || + existing.owner_id !== auth.playerId + ) + throw invalidDelegation( + 'This AI delegation is no longer current for your seat.', + 'AI_DELEGATION_CHANGED', + ); + const current = await readRoom(code); + if (current.version !== version) + throw invalidDelegation( + 'The table changed. Reconnect before revoking this consent.', + 'STALE_VERSION', + ); + const now = clock.now(); + const results = await db().batch([ + db() + .prepare( + `UPDATE rooms SET version = version + 1, updated_at = ? + WHERE code = ? AND version = ? + AND EXISTS (SELECT 1 FROM seats WHERE room_code = ? AND player_id = ? AND token_hash = ? AND revoked = 0) + AND EXISTS ( + SELECT 1 FROM seat_ai_delegations AS consent + JOIN seats AS delegate_session + ON delegate_session.room_code = consent.room_code + AND delegate_session.player_id = consent.delegate_id + AND delegate_session.token_hash = consent.delegate_session_hash + AND delegate_session.revoked = 0 + WHERE consent.room_code = ? AND consent.owner_id = ? AND consent.grant_id = ? + AND consent.owner_session_hash = ? + AND consent.used_at IS NULL AND consent.revoked_at IS NULL + )`, + ) + .bind( + now, + code, + version, + code, + auth.playerId, + auth.tokenHash, + code, + auth.playerId, + grantId, + auth.tokenHash, + ), + db() + .prepare( + `UPDATE seat_ai_delegations SET revoked_at = ? + WHERE room_code = ? AND owner_id = ? AND grant_id = ? + AND owner_session_hash = ? AND used_at IS NULL AND revoked_at IS NULL + AND changes() = 1`, + ) + .bind(now, code, auth.playerId, grantId, auth.tokenHash), + ]); + if (results[0].meta.changes !== 1 || results[1].meta.changes !== 1) + throw invalidDelegation( + 'The table, owner, delegate or consent changed. Reconnect before revoking it.', + 'STALE_VERSION', + ); + return { view: await readSeatView(code, auth), replayed: false }; +} + +export async function useSeatAiDelegate( + code: string, + auth: SeatAuth, + version: unknown, + input: UseSeatAiDelegateInput, + clock: RoomsClock = roomsClock, +): Promise<{ view: GameView; replayed?: boolean }> { + controlVersion(version); + if (!validUseSeatAiDelegateInput(input)) + throw invalidDelegation('Choose the current owner and AI delegation.'); + const consent = await seatAiDelegation(input.grantId); + if ( + !consent || + consent.room_code !== code || + consent.owner_id !== input.ownerId || + consent.delegate_id !== auth.playerId || + consent.delegate_session_hash !== auth.tokenHash + ) + throw invalidDelegation( + 'This AI delegation is not available to this seat.', + 'AI_DELEGATION_CHANGED', + ); + if (!(await delegationSessionsActive(consent))) + throw invalidDelegation( + 'A seat credential changed after this delegation was created.', + 'AI_DELEGATION_INVALIDATED', + ); + if (consent.used_at !== null) + return { view: await readSeatView(code, auth), replayed: true }; + if (consent.revoked_at !== null) + throw invalidDelegation( + 'This AI delegation was revoked or replaced.', + 'AI_DELEGATION_CHANGED', + ); + const now = clock.now(); + if (consent.expires_at <= now) + throw invalidDelegation( + 'This AI delegation has expired.', + 'AI_DELEGATION_EXPIRED', + ); + const current = await readRoom(code); + if (current.version !== version) + throw invalidDelegation( + 'The table changed. Reconnect before activating this consent.', + 'STALE_VERSION', + ); + const owner = current.players.find( + (player) => player.id === consent.owner_id, + ); + const delegate = current.players.find( + (player) => player.id === consent.delegate_id, + ); + if ( + (current.status !== 'setup' && current.status !== 'playing') || + !owner || + owner.bot || + owner.autopilot || + !delegate || + delegate.bot + ) + throw invalidDelegation( + 'The owner is no longer available for this delegated AI activation.', + 'AI_DELEGATION_UNAVAILABLE', + ); + const next = applyAction(current, owner.id, { + type: 'setAutopilot', + difficulty: consent.difficulty as Difficulty, + }); + const entry = next.log.at(-1); + if (entry) + entry.text = `${delegate.name} activated ${consent.difficulty} AI for ${owner.name} using their one-use delegation.`; + queueRoomBots(next, current, now); + next.version = current.version + 1; + const results = await db().batch([ + db() + .prepare( + `UPDATE rooms SET state = ?, version = version + 1, updated_at = ? + WHERE code = ? AND version = ? + AND EXISTS ( + SELECT 1 FROM seat_ai_delegations AS consent + JOIN seats AS owner_session + ON owner_session.room_code = consent.room_code + AND owner_session.player_id = consent.owner_id + AND owner_session.token_hash = consent.owner_session_hash + AND owner_session.revoked = 0 + JOIN seats AS delegate_session + ON delegate_session.room_code = consent.room_code + AND delegate_session.player_id = consent.delegate_id + AND delegate_session.token_hash = consent.delegate_session_hash + AND delegate_session.revoked = 0 + WHERE consent.room_code = ? AND consent.owner_id = ? + AND consent.delegate_id = ? AND consent.grant_id = ? + AND consent.owner_session_hash = ? AND consent.delegate_session_hash = ? + AND consent.expires_at > ? AND consent.used_at IS NULL + AND consent.revoked_at IS NULL + )`, + ) + .bind( + JSON.stringify(next), + now, + code, + version, + code, + consent.owner_id, + consent.delegate_id, + consent.grant_id, + consent.owner_session_hash, + consent.delegate_session_hash, + now, + ), + db() + .prepare( + `UPDATE seat_ai_delegations SET used_at = ? + WHERE room_code = ? AND owner_id = ? AND delegate_id = ? AND grant_id = ? + AND owner_session_hash = ? AND delegate_session_hash = ? + AND expires_at > ? AND used_at IS NULL AND revoked_at IS NULL + AND changes() = 1`, + ) + .bind( + now, + code, + consent.owner_id, + consent.delegate_id, + consent.grant_id, + consent.owner_session_hash, + consent.delegate_session_hash, + now, + ), + ]); + if (results[0].meta.changes !== 1 || results[1].meta.changes !== 1) { + const won = await seatAiDelegation(input.grantId); + if ( + won?.used_at !== null && + won?.room_code === code && + won?.owner_id === input.ownerId && + won?.delegate_id === auth.playerId && + won?.delegate_session_hash === auth.tokenHash && + (await delegationSessionsActive(won)) + ) + return { view: await readSeatView(code, auth), replayed: true }; + throw invalidDelegation( + 'The table, owner, delegate or consent changed. Retry the exact activation after reconnecting.', + 'STALE_VERSION', + ); + } + return { view: await readSeatView(code, auth), replayed: false }; +} + export async function setRecoveryKey( code: string, auth: SeatAuth, @@ -1171,9 +1657,7 @@ export async function claimSeatHandover( claimed ? 'This handover offer has already been claimed.' : 'The table or handover offer changed. Retry the exact claim request.', - claimed - ? 'HANDOVER_ALREADY_CLAIMED' - : 'STALE_VERSION', + claimed ? 'HANDOVER_ALREADY_CLAIMED' : 'STALE_VERSION', ); } return { diff --git a/db/schema.ts b/db/schema.ts index 06738039..5c749954 100644 --- a/db/schema.ts +++ b/db/schema.ts @@ -88,6 +88,27 @@ export const seatHandoverClaimReceipts = sqliteTable( ], ); +export const seatAiDelegations = sqliteTable( + 'seat_ai_delegations', + { + roomCode: text('room_code') + .notNull() + .references(() => rooms.code, { onDelete: 'cascade' }), + ownerId: text('owner_id').notNull(), + grantId: text('grant_id').notNull().unique(), + delegateId: text('delegate_id').notNull(), + difficulty: text('difficulty').notNull(), + ownerSessionHash: text('owner_session_hash').notNull(), + delegateSessionHash: text('delegate_session_hash').notNull(), + expiresAt: integer('expires_at').notNull(), + usedAt: integer('used_at'), + revokedAt: integer('revoked_at'), + }, + (table) => [ + primaryKey({ columns: [table.roomCode, table.ownerId, table.grantId] }), + ], +); + export const roomEntryReceipts = sqliteTable('room_entry_receipts', { operationHash: text('operation_hash').primaryKey(), requestHash: text('request_hash').notNull(), diff --git a/docs/AUTOPILOT.md b/docs/AUTOPILOT.md index 490b4464..9f820d9c 100644 --- a/docs/AUTOPILOT.md +++ b/docs/AUTOPILOT.md @@ -18,7 +18,31 @@ An accepted API action processes a bounded AI batch. If more work is pending, th The current continuation has a sixteen-batch budget. It is **best effort, not a durable scheduler**. Cloudflare permits work after response/disconnect for a bounded period; runtime interruption or exhaustion can leave the persisted `botsPending` flag for a later explicit continuation. The existing browser reconnect/resume flow can resume it. No automatic platform alarm resumes a room after an unattended server restart. That remaining reliability requirement must be implemented and verified before claiming fully unattended operation. [Cloudflare duration limits](https://developers.cloudflare.com/workers/platform/limits/#duration), [module waitUntil export](https://blog.cloudflare.com/nodejs-workers-2025/). -GET remains a private read and does not advance a game. The all-controlled HTTP acceptance case polls only GET after the final delegation request, proving the observed completion came from the request's server continuation. +GET returns the caller's private view and can schedule pending automatic/AI work +through the same bounded continuation used by POST. Polling or reopening can +therefore wake persisted work. It does not establish unattended recovery after +all requests stop. + +### Platform audit, 20 September 2026 + +The current Sites integration exposes no supported Cron Trigger or Durable +Object provisioning contract. Vinext can compile a custom Worker entry with a +`scheduled` handler, but that export does nothing without an installed trigger. +The generated local Wrangler configuration is not a Sites deployment contract. +No inert handler or pretend scheduler has been added. + +Cloudflare Cron requires a separately configured trigger and has minute-level +scheduling. It could enforce a minimum interval, but cannot provide regular +1.5-second wakeups. Durable Object alarms provide finer scheduling, but this +project has no supported binding/provisioning path. D1 due metadata alone cannot +wake a Worker. This milestone is blocked on an available durable scheduler; +independent multiplayer work continues. See [Cron configuration](https://developers.cloudflare.com/workers/configuration/cron-triggers/) +and [Durable Object alarms](https://developers.cloudflare.com/durable-objects/api/alarms/). + +The optional [named-player permission](SEAT_AI_PERMISSION.md) now connects a +one-use, fixed-difficulty activation without transferring the owner's seat or +private information. It uses the same best-effort continuation and does not +remove the scheduling limitation. ## Coverage ledger @@ -30,7 +54,7 @@ GET remains a private read and does not advance a game. The all-controlled HTTP | Background batches cannot overwrite takeback | Current-state read and version-fenced update per batch | Normal reconnect/resume controls | Only persisted bot/autopilot seats run | Five SQLite `bot-continuation.test.ts` cases, including real authenticated takeover race | | Complete an all-controlled game | POST schedules background continuation | Final outcome remains inspectable | Three original human credentials preserved | HTTP final opt-in returned playing, later GET finished; no subsequent gameplay POST | | Responsive and refresh flow | Saved mode read after refresh | Mobile 44px takeback, separate opt-in, keyboard-native controls | Inspection remains readable during delegation | Browser room2SG3ZS3E; details in `VISUAL_PLAYTEST.md` | -| Durable unattended restart scheduling | Missing | Reopen/resume available | No automatic host takeover | Not certified; next reliability work | +| Durable unattended restart scheduling | Blocked on supported platform trigger/binding | Reopen/resume available | No automatic host takeover | Current Sites capability audit; no unattended certification | ## Validation checkpoint diff --git a/docs/CURRENT_STATUS.md b/docs/CURRENT_STATUS.md index 57a6e7a8..4883b0bf 100644 --- a/docs/CURRENT_STATUS.md +++ b/docs/CURRENT_STATUS.md @@ -6,26 +6,29 @@ gated.** Prototypes do not open completion or publication gates. ## Current checkpoint and work -Latest delivered gameplay checkpoint: `54c8030`, [Sandmaster worm rides](SANDMASTER_WORM.md). -Types, lint, **4,894 offline tests**, production build and **43 HTTP tests** passed. -Optional native Fremen destination collection connects multi-sector forces, -controls, minimal legal AI and saved Bene Gesserit arrival continuation. All 1,140 -baseline rooms and 2,385 seats stayed unchanged; isolated checks added 34 rooms -and 71 seats. No restart was needed. The `8f7a62c` policy checkpoint removed the +Latest delivered checkpoint: `e13ad45`, [movement and Traitor practice](INTERACTIVE_INTRODUCTION.md). +Types, lint, **4,899 offline tests** and production build passed. Seven lessons +and five exercises connect shared rules and migrated browser-local saves. All +1,174 baseline rooms and 2,456 seats stayed unchanged; no restart was needed. +The preceding `54c8030` connects [Sandmaster worm rides](SANDMASTER_WORM.md). +The `8f7a62c` policy checkpoint removed the usage cutoff and deferred AI refinement until feature completion, with three adjacent 75% win-rate targets. Earlier evidence remains in the [implementation history](IMPLEMENTATION_STATUS.md). -Current work: the [interactive introduction](INTERACTIVE_INTRODUCTION.md) adds -movement and Traitor practice through shared rules, legal controls and migrated -browser-local saves. Broader curriculum remains unfinished. Final verification -and delivery belong to the source-bound private report and Git message. +Current work: [one-use AI permission](SEAT_AI_PERMISSION.md) connects optional +named-player activation at the owner's chosen difficulty, retained ownership, +both session fences and saved exact retries. Final independent review, +verification and delivery belong to the source-bound private report and Git +message. Broader disconnected-seat acceptance remains unfinished. A bounded remaining-effect audit found that the reviewed faction/Nexus candidates still cross recorded pending rulings. Continue independent features rather than -inventing answers. Durable unattended bot resumption is the next clear backend -capability: it needs a platform scheduler and saved due-work metadata; current -request/reconnect continuation does not establish it. +inventing answers. The [platform audit](AUTOPILOT.md#platform-audit-20-september-2026) +found no supported Sites scheduler or Durable Object provisioning contract. +Durable unattended bot resumption remains blocked on that capability; current +request/reconnect continuation does not establish it. Continue independent +player-facing features and integration while preserving pending rules questions. The connected [Harass & Withdraw prototype](HARASS_WITHDRAW_RUNTIME.md) supports either battle-card slot, private category inspections, exact undialed normal/elite @@ -87,7 +90,7 @@ These links define bounded working behavior, not complete module certification. | Nexus/Homeworlds | [Decision index](RULE_DECISIONS.md) links each integrated faction family, native/borrowed effects, physical custody, private choices, payments and transport. [CHOAM Collection trade](NEXUS_CHOAM_SECRET_ALLY.md) and [Emperor extra revival](NEXUS_EMPEROR_SECRET_ALLY_RUNTIME.md) are connected; CHOAM inspection and Emperor purchase remain pending. A source audit or helper alone is not a completed effect. | | Truthtrance | [Spice facts](TRUTHTRANCE_SPICE_FACTS.md), [card counts](TRUTHTRANCE_CARD_COUNT.md), [hand inventory](TRUTHTRANCE_HAND_INVENTORY.md), [recorded knowledge](TRUTHTRANCE_KNOWLEDGE.md), and [Basic/no-Guild Advanced reserve-shipment promises](TRUTHTRANCE_SHIPMENT_PROMISES.md) use authoritative private state. Earlier readiness audits do not supersede these follow-ups. | | Other cards | [Sapho runtime](JUICE_OF_SAPHO_RUNTIME.md) includes first among remaining unstarted movement turns after Advanced Guild has finished. [Recruits](RECRUITS_RUNTIME.md) connects clean Revival play; [Harass & Withdraw](HARASS_WITHDRAW_RUNTIME.md) connects the bounded battle return in the same independent three-card preview. Richese card contracts and the checklist identify other connected effects and explicit gaps. | -| Multiplayer | Saved rooms/seats, [recovery](../README.md#saved-seats-and-reconnecting), uncertain-request retry, [own-seat AI](AUTOPILOT.md), and [voluntary seat handover](SEAT_HANDOVER.md) have connected controls and recovery evidence. | +| Multiplayer | Saved rooms/seats, [recovery](../README.md#saved-seats-and-reconnecting), uncertain-request retry, [own-seat AI](AUTOPILOT.md), [named-player AI permission](SEAT_AI_PERMISSION.md) and [voluntary seat handover](SEAT_HANDOVER.md) have connected controls and recovery evidence. | ## Remaining readiness diff --git a/docs/IMPLEMENTATION_STATUS.md b/docs/IMPLEMENTATION_STATUS.md index 855fea52..50f327ee 100644 --- a/docs/IMPLEMENTATION_STATUS.md +++ b/docs/IMPLEMENTATION_STATUS.md @@ -1,5 +1,20 @@ # Dune implementation status +## 20 September 2026 — One-use named-player AI permission + +The [AI permission prototype](SEAT_AI_PERMISSION.md) connects optional owner +consent to a named human and fixed difficulty for one activation within 24 hours. +It retains ownership and private information, uses both exact session fences, +atomic versioned activation/consumption, owner takeback invalidation and saved +exact retries. Additive migration 0006 preserves existing rooms and seats. +Independent review, focused SQLite/client/HTTP checks, browser acceptance and +final source-bound check/build/HTTP/preservation evidence belong to the private +checkpoint and Git message. No AI strategy or mode/publication gate changes. + +The [Sites platform audit](AUTOPILOT.md#platform-audit-20-september-2026) found no +supported durable trigger or alarm binding. Unattended resumption remains a +platform blocker; no inert scheduler was added or claimed complete. + ## 20 September 2026 — Movement and Traitor introduction exercises The [introduction](INTERACTIVE_INTRODUCTION.md) now connects seven lessons and diff --git a/docs/MULTIPLAYER_AUDIT.md b/docs/MULTIPLAYER_AUDIT.md index 75a859ad..dbc6a99f 100644 --- a/docs/MULTIPLAYER_AUDIT.md +++ b/docs/MULTIPLAYER_AUDIT.md @@ -61,7 +61,7 @@ Normal waiting for a temporarily disconnected player is legitimate; it should no ## Proposed disconnected-seat contract (historical design) -This broader proposal changes operational control of a seat, not board-game rules. Owner recovery and [voluntary handover](SEAT_HANDOVER.md) now have bounded implementations using exact active-token fencing. The separate generation/delegation schema below is historical design and has not been adopted; unattended or host-driven substitution remains unfinished. The passing test count above predates these additions. Preserve the same player ID, faction, resources, hand, traitors, promises, submitted plans, decision ownership and history throughout every transition. Never restart setup or reveal a sealed plan merely because its controller changes. +This broader proposal changes operational control of a seat, not board-game rules. Owner recovery and [voluntary handover](SEAT_HANDOVER.md) have bounded implementations using exact active-token fencing. The current [one-use named-player AI permission](SEAT_AI_PERMISSION.md) also uses exact session fences while retaining owner control. The separate generation/ownership schema below remains historical design and has not been adopted; unattended or host-driven substitution remains unfinished. The passing test count above predates these additions. Preserve the same player ID, faction, resources, hand, traitors, promises, submitted plans, decision ownership and history throughout every transition. Never restart setup or reveal a sealed plan merely because its controller changes. ### Distinguish three cases diff --git a/docs/SEAT_AI_PERMISSION.md b/docs/SEAT_AI_PERMISSION.md new file mode 100644 index 00000000..5f4d7ef8 --- /dev/null +++ b/docs/SEAT_AI_PERMISSION.md @@ -0,0 +1,65 @@ +# Permission to start another player's AI + +An owning human can authorize one named human player in the same started room to +enable a chosen AI difficulty once, within 24 hours. This is optional operational +consent. It does not change board-game rules, transfer ownership or disclose the +owner's private view. It can be used while the owner is online; no inactivity +detector or host privilege substitutes for consent. + +## Connected behavior + +Below the table, **Let a player start AI for your seat** offers a named player and +Easy, Medium, Hard or Brutal. The owner can replace or revoke an unused grant. +The delegate sees its fixed difficulty and expiry and can activate it once. +Both retain their existing credentials, recovery kits and private views. Public +history names the activating delegate. The owner uses the existing **Take back +control** button; completed AI decisions remain in the game. + +The normal `setAutopilot` control branch preserves gameplay and sealed choices. +Activation queues the existing persisted, 1.5-second AI continuation and does not +implement new AI strategy. Setup/playing human seats are supported. Lobby, +finished, permanent-bot and already-controlled owner seats reject new consent or +activation. A delegate must be a different authenticated human in the room. + +## Consent and saved continuation + +Migration `0006_thick_imperial_guard.sql` adds a separate consent table. Each grant +binds its identifier, owner, delegate, chosen difficulty and expiry to both exact +current seat-session hashes. Only the owner and delegate receive its public +metadata, through the same SQL read that authenticates the viewer and loads the +room. Neither hash is projected. Recovering or transferring either seat makes +old consent unusable; a new owner or delegate must establish fresh consent. + +Creation, replacement, revocation and activation use room-version and credential +predicates. A D1 transaction consumes the grant only after its exact versioned +room update succeeds. Taking back or changing one's own AI control invalidates +unused consent in the same transaction. A losing concurrent action cannot leave +the grant consumed without activation, or reactivate a seat after takeback. + +Grant identifiers remain durable receipts. Retrying creation can report its +original result but never renews or rearms a used, expired, revoked or replaced +grant. Retrying activation reports prior use without repeating control changes. +Replacement hides older grants from the current permission list while retaining +their receipts. Expiry is enforced by server time. + +The browser saves the exact operation, grant identifier and original version in +tab storage before dispatch. An uncertain result offers an explicit exact retry; +refresh restores it. Retry never substitutes a newer version or a new grant. +Clearly rejected operations release the retry record. Explicit abandonment +explains that discarding local details cannot cancel a committed request. No +cookie, recovery secret or private hand is stored in this record. + +## Verification and remaining work + +`seat-ai-delegation-recovery.test.ts` exercises real SQLite migrations and the +production store, including one-use custody, both session fences, rejected-action +immutability, races and restored continuations. The client tests verify exact +retry storage and target/profile injection rejection. HTTP tests cover session, +origin, private projection, fixed-profile activation, background work and +takeback. Independent review, browser evidence and final check/build/HTTP results +belong to the private source-bound checkpoint and Git message. + +This is a bounded prototype of preauthorized absence handling. An unprepared lost +seat still cannot be commandeered by a host. Full network-failure acceptance and +durable unattended scheduling remain unfinished. No mode or publication gate is +opened, and strategic AI work remains deferred until non-AI feature completion. diff --git a/drizzle/0006_thick_imperial_guard.sql b/drizzle/0006_thick_imperial_guard.sql new file mode 100644 index 00000000..fab81437 --- /dev/null +++ b/drizzle/0006_thick_imperial_guard.sql @@ -0,0 +1,16 @@ +CREATE TABLE `seat_ai_delegations` ( + `room_code` text NOT NULL, + `owner_id` text NOT NULL, + `grant_id` text NOT NULL, + `delegate_id` text NOT NULL, + `difficulty` text NOT NULL, + `owner_session_hash` text NOT NULL, + `delegate_session_hash` text NOT NULL, + `expires_at` integer NOT NULL, + `used_at` integer, + `revoked_at` integer, + PRIMARY KEY(`room_code`, `owner_id`, `grant_id`), + FOREIGN KEY (`room_code`) REFERENCES `rooms`(`code`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `seat_ai_delegations_grant_id_unique` ON `seat_ai_delegations` (`grant_id`); \ No newline at end of file diff --git a/drizzle/meta/0006_snapshot.json b/drizzle/meta/0006_snapshot.json new file mode 100644 index 00000000..9cb5cdfd --- /dev/null +++ b/drizzle/meta/0006_snapshot.json @@ -0,0 +1,608 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "f1dbb26a-284d-40c6-b25c-41f5dfa64930", + "prevId": "db4830ec-5bf2-4dad-b47a-45ebd3bb63b3", + "tables": { + "room_entry_receipts": { + "name": "room_entry_receipts", + "columns": { + "operation_hash": { + "name": "operation_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "session_hash": { + "name": "session_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "room_code": { + "name": "room_code", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "player_id": { + "name": "player_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "room_entry_receipts_room_code_rooms_code_fk": { + "name": "room_entry_receipts_room_code_rooms_code_fk", + "tableFrom": "room_entry_receipts", + "tableTo": "rooms", + "columnsFrom": [ + "room_code" + ], + "columnsTo": [ + "code" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "rooms": { + "name": "rooms", + "columns": { + "code": { + "name": "code", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "seat_ai_delegations": { + "name": "seat_ai_delegations", + "columns": { + "room_code": { + "name": "room_code", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "grant_id": { + "name": "grant_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "delegate_id": { + "name": "delegate_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "difficulty": { + "name": "difficulty", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_session_hash": { + "name": "owner_session_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "delegate_session_hash": { + "name": "delegate_session_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "seat_ai_delegations_grant_id_unique": { + "name": "seat_ai_delegations_grant_id_unique", + "columns": [ + "grant_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "seat_ai_delegations_room_code_rooms_code_fk": { + "name": "seat_ai_delegations_room_code_rooms_code_fk", + "tableFrom": "seat_ai_delegations", + "tableTo": "rooms", + "columnsFrom": [ + "room_code" + ], + "columnsTo": [ + "code" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "seat_ai_delegations_room_code_owner_id_grant_id_pk": { + "columns": [ + "room_code", + "owner_id", + "grant_id" + ], + "name": "seat_ai_delegations_room_code_owner_id_grant_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "seat_handover_claim_receipts": { + "name": "seat_handover_claim_receipts", + "columns": { + "room_code": { + "name": "room_code", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "player_id": { + "name": "player_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "operation_hash": { + "name": "operation_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "offer_hash": { + "name": "offer_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_hash": { + "name": "secret_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "session_hash": { + "name": "session_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "claim_fence": { + "name": "claim_fence", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "claimed_at": { + "name": "claimed_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "seat_handover_claim_receipts_claim_fence_unique": { + "name": "seat_handover_claim_receipts_claim_fence_unique", + "columns": [ + "claim_fence" + ], + "isUnique": true + } + }, + "foreignKeys": { + "seat_handover_claim_receipts_room_code_rooms_code_fk": { + "name": "seat_handover_claim_receipts_room_code_rooms_code_fk", + "tableFrom": "seat_handover_claim_receipts", + "tableTo": "rooms", + "columnsFrom": [ + "room_code" + ], + "columnsTo": [ + "code" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "seat_handover_claim_receipts_room_code_player_id_operation_hash_pk": { + "columns": [ + "room_code", + "player_id", + "operation_hash" + ], + "name": "seat_handover_claim_receipts_room_code_player_id_operation_hash_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "seat_handover_offers": { + "name": "seat_handover_offers", + "columns": { + "room_code": { + "name": "room_code", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "player_id": { + "name": "player_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "offer_hash": { + "name": "offer_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_hash": { + "name": "secret_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "issuer_session_hash": { + "name": "issuer_session_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "claim_operation_hash": { + "name": "claim_operation_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_hash": { + "name": "session_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claimed_at": { + "name": "claimed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "seat_handover_offers_offer_hash_unique": { + "name": "seat_handover_offers_offer_hash_unique", + "columns": [ + "offer_hash" + ], + "isUnique": true + } + }, + "foreignKeys": { + "seat_handover_offers_room_code_rooms_code_fk": { + "name": "seat_handover_offers_room_code_rooms_code_fk", + "tableFrom": "seat_handover_offers", + "tableTo": "rooms", + "columnsFrom": [ + "room_code" + ], + "columnsTo": [ + "code" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "seat_handover_offers_room_code_player_id_pk": { + "columns": [ + "room_code", + "player_id" + ], + "name": "seat_handover_offers_room_code_player_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "seat_recovery_keys": { + "name": "seat_recovery_keys", + "columns": { + "room_code": { + "name": "room_code", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "player_id": { + "name": "player_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recovery_hash": { + "name": "recovery_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "current_operation_hash": { + "name": "current_operation_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "seat_recovery_keys_room_code_rooms_code_fk": { + "name": "seat_recovery_keys_room_code_rooms_code_fk", + "tableFrom": "seat_recovery_keys", + "tableTo": "rooms", + "columnsFrom": [ + "room_code" + ], + "columnsTo": [ + "code" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "seat_recovery_keys_room_code_player_id_pk": { + "columns": [ + "room_code", + "player_id" + ], + "name": "seat_recovery_keys_room_code_player_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "seat_recovery_receipts": { + "name": "seat_recovery_receipts", + "columns": { + "room_code": { + "name": "room_code", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "player_id": { + "name": "player_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "operation_hash": { + "name": "operation_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recovery_hash": { + "name": "recovery_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "session_hash": { + "name": "session_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "seat_recovery_receipts_room_code_rooms_code_fk": { + "name": "seat_recovery_receipts_room_code_rooms_code_fk", + "tableFrom": "seat_recovery_receipts", + "tableTo": "rooms", + "columnsFrom": [ + "room_code" + ], + "columnsTo": [ + "code" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "seat_recovery_receipts_room_code_player_id_operation_hash_pk": { + "columns": [ + "room_code", + "player_id", + "operation_hash" + ], + "name": "seat_recovery_receipts_room_code_player_id_operation_hash_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "seats": { + "name": "seats", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "revoked": { + "name": "revoked", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "room_code": { + "name": "room_code", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "player_id": { + "name": "player_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "seats_room_code_rooms_code_fk": { + "name": "seats_room_code_rooms_code_fk", + "tableFrom": "seats", + "tableTo": "rooms", + "columnsFrom": [ + "room_code" + ], + "columnsTo": [ + "code" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 04246d92..e4934390 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1789276284776, "tag": "0005_salty_alice", "breakpoints": true + }, + { + "idx": 6, + "version": "6", + "when": 1789883506588, + "tag": "0006_thick_imperial_guard", + "breakpoints": true } ] -} +} \ No newline at end of file diff --git a/game/engine.ts b/game/engine.ts index fa66fe07..03013071 100644 --- a/game/engine.ts +++ b/game/engine.ts @@ -25328,4 +25328,6 @@ export function viewGame(state: Game, id: string) { })), }; } -export type GameView = ReturnType; +export type GameView = ReturnType & { + seatAiDelegations?: import('../lib/seat-ai-delegation').SeatAiDelegationView[]; +}; diff --git a/game/reference.ts b/game/reference.ts index a416de56..c0fcf70a 100644 --- a/game/reference.ts +++ b/game/reference.ts @@ -217,6 +217,7 @@ export const RULE_TOPICS: RuleTopic[] = [ 'ai-pacing', 'table-sounds', 'seat-handover', + 'seat-ai-permission', 'ecaz-modules', 'discoveries', 'homeworlds', @@ -269,6 +270,29 @@ export const RULE_TOPICS: RuleTopic[] = [ { area: 'Verification', status: 'Partial', detail: 'Focused cursor/audio checks and browser preference controls; physical output and broader browser acceptance remain open.', evidence: ['tests/table-sound.test.tsx'] }, ], }, + { + id: 'seat-ai-permission', + title: 'Let a player start AI for your seat', + category: 'Getting started', + coverage: 'Partial', + developmentStage: 'Prototyped', + summary: 'Authorize one named human player to start your chosen AI once while keeping your seat and private information.', + steps: [ + 'After the game starts, open Let a player start AI for your seat below the table. Choose another human and a difficulty, then grant permission. It expires after 24 hours and can be used even while you are online.', + 'The named player can start only the authorized difficulty. They do not receive your hand, seat credentials or recovery kit. Public history records who activated AI.', + 'You can replace or revoke unused permission. Changing your own AI control or recovering or transferring either seat invalidates unused permission. Take back control stops future AI decisions, but completed choices remain.', + 'An uncertain permission request stays in this tab for exact retry, including after refresh. Retrying cannot renew consent or activate AI twice. Discarding a retry record cannot cancel an operation that reached the server.', + 'Host status and disconnection alone never grant permission. A lost unprepared seat and unattended server recovery remain outside this feature.', + ], + related: ['privacy', 'ai-players', 'ai-pacing', 'seat-handover', 'implementation-checklist'], + checklist: [ + { area: 'Implementation', status: 'Implemented', detail: 'One-use, fixed-profile permission with expiry, both credential fences, atomic activation and owner takeback invalidation.' }, + { area: 'Player controls', status: 'Implemented', detail: 'Named owner consent/replacement/revocation and delegate activation; exact tab-scoped retry continuation.' }, + { area: 'AI', status: 'Implemented', detail: 'Uses the existing legal private-view autopilot and saved 1.5-second pacing; no strategy changes.' }, + { area: 'Documentation', status: 'Implemented', detail: 'Explains consent, expiry, retained ownership, private-information boundaries and uncertain replies.' }, + { area: 'Verification', status: 'Partial', detail: 'Focused SQLite races, recovery, HTTP privacy and browser controls; broader network-failure acceptance remains open.', evidence: ['tests/seat-ai-delegation-client.test.ts', 'tests/seat-ai-delegation-recovery.test.ts', 'tests/seat-ai-delegation-http.test.ts'] }, + ], + }, { id: 'seat-handover', title: 'Pass a seat to another player', @@ -1914,7 +1938,7 @@ export const RULE_TOPICS: RuleTopic[] = [ 'After the game starts, Let AI play for me lets you delegate your own seat to Easy, Medium, Hard or Brutal AI. It uses only your seat’s information and can complete setup, spend resources and commit plans. Your seat, saved choices and recovery kit remain yours. Take back control stops future AI decisions without undoing completed actions.', 'The table displays which human seats are on autopilot. AI stops when another human must decide. Online progress is saved one AI action at a time; if processing is interrupted, reopen the table and use its reconnect or resume control when offered. Autopilot does not automatically start because a player disconnects.', ], - related: ['battle', 'alliance-funding', 'ai-pacing'], + related: ['battle', 'alliance-funding', 'ai-pacing', 'seat-ai-permission'], }, ...PHASES.map( (title, phase): RuleTopic => ({ diff --git a/lib/seat-ai-delegation.ts b/lib/seat-ai-delegation.ts new file mode 100644 index 00000000..343e5e93 --- /dev/null +++ b/lib/seat-ai-delegation.ts @@ -0,0 +1,102 @@ +import { DIFFICULTIES, type Difficulty } from '../game/bot-profiles'; + +/** This is consent metadata, never a seat credential or another player's view. */ +export type SeatAiDelegationView = Readonly<{ + grantId: string; + ownerId: string; + delegateId: string; + difficulty: Difficulty; + expiresAt: number; + usedAt: number | null; +}>; +export type SetSeatAiDelegateInput = Readonly<{ + grantId: string; + delegateId: string; + difficulty: Difficulty; +}>; +export type UseSeatAiDelegateInput = Readonly<{ + ownerId: string; + grantId: string; +}>; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +export const validSeatAiGrantId = (value: unknown): value is string => + typeof value === 'string' && UUID.test(value); +const hasOnly = ( + value: unknown, + keys: string[], +): value is Record => + !!value && + typeof value === 'object' && + !Array.isArray(value) && + Object.keys(value).length === keys.length && + keys.every((key) => Object.hasOwn(value, key)); +export function validSetSeatAiDelegateInput( + value: unknown, +): value is SetSeatAiDelegateInput { + return ( + hasOnly(value, ['grantId', 'delegateId', 'difficulty']) && + validSeatAiGrantId(value.grantId) && + validSeatAiGrantId(value.delegateId) && + DIFFICULTIES.some((difficulty) => difficulty === value.difficulty) + ); +} +export function validUseSeatAiDelegateInput( + value: unknown, +): value is UseSeatAiDelegateInput { + return ( + hasOnly(value, ['ownerId', 'grantId']) && + validSeatAiGrantId(value.ownerId) && + validSeatAiGrantId(value.grantId) + ); +} + +export type SeatAiDelegateRequest = + | ({ type: 'setSeatAiDelegate'; version: number } & SetSeatAiDelegateInput) + | { type: 'revokeSeatAiDelegate'; version: number; grantId: string } + | ({ type: 'useSeatAiDelegate'; version: number } & UseSeatAiDelegateInput); + +export function validSeatAiDelegateRequest( + value: unknown, +): value is SeatAiDelegateRequest { + if (!value || typeof value !== 'object' || Array.isArray(value)) return false; + const { type, version, ...input } = value as Record; + if (!Number.isSafeInteger(version) || (version as number) < 0) return false; + if (type === 'setSeatAiDelegate') return validSetSeatAiDelegateInput(input); + if (type === 'useSeatAiDelegate') return validUseSeatAiDelegateInput(input); + return ( + type === 'revokeSeatAiDelegate' && + hasOnly(input, ['grantId']) && + validSeatAiGrantId(input.grantId) + ); +} + +export const seatAiDelegateStorageKey = (room: string, seat: string) => + `dune.pending-ai-permission.v1.${room}.${seat}`; +export function parseSeatAiDelegateRequest( + text: string, +): SeatAiDelegateRequest { + if (text.length > 2000) + throw new Error('The saved AI permission request is invalid.'); + const value: unknown = JSON.parse(text); + if (!validSeatAiDelegateRequest(value)) + throw new Error('The saved AI permission request is invalid.'); + return Object.freeze(value); +} +export function storeSeatAiDelegateRequest( + storage: Pick, + key: string, + request: SeatAiDelegateRequest | null, +) { + const text = request ? JSON.stringify(request) : null; + const existing = storage.getItem(key); + if (request && existing !== null && existing !== text) + throw new Error( + 'Resolve the saved AI permission request before starting another.', + ); + if (text === null) storage.removeItem(key); + else storage.setItem(key, text); + if (storage.getItem(key) !== text) + throw new Error( + 'The AI permission request could not be saved in this tab.', + ); +} diff --git a/tests/auction-cancellation-recovery.test.ts b/tests/auction-cancellation-recovery.test.ts index d0c27797..5f579032 100644 --- a/tests/auction-cancellation-recovery.test.ts +++ b/tests/auction-cancellation-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/automatic-response-recovery.test.ts b/tests/automatic-response-recovery.test.ts index 960cb703..46e249f9 100644 --- a/tests/automatic-response-recovery.test.ts +++ b/tests/automatic-response-recovery.test.ts @@ -7,8 +7,10 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; +import { loadRoomContinuation } from './fixture-room-continuation'; /** Execute the production room module and SQL, with a hook immediately before its CAS. */ function unitStore(runBots = bots.runBots) { @@ -81,6 +83,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, @@ -262,6 +265,10 @@ function route( run: (code: string) => Promise, ) { const pending: Promise[] = []; + const continuation = loadRoomContinuation({ + continueRoomAutomatic: automatic, + continueRoomBots: run, + }); const exports: { GET?: (req: Request) => Promise; POST?: (req: Request) => Promise; @@ -291,6 +298,7 @@ function route( continueRoomAutomatic: automatic, continueRoomBots: run, }; + if (name === '@/db/room-continuation') return continuation; if (name === '@/game/engine') return engine; if (name === 'cloudflare:workers') return { waitUntil: (work: Promise) => pending.push(work) }; diff --git a/tests/base-setup-recovery.test.ts b/tests/base-setup-recovery.test.ts index f74b5172..d9bd18e2 100644 --- a/tests/base-setup-recovery.test.ts +++ b/tests/base-setup-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type { FactionId } from '../game/catalog'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/battle-aftermath-recovery.test.ts b/tests/battle-aftermath-recovery.test.ts index 1160894e..eff0e475 100644 --- a/tests/battle-aftermath-recovery.test.ts +++ b/tests/battle-aftermath-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/battle-discard-recovery.test.ts b/tests/battle-discard-recovery.test.ts index 7977a075..aaa53787 100644 --- a/tests/battle-discard-recovery.test.ts +++ b/tests/battle-discard-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; import { createRequire } from 'node:module'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/bg-karama-cancel-recovery.test.ts b/tests/bg-karama-cancel-recovery.test.ts index b2352b5d..d6008fb3 100644 --- a/tests/bg-karama-cancel-recovery.test.ts +++ b/tests/bg-karama-cancel-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/bg-karama-opportunity-recovery.test.ts b/tests/bg-karama-opportunity-recovery.test.ts index 0b56cb6e..dac457a3 100644 --- a/tests/bg-karama-opportunity-recovery.test.ts +++ b/tests/bg-karama-opportunity-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/bidding-end-recovery.test.ts b/tests/bidding-end-recovery.test.ts index 8f00fdcb..d3c73233 100644 --- a/tests/bidding-end-recovery.test.ts +++ b/tests/bidding-end-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/bot-continuation.test.ts b/tests/bot-continuation.test.ts index d71e1243..3765cb42 100644 --- a/tests/bot-continuation.test.ts +++ b/tests/bot-continuation.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; /** Execute the production room module and SQL, with a hook immediately before its CAS. */ @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/bot-pacing.test.ts b/tests/bot-pacing.test.ts index cbff7df0..58ebb6a0 100644 --- a/tests/bot-pacing.test.ts +++ b/tests/bot-pacing.test.ts @@ -7,7 +7,9 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; +import { loadRoomContinuation } from './fixture-room-continuation'; /** Execute the production room module and SQL, with a hook immediately before its CAS. */ function unitStore(runBots = bots.runBots) { @@ -80,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, @@ -323,6 +326,11 @@ void test('authenticated GET schedules the persisted queue after reconnect while const f = await fixture(); try { const pending: Promise[] = []; + const continuation = loadRoomContinuation({ + continueRoomAutomatic: async () => {}, + continueRoomBots: (code: string) => + f.rooms.continueRoomBots(code, 1, f.clock), + }); const exports: { GET?: (req: Request) => Promise } = {}; runInNewContext( ts.transpileModule( @@ -349,6 +357,7 @@ void test('authenticated GET schedules the persisted queue after reconnect while continueRoomBots: (code: string) => f.rooms.continueRoomBots(code, 1, f.clock), }; + if (name === '@/db/room-continuation') return continuation; if (name === '@/game/engine') return engine; if (name === 'cloudflare:workers') return { diff --git a/tests/box-discard-recovery.test.ts b/tests/box-discard-recovery.test.ts index 922b85ac..f381e6f0 100644 --- a/tests/box-discard-recovery.test.ts +++ b/tests/box-discard-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; import { createRequire } from 'node:module'; @@ -82,6 +83,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/choam-auditor-recovery.test.ts b/tests/choam-auditor-recovery.test.ts index 1b0b6794..5e6b7d16 100644 --- a/tests/choam-auditor-recovery.test.ts +++ b/tests/choam-auditor-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck, createAuditorLeader } from '../game/cards'; import type * as Rooms from '../db/rooms'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/choam-worthless-cancellation-recovery.test.ts b/tests/choam-worthless-cancellation-recovery.test.ts index dd849e28..484a0f67 100644 --- a/tests/choam-worthless-cancellation-recovery.test.ts +++ b/tests/choam-worthless-cancellation-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { newRevivalRules } from '../game/revival'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/combat-terminal-recovery.test.ts b/tests/combat-terminal-recovery.test.ts index 97d15b0c..279986f9 100644 --- a/tests/combat-terminal-recovery.test.ts +++ b/tests/combat-terminal-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/disaster-revival-recovery.test.ts b/tests/disaster-revival-recovery.test.ts index 76cc7e14..3a906219 100644 --- a/tests/disaster-revival-recovery.test.ts +++ b/tests/disaster-revival-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/distrans-recovery.test.ts b/tests/distrans-recovery.test.ts index 6717de2d..78e07e37 100644 --- a/tests/distrans-recovery.test.ts +++ b/tests/distrans-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/ecaz-alliance-recovery.test.ts b/tests/ecaz-alliance-recovery.test.ts index a4d3b4bb..66673569 100644 --- a/tests/ecaz-alliance-recovery.test.ts +++ b/tests/ecaz-alliance-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { createAmbassadors, placeAmbassador } from '../game/ecaz-ambassadors'; import { createDukeVidal } from '../game/duke-vidal'; @@ -82,6 +83,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/ecaz-collection-recovery.test.ts b/tests/ecaz-collection-recovery.test.ts index 62c0e474..132a914f 100644 --- a/tests/ecaz-collection-recovery.test.ts +++ b/tests/ecaz-collection-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/ecaz-duke-recovery.test.ts b/tests/ecaz-duke-recovery.test.ts index 2688c4b9..b004d555 100644 --- a/tests/ecaz-duke-recovery.test.ts +++ b/tests/ecaz-duke-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { createAmbassadors, @@ -86,6 +87,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/ecaz-entry-recovery.test.ts b/tests/ecaz-entry-recovery.test.ts index fb935f73..b735bc89 100644 --- a/tests/ecaz-entry-recovery.test.ts +++ b/tests/ecaz-entry-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { createAmbassadors, @@ -86,6 +87,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/ecaz-occupy-recovery.test.ts b/tests/ecaz-occupy-recovery.test.ts index 3a0250dd..669cc90a 100644 --- a/tests/ecaz-occupy-recovery.test.ts +++ b/tests/ecaz-occupy-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/ecaz-victory-recovery.test.ts b/tests/ecaz-victory-recovery.test.ts index c10a9dae..27cde4ca 100644 --- a/tests/ecaz-victory-recovery.test.ts +++ b/tests/ecaz-victory-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { createStrongholdCards } from '../game/stronghold-cards'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/fixture-nexus-room-store.ts b/tests/fixture-nexus-room-store.ts index 41a7cee2..664437e8 100644 --- a/tests/fixture-nexus-room-store.ts +++ b/tests/fixture-nexus-room-store.ts @@ -5,6 +5,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; /** Execute the production room module and SQL, with a hook immediately before its CAS. */ @@ -82,6 +83,7 @@ export function unitStore(runBots = bots.runBots, migrationThrough?: string) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/fixture-room-continuation.ts b/tests/fixture-room-continuation.ts new file mode 100644 index 00000000..9a45f4c6 --- /dev/null +++ b/tests/fixture-room-continuation.ts @@ -0,0 +1,37 @@ +import { readFileSync } from 'node:fs'; +import { runInNewContext } from 'node:vm'; +import ts from 'typescript'; +import type * as Rooms from '../db/rooms'; +import type * as RoomContinuation from '../db/room-continuation'; + +/** Load the production isolate-local continuation gate with fixture room calls. */ +export function loadRoomContinuation( + rooms: Pick< + typeof Rooms, + 'continueRoomAutomatic' | 'continueRoomBots' + >, +) { + const exports = {}; + runInNewContext( + ts.transpileModule( + readFileSync( + new URL('../db/room-continuation.ts', import.meta.url), + 'utf8', + ), + { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2022, + }, + }, + ).outputText, + { + exports, + require: (name: string) => { + if (name === './rooms') return rooms; + throw new Error('Unexpected continuation dependency ' + name); + }, + }, + ); + return exports as typeof RoomContinuation; +} diff --git a/tests/fremen-ambassador-recovery.test.ts b/tests/fremen-ambassador-recovery.test.ts index 8bb69f9b..564a612f 100644 --- a/tests/fremen-ambassador-recovery.test.ts +++ b/tests/fremen-ambassador-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { createAmbassadors, @@ -86,6 +87,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/fremen-movement-recovery.test.ts b/tests/fremen-movement-recovery.test.ts index 0a382adc..7ff1ed9e 100644 --- a/tests/fremen-movement-recovery.test.ts +++ b/tests/fremen-movement-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { TERRITORIES, gameDistance, location } from '../game/board'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/ghola-lifecycle-recovery.test.ts b/tests/ghola-lifecycle-recovery.test.ts index 3aff90ee..72c57c37 100644 --- a/tests/ghola-lifecycle-recovery.test.ts +++ b/tests/ghola-lifecycle-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { createDukeVidal, DUKE_VIDAL_ID } from '../game/duke-vidal'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/grumman-collection-recovery.test.ts b/tests/grumman-collection-recovery.test.ts index 7362c3e3..36390a45 100644 --- a/tests/grumman-collection-recovery.test.ts +++ b/tests/grumman-collection-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/guild-ambassador-recovery.test.ts b/tests/guild-ambassador-recovery.test.ts index 3096bec2..1afb20fa 100644 --- a/tests/guild-ambassador-recovery.test.ts +++ b/tests/guild-ambassador-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { createAmbassadors, @@ -85,6 +86,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/guild-homeworld-shipment-recovery.test.ts b/tests/guild-homeworld-shipment-recovery.test.ts index 2aad6520..75c194e2 100644 --- a/tests/guild-homeworld-shipment-recovery.test.ts +++ b/tests/guild-homeworld-shipment-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; import { richeseCards } from '../game/richese-cards'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/guild-payment-recovery.test.ts b/tests/guild-payment-recovery.test.ts index 71ced843..bfae082a 100644 --- a/tests/guild-payment-recovery.test.ts +++ b/tests/guild-payment-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-battle-recovery.test.ts b/tests/homeworld-battle-recovery.test.ts index 30703370..94283a81 100644 --- a/tests/homeworld-battle-recovery.test.ts +++ b/tests/homeworld-battle-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldContext, @@ -87,6 +88,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-benefits-recovery.test.ts b/tests/homeworld-benefits-recovery.test.ts index cbc9228d..8e5330b3 100644 --- a/tests/homeworld-benefits-recovery.test.ts +++ b/tests/homeworld-benefits-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import type { FactionId } from '../game/catalog'; import { homeworldGameIntegrity } from '../game/homeworld-game'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-collection-recovery.test.ts b/tests/homeworld-collection-recovery.test.ts index 8bb045ef..4a8ad8b3 100644 --- a/tests/homeworld-collection-recovery.test.ts +++ b/tests/homeworld-collection-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-grumman-recovery.test.ts b/tests/homeworld-grumman-recovery.test.ts index c6a628a6..988d1a5a 100644 --- a/tests/homeworld-grumman-recovery.test.ts +++ b/tests/homeworld-grumman-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-mobility-recovery.test.ts b/tests/homeworld-mobility-recovery.test.ts index d1e408ae..c40b06c4 100644 --- a/tests/homeworld-mobility-recovery.test.ts +++ b/tests/homeworld-mobility-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { MOBILE_LOCATION, mobileRoutes } from '../game/board'; import { homeworldGameIntegrity } from '../game/homeworld-game'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-payment-income-recovery.test.ts b/tests/homeworld-payment-income-recovery.test.ts index 75ddfc71..22382f31 100644 --- a/tests/homeworld-payment-income-recovery.test.ts +++ b/tests/homeworld-payment-income-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-recovery.test.ts b/tests/homeworld-recovery.test.ts index 3de19874..a6ee5852 100644 --- a/tests/homeworld-recovery.test.ts +++ b/tests/homeworld-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; /** Execute the production room module and SQL, with a hook immediately before its CAS. */ @@ -79,6 +80,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-revival-ambassador-recovery.test.ts b/tests/homeworld-revival-ambassador-recovery.test.ts index 2ff880e3..de86e8f6 100644 --- a/tests/homeworld-revival-ambassador-recovery.test.ts +++ b/tests/homeworld-revival-ambassador-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-revival-deployment-recovery.test.ts b/tests/homeworld-revival-deployment-recovery.test.ts index d6f567c4..c5e55d02 100644 --- a/tests/homeworld-revival-deployment-recovery.test.ts +++ b/tests/homeworld-revival-deployment-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-shipment-recovery.test.ts b/tests/homeworld-shipment-recovery.test.ts index 2c0582f5..8e939b15 100644 --- a/tests/homeworld-shipment-recovery.test.ts +++ b/tests/homeworld-shipment-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; import { richeseCards } from '../game/richese-cards'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-spiritual-advisors-recovery.test.ts b/tests/homeworld-spiritual-advisors-recovery.test.ts index cd07e6b5..9a1abf10 100644 --- a/tests/homeworld-spiritual-advisors-recovery.test.ts +++ b/tests/homeworld-spiritual-advisors-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-tupile-sales-recovery.test.ts b/tests/homeworld-tupile-sales-recovery.test.ts index 25be30e5..73a63c19 100644 --- a/tests/homeworld-tupile-sales-recovery.test.ts +++ b/tests/homeworld-tupile-sales-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/homeworld-victory-reinforcement-recovery.test.ts b/tests/homeworld-victory-reinforcement-recovery.test.ts index de507dd6..6b01bafa 100644 --- a/tests/homeworld-victory-reinforcement-recovery.test.ts +++ b/tests/homeworld-victory-reinforcement-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; import { homeworldVictoryObligationSignature } from '../game/homeworld-victory-return'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/juice-of-sapho-recovery.test.ts b/tests/juice-of-sapho-recovery.test.ts index 30d6d367..c9773815 100644 --- a/tests/juice-of-sapho-recovery.test.ts +++ b/tests/juice-of-sapho-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/junction-transport-recovery.test.ts b/tests/junction-transport-recovery.test.ts index 1d3a816c..67eef3bc 100644 --- a/tests/junction-transport-recovery.test.ts +++ b/tests/junction-transport-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/multiplayer-discard-continuations.test.ts b/tests/multiplayer-discard-continuations.test.ts index d33ffbe7..269ad905 100644 --- a/tests/multiplayer-discard-continuations.test.ts +++ b/tests/multiplayer-discard-continuations.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; import { createAmbassadors } from '../game/ecaz-ambassadors'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/nullentropy-box-recovery.test.ts b/tests/nullentropy-box-recovery.test.ts index 42fce541..49e02fe5 100644 --- a/tests/nullentropy-box-recovery.test.ts +++ b/tests/nullentropy-box-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/ordinary-card-discard-recovery.test.ts b/tests/ordinary-card-discard-recovery.test.ts index 112f7fa1..e4f63b9e 100644 --- a/tests/ordinary-card-discard-recovery.test.ts +++ b/tests/ordinary-card-discard-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { treacheryDeck } from '../game/cards'; import { createTechTokens } from '../game/tech-tokens'; import type * as Rooms from '../db/rooms'; @@ -82,6 +83,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/ornithopter-discard-recovery.test.ts b/tests/ornithopter-discard-recovery.test.ts index 470a8754..6d6d07f0 100644 --- a/tests/ornithopter-discard-recovery.test.ts +++ b/tests/ornithopter-discard-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import { @@ -87,6 +88,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/ornithopter-recovery.test.ts b/tests/ornithopter-recovery.test.ts index 3fb23f28..9ee22da3 100644 --- a/tests/ornithopter-recovery.test.ts +++ b/tests/ornithopter-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import { @@ -85,6 +86,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/paced-games.test.ts b/tests/paced-games.test.ts index f8491eb3..a8f4a88c 100644 --- a/tests/paced-games.test.ts +++ b/tests/paced-games.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; /** Execute the production room module and SQL, with a hook immediately before its CAS. */ @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/pending-shipment-integrity-recovery.test.ts b/tests/pending-shipment-integrity-recovery.test.ts index 0d8285bf..91184224 100644 --- a/tests/pending-shipment-integrity-recovery.test.ts +++ b/tests/pending-shipment-integrity-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/placement-cancellation-recovery.test.ts b/tests/placement-cancellation-recovery.test.ts index 31d81fc2..09962f58 100644 --- a/tests/placement-cancellation-recovery.test.ts +++ b/tests/placement-cancellation-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { createAmbassadors } from '../game/ecaz-ambassadors'; import { createTerrorState } from '../game/moritani-terror'; @@ -83,6 +84,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/portable-snooper-recovery.test.ts b/tests/portable-snooper-recovery.test.ts index 6ab2bd77..fa18625b 100644 --- a/tests/portable-snooper-recovery.test.ts +++ b/tests/portable-snooper-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/residual-poison-recovery.test.ts b/tests/residual-poison-recovery.test.ts index 80dff671..43aa746b 100644 --- a/tests/residual-poison-recovery.test.ts +++ b/tests/residual-poison-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/restored-cancellation-recovery.test.ts b/tests/restored-cancellation-recovery.test.ts index 5599afcf..c96d7025 100644 --- a/tests/restored-cancellation-recovery.test.ts +++ b/tests/restored-cancellation-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/richese-allied-no-field-recovery.test.ts b/tests/richese-allied-no-field-recovery.test.ts index 8cc5b5ee..9f500100 100644 --- a/tests/richese-allied-no-field-recovery.test.ts +++ b/tests/richese-allied-no-field-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { createRicheseNoField, @@ -84,6 +85,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/richese-auction-recovery.test.ts b/tests/richese-auction-recovery.test.ts index e557c453..e7357e04 100644 --- a/tests/richese-auction-recovery.test.ts +++ b/tests/richese-auction-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/richese-gift-recovery.test.ts b/tests/richese-gift-recovery.test.ts index 9a938a39..5f8bff50 100644 --- a/tests/richese-gift-recovery.test.ts +++ b/tests/richese-gift-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/richese-no-field-recovery.test.ts b/tests/richese-no-field-recovery.test.ts index 9ea401ef..0a294a86 100644 --- a/tests/richese-no-field-recovery.test.ts +++ b/tests/richese-no-field-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { createRicheseNoField } from '../game/richese-no-field'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/room-entry-recovery.test.ts b/tests/room-entry-recovery.test.ts index 27d1a12d..22fe4a1e 100644 --- a/tests/room-entry-recovery.test.ts +++ b/tests/room-entry-recovery.test.ts @@ -8,6 +8,7 @@ import { DatabaseSync } from 'node:sqlite'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; const base = process.env.DUNE_TEST_URL ?? 'http://localhost:3000'; @@ -439,6 +440,7 @@ function unitStore() { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return bots; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }); diff --git a/tests/seat-ai-delegation-client.test.ts b/tests/seat-ai-delegation-client.test.ts new file mode 100644 index 00000000..c4311f0f --- /dev/null +++ b/tests/seat-ai-delegation-client.test.ts @@ -0,0 +1,142 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + parseSeatAiDelegateRequest, + seatAiDelegateStorageKey, + storeSeatAiDelegateRequest, + validSeatAiDelegateRequest, + type SeatAiDelegateRequest, +} from '../lib/seat-ai-delegation'; + +const ownerId = crypto.randomUUID(), + delegateId = crypto.randomUUID(), + grantId = crypto.randomUUID(); +const request: SeatAiDelegateRequest = { + type: 'setSeatAiDelegate', + version: 12, + grantId, + delegateId, + difficulty: 'Hard', +}; +function storage() { + const values = new Map(); + return { + getItem: (key: string) => values.get(key) ?? null, + setItem: (key: string, value: string) => { + values.set(key, value); + }, + removeItem: (key: string) => { + values.delete(key); + }, + }; +} + +void test('AI permission retry preserves exact consent and original version across refresh; cannot replace an uncertain request', () => { + const tab = storage(), + key = seatAiDelegateStorageKey('ABCDEFGH', ownerId); + storeSeatAiDelegateRequest(tab, key, request); + const restored = parseSeatAiDelegateRequest(tab.getItem(key)!); + assert.deepEqual(restored, request); + assert.equal(Object.isFrozen(restored), true); + storeSeatAiDelegateRequest(tab, key, restored); + for (const replacement of [ + { ...request, version: 13 }, + { ...request, grantId: crypto.randomUUID() }, + { ...request, delegateId: ownerId }, + ]) + assert.throws( + () => storeSeatAiDelegateRequest(tab, key, replacement), + /Resolve the saved/, + ); + assert.equal( + tab.getItem(seatAiDelegateStorageKey('ABCDEFGH', delegateId)), + null, + ); + assert.equal( + tab.getItem(seatAiDelegateStorageKey('BCDEFGHJ', ownerId)), + null, + ); + storeSeatAiDelegateRequest(tab, key, null); + assert.equal(tab.getItem(key), null); + storeSeatAiDelegateRequest(tab, key, { + ...request, + grantId: crypto.randomUUID(), + }); +}); + +void test('AI permission request validation rejects alternate profiles, target injection, credentials, malformed versions and stored extras', () => { + const use: SeatAiDelegateRequest = { + type: 'useSeatAiDelegate', + version: 13, + grantId, + ownerId, + }; + const revoke: SeatAiDelegateRequest = { + type: 'revokeSeatAiDelegate', + version: 13, + grantId, + }; + for (const good of [request, use, revoke]) + assert.equal(validSeatAiDelegateRequest(good), true); + for (const bad of [ + { ...request, ownerId }, + { ...request, sessionToken: 'secret' }, + { ...request, difficulty: 'Impossible' }, + { ...request, version: -1 }, + { ...request, version: 2.5 }, + { ...request, version: '12' }, + { ...request, grantId: '' }, + { ...request, delegateId: 'another player' }, + { ...use, difficulty: 'Brutal' }, + { ...use, delegateId }, + { ...revoke, ownerId }, + { ...request, type: 'setAutopilot' }, + null, + [], + ]) { + assert.equal(validSeatAiDelegateRequest(bad), false); + assert.throws(() => parseSeatAiDelegateRequest(JSON.stringify(bad))); + } + assert.throws(() => parseSeatAiDelegateRequest(' '.repeat(2001))); +}); + +void test('AI permission storage must persist exactly before a request can be dispatched', () => { + const key = seatAiDelegateStorageKey('ABCDEFGH', ownerId); + assert.throws( + () => + storeSeatAiDelegateRequest( + { getItem: () => null, setItem: () => {}, removeItem: () => {} }, + key, + request, + ), + /could not be saved/, + ); + assert.throws( + () => + storeSeatAiDelegateRequest( + { + getItem: () => JSON.stringify(request), + setItem: () => {}, + removeItem: () => {}, + }, + key, + null, + ), + /could not be saved/, + ); + assert.throws( + () => + storeSeatAiDelegateRequest( + { + getItem: () => { + throw new Error('blocked'); + }, + setItem: () => {}, + removeItem: () => {}, + }, + key, + request, + ), + /blocked/, + ); +}); diff --git a/tests/seat-ai-delegation-http.test.ts b/tests/seat-ai-delegation-http.test.ts new file mode 100644 index 00000000..d0d82c5f --- /dev/null +++ b/tests/seat-ai-delegation-http.test.ts @@ -0,0 +1,233 @@ +// @dune-suite integration +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { setTimeout as pause } from 'node:timers/promises'; +import type { GameView } from '../game/engine'; +const base = process.env.DUNE_TEST_URL ?? 'http://localhost:3000'; +async function request( + path: string, + body?: unknown, + cookie?: string, + origin?: string, +) { + const response = await fetch(base + path, { + method: body === undefined ? 'GET' : 'POST', + signal: AbortSignal.timeout(15_000), + headers: { + ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), + ...(cookie ? { cookie } : {}), + ...(origin ? { origin } : {}), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + const raw = await response.text(); + let data: unknown; + try { + data = JSON.parse(raw); + } catch { + data = { error: 'Non-JSON response' }; + } + return { + status: response.status, + data: data as GameView & { + view: GameView; + replayed?: boolean; + error?: string; + }, + cookie: response.headers.get('set-cookie')?.split(';')[0], + cache: response.headers.get('cache-control'), + }; +} +async function fixture() { + const a = await request('/api/rooms', { + name: 'AI permission owner', + faction: 'atreides', + advanced: false, + expansions: [], + }); + assert.equal(a.status, 201); + assert.ok(a.cookie); + const path = `/api/rooms/${a.data.code}`; + const b = await request(path, { + type: 'join', + name: 'AI permission delegate', + faction: 'emperor', + }); + const c = await request(path, { + type: 'join', + name: 'AI permission observer', + faction: 'guild', + }); + assert.equal(b.status, 200); + assert.ok(b.cookie); + assert.equal(c.status, 200); + assert.ok(c.cookie); + let view = c.data; + for (const player of [a, b, c]) { + const ready = await request( + path, + { version: view.version, action: { type: 'ready' } }, + player.cookie, + ); + assert.equal(ready.status, 200); + view = ready.data; + } + const started = await request( + path, + { version: view.version, action: { type: 'start' } }, + a.cookie, + ); + assert.equal(started.status, 200); + assert.equal(started.data.status, 'setup'); + return { a, b, c, path, view: started.data }; +} +function privateView(view: GameView, ownId: string) { + assert.equal(view.me, ownId); + assert.ok(view.players.find((player) => player.id === ownId)?.traitorChoices); + for (const player of view.players.filter((player) => player.id !== ownId)) + for (const key of ['hand', 'traitors', 'traitorChoices', 'spice']) + assert.equal(key in player, false, `Other seat exposed ${key}`); + for (const secret of [ + 'ownerSessionHash', + 'delegateSessionHash', + 'owner_session_hash', + 'delegate_session_hash', + 'tokenHash', + ]) + assert.equal(JSON.stringify(view).includes(secret), false); +} + +void test('AI permission HTTP restricts creation/use/revoke to consented identities and rejects injection without mutation', async () => { + const f = await fixture(), + control = f.path + '/control'; + const grant = { + type: 'setSeatAiDelegate', + version: f.view.version, + grantId: crypto.randomUUID(), + delegateId: f.b.data.me, + difficulty: 'Hard', + }; + assert.equal((await request(control, grant)).status, 409); + assert.equal( + (await request(control, grant, f.a.cookie, 'https://other.invalid')).status, + 403, + ); + for (const body of [ + { ...grant, ownerId: f.c.data.me }, + { ...grant, delegateId: f.a.data.me }, + { ...grant, difficulty: 'Invalid' }, + ]) + assert.ok((await request(control, body, f.a.cookie)).status >= 400); + assert.equal( + (await request(f.path, undefined, f.a.cookie)).data.version, + f.view.version, + ); + const made = await request(control, grant, f.a.cookie); + assert.equal(made.status, 200); + assert.equal(made.cache, 'no-store'); + assert.equal(made.data.view.seatAiDelegations?.[0].grantId, grant.grantId); + const replay = await request(control, grant, f.a.cookie); + assert.equal(replay.status, 200); + assert.equal(replay.data.replayed, true); + const other = await request(f.path, undefined, f.c.cookie); + assert.equal(other.data.seatAiDelegations, undefined); + const read = await request(f.path, undefined, f.b.cookie); + assert.equal(read.data.seatAiDelegations?.[0].grantId, grant.grantId); + privateView(read.data, f.b.data.me); + const activate = { + type: 'useSeatAiDelegate', + version: read.data.version, + ownerId: f.a.data.me, + grantId: grant.grantId, + }; + for (const [body, cookie] of [ + [activate, f.c.cookie], + [{ ...activate, difficulty: 'Brutal' }, f.b.cookie], + [ + { + type: 'revokeSeatAiDelegate', + version: read.data.version, + grantId: grant.grantId, + }, + f.b.cookie, + ], + ] as const) + assert.ok((await request(control, body, cookie)).status >= 400); + assert.equal( + (await request(f.path, undefined, f.a.cookie)).data.version, + read.data.version, + ); +}); + +void test('AI permission HTTP starts only the chosen profile, resumes paced work, preserves ownership and cannot reactivate after takeback', async () => { + const f = await fixture(), + control = f.path + '/control'; + const grant = { + type: 'setSeatAiDelegate', + version: f.view.version, + grantId: crypto.randomUUID(), + delegateId: f.b.data.me, + difficulty: 'Medium', + }; + const made = await request(control, grant, f.a.cookie); + assert.equal(made.status, 200); + const activate = { + type: 'useSeatAiDelegate', + version: made.data.view.version, + ownerId: f.a.data.me, + grantId: grant.grantId, + }; + const used = await request(control, activate, f.b.cookie); + assert.equal(used.status, 200); + assert.equal(used.cookie, undefined); + assert.equal(used.cache, 'no-store'); + privateView(used.data.view, f.b.data.me); + assert.equal( + used.data.view.players.find((player) => player.id === f.a.data.me) + ?.autopilot, + 'Medium', + ); + assert.ok( + used.data.view.seatAiDelegations?.find( + (entry) => entry.grantId === grant.grantId, + )?.usedAt, + ); + const deadline = Date.now() + 10_000; + let own = await request(f.path, undefined, f.a.cookie); + while (own.data.botsPending && Date.now() < deadline) { + await pause(150); + own = await request(f.path, undefined, f.a.cookie); + } + assert.equal(own.status, 200); + assert.equal(own.data.me, f.a.data.me); + assert.equal(own.data.botsPending, false); + assert.ok( + own.data.version > used.data.view.version, + 'Server continuation should advance the AI setup choice.', + ); + const back = await request( + f.path, + { + version: own.data.version, + action: { type: 'setAutopilot', difficulty: null }, + }, + f.a.cookie, + ); + assert.equal(back.status, 200); + assert.equal( + back.data.players.find((player) => player.id === f.a.data.me)?.autopilot, + undefined, + ); + // Both exact lost-response retry and newly versioned reuse must remain harmless. + for (const version of [activate.version, back.data.version]) { + const retry = await request(control, { ...activate, version }, f.b.cookie); + assert.ok([200, 409].includes(retry.status)); + const current = await request(f.path, undefined, f.a.cookie); + assert.equal(current.data.version, back.data.version); + assert.equal( + current.data.players.find((player) => player.id === f.a.data.me) + ?.autopilot, + undefined, + ); + } +}); diff --git a/tests/seat-ai-delegation-recovery.test.ts b/tests/seat-ai-delegation-recovery.test.ts new file mode 100644 index 00000000..b1c14fa5 --- /dev/null +++ b/tests/seat-ai-delegation-recovery.test.ts @@ -0,0 +1,527 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { DatabaseSync } from 'node:sqlite'; +import type { Game } from '../game/engine'; +import { unitStore } from './fixture-nexus-room-store'; + +const UUID = { + ownerEntry: '71000000-0000-4000-8000-000000000001', + delegateEntry: '71000000-0000-4000-8000-000000000002', + observerEntry: '71000000-0000-4000-8000-000000000003', + grant1: '71000000-0000-4000-8000-000000000011', + grant2: '71000000-0000-4000-8000-000000000012', + grant3: '71000000-0000-4000-8000-000000000013', + grant4: '71000000-0000-4000-8000-000000000014', + recovery: '71000000-0000-4000-8000-000000000021', + offer: '71000000-0000-4000-8000-000000000022', + claim: '71000000-0000-4000-8000-000000000023', +}; +const secret = (pair: string) => pair.repeat(32); +const clock = (now: number) => ({ + now: () => now, + sleep: async () => {}, +}); + +async function fixture() { + const store = unitStore(); + assert.ok(store.sqlite instanceof DatabaseSync); + const owner = await store.rooms.createRoom('Owner', 'atreides', false, [], { + operationId: UUID.ownerEntry, + sessionToken: secret('11'), + }); + const code = owner.view.code; + const delegate = await store.rooms.joinRoom(code, 'Delegate', 'emperor', { + operationId: UUID.delegateEntry, + sessionToken: secret('22'), + }); + const observer = await store.rooms.joinRoom(code, 'Observer', 'fremen', { + operationId: UUID.observerEntry, + sessionToken: secret('33'), + }); + assert.ok(delegate.token); + assert.ok(observer.token); + const auths = { + owner: await store.rooms.authenticate(code, owner.token), + delegate: await store.rooms.authenticate(code, delegate.token), + observer: await store.rooms.authenticate(code, observer.token), + }; + for (const auth of Object.values(auths)) { + const current = await store.rooms.readRoom(code); + await store.rooms.act(code, auth, current.version, { type: 'ready' }); + } + const beforeStart = await store.rooms.readRoom(code); + await store.rooms.act(code, auths.owner, beforeStart.version, { + type: 'start', + }); + return { + ...store, + code, + owner, + delegate, + observer, + ownerId: auths.owner.playerId, + delegateId: auths.delegate.playerId, + observerId: auths.observer.playerId, + auths, + }; +} + +const delegation = ( + f: Awaited>, + grantId: string, +) => ({ + grantId, + delegateId: f.delegateId, + difficulty: 'Hard' as const, +}); + +function storedState(f: Awaited>) { + return f.sqlite.prepare('SELECT state FROM rooms WHERE code = ?').get(f.code)! + .state as string; +} + +function withoutDelegationActivation(game: Game) { + const copy = structuredClone(game); + delete copy.botsPending; + delete copy.botNextActionAt; + copy.version = 0; + copy.log = []; + for (const player of copy.players) delete player.autopilot; + return copy; +} + +void test('delegation is private, survives restart, activates once and preserves sealed setup state', async () => { + const f = await fixture(); + try { + const beforeState = storedState(f); + const before = JSON.parse(beforeState) as Game; + const version = (await f.rooms.readRoom(f.code)).version; + const saved = await f.rooms.setSeatAiDelegate( + f.code, + f.auths.owner, + version, + delegation(f, UUID.grant1), + clock(1000), + ); + assert.equal(saved.replayed, false); + assert.equal(storedState(f), beforeState); + assert.deepEqual(saved.view.seatAiDelegations, [ + { + grantId: UUID.grant1, + ownerId: f.ownerId, + delegateId: f.delegateId, + difficulty: 'Hard', + expiresAt: 1000 + f.rooms.SEAT_AI_DELEGATION_TTL_MS, + usedAt: null, + }, + ]); + assert.deepEqual( + (await f.restart().readSeatView(f.code, f.auths.delegate)) + .seatAiDelegations, + saved.view.seatAiDelegations, + ); + const observer = await f.rooms.readSeatView(f.code, f.auths.observer); + assert.equal(Object.hasOwn(observer, 'seatAiDelegations'), false); + for (const view of [saved.view, observer]) { + const text = JSON.stringify(view); + assert.equal(text.includes('session_hash'), false); + assert.equal(text.includes(secret('11')), false); + assert.equal(text.includes(secret('22')), false); + } + + let reachedBatch = false; + f.hooks.beforeBatch = async () => { + reachedBatch = true; + }; + const beforeFutureVersion = storedState(f); + await assert.rejects( + f.rooms.useSeatAiDelegate( + f.code, + f.auths.delegate, + saved.view.version + 1, + { ownerId: f.ownerId, grantId: UUID.grant1 }, + clock(1750), + ), + /table changed/i, + ); + assert.equal(reachedBatch, false); + delete f.hooks.beforeBatch; + assert.equal(storedState(f), beforeFutureVersion); + + let entered!: () => void; + let release!: () => void; + const waiting = new Promise((resolve) => (entered = resolve)); + const gate = new Promise((resolve) => (release = resolve)); + f.hooks.beforeBatch = async () => { + delete f.hooks.beforeBatch; + entered(); + await gate; + }; + const pending = f.rooms.useSeatAiDelegate( + f.code, + f.auths.delegate, + saved.view.version, + { ownerId: f.ownerId, grantId: UUID.grant1 }, + clock(2000), + ); + await waiting; + const duplicate = await f + .restart() + .useSeatAiDelegate( + f.code, + f.auths.delegate, + saved.view.version, + { ownerId: f.ownerId, grantId: UUID.grant1 }, + clock(2000), + ); + release(); + const first = await pending; + assert.deepEqual( + [first.replayed, duplicate.replayed].sort( + (a, b) => Number(a) - Number(b), + ), + [false, true], + ); + const after = await f.rooms.readRoom(f.code); + assert.equal(after.version, saved.view.version + 1); + assert.equal( + after.players.find((player) => player.id === f.ownerId)?.autopilot, + 'Hard', + ); + assert.equal(after.botsPending, true); + assert.equal(after.botNextActionAt, 3500); + assert.match( + after.log.at(-1)!.text, + /Delegate activated Hard AI for Owner/, + ); + assert.equal( + after.log.filter((entry) => entry.text.includes('one-use delegation')) + .length, + 1, + ); + assert.deepEqual( + withoutDelegationActivation(after), + withoutDelegationActivation(before), + ); + assert.deepEqual( + (await f.rooms.readSeatView(f.code, f.auths.owner)).seatAiDelegations, + [ + { + grantId: UUID.grant1, + ownerId: f.ownerId, + delegateId: f.delegateId, + difficulty: 'Hard', + expiresAt: 1000 + f.rooms.SEAT_AI_DELEGATION_TTL_MS, + usedAt: 2000, + }, + ], + ); + } finally { + f.sqlite.close(); + } +}); + +void test('replacement, revoke, expiry and owner control cannot be bypassed by stale consent', async () => { + const f = await fixture(); + try { + const view = await f.rooms.readSeatView(f.code, f.auths.owner); + let reachedBatch = false; + f.hooks.beforeBatch = async () => { + reachedBatch = true; + }; + await assert.rejects( + f.rooms.setSeatAiDelegate( + f.code, + f.auths.owner, + view.version + 1, + delegation(f, UUID.grant1), + clock(500), + ), + /table changed/i, + ); + assert.equal(reachedBatch, false); + delete f.hooks.beforeBatch; + const first = await f.rooms.setSeatAiDelegate( + f.code, + f.auths.owner, + view.version, + delegation(f, UUID.grant1), + clock(1000), + ); + const replay = await f.rooms.setSeatAiDelegate( + f.code, + f.auths.owner, + first.view.version, + delegation(f, UUID.grant1), + clock(1500), + ); + assert.equal(replay.replayed, true); + assert.equal(replay.view.version, first.view.version); + const replaced = await f.rooms.setSeatAiDelegate( + f.code, + f.auths.owner, + first.view.version, + delegation(f, UUID.grant2), + clock(2000), + ); + assert.deepEqual( + replaced.view.seatAiDelegations?.map((item) => item.grantId), + [UUID.grant2], + ); + const rejectedState = storedState(f); + await assert.rejects( + f.rooms.useSeatAiDelegate( + f.code, + f.auths.delegate, + replaced.view.version, + { ownerId: f.ownerId, grantId: UUID.grant1 }, + clock(2500), + ), + /revoked|replaced/, + ); + assert.equal(storedState(f), rejectedState); + const revoked = await f.rooms.revokeSeatAiDelegate( + f.code, + f.auths.owner, + replaced.view.version, + UUID.grant2, + clock(3000), + ); + assert.equal(revoked.replayed, false); + assert.equal(Object.hasOwn(revoked.view, 'seatAiDelegations'), false); + const revokeReplay = await f.rooms.revokeSeatAiDelegate( + f.code, + f.auths.owner, + replaced.view.version, + UUID.grant2, + clock(3500), + ); + assert.equal(revokeReplay.replayed, true); + assert.equal(revokeReplay.view.version, revoked.view.version); + + const expiring = await f.rooms.setSeatAiDelegate( + f.code, + f.auths.owner, + revoked.view.version, + delegation(f, UUID.grant3), + clock(4000), + ); + const beforeExpiry = storedState(f); + await assert.rejects( + f.rooms.useSeatAiDelegate( + f.code, + f.auths.delegate, + expiring.view.version, + { ownerId: f.ownerId, grantId: UUID.grant3 }, + clock(4000 + f.rooms.SEAT_AI_DELEGATION_TTL_MS), + ), + /expired/, + ); + assert.equal(storedState(f), beforeExpiry); + const current = await f.rooms.readRoom(f.code); + const ownAi = await f.rooms.act( + f.code, + f.auths.owner, + current.version, + { type: 'setAutopilot', difficulty: 'Easy' }, + clock(5000), + ); + assert.equal(Object.hasOwn(ownAi, 'seatAiDelegations'), false); + await assert.rejects( + f.rooms.useSeatAiDelegate( + f.code, + f.auths.delegate, + ownAi.version, + { ownerId: f.ownerId, grantId: UUID.grant3 }, + clock(5500), + ), + /revoked|replaced/, + ); + } finally { + f.sqlite.close(); + } +}); + +void test('owner control and delegated activation serialize without stale takeback or double enable', async () => { + for (const winner of ['owner', 'delegate'] as const) { + const f = await fixture(); + try { + const initial = await f.rooms.readSeatView(f.code, f.auths.owner); + const granted = await f.rooms.setSeatAiDelegate( + f.code, + f.auths.owner, + initial.version, + delegation(f, UUID.grant1), + clock(1000), + ); + let entered!: () => void; + let release!: () => void; + const waiting = new Promise((resolve) => (entered = resolve)); + const gate = new Promise((resolve) => (release = resolve)); + f.hooks.beforeBatch = async () => { + delete f.hooks.beforeBatch; + entered(); + await gate; + }; + if (winner === 'owner') { + const pendingUse = f.rooms.useSeatAiDelegate( + f.code, + f.auths.delegate, + granted.view.version, + { ownerId: f.ownerId, grantId: UUID.grant1 }, + clock(2000), + ); + await waiting; + const controlled = await f + .restart() + .act( + f.code, + f.auths.owner, + granted.view.version, + { type: 'setAutopilot', difficulty: null }, + clock(2000), + ); + release(); + await assert.rejects( + pendingUse, + /table, owner, delegate or consent changed/i, + ); + assert.equal( + controlled.players.find((player) => player.id === f.ownerId) + ?.autopilot, + undefined, + ); + } else { + const pendingControl = f.rooms.act( + f.code, + f.auths.owner, + granted.view.version, + { type: 'setAutopilot', difficulty: null }, + clock(2000), + ); + await waiting; + const used = await f + .restart() + .useSeatAiDelegate( + f.code, + f.auths.delegate, + granted.view.version, + { ownerId: f.ownerId, grantId: UUID.grant1 }, + clock(2000), + ); + assert.equal(used.replayed, false); + release(); + await assert.rejects(pendingControl, /Another action arrived first/); + const current = await f.rooms.readSeatView(f.code, f.auths.owner); + const takenBack = await f.rooms.act( + f.code, + f.auths.owner, + current.version, + { type: 'setAutopilot', difficulty: null }, + clock(3000), + ); + assert.equal( + takenBack.players.find((player) => player.id === f.ownerId) + ?.autopilot, + undefined, + ); + } + const after = await f.rooms.readRoom(f.code); + assert.ok(after.version >= granted.view.version + 1); + assert.ok( + after.log.filter((entry) => entry.text.includes('one-use delegation')) + .length <= 1, + ); + } finally { + f.sqlite.close(); + } + } +}); + +void test('recovery or handover of either bound seat invalidates delegation consent', async () => { + for (const mode of ['recovery', 'handover'] as const) { + for (const target of ['owner', 'delegate'] as const) { + const f = await fixture(); + try { + let targetAuth = f.auths[target]; + let version = (await f.rooms.readRoom(f.code)).version; + const recoverySecret = secret(target === 'owner' ? '44' : '55'); + if (mode === 'recovery') { + const configured = await f.rooms.setRecoveryKey( + f.code, + targetAuth, + version, + recoverySecret, + ); + version = configured.view.version; + } + const granted = await f.rooms.setSeatAiDelegate( + f.code, + f.auths.owner, + version, + delegation(f, UUID.grant4), + clock(1000), + ); + let newToken: string; + if (mode === 'recovery') { + newToken = secret(target === 'owner' ? '66' : '77'); + await f.rooms.recoverSeat(f.code, { + playerId: targetAuth.playerId, + recoverySecret, + operationId: UUID.recovery, + newSessionToken: newToken, + }); + } else { + const offer = { + offerId: UUID.offer, + handoverSecret: secret(target === 'owner' ? '88' : '99'), + }; + await f.rooms.createSeatHandover( + f.code, + targetAuth, + granted.view.version, + offer, + clock(1500), + ); + newToken = secret(target === 'owner' ? 'aa' : 'bb'); + await f.rooms.claimSeatHandover( + f.code, + { + playerId: targetAuth.playerId, + ...offer, + operationId: UUID.claim, + newSessionToken: newToken, + }, + clock(2000), + ); + } + targetAuth = await f.rooms.authenticate(f.code, newToken); + const delegateAuth = + target === 'delegate' ? targetAuth : f.auths.delegate; + const current = await f.rooms.readRoom(f.code); + const before = storedState(f); + await assert.rejects( + f.rooms.useSeatAiDelegate( + f.code, + delegateAuth, + current.version, + { ownerId: f.ownerId, grantId: UUID.grant4 }, + clock(3000), + ), + /credential changed|not available/, + `${mode} of ${target}`, + ); + assert.equal(storedState(f), before); + assert.equal( + Object.hasOwn( + await f.rooms.readSeatView(f.code, targetAuth), + 'seatAiDelegations', + ), + false, + ); + } finally { + f.sqlite.close(); + } + } + } +}); diff --git a/tests/seat-handover-store.test.ts b/tests/seat-handover-store.test.ts index 52ddc90f..578eed10 100644 --- a/tests/seat-handover-store.test.ts +++ b/tests/seat-handover-store.test.ts @@ -4,6 +4,7 @@ import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; import type { DatabaseSync } from 'node:sqlite'; import { baseDeck } from '../game/cards'; +import { createGame, newPlayer } from '../game/engine'; import { unitStore } from './fixture-nexus-room-store'; const UUID = { @@ -301,16 +302,43 @@ void test('claim invalidates the issuer entry receipt that still controlled the }); void test('0005 backfills an active 0004 claim for exact replay after upgrade', async () => { - const f = await fixture(false, '0004_flippant_archangel.sql'); + const f = unitStore(undefined, '0004_flippant_archangel.sql'); try { - const body = claim(f.created.view.me); - const offered = await f.rooms.createSeatHandover( - f.code, - f.auth, - f.view.version, - offer(), - clock(1000), + const code = 'LEGACY05'; + const playerId = UUID.rival; + const oldSessionHash = digest(secret('10')); + const handover = offer(); + const body = claim(playerId); + const game = createGame( + code, + newPlayer(playerId, 'Original owner', 'atreides'), + false, + [], ); + game.players[0].hand = [baseDeck()[0]]; + game.players[0].traitors = ['emperor-0']; + f.sqlite + .prepare( + 'INSERT INTO rooms(code,state,version,updated_at) VALUES(?,?,1,?)', + ) + .run(code, JSON.stringify(game), 1000); + f.sqlite + .prepare( + 'INSERT INTO seats(token_hash,room_code,player_id) VALUES(?,?,?)', + ) + .run(oldSessionHash, code, playerId); + f.sqlite + .prepare( + 'INSERT INTO seat_handover_offers(room_code,player_id,offer_hash,secret_hash,issuer_session_hash,expires_at,claim_operation_hash,session_hash,claimed_at) VALUES(?,?,?,?,?,?,NULL,NULL,NULL)', + ) + .run( + code, + playerId, + digest(handover.offerId), + digest(handover.handoverSecret), + oldSessionHash, + 301000, + ); const operationHash = digest(body.operationId); const sessionHash = digest(body.newSessionToken); f.sqlite.exec('BEGIN'); @@ -319,22 +347,22 @@ void test('0005 backfills an active 0004 claim for exact replay after upgrade', .prepare( 'UPDATE rooms SET version = version + 1, updated_at = ? WHERE code = ? AND version = ?', ) - .run(2000, f.code, offered.view.version); + .run(2000, code, 1); f.sqlite .prepare( 'UPDATE seat_handover_offers SET claim_operation_hash = ?, session_hash = ?, claimed_at = ? WHERE room_code = ? AND player_id = ?', ) - .run(operationHash, sessionHash, 2000, f.code, f.created.view.me); + .run(operationHash, sessionHash, 2000, code, playerId); f.sqlite .prepare( 'UPDATE seats SET revoked = 1 WHERE room_code = ? AND player_id = ? AND revoked = 0', ) - .run(f.code, f.created.view.me); + .run(code, playerId); f.sqlite .prepare( 'INSERT INTO seats(token_hash,room_code,player_id) VALUES (?,?,?)', ) - .run(sessionHash, f.code, f.created.view.me); + .run(sessionHash, code, playerId); f.sqlite.exec('COMMIT'); } catch (error) { f.sqlite.exec('ROLLBACK'); @@ -342,7 +370,7 @@ void test('0005 backfills an active 0004 claim for exact replay after upgrade', } const stateBeforeUpgrade = f.sqlite .prepare('SELECT state FROM rooms WHERE code = ?') - .get(f.code)!.state; + .get(code)!.state; f.sqlite.exec( readFileSync( new URL('../drizzle/0005_salty_alice.sql', import.meta.url), @@ -353,7 +381,7 @@ void test('0005 backfills an active 0004 claim for exact replay after upgrade', .prepare( 'SELECT operation_hash,session_hash,claim_fence FROM seat_handover_claim_receipts WHERE room_code = ? AND player_id = ?', ) - .get(f.code, f.created.view.me)!; + .get(code, playerId)!; assert.equal(receipt.operation_hash, operationHash); assert.equal(receipt.session_hash, sessionHash); assert.match(receipt.claim_fence as string, /^legacy:/); @@ -361,17 +389,19 @@ void test('0005 backfills an active 0004 claim for exact replay after upgrade', (receipt.claim_fence as string).includes(body.newSessionToken), false, ); - const replay = await f.restart().claimSeatHandover( - f.code, - body, - clock(3000), + f.sqlite.exec( + readFileSync( + new URL('../drizzle/0006_thick_imperial_guard.sql', import.meta.url), + 'utf8', + ), ); + const replay = await f.restart().claimSeatHandover(code, body, clock(3000)); assert.equal(replay.replayed, true); assert.equal(replay.token, body.newSessionToken); - assert.equal(replay.view.me, f.created.view.me); + assert.equal(replay.view.me, playerId); assert.equal(replay.view.players[0].hand![0].id, baseDeck()[0].id); assert.equal( - f.sqlite.prepare('SELECT state FROM rooms WHERE code = ?').get(f.code)! + f.sqlite.prepare('SELECT state FROM rooms WHERE code = ?').get(code)! .state, stateBeforeUpgrade, ); diff --git a/tests/seat-recovery.test.ts b/tests/seat-recovery.test.ts index 4584a92f..41ced30a 100644 --- a/tests/seat-recovery.test.ts +++ b/tests/seat-recovery.test.ts @@ -8,6 +8,7 @@ import { DatabaseSync } from 'node:sqlite'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; const base = process.env.DUNE_TEST_URL ?? 'http://localhost:3000'; @@ -350,6 +351,7 @@ function unitStore() { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return bots; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }); diff --git a/tests/shipment-promises-recovery.test.ts b/tests/shipment-promises-recovery.test.ts index 09dd8cc4..c2935e9f 100644 --- a/tests/shipment-promises-recovery.test.ts +++ b/tests/shipment-promises-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; @@ -80,6 +81,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/stone-burner-recovery.test.ts b/tests/stone-burner-recovery.test.ts index caaecb9b..e94116f4 100644 --- a/tests/stone-burner-recovery.test.ts +++ b/tests/stone-burner-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { richeseCards } from '../game/richese-cards'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/stronghold-recovery.test.ts b/tests/stronghold-recovery.test.ts index 31a71738..9acf0dba 100644 --- a/tests/stronghold-recovery.test.ts +++ b/tests/stronghold-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import { createStrongholdCards, @@ -85,6 +86,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/terror-discard-recovery.test.ts b/tests/terror-discard-recovery.test.ts index e1ea3090..2ae5546e 100644 --- a/tests/terror-discard-recovery.test.ts +++ b/tests/terror-discard-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type * as Rooms from '../db/rooms'; import { createRequire } from 'node:module'; @@ -82,6 +83,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/truthtrance-discard-recovery.test.ts b/tests/truthtrance-discard-recovery.test.ts index c4e6dd35..141eda11 100644 --- a/tests/truthtrance-discard-recovery.test.ts +++ b/tests/truthtrance-discard-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type { TruthQuestion } from '../game/truthtrance'; import { createRequire } from 'node:module'; @@ -82,6 +83,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/truthtrance-spice-recovery.test.ts b/tests/truthtrance-spice-recovery.test.ts index 0d5578f8..3f80c834 100644 --- a/tests/truthtrance-spice-recovery.test.ts +++ b/tests/truthtrance-spice-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import { baseDeck } from '../game/cards'; import type { TruthFact } from '../game/truthtrance'; import type * as Rooms from '../db/rooms'; @@ -81,6 +82,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, }, diff --git a/tests/tupile-intelligence-recovery.test.ts b/tests/tupile-intelligence-recovery.test.ts index 8775273b..a34fef56 100644 --- a/tests/tupile-intelligence-recovery.test.ts +++ b/tests/tupile-intelligence-recovery.test.ts @@ -7,6 +7,7 @@ import { runInNewContext } from 'node:vm'; import ts from 'typescript'; import * as engine from '../game/engine'; import * as bots from '../game/bots'; +import * as seatAiDelegation from '../lib/seat-ai-delegation'; import type * as Rooms from '../db/rooms'; import { homeworldGameIntegrity } from '../game/homeworld-game'; import { homeworldContext } from '../game/homeworld-game'; @@ -89,6 +90,7 @@ function unitStore(runBots = bots.runBots) { if (name === 'cloudflare:workers') return { env: { DB: database } }; if (name === '@/game/engine') return engine; if (name === '@/game/bots') return { ...bots, runBots }; + if (name === '@/lib/seat-ai-delegation') return seatAiDelegation; throw new Error('Unexpected module ' + name); }, },