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
This commit is contained in:
Quintine committed 2026-09-20 16:30:37 +10:00
1 parent e13ad454e2
commit b21b2bc378
93 files changed
+2996 -72

No files matched your search

+7
View File
@@ -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.
+41
View File
@@ -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' ||
+1 -17
View File
@@ -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<string, Promise<void>>();
function resumeRoom(code: string): Promise<void> {
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();
+20 -2
View File
@@ -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}
/>
<div className="table-shell">
{(entryAttempt || entryProblem) && (
@@ -678,7 +683,12 @@ export default function Home() {
</p>
<Button
variant="outline"
disabled={busy || checkingConnection || handoverPending}
disabled={
busy ||
checkingConnection ||
handoverPending ||
aiPermissionPending
}
onClick={exitTable}
>
Review saved room request
@@ -700,6 +710,14 @@ export default function Home() {
onUncertain={setHandoverPending}
onRestored={(view) => restoredSeat(view)}
/>
<SeatAiDelegation
key={`ai-permission:${game.code}:${game.me}`}
game={game}
disabled={busy || needsReconcile || checkingConnection}
onPending={controlPending}
onUncertain={setAiPermissionPending}
onRestored={(view) => restoredSeat(view)}
/>
</div>
{(notice || connection || needsReconcile || botRecovery) && (
<output className="floating-notice">
+366
View File
@@ -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<SeatAiDelegateRequest | null>(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<Difficulty>('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 (
<details
className="notice min-w-0"
open={expanded}
onToggle={(event) => setExpanded(event.currentTarget.open)}
>
<summary className="min-h-11 cursor-pointer py-3 text-base font-semibold focus-visible:outline-2 focus-visible:outline-offset-2">
Let a player start AI for your seat
</summary>
<p>
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.
</p>
<p className="fine">
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.
</p>
{record || storageProblem ? (
<section
aria-label="Unconfirmed AI permission request"
className="flex flex-col gap-3"
>
<p>
Confirm the saved request before granting another permission.
Refresh keeps the same request in this tab.
</p>
{record && (
<Button
className="min-h-11 whitespace-normal"
disabled={locked}
onClick={() => void submit(record)}
>
Retry saved AI permission request
</Button>
)}
<label className="flex min-h-11 items-center gap-3">
<input
type="checkbox"
checked={abandon}
disabled={locked}
onChange={(event) => setAbandon(event.target.checked)}
/>
I understand discarding this record cannot cancel a request that
reached the server.
</label>
<Button
className="min-h-11 whitespace-normal"
variant="outline"
disabled={locked || !abandon}
onClick={() => {
try {
store(null);
setAbandon(false);
setMessage(
'Retry record discarded. Check the current permission; revoke it or take back control if needed.',
);
} catch (error) {
setMessage((error as Error).message);
}
}}
>
Discard retry record
</Button>
</section>
) : (
<div className="flex min-w-0 flex-col gap-4">
{ownGrant && (
<section aria-label="Your AI permission">
<p>
{name(ownGrant.delegateId)} · {ownGrant.difficulty} ·{' '}
{ownGrant.usedAt !== null
? 'Already used'
: ownGrant.expiresAt <= now
? 'Expired'
: 'Available once'}
.
</p>
<p className="fine">
Expires {new Date(ownGrant.expiresAt).toLocaleString()}.
</p>
{ownGrant.usedAt === null && (
<Button
className="min-h-11 whitespace-normal"
variant="outline"
disabled={locked}
onClick={() =>
void submit({
type: 'revokeSeatAiDelegate',
version: game.version,
grantId: ownGrant.grantId,
})
}
>
Revoke AI permission
</Button>
)}
</section>
)}
{started && !own.autopilot && peers.length > 0 && (
<div className="flex min-w-0 flex-col gap-3">
<label htmlFor={`${id}-player`}>
Player allowed to start your AI
</label>
<select
id={`${id}-player`}
className="min-h-11 min-w-0 w-full rounded border border-[#454b3c] bg-[#141814] px-3"
value={delegateId}
disabled={locked}
onChange={(event) => setDelegateId(event.target.value)}
>
<option value="">Choose a player</option>
{peers.map((player) => (
<option key={player.id} value={player.id}>
{player.name}
</option>
))}
</select>
<label htmlFor={`${id}-difficulty`}>
Authorized AI difficulty
</label>
<select
id={`${id}-difficulty`}
className="min-h-11 min-w-0 w-full rounded border border-[#454b3c] bg-[#141814] px-3"
value={difficulty}
disabled={locked}
onChange={(event) => {
if (
DIFFICULTIES.some((choice) => choice === event.target.value)
)
setDifficulty(event.target.value as Difficulty);
}}
>
{DIFFICULTIES.map((choice) => (
<option key={choice}>{choice}</option>
))}
</select>
<Button
className="min-h-11 whitespace-normal"
disabled={
locked || !peers.some((player) => player.id === delegateId)
}
onClick={() =>
void submit({
type: 'setSeatAiDelegate',
version: game.version,
grantId: crypto.randomUUID(),
delegateId,
difficulty,
})
}
>
{ownGrant
? 'Replace AI permission'
: 'Allow this player to start AI once'}
</Button>
</div>
)}
{!started && <p>Permission can be granted after the game starts.</p>}
{own.autopilot && (
<p>
Your AI is already running. Use Take back control at the table
before granting another permission.
</p>
)}
{received.map((grant) => (
<section
key={grant.grantId}
aria-label={`AI permission from ${name(grant.ownerId)}`}
>
<p>
{name(grant.ownerId)} authorized you to start {grant.difficulty}{' '}
AI for their seat once.
</p>
<p className="fine">
Expires {new Date(grant.expiresAt).toLocaleString()}.
</p>
{grant.usedAt !== null ? (
<p>Permission already used.</p>
) : grant.expiresAt <= now ? (
<p>Permission expired.</p>
) : (
<Button
className="min-h-11 whitespace-normal"
disabled={
locked ||
!started ||
!!game.players.find((player) => player.id === grant.ownerId)
?.autopilot
}
onClick={() =>
void submit({
type: 'useSeatAiDelegate',
version: game.version,
ownerId: grant.ownerId,
grantId: grant.grantId,
})
}
>
Start {name(grant.ownerId)}’s authorized AI
</Button>
)}
</section>
))}
</div>
)}
{message && <output className="block py-2">{message}</output>}
</details>
);
}
+17
View File
@@ -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<string, Promise<void>>();
export function resumeRoom(code: string): Promise<void> {
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;
}
+497 -13
View File
@@ -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<RoomsClock, 'now'>;
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<SeatAiDelegationRow>();
}
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 {
+21
View File
@@ -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(),
+26 -2
View File
@@ -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
+17 -14
View File
@@ -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
+15
View File
@@ -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
+1 -1
View File
@@ -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
+65
View File
@@ -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.
+16
View File
@@ -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`);
+608
View File
@@ -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": {}
}
}
+8 -1
View File
@@ -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
}
]
}
}
+3 -1
View File
@@ -25328,4 +25328,6 @@ export function viewGame(state: Game, id: string) {
})),
};
}
export type GameView = ReturnType<typeof viewGame>;
export type GameView = ReturnType<typeof viewGame> & {
seatAiDelegations?: import('../lib/seat-ai-delegation').SeatAiDelegationView[];
};
+25 -1
View File
@@ -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 => ({
+102
View File
@@ -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<string, unknown> =>
!!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<string, unknown>;
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<Storage, 'getItem' | 'setItem' | 'removeItem'>,
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.',
);
}
@@ -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);
},
},
@@ -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<void>,
) {
const pending: Promise<void>[] = [];
const continuation = loadRoomContinuation({
continueRoomAutomatic: automatic,
continueRoomBots: run,
});
const exports: {
GET?: (req: Request) => Promise<Response>;
POST?: (req: Request) => Promise<Response>;
@@ -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<void>) => pending.push(work) };
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+9
View File
@@ -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<unknown>[] = [];
const continuation = loadRoomContinuation({
continueRoomAutomatic: async () => {},
continueRoomBots: (code: string) =>
f.rooms.continueRoomBots(code, 1, f.clock),
});
const exports: { GET?: (req: Request) => Promise<Response> } = {};
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 {
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+37
View File
@@ -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;
}
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},
@@ -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);
},
},
@@ -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);
},
},
@@ -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);
},
},
@@ -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);
},
},
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
});
+142
View File
@@ -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<string, string>();
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/,
);
});
+233
View File
@@ -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,
);
}
});
+527
View File
@@ -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<ReturnType<typeof fixture>>,
grantId: string,
) => ({
grantId,
delegateId: f.delegateId,
difficulty: 'Hard' as const,
});
function storedState(f: Awaited<ReturnType<typeof fixture>>) {
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<void>((resolve) => (entered = resolve));
const gate = new Promise<void>((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<void>((resolve) => (entered = resolve));
const gate = new Promise<void>((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();
}
}
}
});
+50 -20
View File
@@ -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,
);
+2
View File
@@ -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);
},
});
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},
+2
View File
@@ -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);
},
},
@@ -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);
},
},