Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9020a773e1 | ||
|
|
bf5ac8c8a8 | ||
|
|
babae7c392 | ||
|
|
a0307e4ccd | ||
|
|
1ddb8ad469 | ||
|
|
b51bde3c25 | ||
|
|
53cf1bdacc | ||
|
|
f1b5645e9d | ||
|
|
1cabea7972 | ||
|
|
a199b64348 | ||
|
|
07c1508999 | ||
|
|
1084f4e099 | ||
|
|
84d1aa8122 | ||
|
|
178de6e4fb | ||
|
|
03b8b661f6 | ||
|
|
4e312d054f | ||
|
|
d7faf739a9 | ||
|
|
bbcd77c41b | ||
|
|
d4491e082e | ||
|
|
6c51c3cec8 | ||
|
|
f52a59c5fc |
@@ -1,5 +1,13 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## v0.10.0 — 2026-10-03 00:57
|
||||||
|
- Queue-based actions (#44): every game action (jump, explore, ship upgrade/expand/build, research) is now a queued task with an assigned team — a lead + optional helpers. Validation and cost deduction happen at queue time (unknown crew → 404, busy/committed crew → 409, in-transit or second jump → 409); effects apply when the task completes, mission accept is instant and free, and mission-completion checks run when the satisfying task resolves.
|
||||||
|
- Manual time: new `POST /api/turn` advances exactly one turn — each active task ticks down, completions resolve via per-type resolvers (reusing the existing jump/explore/ship/research logic), FIFO successors auto-start; an empty queue is a free skip. `save.turn` now only increments here, and the UI gets the NEXT TURN button (bottom-right) with the turn counter.
|
||||||
|
- Crew teaming with a live duration preview: action buttons open an inline team builder — pick a lead (radio), toggle helpers (checkboxes) — and show the computed duration as the team changes ("Lead AVA VANCE · PILOT L2 + 1 helper → 3 turns"); busy/committed members are disabled with a reason. A new active-tasks strip (bottom-left) lists active tasks first, pending FIFO tasks dimmed.
|
||||||
|
- Trait duration modifiers: all 15 non-combat traits now affect duration (7 good — cancel the role-mismatch penalty or −1 turn for a specific action type; 8 bad — +1 turn for a specific type or any action), applied to the lead only; the 3 combat traits are labelled STANDBY until the future encounters iteration (the 2 outcome-effect traits ship in #43).
|
||||||
|
- New `tasks` table (schema v7; idempotent backfill for existing saves — existing saves gain an empty table, turn/crew/inventory untouched) and a single balance module `lib/game/crew-costs.ts` (work points, power bands, trait modifiers); OpenAPI spec updated accordingly.
|
||||||
|
- Tests: unit matrix covers the duration formula, queue validation rules and tick resolution (completion effects, FIFO auto-start, in-transit blocking); the whole e2e suite was reworked from instant-resolution to the queue + NEXT TURN model (assign team → NEXT TURN ×N → assert the effect).
|
||||||
|
|
||||||
## v0.9.12 — 2026-09-29 21:40
|
## v0.9.12 — 2026-09-29 21:40
|
||||||
- ADMIN button in the mission-control header (top right, next to the SHIP NOMINAL / SECTOR SCAN badges) opens a DB CRUD panel (#38): pick any of the ten game tables from `lib/db/schema.ts`, browse its rows in an HTML table, and add/edit/delete rows via a per-column form. Driven by new `/api/admin/` endpoints — `GET /api/admin/tables` (columns + row counts), `GET|POST|PATCH|DELETE /api/admin/tables/{name}/rows` — built off a name→table registry so there is no per-table code; unknown table names get 404, malformed payloads 400, constraint violations 409. Deliberately unauthenticated by explicit request (marked with a `ponytail:` comment).
|
- ADMIN button in the mission-control header (top right, next to the SHIP NOMINAL / SECTOR SCAN badges) opens a DB CRUD panel (#38): pick any of the ten game tables from `lib/db/schema.ts`, browse its rows in an HTML table, and add/edit/delete rows via a per-column form. Driven by new `/api/admin/` endpoints — `GET /api/admin/tables` (columns + row counts), `GET|POST|PATCH|DELETE /api/admin/tables/{name}/rows` — built off a name→table registry so there is no per-table code; unknown table names get 404, malformed payloads 400, constraint violations 409. Deliberately unauthenticated by explicit request (marked with a `ponytail:` comment).
|
||||||
- e2e: new read-only spec — click ADMIN, assert the panel lists every table the API reports, open `saves` and assert its rows render matching `/api/admin/tables/saves/rows` (no mutations in specs; CRUD is covered by unit tests in lib/db/admin.test.ts).
|
- e2e: new read-only spec — click ADMIN, assert the panel lists every table the API reports, open `saves` and assert its rows render matching `/api/admin/tables/saves/rows` (no mutations in specs; CRUD is covered by unit tests in lib/db/admin.test.ts).
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { MAX_TEAM_SIZE } from '@/lib/game/crew'
|
||||||
|
|
||||||
|
// The crew-team half of a queueing-action body (leadCrewId + helperCrewIds) plus the route-layer
|
||||||
|
// team rules: one task team, distinct members, the size cap. queueTask (lib) deliberately does
|
||||||
|
// NOT validate teams, so this shared parse is the single place the team 400s live — extracted
|
||||||
|
// verbatim from the 5a jump/explore crew-parse blocks so the six queueing routes can't drift.
|
||||||
|
// Returns a 400-shaped error object instead of throwing, so the caller maps it to a response.
|
||||||
|
|
||||||
|
export type CrewTeam =
|
||||||
|
| { leadCrewId: number; helperCrewIds: number[] }
|
||||||
|
| { error: string; status: number }
|
||||||
|
|
||||||
|
export function parseCrewTeam(body: unknown): CrewTeam {
|
||||||
|
const leadCrewId = (body as { leadCrewId?: unknown }).leadCrewId
|
||||||
|
if (typeof leadCrewId !== 'number' || !Number.isInteger(leadCrewId)) {
|
||||||
|
return { error: 'leadCrewId must be an integer', status: 400 }
|
||||||
|
}
|
||||||
|
let helperCrewIds: number[] = []
|
||||||
|
const rawHelpers = (body as { helperCrewIds?: unknown }).helperCrewIds
|
||||||
|
if (rawHelpers !== undefined) {
|
||||||
|
if (!Array.isArray(rawHelpers) || !rawHelpers.every((h) => typeof h === 'number' && Number.isInteger(h))) {
|
||||||
|
return { error: 'helperCrewIds must be an array of integers', status: 400 }
|
||||||
|
}
|
||||||
|
helperCrewIds = rawHelpers
|
||||||
|
}
|
||||||
|
// Team rules (route layer, not queueTask's): one task team, distinct members, size cap.
|
||||||
|
const team = [leadCrewId, ...helperCrewIds]
|
||||||
|
if (new Set(team).size !== team.length) {
|
||||||
|
return { error: 'crew members must be unique', status: 400 }
|
||||||
|
}
|
||||||
|
if (team.length > MAX_TEAM_SIZE) {
|
||||||
|
return { error: `a task team holds at most ${MAX_TEAM_SIZE} crew members`, status: 400 }
|
||||||
|
}
|
||||||
|
return { leadCrewId, helperCrewIds }
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import { getGameDb } from '@/lib/db/client'
|
import { getGameDb } from '@/lib/db/client'
|
||||||
import { getCrewState } from '@/lib/game/save'
|
import { getCrewState } from '@/lib/game/save'
|
||||||
|
|
||||||
// The ship's crew roster: starting crew plus members found while exploring. Auto-initializes on first hit.
|
// The ship's crew roster wrapped with the snapshot task queue: { crew, tasks } — the roster
|
||||||
|
// (starting crew plus members found while exploring) and the ACTIVE + PENDING queue. Auto-initializes on first hit.
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
const db = await getGameDb()
|
const db = await getGameDb()
|
||||||
return Response.json(await getCrewState(db))
|
return Response.json(await getCrewState(db))
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
// Handler-level tests for the queueing explore route (Task 5a): POST /api/explore with a crew
|
||||||
|
// team queues an EXPLORE row instead of resolving instantly — same system snapshot (findings key
|
||||||
|
// kept, empty), same pre-check codes, no turn spent at queue time.
|
||||||
|
import { eq } from 'drizzle-orm'
|
||||||
|
import { mkdtemp, rm } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { afterAll, describe, expect, it } from 'vitest'
|
||||||
|
import { getGameDb, type GameDb } from '@/lib/db/client'
|
||||||
|
import * as schema from '@/lib/db/schema'
|
||||||
|
import { getSystemState, type SystemState } from '@/lib/game/save'
|
||||||
|
import { addCrew, buildWorldFixture, insertTaskRow } from '@/lib/game/test-fixtures'
|
||||||
|
import { POST } from './route'
|
||||||
|
|
||||||
|
const dirs: string[] = []
|
||||||
|
// The route talks to the app-process singleton (getGameDb), so each test points it at a
|
||||||
|
// fresh temp file and uses that very instance for fixtures and assertions — two in-memory
|
||||||
|
// sql.js copies of one file would never see each other's writes.
|
||||||
|
const g = globalThis as unknown as { __spaceWandererGameDb?: Promise<GameDb> }
|
||||||
|
|
||||||
|
async function freshFile(): Promise<{ db: GameDb; file: string }> {
|
||||||
|
const dir = await mkdtemp(path.join(tmpdir(), 'sw-explore-route-test-'))
|
||||||
|
dirs.push(dir)
|
||||||
|
const file = path.join(dir, 'test.db')
|
||||||
|
process.env.SPACE_WANDERER_DB_PATH = file
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
return { db: await getGameDb(), file }
|
||||||
|
}
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
delete process.env.SPACE_WANDERER_DB_PATH
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
for (const d of dirs) await rm(d, { recursive: true, force: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
const post = (body: unknown) => POST(new Request('http://localhost/api/explore', { method: 'POST', body: JSON.stringify(body) }))
|
||||||
|
|
||||||
|
describe('POST /api/explore (5a)', () => {
|
||||||
|
it('queues an EXPLORE: row with type/payload, turn unchanged, planet not yet scanned, no haul', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1, c2] = await addCrew(db, 2)
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
const invBefore = (await db.db.select().from(schema.inventoryItems)).map((i) => [i.kind, i.name, i.qty] as const)
|
||||||
|
|
||||||
|
const res = await post({ planetId: f.p0, leadCrewId: c1, helperCrewIds: [c2] })
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const body = await res.json()
|
||||||
|
const sys = await getSystemState(db)
|
||||||
|
for (const k of Object.keys(sys) as (keyof SystemState)[]) expect(body[k]).toEqual(sys[k]) // today's system snapshot part unchanged; the findings key stays, empty (JC-2)
|
||||||
|
const [row] = await db.db.select().from(schema.tasks)
|
||||||
|
expect(row).toMatchObject({ type: 'EXPLORE', leadCrewId: c1, status: 'ACTIVE', queuedAtTurn: before.turn })
|
||||||
|
expect(JSON.parse(row.helpers)).toEqual([c2]) // helpers is a JSON text column
|
||||||
|
expect(JSON.parse(row.payload)).toEqual({ planetId: f.p0 })
|
||||||
|
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn)
|
||||||
|
expect((await db.db.select().from(schema.planets)).find((p) => p.id === f.p0)!.explored).toBe(false) // the effect waits for the tick
|
||||||
|
expect((await db.db.select().from(schema.inventoryItems)).map((i) => [i.kind, i.name, i.qty] as const)).toEqual(invBefore) // no haul yet
|
||||||
|
})
|
||||||
|
|
||||||
|
it('unknown crew → 404 (queueTask)', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
expect((await post({ planetId: f.p0, leadCrewId: 999 })).status).toBe(404)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('busy helper → 409, nothing queued', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1, c2] = await addCrew(db, 2)
|
||||||
|
await insertTaskRow(db, { type: 'EXPLORE', payload: { planetId: f.p1 }, leadCrewId: c2, helpers: [], duration: 2, remaining: 2, status: 'ACTIVE', queuedAtTurn: 1 })
|
||||||
|
expect((await post({ planetId: f.p0, leadCrewId: c1, helperCrewIds: [c2] })).status).toBe(409)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('already scanned → 409 (existing pre-check, existing code)', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
await db.db.update(schema.planets).set({ explored: true }).where(eq(schema.planets.id, f.p0))
|
||||||
|
expect((await post({ planetId: f.p0, leadCrewId: c1 })).status).toBe(409)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,8 +1,13 @@
|
|||||||
import { getGameDb } from '@/lib/db/client'
|
import { getGameDb } from '@/lib/db/client'
|
||||||
import { ExploreError, explorePlanet } from '@/lib/game/save'
|
import { parseCrewTeam } from '@/app/api/crew-team'
|
||||||
|
import { checkExploreTarget, ExploreError, getSystemState, queueStateFromSave, saveTaskRow } from '@/lib/game/save'
|
||||||
|
import { queueTask, TaskError } from '@/lib/game/tasks'
|
||||||
|
|
||||||
// Scan one body of the current system. Body: { "planetId": number }. Returns the fresh
|
// Scan one body of the current system: assign the crew team (lead + helpers) and queue the
|
||||||
// system state plus what this scan found. Costs a turn; each body can only be scanned once.
|
// EXPLORE task — the haul, the scanned flag, the crew roll and the event land when the task
|
||||||
|
// completes on the turn tick (runTurn). Body: { planetId, leadCrewId, helperCrewIds? }.
|
||||||
|
// Queueing spends no turn; returns the same system snapshot as the instant scan, with the
|
||||||
|
// findings key empty until the scan resolves (JC-2).
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
let body: unknown
|
let body: unknown
|
||||||
try {
|
try {
|
||||||
@@ -15,12 +20,20 @@ export async function POST(req: Request) {
|
|||||||
if (typeof planetId !== 'number' || !Number.isInteger(planetId)) {
|
if (typeof planetId !== 'number' || !Number.isInteger(planetId)) {
|
||||||
return Response.json({ error: 'planetId must be an integer' }, { status: 400 })
|
return Response.json({ error: 'planetId must be an integer' }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
const team = parseCrewTeam(body)
|
||||||
|
if ('error' in team) {
|
||||||
|
return Response.json({ error: team.error }, { status: team.status })
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const db = await getGameDb()
|
const db = await getGameDb()
|
||||||
return Response.json(await explorePlanet(db, planetId))
|
await checkExploreTarget(db, planetId) // existing pre-checks: 404 unknown body · 409 already scanned
|
||||||
|
const state = await queueStateFromSave(db)
|
||||||
|
const { task } = queueTask(state, { type: 'EXPLORE', payload: { planetId }, leadCrewId: team.leadCrewId, helperCrewIds: team.helperCrewIds })
|
||||||
|
await saveTaskRow(db, task) // inventory is unchanged until the scan resolves — no hold write
|
||||||
|
return Response.json({ ...(await getSystemState(db)), outcome: [], crewFound: null })
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof ExploreError) {
|
if (err instanceof ExploreError || err instanceof TaskError) {
|
||||||
return Response.json({ error: err.message }, { status: err.status })
|
return Response.json({ error: err.message }, { status: err.status })
|
||||||
}
|
}
|
||||||
throw err
|
throw err
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
// Handler-level tests for the queueing jump route (Task 5a): POST /api/jump with a crew
|
||||||
|
// team queues a JUMP row instead of resolving instantly — same snapshots, same pre-check
|
||||||
|
// codes, no turn spent at queue time.
|
||||||
|
import { mkdtemp, rm } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { afterAll, describe, expect, it } from 'vitest'
|
||||||
|
import { getGameDb, type GameDb } from '@/lib/db/client'
|
||||||
|
import * as schema from '@/lib/db/schema'
|
||||||
|
import { getWorldState } from '@/lib/game/save'
|
||||||
|
import { addCrew, buildWorldFixture, insertTaskRow } from '@/lib/game/test-fixtures'
|
||||||
|
import { POST } from './route'
|
||||||
|
|
||||||
|
const dirs: string[] = []
|
||||||
|
// The route talks to the app-process singleton (getGameDb), so each test points it at a
|
||||||
|
// fresh temp file and uses that very instance for fixtures and assertions — two in-memory
|
||||||
|
// sql.js copies of one file would never see each other's writes.
|
||||||
|
const g = globalThis as unknown as { __spaceWandererGameDb?: Promise<GameDb> }
|
||||||
|
|
||||||
|
async function freshFile(): Promise<{ db: GameDb; file: string }> {
|
||||||
|
const dir = await mkdtemp(path.join(tmpdir(), 'sw-jump-route-test-'))
|
||||||
|
dirs.push(dir)
|
||||||
|
const file = path.join(dir, 'test.db')
|
||||||
|
process.env.SPACE_WANDERER_DB_PATH = file
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
return { db: await getGameDb(), file }
|
||||||
|
}
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
delete process.env.SPACE_WANDERER_DB_PATH
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
for (const d of dirs) await rm(d, { recursive: true, force: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
const post = (body: unknown) => POST(new Request('http://localhost/api/jump', { method: 'POST', body: JSON.stringify(body) }))
|
||||||
|
|
||||||
|
describe('POST /api/jump (5a)', () => {
|
||||||
|
it('queues a JUMP: row with type/payload/status, turn unchanged, snapshot preserved, ship not moved', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1, c2] = await addCrew(db, 2)
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
|
||||||
|
const res = await post({ systemId: f.sys1, leadCrewId: c1, helperCrewIds: [c2] })
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(await res.json()).toEqual(await getWorldState(db)) // the same fresh snapshot as today — queueing changes nothing else
|
||||||
|
const [row] = await db.db.select().from(schema.tasks)
|
||||||
|
expect(row).toMatchObject({ type: 'JUMP', leadCrewId: c1, status: 'ACTIVE', queuedAtTurn: before.turn })
|
||||||
|
expect(JSON.parse(row.helpers)).toEqual([c2]) // helpers is a JSON text column
|
||||||
|
expect(JSON.parse(row.payload)).toEqual({ systemId: f.sys1, hops: 1 }) // route-computed via the existing reachability logic
|
||||||
|
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn) // no turn increment
|
||||||
|
expect((await db.db.select().from(schema.solarSystems)).filter((s) => s.isCurrent).map((s) => s.id)).toEqual([1]) // the effect waits for the tick
|
||||||
|
})
|
||||||
|
|
||||||
|
it('unknown crew → 404 (queueTask)', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
expect((await post({ systemId: f.sys1, leadCrewId: 999 })).status).toBe(404)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('busy helper → 409, nothing queued', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1, c2] = await addCrew(db, 2)
|
||||||
|
await insertTaskRow(db, { type: 'EXPLORE', payload: { planetId: f.p0 }, leadCrewId: c2, helpers: [], duration: 2, remaining: 2, status: 'ACTIVE', queuedAtTurn: 1 })
|
||||||
|
expect((await post({ systemId: f.sys1, leadCrewId: c1, helperCrewIds: [c2] })).status).toBe(409)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a jump in transit → 409 (blocks any new task)', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1, c2] = await addCrew(db, 2)
|
||||||
|
await insertTaskRow(db, { type: 'JUMP', payload: { systemId: f.sys1, hops: 1 }, leadCrewId: c2, helpers: [], duration: 3, remaining: 3, status: 'ACTIVE', queuedAtTurn: 1 })
|
||||||
|
expect((await post({ systemId: f.sys1, leadCrewId: c1 })).status).toBe(409)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a jump already pending → second jump 409', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1, c2] = await addCrew(db, 2)
|
||||||
|
await insertTaskRow(db, { type: 'EXPLORE', payload: { planetId: f.p0 }, leadCrewId: c1, helpers: [], duration: 2, remaining: 2, status: 'ACTIVE', queuedAtTurn: 1 })
|
||||||
|
await insertTaskRow(db, { type: 'JUMP', payload: { systemId: f.sys1, hops: 1 }, leadCrewId: c1, helpers: [], duration: 2, remaining: 2, status: 'PENDING', queuedAtTurn: 1 }) // lead chains behind its own ACTIVE
|
||||||
|
expect((await post({ systemId: f.sys1, leadCrewId: c2 })).status).toBe(409)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('unreachable target → 409 (existing pre-check, existing code)', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
expect((await post({ systemId: f.farSystem, leadCrewId: c1 })).status).toBe(409) // JC-4: a beyond-reach system in the fixture; add it to buildWorldFixture if absent
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('malformed crew fields → 400, nothing queued', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
expect((await post({ systemId: f.sys1 })).status).toBe(400) // leadCrewId is required
|
||||||
|
expect((await post({ systemId: f.sys1, leadCrewId: 'x' })).status).toBe(400)
|
||||||
|
expect((await post({ systemId: f.sys1, leadCrewId: 1.5 })).status).toBe(400)
|
||||||
|
expect((await post({ systemId: f.sys1, leadCrewId: 1, helperCrewIds: 'nope' })).status).toBe(400)
|
||||||
|
expect((await post({ systemId: f.sys1, leadCrewId: 1, helperCrewIds: [1, 'x'] })).status).toBe(400)
|
||||||
|
expect((await post('not json at all' as unknown)).status).toBe(400)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
+17
-4
@@ -1,7 +1,12 @@
|
|||||||
import { getGameDb } from '@/lib/db/client'
|
import { getGameDb } from '@/lib/db/client'
|
||||||
import { JumpError, jumpToSystem } from '@/lib/game/save'
|
import { parseCrewTeam } from '@/app/api/crew-team'
|
||||||
|
import { checkJumpTarget, getWorldState, JumpError, queueStateFromSave, saveTaskRow } from '@/lib/game/save'
|
||||||
|
import { queueTask, TaskError } from '@/lib/game/tasks'
|
||||||
|
|
||||||
// Jump to an adjacent solar system. Body: { "systemId": number }. Returns the fresh world state.
|
// Jump to a system within range: assign the crew team (lead + helpers) and queue the JUMP
|
||||||
|
// task — the move lands when the task completes on the turn tick (runTurn). Body:
|
||||||
|
// { systemId, leadCrewId, helperCrewIds? }. Queueing spends no turn; returns the same fresh
|
||||||
|
// world state as the instant jump did.
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
let body: unknown
|
let body: unknown
|
||||||
try {
|
try {
|
||||||
@@ -14,12 +19,20 @@ export async function POST(req: Request) {
|
|||||||
if (typeof systemId !== 'number' || !Number.isInteger(systemId)) {
|
if (typeof systemId !== 'number' || !Number.isInteger(systemId)) {
|
||||||
return Response.json({ error: 'systemId must be an integer' }, { status: 400 })
|
return Response.json({ error: 'systemId must be an integer' }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
const team = parseCrewTeam(body)
|
||||||
|
if ('error' in team) {
|
||||||
|
return Response.json({ error: team.error }, { status: team.status })
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const db = await getGameDb()
|
const db = await getGameDb()
|
||||||
return Response.json(await jumpToSystem(db, systemId))
|
const hops = await checkJumpTarget(db, systemId) // existing pre-checks: 404 unknown · 409 already there / out of range
|
||||||
|
const state = await queueStateFromSave(db)
|
||||||
|
const { task } = queueTask(state, { type: 'JUMP', payload: { systemId, hops }, leadCrewId: team.leadCrewId, helperCrewIds: team.helperCrewIds })
|
||||||
|
await saveTaskRow(db, task) // inventory is unchanged for a JUMP — no hold write
|
||||||
|
return Response.json(await getWorldState(db))
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof JumpError) {
|
if (err instanceof JumpError || err instanceof TaskError) {
|
||||||
return Response.json({ error: err.message }, { status: err.status })
|
return Response.json({ error: err.message }, { status: err.status })
|
||||||
}
|
}
|
||||||
throw err
|
throw err
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
// Handler-level tests for mission accept (Task 5a(ii)): instant and free per the approved
|
||||||
|
// spec (JC-19) — the AVAILABLE → ACTIVE flip and the event land at the current turn, no
|
||||||
|
// turn is spent, no crew params; the board response shape is unchanged.
|
||||||
|
import { mkdtemp, rm } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { afterAll, describe, expect, it } from 'vitest'
|
||||||
|
import { getGameDb, type GameDb } from '@/lib/db/client'
|
||||||
|
import * as schema from '@/lib/db/schema'
|
||||||
|
import { getMissions } from '@/lib/game/missions'
|
||||||
|
import { buildWorldFixture } from '@/lib/game/test-fixtures'
|
||||||
|
import { POST } from './route'
|
||||||
|
|
||||||
|
const dirs: string[] = []
|
||||||
|
// The route talks to the app-process singleton (getGameDb), so each test points it at a
|
||||||
|
// fresh temp file and uses that very instance for fixtures and assertions — two in-memory
|
||||||
|
// sql.js copies of one file would never see each other's writes.
|
||||||
|
const g = globalThis as unknown as { __spaceWandererGameDb?: Promise<GameDb> }
|
||||||
|
|
||||||
|
async function freshFile(): Promise<{ db: GameDb; file: string }> {
|
||||||
|
const dir = await mkdtemp(path.join(tmpdir(), 'sw-mission-accept-route-test-'))
|
||||||
|
dirs.push(dir)
|
||||||
|
const file = path.join(dir, 'test.db')
|
||||||
|
process.env.SPACE_WANDERER_DB_PATH = file
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
return { db: await getGameDb(), file }
|
||||||
|
}
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
delete process.env.SPACE_WANDERER_DB_PATH
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
for (const d of dirs) await rm(d, { recursive: true, force: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
const post = (id: string) => POST(new Request(`http://localhost/api/missions/${id}/accept`, { method: 'POST' }), { params: Promise.resolve({ id }) })
|
||||||
|
|
||||||
|
// The fixture suite mints no mission rows (JC-6) — insert exactly what the test needs (same
|
||||||
|
// shape as the insertMission helper in lib/game/missions.test.ts, plus a state override).
|
||||||
|
async function insertMission(
|
||||||
|
db: GameDb,
|
||||||
|
fields: { type: string; description: string; targetSystemId?: number | null; conditionKind?: string | null; progressTarget?: number; rewardKind?: string; rewardQty?: number; state?: string },
|
||||||
|
): Promise<number> {
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const [row] = await db.db
|
||||||
|
.insert(schema.missions)
|
||||||
|
.values({ saveId: save.id, type: fields.type, description: fields.description, targetSystemId: fields.targetSystemId ?? null, conditionKind: fields.conditionKind ?? null, progressTarget: fields.progressTarget ?? 1, rewardKind: fields.rewardKind ?? 'resource', rewardQty: fields.rewardQty ?? 1, state: fields.state ?? 'AVAILABLE' })
|
||||||
|
.returning()
|
||||||
|
return row.id
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('POST /api/missions/[id]/accept (5a(ii))', () => {
|
||||||
|
it('happy: mission goes active, board returned, turn unchanged (free)', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const id = await insertMission(db, { type: 'DELIVER', description: 'Jump to Outpost', targetSystemId: 2 })
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
|
||||||
|
const res = await post(String(id))
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(await res.json()).toEqual(await getMissions(db)) // same board shape as today
|
||||||
|
expect((await db.db.select().from(schema.missions)).find((m) => m.id === id)!.state).toBe('ACTIVE') // AVAILABLE → active
|
||||||
|
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn) // free — no turn cost
|
||||||
|
})
|
||||||
|
|
||||||
|
it('non-integer id → 400, nothing changes', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
expect((await post('abc')).status).toBe(400)
|
||||||
|
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('unknown id → 404, nothing changes', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
expect((await post('999')).status).toBe(404)
|
||||||
|
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('not AVAILABLE → 409 (existing code), nothing changes', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const id = await insertMission(db, { type: 'EXPLORE', description: 'Scan 2 bodies', progressTarget: 2, state: 'ACTIVE' })
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
expect((await post(String(id))).status).toBe(409)
|
||||||
|
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a mission already active → 409 (existing code), the target stays AVAILABLE', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
await insertMission(db, { type: 'FIND', description: 'Find a part while scanning', conditionKind: 'part', state: 'ACTIVE' })
|
||||||
|
const id = await insertMission(db, { type: 'EXPLORE', description: 'Scan 2 bodies', progressTarget: 2 })
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
expect((await post(String(id))).status).toBe(409)
|
||||||
|
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn)
|
||||||
|
expect((await db.db.select().from(schema.missions)).find((m) => m.id === id)!.state).toBe('AVAILABLE')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -2,7 +2,8 @@ import { getGameDb } from '@/lib/db/client'
|
|||||||
import { ensureSave } from '@/lib/game/save'
|
import { ensureSave } from '@/lib/game/save'
|
||||||
import { acceptMission, MissionError } from '@/lib/game/missions'
|
import { acceptMission, MissionError } from '@/lib/game/missions'
|
||||||
|
|
||||||
// Accept an AVAILABLE mission — it becomes the single active one. Costs a turn; returns the fresh board.
|
// Accept an AVAILABLE mission — it becomes the single active one. Instant and free (no turn,
|
||||||
|
// no body); returns the fresh board.
|
||||||
export async function POST(_req: Request, ctx: { params: Promise<{ id: string }> }) {
|
export async function POST(_req: Request, ctx: { params: Promise<{ id: string }> }) {
|
||||||
const db = await getGameDb()
|
const db = await getGameDb()
|
||||||
await ensureSave(db) // acceptMission assumes a save exists
|
await ensureSave(db) // acceptMission assumes a save exists
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
// Handler-level tests for the queueing research route (Task 5a(ii)): POST /api/research with
|
||||||
|
// a crew team queues a RESEARCH row instead of resolving instantly — the tech stays
|
||||||
|
// unresearched until the task completes on the turn tick, the cost comes out of the cargo
|
||||||
|
// hold at queue time, same snapshot shape, same pre-check codes, no turn spent at queue time.
|
||||||
|
import { mkdtemp, rm } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { afterAll, describe, expect, it } from 'vitest'
|
||||||
|
import { getGameDb, type GameDb } from '@/lib/db/client'
|
||||||
|
import * as schema from '@/lib/db/schema'
|
||||||
|
import { getTechState } from '@/lib/game/research'
|
||||||
|
import { TECHS, type TechDef } from '@/lib/game/tech'
|
||||||
|
import { addCrew, buildWorldFixture } from '@/lib/game/test-fixtures'
|
||||||
|
import { POST } from './route'
|
||||||
|
|
||||||
|
const dirs: string[] = []
|
||||||
|
// The route talks to the app-process singleton (getGameDb), so each test points it at a
|
||||||
|
// fresh temp file and uses that very instance for fixtures and assertions — two in-memory
|
||||||
|
// sql.js copies of one file would never see each other's writes.
|
||||||
|
const g = globalThis as unknown as { __spaceWandererGameDb?: Promise<GameDb> }
|
||||||
|
|
||||||
|
async function freshFile(): Promise<{ db: GameDb; file: string }> {
|
||||||
|
const dir = await mkdtemp(path.join(tmpdir(), 'sw-research-route-test-'))
|
||||||
|
dirs.push(dir)
|
||||||
|
const file = path.join(dir, 'test.db')
|
||||||
|
process.env.SPACE_WANDERER_DB_PATH = file
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
return { db: await getGameDb(), file }
|
||||||
|
}
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
delete process.env.SPACE_WANDERER_DB_PATH
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
for (const d of dirs) await rm(d, { recursive: true, force: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
const post = (body: unknown) => POST(new Request('http://localhost/api/research', { method: 'POST', body: JSON.stringify(body) }))
|
||||||
|
|
||||||
|
// The fixture suite mints no tech rows (JC-6) — insert exactly what the test needs from the
|
||||||
|
// pure TECHS definitions (WEAPONS_SYSTEMS: part cost, no prerequisites). The happy path seeds
|
||||||
|
// every row, like the new-game backfill: the snapshot read (getTechState) maps every TECHS def.
|
||||||
|
async function insertTech(db: GameDb, def: TechDef, over: { researched?: boolean } = {}) {
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const [row] = await db.db
|
||||||
|
.insert(schema.tech)
|
||||||
|
.values({ saveId: save.id, slug: def.slug, name: def.name, costKind: def.costKind, costQty: def.costQty, prerequisites: def.prereqs.join(','), effect: def.effect, researched: over.researched ?? false })
|
||||||
|
.returning()
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
|
||||||
|
// The fixture suite mints no cargo hold (JC-6) — seed rows directly.
|
||||||
|
async function seedHold(db: GameDb, rows: { kind: 'resource' | 'part'; name: string; qty: number }[]) {
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
for (const r of rows) {
|
||||||
|
await db.db.insert(schema.inventoryItems).values({ saveId: save.id, ...r })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('POST /api/research (5a(ii))', () => {
|
||||||
|
it('happy: row with type/payload, turn unchanged, cost deducted, tech not researched yet', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const def = TECHS[0] // WEAPONS_SYSTEMS — the tech row's cost comes from its TECHS def
|
||||||
|
for (const d of TECHS) await insertTech(db, d) // every row, like the new-game backfill
|
||||||
|
const tech = (await db.db.select().from(schema.tech)).find((t) => t.slug === def.slug)!
|
||||||
|
await seedHold(db, [{ kind: def.costKind, name: def.costKind === 'resource' ? 'resource' : 'part', qty: def.costQty }])
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
|
||||||
|
const res = await post({ techId: tech.id, leadCrewId: c1 })
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(await res.json()).toEqual(await getTechState(db)) // the same snapshot shape the instant action returned
|
||||||
|
const [row] = await db.db.select().from(schema.tasks)
|
||||||
|
expect(row).toMatchObject({ type: 'RESEARCH', leadCrewId: c1, status: 'ACTIVE', queuedAtTurn: before.turn })
|
||||||
|
expect(JSON.parse(row.helpers)).toEqual([]) // helpers is a JSON text column
|
||||||
|
expect(JSON.parse(row.payload)).toEqual({ techId: tech.id })
|
||||||
|
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn) // no turn increment
|
||||||
|
expect(await db.db.select().from(schema.inventoryItems)).toHaveLength(0) // whole cost deducted at queue time
|
||||||
|
expect((await db.db.select().from(schema.tech)).find((t) => t.id === tech.id)!.researched).toBe(false) // the effect waits for the tick
|
||||||
|
})
|
||||||
|
|
||||||
|
it('unaffordable → 422 (existing spendItems message), nothing queued', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const def = TECHS[0]
|
||||||
|
const tech = await insertTech(db, def)
|
||||||
|
await seedHold(db, [{ kind: def.costKind, name: def.costKind === 'resource' ? 'resource' : 'part', qty: def.costQty - 1 }])
|
||||||
|
const res = await post({ techId: tech.id, leadCrewId: c1 })
|
||||||
|
expect(res.status).toBe(422)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('already researched → 409 (existing pre-check, existing code), nothing queued', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const def = TECHS[0]
|
||||||
|
const tech = await insertTech(db, def, { researched: true })
|
||||||
|
expect((await post({ techId: tech.id, leadCrewId: c1 })).status).toBe(409)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,7 +1,14 @@
|
|||||||
import { getGameDb } from '@/lib/db/client'
|
import { getGameDb } from '@/lib/db/client'
|
||||||
import { ResearchError, researchTech } from '@/lib/game/research'
|
import { parseCrewTeam } from '@/app/api/crew-team'
|
||||||
|
import { getTechState, checkResearchPreconditions, ResearchError } from '@/lib/game/research'
|
||||||
|
import { queueStateFromSave, saveInventory, saveTaskRow } from '@/lib/game/save'
|
||||||
|
import { queueTask, TaskError } from '@/lib/game/tasks'
|
||||||
|
|
||||||
// Research one tech. Body: { "techId": number }. Costs inventory items + a turn; returns the fresh tech tree state.
|
// Research one tech: assign the crew team (lead + helpers) and queue the RESEARCH task — the
|
||||||
|
// tech cost is deducted at queue time and the tech is marked researched (unlock effect
|
||||||
|
// included) when the task completes on the turn tick (runTurn). Body:
|
||||||
|
// { techId, leadCrewId, helperCrewIds? }. Queueing spends no turn; returns the same fresh
|
||||||
|
// tech tree state the instant action returned.
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
let body: unknown
|
let body: unknown
|
||||||
try {
|
try {
|
||||||
@@ -14,12 +21,21 @@ export async function POST(req: Request) {
|
|||||||
if (typeof techId !== 'number' || !Number.isInteger(techId)) {
|
if (typeof techId !== 'number' || !Number.isInteger(techId)) {
|
||||||
return Response.json({ error: 'techId must be an integer' }, { status: 400 })
|
return Response.json({ error: 'techId must be an integer' }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
const team = parseCrewTeam(body)
|
||||||
|
if ('error' in team) {
|
||||||
|
return Response.json({ error: team.error }, { status: team.status })
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const db = await getGameDb()
|
const db = await getGameDb()
|
||||||
return Response.json(await researchTech(db, techId))
|
await checkResearchPreconditions(db, techId) // existing pre-checks: 404 unknown · 409 already researched / missing prereq
|
||||||
|
const state = await queueStateFromSave(db)
|
||||||
|
const { task, inventory } = queueTask(state, { type: 'RESEARCH', payload: { techId }, leadCrewId: team.leadCrewId, helperCrewIds: team.helperCrewIds })
|
||||||
|
await saveTaskRow(db, task)
|
||||||
|
await saveInventory(db, inventory) // the cost was deducted at queue time
|
||||||
|
return Response.json(await getTechState(db))
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof ResearchError) {
|
if (err instanceof ResearchError || err instanceof TaskError) {
|
||||||
return Response.json({ error: err.message }, { status: err.status })
|
return Response.json({ error: err.message }, { status: err.status })
|
||||||
}
|
}
|
||||||
throw err
|
throw err
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
// Handler-level tests for the queueing ship-build route (Task 5a(ii)): POST /api/ship/build
|
||||||
|
// with a crew team queues a SHIP_BUILD row instead of resolving instantly — the build at
|
||||||
|
// base values waits for the turn tick, the flat parts cost comes out of the cargo hold at
|
||||||
|
// queue time, same snapshot shape, same pre-check codes, no turn spent at queue time.
|
||||||
|
import { mkdtemp, rm } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { afterAll, describe, expect, it } from 'vitest'
|
||||||
|
import { getGameDb, type GameDb } from '@/lib/db/client'
|
||||||
|
import * as schema from '@/lib/db/schema'
|
||||||
|
import { getShipState } from '@/lib/game/ship'
|
||||||
|
import { BUILD_PART_COST } from '@/lib/game/ship-costs'
|
||||||
|
import { addCrew, buildWorldFixture } from '@/lib/game/test-fixtures'
|
||||||
|
import { POST } from './route'
|
||||||
|
|
||||||
|
const dirs: string[] = []
|
||||||
|
// The route talks to the app-process singleton (getGameDb), so each test points it at a
|
||||||
|
// fresh temp file and uses that very instance for fixtures and assertions — two in-memory
|
||||||
|
// sql.js copies of one file would never see each other's writes.
|
||||||
|
const g = globalThis as unknown as { __spaceWandererGameDb?: Promise<GameDb> }
|
||||||
|
|
||||||
|
async function freshFile(): Promise<{ db: GameDb; file: string }> {
|
||||||
|
const dir = await mkdtemp(path.join(tmpdir(), 'sw-ship-build-route-test-'))
|
||||||
|
dirs.push(dir)
|
||||||
|
const file = path.join(dir, 'test.db')
|
||||||
|
process.env.SPACE_WANDERER_DB_PATH = file
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
return { db: await getGameDb(), file }
|
||||||
|
}
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
delete process.env.SPACE_WANDERER_DB_PATH
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
for (const d of dirs) await rm(d, { recursive: true, force: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
const post = (body: unknown) => POST(new Request('http://localhost/api/ship/build', { method: 'POST', body: JSON.stringify(body) }))
|
||||||
|
|
||||||
|
// The fixture suite mints no ship rows (JC-6) — insert exactly what the test needs. HULL is
|
||||||
|
// the only type that is unbuilt by default AND has no build gate (WEAPONS is gated behind
|
||||||
|
// the WEAPONS SYSTEMS tech, which the fixture leaves unresearched).
|
||||||
|
async function insertSystem(db: GameDb, over: { type: string; level: number; capacity: number }) {
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const [row] = await db.db.insert(schema.shipSystems).values({ saveId: save.id, ...over }).returning()
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
|
||||||
|
// The fixture suite mints no cargo hold (JC-6) — seed rows directly.
|
||||||
|
async function seedHold(db: GameDb, rows: { kind: 'resource' | 'part'; name: string; qty: number }[]) {
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
for (const r of rows) {
|
||||||
|
await db.db.insert(schema.inventoryItems).values({ saveId: save.id, ...r })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('POST /api/ship/build (5a(ii))', () => {
|
||||||
|
it('happy: row with type/payload, turn unchanged, parts deducted, not built yet', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const sys = await insertSystem(db, { type: 'HULL', level: 0, capacity: 0 }) // unbuilt, no gate
|
||||||
|
await seedHold(db, [{ kind: 'part', name: 'part', qty: BUILD_PART_COST }]) // exactly the existing flat cost
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
|
||||||
|
const res = await post({ type: sys.type, leadCrewId: c1 })
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(await res.json()).toEqual(await getShipState(db)) // the same snapshot shape the instant action returned
|
||||||
|
const [row] = await db.db.select().from(schema.tasks)
|
||||||
|
expect(row).toMatchObject({ type: 'SHIP_BUILD', leadCrewId: c1, status: 'ACTIVE', queuedAtTurn: before.turn })
|
||||||
|
expect(JSON.parse(row.helpers)).toEqual([]) // helpers is a JSON text column
|
||||||
|
expect(JSON.parse(row.payload)).toEqual({ type: sys.type })
|
||||||
|
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn) // no turn increment
|
||||||
|
expect(await db.db.select().from(schema.inventoryItems)).toHaveLength(0) // whole cost deducted at queue time
|
||||||
|
expect((await db.db.select().from(schema.shipSystems)).find((s) => s.id === sys.id)!.level).toBe(0) // the effect waits for the tick
|
||||||
|
})
|
||||||
|
|
||||||
|
it('unaffordable → 422 (existing spendItems message), nothing queued', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
await insertSystem(db, { type: 'HULL', level: 0, capacity: 0 })
|
||||||
|
await seedHold(db, [{ kind: 'part', name: 'part', qty: BUILD_PART_COST - 1 }])
|
||||||
|
const res = await post({ type: 'HULL', leadCrewId: c1 })
|
||||||
|
expect(res.status).toBe(422)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('already built → 409 (existing pre-check, existing code), nothing queued', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const sys = await insertSystem(db, { type: 'HULL', level: 1, capacity: 2 }) // built at base values
|
||||||
|
expect((await post({ type: sys.type, leadCrewId: c1 })).status).toBe(409)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,8 +1,14 @@
|
|||||||
import { getGameDb } from '@/lib/db/client'
|
import { getGameDb } from '@/lib/db/client'
|
||||||
import { ShipError, buildSystem } from '@/lib/game/ship'
|
import { parseCrewTeam } from '@/app/api/crew-team'
|
||||||
|
import { checkBuildPreconditions, getShipState, ShipError } from '@/lib/game/ship'
|
||||||
|
import { queueStateFromSave, saveInventory, saveTaskRow } from '@/lib/game/save'
|
||||||
|
import { queueTask, TaskError } from '@/lib/game/tasks'
|
||||||
|
|
||||||
// Build an unbuilt ship system type at base values. Body: { "type": string }.
|
// Build an unbuilt ship system type at base values: assign the crew team (lead + helpers)
|
||||||
// Costs inventory items + a turn; returns the fresh ship state.
|
// and queue the SHIP_BUILD task — the flat parts cost is deducted at queue time and the
|
||||||
|
// build lands when the task completes on the turn tick (runTurn). Body:
|
||||||
|
// { type, leadCrewId, helperCrewIds? }. Queueing spends no turn; returns the same fresh
|
||||||
|
// ship state the instant action returned.
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
let body: unknown
|
let body: unknown
|
||||||
try {
|
try {
|
||||||
@@ -15,12 +21,21 @@ export async function POST(req: Request) {
|
|||||||
if (typeof type !== 'string' || type.length === 0) {
|
if (typeof type !== 'string' || type.length === 0) {
|
||||||
return Response.json({ error: 'type must be a non-empty string' }, { status: 400 })
|
return Response.json({ error: 'type must be a non-empty string' }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
const team = parseCrewTeam(body)
|
||||||
|
if ('error' in team) {
|
||||||
|
return Response.json({ error: team.error }, { status: team.status })
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const db = await getGameDb()
|
const db = await getGameDb()
|
||||||
return Response.json(await buildSystem(db, type))
|
await checkBuildPreconditions(db, type) // existing pre-checks: 404 unknown type · 409 already built / build gate
|
||||||
|
const state = await queueStateFromSave(db)
|
||||||
|
const { task, inventory } = queueTask(state, { type: 'SHIP_BUILD', payload: { type }, leadCrewId: team.leadCrewId, helperCrewIds: team.helperCrewIds })
|
||||||
|
await saveTaskRow(db, task)
|
||||||
|
await saveInventory(db, inventory) // the cost was deducted at queue time
|
||||||
|
return Response.json(await getShipState(db))
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof ShipError) {
|
if (err instanceof ShipError || err instanceof TaskError) {
|
||||||
return Response.json({ error: err.message }, { status: err.status })
|
return Response.json({ error: err.message }, { status: err.status })
|
||||||
}
|
}
|
||||||
throw err
|
throw err
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
// Handler-level tests for the queueing ship-expand route (Task 5a(ii)): POST /api/ship/expand
|
||||||
|
// with a crew team queues a SHIP_EXPAND row instead of resolving instantly — the capacity
|
||||||
|
// bump waits for the turn tick, the cost comes out of the cargo hold at queue time, same
|
||||||
|
// snapshot shape, same pre-check codes, no turn spent at queue time.
|
||||||
|
import { mkdtemp, rm } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { afterAll, describe, expect, it } from 'vitest'
|
||||||
|
import { getGameDb, type GameDb } from '@/lib/db/client'
|
||||||
|
import * as schema from '@/lib/db/schema'
|
||||||
|
import { getShipState } from '@/lib/game/ship'
|
||||||
|
import { expandCost } from '@/lib/game/ship-costs'
|
||||||
|
import { addCrew, buildWorldFixture } from '@/lib/game/test-fixtures'
|
||||||
|
import { POST } from './route'
|
||||||
|
|
||||||
|
const dirs: string[] = []
|
||||||
|
// The route talks to the app-process singleton (getGameDb), so each test points it at a
|
||||||
|
// fresh temp file and uses that very instance for fixtures and assertions — two in-memory
|
||||||
|
// sql.js copies of one file would never see each other's writes.
|
||||||
|
const g = globalThis as unknown as { __spaceWandererGameDb?: Promise<GameDb> }
|
||||||
|
|
||||||
|
async function freshFile(): Promise<{ db: GameDb; file: string }> {
|
||||||
|
const dir = await mkdtemp(path.join(tmpdir(), 'sw-ship-expand-route-test-'))
|
||||||
|
dirs.push(dir)
|
||||||
|
const file = path.join(dir, 'test.db')
|
||||||
|
process.env.SPACE_WANDERER_DB_PATH = file
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
return { db: await getGameDb(), file }
|
||||||
|
}
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
delete process.env.SPACE_WANDERER_DB_PATH
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
for (const d of dirs) await rm(d, { recursive: true, force: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
const post = (body: unknown) => POST(new Request('http://localhost/api/ship/expand', { method: 'POST', body: JSON.stringify(body) }))
|
||||||
|
|
||||||
|
// The fixture suite mints no ship rows (JC-6) — insert exactly what the test needs.
|
||||||
|
async function insertSystem(db: GameDb, over: { type: string; level: number; capacity: number }) {
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const [row] = await db.db.insert(schema.shipSystems).values({ saveId: save.id, ...over }).returning()
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
|
||||||
|
// The fixture suite mints no cargo hold (JC-6) — seed rows directly.
|
||||||
|
async function seedHold(db: GameDb, rows: { kind: 'resource' | 'part'; name: string; qty: number }[]) {
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
for (const r of rows) {
|
||||||
|
await db.db.insert(schema.inventoryItems).values({ saveId: save.id, ...r })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('POST /api/ship/expand (5a(ii))', () => {
|
||||||
|
it('happy: row with type/payload, turn unchanged, cost deducted, no capacity change yet', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const sys = await insertSystem(db, { type: 'REACTOR', level: 1, capacity: 2 }) // built, not maxed (base cap 10)
|
||||||
|
await seedHold(db, [{ kind: 'resource', name: 'resource', qty: expandCost(sys.capacity) }]) // exactly the existing cost logic
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
|
||||||
|
const res = await post({ systemId: sys.id, leadCrewId: c1 })
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(await res.json()).toEqual(await getShipState(db)) // the same snapshot shape the instant action returned
|
||||||
|
const [row] = await db.db.select().from(schema.tasks)
|
||||||
|
expect(row).toMatchObject({ type: 'SHIP_EXPAND', leadCrewId: c1, status: 'ACTIVE', queuedAtTurn: before.turn })
|
||||||
|
expect(JSON.parse(row.helpers)).toEqual([]) // helpers is a JSON text column
|
||||||
|
expect(JSON.parse(row.payload)).toEqual({ systemId: sys.id })
|
||||||
|
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn) // no turn increment
|
||||||
|
expect(await db.db.select().from(schema.inventoryItems)).toHaveLength(0) // whole cost deducted at queue time
|
||||||
|
expect((await db.db.select().from(schema.shipSystems)).find((s) => s.id === sys.id)!.capacity).toBe(sys.capacity) // the effect waits for the tick
|
||||||
|
})
|
||||||
|
|
||||||
|
it('unaffordable → 422 (existing spendItems message), nothing queued', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const sys = await insertSystem(db, { type: 'REACTOR', level: 1, capacity: 2 })
|
||||||
|
await seedHold(db, [{ kind: 'resource', name: 'resource', qty: expandCost(sys.capacity) - 1 }])
|
||||||
|
const res = await post({ systemId: sys.id, leadCrewId: c1 })
|
||||||
|
expect(res.status).toBe(422)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('max capacity → 409 (existing pre-check, existing code), nothing queued', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const sys = await insertSystem(db, { type: 'REACTOR', level: 1, capacity: 99 }) // above any max
|
||||||
|
expect((await post({ systemId: sys.id, leadCrewId: c1 })).status).toBe(409)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,8 +1,14 @@
|
|||||||
import { getGameDb } from '@/lib/db/client'
|
import { getGameDb } from '@/lib/db/client'
|
||||||
import { ShipError, expandSystem } from '@/lib/game/ship'
|
import { parseCrewTeam } from '@/app/api/crew-team'
|
||||||
|
import { checkExpandPreconditions, getShipState, ShipError } from '@/lib/game/ship'
|
||||||
|
import { queueStateFromSave, saveInventory, saveTaskRow } from '@/lib/game/save'
|
||||||
|
import { queueTask, TaskError } from '@/lib/game/tasks'
|
||||||
|
|
||||||
// Raise a built ship system's capacity by one (capped at max capacity). Body: { "systemId": number }.
|
// Raise a built ship system's capacity by one (capped at max capacity): assign the crew team
|
||||||
// Costs inventory items + a turn; returns the fresh ship state.
|
// (lead + helpers) and queue the SHIP_EXPAND task — the cost (`capacity` units of any
|
||||||
|
// resource) is deducted at queue time and the capacity bump lands when the task completes on
|
||||||
|
// the turn tick (runTurn). Body: { systemId, leadCrewId, helperCrewIds? }. Queueing spends no
|
||||||
|
// turn; returns the same fresh ship state the instant action returned.
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
let body: unknown
|
let body: unknown
|
||||||
try {
|
try {
|
||||||
@@ -15,12 +21,21 @@ export async function POST(req: Request) {
|
|||||||
if (typeof systemId !== 'number' || !Number.isInteger(systemId)) {
|
if (typeof systemId !== 'number' || !Number.isInteger(systemId)) {
|
||||||
return Response.json({ error: 'systemId must be an integer' }, { status: 400 })
|
return Response.json({ error: 'systemId must be an integer' }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
const team = parseCrewTeam(body)
|
||||||
|
if ('error' in team) {
|
||||||
|
return Response.json({ error: team.error }, { status: team.status })
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const db = await getGameDb()
|
const db = await getGameDb()
|
||||||
return Response.json(await expandSystem(db, systemId))
|
await checkExpandPreconditions(db, systemId) // existing pre-checks: 404 unknown · 409 not built / max capacity
|
||||||
|
const state = await queueStateFromSave(db)
|
||||||
|
const { task, inventory } = queueTask(state, { type: 'SHIP_EXPAND', payload: { systemId }, leadCrewId: team.leadCrewId, helperCrewIds: team.helperCrewIds })
|
||||||
|
await saveTaskRow(db, task)
|
||||||
|
await saveInventory(db, inventory) // the cost was deducted at queue time
|
||||||
|
return Response.json(await getShipState(db))
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof ShipError) {
|
if (err instanceof ShipError || err instanceof TaskError) {
|
||||||
return Response.json({ error: err.message }, { status: err.status })
|
return Response.json({ error: err.message }, { status: err.status })
|
||||||
}
|
}
|
||||||
throw err
|
throw err
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
// Handler-level tests for the queueing ship-upgrade route (Task 5a(ii)): POST /api/ship/upgrade
|
||||||
|
// with a crew team queues a SHIP_UPGRADE row instead of resolving instantly — the level-up
|
||||||
|
// waits for the turn tick, the cost comes out of the cargo hold at queue time, same snapshot
|
||||||
|
// shape, same pre-check codes, no turn spent at queue time.
|
||||||
|
import { mkdtemp, rm } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { afterAll, describe, expect, it } from 'vitest'
|
||||||
|
import { getGameDb, type GameDb } from '@/lib/db/client'
|
||||||
|
import * as schema from '@/lib/db/schema'
|
||||||
|
import { getShipState } from '@/lib/game/ship'
|
||||||
|
import { upgradeCost } from '@/lib/game/ship-costs'
|
||||||
|
import { addCrew, buildWorldFixture } from '@/lib/game/test-fixtures'
|
||||||
|
import { POST } from './route'
|
||||||
|
|
||||||
|
const dirs: string[] = []
|
||||||
|
// The route talks to the app-process singleton (getGameDb), so each test points it at a
|
||||||
|
// fresh temp file and uses that very instance for fixtures and assertions — two in-memory
|
||||||
|
// sql.js copies of one file would never see each other's writes.
|
||||||
|
const g = globalThis as unknown as { __spaceWandererGameDb?: Promise<GameDb> }
|
||||||
|
|
||||||
|
async function freshFile(): Promise<{ db: GameDb; file: string }> {
|
||||||
|
const dir = await mkdtemp(path.join(tmpdir(), 'sw-ship-upgrade-route-test-'))
|
||||||
|
dirs.push(dir)
|
||||||
|
const file = path.join(dir, 'test.db')
|
||||||
|
process.env.SPACE_WANDERER_DB_PATH = file
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
return { db: await getGameDb(), file }
|
||||||
|
}
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
delete process.env.SPACE_WANDERER_DB_PATH
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
for (const d of dirs) await rm(d, { recursive: true, force: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
const post = (body: unknown) => POST(new Request('http://localhost/api/ship/upgrade', { method: 'POST', body: JSON.stringify(body) }))
|
||||||
|
|
||||||
|
// The fixture suite mints no ship rows (JC-6) — insert exactly what the test needs.
|
||||||
|
async function insertSystem(db: GameDb, over: { type: string; level: number; capacity: number }) {
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const [row] = await db.db.insert(schema.shipSystems).values({ saveId: save.id, ...over }).returning()
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
|
||||||
|
// The fixture suite mints no cargo hold (JC-6) — seed rows directly.
|
||||||
|
async function seedHold(db: GameDb, rows: { kind: 'resource' | 'part'; name: string; qty: number }[]) {
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
for (const r of rows) {
|
||||||
|
await db.db.insert(schema.inventoryItems).values({ saveId: save.id, ...r })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('POST /api/ship/upgrade (5a(ii))', () => {
|
||||||
|
it('happy: row with type/payload, turn unchanged, cost deducted, no level change yet', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const sys = await insertSystem(db, { type: 'REACTOR', level: 2, capacity: 2 }) // built, not maxed (base cap 5)
|
||||||
|
await seedHold(db, [{ kind: 'resource', name: 'resource', qty: upgradeCost(sys.level) }]) // exactly the existing cost logic
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
|
||||||
|
const res = await post({ systemId: sys.id, leadCrewId: c1 })
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
expect(await res.json()).toEqual(await getShipState(db)) // the same snapshot shape the instant action returned
|
||||||
|
const [row] = await db.db.select().from(schema.tasks)
|
||||||
|
expect(row).toMatchObject({ type: 'SHIP_UPGRADE', leadCrewId: c1, status: 'ACTIVE', queuedAtTurn: before.turn })
|
||||||
|
expect(JSON.parse(row.helpers)).toEqual([]) // helpers is a JSON text column
|
||||||
|
expect(JSON.parse(row.payload)).toEqual({ systemId: sys.id })
|
||||||
|
expect((await db.db.select().from(schema.saves))[0].turn).toBe(before.turn) // no turn increment
|
||||||
|
expect(await db.db.select().from(schema.inventoryItems)).toHaveLength(0) // whole cost deducted at queue time
|
||||||
|
expect((await db.db.select().from(schema.shipSystems)).find((s) => s.id === sys.id)!.level).toBe(sys.level) // the effect waits for the tick
|
||||||
|
})
|
||||||
|
|
||||||
|
it('unaffordable → 422 (existing spendItems message), nothing queued', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const sys = await insertSystem(db, { type: 'REACTOR', level: 2, capacity: 2 })
|
||||||
|
await seedHold(db, [{ kind: 'resource', name: 'resource', qty: upgradeCost(sys.level) - 1 }])
|
||||||
|
const res = await post({ systemId: sys.id, leadCrewId: c1 })
|
||||||
|
expect(res.status).toBe(422)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('max level → 409 (existing pre-check, existing code), nothing queued', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const sys = await insertSystem(db, { type: 'REACTOR', level: 99, capacity: 2 }) // above any max
|
||||||
|
expect((await post({ systemId: sys.id, leadCrewId: c1 })).status).toBe(409)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1,8 +1,14 @@
|
|||||||
import { getGameDb } from '@/lib/db/client'
|
import { getGameDb } from '@/lib/db/client'
|
||||||
import { ShipError, upgradeSystem } from '@/lib/game/ship'
|
import { parseCrewTeam } from '@/app/api/crew-team'
|
||||||
|
import { checkUpgradePreconditions, getShipState, ShipError } from '@/lib/game/ship'
|
||||||
|
import { queueStateFromSave, saveInventory, saveTaskRow } from '@/lib/game/save'
|
||||||
|
import { queueTask, TaskError } from '@/lib/game/tasks'
|
||||||
|
|
||||||
// Level up a built ship system by one (capped at max level). Body: { "systemId": number }.
|
// Level up a built ship system by one (capped at max level): assign the crew team (lead +
|
||||||
// Costs inventory items + a turn; returns the fresh ship state.
|
// helpers) and queue the SHIP_UPGRADE task — the cost (`level` units of any resource) is
|
||||||
|
// deducted at queue time and the level-up lands when the task completes on the turn tick
|
||||||
|
// (runTurn). Body: { systemId, leadCrewId, helperCrewIds? }. Queueing spends no turn;
|
||||||
|
// returns the same fresh ship state the instant action returned.
|
||||||
export async function POST(req: Request) {
|
export async function POST(req: Request) {
|
||||||
let body: unknown
|
let body: unknown
|
||||||
try {
|
try {
|
||||||
@@ -15,12 +21,21 @@ export async function POST(req: Request) {
|
|||||||
if (typeof systemId !== 'number' || !Number.isInteger(systemId)) {
|
if (typeof systemId !== 'number' || !Number.isInteger(systemId)) {
|
||||||
return Response.json({ error: 'systemId must be an integer' }, { status: 400 })
|
return Response.json({ error: 'systemId must be an integer' }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
const team = parseCrewTeam(body)
|
||||||
|
if ('error' in team) {
|
||||||
|
return Response.json({ error: team.error }, { status: team.status })
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const db = await getGameDb()
|
const db = await getGameDb()
|
||||||
return Response.json(await upgradeSystem(db, systemId))
|
await checkUpgradePreconditions(db, systemId) // existing pre-checks: 404 unknown · 409 not built / max level
|
||||||
|
const state = await queueStateFromSave(db)
|
||||||
|
const { task, inventory } = queueTask(state, { type: 'SHIP_UPGRADE', payload: { systemId }, leadCrewId: team.leadCrewId, helperCrewIds: team.helperCrewIds })
|
||||||
|
await saveTaskRow(db, task)
|
||||||
|
await saveInventory(db, inventory) // the cost was deducted at queue time
|
||||||
|
return Response.json(await getShipState(db))
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof ShipError) {
|
if (err instanceof ShipError || err instanceof TaskError) {
|
||||||
return Response.json({ error: err.message }, { status: err.status })
|
return Response.json({ error: err.message }, { status: err.status })
|
||||||
}
|
}
|
||||||
throw err
|
throw err
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
// Handler-level tests for the manual tick route (Task 5b): POST /api/turn (no body) advances
|
||||||
|
// exactly one turn — an empty queue is a FREE SKIP (200, turn +1, nothing else changes, the
|
||||||
|
// route never rejects), and a mid-countdown ACTIVE task decrements by exactly one in both the
|
||||||
|
// returned snapshot and the persisted row (no resolution, no mission hook — it never hits 0).
|
||||||
|
import { mkdtemp, rm } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { afterAll, describe, expect, it } from 'vitest'
|
||||||
|
import { getGameDb, type GameDb } from '@/lib/db/client'
|
||||||
|
import * as schema from '@/lib/db/schema'
|
||||||
|
import { addCrew, buildWorldFixture, insertTaskRow } from '@/lib/game/test-fixtures'
|
||||||
|
import { POST } from './route'
|
||||||
|
|
||||||
|
const dirs: string[] = []
|
||||||
|
// The route talks to the app-process singleton (getGameDb), so each test points it at a
|
||||||
|
// fresh temp file and uses that very instance for fixtures and assertions — two in-memory
|
||||||
|
// sql.js copies of one file would never see each other's writes.
|
||||||
|
const g = globalThis as unknown as { __spaceWandererGameDb?: Promise<GameDb> }
|
||||||
|
|
||||||
|
async function freshFile(): Promise<{ db: GameDb; file: string }> {
|
||||||
|
const dir = await mkdtemp(path.join(tmpdir(), 'sw-turn-route-test-'))
|
||||||
|
dirs.push(dir)
|
||||||
|
const file = path.join(dir, 'test.db')
|
||||||
|
process.env.SPACE_WANDERER_DB_PATH = file
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
return { db: await getGameDb(), file }
|
||||||
|
}
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
delete process.env.SPACE_WANDERER_DB_PATH
|
||||||
|
delete g.__spaceWandererGameDb
|
||||||
|
for (const d of dirs) await rm(d, { recursive: true, force: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
// No request body — the handler never reads one.
|
||||||
|
const post = () => POST()
|
||||||
|
|
||||||
|
describe('POST /api/turn', () => {
|
||||||
|
it('empty queue → free skip: 200, turn +1, nothing else changes', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
|
||||||
|
const res = await post()
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const snap = await res.json()
|
||||||
|
expect(snap.turn).toBe(before.turn + 1)
|
||||||
|
expect(await db.db.select().from(schema.tasks)).toHaveLength(0) // the tick creates nothing
|
||||||
|
expect(snap.tasks).toEqual([]) // the composed queue array is empty
|
||||||
|
})
|
||||||
|
|
||||||
|
it('one ACTIVE task → 200, remaining decrements by exactly 1 in the returned snapshot', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const [before] = await db.db.select().from(schema.saves)
|
||||||
|
// Fixture task: one ACTIVE row, mid-countdown — a direct insert on the queue table
|
||||||
|
// (the 4b save.test pattern: it works with the queue rows directly); it never reaches 0
|
||||||
|
// this tick, so no resolver and no mission hook runs
|
||||||
|
await insertTaskRow(db, { type: 'JUMP', payload: { systemId: f.sys1, hops: 1 }, leadCrewId: c1, helpers: [], duration: 5, remaining: 3, status: 'ACTIVE', queuedAtTurn: before.turn })
|
||||||
|
|
||||||
|
const res = await post()
|
||||||
|
expect(res.status).toBe(200)
|
||||||
|
const snap = await res.json()
|
||||||
|
expect(snap.turn).toBe(before.turn + 1)
|
||||||
|
expect(snap.tasks).toHaveLength(1)
|
||||||
|
expect(snap.tasks[0].remaining).toBe(2) // 3 − 1: exactly one decrement
|
||||||
|
expect((await db.db.select().from(schema.tasks))[0].remaining).toBe(2) // the persisted row matches the snapshot
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { getGameDb } from '@/lib/db/client'
|
||||||
|
import { getWorldState, runTurn } from '@/lib/game/save'
|
||||||
|
|
||||||
|
// The manual tick (spec §3): advance exactly one turn — every ACTIVE task ages by one, tasks
|
||||||
|
// that reach 0 resolve (the 4a resolvers + their mission hooks, 4b), and PENDING successors
|
||||||
|
// auto-start in FIFO order. An empty queue is a FREE SKIP: turn +1 with nothing else changed —
|
||||||
|
// the route never rejects a tick, so the UI's NEXT TURN button is never disabled. No request
|
||||||
|
// body. Returns the same world snapshot GET /api/world returns, composed with the tick's
|
||||||
|
// task array (the snapshot readers do not select the tasks table, so it comes from the TickResult).
|
||||||
|
export async function POST() {
|
||||||
|
try {
|
||||||
|
const db = await getGameDb()
|
||||||
|
const tick = await runTurn(db)
|
||||||
|
return Response.json({ ...(await getWorldState(db)), tasks: tick.tasks })
|
||||||
|
} catch (err) {
|
||||||
|
// No domain errors escape runTurn (4b fails the task instead) — anything reaching here is
|
||||||
|
// a non-domain rethrow, i.e. a real bug: the error-mapping pattern, 500 when no status.
|
||||||
|
const e = err as { status?: number; message: string }
|
||||||
|
return Response.json({ error: e.message }, { status: e.status ?? 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
import type { CrewDto } from '@/lib/game/save'
|
import type { CrewDto, CrewState } from '@/lib/game/save'
|
||||||
|
|
||||||
// CREW tab — the ship's roster: starting crew plus members found while exploring. Fetches
|
// CREW tab — the ship's roster: starting crew plus members found while exploring. Fetches
|
||||||
// /api/crew on mount; Radix unmounts inactive tabs, so opening this tab always refetches
|
// /api/crew on mount; Radix unmounts inactive tabs, so opening this tab always refetches
|
||||||
@@ -22,10 +22,10 @@ export function CrewPanel({ narrow }: CrewPanelProps) {
|
|||||||
fetch('/api/crew')
|
fetch('/api/crew')
|
||||||
.then(async (res) => {
|
.then(async (res) => {
|
||||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||||
return (await res.json()) as CrewDto[]
|
return (await res.json()) as CrewState // { crew, tasks } — the endpoint wraps the roster (JC-7)
|
||||||
})
|
})
|
||||||
.then((r) => {
|
.then((r) => {
|
||||||
if (!cancelled) setRoster(r)
|
if (!cancelled) setRoster(r.crew)
|
||||||
})
|
})
|
||||||
.catch((err: unknown) => {
|
.catch((err: unknown) => {
|
||||||
if (!cancelled) setError(err instanceof Error ? err.message : String(err))
|
if (!cancelled) setError(err instanceof Error ? err.message : String(err))
|
||||||
|
|||||||
+47
-11
@@ -1,16 +1,19 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useCallback, useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import type { ExploreResult, SystemState } from '@/lib/game/save'
|
import { TeamBuilder } from '@/components/team-builder'
|
||||||
|
import type { CrewState, ExploreResult, SystemState } from '@/lib/game/save'
|
||||||
import type { FoundItem } from '@/lib/game/world'
|
import type { FoundItem } from '@/lib/game/world'
|
||||||
|
|
||||||
// LOCAL SYSTEM tab — the bodies of the current system (planets + staggered moons) with an
|
// LOCAL SYSTEM tab — the bodies of the current system (planets + staggered moons) with an
|
||||||
// EXPLORE button per unexplored row. The parent (MissionControl) owns the /api/system state so
|
// EXPLORE button per unexplored row. A button click ARMS the planet (#44): the crew team
|
||||||
// the right column's CARGO HOLD mirrors scans immediately; this panel reports each scan's
|
// builder mounts at the top of the column and its DISPATCH POSTs /api/explore with the team.
|
||||||
// response up via onChanged and keeps only its own UI bits locally (no polling). Turn-based:
|
// The parent (MissionControl) owns the /api/system state so the right column's CARGO HOLD
|
||||||
// one scan costs a turn, each body once.
|
// mirrors scans immediately; this panel reports each scan's response up via onChanged and
|
||||||
|
// keeps only its own UI bits locally (no polling). Turn-based: one scan costs a turn, each
|
||||||
|
// body once.
|
||||||
|
|
||||||
interface LocalSystemPanelProps {
|
interface LocalSystemPanelProps {
|
||||||
system: SystemState | null
|
system: SystemState | null
|
||||||
@@ -21,27 +24,50 @@ export function LocalSystemPanel({ system, onChanged }: LocalSystemPanelProps) {
|
|||||||
const [lastOutcome, setLastOutcome] = useState<FoundItem[] | null>(null)
|
const [lastOutcome, setLastOutcome] = useState<FoundItem[] | null>(null)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
const [exploringId, setExploringId] = useState<number | null>(null)
|
const [exploringId, setExploringId] = useState<number | null>(null)
|
||||||
|
// #44 — the armed planet (the last-clicked unexplored row); the builder above the list picks
|
||||||
|
// the team and its DISPATCH performs the scan.
|
||||||
|
const [armedPlanetId, setArmedPlanetId] = useState<number | null>(null)
|
||||||
|
const [crew, setCrew] = useState<CrewState | null>(null)
|
||||||
|
|
||||||
|
// JC-14 — the roster + queue the builder mirrors: fetched on mount and after every
|
||||||
|
// successful dispatch (the scan response updates the system state, not the roster).
|
||||||
|
// Keep-old-on-failure, the house .catch(() => {}) pattern.
|
||||||
|
const fetchCrew = useCallback(() => {
|
||||||
|
fetch('/api/crew')
|
||||||
|
.then(async (res) => {
|
||||||
|
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||||
|
return (await res.json()) as CrewState
|
||||||
|
})
|
||||||
|
.then((c) => setCrew(c))
|
||||||
|
.catch(() => {})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchCrew()
|
||||||
|
}, [fetchCrew])
|
||||||
|
|
||||||
const explore = useCallback(
|
const explore = useCallback(
|
||||||
async (planetId: number) => {
|
async (planetId: number, leadCrewId: number, helperCrewIds: number[]) => {
|
||||||
setExploringId(planetId)
|
setExploringId(planetId)
|
||||||
|
setArmedPlanetId(null)
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/explore', {
|
const res = await fetch('/api/explore', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'content-type': 'application/json' },
|
headers: { 'content-type': 'application/json' },
|
||||||
body: JSON.stringify({ planetId }),
|
body: JSON.stringify({ planetId, leadCrewId, helperCrewIds }),
|
||||||
})
|
})
|
||||||
const body = (await res.json()) as ExploreResult & { error?: string }
|
const body = (await res.json()) as ExploreResult & { error?: string }
|
||||||
if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`)
|
if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`)
|
||||||
onChanged(body) // fresh state straight from the response — parent mirrors it to CARGO HOLD
|
onChanged(body) // fresh state straight from the response — parent mirrors it to CARGO HOLD
|
||||||
setLastOutcome(body.outcome)
|
setLastOutcome(body.outcome)
|
||||||
|
fetchCrew() // JC-14 — the dispatch committed a team; refresh the roster + queue for the builder
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
setError(err instanceof Error ? err.message : String(err))
|
setError(err instanceof Error ? err.message : String(err))
|
||||||
} finally {
|
} finally {
|
||||||
setExploringId(null)
|
setExploringId(null)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[onChanged]
|
[onChanged, fetchCrew]
|
||||||
)
|
)
|
||||||
|
|
||||||
if (!system) {
|
if (!system) {
|
||||||
@@ -57,6 +83,16 @@ export function LocalSystemPanel({ system, onChanged }: LocalSystemPanelProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
|
||||||
|
{/* #44 — the armed planet's crew picker (JC-13: mounted only while a planet is armed);
|
||||||
|
its DISPATCH performs the scan with the picked team. */}
|
||||||
|
{armedPlanetId !== null && crew !== null && (
|
||||||
|
<TeamBuilder
|
||||||
|
type="EXPLORE"
|
||||||
|
roster={crew.crew}
|
||||||
|
tasks={crew.tasks}
|
||||||
|
onQueue={(leadCrewId, helperCrewIds) => void explore(armedPlanetId, leadCrewId, helperCrewIds)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<div style={{ border: '1px solid var(--border)', background: 'var(--surface)', overflow: 'hidden' }}>
|
<div style={{ border: '1px solid var(--border)', background: 'var(--surface)', overflow: 'hidden' }}>
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
@@ -108,9 +144,9 @@ export function LocalSystemPanel({ system, onChanged }: LocalSystemPanelProps) {
|
|||||||
variant="OUTLINE"
|
variant="OUTLINE"
|
||||||
size="SM"
|
size="SM"
|
||||||
disabled={exploringId !== null}
|
disabled={exploringId !== null}
|
||||||
onClick={() => void explore(row.id)}
|
onClick={() => setArmedPlanetId(armedPlanetId === row.id ? null : row.id)} // #44 — arms/disarms; the builder dispatches
|
||||||
>
|
>
|
||||||
{exploringId === row.id ? 'SCANNING…' : `${row.name.toUpperCase()} // EXPLORE`}
|
{exploringId === row.id ? 'SCANNING…' : `${row.name.toUpperCase()} // ${armedPlanetId === row.id ? 'PICK TEAM' : 'EXPLORE'}`}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -13,11 +13,13 @@ import { CrewPanel } from '@/components/crew-panel'
|
|||||||
import { EventLogPanel } from '@/components/event-log'
|
import { EventLogPanel } from '@/components/event-log'
|
||||||
import { LocalSystemPanel } from '@/components/local-system'
|
import { LocalSystemPanel } from '@/components/local-system'
|
||||||
import { MissionPanel } from '@/components/missions'
|
import { MissionPanel } from '@/components/missions'
|
||||||
|
import { NextTurnButton } from '@/components/next-turn-button'
|
||||||
import { ShipSystemsPanel } from '@/components/ship-systems'
|
import { ShipSystemsPanel } from '@/components/ship-systems'
|
||||||
import { SkillTreePanel } from '@/components/skill-tree'
|
import { SkillTreePanel } from '@/components/skill-tree'
|
||||||
|
import { TaskStrip } from '@/components/task-strip'
|
||||||
import { WorldMapPanel } from '@/components/world-map'
|
import { WorldMapPanel } from '@/components/world-map'
|
||||||
import { CREW_CAPACITY } from '@/lib/game/ship-costs'
|
import { CREW_CAPACITY } from '@/lib/game/ship-costs'
|
||||||
import type { CrewDto, SystemState } from '@/lib/game/save'
|
import type { CrewState, SystemState } from '@/lib/game/save'
|
||||||
import type { ShipState } from '@/lib/game/ship'
|
import type { ShipState } from '@/lib/game/ship'
|
||||||
import type { TechDto } from '@/lib/game/tech'
|
import type { TechDto } from '@/lib/game/tech'
|
||||||
import pkg from '@/package.json'
|
import pkg from '@/package.json'
|
||||||
@@ -62,7 +64,12 @@ export function MissionControl() {
|
|||||||
// #38 — admin DB CRUD overlay, opened from the header.
|
// #38 — admin DB CRUD overlay, opened from the header.
|
||||||
const [adminOpen, setAdminOpen] = useState(false)
|
const [adminOpen, setAdminOpen] = useState(false)
|
||||||
|
|
||||||
useEffect(() => {
|
// #44 — the four mount fetches, extracted into a callback so the NEXT TURN button (5b) can
|
||||||
|
// re-run them after /api/turn: a tick can change all four snapshots (the turn always; inventory
|
||||||
|
// on an explore resolve, system on a jump resolve, the roster on a recruit, tech on a research
|
||||||
|
// completion) — a strict superset of refreshSystem, which stays for the jump callback. Same
|
||||||
|
// failure policy as the mount fetch — keep the old state on error.
|
||||||
|
const refreshAll = useCallback(() => {
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
fetch('/api/ship')
|
fetch('/api/ship')
|
||||||
.then(async (res) => {
|
.then(async (res) => {
|
||||||
@@ -94,10 +101,10 @@ export function MissionControl() {
|
|||||||
fetch('/api/crew')
|
fetch('/api/crew')
|
||||||
.then(async (res) => {
|
.then(async (res) => {
|
||||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||||
return (await res.json()) as CrewDto[]
|
return (await res.json()) as CrewState // { crew, tasks } — the endpoint wraps the roster (JC-7)
|
||||||
})
|
})
|
||||||
.then((c) => {
|
.then((c) => {
|
||||||
if (!cancelled) setCrewCount(c.length)
|
if (!cancelled) setCrewCount(c.crew.length)
|
||||||
})
|
})
|
||||||
.catch(() => {})
|
.catch(() => {})
|
||||||
return () => {
|
return () => {
|
||||||
@@ -105,6 +112,9 @@ export function MissionControl() {
|
|||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
// The effect returns refreshAll's cleanup, so unmount still cancels the in-flight setStates.
|
||||||
|
useEffect(() => refreshAll(), [refreshAll])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const id = setInterval(() => setTick((t) => t + 1), 1000)
|
const id = setInterval(() => setTick((t) => t + 1), 1000)
|
||||||
return () => clearInterval(id)
|
return () => clearInterval(id)
|
||||||
@@ -548,6 +558,17 @@ export function MissionControl() {
|
|||||||
|
|
||||||
<Badge variant="ACTIVE">SYS ONLINE</Badge>
|
<Badge variant="ACTIVE">SYS ONLINE</Badge>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
|
{/* #44 — the manual tick control (5b): fixed bottom-right, outside the tab grid so it
|
||||||
|
stays visible on every tab (Radix unmounts inactive tabs — the button only refreshes
|
||||||
|
the snapshots this shell owns) */}
|
||||||
|
<NextTurnButton turn={ship?.turn ?? null} onTicked={refreshAll} />
|
||||||
|
|
||||||
|
{/* #44 — the active-tasks strip: fixed bottom-left (same mount convention as the button —
|
||||||
|
outside the tab grid so it stays visible on every tab). Data: the shell's system
|
||||||
|
snapshot (JC-15) — refreshAll re-runs /api/system on every turn, so it updates on
|
||||||
|
every shell refresh with no fetch of its own. */}
|
||||||
|
<TaskStrip tasks={system?.tasks ?? []} />
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
|
||||||
|
// NEXT TURN — the manual tick control (5b): a fixed bottom-right button + the current turn from
|
||||||
|
// the ship snapshot the shell holds. One click = POST /api/turn (no body); on success the shell
|
||||||
|
// re-fetches its snapshots. Review Focus 4: the button is NEVER disabled by game state — an
|
||||||
|
// empty queue is a FREE SKIP (the route always returns 200) — and the only transient is an
|
||||||
|
// in-flight request, which the handler ignores. `disabled` is never set, so the cva
|
||||||
|
// disabled:opacity-40 styling never applies either.
|
||||||
|
|
||||||
|
export function NextTurnButton({ turn, onTicked }: { turn: number | null; onTicked: () => void }) {
|
||||||
|
const [inFlight, setInFlight] = useState(false)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const tick = () => {
|
||||||
|
if (inFlight) return // the only guard — a transient, never a game-state disable
|
||||||
|
setInFlight(true)
|
||||||
|
setError(null)
|
||||||
|
fetch('/api/turn', { method: 'POST' })
|
||||||
|
.then(async (res) => {
|
||||||
|
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||||
|
onTicked() // the same app-wide snapshot refresh the shell uses after every other action
|
||||||
|
})
|
||||||
|
.catch((err: unknown) => setError(err instanceof Error ? err.message : String(err)))
|
||||||
|
.finally(() => setInFlight(false))
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
right: '1rem',
|
||||||
|
bottom: '1rem',
|
||||||
|
zIndex: 60, // above the header/footer's 50
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
alignItems: 'flex-end',
|
||||||
|
gap: '0.375rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{error && (
|
||||||
|
<span style={{ fontSize: '0.62rem', color: 'var(--color-red)', letterSpacing: '0.08em' }}>{error.toUpperCase()}</span>
|
||||||
|
)}
|
||||||
|
<span style={{ fontSize: '0.62rem', color: 'var(--text-muted)', letterSpacing: '0.12em' }}>
|
||||||
|
TURN {turn ?? '—'}
|
||||||
|
</span>
|
||||||
|
<Button variant="EXEC" size="SM" onClick={tick}>
|
||||||
|
NEXT TURN
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
+80
-11
@@ -1,16 +1,21 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
|
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { TeamBuilder } from '@/components/team-builder'
|
||||||
import { BUILD_PART_COST, expandCost, totalQty, upgradeCost } from '@/lib/game/ship-costs'
|
import { BUILD_PART_COST, expandCost, totalQty, upgradeCost } from '@/lib/game/ship-costs'
|
||||||
import type { ShipState, ShipSystemDto } from '@/lib/game/ship'
|
import type { ShipState, ShipSystemDto } from '@/lib/game/ship'
|
||||||
|
import type { CrewState } from '@/lib/game/save'
|
||||||
import { buildGate, effectiveCapacityCap, effectiveLevelCap } from '@/lib/game/tech'
|
import { buildGate, effectiveCapacityCap, effectiveLevelCap } from '@/lib/game/tech'
|
||||||
|
import type { TaskType } from '@/lib/game/tasks'
|
||||||
|
|
||||||
// SHIP SYSTEMS tab — live data. The parent (MissionControl) owns the ship state so the left
|
// SHIP SYSTEMS tab — live data. The parent (MissionControl) owns the ship state so the left
|
||||||
// column mirrors actions immediately; this panel applies each action's response directly via
|
// column mirrors actions immediately; this panel applies each action's response directly via
|
||||||
// onChanged (no polling). Buttons are disabled when unaffordable, capped or gated by an
|
// onChanged (no polling). A card's UPGRADE / EXPAND / BUILD button ARMS the action (#44): the
|
||||||
|
// crew team builder mounts at the top of the column and its DISPATCH POSTs the ship route with
|
||||||
|
// the team. Buttons are disabled when unaffordable, capped or gated by an
|
||||||
// unresearched tech, using the same pure helpers the API enforces (lib/game/ship-costs.ts +
|
// unresearched tech, using the same pure helpers the API enforces (lib/game/ship-costs.ts +
|
||||||
// lib/game/tech.ts).
|
// lib/game/tech.ts).
|
||||||
|
|
||||||
@@ -24,6 +29,32 @@ interface ShipSystemsPanelProps {
|
|||||||
export function ShipSystemsPanel({ ship, narrow, onChanged, researchedSlugs }: ShipSystemsPanelProps) {
|
export function ShipSystemsPanel({ ship, narrow, onChanged, researchedSlugs }: ShipSystemsPanelProps) {
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
const [busy, setBusy] = useState(false) // one action at a time — turn-based game
|
const [busy, setBusy] = useState(false) // one action at a time — turn-based game
|
||||||
|
// #44 — the armed ship action (which card + which of UPGRADE/EXPAND/BUILD); the builder above
|
||||||
|
// the grid picks the team and its DISPATCH performs it.
|
||||||
|
const [armed, setArmed] = useState<{ type: TaskType; url: string; body: Record<string, unknown>; systemId: number } | null>(null)
|
||||||
|
const [crew, setCrew] = useState<CrewState | null>(null)
|
||||||
|
|
||||||
|
// JC-14 — the roster + queue the builder mirrors: fetched on mount and after every
|
||||||
|
// successful dispatch (the action response updates the ship state, not the roster).
|
||||||
|
// Keep-old-on-failure, the house .catch(() => {}) pattern.
|
||||||
|
const fetchCrew = useCallback(() => {
|
||||||
|
fetch('/api/crew')
|
||||||
|
.then(async (res) => {
|
||||||
|
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||||
|
return (await res.json()) as CrewState
|
||||||
|
})
|
||||||
|
.then((c) => setCrew(c))
|
||||||
|
.catch(() => {})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchCrew()
|
||||||
|
}, [fetchCrew])
|
||||||
|
|
||||||
|
// #44 — arm an action (toggle: clicking the armed action's button again disarms it).
|
||||||
|
const arm = useCallback((type: TaskType, url: string, body: Record<string, unknown>, systemId: number) => {
|
||||||
|
setArmed((a) => (a && a.systemId === systemId && a.type === type ? null : { type, url, body, systemId }))
|
||||||
|
}, [])
|
||||||
|
|
||||||
if (!ship) {
|
if (!ship) {
|
||||||
return (
|
return (
|
||||||
@@ -39,11 +70,13 @@ export function ShipSystemsPanel({ ship, narrow, onChanged, researchedSlugs }: S
|
|||||||
async function act(url: string, body: unknown) {
|
async function act(url: string, body: unknown) {
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
setError(null)
|
setError(null)
|
||||||
|
setArmed(null)
|
||||||
try {
|
try {
|
||||||
const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
||||||
const data = (await res.json()) as ShipState & { error?: string }
|
const data = (await res.json()) as ShipState & { error?: string }
|
||||||
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`)
|
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`)
|
||||||
onChanged(data) // response is the fresh ship state — apply directly
|
onChanged(data) // response is the fresh ship state — apply directly
|
||||||
|
fetchCrew() // JC-14 — the dispatch committed a team; refresh the roster + queue for the builder
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
setError(err instanceof Error ? err.message : String(err))
|
setError(err instanceof Error ? err.message : String(err))
|
||||||
} finally {
|
} finally {
|
||||||
@@ -53,6 +86,16 @@ export function ShipSystemsPanel({ ship, narrow, onChanged, researchedSlugs }: S
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
|
||||||
|
{/* #44 — the armed ship action's crew picker (JC-13: mounted only while an action is
|
||||||
|
armed); its DISPATCH performs it with the picked team. */}
|
||||||
|
{armed !== null && crew !== null && (
|
||||||
|
<TeamBuilder
|
||||||
|
type={armed.type}
|
||||||
|
roster={crew.crew}
|
||||||
|
tasks={crew.tasks}
|
||||||
|
onQueue={(leadCrewId, helperCrewIds) => void act(armed.url, { ...armed.body, leadCrewId, helperCrewIds })}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{error && (
|
{error && (
|
||||||
<div style={{ border: '1px solid var(--border)', background: 'var(--surface)', padding: '0.75rem' }}>
|
<div style={{ border: '1px solid var(--border)', background: 'var(--surface)', padding: '0.75rem' }}>
|
||||||
<span style={{ fontSize: '0.62rem', color: 'var(--color-red)', letterSpacing: '0.08em' }}>{error.toUpperCase()}</span>
|
<span style={{ fontSize: '0.62rem', color: 'var(--color-red)', letterSpacing: '0.08em' }}>{error.toUpperCase()}</span>
|
||||||
@@ -60,7 +103,16 @@ export function ShipSystemsPanel({ ship, narrow, onChanged, researchedSlugs }: S
|
|||||||
)}
|
)}
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: narrow ? '1fr' : 'repeat(2, 1fr)', gap: '0.75rem' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: narrow ? '1fr' : 'repeat(2, 1fr)', gap: '0.75rem' }}>
|
||||||
{ship.systems.map((system) => (
|
{ship.systems.map((system) => (
|
||||||
<SystemCard key={system.id} system={system} resources={resources} parts={parts} busy={busy} researchedSlugs={researchedSlugs} onAct={act} />
|
<SystemCard
|
||||||
|
key={system.id}
|
||||||
|
system={system}
|
||||||
|
resources={resources}
|
||||||
|
parts={parts}
|
||||||
|
busy={busy}
|
||||||
|
researchedSlugs={researchedSlugs}
|
||||||
|
armedType={armed !== null && armed.systemId === system.id ? armed.type : null}
|
||||||
|
onArm={arm}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -73,14 +125,16 @@ function SystemCard({
|
|||||||
parts,
|
parts,
|
||||||
busy,
|
busy,
|
||||||
researchedSlugs,
|
researchedSlugs,
|
||||||
onAct,
|
armedType,
|
||||||
|
onArm,
|
||||||
}: {
|
}: {
|
||||||
system: ShipSystemDto
|
system: ShipSystemDto
|
||||||
resources: number
|
resources: number
|
||||||
parts: number
|
parts: number
|
||||||
busy: boolean
|
busy: boolean
|
||||||
researchedSlugs: Set<string>
|
researchedSlugs: Set<string>
|
||||||
onAct: (url: string, body: unknown) => void
|
armedType: TaskType | null // #44 — which of this card's actions is the armed target
|
||||||
|
onArm: (type: TaskType, url: string, body: Record<string, unknown>, systemId: number) => void
|
||||||
}) {
|
}) {
|
||||||
const maxLevel = effectiveLevelCap(system.type, researchedSlugs)
|
const maxLevel = effectiveLevelCap(system.type, researchedSlugs)
|
||||||
const maxCapacity = effectiveCapacityCap(system.type, researchedSlugs)
|
const maxCapacity = effectiveCapacityCap(system.type, researchedSlugs)
|
||||||
@@ -116,16 +170,31 @@ function SystemCard({
|
|||||||
<CardFooter className="gap-2">
|
<CardFooter className="gap-2">
|
||||||
{system.built ? (
|
{system.built ? (
|
||||||
<>
|
<>
|
||||||
<Button variant="OUTLINE" size="SM" disabled={upgradeDisabled} onClick={() => onAct('/api/ship/upgrade', { systemId: system.id })}>
|
<Button
|
||||||
UPGRADE
|
variant="OUTLINE"
|
||||||
|
size="SM"
|
||||||
|
disabled={upgradeDisabled}
|
||||||
|
onClick={() => onArm('SHIP_UPGRADE', '/api/ship/upgrade', { systemId: system.id }, system.id)}
|
||||||
|
>
|
||||||
|
{armedType === 'SHIP_UPGRADE' ? 'PICK TEAM' : 'UPGRADE'}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="OUTLINE" size="SM" disabled={expandDisabled} onClick={() => onAct('/api/ship/expand', { systemId: system.id })}>
|
<Button
|
||||||
EXPAND
|
variant="OUTLINE"
|
||||||
|
size="SM"
|
||||||
|
disabled={expandDisabled}
|
||||||
|
onClick={() => onArm('SHIP_EXPAND', '/api/ship/expand', { systemId: system.id }, system.id)}
|
||||||
|
>
|
||||||
|
{armedType === 'SHIP_EXPAND' ? 'PICK TEAM' : 'EXPAND'}
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<Button variant="OUTLINE" size="SM" disabled={buildDisabled} onClick={() => onAct('/api/ship/build', { type: system.type })}>
|
<Button
|
||||||
BUILD NEW
|
variant="OUTLINE"
|
||||||
|
size="SM"
|
||||||
|
disabled={buildDisabled}
|
||||||
|
onClick={() => onArm('SHIP_BUILD', '/api/ship/build', { type: system.type }, system.id)}
|
||||||
|
>
|
||||||
|
{armedType === 'SHIP_BUILD' ? 'PICK TEAM' : 'BUILD NEW'}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
|
|||||||
+52
-10
@@ -1,16 +1,20 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
|
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { TeamBuilder } from '@/components/team-builder'
|
||||||
import { totalQty } from '@/lib/game/ship-costs'
|
import { totalQty } from '@/lib/game/ship-costs'
|
||||||
import type { ShipState } from '@/lib/game/ship'
|
import type { ShipState } from '@/lib/game/ship'
|
||||||
|
import type { CrewState } from '@/lib/game/save'
|
||||||
import type { TechDto } from '@/lib/game/tech'
|
import type { TechDto } from '@/lib/game/tech'
|
||||||
|
|
||||||
// SKILL TREE tab — live data. The parent (MissionControl) owns the tech state + ship state; this panel
|
// SKILL TREE tab — live data. The parent (MissionControl) owns the tech state + ship state; this panel
|
||||||
// applies each research response directly via onResearched (no polling). RESEARCH is enabled only when
|
// applies each research response directly via onResearched (no polling). A card's RESEARCH button ARMS
|
||||||
// the tech is AVAILABLE and its cost is payable from the cargo hold, mirroring what POST /api/research enforces.
|
// the tech (#44): the crew team builder mounts at the top of the column and its DISPATCH POSTs
|
||||||
|
// /api/research with the team. The button is enabled only when the tech is AVAILABLE and its cost is
|
||||||
|
// payable from the cargo hold, mirroring what POST /api/research enforces.
|
||||||
|
|
||||||
interface SkillTreePanelProps {
|
interface SkillTreePanelProps {
|
||||||
techs: TechDto[] | null
|
techs: TechDto[] | null
|
||||||
@@ -22,6 +26,27 @@ interface SkillTreePanelProps {
|
|||||||
export function SkillTreePanel({ techs, ship, narrow, onResearched }: SkillTreePanelProps) {
|
export function SkillTreePanel({ techs, ship, narrow, onResearched }: SkillTreePanelProps) {
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
const [busy, setBusy] = useState(false) // one action at a time — turn-based game
|
const [busy, setBusy] = useState(false) // one action at a time — turn-based game
|
||||||
|
// #44 — the armed tech (last-clicked AVAILABLE card); the builder above the grid picks the
|
||||||
|
// team and its DISPATCH performs the research.
|
||||||
|
const [armedTechId, setArmedTechId] = useState<number | null>(null)
|
||||||
|
const [crew, setCrew] = useState<CrewState | null>(null)
|
||||||
|
|
||||||
|
// JC-14 — the roster + queue the builder mirrors: fetched on mount and after every
|
||||||
|
// successful dispatch (the research response updates the tech state, not the roster).
|
||||||
|
// Keep-old-on-failure, the house .catch(() => {}) pattern.
|
||||||
|
const fetchCrew = useCallback(() => {
|
||||||
|
fetch('/api/crew')
|
||||||
|
.then(async (res) => {
|
||||||
|
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||||
|
return (await res.json()) as CrewState
|
||||||
|
})
|
||||||
|
.then((c) => setCrew(c))
|
||||||
|
.catch(() => {})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchCrew()
|
||||||
|
}, [fetchCrew])
|
||||||
|
|
||||||
if (!techs || !ship) {
|
if (!techs || !ship) {
|
||||||
return (
|
return (
|
||||||
@@ -34,14 +59,16 @@ export function SkillTreePanel({ techs, ship, narrow, onResearched }: SkillTreeP
|
|||||||
const resources = totalQty(ship.inventory, 'resource')
|
const resources = totalQty(ship.inventory, 'resource')
|
||||||
const parts = totalQty(ship.inventory, 'part')
|
const parts = totalQty(ship.inventory, 'part')
|
||||||
|
|
||||||
async function research(tech: TechDto) {
|
async function research(tech: TechDto, leadCrewId: number, helperCrewIds: number[]) {
|
||||||
setBusy(true)
|
setBusy(true)
|
||||||
setError(null)
|
setError(null)
|
||||||
|
setArmedTechId(null)
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/research', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ techId: tech.id }) })
|
const res = await fetch('/api/research', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ techId: tech.id, leadCrewId, helperCrewIds }) })
|
||||||
const data = (await res.json()) as TechDto[] & { error?: string }
|
const data = (await res.json()) as TechDto[] & { error?: string }
|
||||||
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`)
|
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`)
|
||||||
onResearched(data) // response is the fresh tech tree state — apply directly
|
onResearched(data) // response is the fresh tech tree state — apply directly
|
||||||
|
fetchCrew() // JC-14 — the dispatch committed a team; refresh the roster + queue for the builder
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
setError(err instanceof Error ? err.message : String(err))
|
setError(err instanceof Error ? err.message : String(err))
|
||||||
} finally {
|
} finally {
|
||||||
@@ -51,6 +78,19 @@ export function SkillTreePanel({ techs, ship, narrow, onResearched }: SkillTreeP
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
|
||||||
|
{/* #44 — the armed tech's crew picker (JC-13: mounted only while a tech is armed);
|
||||||
|
its DISPATCH performs the research with the picked team. */}
|
||||||
|
{armedTechId !== null && crew !== null && (
|
||||||
|
<TeamBuilder
|
||||||
|
type="RESEARCH"
|
||||||
|
roster={crew.crew}
|
||||||
|
tasks={crew.tasks}
|
||||||
|
onQueue={(leadCrewId, helperCrewIds) => {
|
||||||
|
const tech = techs.find((t) => t.id === armedTechId)
|
||||||
|
if (tech) void research(tech, leadCrewId, helperCrewIds)
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{error && (
|
{error && (
|
||||||
<div style={{ border: '1px solid var(--border)', background: 'var(--surface)', padding: '0.75rem' }}>
|
<div style={{ border: '1px solid var(--border)', background: 'var(--surface)', padding: '0.75rem' }}>
|
||||||
<span style={{ fontSize: '0.62rem', color: 'var(--color-red)', letterSpacing: '0.08em' }}>{error.toUpperCase()}</span>
|
<span style={{ fontSize: '0.62rem', color: 'var(--color-red)', letterSpacing: '0.08em' }}>{error.toUpperCase()}</span>
|
||||||
@@ -58,7 +98,7 @@ export function SkillTreePanel({ techs, ship, narrow, onResearched }: SkillTreeP
|
|||||||
)}
|
)}
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: narrow ? '1fr' : 'repeat(2, 1fr)', gap: '0.75rem' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: narrow ? '1fr' : 'repeat(2, 1fr)', gap: '0.75rem' }}>
|
||||||
{techs.map((tech) => (
|
{techs.map((tech) => (
|
||||||
<TechCard key={tech.slug} tech={tech} resources={resources} parts={parts} busy={busy} onResearch={research} />
|
<TechCard key={tech.slug} tech={tech} resources={resources} parts={parts} busy={busy} armed={armedTechId === tech.id} onArm={(t) => setArmedTechId(armedTechId === t.id ? null : t.id)} />
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -70,13 +110,15 @@ function TechCard({
|
|||||||
resources,
|
resources,
|
||||||
parts,
|
parts,
|
||||||
busy,
|
busy,
|
||||||
onResearch,
|
armed,
|
||||||
|
onArm,
|
||||||
}: {
|
}: {
|
||||||
tech: TechDto
|
tech: TechDto
|
||||||
resources: number
|
resources: number
|
||||||
parts: number
|
parts: number
|
||||||
busy: boolean
|
busy: boolean
|
||||||
onResearch: (tech: TechDto) => void
|
armed: boolean // #44 — this card's tech is the armed target (the builder is open for it)
|
||||||
|
onArm: (tech: TechDto) => void
|
||||||
}) {
|
}) {
|
||||||
const affordable = tech.costKind === 'resource' ? resources >= tech.costQty : parts >= tech.costQty
|
const affordable = tech.costKind === 'resource' ? resources >= tech.costQty : parts >= tech.costQty
|
||||||
const researchDisabled = busy || tech.state !== 'AVAILABLE' || !affordable
|
const researchDisabled = busy || tech.state !== 'AVAILABLE' || !affordable
|
||||||
@@ -101,8 +143,8 @@ function TechCard({
|
|||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
<CardFooter>
|
<CardFooter>
|
||||||
<Button variant="OUTLINE" size="SM" disabled={researchDisabled} onClick={() => onResearch(tech)}>
|
<Button variant="OUTLINE" size="SM" disabled={researchDisabled} onClick={() => onArm(tech)}>
|
||||||
RESEARCH
|
{armed ? 'PICK TEAM' : 'RESEARCH'}
|
||||||
</Button>
|
</Button>
|
||||||
</CardFooter>
|
</CardFooter>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import type { QueueDto } from '@/lib/game/save'
|
||||||
|
|
||||||
|
// TASK STRIP — the save's task queue, fixed bottom-left next to the NEXT TURN button (#44).
|
||||||
|
// The array arrives pre-ordered from the snapshot builder (Task 6: ACTIVE block, then PENDING
|
||||||
|
// block, each by (queuedAtTurn, id)) — the strip renders it as-is, dimming the PENDING rows,
|
||||||
|
// and never fetches or re-sorts. Empty queue → null, no box at all. The shell re-renders it on
|
||||||
|
// every refreshAll (Task 7) — a pure display of the array it is handed.
|
||||||
|
|
||||||
|
export function TaskStrip({ tasks }: { tasks: QueueDto[] }) {
|
||||||
|
if (tasks.length === 0) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
left: '1rem',
|
||||||
|
bottom: '1rem',
|
||||||
|
zIndex: 60, // above the header/footer's 50
|
||||||
|
background: 'var(--surface)',
|
||||||
|
border: '1px solid var(--border)',
|
||||||
|
padding: '0.5rem 0.75rem',
|
||||||
|
maxWidth: '26rem',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span style={{ display: 'block', fontSize: '0.6rem', color: 'var(--text-muted)', letterSpacing: '0.12em', marginBottom: '0.3rem' }}>
|
||||||
|
ACTIVE TASKS
|
||||||
|
</span>
|
||||||
|
{tasks.map((t) => (
|
||||||
|
<div
|
||||||
|
key={t.id}
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
gap: '0.75rem',
|
||||||
|
padding: '0.2rem 0',
|
||||||
|
opacity: t.status === 'PENDING' ? 0.45 : 1, // dim, don't reorder — the array is the order
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span style={{ fontSize: '0.62rem', color: 'var(--text-secondary)', letterSpacing: '0.06em' }}>
|
||||||
|
{t.type} // {t.targetLabel}
|
||||||
|
</span>
|
||||||
|
<span style={{ fontSize: '0.62rem', color: 'var(--text-muted)', letterSpacing: '0.04em', whiteSpace: 'nowrap' }}>
|
||||||
|
{t.leadName}
|
||||||
|
{t.helperNames.length > 0 ? ` +${t.helperNames.join(' +')}` : ''}
|
||||||
|
{' — '}
|
||||||
|
{t.status === 'ACTIVE' ? `${t.remaining} turn(s) left` : 'queued'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import type { CrewDto, QueueDto } from '@/lib/game/save'
|
||||||
|
import { computeDuration, type TaskType } from '@/lib/game/tasks'
|
||||||
|
|
||||||
|
// Shared crew picker for the four action panels — PR A: an action is queued as a lead +
|
||||||
|
// helpers task, not a one-click. Self-contained: the panel passes the /api/crew CrewState
|
||||||
|
// it fetched (roster + queue, Task 6) and onQueue hands back the picked team; the panel
|
||||||
|
// performs its own fetch with the team fields in the body (Task 5a). The live preview is
|
||||||
|
// Task 1's computeDuration (pure, no DB import) with the default powerOf — the same call
|
||||||
|
// 5a's route makes, so it equals the stored duration. The rows mirror Task 3's queueTask
|
||||||
|
// so the UI never offers a 409 (JC-11's fields make the member↔row check exact).
|
||||||
|
export function TeamBuilder({ type, hopCount, roster, tasks, onQueue }: {
|
||||||
|
type: TaskType
|
||||||
|
hopCount?: number
|
||||||
|
roster: CrewDto[]
|
||||||
|
tasks: QueueDto[]
|
||||||
|
onQueue: (leadCrewId: number, helperCrewIds: number[]) => void
|
||||||
|
}) {
|
||||||
|
const [leadId, setLeadId] = useState<number | null>(null)
|
||||||
|
const [helperIds, setHelperIds] = useState<number[]>([])
|
||||||
|
|
||||||
|
// Whole-builder blocks: an ACTIVE jump is in transit (all types); in the jump panel any
|
||||||
|
// queued jump is — the second-jump 409 (JC-12).
|
||||||
|
const inTransit = tasks.find((t) => t.type === 'JUMP' && t.status === 'ACTIVE')
|
||||||
|
const blocked = inTransit ?? (type === 'JUMP' ? tasks.find((t) => t.type === 'JUMP') : null)
|
||||||
|
|
||||||
|
const lead = roster.find((c) => c.id === leadId) ?? null
|
||||||
|
const helpers = roster.filter((c) => helperIds.includes(c.id))
|
||||||
|
const duration = lead ? computeDuration(type, hopCount ?? 0, lead, helpers) : null // CrewDto ⊇ CrewMember
|
||||||
|
|
||||||
|
const leadReason = (c: CrewDto) => {
|
||||||
|
const leads = tasks.find((x) => x.leadCrewId === c.id && x.status === 'PENDING')
|
||||||
|
if (leads) return `${leads.type} ALREADY QUEUED`
|
||||||
|
const helps = tasks.find((x) => x.helperCrewIds.includes(c.id) && x.status === 'PENDING')
|
||||||
|
return helps ? `COMMITTED: ${helps.type}` : null
|
||||||
|
}
|
||||||
|
const helperReason = (c: CrewDto) => {
|
||||||
|
const t = tasks.find((x) => (x.leadCrewId === c.id || x.helperCrewIds.includes(c.id)) && (x.status === 'ACTIVE' || x.status === 'PENDING'))
|
||||||
|
return t ? `BUSY: ${t.type}` : null
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ border: '1px solid var(--border)', background: 'var(--surface)', padding: '0.75rem', display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
|
||||||
|
<span style={{ fontSize: '0.6rem', color: 'var(--text-muted)', letterSpacing: '0.12em' }}>PICK TEAM // {type}</span>
|
||||||
|
{blocked ? (
|
||||||
|
<span style={{ fontSize: '0.62rem', color: 'var(--color-red)', letterSpacing: '0.08em' }}>
|
||||||
|
{inTransit ? `IN TRANSIT // ${inTransit.targetLabel}` : 'A JUMP IS ALREADY QUEUED'}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
roster.map((c) => (
|
||||||
|
<label key={c.id} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="lead"
|
||||||
|
checked={leadId === c.id}
|
||||||
|
disabled={leadReason(c) !== null}
|
||||||
|
onChange={() => {
|
||||||
|
setLeadId(c.id)
|
||||||
|
setHelperIds((h) => h.filter((x) => x !== c.id)) // a lead is never also a helper of the same task
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<input type="checkbox" checked={helperIds.includes(c.id)} disabled={leadId === c.id || helperReason(c) !== null} onChange={() => setHelperIds((h) => (h.includes(c.id) ? h.filter((x) => x !== c.id) : [...h, c.id]))} />
|
||||||
|
<span style={{ fontSize: '0.65rem', color: leadId === c.id ? 'var(--text-secondary)' : 'var(--text-muted)', letterSpacing: '0.08em' }}>
|
||||||
|
{c.name}
|
||||||
|
{leadId === c.id ? ' // LEAD' : ''} {leadReason(c) ?? helperReason(c) ?? ''}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
|
||||||
|
<span style={{ fontSize: '0.62rem', color: 'var(--text-muted)', letterSpacing: '0.08em' }}>
|
||||||
|
{duration !== null ? `WILL TAKE ${duration} TURN(S)` : 'PICK A LEAD'}
|
||||||
|
</span>
|
||||||
|
<Button variant="EXEC" size="SM" className="ml-auto" disabled={!lead || blocked !== null || leadReason(lead) !== null} onClick={() => lead && onQueue(lead.id, helperIds)}>
|
||||||
|
DISPATCH
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
+81
-18
@@ -1,16 +1,18 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { forceCenter, forceCollide, forceLink, forceManyBody, forceSimulation } from 'd3-force'
|
import { forceCenter, forceCollide, forceLink, forceManyBody, forceSimulation } from 'd3-force'
|
||||||
import type { SimulationNodeDatum } from 'd3-force'
|
import type { SimulationNodeDatum } from 'd3-force'
|
||||||
import { select } from 'd3-selection'
|
import { select } from 'd3-selection'
|
||||||
import { zoom, zoomIdentity } from 'd3-zoom'
|
import { zoom, zoomIdentity } from 'd3-zoom'
|
||||||
import type { WorldState } from '@/lib/game/save'
|
import { TeamBuilder } from '@/components/team-builder'
|
||||||
|
import type { CrewState, WorldState } from '@/lib/game/save'
|
||||||
import { reachableWithin } from '@/lib/game/world'
|
import { reachableWithin } from '@/lib/game/world'
|
||||||
|
|
||||||
// WORLD MAP tab — real world state from /api/world on a force-directed chart (d3-force) with
|
// WORLD MAP tab — real world state from /api/world on a force-directed chart (d3-force) with
|
||||||
// pan + zoom (d3-zoom), per #28. Clicking a system within jump range of the current one jumps
|
// pan + zoom (d3-zoom), per #28. Clicking a system within jump range of the current one ARMS
|
||||||
// there (same POST /api/jump flow as before; two hops away once NAVIGATION AI is researched,
|
// it (#44): the crew team builder mounts as a floating card over the chart, and its DISPATCH
|
||||||
|
// POSTs /api/jump with the team in the body (two hops away once NAVIGATION AI is researched,
|
||||||
// #35); the current and unreachable systems are dimmed and not
|
// #35); the current and unreachable systems are dimmed and not
|
||||||
// clickable, and every node is locked while a jump is in flight. Turn-based: fetch on mount,
|
// clickable, and every node is locked while a jump is in flight. Turn-based: fetch on mount,
|
||||||
// refetch via the jump response — no polling. In wide mode (#36) the chart fills the whole tab
|
// refetch via the jump response — no polling. In wide mode (#36) the chart fills the whole tab
|
||||||
@@ -55,6 +57,9 @@ export function WorldMapPanel({ height = 380, narrow = false, navAi = false, onJ
|
|||||||
const [world, setWorld] = useState<WorldState | null>(null)
|
const [world, setWorld] = useState<WorldState | null>(null)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
const [jumpingId, setJumpingId] = useState<number | null>(null)
|
const [jumpingId, setJumpingId] = useState<number | null>(null)
|
||||||
|
// #44 — the team builder: the clicked node is the armed target; its DISPATCH performs the jump.
|
||||||
|
const [crew, setCrew] = useState<CrewState | null>(null)
|
||||||
|
const [armedId, setArmedId] = useState<number | null>(null)
|
||||||
const containerRef = useRef<HTMLDivElement>(null)
|
const containerRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -75,53 +80,85 @@ export function WorldMapPanel({ height = 380, narrow = false, navAi = false, onJ
|
|||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
// JC-14 — the roster + queue the builder mirrors: fetched on mount and after every
|
||||||
|
// successful dispatch (the jump response updates the world state, not the roster).
|
||||||
|
// Keep-old-on-failure, the house .catch(() => {}) pattern.
|
||||||
|
const fetchCrew = useCallback(() => {
|
||||||
|
fetch('/api/crew')
|
||||||
|
.then(async (res) => {
|
||||||
|
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||||
|
return (await res.json()) as CrewState
|
||||||
|
})
|
||||||
|
.then((c) => setCrew(c))
|
||||||
|
.catch(() => {})
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchCrew()
|
||||||
|
}, [fetchCrew])
|
||||||
|
|
||||||
|
// #35 — the jump-reach map: one hop away, or two once NAVIGATION AI is researched. The chart
|
||||||
|
// marks its fields clickable from it, and the team builder previews the armed target's
|
||||||
|
// duration from its hop count (the same logic /api/jump recomputes).
|
||||||
|
const hopMap = useMemo(() => {
|
||||||
|
if (!world) return null
|
||||||
|
const current = world.systems.find((s) => s.current)
|
||||||
|
return current ? reachableWithin(world.edges, current.id, navAi ? 2 : 1) : null
|
||||||
|
}, [world, navAi])
|
||||||
|
|
||||||
// Ref guard so a double-click can't start two jumps before the re-render locks the nodes.
|
// Ref guard so a double-click can't start two jumps before the re-render locks the nodes.
|
||||||
const jumpingRef = useRef(false)
|
const jumpingRef = useRef(false)
|
||||||
|
|
||||||
const jump = useCallback(async (systemId: number) => {
|
// #44 — a node click ARMS the target instead of jumping: the builder over the chart picks the
|
||||||
|
// team, and its DISPATCH performs the fetch (below). Clicking another jumpable node retargets.
|
||||||
|
const arm = useCallback((systemId: number) => {
|
||||||
|
if (jumpingRef.current) return
|
||||||
|
setArmedId(systemId)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const jump = useCallback(async (systemId: number, leadCrewId: number, helperCrewIds: number[]) => {
|
||||||
if (jumpingRef.current) return
|
if (jumpingRef.current) return
|
||||||
jumpingRef.current = true
|
jumpingRef.current = true
|
||||||
setJumpingId(systemId)
|
setJumpingId(systemId)
|
||||||
|
setArmedId(null)
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/jump', {
|
const res = await fetch('/api/jump', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'content-type': 'application/json' },
|
headers: { 'content-type': 'application/json' },
|
||||||
body: JSON.stringify({ systemId }),
|
body: JSON.stringify({ systemId, leadCrewId, helperCrewIds }),
|
||||||
})
|
})
|
||||||
const body = (await res.json()) as WorldState & { error?: string }
|
const body = (await res.json()) as WorldState & { error?: string }
|
||||||
if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`)
|
if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`)
|
||||||
setWorld(body) // fresh state straight from the response — no refetch needed
|
setWorld(body) // fresh state straight from the response — no refetch needed
|
||||||
onJumped?.() // #30 — parent re-fetches /api/system (LOCAL SYSTEM + CARGO HOLD mirror it)
|
onJumped?.() // #30 — parent re-fetches /api/system (LOCAL SYSTEM + CARGO HOLD mirror it)
|
||||||
|
fetchCrew() // JC-14 — the dispatch committed a team; refresh the roster + queue for the builder
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
setError(err instanceof Error ? err.message : String(err))
|
setError(err instanceof Error ? err.message : String(err))
|
||||||
} finally {
|
} finally {
|
||||||
jumpingRef.current = false
|
jumpingRef.current = false
|
||||||
setJumpingId(null)
|
setJumpingId(null)
|
||||||
}
|
}
|
||||||
}, [onJumped])
|
}, [onJumped, fetchCrew])
|
||||||
|
|
||||||
// Rebuild the chart on every world/lock change — the force layout re-settles from the API's
|
// Rebuild the chart on every world/lock change — the force layout re-settles from the API's
|
||||||
// coordinates, so nodes visibly rearrange after each jump (#28).
|
// coordinates, so nodes visibly rearrange after each jump (#28).
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const container = containerRef.current
|
const container = containerRef.current
|
||||||
if (!container || !world) return
|
if (!container || !world || !hopMap) return
|
||||||
|
|
||||||
// Measured pane size (#36): the flex chain gives a definite box in wide mode; `height` is the
|
// Measured pane size (#36): the flex chain gives a definite box in wide mode; `height` is the
|
||||||
// fallback when the container has no resolved size yet (narrow flow, or tab hidden on load).
|
// fallback when the container has no resolved size yet (narrow flow, or tab hidden on load).
|
||||||
const W = container.clientWidth || 800
|
const W = container.clientWidth || 800
|
||||||
const H = container.clientHeight || height
|
const H = container.clientHeight || height
|
||||||
const current = world.systems.find((s) => s.current)!
|
|
||||||
// Clickable chart fields: one hop away, or two hops once NAVIGATION AI is researched (#35).
|
|
||||||
const hops = reachableWithin(world.edges, current.id, navAi ? 2 : 1)
|
|
||||||
|
|
||||||
const nodes: ChartNode[] = world.systems.map((s) => ({
|
const nodes: ChartNode[] = world.systems.map((s) => ({
|
||||||
id: s.id,
|
id: s.id,
|
||||||
name: s.name.toUpperCase(),
|
name: s.name.toUpperCase(),
|
||||||
status: s.current ? 'current' : hops.has(s.id) ? 'jumpable' : 'offline',
|
status: s.current ? 'current' : hopMap.has(s.id) ? 'jumpable' : 'offline',
|
||||||
sublabel: s.current
|
sublabel: s.current
|
||||||
? 'CURRENT'
|
? 'CURRENT'
|
||||||
: hops.has(s.id)
|
: hopMap.has(s.id)
|
||||||
? `${s.discovered ? 'DISCOVERED' : 'UNKNOWN'} // JUMP${(hops.get(s.id) ?? 1) > 1 ? ' ×2' : ''}`
|
? `${s.discovered ? 'DISCOVERED' : 'UNKNOWN'} // JUMP${(hopMap.get(s.id) ?? 1) > 1 ? ' ×2' : ''}`
|
||||||
: s.discovered ? 'DISCOVERED' : 'UNKNOWN',
|
: s.discovered ? 'DISCOVERED' : 'UNKNOWN',
|
||||||
x: (s.x / 100) * W, // seed from the API coordinates so the layout settles near the old chart
|
x: (s.x / 100) * W, // seed from the API coordinates so the layout settles near the old chart
|
||||||
y: (s.y / 100) * H,
|
y: (s.y / 100) * H,
|
||||||
@@ -187,18 +224,19 @@ export function WorldMapPanel({ height = 380, narrow = false, navAi = false, onJ
|
|||||||
|
|
||||||
// Same accessible contract as the old chart: only jumpable nodes are role=button with their
|
// Same accessible contract as the old chart: only jumpable nodes are role=button with their
|
||||||
// name as the accessible label (e2e clicks them by role/name); all locked while a jump is in flight.
|
// name as the accessible label (e2e clicks them by role/name); all locked while a jump is in flight.
|
||||||
|
// A click ARMS the node (#44) — the team builder over the chart performs the jump.
|
||||||
nodeSel.filter((d) => d.status === 'jumpable' && jumpingId === null)
|
nodeSel.filter((d) => d.status === 'jumpable' && jumpingId === null)
|
||||||
.attr('role', 'button')
|
.attr('role', 'button')
|
||||||
.attr('tabindex', 0)
|
.attr('tabindex', 0)
|
||||||
.attr('aria-label', (d) => d.name)
|
.attr('aria-label', (d) => d.name)
|
||||||
.style('cursor', 'pointer')
|
.style('cursor', 'pointer')
|
||||||
.on('click', (event: MouseEvent, d) => {
|
.on('click', (event: MouseEvent, d) => {
|
||||||
if (!panned) void jump(d.id) // a real pan ends with a click too — don't jump on that one
|
if (!panned) arm(d.id) // a real pan ends with a click too — don't arm on that one
|
||||||
})
|
})
|
||||||
.on('keydown', (event: KeyboardEvent, d) => {
|
.on('keydown', (event: KeyboardEvent, d) => {
|
||||||
if (event.key === 'Enter' || event.key === ' ') {
|
if (event.key === 'Enter' || event.key === ' ') {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
void jump(d.id)
|
arm(d.id)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -246,7 +284,7 @@ export function WorldMapPanel({ height = 380, narrow = false, navAi = false, onJ
|
|||||||
simulation.stop()
|
simulation.stop()
|
||||||
svg.remove()
|
svg.remove()
|
||||||
}
|
}
|
||||||
}, [world, jumpingId, jump, height, navAi])
|
}, [world, jumpingId, arm, height, navAi, hopMap])
|
||||||
|
|
||||||
if (error && !world) {
|
if (error && !world) {
|
||||||
return (
|
return (
|
||||||
@@ -269,13 +307,15 @@ export function WorldMapPanel({ height = 380, narrow = false, navAi = false, onJ
|
|||||||
// flex (not height:'100%'): the pane chain is sized by min-height, where percentages don't resolve
|
// flex (not height:'100%'): the pane chain is sized by min-height, where percentages don't resolve
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem', ...(filling ? { flex: 1, minHeight: 0 } : {}) }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem', ...(filling ? { flex: 1, minHeight: 0 } : {}) }}>
|
||||||
{/* Wrapper + title bar; in wide mode the box flexes to fill the whole pane (#36). d3 owns everything inside it. */}
|
{/* Wrapper + title bar; in wide mode the box flexes to fill the whole pane (#36). d3 owns the
|
||||||
|
chart container inside it; the armed target's team builder floats over the chart (#44). */}
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
border: '1px solid var(--border)',
|
border: '1px solid var(--border)',
|
||||||
background: 'var(--surface)',
|
background: 'var(--surface)',
|
||||||
fontFamily: 'var(--font-mono)',
|
fontFamily: 'var(--font-mono)',
|
||||||
overflow: 'hidden',
|
overflow: 'hidden',
|
||||||
|
position: 'relative',
|
||||||
...(filling ? { flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' } : {}),
|
...(filling ? { flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' } : {}),
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -293,6 +333,29 @@ export function WorldMapPanel({ height = 380, narrow = false, navAi = false, onJ
|
|||||||
GALACTIC CHART // JUMP ROUTES — TURN {world.turn}
|
GALACTIC CHART // JUMP ROUTES — TURN {world.turn}
|
||||||
</div>
|
</div>
|
||||||
<div ref={containerRef} style={{ width: '100%', ...(filling ? { flex: 1, minHeight: 0 } : { height: `${height}px` }) }} />
|
<div ref={containerRef} style={{ width: '100%', ...(filling ? { flex: 1, minHeight: 0 } : { height: `${height}px` }) }} />
|
||||||
|
|
||||||
|
{/* #44 — the armed target's crew picker, floating over the chart (JC-13: mounted only
|
||||||
|
while a target is armed); its DISPATCH performs the jump with the picked team. */}
|
||||||
|
{armedId !== null && crew !== null && (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
left: '50%',
|
||||||
|
top: '50%',
|
||||||
|
transform: 'translate(-50%, -50%)',
|
||||||
|
width: 'min(24rem, calc(100% - 1.5rem))',
|
||||||
|
zIndex: 10,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<TeamBuilder
|
||||||
|
type="JUMP"
|
||||||
|
hopCount={hopMap?.get(armedId) ?? 0}
|
||||||
|
roster={crew.crew}
|
||||||
|
tasks={crew.tasks}
|
||||||
|
onQueue={(leadCrewId, helperCrewIds) => void jump(armedId, leadCrewId, helperCrewIds)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,121 @@
|
|||||||
|
# Crew-Driven Actions & Skill Progression — Design Spec
|
||||||
|
|
||||||
|
- Date: 2026-10-01
|
||||||
|
- Status: approved
|
||||||
|
- Tracking: Gitea issues #43–#45 (created after spec approval)
|
||||||
|
- Repo rules: AGENTS.md change process applies to every issue below
|
||||||
|
|
||||||
|
## 1. Background
|
||||||
|
|
||||||
|
SpaceWanderer is a single-player, turn-based space adventure (dungeon-crawler flavor; reference: Out There). As of v0.9.12 the loop is jump → scan planets → collect hauls → spend on ship upgrades & research → take missions for generic rewards. Every action resolves instantly and costs exactly 1 turn (jumps cost hop count, 1–2 with NAV AI tech). Crew members carry a role and two traits but change nothing mechanically — ORCHESTRATOR.md's "manage crew of flawed humans" is unimplemented.
|
||||||
|
|
||||||
|
This iteration makes **crew the central resource**: every action requires an assigned team, takes variable duration based on that team's roles/skills/traits, and time advances only when the player presses NEXT TURN. Doing jobs builds skill levels, so crews specialise over a playthrough.
|
||||||
|
|
||||||
|
## 2. Goals / Non-goals
|
||||||
|
|
||||||
|
Goals:
|
||||||
|
1. Every game action (jump, explore, ship work, research) becomes a queued task with an assigned team (lead + optional helpers).
|
||||||
|
2. Duration is computed from work points ÷ team power, modified by role mismatch and the lead's traits — min 1 turn.
|
||||||
|
3. Manual time: NEXT TURN button (bottom-right) advances exactly 1 turn; empty queue = free skip.
|
||||||
|
4. Skill progression: 4 skills keyed by action type; XP from completed tasks; levels 0–5 with power bands; role-based starting specialisation; titles at L3/L5.
|
||||||
|
5. All 20 traits get mechanical meaning (duration modifiers now; two outcome effects in #43; three combat traits marked STANDBY for the future encounters iteration).
|
||||||
|
|
||||||
|
Non-goals (explicitly out of scope):
|
||||||
|
- Random encounters, combat, damage, death (next roadmap item per ORCHESTRATOR.md §7)
|
||||||
|
- Real-time mode — but the work-point model is time-independent by design to ease that migration later
|
||||||
|
- Crew injury/departure, supplies/hunger systems, task cancellation
|
||||||
|
|
||||||
|
## 3. Core Model: Queued Tasks + Turn Tick
|
||||||
|
|
||||||
|
- New `tasks` table (schema v7): one row per queued/active task. Fields: id, saveId, type (`JUMP|EXPLORE|SHIP_UPGRADE|SHIP_EXPAND|SHIP_BUILD|RESEARCH`), payload (JSON — targetSystemId / planetId / systemType+action / techSlug), leadCrewId, helpers (JSON array of crew ids), duration, remaining, status (`ACTIVE|PENDING|DONE`).
|
||||||
|
- **One active task per crew member** (as lead or helper). A crew member may hold a chain of PENDING tasks (FIFO pre-queueing); when their current task completes on a turn tick, the next pending auto-starts. Helper slots are fixed at queue time; a committed helper is busy for that task's duration and cannot be added elsewhere meanwhile.
|
||||||
|
- **Costs deduct at queue time** (ship work & research consume resources/parts immediately — prevents mid-turn affordability races); effects apply on completion. Jumps/explores have no resource cost.
|
||||||
|
- `save.turn` increments only via `POST /api/turn`. The tick: for every ACTIVE task, remaining−=1; tasks reaching 0 resolve (per-type resolvers reusing existing logic from save.ts / ship / research), grant XP (§6), write events, free the team, auto-start any FIFO successor, then run mission-completion checks for what just resolved.
|
||||||
|
- **In-transit rule:** while any JUMP task is ACTIVE, no new tasks can be queued (409). Pending jumps do not block; already-active/pending non-jump work continues through the jump and resolves against its target regardless of current system location. Only one JUMP may exist at a time (active or pending) — prevents two arrivals on one tick.
|
||||||
|
- **Mission accept becomes instant/free** (paperwork: no crew, no turn cost). Completion checks run when the satisfying task completes (jump arrival → DELIVER; scan → EXPLORE/FIND), same as today's hooks moved into tick resolution.
|
||||||
|
|
||||||
|
## 4. Duration Model: Work Points & Team Power
|
||||||
|
|
||||||
|
`duration = max(1, ceil(work(action) / totalPower) + mismatchPenalty + traitModifierSum)`
|
||||||
|
|
||||||
|
- `work(action)` — work points (balance knobs, §11): EXPLORE=4 · JUMP=hops×3 (single 3 / two-hop 6) · SHIP work=6 · RESEARCH=9. Durations are deliberately much longer than today; teams and skill levels claw back the time.
|
||||||
|
- `totalPower` — sum over lead + helpers of each member's power band in that action type's skill: L0–L2 → 1, L3–L4 → 2, L5 → 3. (Until #45 lands there is no skill table, so every crew member contributes power 1 — teamwork already works; progression layers on top.)
|
||||||
|
- `mismatchPenalty` — +1 turn if the LEAD's role is not a preferred role for the action type (preferred: JUMP → PILOT/NAVIGATOR · EXPLORE → SCIENTIST · SHIP work → ENGINEER/TECHNICIAN · RESEARCH → SCIENTIST). Helpers are never penalised. STEADY UNDER PRESSURE cancels it.
|
||||||
|
- `traitModifierSum` — sum of the LEAD's trait modifiers for this action type (§5 table). Helper traits do not apply.
|
||||||
|
|
||||||
|
Solo durations (power 1, no mismatch/traits): EXPLORE 4 · JUMP single 3 / two-hop 6 · SHIP work 6 · RESEARCH 9. A maxed specialist + helpers converges back to ~1–2 turns (§6 examples).
|
||||||
|
|
||||||
|
## 5. Trait Mechanics — all 20 traits
|
||||||
|
|
||||||
|
Duration modifiers (lead only, additive in §4 formula):
|
||||||
|
|
||||||
|
| Good trait | Effect |
|
||||||
|
|---|---|
|
||||||
|
| STEADY UNDER PRESSURE | Cancels role-mismatch penalty on any action |
|
||||||
|
| RECKLESS COURAGE | JUMP −1 turn |
|
||||||
|
| CALM IN A CRISIS | EXPLORE −1 turn |
|
||||||
|
| FIXES ANYTHING | SHIP work −1 turn |
|
||||||
|
| READS STARS BLIND | JUMP −1 turn |
|
||||||
|
| QUICK HANDS | Any action −1 turn |
|
||||||
|
| IRON WILL | RESEARCH −1 turn |
|
||||||
|
|
||||||
|
| Bad trait | Effect |
|
||||||
|
|---|---|
|
||||||
|
| RIGID — SLOW TO ADAPT | RESEARCH +1 turn |
|
||||||
|
| OVERCAUTIOUS | Any action +1 turn |
|
||||||
|
| SLOWS THE CREW DOWN | Any action +1 turn |
|
||||||
|
| CARELESS WITH FUSES | SHIP work +1 turn |
|
||||||
|
| HOARDS RATIONS | SHIP work +1 turn |
|
||||||
|
| FORGETS TO EAT | EXPLORE +1 turn |
|
||||||
|
| ARGUES WITH EVERYONE | RESEARCH +1 turn |
|
||||||
|
| DOUBTS THE CAPTAIN | JUMP +1 turn |
|
||||||
|
|
||||||
|
Outcome effects (#43): FINDS HIDDEN THINGS → exploration hauls gain +1 item (extra roll on the same seeded per-planet stream) · TALKS TO ANYONE → crew-recruit chance 18% → 30%.
|
||||||
|
Encounter-ready STANDBY (activate when random encounters land; shown as "STANDBY" in UI): SHARP SHOOTER, SHORT FUSE, JINXED IN A DOGFIGHT.
|
||||||
|
|
||||||
|
## 6. Skill Progression & Specialisation
|
||||||
|
|
||||||
|
- **Skills** — one per action type: NAVIGATION (jumps), SCANNING (exploration), ENGINEERING (ship work), RESEARCH. Stored in a new `crew_skills` table (schema v8): saveId, crewId, skill, level, xp — extensible for future COMBAT/MEDICAL skills.
|
||||||
|
- **Roles keep their names** — the existing 8 roles are unchanged; skills are a separate progression axis. A role matters only for: starting levels and the lead mismatch penalty.
|
||||||
|
- **Starting specialisation (role → L2 in its skill(s)):** PILOT/NAVIGATOR → NAVIGATION · SCIENTIST → SCANNING + RESEARCH · ENGINEER/TECHNICIAN → ENGINEERING · COMMANDER/MEDIC/GUNNER → all skills L0 (generalists; MEDIC/GUNNER become relevant with encounters).
|
||||||
|
- **Buildup by doing the job:** on task completion, every assigned crew member (lead and helpers) gains +1 XP in that action type's skill. Level thresholds (cumulative completions): L1=5 · L2=10 · L3=15 · L4=20 · L5=25 (cap).
|
||||||
|
- **Power bands:** L0–L2 → 1 · L3–L4 → 2 · L5 → 3 (§4).
|
||||||
|
- **Titles** (display only, role name preserved): highest skill level ≥5 → "MASTER <ROLE>", ≥3 → "SENIOR <ROLE>". Level-ups write an event ("BEN OKONKWO is now a SENIOR PILOT — NAVIGATION L3").
|
||||||
|
|
||||||
|
Duration examples (work values §4): EXPLORE solo rookie 4 turns → solo master 2 → master+rookie helper 1 · JUMP two-hop solo rookie 6 → solo master 2 → two masters 1 · SHIP work solo rookie 6 → solo master 2 · RESEARCH solo rookie 9 → solo master 3 (stays the long pole by design).
|
||||||
|
|
||||||
|
## 7. API Changes
|
||||||
|
|
||||||
|
- All action endpoints become queueing operations and gain crew params: `POST /api/jump {targetSystemId, leadCrewId, helperCrewIds[]}` · `POST /api/explore {planetId, ...}` · `POST /api/ship/{upgrade|expand|build} {...}` · `POST /api/research {techSlug, ...}`. Validation at queue time: unknown crew → 404; busy/committed crew → 409; in-transit or second jump → 409; unreachable target / unaffordable cost / build gate → existing error codes. No turn increment on queue.
|
||||||
|
- New `POST /api/turn` — advances exactly one turn (§3 tick), returns full snapshot.
|
||||||
|
- Snapshots (world/system/crew responses) gain an active+pending `tasks` array: {id, type, targetLabel, leadName, helperNames[], remaining} so the UI can render the task strip and disable busy crew. The admin CRUD panel picks up new tables automatically.
|
||||||
|
- OpenAPI spec in lib/openapi.ts updated accordingly; DDL in lib/db/client.ts kept in sync with lib/db/schema.ts (repo rule).
|
||||||
|
|
||||||
|
## 8. UI
|
||||||
|
|
||||||
|
- **NEXT TURN button fixed bottom-right** with current turn counter ("TURN 12") — the game's heartbeat; pressing it with an empty queue is a free skip.
|
||||||
|
- **Crew picker:** action buttons open an inline team builder — pick lead (radio), toggle helpers (checkboxes); live-computed duration updates as the team changes ("Lead AVA VANCE · PILOT L2 + 1 helper → 3 turns"); busy/committed members disabled with reason.
|
||||||
|
- **Active-tasks strip** (bottom-left): each task's type, target, team, remaining turns; pending FIFO tasks shown dimmed.
|
||||||
|
- **CREW tab:** per member — role (+title), traits, and the 4 skill levels; STANDBY traits labelled as encounter-ready.
|
||||||
|
- **Event log:** task-completion and level-up events.
|
||||||
|
|
||||||
|
## 9. Determinism & Testing
|
||||||
|
|
||||||
|
- Duration is a pure function `(actionType, hopCount, lead, helpers) → number` — unit-tested across work values × power bands × mismatch × trait matrix.
|
||||||
|
- XP/level-ups are deterministic (no rng). Trait outcome effects (#43) draw from the existing seeded per-planet streams (same save+planet → same haul), keeping everything reproducible.
|
||||||
|
- Unit tests (colocated *.test.ts): duration matrix; queue validation rules (busy 409, in-transit 409, second jump 409); tick resolution (completion effects, XP grant, level-up event, FIFO auto-start, mission checks); cost deduction at queue time.
|
||||||
|
- E2E (CI-only per AGENTS.md): assign team → NEXT TURN ×N → effect lands; parallel tasks complete independently; pre-queued FIFO starts after predecessor completes; in-transit queuing blocked; empty-queue skip works.
|
||||||
|
|
||||||
|
## 10. Delivery Plan — Gitea issues as TODO list
|
||||||
|
|
||||||
|
One issue = one feature branch/PR/version bump, per AGENTS.md loop (branch off master → version bump + CHANGELOG entry → local verify `tsc --noEmit` / `vitest run` / `playwright test --list` → push, CI auto-merge on green → tag → manual deploy → close issue with comment).
|
||||||
|
|
||||||
|
| Issue | Version | Scope |
|
||||||
|
|---|---|---|
|
||||||
|
| #44 Crew-driven actions + NEXT TURN engine | v0.10.0 | tasks table (schema v7; backfill creates empty table for existing saves), POST /api/turn tick, all action endpoints → queueing with lead+helpers, duration model (§4; power 1 for everyone until #45), trait duration modifiers (§5), UI: NEXT TURN button bottom-right + turn counter, crew picker with live duration, task strip. OpenAPI update. Rework existing unit/e2e assertions from instant-resolution to the queue+tick model |
|
||||||
|
| #45 Skill progression & specialisation | v0.11.0 | crew_skills table (schema v8; idempotent backfill seeds rows per role mapping for existing saves), XP on completion for all assigned crew, level-up events, power bands active (§6), UI: skill display in CREW tab + titles, picker shows per-member contribution |
|
||||||
|
| #43 Trait outcome effects | v0.12.0 | FINDS HIDDEN THINGS → hauls +1 item; TALKS TO ANYONE → recruit chance 30% |
|
||||||
|
|
||||||
|
## 11. Balance Knobs (single tuning surface)
|
||||||
|
|
||||||
|
All constants live in one new module `lib/game/crew-costs.ts` (alongside ship-costs.ts): WORK_POINTS per action type, POWER_BANDS, XP_THRESHOLDS, STARTING_LEVELS per role, recruit chance values. Tuning a number = editing one file; the duration formula and resolvers read from it.
|
||||||
+64
-4
@@ -5,11 +5,56 @@ import { expect, type Page } from '@playwright/test';
|
|||||||
interface WorldSystemDto { id: number; name: string; x: number; y: number; discovered: boolean; current: boolean }
|
interface WorldSystemDto { id: number; name: string; x: number; y: number; discovered: boolean; current: boolean }
|
||||||
interface WorldState { systems: WorldSystemDto[]; edges: [number, number][]; turn: number }
|
interface WorldState { systems: WorldSystemDto[]; edges: [number, number][]; turn: number }
|
||||||
|
|
||||||
|
// Minimal crew member — GET /api/crew is the {crew, tasks} object (Task 6 / JC-7); the full
|
||||||
|
// member shape lives in e2e/state.spec.ts.
|
||||||
|
interface CrewDto { id: number; role: string }
|
||||||
|
|
||||||
|
// The real TaskType strings (lib/game/tasks.ts) keyed by the action POST path — there is no
|
||||||
|
// bare SHIP type, ship actions split into UPGRADE / EXPAND / BUILD.
|
||||||
|
const TASK_TYPE: Record<string, string> = {
|
||||||
|
'/api/jump': 'JUMP',
|
||||||
|
'/api/explore': 'EXPLORE',
|
||||||
|
'/api/research': 'RESEARCH',
|
||||||
|
'/api/ship/upgrade': 'SHIP_UPGRADE',
|
||||||
|
'/api/ship/expand': 'SHIP_EXPAND',
|
||||||
|
'/api/ship/build': 'SHIP_BUILD',
|
||||||
|
};
|
||||||
|
|
||||||
|
// The GET endpoint that serves each action's final snapshot (the action paths are POST-only).
|
||||||
|
const FINAL_SNAPSHOT: Record<string, string> = {
|
||||||
|
'/api/jump': '/api/world',
|
||||||
|
'/api/explore': '/api/system',
|
||||||
|
'/api/research': '/api/tech',
|
||||||
|
'/api/ship/upgrade': '/api/ship',
|
||||||
|
'/api/ship/expand': '/api/ship',
|
||||||
|
'/api/ship/build': '/api/ship',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Queue an action POST with a default one-person crew, then tick until that task resolves.
|
||||||
|
// The POST only queues (200, no turn bump, effect not yet visible); the effect appears once the
|
||||||
|
// task hits 0 on a tick — a task that starts ACTIVE with remaining N resolves on the Nth tick
|
||||||
|
// (lib/game/tasks.ts tickTurn) — so N (the full duration) is read from the queue response's
|
||||||
|
// tasks array and POST /api/turn is sent exactly N times. Returns the final snapshot for the
|
||||||
|
// path. A 409 on the queue POST is a busy / in-transit rejection (Task 3), not a tick-count bug.
|
||||||
|
export async function resolveAction(page: Page, path: string, data: Record<string, unknown>): Promise<unknown> {
|
||||||
|
const roster = (await (await page.request.get('/api/crew')).json()) as { crew?: CrewDto[] } | CrewDto[];
|
||||||
|
const members: CrewDto[] = Array.isArray(roster) ? roster : (roster.crew ?? []); // {crew, tasks} object (JC-7); the array guard keeps the helper shape-tolerant
|
||||||
|
expect(members.length).toBeGreaterThan(0); // starting crew is always seeded
|
||||||
|
const res = await page.request.post(path, { data: { ...data, leadCrewId: members[0].id, helperCrewIds: [] } });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const snap = (await res.json()) as { tasks?: { type: string; remaining: number }[] };
|
||||||
|
const n = snap.tasks?.find((t) => t.type === TASK_TYPE[path])?.remaining ?? 1;
|
||||||
|
for (let i = 0; i < n; i++) expect((await page.request.post('/api/turn')).status()).toBe(200);
|
||||||
|
return (await page.request.get(FINAL_SNAPSHOT[path])).json();
|
||||||
|
}
|
||||||
|
|
||||||
// Jump to an adjacent system, preferring one that is still undiscovered. Every jump into an
|
// Jump to an adjacent system, preferring one that is still undiscovered. Every jump into an
|
||||||
// undiscovered system generates 4 fresh neighbours (lib/game/world.ts), so fresh territory is
|
// undiscovered system generates 4 fresh neighbours (lib/game/world.ts), so fresh territory is
|
||||||
// always available — picking the FIRST edge instead ping-pongs between exhausted systems, because
|
// always available — picking the FIRST edge instead ping-pongs between exhausted systems, because
|
||||||
// edges come back in insertion order and the oldest route out of a system is usually the one that
|
// edges come back in insertion order and the oldest route out of a system is usually the one that
|
||||||
// led here. Falls back to any non-current adjacent system if none is undiscovered.
|
// led here. Falls back to any non-current adjacent system if none is undiscovered. The jump is
|
||||||
|
// queued with a default one-person crew and ticked to completion (resolveAction) before this
|
||||||
|
// returns, so the caller is already standing in the target system, not merely en route to it.
|
||||||
export async function jumpToFreshSystem(page: Page): Promise<WorldState> {
|
export async function jumpToFreshSystem(page: Page): Promise<WorldState> {
|
||||||
const world = (await (await page.request.get('/api/world')).json()) as WorldState;
|
const world = (await (await page.request.get('/api/world')).json()) as WorldState;
|
||||||
const currentId = world.systems.find((s) => s.current)!.id;
|
const currentId = world.systems.find((s) => s.current)!.id;
|
||||||
@@ -23,7 +68,22 @@ export async function jumpToFreshSystem(page: Page): Promise<WorldState> {
|
|||||||
const target = candidates.find((s) => !s.discovered) ?? candidates[0];
|
const target = candidates.find((s) => !s.discovered) ?? candidates[0];
|
||||||
expect(target).toBeDefined(); // every system has at least one route out (ring generation)
|
expect(target).toBeDefined(); // every system has at least one route out (ring generation)
|
||||||
|
|
||||||
const res = await page.request.post('/api/jump', { data: { systemId: target.id } });
|
const after = (await resolveAction(page, '/api/jump', { systemId: target.id })) as WorldState;
|
||||||
expect(res.status()).toBe(200);
|
expect(after.systems.find((s) => s.current)?.id).toBe(target.id); // landed, not just queued
|
||||||
return (await res.json()) as WorldState;
|
return after;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tick the save's task queue until it is empty (free skips are legal 200s; every tick decrements
|
||||||
|
// every ACTIVE row and PENDING rows auto-start, so a non-empty queue always shrinks — the bound
|
||||||
|
// only fails a pathological state). Every spec that queues actions starts from this on retry:
|
||||||
|
// the CI DB persists across attempts, and a failed one may have left a row behind — an in-transit
|
||||||
|
// JUMP would 409 every new queue (lib/game/tasks.ts's in-transit rule).
|
||||||
|
export async function drainQueue(page: Page): Promise<void> {
|
||||||
|
for (let ticks = 0; ; ticks++) {
|
||||||
|
const body = (await (await page.request.get('/api/crew')).json()) as { crew?: CrewDto[]; tasks?: { id: number }[] } | CrewDto[];
|
||||||
|
const tasks = Array.isArray(body) ? [] : (body.tasks ?? []);
|
||||||
|
if (tasks.length === 0) return;
|
||||||
|
expect(ticks).toBeLessThan(60);
|
||||||
|
expect((await page.request.post('/api/turn')).status()).toBe(200);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+506
-52
@@ -1,12 +1,15 @@
|
|||||||
import { expect, test } from '@playwright/test';
|
import { expect, test, type Page } from '@playwright/test';
|
||||||
import { jumpToFreshSystem } from './helpers';
|
import { drainQueue, jumpToFreshSystem, resolveAction } from './helpers';
|
||||||
|
|
||||||
// Mirrors the /api/world + /api/system response shapes (lib/game/save.ts) — kept local so the spec stays self-contained.
|
// Mirrors the /api/world + /api/system response shapes (lib/game/save.ts) — kept local so the spec stays self-contained.
|
||||||
|
// Since Task 6 both snapshots also carry the save's task queue (ACTIVE block first, then PENDING).
|
||||||
interface WorldSystemDto { id: number; name: string; x: number; y: number; discovered: boolean; current: boolean }
|
interface WorldSystemDto { id: number; name: string; x: number; y: number; discovered: boolean; current: boolean }
|
||||||
interface WorldState { systems: WorldSystemDto[]; edges: [number, number][]; turn: number }
|
// The subset of QueueDto the spec reads: the task type and its live duration (`remaining`).
|
||||||
|
interface QueueTaskDto { type: string; remaining: number }
|
||||||
|
interface WorldState { systems: WorldSystemDto[]; edges: [number, number][]; turn: number; tasks: QueueTaskDto[] }
|
||||||
interface PlanetDto { id: number; name: string; type: string; hazard: boolean; explored: boolean; parent: number | null }
|
interface PlanetDto { id: number; name: string; type: string; hazard: boolean; explored: boolean; parent: number | null }
|
||||||
interface InventoryItemDto { kind: string; name: string; qty: number }
|
interface InventoryItemDto { kind: string; name: string; qty: number }
|
||||||
interface SystemState { systemId: number; systemName: string; planets: PlanetDto[]; inventory: InventoryItemDto[]; turn: number }
|
interface SystemState { systemId: number; systemName: string; planets: PlanetDto[]; inventory: InventoryItemDto[]; turn: number; tasks: QueueTaskDto[] }
|
||||||
interface FoundItem { kind: string; name: string; qty: number }
|
interface FoundItem { kind: string; name: string; qty: number }
|
||||||
interface ExploreResult extends SystemState { outcome: FoundItem[]; crewFound: unknown }
|
interface ExploreResult extends SystemState { outcome: FoundItem[]; crewFound: unknown }
|
||||||
interface CrewDto { id: number; name: string; role: string; traitGood: string; traitBad: string; origin: string }
|
interface CrewDto { id: number; name: string; role: string; traitGood: string; traitBad: string; origin: string }
|
||||||
@@ -47,6 +50,40 @@ const shortestJumpPath = (fromId: number, toId: number, edges: [number, number][
|
|||||||
return path;
|
return path;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- PR A's UI flow (Task 8's team builder + Task 7's NEXT TURN button) -----------------
|
||||||
|
|
||||||
|
// The team-builder half of every action panel: pick the default one-person crew in the mounted
|
||||||
|
// builder — the first lead radio, the same default member (the roster is in join order) that
|
||||||
|
// resolveAction queues with, no helpers — and click DISPATCH. Returns the queue POST's response:
|
||||||
|
// 200, no turn bump, the effect not yet applied. Its `tasks` array (where the snapshot carries
|
||||||
|
// one) holds the new task's `remaining` — the team's live duration N (Task 6).
|
||||||
|
async function dispatchDefaultCrew(page: Page, path: string) {
|
||||||
|
await page.getByRole('tabpanel').locator('input[type="radio"][name="lead"]').first().check();
|
||||||
|
const [res] = await Promise.all([
|
||||||
|
page.waitForResponse((r) => r.request().method() === 'POST' && r.url().endsWith(path)),
|
||||||
|
page.getByRole('button', { name: 'DISPATCH' }).click(),
|
||||||
|
]);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One NEXT TURN click (Task 7) = one POST /api/turn. The button drops a click while a tick is
|
||||||
|
// in flight, so each click waits for the button's own TURN span (the shell's ship snapshot —
|
||||||
|
// refreshed on every tick) to show the next turn before the following click.
|
||||||
|
async function tickTo(page: Page, toTurn: number) {
|
||||||
|
await page.getByRole('button', { name: 'NEXT TURN' }).click();
|
||||||
|
await expect(page.getByText(`TURN ${toTurn}`, { exact: true })).toBeVisible();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The N for a ship or research action, read from the crew snapshot: the queueing routes for
|
||||||
|
// /api/ship/* and /api/research return a bare ShipState / TechDto[] with no `tasks` field of
|
||||||
|
// their own (unlike the world/system snapshots), but the queue itself is the same one GET
|
||||||
|
// /api/crew exposes (JC-7). Every test ticks its actions to completion, so at most one task of
|
||||||
|
// a given type is ever in the queue when this reads it.
|
||||||
|
async function crewTasks(page: Page): Promise<QueueTaskDto[]> {
|
||||||
|
const { tasks } = (await (await page.request.get('/api/crew')).json()) as { crew: CrewDto[]; tasks: QueueTaskDto[] };
|
||||||
|
return tasks;
|
||||||
|
}
|
||||||
|
|
||||||
test('landing page loads with the SpaceWanderer title', async ({ page }) => {
|
test('landing page loads with the SpaceWanderer title', async ({ page }) => {
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
await expect(page.getByRole('heading', { name: 'SpaceWanderer' })).toBeVisible();
|
await expect(page.getByRole('heading', { name: 'SpaceWanderer' })).toBeVisible();
|
||||||
@@ -135,6 +172,7 @@ test('world map shows the generated starting system and its neighbours', async (
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('jumping to an adjacent system updates the world state and turn counter', async ({ page }) => {
|
test('jumping to an adjacent system updates the world state and turn counter', async ({ page }) => {
|
||||||
|
await drainQueue(page); // retry-safety: a failed earlier attempt may have left a row queued (an in-transit JUMP would 409 every new queue)
|
||||||
const before = (await (await page.request.get('/api/world')).json()) as WorldState;
|
const before = (await (await page.request.get('/api/world')).json()) as WorldState;
|
||||||
const currentId = before.systems.find((s) => s.current)!.id;
|
const currentId = before.systems.find((s) => s.current)!.id;
|
||||||
const edge = before.edges.find(([a, b]) => a === currentId || b === currentId)!;
|
const edge = before.edges.find(([a, b]) => a === currentId || b === currentId)!;
|
||||||
@@ -142,15 +180,27 @@ test('jumping to an adjacent system updates the world state and turn counter', a
|
|||||||
const targetName = before.systems.find((s) => s.id === targetId)!.name;
|
const targetName = before.systems.find((s) => s.id === targetId)!.name;
|
||||||
|
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
// Click the target's chart field — clickable nodes are role=button with their name as accessible label.
|
// Click the target's chart field — it ARMS the node: the crew team builder floats over the chart.
|
||||||
await page.getByRole('tabpanel').getByRole('button', { name: targetName.toUpperCase(), exact: true }).click();
|
await page.getByRole('tabpanel').getByRole('button', { name: targetName.toUpperCase(), exact: true }).click();
|
||||||
|
// Dispatch with the default one-person crew — the POST only QUEUES the JUMP: 200, no turn bump,
|
||||||
|
// and the ship has not moved yet (the origin is still `current` in the queue response).
|
||||||
|
const res = await dispatchDefaultCrew(page, '/api/jump');
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const queued = (await res.json()) as WorldState;
|
||||||
|
expect(queued.turn).toBe(before.turn);
|
||||||
|
expect(queued.systems.find((s) => s.current)?.id).toBe(currentId); // no instant landing
|
||||||
|
const n = queued.tasks.find((t) => t.type === 'JUMP')!.remaining; // N = the team's live duration (Task 6/8)
|
||||||
|
|
||||||
|
// The tick, not the queue, advances the counter: N NEXT TURN clicks, one turn each.
|
||||||
|
for (let k = 1; k <= n; k++) await tickTo(page, before.turn + k);
|
||||||
|
|
||||||
const after = (await (await page.request.get('/api/world')).json()) as WorldState;
|
const after = (await (await page.request.get('/api/world')).json()) as WorldState;
|
||||||
expect(after.turn).toBe(before.turn + 1);
|
expect(after.turn).toBe(before.turn + n);
|
||||||
expect(after.systems.find((s) => s.current)?.id).toBe(targetId);
|
expect(after.systems.find((s) => s.current)?.id).toBe(targetId);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('local system shows the new current system after a jump, without a page reload (#30)', async ({ page }) => {
|
test('local system shows the new current system after a jump, without a page reload (#30)', async ({ page }) => {
|
||||||
|
await drainQueue(page); // retry-safety: a failed earlier attempt may have left a row queued (an in-transit JUMP would 409 every new queue)
|
||||||
const before = (await (await page.request.get('/api/world')).json()) as WorldState;
|
const before = (await (await page.request.get('/api/world')).json()) as WorldState;
|
||||||
const currentId = before.systems.find((s) => s.current)!.id;
|
const currentId = before.systems.find((s) => s.current)!.id;
|
||||||
const edge = before.edges.find(([a, b]) => a === currentId || b === currentId)!;
|
const edge = before.edges.find(([a, b]) => a === currentId || b === currentId)!;
|
||||||
@@ -158,18 +208,28 @@ test('local system shows the new current system after a jump, without a page rel
|
|||||||
const targetName = before.systems.find((s) => s.id === targetId)!.name;
|
const targetName = before.systems.find((s) => s.id === targetId)!.name;
|
||||||
|
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
// Jump through the UI: click the target's chart field on WORLD MAP (the default tab).
|
// Jump through the UI: click the target's chart field on WORLD MAP (the default tab) — it arms
|
||||||
|
// the node and floats the crew team builder over the chart.
|
||||||
await page.getByRole('tabpanel').getByRole('button', { name: targetName.toUpperCase(), exact: true }).click();
|
await page.getByRole('tabpanel').getByRole('button', { name: targetName.toUpperCase(), exact: true }).click();
|
||||||
|
const res = await dispatchDefaultCrew(page, '/api/jump');
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
// The queue response is applied to the chart — but the turn is still the origin's: no landing,
|
||||||
|
// no counter bump until the ticks.
|
||||||
|
const queued = (await res.json()) as WorldState;
|
||||||
|
expect(queued.turn).toBe(before.turn);
|
||||||
|
expect(queued.systems.find((s) => s.current)?.id).toBe(currentId);
|
||||||
|
const n = queued.tasks.find((t) => t.type === 'JUMP')!.remaining;
|
||||||
|
|
||||||
// Wait until the jump response is applied to the chart — server state is committed by then, so
|
// Wait until the ticks are done: the tick, not the queue, advances the counter (the button's
|
||||||
// the /api/world read below can't race the in-flight POST.
|
// TURN span is the shell's live counter; the last click lands the jump and shows TURN before+N).
|
||||||
await expect(page.getByText(`GALACTIC CHART // JUMP ROUTES — TURN ${before.turn + 1}`)).toBeVisible();
|
for (let k = 1; k <= n; k++) await tickTo(page, before.turn + k);
|
||||||
|
|
||||||
const after = (await (await page.request.get('/api/world')).json()) as WorldState;
|
const after = (await (await page.request.get('/api/world')).json()) as WorldState;
|
||||||
const newCurrent = after.systems.find((s) => s.current)!;
|
const newCurrent = after.systems.find((s) => s.current)!;
|
||||||
expect(newCurrent.id).toBe(targetId); // the jump landed where we aimed
|
expect(newCurrent.id).toBe(targetId); // the jump landed where we aimed, on the Nth tick
|
||||||
|
|
||||||
// Switch to LOCAL SYSTEM — it must show the NEW current system without a page reload (#30).
|
// Switch to LOCAL SYSTEM — it must show the NEW current system without a page reload (#30):
|
||||||
|
// the shell re-fetches /api/system on every tick, so its header carries the final turn.
|
||||||
await page.getByRole('tab', { name: 'LOCAL SYSTEM' }).click();
|
await page.getByRole('tab', { name: 'LOCAL SYSTEM' }).click();
|
||||||
await expect(page.getByText(`EXPLORABLE WORLDS // ${newCurrent.name.toUpperCase()} — TURN ${after.turn}`)).toBeVisible();
|
await expect(page.getByText(`EXPLORABLE WORLDS // ${newCurrent.name.toUpperCase()} — TURN ${after.turn}`)).toBeVisible();
|
||||||
});
|
});
|
||||||
@@ -189,23 +249,41 @@ test('local system shows the current system bodies with staggered moons and expl
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('exploring a body flips its row state, bumps the turn and shows the scan result', async ({ page }) => {
|
test('exploring a body flips its row state, bumps the turn and shows the scan result', async ({ page }) => {
|
||||||
|
await drainQueue(page); // retry-safety: a failed earlier attempt may have left a row queued (an in-transit JUMP would 409 every new queue)
|
||||||
const before = (await (await page.request.get('/api/system')).json()) as SystemState;
|
const before = (await (await page.request.get('/api/system')).json()) as SystemState;
|
||||||
const target = before.planets.find((p) => !p.explored)!;
|
const target = before.planets.find((p) => !p.explored)!;
|
||||||
|
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
await page.getByRole('tab', { name: 'LOCAL SYSTEM' }).click();
|
await page.getByRole('tab', { name: 'LOCAL SYSTEM' }).click();
|
||||||
|
// The row's button ARMS the planet (it flips to PICK TEAM); the crew team builder mounts above the list.
|
||||||
await page.getByRole('button', { name: `${target.name.toUpperCase()} // EXPLORE` }).click();
|
await page.getByRole('button', { name: `${target.name.toUpperCase()} // EXPLORE` }).click();
|
||||||
|
// Dispatch with the default one-person crew — the POST only QUEUES the scan: 200, no turn bump,
|
||||||
|
// the body still unexplored in the response and its `outcome` empty until the scan resolves (JC-2).
|
||||||
|
const res = await dispatchDefaultCrew(page, '/api/explore');
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const queued = (await res.json()) as ExploreResult;
|
||||||
|
expect(queued.turn).toBe(before.turn);
|
||||||
|
expect(queued.planets.find((p) => p.id === target.id)?.explored).toBe(false);
|
||||||
|
expect(queued.outcome).toEqual([]);
|
||||||
|
expect(queued.crewFound).toBeNull();
|
||||||
|
const n = queued.tasks.find((t) => t.type === 'EXPLORE')!.remaining;
|
||||||
|
|
||||||
|
// The ticks: the scan resolves (explored flips, the haul lands) on the Nth one.
|
||||||
|
for (let k = 1; k <= n; k++) await tickTo(page, before.turn + k);
|
||||||
|
|
||||||
const after = (await (await page.request.get('/api/system')).json()) as SystemState;
|
const after = (await (await page.request.get('/api/system')).json()) as SystemState;
|
||||||
expect(after.turn).toBe(before.turn + 1);
|
expect(after.turn).toBe(before.turn + n);
|
||||||
expect(after.planets.find((p) => p.id === target.id)?.explored).toBe(true);
|
expect(after.planets.find((p) => p.id === target.id)?.explored).toBe(true);
|
||||||
|
|
||||||
// UI reflects it: the row badge flipped to SCANNED and its EXPLORE button is gone.
|
// UI reflects it after the ticks: the row badge flipped to SCANNED and its EXPLORE button is gone.
|
||||||
|
// (The SCAN RESULT block already showed the queue response's empty outcome — NOTHING FOUND — as
|
||||||
|
// soon as the scan was dispatched; the haul itself only ever lands on the tick, into the hold.)
|
||||||
await expect(page.getByRole('button', { name: `${target.name.toUpperCase()} // EXPLORE` })).toHaveCount(0);
|
await expect(page.getByRole('button', { name: `${target.name.toUpperCase()} // EXPLORE` })).toHaveCount(0);
|
||||||
await expect(page.getByText(/SCAN RESULT \/\/ /)).toBeVisible();
|
await expect(page.getByText(/SCAN RESULT \/\/ /)).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('exploration yields finds that accumulate in the inventory', async ({ page }) => {
|
test('exploration yields finds that accumulate in the inventory', async ({ page }) => {
|
||||||
|
await drainQueue(page); // retry-safety: a failed earlier attempt may have left a row queued (an in-transit JUMP would 409 every new queue)
|
||||||
// Scan bodies until one yields something (most scans do; jumping keeps it going if a whole
|
// Scan bodies until one yields something (most scans do; jumping keeps it going if a whole
|
||||||
// system is exhausted). P(no find across this many scans) ≈ 0.21^30 — negligible.
|
// system is exhausted). P(no find across this many scans) ≈ 0.21^30 — negligible.
|
||||||
const found = new Map<string, number>(); // kind|name -> qty
|
const found = new Map<string, number>(); // kind|name -> qty
|
||||||
@@ -215,18 +293,22 @@ test('exploration yields finds that accumulate in the inventory', async ({ page
|
|||||||
const sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
const sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
||||||
const unexplored = sys.planets.filter((p) => !p.explored);
|
const unexplored = sys.planets.filter((p) => !p.explored);
|
||||||
if (unexplored.length > 0) {
|
if (unexplored.length > 0) {
|
||||||
const res = await page.request.post('/api/explore', { data: { planetId: unexplored[0].id } });
|
// Queue + tick the scan (resolveAction). The queue response's `outcome` is empty until the
|
||||||
expect(res.status()).toBe(200);
|
// tick (JC-2), so the haul is read from the post-tick /api/system snapshot it returns:
|
||||||
for (const item of ((await res.json()) as ExploreResult).outcome) {
|
// the inventory delta of this scan (the queue is clean at the start of every iteration).
|
||||||
found.set(`${item.kind}|${item.name}`, item.qty);
|
const after = (await resolveAction(page, '/api/explore', { planetId: unexplored[0].id })) as SystemState;
|
||||||
|
const before = new Map(sys.inventory.map((i) => [`${i.kind}|${i.name}`, i.qty]));
|
||||||
|
for (const item of after.inventory) {
|
||||||
|
const qty = item.qty - (before.get(`${item.kind}|${item.name}`) ?? 0);
|
||||||
|
if (qty > 0) found.set(`${item.kind}|${item.name}`, qty);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Current system fully scanned — jump somewhere and keep scanning.
|
// Current system fully scanned — jump somewhere (queued, then ticked) and keep scanning.
|
||||||
const world = (await (await page.request.get('/api/world')).json()) as WorldState;
|
const world = (await (await page.request.get('/api/world')).json()) as WorldState;
|
||||||
const currentId = world.systems.find((s) => s.current)!.id;
|
const currentId = world.systems.find((s) => s.current)!.id;
|
||||||
const edge = world.edges.find(([a, b]) => a === currentId || b === currentId)!;
|
const edge = world.edges.find(([a, b]) => a === currentId || b === currentId)!;
|
||||||
const targetId = edge[0] === currentId ? edge[1] : edge[0];
|
const targetId = edge[0] === currentId ? edge[1] : edge[0];
|
||||||
expect((await page.request.post('/api/jump', { data: { systemId: targetId } })).status()).toBe(200);
|
await resolveAction(page, '/api/jump', { systemId: targetId });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
expect(found.size).toBeGreaterThan(0);
|
expect(found.size).toBeGreaterThan(0);
|
||||||
@@ -240,13 +322,14 @@ test('exploration yields finds that accumulate in the inventory', async ({ page
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('CREW tab renders real roster cards, each showing both traits and an origin', async ({ page }) => {
|
test('CREW tab renders real roster cards, each showing both traits and an origin', async ({ page }) => {
|
||||||
const roster = (await (await page.request.get('/api/crew')).json()) as CrewDto[];
|
// GET /api/crew is the {crew, tasks} object since Task 6 (JC-18) — the roster is its crew field.
|
||||||
expect(roster.length).toBeGreaterThanOrEqual(2); // starting crew is always seeded
|
const { crew } = (await (await page.request.get('/api/crew')).json()) as { crew: CrewDto[]; tasks: QueueTaskDto[] };
|
||||||
|
expect(crew.length).toBeGreaterThanOrEqual(2); // starting crew is always seeded
|
||||||
|
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
await page.getByRole('tab', { name: 'CREW' }).click();
|
await page.getByRole('tab', { name: 'CREW' }).click();
|
||||||
|
|
||||||
for (const member of roster) {
|
for (const member of crew) {
|
||||||
const heading = page.getByRole('heading', { name: member.name });
|
const heading = page.getByRole('heading', { name: member.name });
|
||||||
await expect(heading).toBeVisible();
|
await expect(heading).toBeVisible();
|
||||||
// The card is the third div ancestor of the title (flex row → CardHeader → Card).
|
// The card is the third div ancestor of the title (flex row → CardHeader → Card).
|
||||||
@@ -259,8 +342,11 @@ test('CREW tab renders real roster cards, each showing both traits and an origin
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('SHIP SYSTEMS tab performs an affordable action and reflects it in the card and left column', async ({ page }) => {
|
test('SHIP SYSTEMS tab performs an affordable action and reflects it in the card and left column', async ({ page }) => {
|
||||||
|
await drainQueue(page); // retry-safety: a failed earlier attempt may have left a row queued (an in-transit JUMP would 409 every new queue)
|
||||||
// Scan bodies until something is affordable: an upgrade costs `level` resources (at least one),
|
// Scan bodies until something is affordable: an upgrade costs `level` resources (at least one),
|
||||||
// a build costs three parts. Jumping keeps it going if a whole system is exhausted.
|
// a build costs three parts. Every scan/jump is queued with a default crew and ticked to
|
||||||
|
// completion (resolveAction) — the hold only changes once the task resolves on a tick. Jumping
|
||||||
|
// keeps it going if a whole system is exhausted.
|
||||||
let ship = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
let ship = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
||||||
const upgradeTarget = () => ship.systems.find((s) => s.built && s.level < 5 && totalQty(ship.inventory, 'resource') >= s.level);
|
const upgradeTarget = () => ship.systems.find((s) => s.built && s.level < 5 && totalQty(ship.inventory, 'resource') >= s.level);
|
||||||
// WEAPONS is gated behind the unresearched WEAPONS SYSTEMS tech — its build path is covered by
|
// WEAPONS is gated behind the unresearched WEAPONS SYSTEMS tech — its build path is covered by
|
||||||
@@ -273,13 +359,13 @@ test('SHIP SYSTEMS tab performs an affordable action and reflects it in the card
|
|||||||
const sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
const sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
||||||
const unexplored = sys.planets.filter((p) => !p.explored);
|
const unexplored = sys.planets.filter((p) => !p.explored);
|
||||||
if (unexplored.length > 0) {
|
if (unexplored.length > 0) {
|
||||||
expect((await page.request.post('/api/explore', { data: { planetId: unexplored[0].id } })).status()).toBe(200);
|
await resolveAction(page, '/api/explore', { planetId: unexplored[0].id });
|
||||||
} else {
|
} else {
|
||||||
const world = (await (await page.request.get('/api/world')).json()) as WorldState;
|
const world = (await (await page.request.get('/api/world')).json()) as WorldState;
|
||||||
const currentId = world.systems.find((s) => s.current)!.id;
|
const currentId = world.systems.find((s) => s.current)!.id;
|
||||||
const edge = world.edges.find(([a, b]) => a === currentId || b === currentId)!;
|
const edge = world.edges.find(([a, b]) => a === currentId || b === currentId)!;
|
||||||
const targetId = edge[0] === currentId ? edge[1] : edge[0];
|
const targetId = edge[0] === currentId ? edge[1] : edge[0];
|
||||||
expect((await page.request.post('/api/jump', { data: { systemId: targetId } })).status()).toBe(200);
|
await resolveAction(page, '/api/jump', { systemId: targetId });
|
||||||
}
|
}
|
||||||
ship = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
ship = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
||||||
}
|
}
|
||||||
@@ -292,28 +378,58 @@ test('SHIP SYSTEMS tab performs an affordable action and reflects it in the card
|
|||||||
await page.getByRole('tab', { name: 'SHIP SYSTEMS' }).click();
|
await page.getByRole('tab', { name: 'SHIP SYSTEMS' }).click();
|
||||||
|
|
||||||
if (upgrade) {
|
if (upgrade) {
|
||||||
|
// The UPGRADE button ARMS the action — the crew team builder mounts above the grid.
|
||||||
const card = page.getByRole('heading', { name: upgrade.type }).locator('xpath=ancestor::div[3]');
|
const card = page.getByRole('heading', { name: upgrade.type }).locator('xpath=ancestor::div[3]');
|
||||||
await expect(card.getByRole('button', { name: 'UPGRADE' })).toBeEnabled();
|
await expect(card.getByRole('button', { name: 'UPGRADE' })).toBeEnabled();
|
||||||
await card.getByRole('button', { name: 'UPGRADE' }).click();
|
await card.getByRole('button', { name: 'UPGRADE' }).click();
|
||||||
|
|
||||||
|
// Dispatch with the default one-person crew — the POST only QUEUES the upgrade: 200, no turn
|
||||||
|
// bump, the cost (`level` resources) already deducted from the hold, the level NOT yet up.
|
||||||
|
const res = await dispatchDefaultCrew(page, '/api/ship/upgrade');
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const queued = (await res.json()) as ShipState;
|
||||||
|
expect(queued.turn).toBe(ship.turn);
|
||||||
|
expect(queued.systems.find((s) => s.id === upgrade.id)!.level).toBe(upgrade.level); // no instant upgrade
|
||||||
|
expect(totalQty(queued.inventory, 'resource')).toBe(totalQty(ship.inventory, 'resource') - upgrade.level); // cost at queue time
|
||||||
|
const n = (await crewTasks(page)).find((t) => t.type === 'SHIP_UPGRADE')!.remaining; // N = the team's live duration (Task 6/8)
|
||||||
|
|
||||||
|
// The ticks: the level-up lands on the Nth one.
|
||||||
|
for (let k = 1; k <= n; k++) await tickTo(page, ship.turn + k);
|
||||||
|
|
||||||
const after = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
const after = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
||||||
const row = after.systems.find((s) => s.id === upgrade.id)!;
|
const row = after.systems.find((s) => s.id === upgrade.id)!;
|
||||||
expect(row.level).toBe(upgrade.level + 1);
|
expect(row.level).toBe(upgrade.level + 1);
|
||||||
expect(after.turn).toBe(ship.turn + 1);
|
expect(after.turn).toBe(ship.turn + n); // the tick, not the click, advances the counter
|
||||||
|
|
||||||
// The card badge flipped to the new level and the left column mirrors it.
|
// The card badge flipped to the new level and the left column mirrors it — both re-fetched by
|
||||||
|
// the tick, not by the click.
|
||||||
await expect(card.getByText(`LV ${upgrade.level + 1}`)).toBeVisible();
|
await expect(card.getByText(`LV ${upgrade.level + 1}`)).toBeVisible();
|
||||||
await expect(page.getByText(`LV ${row.level} · CAP ${row.capacity}`)).toBeVisible();
|
await expect(page.getByText(`LV ${row.level} · CAP ${row.capacity}`)).toBeVisible();
|
||||||
} else {
|
} else {
|
||||||
const target = build!;
|
const target = build!;
|
||||||
|
// The BUILD NEW button ARMS the action — the crew team builder mounts above the grid.
|
||||||
const card = page.getByRole('heading', { name: target.type }).locator('xpath=ancestor::div[3]');
|
const card = page.getByRole('heading', { name: target.type }).locator('xpath=ancestor::div[3]');
|
||||||
await expect(card.getByRole('button', { name: 'BUILD NEW' })).toBeEnabled();
|
await expect(card.getByRole('button', { name: 'BUILD NEW' })).toBeEnabled();
|
||||||
await card.getByRole('button', { name: 'BUILD NEW' }).click();
|
await card.getByRole('button', { name: 'BUILD NEW' }).click();
|
||||||
|
|
||||||
|
// Dispatch — the POST only QUEUES the build: 200, no turn bump, the flat 3-parts cost already
|
||||||
|
// deducted, the system NOT yet built.
|
||||||
|
const res = await dispatchDefaultCrew(page, '/api/ship/build');
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const queued = (await res.json()) as ShipState;
|
||||||
|
expect(queued.turn).toBe(ship.turn);
|
||||||
|
expect(queued.systems.find((s) => s.id === target.id)!.built).toBe(false); // no instant build
|
||||||
|
expect(totalQty(queued.inventory, 'part')).toBe(totalQty(ship.inventory, 'part') - 3); // cost at queue time
|
||||||
|
const n = (await crewTasks(page)).find((t) => t.type === 'SHIP_BUILD')!.remaining;
|
||||||
|
|
||||||
|
// The ticks: the build lands (OFFLINE → LV 1) on the Nth one.
|
||||||
|
for (let k = 1; k <= n; k++) await tickTo(page, ship.turn + k);
|
||||||
|
|
||||||
const after = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
const after = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
||||||
const row = after.systems.find((s) => s.id === target.id)!;
|
const row = after.systems.find((s) => s.id === target.id)!;
|
||||||
expect(row.built).toBe(true);
|
expect(row.built).toBe(true);
|
||||||
expect({ level: row.level, capacity: row.capacity }).toEqual({ level: 1, capacity: 2 });
|
expect({ level: row.level, capacity: row.capacity }).toEqual({ level: 1, capacity: 2 });
|
||||||
|
expect(after.turn).toBe(ship.turn + n); // the tick, not the click, advances the counter
|
||||||
|
|
||||||
// The card badge flipped OFFLINE → LV 1 and the left column's online count went up.
|
// The card badge flipped OFFLINE → LV 1 and the left column's online count went up.
|
||||||
await expect(card.getByText('LV 1')).toBeVisible();
|
await expect(card.getByText('LV 1')).toBeVisible();
|
||||||
@@ -322,7 +438,9 @@ test('SHIP SYSTEMS tab performs an affordable action and reflects it in the card
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('SKILL TREE tab researches WEAPONS SYSTEMS and unlocks the gated WEAPONS build', async ({ page }) => {
|
test('SKILL TREE tab researches WEAPONS SYSTEMS and unlocks the gated WEAPONS build', async ({ page }) => {
|
||||||
// Research costs two parts, building WEAPONS three — scan until the hold has five. Parts drop on
|
await drainQueue(page); // retry-safety: a failed earlier attempt may have left a row queued (an in-transit JUMP would 409 every new queue)
|
||||||
|
// Research costs two parts, building WEAPONS three — scan until the hold has five. Every
|
||||||
|
// scan/jump is queued with a default crew and ticked to completion (resolveAction). Parts drop on
|
||||||
// ~30% of scans, so P(<5 in 80 scans) is negligible; jumping keeps it going if a system exhausts.
|
// ~30% of scans, so P(<5 in 80 scans) is negligible; jumping keeps it going if a system exhausts.
|
||||||
let ship = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
let ship = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
||||||
let iterations = 0;
|
let iterations = 0;
|
||||||
@@ -331,7 +449,7 @@ test('SKILL TREE tab researches WEAPONS SYSTEMS and unlocks the gated WEAPONS bu
|
|||||||
const sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
const sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
||||||
const unexplored = sys.planets.filter((p) => !p.explored);
|
const unexplored = sys.planets.filter((p) => !p.explored);
|
||||||
if (unexplored.length > 0) {
|
if (unexplored.length > 0) {
|
||||||
expect((await page.request.post('/api/explore', { data: { planetId: unexplored[0].id } })).status()).toBe(200);
|
await resolveAction(page, '/api/explore', { planetId: unexplored[0].id });
|
||||||
} else {
|
} else {
|
||||||
await jumpToFreshSystem(page); // prefer undiscovered territory — first-edge ping-pongs between exhausted systems
|
await jumpToFreshSystem(page); // prefer undiscovered territory — first-edge ping-pongs between exhausted systems
|
||||||
}
|
}
|
||||||
@@ -347,34 +465,62 @@ test('SKILL TREE tab researches WEAPONS SYSTEMS and unlocks the gated WEAPONS bu
|
|||||||
await expect(weaponsCard.getByText('REQUIRES // WEAPONS SYSTEMS')).toBeVisible();
|
await expect(weaponsCard.getByText('REQUIRES // WEAPONS SYSTEMS')).toBeVisible();
|
||||||
await expect(weaponsCard.getByRole('button', { name: 'BUILD NEW' })).toBeDisabled();
|
await expect(weaponsCard.getByRole('button', { name: 'BUILD NEW' })).toBeDisabled();
|
||||||
|
|
||||||
// SKILL TREE tab: research WEAPONS SYSTEMS (two parts) — the card flips to RESEARCHED.
|
// SKILL TREE tab: research WEAPONS SYSTEMS (two parts). The RESEARCH button ARMS the tech — the
|
||||||
|
// crew team builder mounts — and its DISPATCH queues the RESEARCH task: 200, no turn bump, the
|
||||||
|
// cost already deducted, and the card NOT yet RESEARCHED (it flips on the resolving tick).
|
||||||
await page.getByRole('tab', { name: 'SKILL TREE' }).click();
|
await page.getByRole('tab', { name: 'SKILL TREE' }).click();
|
||||||
const techCard = page.getByRole('heading', { name: 'WEAPONS SYSTEMS' }).locator('xpath=ancestor::div[3]');
|
const techCard = page.getByRole('heading', { name: 'WEAPONS SYSTEMS' }).locator('xpath=ancestor::div[3]');
|
||||||
await expect(techCard.getByText('AVAILABLE')).toBeVisible(); // root tech — no prerequisites
|
await expect(techCard.getByText('AVAILABLE')).toBeVisible(); // root tech — no prerequisites
|
||||||
await expect(techCard.getByRole('button', { name: 'RESEARCH' })).toBeEnabled(); // parts ≥ 2
|
await expect(techCard.getByRole('button', { name: 'RESEARCH' })).toBeEnabled(); // parts ≥ 2
|
||||||
const turnBefore = ship.turn;
|
const turnBefore = ship.turn;
|
||||||
await techCard.getByRole('button', { name: 'RESEARCH' }).click();
|
await techCard.getByRole('button', { name: 'RESEARCH' }).click();
|
||||||
await expect(techCard.getByText('RESEARCHED')).toBeVisible();
|
const res = await dispatchDefaultCrew(page, '/api/research');
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const queuedTechs = (await res.json()) as { id: number; slug: string; state: string }[];
|
||||||
|
expect(queuedTechs.find((t) => t.slug === 'WEAPONS_SYSTEMS')!.state).toBe('AVAILABLE'); // no instant flip
|
||||||
|
// The research response is a bare TechDto[] — the cost deduction is checked on the ship snapshot.
|
||||||
|
const queuedShip = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
||||||
|
expect(queuedShip.turn).toBe(turnBefore);
|
||||||
|
expect(totalQty(queuedShip.inventory, 'part')).toBe(totalQty(ship.inventory, 'part') - 2); // cost at queue time
|
||||||
|
const n = (await crewTasks(page)).find((t) => t.type === 'RESEARCH')!.remaining;
|
||||||
|
|
||||||
|
// The ticks: the tech flips RESEARCHED (and unlocks the gated build) on the Nth one.
|
||||||
|
for (let k = 1; k <= n; k++) await tickTo(page, turnBefore + k);
|
||||||
|
await expect(techCard.getByText('RESEARCHED')).toBeVisible(); // the card flips on the resolving tick
|
||||||
const afterResearch = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
const afterResearch = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
||||||
expect(afterResearch.turn).toBe(turnBefore + 1); // research costs a turn
|
expect(afterResearch.turn).toBe(turnBefore + n); // the tick, not the click, advances the counter
|
||||||
|
|
||||||
// The gated ship action is now available: BUILD NEW on WEAPONS flips to enabled and builds.
|
// The gated ship action is now available: BUILD NEW on WEAPONS flips to enabled and ARMS the build.
|
||||||
await page.getByRole('tab', { name: 'SHIP SYSTEMS' }).click();
|
await page.getByRole('tab', { name: 'SHIP SYSTEMS' }).click();
|
||||||
await expect(weaponsCard.getByRole('button', { name: 'BUILD NEW' })).toBeEnabled();
|
await expect(weaponsCard.getByRole('button', { name: 'BUILD NEW' })).toBeEnabled();
|
||||||
await weaponsCard.getByRole('button', { name: 'BUILD NEW' }).click();
|
await weaponsCard.getByRole('button', { name: 'BUILD NEW' }).click();
|
||||||
|
|
||||||
|
// Dispatch the build — again queue, not instant: 200, no turn bump, still OFFLINE, cost deducted.
|
||||||
|
const buildRes = await dispatchDefaultCrew(page, '/api/ship/build');
|
||||||
|
expect(buildRes.status()).toBe(200);
|
||||||
|
const queuedBuild = (await buildRes.json()) as ShipState;
|
||||||
|
expect(queuedBuild.turn).toBe(afterResearch.turn);
|
||||||
|
expect(queuedBuild.systems.find((s) => s.type === 'WEAPONS')!.built).toBe(false); // no instant build
|
||||||
|
expect(totalQty(queuedBuild.inventory, 'part')).toBe(totalQty(afterResearch.inventory, 'part') - 3); // cost at queue time
|
||||||
|
const n2 = (await crewTasks(page)).find((t) => t.type === 'SHIP_BUILD')!.remaining;
|
||||||
|
|
||||||
|
// The ticks: WEAPONS comes online (OFFLINE → LV 1) on the Nth one.
|
||||||
|
for (let k = 1; k <= n2; k++) await tickTo(page, afterResearch.turn + k);
|
||||||
|
|
||||||
const afterBuild = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
const afterBuild = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
||||||
expect(afterBuild.systems.find((s) => s.type === 'WEAPONS')!.built).toBe(true);
|
expect(afterBuild.systems.find((s) => s.type === 'WEAPONS')!.built).toBe(true);
|
||||||
|
expect(afterBuild.turn).toBe(afterResearch.turn + n2);
|
||||||
await expect(weaponsCard.getByText('LV 1')).toBeVisible();
|
await expect(weaponsCard.getByText('LV 1')).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('NAVIGATION AI research unlocks two-hop jumps on the world map (#35)', async ({ page }) => {
|
test('NAVIGATION AI research unlocks two-hop jumps on the world map (#35)', async ({ page }) => {
|
||||||
|
await drainQueue(page); // retry-safety: a failed earlier attempt may have left a row queued (an in-transit JUMP would 409 every new queue)
|
||||||
// Research costs two resources (70% of scans drop one), so a short scan loop makes it affordable;
|
// Research costs two resources (70% of scans drop one), so a short scan loop makes it affordable;
|
||||||
// jumping keeps it going if a system exhausts. Idempotent: a retry finds it already RESEARCHED.
|
// jumping keeps it going if a system exhausts. Idempotent: a retry finds it already RESEARCHED.
|
||||||
let techs = (await (await page.request.get('/api/tech')).json()) as { id: number; slug: string; state: string }[];
|
let techs = (await (await page.request.get('/api/tech')).json()) as { id: number; slug: string; state: string }[];
|
||||||
const navAiState = () => techs.find((t) => t.slug === 'NAV_AI')!.state;
|
const navAiState = () => techs.find((t) => t.slug === 'NAV_AI')!.state;
|
||||||
if (navAiState() !== 'RESEARCHED') {
|
if (navAiState() !== 'RESEARCHED') {
|
||||||
|
// Every scan/jump is queued with a default crew and ticked to completion (resolveAction).
|
||||||
let ship = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
let ship = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
||||||
let iterations = 0;
|
let iterations = 0;
|
||||||
while (totalQty(ship.inventory, 'resource') < 2 && iterations < 40) {
|
while (totalQty(ship.inventory, 'resource') < 2 && iterations < 40) {
|
||||||
@@ -382,7 +528,7 @@ test('NAVIGATION AI research unlocks two-hop jumps on the world map (#35)', asyn
|
|||||||
const sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
const sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
||||||
const unexplored = sys.planets.filter((p) => !p.explored);
|
const unexplored = sys.planets.filter((p) => !p.explored);
|
||||||
if (unexplored.length > 0) {
|
if (unexplored.length > 0) {
|
||||||
expect((await page.request.post('/api/explore', { data: { planetId: unexplored[0].id } })).status()).toBe(200);
|
await resolveAction(page, '/api/explore', { planetId: unexplored[0].id });
|
||||||
} else {
|
} else {
|
||||||
await jumpToFreshSystem(page); // prefer undiscovered territory — first-edge ping-pongs between exhausted systems
|
await jumpToFreshSystem(page); // prefer undiscovered territory — first-edge ping-pongs between exhausted systems
|
||||||
}
|
}
|
||||||
@@ -391,12 +537,25 @@ test('NAVIGATION AI research unlocks two-hop jumps on the world map (#35)', asyn
|
|||||||
expect(totalQty(ship.inventory, 'resource')).toBeGreaterThanOrEqual(2);
|
expect(totalQty(ship.inventory, 'resource')).toBeGreaterThanOrEqual(2);
|
||||||
|
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
// SKILL TREE tab: research NAVIGATION AI (two resources) — the card flips to RESEARCHED.
|
// SKILL TREE tab: research NAVIGATION AI (two resources). The RESEARCH button ARMS the tech —
|
||||||
|
// the crew team builder mounts — and its DISPATCH queues the RESEARCH task: 200, no turn bump,
|
||||||
|
// the cost already deducted, and the card NOT yet RESEARCHED.
|
||||||
await page.getByRole('tab', { name: 'SKILL TREE' }).click();
|
await page.getByRole('tab', { name: 'SKILL TREE' }).click();
|
||||||
const techCard = page.getByRole('heading', { name: 'NAVIGATION AI' }).locator('xpath=ancestor::div[3]');
|
const techCard = page.getByRole('heading', { name: 'NAVIGATION AI' }).locator('xpath=ancestor::div[3]');
|
||||||
await expect(techCard.getByText('AVAILABLE')).toBeVisible(); // root tech — no prerequisites
|
await expect(techCard.getByText('AVAILABLE')).toBeVisible(); // root tech — no prerequisites
|
||||||
await expect(techCard.getByRole('button', { name: 'RESEARCH' })).toBeEnabled(); // resources ≥ 2
|
await expect(techCard.getByRole('button', { name: 'RESEARCH' })).toBeEnabled(); // resources ≥ 2
|
||||||
await techCard.getByRole('button', { name: 'RESEARCH' }).click();
|
await techCard.getByRole('button', { name: 'RESEARCH' }).click();
|
||||||
|
const res = await dispatchDefaultCrew(page, '/api/research');
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const queuedTechs = (await res.json()) as { id: number; slug: string; state: string }[];
|
||||||
|
expect(queuedTechs.find((t) => t.slug === 'NAV_AI')!.state).toBe('AVAILABLE'); // no instant flip
|
||||||
|
const queuedShip = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
||||||
|
expect(queuedShip.turn).toBe(ship.turn);
|
||||||
|
expect(totalQty(queuedShip.inventory, 'resource')).toBe(totalQty(ship.inventory, 'resource') - 2); // cost at queue time
|
||||||
|
const n = (await crewTasks(page)).find((t) => t.type === 'RESEARCH')!.remaining;
|
||||||
|
|
||||||
|
// The ticks: the card flips RESEARCHED on the Nth one (the unlock lands with it).
|
||||||
|
for (let k = 1; k <= n; k++) await tickTo(page, ship.turn + k);
|
||||||
await expect(techCard.getByText('RESEARCHED')).toBeVisible();
|
await expect(techCard.getByText('RESEARCHED')).toBeVisible();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -426,14 +585,30 @@ test('NAVIGATION AI research unlocks two-hop jumps on the world map (#35)', asyn
|
|||||||
|
|
||||||
// The two-hop systems render as distinct chart fields (// JUMP ×2 sublabel) — several at once, so .first().
|
// The two-hop systems render as distinct chart fields (// JUMP ×2 sublabel) — several at once, so .first().
|
||||||
await expect(panel.getByText(/(DISCOVERED|UNKNOWN) \/\/ JUMP ×2/).first()).toBeVisible();
|
await expect(panel.getByText(/(DISCOVERED|UNKNOWN) \/\/ JUMP ×2/).first()).toBeVisible();
|
||||||
|
// Click the target's chart field — it ARMS the node: the crew team builder floats over the chart.
|
||||||
await panel.getByRole('button', { name: target.name.toUpperCase() }).click();
|
await panel.getByRole('button', { name: target.name.toUpperCase() }).click();
|
||||||
|
|
||||||
|
// Dispatch with the default one-person crew — the POST only QUEUES the two-hop jump: 200, no
|
||||||
|
// turn bump, no landing yet (the origin is still `current` in the queue response).
|
||||||
|
const res = await dispatchDefaultCrew(page, '/api/jump');
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const queued = (await res.json()) as WorldState;
|
||||||
|
expect(queued.turn).toBe(turnBefore);
|
||||||
|
expect(queued.systems.find((s) => s.current)?.id).toBe(world.systems.find((s) => s.current)!.id); // no instant landing
|
||||||
|
// The hop count now feeds the duration model, not a flat turn delta: N is the team's live
|
||||||
|
// duration for a two-hop jump (the route puts the hop count in the queued payload).
|
||||||
|
const n = queued.tasks.find((t) => t.type === 'JUMP')!.remaining;
|
||||||
|
|
||||||
|
// The ticks: the counter advances one per tick, and the jump lands on the Nth one.
|
||||||
|
for (let k = 1; k <= n; k++) await tickTo(page, turnBefore + k);
|
||||||
|
|
||||||
const after = (await (await page.request.get('/api/world')).json()) as WorldState;
|
const after = (await (await page.request.get('/api/world')).json()) as WorldState;
|
||||||
expect(after.systems.find((s) => s.id === target.id)!.current).toBe(true); // world state updated in one action
|
expect(after.systems.find((s) => s.id === target.id)!.current).toBe(true); // the jump landed on the Nth tick
|
||||||
expect(after.turn).toBe(turnBefore + 2); // the turn cost scales with hop count (#35)
|
expect(after.turn).toBe(turnBefore + n); // the hop count scaled the duration, not a flat +2 (#35)
|
||||||
});
|
});
|
||||||
|
|
||||||
test('MISSIONS tab accepts a contract and completing it grants the reward', async ({ page }) => {
|
test('MISSIONS tab accepts a contract and completing it grants the reward', async ({ page }) => {
|
||||||
|
await drainQueue(page); // retry-safety: a failed earlier attempt may have left a row queued (an in-transit JUMP would 409 every new queue)
|
||||||
const board = (await (await page.request.get('/api/missions')).json()) as MissionDto[];
|
const board = (await (await page.request.get('/api/missions')).json()) as MissionDto[];
|
||||||
expect(board.filter((m) => m.state === 'AVAILABLE').length).toBeGreaterThanOrEqual(3); // the board is always topped up
|
expect(board.filter((m) => m.state === 'AVAILABLE').length).toBeGreaterThanOrEqual(3); // the board is always topped up
|
||||||
|
|
||||||
@@ -461,14 +636,19 @@ test('MISSIONS tab accepts a contract and completing it grants the reward', asyn
|
|||||||
|
|
||||||
// One ACCEPT button per card, in board order — the picked contract's is enabled (AVAILABLE, nothing active).
|
// One ACCEPT button per card, in board order — the picked contract's is enabled (AVAILABLE, nothing active).
|
||||||
await expect(acceptButtons.nth(idx)).toBeEnabled();
|
await expect(acceptButtons.nth(idx)).toBeEnabled();
|
||||||
|
// Accepting is the one action in the suite that does NOT queue (JC-19): no crew params, and no
|
||||||
|
// turn bump — the turn counter only ever moves on a NEXT TURN tick.
|
||||||
|
const worldBefore = (await (await page.request.get('/api/world')).json()) as WorldState;
|
||||||
await acceptButtons.nth(idx).click();
|
await acceptButtons.nth(idx).click();
|
||||||
|
const worldAfter = (await (await page.request.get('/api/world')).json()) as WorldState;
|
||||||
|
expect(worldAfter.turn).toBe(worldBefore.turn); // JC-19 — accept is free, it does not tick
|
||||||
|
|
||||||
// UI flipped: exactly one ACTIVE badge on the board and the accepted card's button is now disabled.
|
// UI flipped: exactly one ACTIVE badge on the board and the accepted card's button is now disabled.
|
||||||
// No exact match — ACTIVE badges render a "●" dot prefix (components/ui/badge.tsx), so their text is "●ACTIVE".
|
// No exact match — ACTIVE badges render a "●" dot prefix (components/ui/badge.tsx), so their text is "●ACTIVE".
|
||||||
await expect(panel.getByText('ACTIVE')).toBeVisible();
|
await expect(panel.getByText('ACTIVE')).toBeVisible();
|
||||||
await expect(acceptButtons.nth(idx)).toBeDisabled();
|
await expect(acceptButtons.nth(idx)).toBeDisabled();
|
||||||
|
|
||||||
// API confirms it: exactly one ACTIVE mission, the picked one (accepting cost a turn).
|
// API confirms it: exactly one ACTIVE mission, the picked one.
|
||||||
const boardAfterAccept = (await (await page.request.get('/api/missions')).json()) as MissionDto[];
|
const boardAfterAccept = (await (await page.request.get('/api/missions')).json()) as MissionDto[];
|
||||||
expect(boardAfterAccept.filter((m) => m.state === 'ACTIVE')).toEqual([boardAfterAccept.find((m) => m.id === picked.id)!]);
|
expect(boardAfterAccept.filter((m) => m.state === 'ACTIVE')).toEqual([boardAfterAccept.find((m) => m.id === picked.id)!]);
|
||||||
}
|
}
|
||||||
@@ -477,9 +657,11 @@ test('MISSIONS tab accepts a contract and completing it grants the reward', asyn
|
|||||||
const shipBefore = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
const shipBefore = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
||||||
const baseline = totalQty(shipBefore.inventory, picked.rewardKind);
|
const baseline = totalQty(shipBefore.inventory, picked.rewardKind);
|
||||||
|
|
||||||
// Complete it. EXPLORE/FIND: scan until done, jumping when a system exhausts (parts drop on ~30% of
|
// Complete it. Every scan/jump is queued with a default crew and ticked to completion
|
||||||
// scans, so P(a FIND-part misses in 80 scans) ≈ 0.7^80 — negligible). DELIVER: follow the shortest
|
// (resolveAction) — the mission hooks run on the resolving ticks. EXPLORE/FIND: scan until done,
|
||||||
// jump path to its target (edges only ever get added, so the precomputed path stays valid).
|
// jumping when a system exhausts (parts drop on ~30% of scans, so P(a FIND-part misses in 80
|
||||||
|
// scans) ≈ 0.7^80 — negligible). DELIVER: follow the shortest jump path to its target (edges
|
||||||
|
// only ever get added, so the precomputed path stays valid).
|
||||||
let deliverPath: number[] = [];
|
let deliverPath: number[] = [];
|
||||||
if (picked.type === 'DELIVER') {
|
if (picked.type === 'DELIVER') {
|
||||||
const worldNow = (await (await page.request.get('/api/world')).json()) as WorldState;
|
const worldNow = (await (await page.request.get('/api/world')).json()) as WorldState;
|
||||||
@@ -491,12 +673,12 @@ test('MISSIONS tab accepts a contract and completing it grants the reward', asyn
|
|||||||
while (state !== 'DONE' && iterations < 80) {
|
while (state !== 'DONE' && iterations < 80) {
|
||||||
iterations++;
|
iterations++;
|
||||||
if (deliverPath.length > 0) {
|
if (deliverPath.length > 0) {
|
||||||
expect((await page.request.post('/api/jump', { data: { systemId: deliverPath.shift()! } })).status()).toBe(200);
|
await resolveAction(page, '/api/jump', { systemId: deliverPath.shift()! });
|
||||||
} else {
|
} else {
|
||||||
const sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
const sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
||||||
const unexplored = sys.planets.filter((p) => !p.explored);
|
const unexplored = sys.planets.filter((p) => !p.explored);
|
||||||
if (unexplored.length > 0) {
|
if (unexplored.length > 0) {
|
||||||
expect((await page.request.post('/api/explore', { data: { planetId: unexplored[0].id } })).status()).toBe(200);
|
await resolveAction(page, '/api/explore', { planetId: unexplored[0].id });
|
||||||
} else {
|
} else {
|
||||||
await jumpToFreshSystem(page); // prefer undiscovered territory — first-edge ping-pongs between exhausted systems
|
await jumpToFreshSystem(page); // prefer undiscovered territory — first-edge ping-pongs between exhausted systems
|
||||||
}
|
}
|
||||||
@@ -510,11 +692,14 @@ test('MISSIONS tab accepts a contract and completing it grants the reward', asyn
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('EVENT LOG tab shows real game events, newest first', async ({ page }) => {
|
test('EVENT LOG tab shows real game events, newest first', async ({ page }) => {
|
||||||
|
await drainQueue(page); // retry-safety: a failed earlier attempt may have left a row queued (an in-transit JUMP would 409 every new queue)
|
||||||
// Idempotent across retries sharing a DB: assert on THIS run's own entries (identified by turn and
|
// Idempotent across retries sharing a DB: assert on THIS run's own entries (identified by turn and
|
||||||
// message), never on absolute counts — earlier attempts leave their events behind.
|
// message), never on absolute counts — earlier attempts leave their events behind.
|
||||||
|
// The jump is queued + ticked to completion: the event it writes carries the tick it RESOLVED
|
||||||
|
// on, not the turn of the queueing POST.
|
||||||
const afterJump = await jumpToFreshSystem(page);
|
const afterJump = await jumpToFreshSystem(page);
|
||||||
const jumpedName = afterJump.systems.find((s) => s.current)!.name;
|
const jumpedName = afterJump.systems.find((s) => s.current)!.name;
|
||||||
const jumpTurn = afterJump.turn;
|
const jumpTurn = afterJump.turn; // the resolution tick's turn
|
||||||
|
|
||||||
// Scan one body — if the current system is exhausted (leftover from a previous attempt), hop again first.
|
// Scan one body — if the current system is exhausted (leftover from a previous attempt), hop again first.
|
||||||
let sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
let sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
||||||
@@ -523,23 +708,25 @@ test('EVENT LOG tab shows real game events, newest first', async ({ page }) => {
|
|||||||
sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
sys = (await (await page.request.get('/api/system')).json()) as SystemState;
|
||||||
}
|
}
|
||||||
const planet = sys.planets.find((p) => !p.explored)!;
|
const planet = sys.planets.find((p) => !p.explored)!;
|
||||||
const exploreRes = await page.request.post('/api/explore', { data: { planetId: planet.id } });
|
// The explore POST only queues — no turn bump, no event yet — so tick it to completion: the scan
|
||||||
expect(exploreRes.status()).toBe(200);
|
// event lands on the resolving tick, and the post-tick /api/system snapshot carries that turn.
|
||||||
const explored = (await exploreRes.json()) as ExploreResult;
|
const explored = (await resolveAction(page, '/api/explore', { planetId: planet.id })) as SystemState;
|
||||||
|
const exploreTurn = explored.turn;
|
||||||
|
|
||||||
// API: this run's jump + scan are in the log, and the newer one (the scan) comes first.
|
// API: this run's jump + scan are in the log, each stamped with the tick it resolved on, and the
|
||||||
|
// newer one (the scan) comes first.
|
||||||
const events = (await (await page.request.get('/api/events')).json()) as EventDto[];
|
const events = (await (await page.request.get('/api/events')).json()) as EventDto[];
|
||||||
const exploreEvent = events.find((e) => e.turn === explored.turn && e.type === 'explore');
|
const exploreEvent = events.find((e) => e.turn === exploreTurn && e.type === 'explore');
|
||||||
expect(exploreEvent?.message).toMatch(new RegExp(`^Explored ${planet.name} — found`));
|
expect(exploreEvent?.message).toMatch(new RegExp(`^Explored ${planet.name} — found`));
|
||||||
const jumpEvent = events.find((e) => e.type === 'jump' && e.message === `Jumped to ${jumpedName}`);
|
const jumpEvent = events.find((e) => e.type === 'jump' && e.message === `Jumped to ${jumpedName}`);
|
||||||
expect(jumpEvent).toBeDefined(); // system names are unique, so the message pins this run's jump
|
expect(jumpEvent).toBeDefined(); // system names are unique, so the message pins this run's jump
|
||||||
expect(events.indexOf(exploreEvent!)).toBeLessThan(events.indexOf(jumpEvent!));
|
expect(events.indexOf(exploreEvent!)).toBeLessThan(events.indexOf(jumpEvent!));
|
||||||
|
|
||||||
// UI: the terminal renders both lines (T<turn> // <MESSAGE>, uppercased).
|
// UI: the terminal renders both lines (T<turn> // <MESSAGE>, uppercased) with the resolution turns.
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
await page.getByRole('tab', { name: 'EVENT LOG' }).click();
|
await page.getByRole('tab', { name: 'EVENT LOG' }).click();
|
||||||
const panel = page.getByRole('tabpanel');
|
const panel = page.getByRole('tabpanel');
|
||||||
await expect(panel.getByText(new RegExp(`T${explored.turn} // EXPLORED ${planet.name.toUpperCase()}`))).toBeVisible();
|
await expect(panel.getByText(new RegExp(`T${exploreTurn} // EXPLORED ${planet.name.toUpperCase()}`))).toBeVisible();
|
||||||
await expect(panel.getByText(new RegExp(`T${jumpTurn} // JUMPED TO ${jumpedName.toUpperCase()}`))).toBeVisible();
|
await expect(panel.getByText(new RegExp(`T${jumpTurn} // JUMPED TO ${jumpedName.toUpperCase()}`))).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -550,3 +737,270 @@ test('GET /api/version reports the app version as JSON', async ({ page }) => {
|
|||||||
const body = (await res.json()) as { version: string };
|
const body = (await res.json()) as { version: string };
|
||||||
expect(body.version).toMatch(/^\d+\.\d+\.\d+$/);
|
expect(body.version).toMatch(/^\d+\.\d+\.\d+$/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- The new queue + tick model scenarios (Task 10 / #44) -------------------------------
|
||||||
|
// All five start from a clean queue (drainQueue): the CI DB persists across retries, and a
|
||||||
|
// failed earlier attempt can leave an ACTIVE / PENDING row — or an in-transit JUMP — behind.
|
||||||
|
// Every duration below is read live from the queue responses (the team builder's value, Task 8),
|
||||||
|
// never hard-coded, and every tick goes through the raw POST /api/turn — the only turn bump.
|
||||||
|
|
||||||
|
// The full queue row keyed by id — the same array the Task 9 strip renders (ACTIVE block first,
|
||||||
|
// then PENDING; DONE rows are filtered out of the snapshots, so only ACTIVE/PENDING appear).
|
||||||
|
interface QueueTaskRow { id: number; type: string; status: string; remaining: number }
|
||||||
|
// World / system snapshot views carrying that full row shape (the top-level DTOs keep the minimal
|
||||||
|
// {type, remaining} subset the reworked tests read).
|
||||||
|
interface WorldStateQ { systems: WorldSystemDto[]; edges: [number, number][]; turn: number; tasks: QueueTaskRow[] }
|
||||||
|
interface SystemStateQ { systemId: number; systemName: string; planets: PlanetDto[]; inventory: InventoryItemDto[]; turn: number; tasks: QueueTaskRow[] }
|
||||||
|
|
||||||
|
// One POST /api/turn (no body) — the only thing that advances the turn counter.
|
||||||
|
const tickOnce = async (page: Page) => {
|
||||||
|
expect((await page.request.post('/api/turn')).status()).toBe(200);
|
||||||
|
};
|
||||||
|
|
||||||
|
test('queueing a one-person JUMP leaves the ship in the origin until its Nth tick (#44)', async ({ page }) => {
|
||||||
|
await drainQueue(page);
|
||||||
|
const world = (await (await page.request.get('/api/world')).json()) as WorldStateQ;
|
||||||
|
const currentId = world.systems.find((s) => s.current)!.id;
|
||||||
|
const edge = world.edges.find(([a, b]) => a === currentId || b === currentId)!;
|
||||||
|
const targetId = edge[0] === currentId ? edge[1] : edge[0];
|
||||||
|
const T = world.turn;
|
||||||
|
const { crew } = (await (await page.request.get('/api/crew')).json()) as { crew: CrewDto[]; tasks: QueueTaskDto[] };
|
||||||
|
expect(crew.length).toBeGreaterThanOrEqual(2);
|
||||||
|
|
||||||
|
// The queue POST: 200, no turn bump, no landing — the free member starts the JUMP ACTIVE at once.
|
||||||
|
const res = await page.request.post('/api/jump', { data: { systemId: targetId, leadCrewId: crew[0].id, helperCrewIds: [] } });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const queued = (await res.json()) as WorldStateQ;
|
||||||
|
expect(queued.turn).toBe(T);
|
||||||
|
expect(queued.systems.find((s) => s.current)?.id).toBe(currentId); // unchanged immediately after the queue POST
|
||||||
|
const n = queued.tasks.find((t) => t.type === 'JUMP')!.remaining; // N = the team's live duration (Task 6/8)
|
||||||
|
expect(queued.tasks.find((t) => t.type === 'JUMP')!.status).toBe('ACTIVE');
|
||||||
|
|
||||||
|
// N-1 ticks: still in transit — remaining 1, the origin still current.
|
||||||
|
for (let k = 0; k < n - 1; k++) await tickOnce(page);
|
||||||
|
const mid = (await (await page.request.get('/api/world')).json()) as WorldStateQ;
|
||||||
|
expect(mid.turn).toBe(T + n - 1);
|
||||||
|
expect(mid.systems.find((s) => s.current)?.id).toBe(currentId); // unchanged after N-1 ticks
|
||||||
|
expect(mid.tasks.find((t) => t.type === 'JUMP')!.remaining).toBe(1);
|
||||||
|
|
||||||
|
// The Nth tick lands the jump.
|
||||||
|
await tickOnce(page);
|
||||||
|
const after = (await (await page.request.get('/api/world')).json()) as WorldStateQ;
|
||||||
|
expect(after.turn).toBe(T + n);
|
||||||
|
expect(after.systems.find((s) => s.current)?.id).toBe(targetId); // changed exactly on the Nth tick
|
||||||
|
expect(after.tasks.some((t) => t.type === 'JUMP')).toBe(false); // resolved rows are filtered out
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a JUMP and a disjoint-crew EXPLORE run in parallel and resolve at their own durations (#44)', async ({ page }) => {
|
||||||
|
await drainQueue(page);
|
||||||
|
const { crew } = (await (await page.request.get('/api/crew')).json()) as { crew: CrewDto[]; tasks: QueueTaskDto[] };
|
||||||
|
expect(crew.length).toBeGreaterThanOrEqual(2); // disjoint one-person teams
|
||||||
|
|
||||||
|
// The explore's body: an unexplored planet in the current system. A jump's fallback target can
|
||||||
|
// be a fully-explored system (jumpToFreshSystem prefers undiscovered, not unexplored), so loop
|
||||||
|
// like the other preambles instead of a single if.
|
||||||
|
let sys = (await (await page.request.get('/api/system')).json()) as SystemStateQ;
|
||||||
|
for (let guard = 0; !sys.planets.some((p) => !p.explored) && guard < 10; guard++) {
|
||||||
|
await jumpToFreshSystem(page);
|
||||||
|
sys = (await (await page.request.get('/api/system')).json()) as SystemStateQ;
|
||||||
|
}
|
||||||
|
const planet = sys.planets.find((p) => !p.explored)!;
|
||||||
|
expect(planet).toBeDefined(); // the world keeps producing fresh unscanned bodies
|
||||||
|
|
||||||
|
const world = (await (await page.request.get('/api/world')).json()) as WorldStateQ;
|
||||||
|
const currentId = world.systems.find((s) => s.current)!.id;
|
||||||
|
const edge = world.edges.find(([a, b]) => a === currentId || b === currentId)!;
|
||||||
|
const targetId = edge[0] === currentId ? edge[1] : edge[0];
|
||||||
|
const targetName = world.systems.find((s) => s.id === targetId)!.name;
|
||||||
|
const T = world.turn;
|
||||||
|
|
||||||
|
// Mandated order (JC-17): the EXPLORE is queued FIRST — while a JUMP is ACTIVE no new task of any
|
||||||
|
// type may be queued, so a jump-first order would 409 the explore. Both crews are free, so both
|
||||||
|
// tasks start ACTIVE immediately and run in parallel, with no interleaving clicks.
|
||||||
|
const expRes = await page.request.post('/api/explore', { data: { planetId: planet.id, leadCrewId: crew[1].id, helperCrewIds: [] } });
|
||||||
|
expect(expRes.status()).toBe(200);
|
||||||
|
const expQ = (await expRes.json()) as SystemStateQ;
|
||||||
|
expect(expQ.turn).toBe(T);
|
||||||
|
const nExp = expQ.tasks.find((t) => t.type === 'EXPLORE')!.remaining;
|
||||||
|
expect(expQ.tasks.find((t) => t.type === 'EXPLORE')!.status).toBe('ACTIVE');
|
||||||
|
|
||||||
|
const jmpRes = await page.request.post('/api/jump', { data: { systemId: targetId, leadCrewId: crew[0].id, helperCrewIds: [] } });
|
||||||
|
expect(jmpRes.status()).toBe(200); // legal even while the non-jump explore is ACTIVE
|
||||||
|
const jmpQ = (await jmpRes.json()) as WorldStateQ;
|
||||||
|
expect(jmpQ.turn).toBe(T);
|
||||||
|
const nJmp = jmpQ.tasks.find((t) => t.type === 'JUMP')!.remaining;
|
||||||
|
expect(jmpQ.tasks.find((t) => t.type === 'EXPLORE')!.status).toBe('ACTIVE'); // the explore kept running
|
||||||
|
expect(jmpQ.tasks.find((t) => t.type === 'JUMP')!.status).toBe('ACTIVE');
|
||||||
|
|
||||||
|
const getEvents = async () => (await (await page.request.get('/api/events')).json()) as EventDto[];
|
||||||
|
// A planet flip and a jump are both recorded by the event log (the same records the EVENT LOG test
|
||||||
|
// reads), each stamped with the tick it resolved on — turn numbers are unique within a run, so the
|
||||||
|
// (turn, message) pair pins this run's own tasks.
|
||||||
|
const exploreEventAt = async (turn: number) =>
|
||||||
|
(await getEvents()).find((e) => e.type === 'explore' && e.turn === turn && e.message.startsWith(`Explored ${planet.name} — found`));
|
||||||
|
const jumpEventAt = async (turn: number) =>
|
||||||
|
(await getEvents()).find((e) => e.type === 'jump' && e.turn === turn && e.message === `Jumped to ${targetName}`);
|
||||||
|
|
||||||
|
if (nExp < nJmp) {
|
||||||
|
// The scan resolves first (tick nExp), while the ship is still in the origin — so the flip is
|
||||||
|
// readable directly off the current system.
|
||||||
|
for (let k = 0; k < nExp; k++) await tickOnce(page);
|
||||||
|
const mid = (await (await page.request.get('/api/system')).json()) as SystemStateQ;
|
||||||
|
expect(mid.turn).toBe(T + nExp);
|
||||||
|
expect(mid.planets.find((p) => p.id === planet.id)?.explored).toBe(true); // the scan's effect, on its own tick
|
||||||
|
expect(mid.tasks.some((t) => t.type === 'EXPLORE')).toBe(false);
|
||||||
|
expect(await exploreEventAt(T + nExp)).toBeDefined();
|
||||||
|
const midWorld = (await (await page.request.get('/api/world')).json()) as WorldStateQ;
|
||||||
|
expect(midWorld.systems.find((s) => s.current)?.id).toBe(currentId); // not landed yet
|
||||||
|
expect(midWorld.tasks.find((t) => t.type === 'JUMP')!.status).toBe('ACTIVE');
|
||||||
|
expect(midWorld.tasks.find((t) => t.type === 'JUMP')!.remaining).toBe(nJmp - nExp); // nJmp - nExp ticks left
|
||||||
|
for (let k = 0; k < nJmp - nExp; k++) await tickOnce(page);
|
||||||
|
} else if (nJmp < nExp) {
|
||||||
|
// The jump lands first (tick nJmp); the origin is no longer `current` (GET /api/system is
|
||||||
|
// current-only), so the scan's flip is proven by the event it writes on its own resolution tick.
|
||||||
|
for (let k = 0; k < nJmp; k++) await tickOnce(page);
|
||||||
|
const midWorld = (await (await page.request.get('/api/world')).json()) as WorldStateQ;
|
||||||
|
expect(midWorld.turn).toBe(T + nJmp);
|
||||||
|
expect(midWorld.systems.find((s) => s.current)?.id).toBe(targetId);
|
||||||
|
expect(await jumpEventAt(T + nJmp)).toBeDefined();
|
||||||
|
expect(midWorld.tasks.find((t) => t.type === 'EXPLORE')!.status).toBe('ACTIVE');
|
||||||
|
expect(midWorld.tasks.find((t) => t.type === 'EXPLORE')!.remaining).toBe(nExp - nJmp); // nExp - nJmp ticks left
|
||||||
|
for (let k = 0; k < nExp - nJmp; k++) await tickOnce(page);
|
||||||
|
} else {
|
||||||
|
// Equal durations: both decrement in lockstep and stay ACTIVE through every tick before the last.
|
||||||
|
for (let k = 1; k < nExp; k++) {
|
||||||
|
await tickOnce(page);
|
||||||
|
const midWorld = (await (await page.request.get('/api/world')).json()) as WorldStateQ;
|
||||||
|
expect(midWorld.tasks.find((t) => t.type === 'EXPLORE')!.remaining).toBe(nExp - k);
|
||||||
|
expect(midWorld.tasks.find((t) => t.type === 'JUMP')!.remaining).toBe(nExp - k);
|
||||||
|
}
|
||||||
|
// The Nth tick resolves both — the loop above covered ticks 1..N-1 only (mirrors how the other
|
||||||
|
// scenarios end on their resolving tick).
|
||||||
|
await tickOnce(page);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Both resolved at their own durations: the jump landed, each event is stamped on its task's
|
||||||
|
// resolution tick, and the queue is clean again.
|
||||||
|
const after = (await (await page.request.get('/api/world')).json()) as WorldStateQ;
|
||||||
|
expect(after.turn).toBe(T + Math.max(nExp, nJmp));
|
||||||
|
expect(after.systems.find((s) => s.current)?.id).toBe(targetId);
|
||||||
|
expect(after.tasks.some((t) => t.type === 'JUMP' || t.type === 'EXPLORE')).toBe(false);
|
||||||
|
expect(await exploreEventAt(T + nExp)).toBeDefined();
|
||||||
|
expect(await jumpEventAt(T + nJmp)).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a second task for a member on an ACTIVE one is pre-queued PENDING and auto-starts on its tick (#44)', async ({ page }) => {
|
||||||
|
await drainQueue(page);
|
||||||
|
const { crew } = (await (await page.request.get('/api/crew')).json()) as { crew: CrewDto[]; tasks: QueueTaskDto[] };
|
||||||
|
expect(crew.length).toBeGreaterThanOrEqual(2);
|
||||||
|
|
||||||
|
// Two unexplored bodies in the current system; a fresh system always has them, so jump until the
|
||||||
|
// current one does (the bounded guard fails the test if the world ever stops producing them).
|
||||||
|
let sys = (await (await page.request.get('/api/system')).json()) as SystemStateQ;
|
||||||
|
for (let guard = 0; sys.planets.filter((p) => !p.explored).length < 2 && guard < 10; guard++) {
|
||||||
|
await jumpToFreshSystem(page);
|
||||||
|
sys = (await (await page.request.get('/api/system')).json()) as SystemStateQ;
|
||||||
|
}
|
||||||
|
const unexplored = sys.planets.filter((p) => !p.explored);
|
||||||
|
expect(unexplored.length).toBeGreaterThanOrEqual(2);
|
||||||
|
const planetA = unexplored[0]!;
|
||||||
|
const planetB = unexplored[1]!;
|
||||||
|
const T = sys.turn;
|
||||||
|
|
||||||
|
// Task 1: crew[0] is free, so the scan starts ACTIVE at once.
|
||||||
|
const res1 = await page.request.post('/api/explore', { data: { planetId: planetA.id, leadCrewId: crew[0].id, helperCrewIds: [] } });
|
||||||
|
expect(res1.status()).toBe(200);
|
||||||
|
const q1 = (await res1.json()) as SystemStateQ;
|
||||||
|
expect(q1.turn).toBe(T); // no turn bump on queue
|
||||||
|
const t1 = q1.tasks.find((t) => t.type === 'EXPLORE')!; // the only row — the queue was clean
|
||||||
|
expect(t1.status).toBe('ACTIVE');
|
||||||
|
const na = t1.remaining;
|
||||||
|
|
||||||
|
// Task 2, same member, a different target: a lead on an ACTIVE may chain (JC-16) — it is accepted
|
||||||
|
// (the member is on ACTIVE, not PENDING, and no jump is in transit) and starts PENDING.
|
||||||
|
const res2 = await page.request.post('/api/explore', { data: { planetId: planetB.id, leadCrewId: crew[0].id, helperCrewIds: [] } });
|
||||||
|
expect(res2.status()).toBe(200);
|
||||||
|
const q2 = (await res2.json()) as SystemStateQ;
|
||||||
|
expect(q2.turn).toBe(T);
|
||||||
|
expect(q2.tasks.find((t) => t.id === t1.id)!.status).toBe('ACTIVE');
|
||||||
|
const t2 = q2.tasks.find((t) => t.id !== t1.id && t.type === 'EXPLORE')!;
|
||||||
|
expect(t2.status).toBe('PENDING'); // the second is dimmed in the strip (Task 9) until it starts
|
||||||
|
const nb = t2.remaining; // its full duration — untouched until it starts
|
||||||
|
// The snapshot orders the ACTIVE block before the PENDING block (Task 6).
|
||||||
|
expect(q2.tasks.findIndex((t) => t.id === t1.id)).toBeLessThan(q2.tasks.findIndex((t) => t.id === t2.id));
|
||||||
|
|
||||||
|
// Tick until task 1 resolves — a loop keyed on its specific id (resolveAction's find-by-type would
|
||||||
|
// grab the earliest same-type row, which is the ambiguity two same-type rows create).
|
||||||
|
for (let k = 1; k < na; k++) {
|
||||||
|
await tickOnce(page);
|
||||||
|
const snap = (await (await page.request.get('/api/system')).json()) as SystemStateQ;
|
||||||
|
expect(snap.tasks.find((t) => t.id === t1.id)!.remaining).toBe(na - k); // the ACTIVE row decrements
|
||||||
|
expect(snap.tasks.find((t) => t.id === t2.id)!.status).toBe('PENDING'); // the second keeps waiting
|
||||||
|
}
|
||||||
|
// The na-th tick: task 1 resolves (filtered out of the snapshot), and task 2 auto-starts on that
|
||||||
|
// same tick — ACTIVE with its FULL remaining (the first decrement lands on the next tick).
|
||||||
|
await tickOnce(page);
|
||||||
|
const done = (await (await page.request.get('/api/system')).json()) as SystemStateQ;
|
||||||
|
expect(done.tasks.some((t) => t.id === t1.id)).toBe(false);
|
||||||
|
expect(done.tasks.find((t) => t.id === t2.id)!.status).toBe('ACTIVE');
|
||||||
|
expect(done.tasks.find((t) => t.id === t2.id)!.remaining).toBe(nb);
|
||||||
|
|
||||||
|
// Leave the queue clean for the next scenario: tick task 2 to completion.
|
||||||
|
for (let k = 0; k < nb; k++) await tickOnce(page);
|
||||||
|
const clean = (await (await page.request.get('/api/system')).json()) as SystemStateQ;
|
||||||
|
expect(clean.tasks.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('queueing a second JUMP while one is in transit is refused 409 (#44)', async ({ page }) => {
|
||||||
|
await drainQueue(page);
|
||||||
|
const world = (await (await page.request.get('/api/world')).json()) as WorldStateQ;
|
||||||
|
const currentId = world.systems.find((s) => s.current)!.id;
|
||||||
|
const edge = world.edges.find(([a, b]) => a === currentId || b === currentId)!;
|
||||||
|
const targetId = edge[0] === currentId ? edge[1] : edge[0];
|
||||||
|
const T = world.turn;
|
||||||
|
const { crew } = (await (await page.request.get('/api/crew')).json()) as { crew: CrewDto[]; tasks: QueueTaskDto[] };
|
||||||
|
expect(crew.length).toBeGreaterThanOrEqual(2);
|
||||||
|
|
||||||
|
const res = await page.request.post('/api/jump', { data: { systemId: targetId, leadCrewId: crew[0].id, helperCrewIds: [] } });
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const queued = (await res.json()) as WorldStateQ;
|
||||||
|
expect(queued.turn).toBe(T);
|
||||||
|
expect(queued.tasks.find((t) => t.type === 'JUMP')!.status).toBe('ACTIVE'); // in transit — and deliberately not ticked
|
||||||
|
|
||||||
|
// A second JUMP while the first is in transit — a different, free member, so the 409 is the
|
||||||
|
// global in-transit rule ("a jump is in transit — no new tasks can be queued" / "a jump is
|
||||||
|
// already queued"), not crew availability. (The UI variant and the full 409 matrix are
|
||||||
|
// unit-covered by Task 3 — this single API case is what e2e carries.)
|
||||||
|
const second = await page.request.post('/api/jump', { data: { systemId: targetId, leadCrewId: crew[1].id, helperCrewIds: [] } });
|
||||||
|
expect(second.status()).toBe(409);
|
||||||
|
expect(await second.text()).toMatch(/jump/i);
|
||||||
|
|
||||||
|
// The first is still in transit, untouched by the refused queue.
|
||||||
|
const still = (await (await page.request.get('/api/world')).json()) as WorldStateQ;
|
||||||
|
expect(still.turn).toBe(T);
|
||||||
|
expect(still.systems.find((s) => s.current)?.id).toBe(currentId);
|
||||||
|
expect(still.tasks.find((t) => t.type === 'JUMP')!.status).toBe('ACTIVE');
|
||||||
|
// The jump is left in transit on purpose (the scenario is about the blocked queue); the next
|
||||||
|
// scenario's drainQueue ticks it out before its empty-queue precondition.
|
||||||
|
});
|
||||||
|
|
||||||
|
test('NEXT TURN with an empty queue is a free skip — +1 turn, the strip stays hidden (#44)', async ({ page }) => {
|
||||||
|
await drainQueue(page);
|
||||||
|
const world = (await (await page.request.get('/api/world')).json()) as WorldStateQ;
|
||||||
|
expect(world.tasks.length).toBe(0); // the precondition: nothing queued
|
||||||
|
const T = world.turn;
|
||||||
|
|
||||||
|
await page.goto('/');
|
||||||
|
// The button's live counter shows the current turn; with an empty queue the strip renders nothing.
|
||||||
|
await expect(page.getByText(`TURN ${T}`, { exact: true })).toBeVisible();
|
||||||
|
await expect(page.getByText('ACTIVE TASKS', { exact: true })).toHaveCount(0);
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: 'NEXT TURN' }).click();
|
||||||
|
await expect(page.getByText(`TURN ${T + 1}`, { exact: true })).toBeVisible(); // the click is a real tick
|
||||||
|
await expect(page.getByText('ACTIVE TASKS', { exact: true })).toHaveCount(0); // a free skip queues no task
|
||||||
|
|
||||||
|
// API confirms the model: the turn advanced by exactly one and the queue is still empty.
|
||||||
|
const after = (await (await page.request.get('/api/world')).json()) as WorldStateQ;
|
||||||
|
expect(after.turn).toBe(T + 1);
|
||||||
|
expect(after.tasks.length).toBe(0);
|
||||||
|
});
|
||||||
|
|||||||
+20
-8
@@ -1,7 +1,7 @@
|
|||||||
import { execSync } from 'node:child_process';
|
import { execSync } from 'node:child_process';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { expect, test } from '@playwright/test';
|
import { expect, test } from '@playwright/test';
|
||||||
import { jumpToFreshSystem } from './helpers';
|
import { drainQueue, jumpToFreshSystem, resolveAction } from './helpers';
|
||||||
|
|
||||||
// Repo root — docker-compose.yml lives here; `docker compose restart` runs on
|
// Repo root — docker-compose.yml lives here; `docker compose restart` runs on
|
||||||
// this host (the test runner), browsers stay remote. CI points E2E_COMPOSE_ARGS at the
|
// this host (the test runner), browsers stay remote. CI points E2E_COMPOSE_ARGS at the
|
||||||
@@ -13,6 +13,11 @@ const composeArgs = process.env.E2E_COMPOSE_ARGS ?? '';
|
|||||||
interface PlanetDto { id: number; name: string; type: string; hazard: boolean; explored: boolean; parent: number | null }
|
interface PlanetDto { id: number; name: string; type: string; hazard: boolean; explored: boolean; parent: number | null }
|
||||||
interface SystemState { systemId: number; systemName: string; planets: PlanetDto[]; inventory: { kind: string; name: string; qty: number }[]; turn: number }
|
interface SystemState { systemId: number; systemName: string; planets: PlanetDto[]; inventory: { kind: string; name: string; qty: number }[]; turn: number }
|
||||||
interface CrewDto { id: number; name: string; role: string; traitGood: string; traitBad: string; origin: string }
|
interface CrewDto { id: number; name: string; role: string; traitGood: string; traitBad: string; origin: string }
|
||||||
|
// Mirrors the QueueDto of lib/game/save.ts — GET /api/crew is the {crew, tasks} object (Task 6 /
|
||||||
|
// JC-7): the queue's display shape (resolved names, no raw payload), ACTIVE block first, then
|
||||||
|
// PENDING, DONE filtered.
|
||||||
|
interface TaskDto { id: number; type: string; targetLabel: string; leadName: string; helperNames: string[]; remaining: number; status: string; leadCrewId: number; helperCrewIds: number[] }
|
||||||
|
interface CrewState { crew: CrewDto[]; tasks: TaskDto[] }
|
||||||
interface ShipSystemDto { id: number; type: string; level: number; capacity: number; built: boolean }
|
interface ShipSystemDto { id: number; type: string; level: number; capacity: number; built: boolean }
|
||||||
interface ShipState { systems: ShipSystemDto[]; inventory: { kind: string; name: string; qty: number }[]; turn: number }
|
interface ShipState { systems: ShipSystemDto[]; inventory: { kind: string; name: string; qty: number }[]; turn: number }
|
||||||
interface TechDto { id: number; slug: string; name: string; costKind: string; costQty: number; prereqs: string[]; effect: string; state: string; missingPrereqs: string[] }
|
interface TechDto { id: number; slug: string; name: string; costKind: string; costQty: number; prereqs: string[]; effect: string; state: string; missingPrereqs: string[] }
|
||||||
@@ -22,6 +27,10 @@ interface EventDto { id: number; turn: number; type: string; message: string; cr
|
|||||||
test('app survives a container restart (stack + volume persistence)', async ({ page }) => {
|
test('app survives a container restart (stack + volume persistence)', async ({ page }) => {
|
||||||
test.setTimeout(180_000);
|
test.setTimeout(180_000);
|
||||||
|
|
||||||
|
// Retry-safety: a failed earlier attempt may have left a row queued — an in-transit JUMP would
|
||||||
|
// 409 every new queue (lib/game/tasks.ts's in-transit rule), so drain before the baselines.
|
||||||
|
await drainQueue(page);
|
||||||
|
|
||||||
// Baseline: the app serves and reports its version.
|
// Baseline: the app serves and reports its version.
|
||||||
const resBefore = await page.request.get('/api/version');
|
const resBefore = await page.request.get('/api/version');
|
||||||
expect(resBefore.status()).toBe(200);
|
expect(resBefore.status()).toBe(200);
|
||||||
@@ -39,13 +48,15 @@ test('app survives a container restart (stack + volume persistence)', async ({ p
|
|||||||
sysBefore = (await (await page.request.get('/api/system')).json()) as SystemState;
|
sysBefore = (await (await page.request.get('/api/system')).json()) as SystemState;
|
||||||
}
|
}
|
||||||
const targetPlanet = sysBefore.planets.find((p) => !p.explored)!;
|
const targetPlanet = sysBefore.planets.find((p) => !p.explored)!;
|
||||||
const exploreRes = await page.request.post('/api/explore', { data: { planetId: targetPlanet.id } });
|
// The explore POST only queues — no turn bump, explored not yet flipped — so tick it to
|
||||||
expect(exploreRes.status()).toBe(200);
|
// completion and re-derive the baseline from the post-tick /api/system snapshot: the turn it
|
||||||
const sysExplored = (await exploreRes.json()) as SystemState;
|
// pins (compared after the restart) must be the resolved one, not the queue's.
|
||||||
|
const sysExplored = (await resolveAction(page, '/api/explore', { planetId: targetPlanet.id })) as SystemState;
|
||||||
|
expect(sysExplored.planets.find((p) => p.id === targetPlanet.id)?.explored).toBe(true); // the scan resolved before the baseline is pinned
|
||||||
|
|
||||||
// Crew baseline: the roster (starting crew + any finds so far) must survive too.
|
// Crew baseline: the roster (starting crew + any finds so far) must survive too.
|
||||||
const crewBefore = (await (await page.request.get('/api/crew')).json()) as CrewDto[];
|
const crewBefore = (await (await page.request.get('/api/crew')).json()) as CrewState;
|
||||||
expect(crewBefore.length).toBeGreaterThanOrEqual(2); // starting crew is always seeded
|
expect(crewBefore.crew.length).toBeGreaterThanOrEqual(2); // starting crew is always seeded
|
||||||
|
|
||||||
// Ship baseline: the systems (levels/capacities) + cargo hold must survive too.
|
// Ship baseline: the systems (levels/capacities) + cargo hold must survive too.
|
||||||
const shipBefore = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
const shipBefore = (await (await page.request.get('/api/ship')).json()) as ShipState;
|
||||||
@@ -95,8 +106,9 @@ test('app survives a container restart (stack + volume persistence)', async ({ p
|
|||||||
expect(sysAfter.turn).toBe(sysExplored.turn);
|
expect(sysAfter.turn).toBe(sysExplored.turn);
|
||||||
expect(sysAfter.planets.find((p) => p.id === targetPlanet.id)?.explored).toBe(true);
|
expect(sysAfter.planets.find((p) => p.id === targetPlanet.id)?.explored).toBe(true);
|
||||||
|
|
||||||
// Crew roster survived too: same members, traits and origins (no re-seed on restart).
|
// Crew roster survived too: same members, traits and origins (no re-seed on restart). The
|
||||||
const crewAfter = (await (await page.request.get('/api/crew')).json()) as CrewDto[];
|
// {crew, tasks} object shape (JC-7) means the still-queued task rows survive with it too.
|
||||||
|
const crewAfter = (await (await page.request.get('/api/crew')).json()) as CrewState;
|
||||||
expect(crewAfter).toEqual(crewBefore);
|
expect(crewAfter).toEqual(crewBefore);
|
||||||
|
|
||||||
// Ship state survived too: same systems, levels/capacities and cargo hold.
|
// Ship state survived too: same systems, levels/capacities and cargo hold.
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ export const ADMIN_TABLES = {
|
|||||||
tech: schema.tech,
|
tech: schema.tech,
|
||||||
missions: schema.missions,
|
missions: schema.missions,
|
||||||
events: schema.events,
|
events: schema.events,
|
||||||
|
tasks: schema.tasks,
|
||||||
} as const satisfies Record<string, SQLiteTable>
|
} as const satisfies Record<string, SQLiteTable>
|
||||||
|
|
||||||
const TABLE_NAMES: Set<string> = new Set(Object.values(ADMIN_TABLES).map((t) => getTableName(t)))
|
const TABLE_NAMES: Set<string> = new Set(Object.values(ADMIN_TABLES).map((t) => getTableName(t)))
|
||||||
|
|||||||
@@ -116,6 +116,19 @@ CREATE TABLE IF NOT EXISTS events (
|
|||||||
message TEXT NOT NULL,
|
message TEXT NOT NULL,
|
||||||
created_at TEXT NOT NULL
|
created_at TEXT NOT NULL
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS tasks (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
save_id INTEGER NOT NULL REFERENCES saves(id),
|
||||||
|
type TEXT NOT NULL, -- 'JUMP' | 'EXPLORE' | 'SHIP_UPGRADE' | 'SHIP_EXPAND' | 'SHIP_BUILD' | 'RESEARCH'
|
||||||
|
payload TEXT NOT NULL, -- JSON per type: JUMP {systemId, hops} · SHIP_UPGRADE/EXPAND {systemId} · SHIP_BUILD {type} · RESEARCH {techId} · EXPLORE {planetId}
|
||||||
|
lead_crew_id INTEGER NOT NULL REFERENCES crew(id),
|
||||||
|
helpers TEXT NOT NULL DEFAULT '[]', -- JSON array of crew ids
|
||||||
|
duration INTEGER NOT NULL,
|
||||||
|
remaining INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'ACTIVE', -- 'ACTIVE' | 'PENDING' | 'DONE'
|
||||||
|
queued_at_turn INTEGER NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
// SPACE_WANDERER_DB_PATH override exists so unit tests can point at a temp file instead
|
// SPACE_WANDERER_DB_PATH override exists so unit tests can point at a temp file instead
|
||||||
|
|||||||
@@ -136,3 +136,20 @@ export const events = sqliteTable('events', {
|
|||||||
message: text('message').notNull(),
|
message: text('message').notNull(),
|
||||||
createdAt: text('created_at').notNull(),
|
createdAt: text('created_at').notNull(),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Queued actions (PR A, spec §3): one row per task assigned to a team. `payload` is a JSON
|
||||||
|
// string whose shape depends on `type` (see the Task interface in lib/game/tasks.ts);
|
||||||
|
// `helpers` is a JSON array of crew ids. Upgraded saves start with an empty queue — the v7
|
||||||
|
// backfill stamps the version, the DDL in client.ts creates the table.
|
||||||
|
export const tasks = sqliteTable('tasks', {
|
||||||
|
id: integer('id').primaryKey({ autoIncrement: true }),
|
||||||
|
saveId: integer('save_id').notNull().references(() => saves.id),
|
||||||
|
type: text('type').notNull(), // TaskType
|
||||||
|
payload: text('payload').notNull(),
|
||||||
|
leadCrewId: integer('lead_crew_id').notNull().references(() => crew.id),
|
||||||
|
helpers: text('helpers').notNull().default('[]'), // JSON array of crew ids
|
||||||
|
duration: integer('duration').notNull(),
|
||||||
|
remaining: integer('remaining').notNull(),
|
||||||
|
status: text('status').notNull().default('ACTIVE'), // 'ACTIVE' | 'PENDING' | 'DONE'
|
||||||
|
queuedAtTurn: integer('queued_at_turn').notNull().default(0),
|
||||||
|
})
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
// Pure crew-balance module (spec §11): every tuning knob for the duration model and skill
|
||||||
|
// progression lives here, so tuning a number means editing one file. No lib/db imports —
|
||||||
|
// the frontend imports this for the live duration preview in the crew picker (same precedent
|
||||||
|
// as ship-costs.ts).
|
||||||
|
import type { TaskType } from './tasks'
|
||||||
|
|
||||||
|
export type SkillName = 'NAVIGATION' | 'SCANNING' | 'ENGINEERING' | 'RESEARCH'
|
||||||
|
|
||||||
|
export const WORK_POINTS = { EXPLORE: 4, JUMP_PER_HOP: 3, SHIP_WORK: 6, RESEARCH: 9 } as const
|
||||||
|
|
||||||
|
export const ACTION_SKILL: Record<TaskType, SkillName> = {
|
||||||
|
JUMP: 'NAVIGATION',
|
||||||
|
EXPLORE: 'SCANNING',
|
||||||
|
SHIP_UPGRADE: 'ENGINEERING',
|
||||||
|
SHIP_EXPAND: 'ENGINEERING',
|
||||||
|
SHIP_BUILD: 'ENGINEERING',
|
||||||
|
RESEARCH: 'RESEARCH',
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PREFERRED_ROLES: Record<TaskType, string[]> = {
|
||||||
|
JUMP: ['PILOT', 'NAVIGATOR'],
|
||||||
|
EXPLORE: ['SCIENTIST'],
|
||||||
|
SHIP_UPGRADE: ['ENGINEER', 'TECHNICIAN'],
|
||||||
|
SHIP_EXPAND: ['ENGINEER', 'TECHNICIAN'],
|
||||||
|
SHIP_BUILD: ['ENGINEER', 'TECHNICIAN'],
|
||||||
|
RESEARCH: ['SCIENTIST'],
|
||||||
|
}
|
||||||
|
|
||||||
|
export const POWER_BANDS = [1, 1, 1, 2, 2, 3] // skill level 0..5 → power (L0–L2 → 1 · L3–L4 → 2 · L5 → 3)
|
||||||
|
export const XP_THRESHOLDS = [5, 10, 15, 20, 25] // cumulative task completions for L1..L5 (cap 5)
|
||||||
|
|
||||||
|
// Role → starting skill levels (spec §6): specialists start at L2, everyone else at L0.
|
||||||
|
export const STARTING_LEVELS: Record<string, Record<SkillName, number>> = {
|
||||||
|
COMMANDER: { NAVIGATION: 0, SCANNING: 0, ENGINEERING: 0, RESEARCH: 0 },
|
||||||
|
PILOT: { NAVIGATION: 2, SCANNING: 0, ENGINEERING: 0, RESEARCH: 0 },
|
||||||
|
ENGINEER: { NAVIGATION: 0, SCANNING: 0, ENGINEERING: 2, RESEARCH: 0 },
|
||||||
|
MEDIC: { NAVIGATION: 0, SCANNING: 0, ENGINEERING: 0, RESEARCH: 0 },
|
||||||
|
NAVIGATOR: { NAVIGATION: 2, SCANNING: 0, ENGINEERING: 0, RESEARCH: 0 },
|
||||||
|
SCIENTIST: { NAVIGATION: 0, SCANNING: 2, ENGINEERING: 0, RESEARCH: 2 },
|
||||||
|
GUNNER: { NAVIGATION: 0, SCANNING: 0, ENGINEERING: 0, RESEARCH: 0 },
|
||||||
|
TECHNICIAN: { NAVIGATION: 0, SCANNING: 0, ENGINEERING: 2, RESEARCH: 0 },
|
||||||
|
}
|
||||||
|
|
||||||
|
// The lead's good trait that cancels the role-mismatch penalty (spec §5).
|
||||||
|
export const MISMATCH_CANCEL_TRAIT = 'STEADY UNDER PRESSURE'
|
||||||
|
|
||||||
|
// All 15 duration traits of spec §5, keyed by the EXACT trait strings from lib/game/crew.ts.
|
||||||
|
// Value = additive turn modifier keyed by action type or 'ANY'; empty object = no additive
|
||||||
|
// modifier (the trait's effect is the mismatch cancel, see MISMATCH_CANCEL_TRAIT). Traits
|
||||||
|
// with no entry (the three STANDBY combat traits and #45's outcome traits) contribute 0.
|
||||||
|
// "SHIP work" covers all three SHIP types.
|
||||||
|
export const TRAIT_DURATION_MODIFIERS: Record<string, Partial<Record<TaskType | 'ANY', number>>> = {
|
||||||
|
'STEADY UNDER PRESSURE': {},
|
||||||
|
'RECKLESS COURAGE': { JUMP: -1 },
|
||||||
|
'CALM IN A CRISIS': { EXPLORE: -1 },
|
||||||
|
'FIXES ANYTHING': { SHIP_UPGRADE: -1, SHIP_EXPAND: -1, SHIP_BUILD: -1 },
|
||||||
|
'READS STARS BLIND': { JUMP: -1 },
|
||||||
|
'QUICK HANDS': { ANY: -1 },
|
||||||
|
'IRON WILL': { RESEARCH: -1 },
|
||||||
|
'RIGID — SLOW TO ADAPT': { RESEARCH: 1 },
|
||||||
|
'OVERCAUTIOUS': { ANY: 1 },
|
||||||
|
'SLOWS THE CREW DOWN': { ANY: 1 },
|
||||||
|
'CARELESS WITH FUSES': { SHIP_UPGRADE: 1, SHIP_EXPAND: 1, SHIP_BUILD: 1 },
|
||||||
|
'HOARDS RATIONS': { SHIP_UPGRADE: 1, SHIP_EXPAND: 1, SHIP_BUILD: 1 },
|
||||||
|
'FORGETS TO EAT': { EXPLORE: 1 },
|
||||||
|
'ARGUES WITH EVERYONE': { RESEARCH: 1 },
|
||||||
|
'DOUBTS THE CAPTAIN': { JUMP: 1 },
|
||||||
|
}
|
||||||
|
|
||||||
|
export const RECRUIT_CHANCE_BASE = 0.18 // a scan finds a joining member (matches crew.ts's current CREW_CHANCE)
|
||||||
|
export const RECRUIT_CHANCE_TALKER = 0.3 // lead with TALKS TO ANYONE (wired in PR C)
|
||||||
@@ -40,6 +40,11 @@ const STARTING_CREW_MIN = 2
|
|||||||
const STARTING_CREW_SPREAD = 2 // 2..3 starting members
|
const STARTING_CREW_SPREAD = 2 // 2..3 starting members
|
||||||
export const CREW_CHANCE = 0.18 // a scan finds a crew member who joins the ship (~1 in 5-6 scans)
|
export const CREW_CHANCE = 0.18 // a scan finds a crew member who joins the ship (~1 in 5-6 scans)
|
||||||
|
|
||||||
|
// A task team is one lead plus up to this many members total — the queueing routes reject
|
||||||
|
// a bigger team with a 400 (spec §3 leaves the cap to balance; 4 lets a full crew bring
|
||||||
|
// RESEARCH's 9 work points down to 3 turns, matching a solo L5 specialist).
|
||||||
|
export const MAX_TEAM_SIZE = 4
|
||||||
|
|
||||||
function title(word: string): string {
|
function title(word: string): string {
|
||||||
return word.charAt(0) + word.slice(1).toLowerCase()
|
return word.charAt(0) + word.slice(1).toLowerCase()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -138,7 +138,7 @@ describe('acceptMission', () => {
|
|||||||
await expect(acceptMission(db, b.id)).rejects.toMatchObject({ status: 409, message: /One mission at a time/ })
|
await expect(acceptMission(db, b.id)).rejects.toMatchObject({ status: 409, message: /One mission at a time/ })
|
||||||
})
|
})
|
||||||
|
|
||||||
it('activates an AVAILABLE contract, costs a turn, writes an event and keeps the board topped up', async () => {
|
it('activates an AVAILABLE contract, spends no turn, writes an event and keeps the board topped up', async () => {
|
||||||
const { db } = await freshFile()
|
const { db } = await freshFile()
|
||||||
await getWorldState(db)
|
await getWorldState(db)
|
||||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
@@ -149,11 +149,11 @@ describe('acceptMission', () => {
|
|||||||
expect(board.find((m) => m.id === a.id)!.state).toBe('ACTIVE')
|
expect(board.find((m) => m.id === a.id)!.state).toBe('ACTIVE')
|
||||||
expect(board.filter((m) => m.state === 'AVAILABLE').length).toBeGreaterThanOrEqual(MIN_AVAILABLE) // topped back up
|
expect(board.filter((m) => m.state === 'AVAILABLE').length).toBeGreaterThanOrEqual(MIN_AVAILABLE) // topped back up
|
||||||
const [after] = await db.db.select().from(schema.saves).limit(1)
|
const [after] = await db.db.select().from(schema.saves).limit(1)
|
||||||
expect(after.turn).toBe(save.turn + 1)
|
expect(after.turn).toBe(save.turn) // free — no turn cost
|
||||||
|
|
||||||
const event = (await db.db.select().from(schema.events)).find((e) => e.type === 'mission')!
|
const event = (await db.db.select().from(schema.events)).find((e) => e.type === 'mission')!
|
||||||
expect(event.message).toContain('Accepted mission')
|
expect(event.message).toContain('Accepted mission')
|
||||||
expect(event.turn).toBe(save.turn + 1)
|
expect(event.turn).toBe(save.turn) // stamped at the current turn — accept spends none
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -185,7 +185,7 @@ describe('completion', () => {
|
|||||||
expect(reward.qty).toBe(2)
|
expect(reward.qty).toBe(2)
|
||||||
|
|
||||||
const event = (await db.db.select().from(schema.events)).find((e) => e.type === 'mission' && /complete/i.test(e.message))!
|
const event = (await db.db.select().from(schema.events)).find((e) => e.type === 'mission' && /complete/i.test(e.message))!
|
||||||
expect(event.turn).toBe(4) // accept (1) + three scans (2–4); completion is written by the third scan
|
expect(event.turn).toBe(3) // free accept (turn 0) + three scans (1–3); completion is written by the third scan
|
||||||
expect(event.message).toContain('Scan 3 bodies')
|
expect(event.message).toContain('Scan 3 bodies')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
+10
-7
@@ -34,8 +34,12 @@ export interface MissionSystem {
|
|||||||
isCurrent: boolean
|
isCurrent: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deterministic per (seed, turn) — same anchoring style as world expansion in save.ts. Every
|
// Deterministic per (seed, turn) — same anchoring style as world expansion in save.ts.
|
||||||
// action costs exactly one turn, so the stream never repeats for two different top-ups.
|
// Turn-advancing actions re-anchor the stream, so top-ups on different turns generate
|
||||||
|
// different contracts. Mission accept is free and tops up at the current turn, so it may
|
||||||
|
// share an anchor with a top-up that already ran at that turn (e.g. the new-game seed at
|
||||||
|
// turn 0) — the generated contract can then mirror an existing one: cosmetic, never a
|
||||||
|
// double reward (rewards are per row).
|
||||||
export function missionRng(seed: string, turn: number): () => number {
|
export function missionRng(seed: string, turn: number): () => number {
|
||||||
return mulberry32((Number(seed) + Math.imul(turn, 0x9e3779b1)) >>> 0)
|
return mulberry32((Number(seed) + Math.imul(turn, 0x9e3779b1)) >>> 0)
|
||||||
}
|
}
|
||||||
@@ -152,8 +156,9 @@ export const REWARD_ITEM_NAME = 'MISSION REWARD'
|
|||||||
|
|
||||||
const kindLabel = (kind: ItemKind): string => (kind === 'resource' ? 'RESOURCES' : 'PARTS')
|
const kindLabel = (kind: ItemKind): string => (kind === 'resource' ? 'RESOURCES' : 'PARTS')
|
||||||
|
|
||||||
// Accepts an AVAILABLE contract: it becomes THE active mission (one at a time), costs a turn like
|
// Accepts an AVAILABLE contract: it becomes THE active mission (one at a time). Instant and
|
||||||
// every other action and writes an event. Returns the fresh board.
|
// free (JC-19) — no turn, no cost; the event is stamped at the current turn. Returns the fresh
|
||||||
|
// board.
|
||||||
export async function acceptMission(db: GameDb, missionId: number): Promise<MissionDto[]> {
|
export async function acceptMission(db: GameDb, missionId: number): Promise<MissionDto[]> {
|
||||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
if (!save) throw new MissionError(404, 'No save yet')
|
if (!save) throw new MissionError(404, 'No save yet')
|
||||||
@@ -164,10 +169,8 @@ export async function acceptMission(db: GameDb, missionId: number): Promise<Miss
|
|||||||
const active = rows.find((m) => m.state === 'ACTIVE')
|
const active = rows.find((m) => m.state === 'ACTIVE')
|
||||||
if (active) throw new MissionError(409, `One mission at a time — finish "${active.description}" first`)
|
if (active) throw new MissionError(409, `One mission at a time — finish "${active.description}" first`)
|
||||||
|
|
||||||
const turn = save.turn + 1
|
|
||||||
await db.db.update(schema.missions).set({ state: 'ACTIVE' }).where(eq(schema.missions.id, target.id))
|
await db.db.update(schema.missions).set({ state: 'ACTIVE' }).where(eq(schema.missions.id, target.id))
|
||||||
await db.db.update(schema.saves).set({ turn }).where(eq(schema.saves.id, save.id))
|
await db.db.insert(schema.events).values({ saveId: save.id, turn: save.turn, type: 'mission', message: `Accepted mission — ${target.description}`, createdAt: new Date().toISOString() })
|
||||||
await db.db.insert(schema.events).values({ saveId: save.id, turn, type: 'mission', message: `Accepted mission — ${target.description}`, createdAt: new Date().toISOString() })
|
|
||||||
await topUpMissionBoard(db) // one contract left the AVAILABLE list — keep the board topped up
|
await topUpMissionBoard(db) // one contract left the AVAILABLE list — keep the board topped up
|
||||||
await persist(db)
|
await persist(db)
|
||||||
|
|
||||||
|
|||||||
@@ -6,9 +6,11 @@ import { eq } from 'drizzle-orm'
|
|||||||
import { openGameDb, type GameDb } from '@/lib/db/client'
|
import { openGameDb, type GameDb } from '@/lib/db/client'
|
||||||
import * as schema from '@/lib/db/schema'
|
import * as schema from '@/lib/db/schema'
|
||||||
import { BUILD_PART_COST, MAX_LEVEL, upgradeCost } from './ship-costs'
|
import { BUILD_PART_COST, MAX_LEVEL, upgradeCost } from './ship-costs'
|
||||||
import { buildSystem, getShipState, upgradeSystem, type ShipState } from './ship'
|
import { buildSystem, getShipState, spendItems, upgradeSystem, type ShipState } from './ship'
|
||||||
import { TECHS } from './tech'
|
import { TECHS } from './tech'
|
||||||
import { getTechState, researchTech } from './research'
|
import { SCHEMA_VERSION } from './save'
|
||||||
|
import { getTechState, researchTech, resolveResearchTask } from './research'
|
||||||
|
import type { Task } from './tasks'
|
||||||
|
|
||||||
const dirs: string[] = []
|
const dirs: string[] = []
|
||||||
|
|
||||||
@@ -145,3 +147,74 @@ describe('gating of ship actions', () => {
|
|||||||
expect(systemOf(state, 'REACTOR').level).toBe(MAX_LEVEL + 1)
|
expect(systemOf(state, 'REACTOR').level).toBe(MAX_LEVEL + 1)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// --- A/B: resolver vs the legacy immediate action (Task 4a) ---------------------------
|
||||||
|
const T0 = '2026-10-01T00:00:00.000Z'
|
||||||
|
|
||||||
|
// Stamped save (no backfill), the full tech tree, nothing researched yet. Identical build
|
||||||
|
// per world → ids line up.
|
||||||
|
async function buildResearchFixture(db: GameDb): Promise<void> {
|
||||||
|
const [save] = await db.db.insert(schema.saves).values({ seed: '42', turn: 0, createdAt: T0, schemaVersion: SCHEMA_VERSION }).returning()
|
||||||
|
for (const def of TECHS) {
|
||||||
|
await db.db.insert(schema.tech).values({ saveId: save.id, slug: def.slug, name: def.name, costKind: def.costKind, costQty: def.costQty, prerequisites: def.prereqs.join(','), effect: def.effect })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const task = (payload: object): Task =>
|
||||||
|
({ id: 0, saveId: 0, type: 'RESEARCH', payload: JSON.stringify(payload), leadCrewId: 0, helpers: [], duration: 0, remaining: 0, status: 'ACTIVE', queuedAtTurn: 0 })
|
||||||
|
|
||||||
|
async function snapshot(db: GameDb): Promise<string> {
|
||||||
|
const [saves, systems, routes, planets, inventory, crew, ship, tech, missions, events] = await Promise.all([
|
||||||
|
db.db.select({ id: schema.saves.id, seed: schema.saves.seed, turn: schema.saves.turn, schemaVersion: schema.saves.schemaVersion }).from(schema.saves),
|
||||||
|
db.db.select().from(schema.solarSystems),
|
||||||
|
db.db.select().from(schema.jumpRoutes),
|
||||||
|
db.db.select().from(schema.planets),
|
||||||
|
db.db.select().from(schema.inventoryItems),
|
||||||
|
db.db.select().from(schema.crew),
|
||||||
|
db.db.select().from(schema.shipSystems),
|
||||||
|
db.db.select().from(schema.tech),
|
||||||
|
db.db.select().from(schema.missions),
|
||||||
|
db.db.select({ id: schema.events.id, turn: schema.events.turn, type: schema.events.type, message: schema.events.message }).from(schema.events),
|
||||||
|
])
|
||||||
|
return JSON.stringify({ saves, systems, routes, planets, inventory, crew, ship, tech, missions, events })
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('resolveResearchTask (A/B against researchTech)', () => {
|
||||||
|
// A = legacy immediate action (validates, deducts the cost, +1 turn, marks researched,
|
||||||
|
// event). B = the queued shape: the cost was deducted at queue time (Task 3), the tick
|
||||||
|
// advanced the turn (Task 4b), then the resolver marks the tech. Same starting world →
|
||||||
|
// byte-identical end states.
|
||||||
|
|
||||||
|
it('lands exactly what researchTech lands', async () => {
|
||||||
|
const { db: a } = await freshFile()
|
||||||
|
const { db: b } = await freshFile()
|
||||||
|
await buildResearchFixture(a)
|
||||||
|
await buildResearchFixture(b)
|
||||||
|
await addItem(a, 'resource', 'IRON ORE', 2) // NAVIGATION AI costs 2 resources
|
||||||
|
await addItem(b, 'resource', 'IRON ORE', 2)
|
||||||
|
|
||||||
|
const [navA] = await a.db.select().from(schema.tech).where(eq(schema.tech.slug, 'NAV_AI'))
|
||||||
|
const [navB] = await b.db.select().from(schema.tech).where(eq(schema.tech.slug, 'NAV_AI'))
|
||||||
|
await researchTech(a, navA.id)
|
||||||
|
await spendItems(b, 1, 'resource', 2) // the queue-time deduction
|
||||||
|
await b.db.update(schema.saves).set({ turn: 1 }).where(eq(schema.saves.id, 1))
|
||||||
|
await resolveResearchTask(b, task({ techId: navB.id }))
|
||||||
|
|
||||||
|
expect(await snapshot(b)).toEqual(await snapshot(a))
|
||||||
|
expect((await b.db.select().from(schema.tech)).find((t) => t.id === navB.id)?.researched).toBe(true)
|
||||||
|
const ev = (await b.db.select({ turn: schema.events.turn, type: schema.events.type, message: schema.events.message }).from(schema.events)).find((e) => e.type === 'research')!
|
||||||
|
expect(ev.turn).toBe(1)
|
||||||
|
expect(ev.message).toBe('Researched NAVIGATION AI (cost: 2× resources)')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('guards: 404 unknown tech, 409 already researched (prereqs are monotone — no guard needed)', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildResearchFixture(db)
|
||||||
|
const [nav] = await db.db.select().from(schema.tech).where(eq(schema.tech.slug, 'NAV_AI'))
|
||||||
|
await db.db.update(schema.saves).set({ turn: 1 }).where(eq(schema.saves.id, 1))
|
||||||
|
|
||||||
|
await expect(resolveResearchTask(db, task({ techId: 999 }))).rejects.toMatchObject({ status: 404, message: 'Unknown tech 999' })
|
||||||
|
await resolveResearchTask(db, task({ techId: nav.id }))
|
||||||
|
await expect(resolveResearchTask(db, task({ techId: nav.id }))).rejects.toMatchObject({ status: 409, message: 'NAVIGATION AI is already researched' })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
+43
-4
@@ -4,6 +4,7 @@ import { persist, type GameDb } from '@/lib/db/client'
|
|||||||
import { EFFECTS, TECHS, techStatus, type TechDto } from './tech'
|
import { EFFECTS, TECHS, techStatus, type TechDto } from './tech'
|
||||||
import { ensureSave } from './save'
|
import { ensureSave } from './save'
|
||||||
import { ShipError, spendItems } from './ship'
|
import { ShipError, spendItems } from './ship'
|
||||||
|
import type { Task, TaskType } from './tasks'
|
||||||
|
|
||||||
// Technology research: the SKILL TREE tab's read + action. Researching a tech costs inventory
|
// Technology research: the SKILL TREE tab's read + action. Researching a tech costs inventory
|
||||||
// items (oldest row first, like ship actions) plus a turn, and its unlock effect then gates or
|
// items (oldest row first, like ship actions) plus a turn, and its unlock effect then gates or
|
||||||
@@ -46,8 +47,48 @@ export async function getTechState(db: GameDb): Promise<TechDto[]> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function syntheticTask(type: TaskType, payload: object): Task {
|
||||||
|
return { id: 0, saveId: 0, type, payload: JSON.stringify(payload), leadCrewId: 0, helpers: [], duration: 0, remaining: 0, status: 'ACTIVE', queuedAtTurn: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
// RESEARCH — mark the payload's tech researched at the current turn. No cost here (deducted
|
||||||
|
// at queue time — Task 3 — or by researchTech before delegating); no mission hooks (the
|
||||||
|
// current action has none).
|
||||||
|
export async function resolveResearchTask(db: GameDb, task: Task): Promise<void> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const { techId } = JSON.parse(task.payload) as { techId: number }
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const rows = await db.db.select().from(schema.tech)
|
||||||
|
const target = rows.find((t) => t.id === techId)
|
||||||
|
if (!target) throw new ResearchError(404, `Unknown tech ${techId}`)
|
||||||
|
|
||||||
|
const def = TECHS.find((t) => t.slug === target.slug)!
|
||||||
|
if (target.researched) throw new ResearchError(409, `${def.name} is already researched`)
|
||||||
|
|
||||||
|
await db.db.update(schema.tech).set({ researched: true }).where(eq(schema.tech.id, target.id))
|
||||||
|
await db.db.insert(schema.events).values({ saveId: save.id, turn: save.turn, type: 'research', message: `Researched ${def.name} (cost: ${def.costQty}× ${def.costKind === 'resource' ? 'resources' : 'parts'})`, createdAt: new Date().toISOString() })
|
||||||
|
await persist(db)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The research pre-checks, extracted for the queueing route (5a(ii)): the same codes and
|
||||||
|
// messages as researchTech — unknown tech (404), already researched (409), missing prereqs
|
||||||
|
// (409, naming what is missing). The cost check stays out: the queueing path deducts at
|
||||||
|
// queue time (queueTask) and the research lands when the task completes on the tick.
|
||||||
|
export async function checkResearchPreconditions(db: GameDb, techId: number): Promise<void> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const rows = await db.db.select().from(schema.tech)
|
||||||
|
const target = rows.find((t) => t.id === techId)
|
||||||
|
if (!target) throw new ResearchError(404, `Unknown tech ${techId}`)
|
||||||
|
|
||||||
|
const def = TECHS.find((t) => t.slug === target.slug)!
|
||||||
|
const researched = await researchedSlugs(db)
|
||||||
|
if (researched.has(def.slug)) throw new ResearchError(409, `${def.name} is already researched`)
|
||||||
|
const missing = def.prereqs.filter((p) => !researched.has(p)).map((slug) => TECHS.find((t) => t.slug === slug)?.name ?? slug)
|
||||||
|
if (missing.length > 0) throw new ResearchError(409, `${def.name} requires ${missing.join(' and ')} first`)
|
||||||
|
}
|
||||||
|
|
||||||
// Research one tech: validates prerequisites (409, naming what is missing) and the cost (422),
|
// Research one tech: validates prerequisites (409, naming what is missing) and the cost (422),
|
||||||
// spends it from the cargo hold, marks it researched, costs a turn and writes an event.
|
// spends it from the cargo hold, then delegates the unlock to the resolver at the new turn.
|
||||||
export async function researchTech(db: GameDb, techId: number): Promise<TechDto[]> {
|
export async function researchTech(db: GameDb, techId: number): Promise<TechDto[]> {
|
||||||
await ensureSave(db)
|
await ensureSave(db)
|
||||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
@@ -70,10 +111,8 @@ export async function researchTech(db: GameDb, techId: number): Promise<TechDto[
|
|||||||
}
|
}
|
||||||
|
|
||||||
const turn = save.turn + 1
|
const turn = save.turn + 1
|
||||||
await db.db.update(schema.tech).set({ researched: true }).where(eq(schema.tech.id, target.id))
|
|
||||||
await db.db.update(schema.saves).set({ turn }).where(eq(schema.saves.id, save.id))
|
await db.db.update(schema.saves).set({ turn }).where(eq(schema.saves.id, save.id))
|
||||||
await db.db.insert(schema.events).values({ saveId: save.id, turn, type: 'research', message: `Researched ${def.name} (cost: ${def.costQty}× ${def.costKind === 'resource' ? 'resources' : 'parts'})`, createdAt: new Date().toISOString() })
|
await resolveResearchTask(db, syntheticTask('RESEARCH', { techId }))
|
||||||
await persist(db)
|
|
||||||
|
|
||||||
return getTechState(db)
|
return getTechState(db)
|
||||||
}
|
}
|
||||||
|
|||||||
+360
-5
@@ -6,9 +6,12 @@ import { eq } from 'drizzle-orm'
|
|||||||
import { openGameDb, type GameDb } from '@/lib/db/client'
|
import { openGameDb, type GameDb } from '@/lib/db/client'
|
||||||
import * as schema from '@/lib/db/schema'
|
import * as schema from '@/lib/db/schema'
|
||||||
import { generateStartingCrew, rollCrewMember, startingCrewRng } from './crew'
|
import { generateStartingCrew, rollCrewMember, startingCrewRng } from './crew'
|
||||||
|
import { MIN_AVAILABLE } from './missions'
|
||||||
import { BASE_CAPACITY, BASE_LEVEL, SHIP_TYPES } from './ship-costs'
|
import { BASE_CAPACITY, BASE_LEVEL, SHIP_TYPES } from './ship-costs'
|
||||||
import { TECHS } from './tech'
|
import { TECHS } from './tech'
|
||||||
import { SCHEMA_VERSION, getCrewState, getSystemState, explorePlanet, getWorldState, jumpToSystem, type WorldState } from './save'
|
import { SCHEMA_VERSION, getCrewState, getSystemState, explorePlanet, getWorldState, jumpToSystem, resolveJumpTask, resolveExploreTask, runTurn, type WorldState } from './save'
|
||||||
|
import { addCrew, buildWorldFixture, insertTaskRow } from './test-fixtures'
|
||||||
|
import type { Task } from './tasks'
|
||||||
import { bodyRng, explorationRng, generatePlanets, rollExploration } from './world'
|
import { bodyRng, explorationRng, generatePlanets, rollExploration } from './world'
|
||||||
|
|
||||||
const dirs: string[] = []
|
const dirs: string[] = []
|
||||||
@@ -236,7 +239,7 @@ describe('explorePlanet', () => {
|
|||||||
describe('getCrewState', () => {
|
describe('getCrewState', () => {
|
||||||
it('seeds a starting crew of 2–3 members derived from the save seed', async () => {
|
it('seeds a starting crew of 2–3 members derived from the save seed', async () => {
|
||||||
const { db } = await freshFile()
|
const { db } = await freshFile()
|
||||||
const crew = await getCrewState(db) // ensureSave runs inside, so this also seeds the crew
|
const crew = (await getCrewState(db)).crew // ensureSave runs inside, so this also seeds the crew (the roster moved under .crew — JC-7)
|
||||||
|
|
||||||
expect(crew.length).toBeGreaterThanOrEqual(2)
|
expect(crew.length).toBeGreaterThanOrEqual(2)
|
||||||
expect(crew.length).toBeLessThanOrEqual(3)
|
expect(crew.length).toBeLessThanOrEqual(3)
|
||||||
@@ -282,7 +285,7 @@ describe('explorePlanet crew finds', () => {
|
|||||||
await db.db.insert(schema.planets).values({ systemId: sys.id, parentId: null, name: `P${i}`, type: 'ROCKY', hazard: false })
|
await db.db.insert(schema.planets).values({ systemId: sys.id, parentId: null, name: `P${i}`, type: 'ROCKY', hazard: false })
|
||||||
}
|
}
|
||||||
|
|
||||||
const before = await getCrewState(db) // empty — this save was hand-built, no starting crew seeded
|
const before = (await getCrewState(db)).crew // empty — this save was hand-built, no starting crew seeded
|
||||||
const result = await explorePlanet(db, crewPlanetId)
|
const result = await explorePlanet(db, crewPlanetId)
|
||||||
|
|
||||||
expect(result.crewFound).not.toBeNull()
|
expect(result.crewFound).not.toBeNull()
|
||||||
@@ -294,13 +297,342 @@ describe('explorePlanet crew finds', () => {
|
|||||||
expect([result.crewFound!.traitGood, result.crewFound!.traitBad]).toEqual([expectedMember.traitGood, expectedMember.traitBad])
|
expect([result.crewFound!.traitGood, result.crewFound!.traitBad]).toEqual([expectedMember.traitGood, expectedMember.traitBad])
|
||||||
expect(result.crewFound!.origin).toBe(`${planetName}, Test System`)
|
expect(result.crewFound!.origin).toBe(`${planetName}, Test System`)
|
||||||
|
|
||||||
const after = await getCrewState(db)
|
const after = (await getCrewState(db)).crew
|
||||||
expect(after.length).toBe(before.length + 1) // exactly one join
|
expect(after.length).toBe(before.length + 1) // exactly one join
|
||||||
expect(after.find((c) => c.id === result.crewFound!.id)).toMatchObject({ name: expectedMember.name, origin: `${planetName}, Test System` })
|
expect(after.find((c) => c.id === result.crewFound!.id)).toMatchObject({ name: expectedMember.name, origin: `${planetName}, Test System` })
|
||||||
|
|
||||||
// The body is already explored → a second scan is rejected and no duplicate joins.
|
// The body is already explored → a second scan is rejected and no duplicate joins.
|
||||||
await expect(explorePlanet(db, crewPlanetId)).rejects.toMatchObject({ status: 409 })
|
await expect(explorePlanet(db, crewPlanetId)).rejects.toMatchObject({ status: 409 })
|
||||||
expect((await getCrewState(db)).length).toBe(before.length + 1)
|
expect((await getCrewState(db)).crew.length).toBe(before.length + 1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- A/B: resolvers vs the legacy immediate actions (Task 4a) -------------------------
|
||||||
|
//
|
||||||
|
// Each test builds the identical deterministic fixture (buildWorldFixture — the shared
|
||||||
|
// fixture suite in ./test-fixtures: seed '42', stamped save → no backfill; ids line up
|
||||||
|
// across worlds) in two fresh files and compares their full state:
|
||||||
|
// A = the legacy immediate action (validates, costs a turn, applies the effect);
|
||||||
|
// B = the queued shape — the tick has advanced the turn (Task 4b) and the resolver
|
||||||
|
// applies the effect (ship/research rows deduct the cost up front, as queueTask did at
|
||||||
|
// queue time — Task 3). snapshot() normalizes every game table (wall-clock columns
|
||||||
|
// excluded), so the two end states must be byte-identical.
|
||||||
|
|
||||||
|
// The resolvers only read `type` + `payload` — tests mint stand-in rows with zeroed
|
||||||
|
// identity fields, the same way the public functions' delegation does.
|
||||||
|
const task = (type: 'JUMP' | 'EXPLORE', payload: object): Task =>
|
||||||
|
({ id: 0, saveId: 0, type, payload: JSON.stringify(payload), leadCrewId: 0, helpers: [], duration: 0, remaining: 0, status: 'ACTIVE', queuedAtTurn: 0 })
|
||||||
|
|
||||||
|
async function snapshot(db: GameDb): Promise<string> {
|
||||||
|
const [saves, systems, routes, planets, inventory, crew, ship, tech, missions, events] = await Promise.all([
|
||||||
|
db.db.select({ id: schema.saves.id, seed: schema.saves.seed, turn: schema.saves.turn, schemaVersion: schema.saves.schemaVersion }).from(schema.saves),
|
||||||
|
db.db.select().from(schema.solarSystems),
|
||||||
|
db.db.select().from(schema.jumpRoutes),
|
||||||
|
db.db.select().from(schema.planets),
|
||||||
|
db.db.select().from(schema.inventoryItems),
|
||||||
|
db.db.select().from(schema.crew),
|
||||||
|
db.db.select().from(schema.shipSystems),
|
||||||
|
db.db.select().from(schema.tech),
|
||||||
|
db.db.select().from(schema.missions),
|
||||||
|
db.db.select({ id: schema.events.id, turn: schema.events.turn, type: schema.events.type, message: schema.events.message }).from(schema.events),
|
||||||
|
])
|
||||||
|
return JSON.stringify({ saves, systems, routes, planets, inventory, crew, ship, tech, missions, events })
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('resolveJumpTask (A/B against jumpToSystem)', () => {
|
||||||
|
it('undiscovered target: lands exactly what jumpToSystem lands — move, discover, ring, event', async () => {
|
||||||
|
const { db: a } = await freshFile()
|
||||||
|
const { db: b } = await freshFile()
|
||||||
|
const fa = await buildWorldFixture(a)
|
||||||
|
const fb = await buildWorldFixture(b)
|
||||||
|
|
||||||
|
await jumpToSystem(a, fa.sys1) // legacy: validates, +1 turn, effect, event at turn 1
|
||||||
|
await b.db.update(schema.saves).set({ turn: 1 }).where(eq(schema.saves.id, 1)) // the tick's job (Task 4b)
|
||||||
|
await resolveJumpTask(b, task('JUMP', { systemId: fb.sys1, hops: 1 }))
|
||||||
|
|
||||||
|
expect(await snapshot(b)).toEqual(await snapshot(a))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('discovered target: no ring — still byte-identical to jumpToSystem', async () => {
|
||||||
|
const { db: a } = await freshFile()
|
||||||
|
const { db: b } = await freshFile()
|
||||||
|
const fa = await buildWorldFixture(a, true)
|
||||||
|
const fb = await buildWorldFixture(b, true)
|
||||||
|
|
||||||
|
await jumpToSystem(a, fa.sys1)
|
||||||
|
await b.db.update(schema.saves).set({ turn: 1 }).where(eq(schema.saves.id, 1))
|
||||||
|
await resolveJumpTask(b, task('JUMP', { systemId: fb.sys1, hops: 1 }))
|
||||||
|
|
||||||
|
expect(await snapshot(b)).toEqual(await snapshot(a))
|
||||||
|
expect(await b.db.select().from(schema.solarSystems)).toHaveLength(3) // the fixture's three systems, no ring added
|
||||||
|
})
|
||||||
|
|
||||||
|
it('guards: 404 unknown system, 409 already-current', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
await db.db.update(schema.saves).set({ turn: 1 }).where(eq(schema.saves.id, 1))
|
||||||
|
|
||||||
|
await expect(resolveJumpTask(db, task('JUMP', { systemId: 999, hops: 1 }))).rejects.toMatchObject({ status: 404, message: 'Unknown system 999' })
|
||||||
|
await db.db.update(schema.solarSystems).set({ isCurrent: false }).where(eq(schema.solarSystems.id, 1))
|
||||||
|
await db.db.update(schema.solarSystems).set({ isCurrent: true }).where(eq(schema.solarSystems.id, f.sys1))
|
||||||
|
await expect(resolveJumpTask(db, task('JUMP', { systemId: f.sys1, hops: 1 }))).rejects.toMatchObject({ status: 409, message: 'Already at this system' })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('resolveExploreTask (A/B against explorePlanet)', () => {
|
||||||
|
it('planet in the current system: lands exactly what explorePlanet lands — haul, explored, event', async () => {
|
||||||
|
const { db: a } = await freshFile()
|
||||||
|
const { db: b } = await freshFile()
|
||||||
|
const fa = await buildWorldFixture(a)
|
||||||
|
const fb = await buildWorldFixture(b)
|
||||||
|
|
||||||
|
await explorePlanet(a, fa.p0)
|
||||||
|
await b.db.update(schema.saves).set({ turn: 1 }).where(eq(schema.saves.id, 1))
|
||||||
|
await resolveExploreTask(b, task('EXPLORE', { planetId: fb.p0 }))
|
||||||
|
|
||||||
|
expect(await snapshot(b)).toEqual(await snapshot(a))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('payload planet wins over the current system — the ship stays put (elsewhere semantics)', async () => {
|
||||||
|
const { db: a } = await freshFile()
|
||||||
|
const { db: b } = await freshFile()
|
||||||
|
const fa = await buildWorldFixture(a)
|
||||||
|
const fb = await buildWorldFixture(b)
|
||||||
|
|
||||||
|
await explorePlanet(a, fa.p1) // the current function already scans any planet, not just the current system's
|
||||||
|
await b.db.update(schema.saves).set({ turn: 1 }).where(eq(schema.saves.id, 1))
|
||||||
|
await resolveExploreTask(b, task('EXPLORE', { planetId: fb.p1 }))
|
||||||
|
|
||||||
|
expect(await snapshot(b)).toEqual(await snapshot(a))
|
||||||
|
|
||||||
|
const sysB = await b.db.select().from(schema.solarSystems)
|
||||||
|
expect(sysB.filter((s) => s.isCurrent).map((s) => s.name)).toEqual(['Origin']) // the ship never moved
|
||||||
|
expect(sysB.find((s) => s.name === 'Outpost')!.discovered).toBe(false) // a scan never discovers a system
|
||||||
|
|
||||||
|
const ev = (await b.db.select({ turn: schema.events.turn, type: schema.events.type, message: schema.events.message }).from(schema.events)).find((e) => e.type === 'explore')!
|
||||||
|
expect(ev.turn).toBe(1)
|
||||||
|
// Exact existing format, recomputed the way save.ts computes it: haul first, crew roll on the same stream.
|
||||||
|
const rng = explorationRng('42', fb.p1)
|
||||||
|
const haul = rollExploration(rng)
|
||||||
|
const member = rollCrewMember(rng, new Set<string>())
|
||||||
|
const foundText = haul.length > 0 ? haul.map((i) => `${i.qty}× ${i.name}`).join(', ') : 'nothing'
|
||||||
|
expect(ev.message).toBe(`Explored Basalt — found ${foundText}${member ? ` — ${member.name} joined the crew` : ''}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('guards: 404 unknown planet, 409 already explored (double-resolution safe)', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
await db.db.update(schema.saves).set({ turn: 1 }).where(eq(schema.saves.id, 1))
|
||||||
|
|
||||||
|
await expect(resolveExploreTask(db, task('EXPLORE', { planetId: 999 }))).rejects.toMatchObject({ status: 404, message: 'Unknown planet 999' })
|
||||||
|
await resolveExploreTask(db, task('EXPLORE', { planetId: f.p1 }))
|
||||||
|
await expect(resolveExploreTask(db, task('EXPLORE', { planetId: f.p1 }))).rejects.toMatchObject({ status: 409, message: 'Basalt was already explored' })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- runTurn: the DB-side tick (POST /api/turn — Task 5 wires the route) -----------------
|
||||||
|
//
|
||||||
|
// The route→save pattern: ensureSave first, unscoped single-player reads, persist last.
|
||||||
|
// The tick (tickTurn) owns the turn increment and the queue math; the 4a resolvers own the
|
||||||
|
// effects and the mission hooks (their contract — invoked here, at the tick's new turn,
|
||||||
|
// before the final persist); this function owns the table writes.
|
||||||
|
describe('runTurn (tick on the DB)', () => {
|
||||||
|
// buildWorldFixture (the shared suite in ./test-fixtures) seeds the save + Origin /
|
||||||
|
// Outpost / Farpoint + Alder / Basalt + the route chain — but no crew or tasks; the tick
|
||||||
|
// needs both, so each test here mints its own rows via addCrew / insertTaskRow.
|
||||||
|
it('free skip: an empty queue costs exactly one turn and touches nothing else (Review Focus 4)', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
const count = (t: typeof schema.solarSystems | typeof schema.planets | typeof schema.inventoryItems | typeof schema.missions | typeof schema.events | typeof schema.tasks) => db.db.select().from(t).then((rows) => rows.length)
|
||||||
|
const before = {
|
||||||
|
systems: await count(schema.solarSystems),
|
||||||
|
planets: await count(schema.planets),
|
||||||
|
inventory: await count(schema.inventoryItems),
|
||||||
|
missions: await count(schema.missions),
|
||||||
|
events: await count(schema.events),
|
||||||
|
}
|
||||||
|
|
||||||
|
const r = await runTurn(db)
|
||||||
|
expect(r.turn).toBe(1)
|
||||||
|
expect(r.tasks).toEqual([])
|
||||||
|
expect(r.completed).toEqual([])
|
||||||
|
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
expect(save.turn).toBe(1) // the tick is the increment — the only write of the call
|
||||||
|
expect(await count(schema.solarSystems)).toBe(before.systems)
|
||||||
|
expect(await count(schema.planets)).toBe(before.planets)
|
||||||
|
expect(await count(schema.inventoryItems)).toBe(before.inventory)
|
||||||
|
expect(await count(schema.missions)).toBe(before.missions) // no top-up without a resolution
|
||||||
|
expect(await count(schema.events)).toBe(before.events) // no event for a skip
|
||||||
|
expect(await count(schema.tasks)).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a resolved JUMP completes the matching DELIVER mission, grants the reward, and tops the board up — the 4a hooks, at the tick\'s new turn', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db) // s0 current; s1 'Outpost' undiscovered
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const jumpId = await insertTaskRow(db, { type: 'JUMP', payload: { systemId: f.sys1, hops: 1 }, leadCrewId: c1, helpers: [], duration: 2, remaining: 1, status: 'ACTIVE', queuedAtTurn: 4 })
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
await db.db.update(schema.saves).set({ turn: 5 }).where(eq(schema.saves.id, save.id))
|
||||||
|
const [mission] = await db.db.insert(schema.missions).values({ saveId: save.id, type: 'DELIVER', description: 'Jump to Outpost', targetSystemId: f.sys1, progressTarget: 1, rewardKind: 'resource', rewardQty: 2, state: 'ACTIVE' }).returning({ id: schema.missions.id })
|
||||||
|
|
||||||
|
const r = await runTurn(db)
|
||||||
|
expect(r.turn).toBe(6)
|
||||||
|
expect(r.completed.map((t) => t.id)).toEqual([jumpId])
|
||||||
|
expect((await db.db.select().from(schema.tasks)).find((t) => t.id === jumpId)!.status).toBe('DONE')
|
||||||
|
|
||||||
|
// the mission resolved at the new turn: DONE + reward in the hold + both events at turn 6
|
||||||
|
expect((await db.db.select().from(schema.missions)).find((m) => m.id === mission.id)).toMatchObject({ state: 'DONE', progress: 1 })
|
||||||
|
expect(await db.db.select().from(schema.inventoryItems)).toEqual([{ id: expect.any(Number), saveId: save.id, kind: 'resource', name: 'MISSION REWARD', qty: 2 }])
|
||||||
|
const events = (await db.db.select().from(schema.events)).map((e) => [e.turn, e.type] as const)
|
||||||
|
expect(events).toHaveLength(2)
|
||||||
|
expect(events).toContainEqual([6, 'jump'])
|
||||||
|
expect(events).toContainEqual([6, 'mission'])
|
||||||
|
|
||||||
|
// the board is topped up after the arrival (the 4a jump-resolver hook) to exactly the floor
|
||||||
|
const available = (await db.db.select({ state: schema.missions.state }).from(schema.missions)).filter((m) => m.state === 'AVAILABLE').length
|
||||||
|
expect(available).toBe(MIN_AVAILABLE)
|
||||||
|
|
||||||
|
// the effect half: the ship is at the payload system
|
||||||
|
expect((await db.db.select().from(schema.solarSystems)).find((s) => s.id === f.sys1)!.isCurrent).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a JUMP and an EXPLORE both resolving on one tick: the explore effect lands on its payload planet, not the newly arrived system (Review Focus 3)', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db) // p0 'Alder' in s0 (Origin); p1 'Basalt' in s1 (Outpost)
|
||||||
|
const [c1, c2] = await addCrew(db, 2)
|
||||||
|
await insertTaskRow(db, { type: 'EXPLORE', payload: { planetId: f.p0 }, leadCrewId: c1, helpers: [], duration: 1, remaining: 1, status: 'ACTIVE', queuedAtTurn: 3 })
|
||||||
|
await insertTaskRow(db, { type: 'JUMP', payload: { systemId: f.sys1, hops: 1 }, leadCrewId: c2, helpers: [], duration: 1, remaining: 1, status: 'ACTIVE', queuedAtTurn: 3 })
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
await db.db.update(schema.saves).set({ turn: 4 }).where(eq(schema.saves.id, save.id))
|
||||||
|
|
||||||
|
const r = await runTurn(db)
|
||||||
|
expect(r.completed.map((t) => t.type)).toEqual(['EXPLORE', 'JUMP']) // both this tick — the resolvers are payload-targeted (4a), so resolution order cannot change what lands
|
||||||
|
|
||||||
|
const planets = await db.db.select().from(schema.planets)
|
||||||
|
expect(planets.find((p) => p.id === f.p0)!.explored).toBe(true) // the payload planet — in the OLD system
|
||||||
|
expect(planets.find((p) => p.id === f.p1)!.explored).toBe(false) // nothing in the new system
|
||||||
|
expect((await db.db.select().from(schema.solarSystems)).find((s) => s.id === f.sys1)!.isCurrent).toBe(true) // the jump still landed
|
||||||
|
// the haul is the payload planet's deterministic stream (seed '42', p0) — never the new system's
|
||||||
|
expect((await db.db.select().from(schema.inventoryItems)).map((i) => ({ kind: i.kind, name: i.name, qty: i.qty }))).toEqual(rollExploration(explorationRng('42', f.p0)))
|
||||||
|
// the ~18% crew roll rides the same stream — at most one member joins (PR C pins the stream)
|
||||||
|
expect((await db.db.select().from(schema.crew)).length).toBeGreaterThanOrEqual(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a resolver guard failure fails just that task — the turn still lands, the sibling still resolves, no event for the failure', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1, c2] = await addCrew(db, 2)
|
||||||
|
const badJumpId = await insertTaskRow(db, { type: 'JUMP', payload: { systemId: 999, hops: 1 }, leadCrewId: c1, helpers: [], duration: 1, remaining: 1, status: 'ACTIVE', queuedAtTurn: 3 })
|
||||||
|
const exploreId = await insertTaskRow(db, { type: 'EXPLORE', payload: { planetId: f.p0 }, leadCrewId: c2, helpers: [], duration: 1, remaining: 1, status: 'ACTIVE', queuedAtTurn: 3 })
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
await db.db.update(schema.saves).set({ turn: 4 }).where(eq(schema.saves.id, save.id))
|
||||||
|
|
||||||
|
const r = await runTurn(db) // must not throw — the 4a guard throw is a failure signal, not an error
|
||||||
|
expect(r.turn).toBe(5)
|
||||||
|
expect(r.completed.map((t) => t.id)).toEqual([badJumpId, exploreId]) // both reported; only the sibling's effect lands
|
||||||
|
expect((await db.db.select().from(schema.tasks)).find((t) => t.id === badJumpId)!.status).toBe('DONE') // failed task: done — the turn is spent, the crew freed
|
||||||
|
expect((await db.db.select().from(schema.planets)).find((p) => p.id === f.p0)!.explored).toBe(true) // the sibling resolved
|
||||||
|
const types = (await db.db.select().from(schema.events)).map((e) => e.type)
|
||||||
|
expect(types.filter((t) => t === 'jump')).toHaveLength(0) // the 404 guard threw before the jump effect/event
|
||||||
|
expect(types.filter((t) => t === 'explore')).toHaveLength(1)
|
||||||
|
expect((await db.db.select().from(schema.solarSystems)).filter((s) => s.isCurrent).map((s) => s.id)).toEqual([1]) // the ship did not move
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- The GET snapshots' task queue (Task 6) ---------------------------------------------
|
||||||
|
//
|
||||||
|
// Every GET snapshot (world / system / crew) carries the active + pending queue: ACTIVE rows
|
||||||
|
// first, then PENDING, each block ordered by (queuedAtTurn, id); DONE rows never appear. A
|
||||||
|
// pure read — `remaining` is the stored value, never recomputed; crew names resolve from the
|
||||||
|
// roster by id.
|
||||||
|
describe('snapshot task queue (world / system / crew)', () => {
|
||||||
|
// buildWorldFixture (4a): a save (seed '42') + Origin (s0, current) / Outpost (s1) +
|
||||||
|
// Alder (p0) / Basalt (p1) + the route pair — no crew, no tasks; this block adds its own.
|
||||||
|
|
||||||
|
// insertTaskRow JSON-encodes its arguments, so the corruption tests seed raw strings straight
|
||||||
|
// into the tasks table (same row shape, no encoding) to reach states the encoder can't.
|
||||||
|
async function insertRawTaskRow(
|
||||||
|
db: GameDb,
|
||||||
|
over: { type: string; payload: string; helpers: string; leadCrewId: number; duration: number; remaining: number; status: string; queuedAtTurn: number },
|
||||||
|
): Promise<number> {
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const [row] = await db.db
|
||||||
|
.insert(schema.tasks)
|
||||||
|
.values({ saveId: save.id, ...over })
|
||||||
|
.returning({ id: schema.tasks.id })
|
||||||
|
return row.id
|
||||||
|
}
|
||||||
|
|
||||||
|
it('empty queue → every GET snapshot carries tasks: []', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildWorldFixture(db)
|
||||||
|
expect((await getWorldState(db)).tasks).toEqual([])
|
||||||
|
expect((await getSystemState(db)).tasks).toEqual([])
|
||||||
|
const crew = await getCrewState(db)
|
||||||
|
expect(crew.tasks).toEqual([])
|
||||||
|
expect(crew.crew).toEqual([]) // the new wrapper: the roster moves under .crew (JC-7)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('one ACTIVE + one PENDING row → exactly those two, ACTIVE first, in all three snapshots', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1, c2, c3] = await addCrew(db, 3)
|
||||||
|
const jumpId = await insertTaskRow(db, { type: 'JUMP', payload: { systemId: f.sys1, hops: 1 }, leadCrewId: c1, helpers: [], duration: 2, remaining: 1, status: 'ACTIVE', queuedAtTurn: 3 })
|
||||||
|
const exploreId = await insertTaskRow(db, { type: 'EXPLORE', payload: { planetId: f.p1 }, leadCrewId: c2, helpers: [c3], duration: 4, remaining: 4, status: 'PENDING', queuedAtTurn: 3 })
|
||||||
|
const expected = [
|
||||||
|
{ id: jumpId, type: 'JUMP', targetLabel: 'Outpost', leadName: 'CREW 1', helperNames: [], remaining: 1, status: 'ACTIVE', leadCrewId: c1, helperCrewIds: [] },
|
||||||
|
{ id: exploreId, type: 'EXPLORE', targetLabel: 'Basalt', leadName: 'CREW 2', helperNames: ['CREW 3'], remaining: 4, status: 'PENDING', leadCrewId: c2, helperCrewIds: [c3] },
|
||||||
|
]
|
||||||
|
expect((await getWorldState(db)).tasks).toEqual(expected)
|
||||||
|
expect((await getSystemState(db)).tasks).toEqual(expected)
|
||||||
|
expect((await getCrewState(db)).tasks).toEqual(expected)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('DONE rows never appear — even when they sort first by (queuedAtTurn, id)', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
await insertTaskRow(db, { type: 'JUMP', payload: { systemId: f.sys1, hops: 1 }, leadCrewId: c1, helpers: [], duration: 1, remaining: 0, status: 'DONE', queuedAtTurn: 1 }) // oldest, lowest id in the queue
|
||||||
|
await insertTaskRow(db, { type: 'EXPLORE', payload: { planetId: f.p0 }, leadCrewId: c1, helpers: [], duration: 4, remaining: 4, status: 'PENDING', queuedAtTurn: 2 })
|
||||||
|
const snap = await getWorldState(db)
|
||||||
|
expect(snap.tasks).toHaveLength(1)
|
||||||
|
expect(snap.tasks[0].type).toBe('EXPLORE') // the DONE row is filtered out, not reordered to the back
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a corrupted payload degrades to targetLabel `unknown` — the snapshot still builds', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1, c2] = await addCrew(db, 2)
|
||||||
|
const badId = await insertRawTaskRow(db, { type: 'EXPLORE', payload: 'not-json', helpers: '[]', leadCrewId: c1, duration: 1, remaining: 1, status: 'ACTIVE', queuedAtTurn: 2 })
|
||||||
|
const exploreId = await insertTaskRow(db, { type: 'EXPLORE', payload: { planetId: f.p0 }, leadCrewId: c2, helpers: [], duration: 1, remaining: 1, status: 'ACTIVE', queuedAtTurn: 3 })
|
||||||
|
const snap = await getWorldState(db) // must not throw out of the read
|
||||||
|
expect(snap.tasks).toEqual([
|
||||||
|
{ id: badId, type: 'EXPLORE', targetLabel: 'unknown', leadName: 'CREW 1', helperNames: [], remaining: 1, status: 'ACTIVE', leadCrewId: c1, helperCrewIds: [] },
|
||||||
|
{ id: exploreId, type: 'EXPLORE', targetLabel: 'Alder', leadName: 'CREW 2', helperNames: [], remaining: 1, status: 'ACTIVE', leadCrewId: c2, helperCrewIds: [] }, // the well-formed sibling still resolves
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a corrupted helpers blob degrades to helperNames [] — no throw', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const badId = await insertRawTaskRow(db, { type: 'JUMP', payload: JSON.stringify({ systemId: f.sys1, hops: 1 }), helpers: '[not-json', leadCrewId: c1, duration: 1, remaining: 1, status: 'ACTIVE', queuedAtTurn: 3 })
|
||||||
|
const snap = await getWorldState(db)
|
||||||
|
expect(snap.tasks).toEqual([
|
||||||
|
{ id: badId, type: 'JUMP', targetLabel: 'Outpost', leadName: 'CREW 1', helperNames: [], remaining: 1, status: 'ACTIVE', leadCrewId: c1, helperCrewIds: [] },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a corrupted type string degrades to targetLabel `unknown` — no throw', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
const f = await buildWorldFixture(db)
|
||||||
|
const [c1] = await addCrew(db, 1)
|
||||||
|
const badId = await insertRawTaskRow(db, { type: 'TELEPORT', payload: JSON.stringify({ systemId: f.sys1, hops: 1 }), helpers: '[]', leadCrewId: c1, duration: 1, remaining: 1, status: 'ACTIVE', queuedAtTurn: 3 })
|
||||||
|
const snap = await getWorldState(db)
|
||||||
|
expect(snap.tasks).toEqual([
|
||||||
|
{ id: badId, type: 'TELEPORT', targetLabel: 'unknown', leadName: 'CREW 1', helperNames: [], remaining: 1, status: 'ACTIVE', leadCrewId: c1, helperCrewIds: [] },
|
||||||
|
])
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -379,6 +711,29 @@ describe('backfill (old saves)', () => {
|
|||||||
expect((await db.db.select().from(schema.planets)).length).toBe(planetCount)
|
expect((await db.db.select().from(schema.planets)).length).toBe(planetCount)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('v7: a v6-stamped save gets an empty tasks table without touching state; idempotent across restart', async () => {
|
||||||
|
const { db, file } = await freshFile()
|
||||||
|
const world = await getWorldState(db) // fresh game, stamped at the current version
|
||||||
|
const crewBefore = await db.db.select().from(schema.crew)
|
||||||
|
const invBefore = await db.db.select().from(schema.inventoryItems)
|
||||||
|
|
||||||
|
await db.db.update(schema.saves).set({ schemaVersion: 6 }) // simulate a save stamped by v0.9.12
|
||||||
|
const world2 = await getWorldState(db) // ensureSave → backfill v6 → v7
|
||||||
|
|
||||||
|
expect(world2).toEqual(world) // turn, systems, edges — untouched (Review Focus 1)
|
||||||
|
expect((await db.db.select().from(schema.saves))[0].schemaVersion).toBe(7)
|
||||||
|
expect(await db.db.select().from(schema.crew)).toEqual(crewBefore)
|
||||||
|
expect(await db.db.select().from(schema.inventoryItems)).toEqual(invBefore)
|
||||||
|
const tables = db.raw.exec("SELECT name FROM sqlite_master WHERE type = 'table'")
|
||||||
|
expect(tables[0].values.map((v) => v[0])).toContain('tasks')
|
||||||
|
expect(Number(db.raw.exec('SELECT COUNT(*) FROM tasks')[0]?.values[0][0] ?? 0)).toBe(0) // empty queue after upgrade
|
||||||
|
|
||||||
|
const reopened = await openGameDb(file) // restart: the backfill must be a no-op
|
||||||
|
await getWorldState(reopened)
|
||||||
|
expect((await reopened.db.select().from(schema.saves))[0].schemaVersion).toBe(7)
|
||||||
|
expect(Number(reopened.raw.exec('SELECT COUNT(*) FROM tasks')[0]?.values[0][0] ?? 0)).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
it('seeds the starting ship on a new game: core types built at base values, WEAPONS unbuilt', async () => {
|
it('seeds the starting ship on a new game: core types built at base values, WEAPONS unbuilt', async () => {
|
||||||
const { db } = await freshFile()
|
const { db } = await freshFile()
|
||||||
await getWorldState(db)
|
await getWorldState(db)
|
||||||
|
|||||||
+335
-36
@@ -1,10 +1,13 @@
|
|||||||
import { eq } from 'drizzle-orm'
|
import { eq, inArray } from 'drizzle-orm'
|
||||||
import type { GameDb } from '@/lib/db/client'
|
import type { GameDb } from '@/lib/db/client'
|
||||||
import { persist } from '@/lib/db/client'
|
import { persist } from '@/lib/db/client'
|
||||||
import * as schema from '@/lib/db/schema'
|
import * as schema from '@/lib/db/schema'
|
||||||
import { generateStartingCrew, rollCrewMember, startingCrewRng, type CrewMember } from './crew'
|
import { generateStartingCrew, rollCrewMember, startingCrewRng, type CrewMember } from './crew'
|
||||||
import { BASE_CAPACITY, BASE_LEVEL, SHIP_TYPES } from './ship-costs'
|
import { BASE_CAPACITY, BASE_LEVEL, SHIP_TYPES } from './ship-costs'
|
||||||
import { checkMissionCompletion, topUpMissionBoard } from './missions'
|
import { checkMissionCompletion, topUpMissionBoard } from './missions'
|
||||||
|
import { resolveResearchTask, ResearchError } from './research'
|
||||||
|
import { resolveShipBuildTask, resolveShipExpandTask, resolveShipUpgradeTask, ShipError } from './ship'
|
||||||
|
import { tickTurn, type QueueState, type Task, type TaskStatus, type TickResult, type TaskType } from './tasks'
|
||||||
import { TECHS } from './tech'
|
import { TECHS } from './tech'
|
||||||
import { bodyRng, explorationRng, generatePlanets, generateRing, generateStartRegion, mulberry32, reachableWithin, rollExploration, type FoundItem } from './world'
|
import { bodyRng, explorationRng, generatePlanets, generateRing, generateStartRegion, mulberry32, reachableWithin, rollExploration, type FoundItem } from './world'
|
||||||
|
|
||||||
@@ -21,10 +24,29 @@ export interface WorldSystemDto {
|
|||||||
current: boolean
|
current: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// One row of the snapshot task queue — what the GET builders expose of the tasks table
|
||||||
|
// (distinct from the tick's TickResult, which reports every row including DONE): the display
|
||||||
|
// fields the UI needs, names resolved, no raw payload — plus the raw row state (JC-11):
|
||||||
|
// `status` (the array's ACTIVE-block-first order isn't readable back from it) and the crew
|
||||||
|
// ids, which the team builder needs for exact member↔row matching (name matching breaks on
|
||||||
|
// the `unknown` fallback).
|
||||||
|
export interface QueueDto {
|
||||||
|
id: number
|
||||||
|
type: TaskType
|
||||||
|
targetLabel: string
|
||||||
|
leadName: string
|
||||||
|
helperNames: string[]
|
||||||
|
remaining: number
|
||||||
|
status: TaskStatus // ACTIVE block first in the array, then PENDING
|
||||||
|
leadCrewId: number // crew.id of the team lead
|
||||||
|
helperCrewIds: number[] // crew.id of the supporting crew (degrades to [] on a corrupted blob, like helperNames)
|
||||||
|
}
|
||||||
|
|
||||||
export interface WorldState {
|
export interface WorldState {
|
||||||
systems: WorldSystemDto[]
|
systems: WorldSystemDto[]
|
||||||
edges: [number, number][] // undirected system-id pairs, deduped + sorted for stable output
|
edges: [number, number][] // undirected system-id pairs, deduped + sorted for stable output
|
||||||
turn: number
|
turn: number
|
||||||
|
tasks: QueueDto[] // the active + pending queue — DONE rows never appear
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carries an HTTP status so route handlers can map failures to responses without re-parsing.
|
// Carries an HTTP status so route handlers can map failures to responses without re-parsing.
|
||||||
@@ -97,7 +119,7 @@ async function seedStartingCrew(db: GameDb, saveId: number, seed: string): Promi
|
|||||||
// What each schema version added to a save. Saves created by older code lack the data newer
|
// What each schema version added to a save. Saves created by older code lack the data newer
|
||||||
// versions seed at new-game time, so ensureSave runs these steps in order for anything below
|
// versions seed at new-game time, so ensureSave runs these steps in order for anything below
|
||||||
// current — each step is idempotent (a no-op when its data already exists).
|
// current — each step is idempotent (a no-op when its data already exists).
|
||||||
export const SCHEMA_VERSION = 6 // v1: save + start region only · v2: bodies for every system · v3: starting crew · v4: starting ship · v5: tech tree · v6: mission board
|
export const SCHEMA_VERSION = 7 // v1: save + start region only · v2: bodies for every system · v3: starting crew · v4: starting ship · v5: tech tree · v6: mission board · v7: tasks table
|
||||||
|
|
||||||
// Seeds the starting ship: one row per known type — core types built at base values, the rest
|
// Seeds the starting ship: one row per known type — core types built at base values, the rest
|
||||||
// unbuilt (level/capacity 0) until a BUILD action.
|
// unbuilt (level/capacity 0) until a BUILD action.
|
||||||
@@ -173,6 +195,11 @@ async function backfillSave(db: GameDb, save: { id: number; seed: string; schema
|
|||||||
await topUpMissionBoard(db) // idempotent — only inserts when fewer than MIN_AVAILABLE AVAILABLE contracts exist
|
await topUpMissionBoard(db) // idempotent — only inserts when fewer than MIN_AVAILABLE AVAILABLE contracts exist
|
||||||
version = 6
|
version = 6
|
||||||
}
|
}
|
||||||
|
if (version < 7) {
|
||||||
|
// The tasks table itself is created by the DDL at open (CREATE TABLE IF NOT EXISTS) for
|
||||||
|
// every file — new or old — so an upgraded save simply starts with an empty queue; stamp.
|
||||||
|
version = 7
|
||||||
|
}
|
||||||
|
|
||||||
if (from !== SCHEMA_VERSION) {
|
if (from !== SCHEMA_VERSION) {
|
||||||
await db.db.update(schema.saves).set({ schemaVersion: version }).where(eq(schema.saves.id, save.id))
|
await db.db.update(schema.saves).set({ schemaVersion: version }).where(eq(schema.saves.id, save.id))
|
||||||
@@ -180,6 +207,66 @@ async function backfillSave(db: GameDb, save: { id: number; seed: string; schema
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The snapshot task queue — the GET builders' read of the tasks table (distinct from the
|
||||||
|
// tick's TickResult, which reports every row): one select of the tasks table filtered to
|
||||||
|
// ACTIVE + PENDING (DONE rows never appear) plus one select each of the name-resolution
|
||||||
|
// tables. The ACTIVE block comes first, then the PENDING block, each ordered by
|
||||||
|
// (queuedAtTurn, id). Pure read: `remaining` is the stored row value, never recomputed;
|
||||||
|
// crew names resolve from the roster by id, `unknown` tolerating a deleted member (the same
|
||||||
|
// spirit as 4b's <= 0 check). Private — every caller is a public read that already ran
|
||||||
|
// ensureSave.
|
||||||
|
async function taskQueue(db: GameDb): Promise<QueueDto[]> {
|
||||||
|
const [taskRows, crew, systems, planets, tech] = await Promise.all([
|
||||||
|
db.db.select().from(schema.tasks).where(inArray(schema.tasks.status, ['ACTIVE', 'PENDING'])),
|
||||||
|
db.db.select().from(schema.crew),
|
||||||
|
db.db.select().from(schema.solarSystems),
|
||||||
|
db.db.select().from(schema.planets),
|
||||||
|
db.db.select().from(schema.tech),
|
||||||
|
])
|
||||||
|
|
||||||
|
const systemName = new Map(systems.map((s): [number, string] => [s.id, s.name]))
|
||||||
|
const planetName = new Map(planets.map((p): [number, string] => [p.id, p.name]))
|
||||||
|
const techName = new Map(tech.map((t): [number, string] => [t.id, t.name]))
|
||||||
|
const crewName = (id: number) => crew.find((c) => c.id === id)?.name ?? 'unknown'
|
||||||
|
|
||||||
|
// Corrupted-row tolerance: every JSON read goes through a guarded parse — a malformed
|
||||||
|
// payload / helpers / type degrades to `unknown` / [] instead of throwing out of this
|
||||||
|
// pure read (one bad row must not 500 the /api/world, /api/system and /api/crew routes).
|
||||||
|
const parse = <T>(raw: string): T | null => { try { return JSON.parse(raw) as T } catch { return null } }
|
||||||
|
const parseHelpers = (raw: string): number[] => { const v = parse<unknown>(raw); return Array.isArray(v) ? (v as number[]) : [] }
|
||||||
|
|
||||||
|
// targetLabel from the 4a payload shapes, per type (the Task interface in tasks.ts): the
|
||||||
|
// target's display name (the jump destination, the scanned body, the researched tech), the
|
||||||
|
// ship system's name with the verb suffixed for upgrade/expand, and the SHIP_TYPES string
|
||||||
|
// as-is for a build. A deleted lookup target, a malformed payload, or a missing field
|
||||||
|
// falls back to `unknown`.
|
||||||
|
const labelFor: Record<TaskType, (payload: string) => string> = {
|
||||||
|
JUMP: (payload) => { const p = parse<{ systemId: number }>(payload); return p ? (systemName.get(p.systemId) ?? 'unknown') : 'unknown' },
|
||||||
|
EXPLORE: (payload) => { const p = parse<{ planetId: number }>(payload); return p ? (planetName.get(p.planetId) ?? 'unknown') : 'unknown' },
|
||||||
|
SHIP_UPGRADE: (payload) => { const p = parse<{ systemId: number }>(payload); return p ? `${systemName.get(p.systemId) ?? 'unknown'} — upgrade` : 'unknown' },
|
||||||
|
SHIP_EXPAND: (payload) => { const p = parse<{ systemId: number }>(payload); return p ? `${systemName.get(p.systemId) ?? 'unknown'} — expand` : 'unknown' },
|
||||||
|
SHIP_BUILD: (payload) => parse<{ type: string }>(payload)?.type ?? 'unknown',
|
||||||
|
RESEARCH: (payload) => { const p = parse<{ techId: number }>(payload); return p ? (techName.get(p.techId) ?? 'unknown') : 'unknown' },
|
||||||
|
}
|
||||||
|
|
||||||
|
const queue = taskRows.map((t) => ({
|
||||||
|
id: t.id,
|
||||||
|
type: t.type as TaskType,
|
||||||
|
targetLabel: labelFor[t.type as TaskType]?.(t.payload) ?? 'unknown',
|
||||||
|
leadName: crewName(t.leadCrewId),
|
||||||
|
helperNames: parseHelpers(t.helpers).map(crewName),
|
||||||
|
remaining: t.remaining,
|
||||||
|
status: t.status as TaskStatus,
|
||||||
|
leadCrewId: t.leadCrewId,
|
||||||
|
helperCrewIds: parseHelpers(t.helpers),
|
||||||
|
queuedAtTurn: t.queuedAtTurn,
|
||||||
|
}))
|
||||||
|
const byQueueOrder = (rows: typeof queue) => rows.sort((a, b) => a.queuedAtTurn - b.queuedAtTurn || a.id - b.id)
|
||||||
|
const ordered = [...byQueueOrder(queue.filter((t) => t.status === 'ACTIVE')), ...byQueueOrder(queue.filter((t) => t.status === 'PENDING'))]
|
||||||
|
// queuedAtTurn is only for ordering — the exposed shape is exactly QueueDto (status stays: JC-11).
|
||||||
|
return ordered.map(({ queuedAtTurn, ...dto }) => dto)
|
||||||
|
}
|
||||||
|
|
||||||
export async function getWorldState(db: GameDb): Promise<WorldState> {
|
export async function getWorldState(db: GameDb): Promise<WorldState> {
|
||||||
await ensureSave(db)
|
await ensureSave(db)
|
||||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
@@ -203,9 +290,62 @@ export async function getWorldState(db: GameDb): Promise<WorldState> {
|
|||||||
systems: systems.map((s) => ({ id: s.id, name: s.name, x: s.x, y: s.y, discovered: s.discovered, current: s.isCurrent })),
|
systems: systems.map((s) => ({ id: s.id, name: s.name, x: s.x, y: s.y, discovered: s.discovered, current: s.isCurrent })),
|
||||||
edges,
|
edges,
|
||||||
turn: save.turn,
|
turn: save.turn,
|
||||||
|
tasks: await taskQueue(db),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Per-type resolvers (PR A, spec §3) -------------------------------------------
|
||||||
|
//
|
||||||
|
// The effect bodies of the instant actions, extracted so the turn tick (Task 4b) can
|
||||||
|
// resolve a completed task row against whatever the world looks like at resolution time.
|
||||||
|
// Contract (all six resolvers across save.ts / ship.ts / research.ts — see the Interfaces
|
||||||
|
// block of this plan): effects land on the PAYLOAD target, never on the current location;
|
||||||
|
// no turn advance (the caller owns the turn); no cost deduction (queueTask deducted at
|
||||||
|
// queue time — Task 3; the immediate public functions deduct before delegating); a minimal
|
||||||
|
// guard against a stale or double-resolved target (existing error class + exact message —
|
||||||
|
// a throw is the signal for the 4b tick's re-validation); the existing event text formats
|
||||||
|
// at the current turn; persist at the end.
|
||||||
|
|
||||||
|
// A stand-in task row for the immediate public functions delegating to a resolver: the
|
||||||
|
// resolvers only read `type` + `payload`, so the identity fields are zeroed.
|
||||||
|
function syntheticTask(type: TaskType, payload: object): Task {
|
||||||
|
return { id: 0, saveId: 0, type, payload: JSON.stringify(payload), leadCrewId: 0, helpers: [], duration: 0, remaining: 0, status: 'ACTIVE', queuedAtTurn: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
// JUMP — move the ship to the payload's system: flip isCurrent, discover the target, and
|
||||||
|
// when it was undiscovered grow the chart ring off the same (seed, turn) stream as before.
|
||||||
|
export async function resolveJumpTask(db: GameDb, task: Task): Promise<void> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const { systemId } = JSON.parse(task.payload) as { systemId: number }
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const systems = await db.db.select().from(schema.solarSystems)
|
||||||
|
|
||||||
|
const target = systems.find((s) => s.id === systemId)
|
||||||
|
if (!target) throw new JumpError(404, `Unknown system ${systemId}`)
|
||||||
|
if (target.isCurrent) throw new JumpError(409, 'Already at this system')
|
||||||
|
const current = systems.find((s) => s.isCurrent)!
|
||||||
|
|
||||||
|
await db.db.update(schema.solarSystems).set({ isCurrent: false }).where(eq(schema.solarSystems.id, current.id))
|
||||||
|
await db.db.update(schema.solarSystems).set({ isCurrent: true, discovered: true }).where(eq(schema.solarSystems.id, target.id))
|
||||||
|
|
||||||
|
if (!target.discovered) {
|
||||||
|
// Growing the chart: a ring of new (undiscovered) neighbours around the newly reached
|
||||||
|
// system, so there is always somewhere to jump next and a route back.
|
||||||
|
const rng = expansionRng(save.seed, save.turn)
|
||||||
|
const takenNames = new Set(systems.map((s) => s.name))
|
||||||
|
const ring = generateRing(rng, target.x, target.y, takenNames, systems)
|
||||||
|
const ringIds: number[] = []
|
||||||
|
for (const s of ring.systems) ringIds.push(await insertSystemWithBodies(db, save.id, s, save.seed))
|
||||||
|
const resolve = (index: number) => (index === 0 ? target.id : ringIds[index - 1])
|
||||||
|
await insertRoutes(db, ring.edges, resolve)
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.db.insert(schema.events).values({ saveId: save.id, turn: save.turn, type: 'jump', message: `Jumped to ${target.name}`, createdAt: new Date().toISOString() })
|
||||||
|
await checkMissionCompletion(db, save.id, save.turn, { jumpedTo: target.id }) // an ACTIVE DELIVER may have arrived at its destination
|
||||||
|
await topUpMissionBoard(db)
|
||||||
|
await persist(db)
|
||||||
|
}
|
||||||
|
|
||||||
export async function jumpToSystem(db: GameDb, systemId: number): Promise<WorldState> {
|
export async function jumpToSystem(db: GameDb, systemId: number): Promise<WorldState> {
|
||||||
await ensureSave(db)
|
await ensureSave(db)
|
||||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
@@ -217,37 +357,43 @@ export async function jumpToSystem(db: GameDb, systemId: number): Promise<WorldS
|
|||||||
if (current.id === target.id) throw new JumpError(409, 'Already at this system')
|
if (current.id === target.id) throw new JumpError(409, 'Already at this system')
|
||||||
|
|
||||||
const routes = await db.db.select().from(schema.jumpRoutes)
|
const routes = await db.db.select().from(schema.jumpRoutes)
|
||||||
// #35 — NAVIGATION AI extends the jump range from adjacent (1 hop) to 2 hops; a multi-hop jump
|
// #35 — NAVIGATION AI extends the jump range from adjacent (1 hop) to 2 hops; a multi-hop
|
||||||
// costs one turn per hop, so single-hop jumps keep their existing cost.
|
// jump costs one turn per hop, so single-hop jumps keep their existing cost.
|
||||||
const navAi = (await db.db.select().from(schema.tech)).some((t) => t.slug === 'NAV_AI' && t.researched)
|
const navAi = (await db.db.select().from(schema.tech)).some((t) => t.slug === 'NAV_AI' && t.researched)
|
||||||
const hopCount = reachableWithin(routes.map((r) => [r.fromSystem, r.toSystem]), current.id, navAi ? 2 : 1).get(target.id)
|
const hopCount = reachableWithin(routes.map((r) => [r.fromSystem, r.toSystem]), current.id, navAi ? 2 : 1).get(target.id)
|
||||||
if (hopCount === undefined) throw new JumpError(409, `${target.name} is not reachable from ${current.name}`)
|
if (hopCount === undefined) throw new JumpError(409, `${target.name} is not reachable from ${current.name}`)
|
||||||
|
|
||||||
|
// The immediate jump keeps its own turn cost (the tick owns turn advances for queued
|
||||||
|
// tasks): advance it before delegating so the resolver's event lands at exactly the
|
||||||
|
// turn the old code wrote.
|
||||||
const turn = save.turn + hopCount
|
const turn = save.turn + hopCount
|
||||||
await db.db.update(schema.solarSystems).set({ isCurrent: false }).where(eq(schema.solarSystems.id, current.id))
|
|
||||||
await db.db.update(schema.solarSystems).set({ isCurrent: true, discovered: true }).where(eq(schema.solarSystems.id, target.id))
|
|
||||||
|
|
||||||
if (!target.discovered) {
|
|
||||||
// Growing the chart: a ring of new (undiscovered) neighbours around the newly reached
|
|
||||||
// system, so there is always somewhere to jump next and a route back.
|
|
||||||
const rng = expansionRng(save.seed, turn)
|
|
||||||
const takenNames = new Set(systems.map((s) => s.name))
|
|
||||||
const ring = generateRing(rng, target.x, target.y, takenNames, systems)
|
|
||||||
const ringIds: number[] = []
|
|
||||||
for (const s of ring.systems) ringIds.push(await insertSystemWithBodies(db, save.id, s, save.seed))
|
|
||||||
const resolve = (index: number) => (index === 0 ? target.id : ringIds[index - 1])
|
|
||||||
await insertRoutes(db, ring.edges, resolve)
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.db.update(schema.saves).set({ turn }).where(eq(schema.saves.id, save.id))
|
await db.db.update(schema.saves).set({ turn }).where(eq(schema.saves.id, save.id))
|
||||||
await db.db.insert(schema.events).values({ saveId: save.id, turn, type: 'jump', message: `Jumped to ${target.name}`, createdAt: new Date().toISOString() })
|
await resolveJumpTask(db, syntheticTask('JUMP', { systemId, hops: hopCount }))
|
||||||
await checkMissionCompletion(db, save.id, turn, { jumpedTo: target.id }) // an ACTIVE DELIVER may have arrived at its destination
|
|
||||||
await topUpMissionBoard(db)
|
|
||||||
await persist(db)
|
|
||||||
|
|
||||||
return getWorldState(db)
|
return getWorldState(db)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The jump pre-checks, extracted for the queueing route (5a): the same codes and messages
|
||||||
|
// as jumpToSystem — unknown system (404), already there (409), outside range (409) — and
|
||||||
|
// the hop count (reachableWithin + NAV AI, the existing reachability logic) the route puts
|
||||||
|
// in the queued JUMP payload.
|
||||||
|
export async function checkJumpTarget(db: GameDb, systemId: number): Promise<number> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const systems = await db.db.select().from(schema.solarSystems)
|
||||||
|
|
||||||
|
const target = systems.find((s) => s.id === systemId)
|
||||||
|
if (!target) throw new JumpError(404, `Unknown system ${systemId}`)
|
||||||
|
const current = systems.find((s) => s.isCurrent)!
|
||||||
|
if (current.id === target.id) throw new JumpError(409, 'Already at this system')
|
||||||
|
|
||||||
|
const routes = await db.db.select().from(schema.jumpRoutes)
|
||||||
|
// #35 — NAVIGATION AI extends the jump range from adjacent (1 hop) to 2 hops.
|
||||||
|
const navAi = (await db.db.select().from(schema.tech)).some((t) => t.slug === 'NAV_AI' && t.researched)
|
||||||
|
const hopCount = reachableWithin(routes.map((r) => [r.fromSystem, r.toSystem]), current.id, navAi ? 2 : 1).get(target.id)
|
||||||
|
if (hopCount === undefined) throw new JumpError(409, `${target.name} is not reachable from ${current.name}`)
|
||||||
|
return hopCount
|
||||||
|
}
|
||||||
|
|
||||||
// --- Local system + exploration ---------------------------------------------
|
// --- Local system + exploration ---------------------------------------------
|
||||||
|
|
||||||
export interface PlanetDto {
|
export interface PlanetDto {
|
||||||
@@ -271,6 +417,7 @@ export interface SystemState {
|
|||||||
planets: PlanetDto[] // insertion order = display order (a moon follows its parent row)
|
planets: PlanetDto[] // insertion order = display order (a moon follows its parent row)
|
||||||
inventory: InventoryItemDto[]
|
inventory: InventoryItemDto[]
|
||||||
turn: number
|
turn: number
|
||||||
|
tasks: QueueDto[] // the active + pending queue — DONE rows never appear
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carries an HTTP status so route handlers can map failures to responses without re-parsing.
|
// Carries an HTTP status so route handlers can map failures to responses without re-parsing.
|
||||||
@@ -296,7 +443,7 @@ async function readSystemState(db: GameDb): Promise<SystemState> {
|
|||||||
parent: p.parentId,
|
parent: p.parentId,
|
||||||
}))
|
}))
|
||||||
const inventory = (await db.db.select().from(schema.inventoryItems)).map((i) => ({ kind: i.kind as 'resource' | 'part', name: i.name, qty: i.qty }))
|
const inventory = (await db.db.select().from(schema.inventoryItems)).map((i) => ({ kind: i.kind as 'resource' | 'part', name: i.name, qty: i.qty }))
|
||||||
return { systemId: current.id, systemName: current.name, planets, inventory, turn: save.turn }
|
return { systemId: current.id, systemName: current.name, planets, inventory, turn: save.turn, tasks: await taskQueue(db) }
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getSystemState(db: GameDb): Promise<SystemState> {
|
export async function getSystemState(db: GameDb): Promise<SystemState> {
|
||||||
@@ -315,10 +462,19 @@ export interface CrewDto {
|
|||||||
origin: string // 'STARTING CREW' or '<planet>, <system>' for members found while exploring
|
origin: string // 'STARTING CREW' or '<planet>, <system>' for members found while exploring
|
||||||
}
|
}
|
||||||
|
|
||||||
// The full roster in join order (starting crew first, then finds). Auto-initializes like the other reads.
|
// GET /api/crew wraps the roster with the snapshot task queue (JC-7): a bare array cannot
|
||||||
export async function getCrewState(db: GameDb): Promise<CrewDto[]> {
|
// carry a sibling tasks field, so the endpoint returns this object.
|
||||||
|
export interface CrewState {
|
||||||
|
crew: CrewDto[]
|
||||||
|
tasks: QueueDto[]
|
||||||
|
}
|
||||||
|
|
||||||
|
// The full roster in join order (starting crew first, then finds), wrapped with the queue.
|
||||||
|
// Auto-initializes like the other reads.
|
||||||
|
export async function getCrewState(db: GameDb): Promise<CrewState> {
|
||||||
await ensureSave(db)
|
await ensureSave(db)
|
||||||
return (await db.db.select().from(schema.crew)).map((c) => ({ id: c.id, name: c.name, role: c.role, traitGood: c.traitGood, traitBad: c.traitBad, origin: c.origin }))
|
const crew = (await db.db.select().from(schema.crew)).map((c) => ({ id: c.id, name: c.name, role: c.role, traitGood: c.traitGood, traitBad: c.traitBad, origin: c.origin }))
|
||||||
|
return { crew, tasks: await taskQueue(db) }
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ExploreResult extends SystemState {
|
export interface ExploreResult extends SystemState {
|
||||||
@@ -326,12 +482,13 @@ export interface ExploreResult extends SystemState {
|
|||||||
crewFound: CrewDto | null // a member who joined the ship on this scan (null when none)
|
crewFound: CrewDto | null // a member who joined the ship on this scan (null when none)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Scan one body of the save: deterministic haul from (seed, planet id), marks it explored,
|
// EXPLORE — scan the payload's planet (any system — the UI only offered the current
|
||||||
// costs a turn, accumulates finds into inventory and writes an event. The same per-planet
|
// system's rows; a queued scan may resolve while the ship is elsewhere): deterministic
|
||||||
// rng stream also rolls for a crew member (~18% of scans) who joins the roster. Any existing
|
// haul into the inventory, planet marked explored, crew-join roll on the same
|
||||||
// planet may be scanned (the UI only offers the current system's rows).
|
// (seed, planet) stream.
|
||||||
export async function explorePlanet(db: GameDb, planetId: number): Promise<ExploreResult> {
|
export async function resolveExploreTask(db: GameDb, task: Task): Promise<{ outcome: FoundItem[]; crewFound: CrewDto | null }> {
|
||||||
await ensureSave(db)
|
await ensureSave(db)
|
||||||
|
const { planetId } = JSON.parse(task.payload) as { planetId: number }
|
||||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
const planets = await db.db.select().from(schema.planets)
|
const planets = await db.db.select().from(schema.planets)
|
||||||
const target = planets.find((p) => p.id === planetId)
|
const target = planets.find((p) => p.id === planetId)
|
||||||
@@ -342,7 +499,6 @@ export async function explorePlanet(db: GameDb, planetId: number): Promise<Explo
|
|||||||
const outcome = rollExploration(rng) // resource/part haul first…
|
const outcome = rollExploration(rng) // resource/part haul first…
|
||||||
const takenNames = new Set((await db.db.select().from(schema.crew)).map((c) => c.name))
|
const takenNames = new Set((await db.db.select().from(schema.crew)).map((c) => c.name))
|
||||||
const foundMember = rollCrewMember(rng, takenNames) // …then the crew roll on the same stream
|
const foundMember = rollCrewMember(rng, takenNames) // …then the crew roll on the same stream
|
||||||
const turn = save.turn + 1
|
|
||||||
|
|
||||||
await db.db.update(schema.planets).set({ explored: true }).where(eq(schema.planets.id, target.id))
|
await db.db.update(schema.planets).set({ explored: true }).where(eq(schema.planets.id, target.id))
|
||||||
for (const item of outcome) {
|
for (const item of outcome) {
|
||||||
@@ -365,11 +521,154 @@ export async function explorePlanet(db: GameDb, planetId: number): Promise<Explo
|
|||||||
|
|
||||||
const foundText = outcome.length > 0 ? outcome.map((i) => `${i.qty}× ${i.name}`).join(', ') : 'nothing'
|
const foundText = outcome.length > 0 ? outcome.map((i) => `${i.qty}× ${i.name}`).join(', ') : 'nothing'
|
||||||
const crewText = crewFound ? ` — ${crewFound.name} joined the crew` : ''
|
const crewText = crewFound ? ` — ${crewFound.name} joined the crew` : ''
|
||||||
await db.db.update(schema.saves).set({ turn }).where(eq(schema.saves.id, save.id))
|
await db.db.insert(schema.events).values({ saveId: save.id, turn: save.turn, type: 'explore', message: `Explored ${target.name} — found ${foundText}${crewText}`, createdAt: new Date().toISOString() })
|
||||||
await db.db.insert(schema.events).values({ saveId: save.id, turn, type: 'explore', message: `Explored ${target.name} — found ${foundText}${crewText}`, createdAt: new Date().toISOString() })
|
await checkMissionCompletion(db, save.id, save.turn, { outcome }) // an ACTIVE EXPLORE/FIND may have advanced or completed
|
||||||
await checkMissionCompletion(db, save.id, turn, { outcome }) // an ACTIVE EXPLORE/FIND may have advanced or completed
|
|
||||||
await topUpMissionBoard(db)
|
await topUpMissionBoard(db)
|
||||||
await persist(db)
|
await persist(db)
|
||||||
|
|
||||||
|
return { outcome, crewFound }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scan one body of the save: deterministic haul from (seed, planet id), marks it explored,
|
||||||
|
// costs a turn, accumulates finds into inventory and writes an event. The same per-planet
|
||||||
|
// rng stream also rolls for a crew member (~18% of scans) who joins the roster. Any existing
|
||||||
|
// planet may be scanned (the UI only offers the current system's rows).
|
||||||
|
export async function explorePlanet(db: GameDb, planetId: number): Promise<ExploreResult> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const planets = await db.db.select().from(schema.planets)
|
||||||
|
const target = planets.find((p) => p.id === planetId)
|
||||||
|
if (!target) throw new ExploreError(404, `Unknown planet ${planetId}`)
|
||||||
|
if (target.explored) throw new ExploreError(409, `${target.name} was already explored`)
|
||||||
|
|
||||||
|
// The immediate scan keeps its one-turn cost; the resolver applies everything else at that turn.
|
||||||
|
const turn = save.turn + 1
|
||||||
|
await db.db.update(schema.saves).set({ turn }).where(eq(schema.saves.id, save.id))
|
||||||
|
const { outcome, crewFound } = await resolveExploreTask(db, syntheticTask('EXPLORE', { planetId }))
|
||||||
|
|
||||||
return { ...(await readSystemState(db)), outcome, crewFound }
|
return { ...(await readSystemState(db)), outcome, crewFound }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The explore pre-checks, extracted for the queueing route (5a): the same codes and messages
|
||||||
|
// as explorePlanet — unknown body (404), already scanned (409).
|
||||||
|
export async function checkExploreTarget(db: GameDb, planetId: number): Promise<void> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const planets = await db.db.select().from(schema.planets)
|
||||||
|
const target = planets.find((p) => p.id === planetId)
|
||||||
|
if (!target) throw new ExploreError(404, `Unknown planet ${planetId}`)
|
||||||
|
if (target.explored) throw new ExploreError(409, `${target.name} was already explored`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- The turn tick on the DB (POST /api/turn — Task 5 wires the route) ---------------------
|
||||||
|
//
|
||||||
|
// The route→save pattern: ensureSave first, unscoped single-player reads, persist last.
|
||||||
|
// The tick (tickTurn) owns the turn increment and the queue math; the 4a resolvers own the
|
||||||
|
// effects and the mission hooks (their contract — invoked here, at the tick's new turn,
|
||||||
|
// before the final persist); this function owns the table writes.
|
||||||
|
|
||||||
|
// The 4a contract names the resolvers 1:1 exactly for this dispatch; exhaustive by type —
|
||||||
|
// a TaskType without a resolver is a compile error.
|
||||||
|
const TASK_RESOLVERS: Record<TaskType, (db: GameDb, task: Task) => Promise<unknown>> = {
|
||||||
|
JUMP: resolveJumpTask,
|
||||||
|
EXPLORE: resolveExploreTask,
|
||||||
|
SHIP_UPGRADE: resolveShipUpgradeTask,
|
||||||
|
SHIP_EXPAND: resolveShipExpandTask,
|
||||||
|
SHIP_BUILD: resolveShipBuildTask,
|
||||||
|
RESEARCH: resolveResearchTask,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Row→domain at the save.ts boundary (the inverse — Task→row at insert — stays with the
|
||||||
|
// routes' queueing path).
|
||||||
|
function rowToTask(row: { id: number; saveId: number; type: string; payload: string; leadCrewId: number; helpers: string; duration: number; remaining: number; status: string; queuedAtTurn: number }): Task {
|
||||||
|
return { id: row.id, saveId: row.saveId, type: row.type as TaskType, payload: row.payload, leadCrewId: row.leadCrewId, helpers: JSON.parse(row.helpers) as number[], duration: row.duration, remaining: row.remaining, status: row.status as TaskStatus, queuedAtTurn: row.queuedAtTurn }
|
||||||
|
}
|
||||||
|
|
||||||
|
// The plain queue snapshot Task 3's engine runs over, mapped from the schema's rows: crew,
|
||||||
|
// tasks, inventory, shipSystems and tech, all in id order (single save, unscoped). The route
|
||||||
|
// never touches lib/db/schema, so the single save row is resolved here, not passed in.
|
||||||
|
export async function queueStateFromSave(db: GameDb): Promise<QueueState> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const [crew, taskRows, inventory, shipSystems, tech] = await Promise.all([
|
||||||
|
db.db.select().from(schema.crew),
|
||||||
|
db.db.select().from(schema.tasks),
|
||||||
|
db.db.select().from(schema.inventoryItems),
|
||||||
|
db.db.select().from(schema.shipSystems),
|
||||||
|
db.db.select().from(schema.tech),
|
||||||
|
])
|
||||||
|
return {
|
||||||
|
turn: save.turn,
|
||||||
|
crew: crew.map((c) => ({ id: c.id, name: c.name, role: c.role, traitGood: c.traitGood, traitBad: c.traitBad, origin: c.origin })),
|
||||||
|
tasks: taskRows.map(rowToTask),
|
||||||
|
inventory: inventory.map((i) => ({ kind: i.kind as 'resource' | 'part', name: i.name, qty: i.qty })),
|
||||||
|
shipSystems: shipSystems.map((s) => ({ id: s.id, type: s.type, level: s.level, capacity: s.capacity })),
|
||||||
|
tech: tech.map((t) => ({ id: t.id, slug: t.slug })),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The route's DB-boundary insert (the route→save pattern): queueTask's row minus the two
|
||||||
|
// values only the DB boundary knows (id autoincrement, saveId = the single save's id).
|
||||||
|
// payload is already a JSON string from queueTask (passed through); the crew ids serialize
|
||||||
|
// to the JSON column. Persists so the queue survives a crash; returns the new row id.
|
||||||
|
export async function saveTaskRow(db: GameDb, task: Omit<Task, 'id' | 'saveId'>): Promise<number> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const [row] = await db.db
|
||||||
|
.insert(schema.tasks)
|
||||||
|
.values({ saveId: save.id, type: task.type, payload: task.payload, leadCrewId: task.leadCrewId, helpers: JSON.stringify(task.helpers), duration: task.duration, remaining: task.remaining, status: task.status, queuedAtTurn: task.queuedAtTurn })
|
||||||
|
.returning({ id: schema.tasks.id })
|
||||||
|
await persist(db)
|
||||||
|
return row.id
|
||||||
|
}
|
||||||
|
|
||||||
|
// The route's DB-boundary hold write (the route→save pattern): queueTask's deducted inventory
|
||||||
|
// replaces the save's rows — array order = oldest first = id order, so spendItems' oldest-row-
|
||||||
|
// first consumption and the id-ordered reads stay consistent after the rewrite. Persists so
|
||||||
|
// the deduction survives a crash; the queueing routes call it with queueTask's result.
|
||||||
|
export async function saveInventory(db: GameDb, items: InventoryItemDto[]): Promise<void> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
await db.db.delete(schema.inventoryItems).where(eq(schema.inventoryItems.saveId, save.id))
|
||||||
|
for (const item of items) {
|
||||||
|
await db.db.insert(schema.inventoryItems).values({ saveId: save.id, kind: item.kind, name: item.name, qty: item.qty })
|
||||||
|
}
|
||||||
|
await persist(db)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runTurn(db: GameDb): Promise<TickResult> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const state = await queueStateFromSave(db)
|
||||||
|
|
||||||
|
const result = tickTurn(state)
|
||||||
|
|
||||||
|
// (e) the tick IS the turn increment — written BEFORE the resolvers run, so their events
|
||||||
|
// and the checkMissionCompletion / topUpMissionBoard hooks (4a contract) land at the new
|
||||||
|
// turn, exactly where today's actions place them.
|
||||||
|
await db.db.update(schema.saves).set({ turn: result.turn }).where(eq(schema.saves.id, save.id))
|
||||||
|
|
||||||
|
// (b) + (d) resolve in the order tickTurn returned. A resolver throw is its 4a guard
|
||||||
|
// (stale or double-resolved target): the task fails — it is already DONE (the tick freed
|
||||||
|
// the team; the turn is spent), the effect simply does not land, and no event is written
|
||||||
|
// for it. Only the four domain error classes fail a task; anything else rethrows.
|
||||||
|
for (const task of result.completed) {
|
||||||
|
try {
|
||||||
|
await TASK_RESOLVERS[task.type](db, task)
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof JumpError || err instanceof ExploreError || err instanceof ShipError || err instanceof ResearchError) continue
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Persist the tick's queue changes (the resolvers already persisted their own effects) —
|
||||||
|
// one final whole-DB write makes the turn atomic on disk.
|
||||||
|
for (const before of state.tasks) {
|
||||||
|
const after = result.tasks.find((t) => t.id === before.id)
|
||||||
|
if (after && (after.status !== before.status || after.remaining !== before.remaining)) {
|
||||||
|
await db.db.update(schema.tasks).set({ status: after.status, remaining: after.remaining }).where(eq(schema.tasks.id, after.id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await persist(db)
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|||||||
+128
-1
@@ -6,7 +6,10 @@ import { eq } from 'drizzle-orm'
|
|||||||
import { openGameDb, type GameDb } from '@/lib/db/client'
|
import { openGameDb, type GameDb } from '@/lib/db/client'
|
||||||
import * as schema from '@/lib/db/schema'
|
import * as schema from '@/lib/db/schema'
|
||||||
import { BASE_CAPACITY, BASE_LEVEL, BUILD_PART_COST, MAX_CAPACITY, MAX_LEVEL, SHIP_TYPES } from './ship-costs'
|
import { BASE_CAPACITY, BASE_LEVEL, BUILD_PART_COST, MAX_CAPACITY, MAX_LEVEL, SHIP_TYPES } from './ship-costs'
|
||||||
import { buildSystem, expandSystem, getShipState, upgradeSystem, type ShipState } from './ship'
|
import { buildSystem, expandSystem, getShipState, resolveShipBuildTask, resolveShipExpandTask, resolveShipUpgradeTask, spendItems, upgradeSystem, type ShipState } from './ship'
|
||||||
|
import { SCHEMA_VERSION } from './save'
|
||||||
|
import { TECHS } from './tech'
|
||||||
|
import type { Task } from './tasks'
|
||||||
|
|
||||||
const dirs: string[] = []
|
const dirs: string[] = []
|
||||||
|
|
||||||
@@ -155,3 +158,127 @@ describe('buildSystem', () => {
|
|||||||
await expect(buildSystem(db, 'SHIELDS')).rejects.toMatchObject({ status: 404 }) // not a known type
|
await expect(buildSystem(db, 'SHIELDS')).rejects.toMatchObject({ status: 404 }) // not a known type
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// --- A/B: resolvers vs the legacy immediate ship actions (Task 4a) ---------------------
|
||||||
|
const T0 = '2026-10-01T00:00:00.000Z'
|
||||||
|
|
||||||
|
// Stamped save (no backfill), the full ship per SHIP_TYPES, the full tech tree with
|
||||||
|
// WEAPONS_SYSTEMS researched (unlocks the BUILD row). Identical build per world → ids line up.
|
||||||
|
async function buildShipFixture(db: GameDb): Promise<void> {
|
||||||
|
const [save] = await db.db.insert(schema.saves).values({ seed: '42', turn: 0, createdAt: T0, schemaVersion: SCHEMA_VERSION }).returning()
|
||||||
|
for (const def of SHIP_TYPES) {
|
||||||
|
await db.db.insert(schema.shipSystems).values({ saveId: save.id, type: def.type, level: def.builtAtStart ? BASE_LEVEL : 0, capacity: def.builtAtStart ? BASE_CAPACITY : 0 })
|
||||||
|
}
|
||||||
|
for (const def of TECHS) {
|
||||||
|
await db.db.insert(schema.tech).values({ saveId: save.id, slug: def.slug, name: def.name, costKind: def.costKind, costQty: def.costQty, prerequisites: def.prereqs.join(','), effect: def.effect, researched: def.slug === 'WEAPONS_SYSTEMS' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const task = (type: 'SHIP_UPGRADE' | 'SHIP_EXPAND' | 'SHIP_BUILD', payload: object): Task =>
|
||||||
|
({ id: 0, saveId: 0, type, payload: JSON.stringify(payload), leadCrewId: 0, helpers: [], duration: 0, remaining: 0, status: 'ACTIVE', queuedAtTurn: 0 })
|
||||||
|
|
||||||
|
async function snapshot(db: GameDb): Promise<string> {
|
||||||
|
const [saves, systems, routes, planets, inventory, crew, ship, tech, missions, events] = await Promise.all([
|
||||||
|
db.db.select({ id: schema.saves.id, seed: schema.saves.seed, turn: schema.saves.turn, schemaVersion: schema.saves.schemaVersion }).from(schema.saves),
|
||||||
|
db.db.select().from(schema.solarSystems),
|
||||||
|
db.db.select().from(schema.jumpRoutes),
|
||||||
|
db.db.select().from(schema.planets),
|
||||||
|
db.db.select().from(schema.inventoryItems),
|
||||||
|
db.db.select().from(schema.crew),
|
||||||
|
db.db.select().from(schema.shipSystems),
|
||||||
|
db.db.select().from(schema.tech),
|
||||||
|
db.db.select().from(schema.missions),
|
||||||
|
db.db.select({ id: schema.events.id, turn: schema.events.turn, type: schema.events.type, message: schema.events.message }).from(schema.events),
|
||||||
|
])
|
||||||
|
return JSON.stringify({ saves, systems, routes, planets, inventory, crew, ship, tech, missions, events })
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('resolveShip* (A/B against the immediate actions)', () => {
|
||||||
|
// A = legacy immediate action (validates, deducts the cost, +1 turn, effect, event).
|
||||||
|
// B = the queued shape: the cost is deducted up front (queueTask did it at queue time —
|
||||||
|
// Task 3), the tick advanced the turn (Task 4b), then the resolver applies the effect.
|
||||||
|
// Same starting world → byte-identical end states.
|
||||||
|
|
||||||
|
it('UPGRADE: lands exactly what upgradeSystem lands', async () => {
|
||||||
|
const { db: a } = await freshFile()
|
||||||
|
const { db: b } = await freshFile()
|
||||||
|
await buildShipFixture(a)
|
||||||
|
await buildShipFixture(b)
|
||||||
|
await addItem(a, 'resource', 'IRON ORE', 1) // level 1 → cost 1
|
||||||
|
await addItem(b, 'resource', 'IRON ORE', 1)
|
||||||
|
|
||||||
|
const reactorId = systemOf(await getShipState(a), 'REACTOR').id
|
||||||
|
await upgradeSystem(a, reactorId)
|
||||||
|
await spendItems(b, 1, 'resource', 1) // the queue-time deduction
|
||||||
|
await b.db.update(schema.saves).set({ turn: 1 }).where(eq(schema.saves.id, 1))
|
||||||
|
await resolveShipUpgradeTask(b, task('SHIP_UPGRADE', { systemId: reactorId }))
|
||||||
|
|
||||||
|
expect(await snapshot(b)).toEqual(await snapshot(a))
|
||||||
|
const ev = (await b.db.select({ turn: schema.events.turn, type: schema.events.type, message: schema.events.message }).from(schema.events)).find((e) => e.type === 'upgrade')!
|
||||||
|
expect(ev.turn).toBe(1)
|
||||||
|
expect(ev.message).toBe('Upgraded REACTOR to level 2 (cost: 1× resources)')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('EXPAND: lands exactly what expandSystem lands', async () => {
|
||||||
|
const { db: a } = await freshFile()
|
||||||
|
const { db: b } = await freshFile()
|
||||||
|
await buildShipFixture(a)
|
||||||
|
await buildShipFixture(b)
|
||||||
|
await addItem(a, 'resource', 'CRYSTAL DUST', 2) // capacity 2 → cost 2
|
||||||
|
await addItem(b, 'resource', 'CRYSTAL DUST', 2)
|
||||||
|
|
||||||
|
const hullId = systemOf(await getShipState(a), 'HULL').id
|
||||||
|
await expandSystem(a, hullId)
|
||||||
|
await spendItems(b, 1, 'resource', 2)
|
||||||
|
await b.db.update(schema.saves).set({ turn: 1 }).where(eq(schema.saves.id, 1))
|
||||||
|
await resolveShipExpandTask(b, task('SHIP_EXPAND', { systemId: hullId }))
|
||||||
|
|
||||||
|
expect(await snapshot(b)).toEqual(await snapshot(a))
|
||||||
|
const ev = (await b.db.select({ turn: schema.events.turn, type: schema.events.type, message: schema.events.message }).from(schema.events)).find((e) => e.type === 'expand')!
|
||||||
|
expect(ev.turn).toBe(1)
|
||||||
|
expect(ev.message).toBe('Expanded HULL capacity to 3 (cost: 2× resources)')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('BUILD: lands exactly what buildSystem lands', async () => {
|
||||||
|
const { db: a } = await freshFile()
|
||||||
|
const { db: b } = await freshFile()
|
||||||
|
await buildShipFixture(a)
|
||||||
|
await buildShipFixture(b)
|
||||||
|
await addItem(a, 'part', 'SERVO ACTUATOR', 3)
|
||||||
|
await addItem(b, 'part', 'SERVO ACTUATOR', 3)
|
||||||
|
|
||||||
|
await buildSystem(a, 'WEAPONS')
|
||||||
|
await spendItems(b, 1, 'part', 3)
|
||||||
|
await b.db.update(schema.saves).set({ turn: 1 }).where(eq(schema.saves.id, 1))
|
||||||
|
await resolveShipBuildTask(b, task('SHIP_BUILD', { type: 'WEAPONS' }))
|
||||||
|
|
||||||
|
expect(await snapshot(b)).toEqual(await snapshot(a))
|
||||||
|
const ev = (await b.db.select({ turn: schema.events.turn, type: schema.events.type, message: schema.events.message }).from(schema.events)).find((e) => e.type === 'build')!
|
||||||
|
expect(ev.turn).toBe(1)
|
||||||
|
expect(ev.message).toBe('Built WEAPONS at base values (cost: 3× parts)')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('guards: 404 unknown, 409 unbuilt / max level / max capacity / gate / already built', async () => {
|
||||||
|
const { db } = await freshFile()
|
||||||
|
await buildShipFixture(db)
|
||||||
|
const state = await getShipState(db)
|
||||||
|
const reactorId = systemOf(state, 'REACTOR').id
|
||||||
|
const hullId = systemOf(state, 'HULL').id
|
||||||
|
const weaponsId = systemOf(state, 'WEAPONS').id
|
||||||
|
await db.db.update(schema.saves).set({ turn: 1 }).where(eq(schema.saves.id, 1))
|
||||||
|
|
||||||
|
await expect(resolveShipUpgradeTask(db, task('SHIP_UPGRADE', { systemId: 999 }))).rejects.toMatchObject({ status: 404, message: 'Unknown ship system 999' })
|
||||||
|
await expect(resolveShipUpgradeTask(db, task('SHIP_UPGRADE', { systemId: weaponsId }))).rejects.toMatchObject({ status: 409, message: 'WEAPONS is not built' })
|
||||||
|
await db.db.update(schema.shipSystems).set({ level: MAX_LEVEL }).where(eq(schema.shipSystems.id, reactorId))
|
||||||
|
await expect(resolveShipUpgradeTask(db, task('SHIP_UPGRADE', { systemId: reactorId }))).rejects.toMatchObject({ status: 409, message: `REACTOR is at max level (${MAX_LEVEL})` })
|
||||||
|
|
||||||
|
await expect(resolveShipExpandTask(db, task('SHIP_EXPAND', { systemId: 999 }))).rejects.toMatchObject({ status: 404, message: 'Unknown ship system 999' })
|
||||||
|
await db.db.update(schema.shipSystems).set({ capacity: MAX_CAPACITY }).where(eq(schema.shipSystems.id, hullId))
|
||||||
|
await expect(resolveShipExpandTask(db, task('SHIP_EXPAND', { systemId: hullId }))).rejects.toMatchObject({ status: 409, message: `HULL is at max capacity (${MAX_CAPACITY})` })
|
||||||
|
|
||||||
|
await expect(resolveShipBuildTask(db, task('SHIP_BUILD', { type: 'SHIELDS' }))).rejects.toMatchObject({ status: 404, message: 'Unknown ship system type SHIELDS' })
|
||||||
|
await db.db.update(schema.tech).set({ researched: false }).where(eq(schema.tech.slug, 'WEAPONS_SYSTEMS'))
|
||||||
|
await expect(resolveShipBuildTask(db, task('SHIP_BUILD', { type: 'WEAPONS' }))).rejects.toMatchObject({ status: 409, message: 'Building WEAPONS requires the WEAPONS SYSTEMS tech' })
|
||||||
|
await expect(resolveShipBuildTask(db, task('SHIP_BUILD', { type: 'HULL' }))).rejects.toMatchObject({ status: 409, message: 'HULL is already built' })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
+105
-22
@@ -4,6 +4,7 @@ import { persist, type GameDb } from '@/lib/db/client'
|
|||||||
import { BUILD_PART_COST, BASE_CAPACITY, BASE_LEVEL, SHIP_TYPES, expandCost, upgradeCost } from './ship-costs'
|
import { BUILD_PART_COST, BASE_CAPACITY, BASE_LEVEL, SHIP_TYPES, expandCost, upgradeCost } from './ship-costs'
|
||||||
import { buildGate, effectiveCapacityCap, effectiveLevelCap } from './tech'
|
import { buildGate, effectiveCapacityCap, effectiveLevelCap } from './tech'
|
||||||
import { ensureSave, type InventoryItemDto } from './save'
|
import { ensureSave, type InventoryItemDto } from './save'
|
||||||
|
import type { Task, TaskType } from './tasks'
|
||||||
|
|
||||||
export interface ShipSystemDto {
|
export interface ShipSystemDto {
|
||||||
id: number
|
id: number
|
||||||
@@ -68,17 +69,82 @@ export async function spendItems(db: GameDb, saveId: number, kind: 'resource' |
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function bumpTurnAndEvent(db: GameDb, saveId: number, turn: number, type: string, message: string): Promise<void> {
|
|
||||||
await db.db.update(schema.saves).set({ turn }).where(eq(schema.saves.id, saveId))
|
|
||||||
await db.db.insert(schema.events).values({ saveId, turn, type, message, createdAt: new Date().toISOString() })
|
|
||||||
}
|
|
||||||
|
|
||||||
// Slugs of the researched techs on this save — drives the effective caps and build gates below.
|
// Slugs of the researched techs on this save — drives the effective caps and build gates below.
|
||||||
async function researchedTechSlugs(db: GameDb): Promise<Set<string>> {
|
async function researchedTechSlugs(db: GameDb): Promise<Set<string>> {
|
||||||
return new Set((await db.db.select().from(schema.tech)).filter((t) => t.researched).map((t) => t.slug))
|
return new Set((await db.db.select().from(schema.tech)).filter((t) => t.researched).map((t) => t.slug))
|
||||||
}
|
}
|
||||||
|
|
||||||
// UPGRADE — level up a built system by one (capped at the effective max level, raised by techs). Cost: `level` units of any resource.
|
function syntheticTask(type: TaskType, payload: object): Task {
|
||||||
|
return { id: 0, saveId: 0, type, payload: JSON.stringify(payload), leadCrewId: 0, helpers: [], duration: 0, remaining: 0, status: 'ACTIVE', queuedAtTurn: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
// SHIP_UPGRADE — level a built system by one, at whatever level it sits at resolution
|
||||||
|
// time. No cost here (deducted at queue time — Task 3 — or by upgradeSystem before
|
||||||
|
// delegating); no mission hooks (the current action has none).
|
||||||
|
export async function resolveShipUpgradeTask(db: GameDb, task: Task): Promise<void> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const { systemId } = JSON.parse(task.payload) as { systemId: number }
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const target = (await db.db.select().from(schema.shipSystems)).find((s) => s.id === systemId)
|
||||||
|
if (!target) throw new ShipError(404, `Unknown ship system ${systemId}`)
|
||||||
|
if (target.level <= 0) throw new ShipError(409, `${target.type} is not built`)
|
||||||
|
const maxLevel = effectiveLevelCap(target.type, await researchedTechSlugs(db))
|
||||||
|
if (target.level >= maxLevel) throw new ShipError(409, `${target.type} is at max level (${maxLevel})`)
|
||||||
|
|
||||||
|
const cost = upgradeCost(target.level)
|
||||||
|
await db.db.update(schema.shipSystems).set({ level: target.level + 1 }).where(eq(schema.shipSystems.id, target.id))
|
||||||
|
await db.db.insert(schema.events).values({ saveId: save.id, turn: save.turn, type: 'upgrade', message: `Upgraded ${target.type} to level ${target.level + 1} (cost: ${cost}× resources)`, createdAt: new Date().toISOString() })
|
||||||
|
await persist(db)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SHIP_EXPAND — same shape for capacity (cost: `capacity` units of any resource, deducted).
|
||||||
|
export async function resolveShipExpandTask(db: GameDb, task: Task): Promise<void> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const { systemId } = JSON.parse(task.payload) as { systemId: number }
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const target = (await db.db.select().from(schema.shipSystems)).find((s) => s.id === systemId)
|
||||||
|
if (!target) throw new ShipError(404, `Unknown ship system ${systemId}`)
|
||||||
|
if (target.level <= 0) throw new ShipError(409, `${target.type} is not built`)
|
||||||
|
const maxCapacity = effectiveCapacityCap(target.type, await researchedTechSlugs(db))
|
||||||
|
if (target.capacity >= maxCapacity) throw new ShipError(409, `${target.type} is at max capacity (${maxCapacity})`)
|
||||||
|
|
||||||
|
const cost = expandCost(target.capacity)
|
||||||
|
await db.db.update(schema.shipSystems).set({ capacity: target.capacity + 1 }).where(eq(schema.shipSystems.id, target.id))
|
||||||
|
await db.db.insert(schema.events).values({ saveId: save.id, turn: save.turn, type: 'expand', message: `Expanded ${target.type} capacity to ${target.capacity + 1} (cost: ${cost}× resources)`, createdAt: new Date().toISOString() })
|
||||||
|
await persist(db)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SHIP_BUILD — build an unbuilt type at base values. The flat parts cost is already
|
||||||
|
// deducted; some types are gated behind a researched tech (see EFFECTS in lib/game/tech.ts).
|
||||||
|
export async function resolveShipBuildTask(db: GameDb, task: Task): Promise<void> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const { type } = JSON.parse(task.payload) as { type: string }
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const target = (await db.db.select().from(schema.shipSystems)).find((s) => s.type === type)
|
||||||
|
if (!target) throw new ShipError(404, `Unknown ship system type ${type}`)
|
||||||
|
if (target.level > 0) throw new ShipError(409, `${target.type} is already built`)
|
||||||
|
const gate = buildGate(type, await researchedTechSlugs(db))
|
||||||
|
if (gate) throw new ShipError(409, `Building ${type} requires the ${gate} tech`)
|
||||||
|
|
||||||
|
await db.db.update(schema.shipSystems).set({ level: BASE_LEVEL, capacity: BASE_CAPACITY }).where(eq(schema.shipSystems.id, target.id))
|
||||||
|
await db.db.insert(schema.events).values({ saveId: save.id, turn: save.turn, type: 'build', message: `Built ${target.type} at base values (cost: ${BUILD_PART_COST}× parts)`, createdAt: new Date().toISOString() })
|
||||||
|
await persist(db)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The upgrade pre-checks, extracted for the queueing route (5a(ii)): the same codes and
|
||||||
|
// messages as upgradeSystem — unknown system (404), not built (409), at max level (409).
|
||||||
|
// Cost, turn and the level-up effect stay out: the queueing path deducts at queue time
|
||||||
|
// (queueTask) and the effect lands when the task completes on the tick.
|
||||||
|
export async function checkUpgradePreconditions(db: GameDb, systemId: number): Promise<void> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const target = (await db.db.select().from(schema.shipSystems)).find((s) => s.id === systemId)
|
||||||
|
if (!target) throw new ShipError(404, `Unknown ship system ${systemId}`)
|
||||||
|
if (target.level <= 0) throw new ShipError(409, `${target.type} is not built`)
|
||||||
|
const maxLevel = effectiveLevelCap(target.type, await researchedTechSlugs(db))
|
||||||
|
if (target.level >= maxLevel) throw new ShipError(409, `${target.type} is at max level (${maxLevel})`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// UPGRADE — level up a built system by one (capped at the effective max level, raised by techs).
|
||||||
export async function upgradeSystem(db: GameDb, systemId: number): Promise<ShipState> {
|
export async function upgradeSystem(db: GameDb, systemId: number): Promise<ShipState> {
|
||||||
await ensureSave(db)
|
await ensureSave(db)
|
||||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
@@ -88,16 +154,25 @@ export async function upgradeSystem(db: GameDb, systemId: number): Promise<ShipS
|
|||||||
const maxLevel = effectiveLevelCap(target.type, await researchedTechSlugs(db))
|
const maxLevel = effectiveLevelCap(target.type, await researchedTechSlugs(db))
|
||||||
if (target.level >= maxLevel) throw new ShipError(409, `${target.type} is at max level (${maxLevel})`)
|
if (target.level >= maxLevel) throw new ShipError(409, `${target.type} is at max level (${maxLevel})`)
|
||||||
|
|
||||||
const cost = upgradeCost(target.level)
|
await spendItems(db, save.id, 'resource', upgradeCost(target.level))
|
||||||
await spendItems(db, save.id, 'resource', cost)
|
|
||||||
const turn = save.turn + 1
|
const turn = save.turn + 1
|
||||||
await db.db.update(schema.shipSystems).set({ level: target.level + 1 }).where(eq(schema.shipSystems.id, target.id))
|
await db.db.update(schema.saves).set({ turn }).where(eq(schema.saves.id, save.id))
|
||||||
await bumpTurnAndEvent(db, save.id, turn, 'upgrade', `Upgraded ${target.type} to level ${target.level + 1} (cost: ${cost}× resources)`)
|
await resolveShipUpgradeTask(db, syntheticTask('SHIP_UPGRADE', { systemId }))
|
||||||
await persist(db)
|
|
||||||
return readShipState(db)
|
return readShipState(db)
|
||||||
}
|
}
|
||||||
|
|
||||||
// EXPAND — raise a built system's capacity by one (capped at the effective max capacity, raised by techs). Cost: `capacity` units of any resource.
|
// The expand pre-checks, extracted for the queueing route (5a(ii)): the same codes and
|
||||||
|
// messages as expandSystem — unknown system (404), not built (409), at max capacity (409).
|
||||||
|
export async function checkExpandPreconditions(db: GameDb, systemId: number): Promise<void> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const target = (await db.db.select().from(schema.shipSystems)).find((s) => s.id === systemId)
|
||||||
|
if (!target) throw new ShipError(404, `Unknown ship system ${systemId}`)
|
||||||
|
if (target.level <= 0) throw new ShipError(409, `${target.type} is not built`)
|
||||||
|
const maxCapacity = effectiveCapacityCap(target.type, await researchedTechSlugs(db))
|
||||||
|
if (target.capacity >= maxCapacity) throw new ShipError(409, `${target.type} is at max capacity (${maxCapacity})`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EXPAND — raise a built system's capacity by one (capped at the effective max capacity, raised by techs).
|
||||||
export async function expandSystem(db: GameDb, systemId: number): Promise<ShipState> {
|
export async function expandSystem(db: GameDb, systemId: number): Promise<ShipState> {
|
||||||
await ensureSave(db)
|
await ensureSave(db)
|
||||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
@@ -107,17 +182,26 @@ export async function expandSystem(db: GameDb, systemId: number): Promise<ShipSt
|
|||||||
const maxCapacity = effectiveCapacityCap(target.type, await researchedTechSlugs(db))
|
const maxCapacity = effectiveCapacityCap(target.type, await researchedTechSlugs(db))
|
||||||
if (target.capacity >= maxCapacity) throw new ShipError(409, `${target.type} is at max capacity (${maxCapacity})`)
|
if (target.capacity >= maxCapacity) throw new ShipError(409, `${target.type} is at max capacity (${maxCapacity})`)
|
||||||
|
|
||||||
const cost = expandCost(target.capacity)
|
await spendItems(db, save.id, 'resource', expandCost(target.capacity))
|
||||||
await spendItems(db, save.id, 'resource', cost)
|
|
||||||
const turn = save.turn + 1
|
const turn = save.turn + 1
|
||||||
await db.db.update(schema.shipSystems).set({ capacity: target.capacity + 1 }).where(eq(schema.shipSystems.id, target.id))
|
await db.db.update(schema.saves).set({ turn }).where(eq(schema.saves.id, save.id))
|
||||||
await bumpTurnAndEvent(db, save.id, turn, 'expand', `Expanded ${target.type} capacity to ${target.capacity + 1} (cost: ${cost}× resources)`)
|
await resolveShipExpandTask(db, syntheticTask('SHIP_EXPAND', { systemId }))
|
||||||
await persist(db)
|
|
||||||
return readShipState(db)
|
return readShipState(db)
|
||||||
}
|
}
|
||||||
|
|
||||||
// BUILD — build an unbuilt type at base values. Cost: a flat amount of parts. Some types are
|
// The build pre-checks, extracted for the queueing route (5a(ii)): the same codes and
|
||||||
// gated behind a researched tech (see EFFECTS in lib/game/tech.ts).
|
// messages as buildSystem — unknown type (404), already built (409), build-gate tech
|
||||||
|
// missing (409). The parts cost stays out: the queueing path deducts it at queue time.
|
||||||
|
export async function checkBuildPreconditions(db: GameDb, type: string): Promise<void> {
|
||||||
|
await ensureSave(db)
|
||||||
|
const target = (await db.db.select().from(schema.shipSystems)).find((s) => s.type === type)
|
||||||
|
if (!target) throw new ShipError(404, `Unknown ship system type ${type}`)
|
||||||
|
if (target.level > 0) throw new ShipError(409, `${target.type} is already built`)
|
||||||
|
const gate = buildGate(type, await researchedTechSlugs(db))
|
||||||
|
if (gate) throw new ShipError(409, `Building ${type} requires the ${gate} tech`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BUILD — build an unbuilt type at base values. Cost: a flat amount of parts.
|
||||||
export async function buildSystem(db: GameDb, type: string): Promise<ShipState> {
|
export async function buildSystem(db: GameDb, type: string): Promise<ShipState> {
|
||||||
await ensureSave(db)
|
await ensureSave(db)
|
||||||
const [save] = await db.db.select().from(schema.saves).limit(1)
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
@@ -129,8 +213,7 @@ export async function buildSystem(db: GameDb, type: string): Promise<ShipState>
|
|||||||
|
|
||||||
await spendItems(db, save.id, 'part', BUILD_PART_COST)
|
await spendItems(db, save.id, 'part', BUILD_PART_COST)
|
||||||
const turn = save.turn + 1
|
const turn = save.turn + 1
|
||||||
await db.db.update(schema.shipSystems).set({ level: BASE_LEVEL, capacity: BASE_CAPACITY }).where(eq(schema.shipSystems.id, target.id))
|
await db.db.update(schema.saves).set({ turn }).where(eq(schema.saves.id, save.id))
|
||||||
await bumpTurnAndEvent(db, save.id, turn, 'build', `Built ${target.type} at base values (cost: ${BUILD_PART_COST}× parts)`)
|
await resolveShipBuildTask(db, syntheticTask('SHIP_BUILD', { type }))
|
||||||
await persist(db)
|
|
||||||
return readShipState(db)
|
return readShipState(db)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,277 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import type { CrewMember } from './crew'
|
||||||
|
import { MISMATCH_CANCEL_TRAIT, PREFERRED_ROLES, POWER_BANDS, RECRUIT_CHANCE_BASE, RECRUIT_CHANCE_TALKER, STARTING_LEVELS, TRAIT_DURATION_MODIFIERS, WORK_POINTS, XP_THRESHOLDS } from './crew-costs'
|
||||||
|
import type { CrewDto } from './save'
|
||||||
|
import { computeDuration, queueTask, tickTurn, TaskError, type QueueState, type Task, type TaskType } from './tasks'
|
||||||
|
|
||||||
|
// Trait strings copied verbatim from lib/game/crew.ts GOOD_TRAITS/BAD_TRAITS — TRAIT_DURATION_MODIFIERS
|
||||||
|
// is keyed by exactly these strings, so a rename in crew.ts breaks these tests.
|
||||||
|
const NEUTRAL_GOOD = 'FINDS HIDDEN THINGS' // no duration entry → no effect
|
||||||
|
const NEUTRAL_BAD = 'JINXED IN A DOGFIGHT' // STANDBY combat trait → no duration effect
|
||||||
|
const crew = (role: string, traitGood = NEUTRAL_GOOD, traitBad = NEUTRAL_BAD): CrewMember => ({ name: 'TEST', role, traitGood, traitBad })
|
||||||
|
const WORK: Record<TaskType, number> = { JUMP: 3, EXPLORE: 4, SHIP_UPGRADE: 6, SHIP_EXPAND: 6, SHIP_BUILD: 6, RESEARCH: 9 }
|
||||||
|
const TYPES = Object.keys(WORK) as TaskType[]
|
||||||
|
const SHIP: TaskType[] = ['SHIP_UPGRADE', 'SHIP_EXPAND', 'SHIP_BUILD']
|
||||||
|
|
||||||
|
describe('solo baselines (one crew, power 1, no modifiers)', () => {
|
||||||
|
it('work points are the duration for the preferred role: EXPLORE 4 · JUMP 3 / 6 · SHIP 6 · RESEARCH 9', () => {
|
||||||
|
for (const type of TYPES) {
|
||||||
|
expect(computeDuration(type, 1, crew(PREFERRED_ROLES[type][0]), [])).toBe(WORK[type])
|
||||||
|
}
|
||||||
|
expect(computeDuration('JUMP', 2, crew('PILOT'), [])).toBe(6) // two-hop = 2 × 3
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('role mismatch (lead only, helpers never penalised)', () => {
|
||||||
|
it('a lead outside the preferred role adds +1; helpers contribute power only', () => {
|
||||||
|
expect(computeDuration('JUMP', 1, crew('SCIENTIST'), [])).toBe(4) // 3 + 1 mismatch
|
||||||
|
expect(computeDuration('JUMP', 1, crew('SCIENTIST'), [crew('PILOT')])).toBe(3) // ceil(3/2) + 1 — power 2, mismatch still on the lead
|
||||||
|
expect(computeDuration('EXPLORE', 1, crew('SCIENTIST'), [crew('PILOT', 'QUICK HANDS')])).toBe(2) // 4/2 — the helper's trait does not apply
|
||||||
|
})
|
||||||
|
it('STEADY UNDER PRESSURE cancels the mismatch penalty and adds nothing of its own', () => {
|
||||||
|
expect(computeDuration('JUMP', 1, crew('SCIENTIST', 'STEADY UNDER PRESSURE'), [])).toBe(3)
|
||||||
|
expect(computeDuration('EXPLORE', 1, crew('SCIENTIST', 'STEADY UNDER PRESSURE'), [])).toBe(4)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('floor', () => {
|
||||||
|
it('never returns below 1 turn', () => {
|
||||||
|
const lead = crew('PILOT', 'QUICK HANDS')
|
||||||
|
expect(computeDuration('JUMP', 1, lead, [crew('PILOT'), crew('PILOT')], () => 3)).toBe(1) // ceil(3/9) − 1 = 0 → floor 1
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// All 15 duration traits from spec §5, each tested once in its own action context (plus its
|
||||||
|
// non-applicable types). target 'SHIP_UPGRADE' stands for the whole "SHIP work" class.
|
||||||
|
const TABLE: [trait: string, isGood: boolean, target: TaskType | 'ANY', delta: number][] = [
|
||||||
|
['RECKLESS COURAGE', true, 'JUMP', -1],
|
||||||
|
['CALM IN A CRISIS', true, 'EXPLORE', -1],
|
||||||
|
['FIXES ANYTHING', true, 'SHIP_UPGRADE', -1],
|
||||||
|
['READS STARS BLIND', true, 'JUMP', -1],
|
||||||
|
['QUICK HANDS', true, 'ANY', -1],
|
||||||
|
['IRON WILL', true, 'RESEARCH', -1],
|
||||||
|
['RIGID — SLOW TO ADAPT', false, 'RESEARCH', 1],
|
||||||
|
['OVERCAUTIOUS', false, 'ANY', 1],
|
||||||
|
['SLOWS THE CREW DOWN', false, 'ANY', 1],
|
||||||
|
['CARELESS WITH FUSES', false, 'SHIP_UPGRADE', 1],
|
||||||
|
['HOARDS RATIONS', false, 'SHIP_UPGRADE', 1],
|
||||||
|
['FORGETS TO EAT', false, 'EXPLORE', 1],
|
||||||
|
['ARGUES WITH EVERYONE', false, 'RESEARCH', 1],
|
||||||
|
['DOUBTS THE CAPTAIN', false, 'JUMP', 1],
|
||||||
|
]
|
||||||
|
|
||||||
|
describe('the 15 duration traits (spec §5, exact strings from crew.ts)', () => {
|
||||||
|
const applies = (type: TaskType, target: TaskType | 'ANY') => {
|
||||||
|
if (target === 'ANY') return true
|
||||||
|
if (target === type) return true
|
||||||
|
return SHIP.includes(target) && SHIP.includes(type) // "SHIP work" class: any SHIP type → any SHIP type
|
||||||
|
}
|
||||||
|
it('each trait shifts only its own action class, lead only, across all six types', () => {
|
||||||
|
for (const [trait, isGood, target, delta] of TABLE) {
|
||||||
|
for (const type of TYPES) {
|
||||||
|
const lead = isGood ? crew(PREFERRED_ROLES[type][0], trait) : crew(PREFERRED_ROLES[type][0], NEUTRAL_GOOD, trait)
|
||||||
|
expect(computeDuration(type, 1, lead, []), `${trait} → ${type}`).toBe(WORK[type] + (applies(type, target) ? delta : 0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('crew-costs — the §11 tuning surface', () => {
|
||||||
|
it('pins the balance knobs', () => {
|
||||||
|
expect(WORK_POINTS).toEqual({ EXPLORE: 4, JUMP_PER_HOP: 3, SHIP_WORK: 6, RESEARCH: 9 })
|
||||||
|
expect(XP_THRESHOLDS).toEqual([5, 10, 15, 20, 25])
|
||||||
|
expect(POWER_BANDS).toEqual([1, 1, 1, 2, 2, 3]) // L0–L2 → 1 · L3–L4 → 2 · L5 → 3
|
||||||
|
expect(STARTING_LEVELS.PILOT).toEqual({ NAVIGATION: 2, SCANNING: 0, ENGINEERING: 0, RESEARCH: 0 })
|
||||||
|
expect(STARTING_LEVELS.SCIENTIST).toEqual({ NAVIGATION: 0, SCANNING: 2, ENGINEERING: 0, RESEARCH: 2 })
|
||||||
|
expect(STARTING_LEVELS.COMMANDER).toEqual({ NAVIGATION: 0, SCANNING: 0, ENGINEERING: 0, RESEARCH: 0 })
|
||||||
|
expect(RECRUIT_CHANCE_BASE).toBe(0.18)
|
||||||
|
expect(RECRUIT_CHANCE_TALKER).toBe(0.3)
|
||||||
|
expect(Object.keys(TRAIT_DURATION_MODIFIERS)).toHaveLength(15) // all 15 duration traits of spec §5, nothing else
|
||||||
|
expect(TRAIT_DURATION_MODIFIERS[MISMATCH_CANCEL_TRAIT]).toEqual({}) // its effect is the cancel, not an additive modifier
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// Shared queue fixtures (file scope — reused by the queueTask and tickTurn blocks): the roster,
|
||||||
|
// a state factory (turn 10, empty queue) and a one-turn row factory.
|
||||||
|
// The roster: a PILOT lead, an ENGINEER helper, a SCIENTIST third member. `origin` fills
|
||||||
|
// the CrewDto shape (unused by the duration model but part of the type).
|
||||||
|
const CREW: CrewDto[] = [
|
||||||
|
{ id: 1, name: 'AVA VANCE', role: 'PILOT', traitGood: 'QUICK HANDS', traitBad: 'OVERCAUTIOUS', origin: 'STARTING CREW' },
|
||||||
|
{ id: 2, name: 'BEN OKONKWO', role: 'ENGINEER', traitGood: 'FIXES ANYTHING', traitBad: 'HOARDS RATIONS', origin: 'STARTING CREW' },
|
||||||
|
{ id: 3, name: 'CASS SORENSEN', role: 'SCIENTIST', traitGood: 'CALM IN A CRISIS', traitBad: 'FORGETS TO EAT', origin: 'STARTING CREW' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const state = (over: Partial<QueueState> = {}): QueueState => ({ turn: 10, crew: CREW, tasks: [], inventory: [], shipSystems: [], tech: [], ...over })
|
||||||
|
const task = (over: Partial<Task> = {}): Task => ({ id: 90, saveId: 1, type: 'SHIP_UPGRADE', payload: '{}', leadCrewId: 1, helpers: [], duration: 1, remaining: 1, status: 'ACTIVE', queuedAtTurn: 9, ...over })
|
||||||
|
|
||||||
|
describe('queueTask', () => {
|
||||||
|
// Sync twin of the rejects.toMatchObject house style — queueTask throws instead of rejecting.
|
||||||
|
const expectErr = (fn: () => unknown, status: number, message?: RegExp): void => {
|
||||||
|
let err: unknown
|
||||||
|
try {
|
||||||
|
fn()
|
||||||
|
} catch (e) {
|
||||||
|
err = e
|
||||||
|
}
|
||||||
|
expect(err).toBeInstanceOf(TaskError)
|
||||||
|
expect((err as TaskError).status).toBe(status)
|
||||||
|
if (message) expect((err as TaskError).message).toMatch(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
it('unknown lead or helper id → 404', () => {
|
||||||
|
expectErr(() => queueTask(state(), { type: 'EXPLORE', payload: { planetId: 5 }, leadCrewId: 42, helperCrewIds: [] }), 404, /Unknown crew member 42/)
|
||||||
|
expectErr(() => queueTask(state(), { type: 'EXPLORE', payload: { planetId: 5 }, leadCrewId: 1, helperCrewIds: [42] }), 404, /Unknown crew member 42/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('busy lead → 409 — already committed to a PENDING task (as lead or helper of one)', () => {
|
||||||
|
expectErr(() => queueTask(state({ tasks: [task({ status: 'PENDING' })] }), { type: 'EXPLORE', payload: { planetId: 5 }, leadCrewId: 1, helperCrewIds: [] }), 409, /AVA VANCE is already committed to a pending task/)
|
||||||
|
expectErr(() => queueTask(state({ tasks: [task({ id: 91, leadCrewId: 3, helpers: [1], status: 'PENDING' })] }), { type: 'EXPLORE', payload: { planetId: 5 }, leadCrewId: 1, helperCrewIds: [] }), 409, /AVA VANCE is already committed to a pending task/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('busy helper → 409 — on an ACTIVE task, or committed to a PENDING one', () => {
|
||||||
|
expectErr(() => queueTask(state({ tasks: [task({ leadCrewId: 3, helpers: [2] })] }), { type: 'EXPLORE', payload: { planetId: 5 }, leadCrewId: 1, helperCrewIds: [2] }), 409, /BEN OKONKWO is already busy/)
|
||||||
|
expectErr(() => queueTask(state({ tasks: [task({ id: 91, leadCrewId: 3, helpers: [2], status: 'PENDING' })] }), { type: 'EXPLORE', payload: { planetId: 5 }, leadCrewId: 1, helperCrewIds: [2] }), 409, /BEN OKONKWO is already committed to a pending task/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('in transit (a JUMP is ACTIVE) → 409 for a non-jump action', () => {
|
||||||
|
expectErr(() => queueTask(state({ tasks: [task({ id: 91, type: 'JUMP', leadCrewId: 3 })] }), { type: 'EXPLORE', payload: { planetId: 5 }, leadCrewId: 1, helperCrewIds: [] }), 409, /in transit/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('second jump → 409 while one is pending', () => {
|
||||||
|
expectErr(() => queueTask(state({ tasks: [task({ id: 91, type: 'JUMP', leadCrewId: 3, status: 'PENDING' })] }), { type: 'JUMP', payload: { systemId: 2, hops: 1 }, leadCrewId: 1, helperCrewIds: [] }), 409, /A jump is already queued/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('SHIP / RESEARCH cost deducts at queue time; shortfall → the existing 422', () => {
|
||||||
|
const hold = [{ kind: 'resource' as const, name: 'IRON', qty: 5 }, { kind: 'part' as const, name: 'ALLOY', qty: 4 }]
|
||||||
|
const systems = [{ id: 7, type: 'REACTOR', level: 2, capacity: 3 }]
|
||||||
|
const techRows = [{ id: 3, slug: 'REACTOR_OVERCLOCK' }] // the def's cost: 3 resources (TECHS)
|
||||||
|
const upgraded = queueTask(state({ inventory: hold, shipSystems: systems, tech: techRows }), { type: 'SHIP_UPGRADE', payload: { systemId: 7 }, leadCrewId: 2, helperCrewIds: [] })
|
||||||
|
expect(upgraded.inventory).toEqual([{ kind: 'resource', name: 'IRON', qty: 3 }, { kind: 'part', name: 'ALLOY', qty: 4 }]) // upgradeCost(2) = 2, oldest row first
|
||||||
|
const shortHold = [{ kind: 'resource' as const, name: 'IRON', qty: 2 }]
|
||||||
|
expectErr(() => queueTask(state({ inventory: shortHold, tech: techRows }), { type: 'RESEARCH', payload: { techId: 3 }, leadCrewId: 2, helperCrewIds: [] }), 422, /Insufficient resources in the cargo hold — need 3/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ACTIVE-vs-PENDING rule: PENDING while the lead is busy (no turn change); all free → ACTIVE', () => {
|
||||||
|
const s = state({ tasks: [task({ leadCrewId: 1 })] })
|
||||||
|
const pending = queueTask(s, { type: 'EXPLORE', payload: { planetId: 5 }, leadCrewId: 1, helperCrewIds: [2] })
|
||||||
|
expect(pending.task.status).toBe('PENDING')
|
||||||
|
expect(pending.task.remaining).toBe(computeDuration('EXPLORE', 0, CREW[0], [CREW[1]]))
|
||||||
|
expect(pending.task.queuedAtTurn).toBe(10)
|
||||||
|
expect(s.turn).toBe(10) // queueing never advances the turn — only the tick does
|
||||||
|
const active = queueTask(state(), { type: 'EXPLORE', payload: { planetId: 5 }, leadCrewId: 1, helperCrewIds: [2] })
|
||||||
|
expect(active.task.status).toBe('ACTIVE')
|
||||||
|
expect(active.task.remaining).toBe(computeDuration('EXPLORE', 0, CREW[0], [CREW[1]]))
|
||||||
|
expect(active.task.queuedAtTurn).toBe(10)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- The turn tick: decrement, resolve, FIFO auto-start (pure — no DB) -------------------
|
||||||
|
//
|
||||||
|
// tickTurn is the whole §3 tick over the same plain QueueState queueTask consumes. It owns
|
||||||
|
// the turn increment and nothing else: it applies no effect and runs no mission logic —
|
||||||
|
// the save.ts orchestrator (runTurn) calls the 4a resolvers for the returned `completed`
|
||||||
|
// tasks, in the order returned.
|
||||||
|
describe('tickTurn', () => {
|
||||||
|
// The queueTask block's file-scope fixture helpers (above): CREW = [1 AVA PILOT,
|
||||||
|
// 2 BEN ENGINEER, 3 CASS SCIENTIST]; state() → { turn: 10, crew: CREW, tasks: [], … };
|
||||||
|
// task() → a one-turn row. The tick never parses payloads — the targets below are inert.
|
||||||
|
const JUMP = (id: number, over: Partial<Task> = {}): Task => task({ id, type: 'JUMP', payload: '{"systemId":2,"hops":1}', ...over })
|
||||||
|
const EXPLORE = (id: number, planetId: number, over: Partial<Task> = {}): Task => task({ id, type: 'EXPLORE', payload: `{"planetId":${planetId}}`, ...over })
|
||||||
|
|
||||||
|
it('decrements every ACTIVE task by one; a task that hits 0 is DONE (its team freed); PENDING rows do not age; the input is never mutated', () => {
|
||||||
|
const s = state({
|
||||||
|
tasks: [
|
||||||
|
JUMP(1, { duration: 3, remaining: 3, leadCrewId: 1, queuedAtTurn: 8 }),
|
||||||
|
EXPLORE(2, 5, { leadCrewId: 3, helpers: [2], duration: 1, remaining: 1, queuedAtTurn: 9 }),
|
||||||
|
EXPLORE(3, 6, { leadCrewId: 1, duration: 4, remaining: 4, status: 'PENDING', queuedAtTurn: 10 }), // member 1 is on ACTIVE 1
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
const r = tickTurn(s)
|
||||||
|
expect(r.turn).toBe(11) // the tick is the increment
|
||||||
|
expect(r.tasks.find((t) => t.id === 1)!.remaining).toBe(2)
|
||||||
|
expect(r.tasks.find((t) => t.id === 1)!.status).toBe('ACTIVE')
|
||||||
|
expect(r.tasks.find((t) => t.id === 2)!.status).toBe('DONE')
|
||||||
|
expect(r.completed.map((t) => t.id)).toEqual([2])
|
||||||
|
expect(r.tasks.find((t) => t.id === 3)!.status).toBe('PENDING')
|
||||||
|
expect(r.tasks.find((t) => t.id === 3)!.remaining).toBe(4) // pending does not age
|
||||||
|
expect(s.tasks.find((t) => t.id === 1)!.remaining).toBe(3) // input state untouched
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a 3-deep PENDING chain on one lead: when the lead task completes, exactly ONE successor starts — earliest queuedAtTurn wins (Review Focus 2)', () => {
|
||||||
|
let s = state({
|
||||||
|
tasks: [
|
||||||
|
JUMP(9, { duration: 3, remaining: 1, leadCrewId: 1, queuedAtTurn: 5 }),
|
||||||
|
EXPLORE(10, 5, { leadCrewId: 1, duration: 2, remaining: 2, status: 'PENDING', queuedAtTurn: 8 }),
|
||||||
|
EXPLORE(11, 6, { leadCrewId: 1, duration: 2, remaining: 2, status: 'PENDING', queuedAtTurn: 9 }),
|
||||||
|
EXPLORE(12, 7, { leadCrewId: 1, duration: 1, remaining: 1, status: 'PENDING', queuedAtTurn: 10 }),
|
||||||
|
],
|
||||||
|
})
|
||||||
|
let r = tickTurn(s)
|
||||||
|
expect(r.completed.map((t) => t.id)).toEqual([9])
|
||||||
|
expect(r.tasks.find((t) => t.id === 9)!.status).toBe('DONE')
|
||||||
|
expect(r.tasks.find((t) => t.id === 10)!.status).toBe('ACTIVE') // earliest queuedAtTurn starts
|
||||||
|
expect(r.tasks.find((t) => t.id === 10)!.remaining).toBe(2) // full duration — first decrement next tick
|
||||||
|
expect(r.tasks.find((t) => t.id === 11)!.status).toBe('PENDING') // the others wait for their own tick
|
||||||
|
expect(r.tasks.find((t) => t.id === 12)!.status).toBe('PENDING')
|
||||||
|
|
||||||
|
// Walk the chain to the end: each successor starts on exactly the tick its predecessor completes.
|
||||||
|
const EXPECT: [completed: number[], active: number[]][] = [
|
||||||
|
[[], [10]],
|
||||||
|
[[10], [11]],
|
||||||
|
[[], [11]],
|
||||||
|
[[11], [12]],
|
||||||
|
[[12], []],
|
||||||
|
]
|
||||||
|
for (const [done, active] of EXPECT) {
|
||||||
|
s = { ...s, turn: r.turn, tasks: r.tasks }
|
||||||
|
r = tickTurn(s)
|
||||||
|
expect(r.completed.map((t) => t.id)).toEqual(done)
|
||||||
|
expect(r.tasks.filter((t) => t.status === 'ACTIVE').map((t) => t.id)).toEqual(active)
|
||||||
|
}
|
||||||
|
expect(r.turn).toBe(16) // 10 + 1 (the first tick) + 5 (the walk)
|
||||||
|
expect(r.tasks.every((t) => t.status === 'DONE')).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('same queuedAtTurn ties break by id, and a started task blocks a later one sharing a member — at most one start per freed member (Review Focus 2, corrupt-row half)', () => {
|
||||||
|
// queueTask forbids a member committed to two PENDINGs (rule 2), so this shape only
|
||||||
|
// exists on admin-corrupted rows — the tick must still be deterministic about it.
|
||||||
|
const s = state({
|
||||||
|
tasks: [
|
||||||
|
JUMP(19, { duration: 1, remaining: 1, leadCrewId: 1, queuedAtTurn: 5 }),
|
||||||
|
EXPLORE(20, 5, { leadCrewId: 2, helpers: [3], duration: 2, remaining: 2, status: 'PENDING', queuedAtTurn: 8 }),
|
||||||
|
EXPLORE(21, 6, { leadCrewId: 3, helpers: [2], duration: 2, remaining: 2, status: 'PENDING', queuedAtTurn: 8 }),
|
||||||
|
],
|
||||||
|
})
|
||||||
|
const r = tickTurn(s)
|
||||||
|
expect(r.tasks.find((t) => t.id === 20)!.status).toBe('ACTIVE') // (8, 20) < (8, 21) — starts first and takes members 2 and 3
|
||||||
|
expect(r.tasks.find((t) => t.id === 21)!.status).toBe('PENDING')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a JUMP and an EXPLORE can both resolve on the same tick — completion is location-independent (Review Focus 3, tick half)', () => {
|
||||||
|
const s = state({
|
||||||
|
tasks: [
|
||||||
|
EXPLORE(1, 5, { leadCrewId: 1, duration: 1, remaining: 1, queuedAtTurn: 8 }),
|
||||||
|
JUMP(2, { leadCrewId: 2, duration: 1, remaining: 1, queuedAtTurn: 8 }),
|
||||||
|
],
|
||||||
|
})
|
||||||
|
const r = tickTurn(s)
|
||||||
|
expect(r.completed.map((t) => t.id)).toEqual([1, 2]) // both this tick, queue order (explore first)
|
||||||
|
expect(r.tasks.find((t) => t.id === 1)!.status).toBe('DONE')
|
||||||
|
expect(r.tasks.find((t) => t.id === 2)!.status).toBe('DONE')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('free skip: an empty queue advances exactly one turn and changes nothing; a fully-free PENDING still starts (Review Focus 4)', () => {
|
||||||
|
const r = tickTurn(state())
|
||||||
|
expect(r.turn).toBe(11)
|
||||||
|
expect(r.tasks).toEqual([])
|
||||||
|
expect(r.completed).toEqual([])
|
||||||
|
|
||||||
|
// No ACTIVE tasks and a startable PENDING (a corrupt-row shape — a legal PENDING always
|
||||||
|
// has a busy member): the pass still starts it. Skipping means "no resolution", not
|
||||||
|
// "no starts".
|
||||||
|
const r2 = tickTurn(state({ tasks: [EXPLORE(30, 5, { leadCrewId: 1, helpers: [2, 3], duration: 3, remaining: 3, status: 'PENDING', queuedAtTurn: 9 })] }))
|
||||||
|
expect(r2.turn).toBe(11)
|
||||||
|
expect(r2.tasks.find((t) => t.id === 30)!.status).toBe('ACTIVE')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
// Pure task-engine model (spec §3–§4): the task types and the duration formula. No lib/db
|
||||||
|
// imports — the frontend imports this for the live duration preview in the crew picker
|
||||||
|
// (same precedent as tech.ts / ship-costs.ts).
|
||||||
|
import { MISMATCH_CANCEL_TRAIT, PREFERRED_ROLES, TRAIT_DURATION_MODIFIERS, WORK_POINTS } from './crew-costs'
|
||||||
|
import type { CrewMember } from './crew'
|
||||||
|
import type { CrewDto, InventoryItemDto } from './save'
|
||||||
|
import { BUILD_PART_COST, expandCost, totalQty, upgradeCost } from './ship-costs'
|
||||||
|
import { TECHS } from './tech'
|
||||||
|
|
||||||
|
export type TaskType = 'JUMP' | 'EXPLORE' | 'SHIP_UPGRADE' | 'SHIP_EXPAND' | 'SHIP_BUILD' | 'RESEARCH'
|
||||||
|
|
||||||
|
export type TaskStatus = 'ACTIVE' | 'PENDING' | 'DONE'
|
||||||
|
|
||||||
|
// One queued/active/done action (spec §3). `payload` is a JSON string whose shape depends on
|
||||||
|
// the TaskType: JUMP {systemId, hops} · SHIP_UPGRADE/EXPAND {systemId} · SHIP_BUILD {type} ·
|
||||||
|
// RESEARCH {techId} · EXPLORE {planetId}.
|
||||||
|
export interface Task {
|
||||||
|
id: number
|
||||||
|
saveId: number
|
||||||
|
type: TaskType
|
||||||
|
payload: string
|
||||||
|
leadCrewId: number
|
||||||
|
helpers: number[]
|
||||||
|
duration: number
|
||||||
|
remaining: number
|
||||||
|
status: TaskStatus
|
||||||
|
queuedAtTurn: number
|
||||||
|
}
|
||||||
|
|
||||||
|
// Work points per action (spec §4): JUMP scales with hop count, the rest are flat.
|
||||||
|
function workPoints(type: TaskType, hopCount: number): number {
|
||||||
|
switch (type) {
|
||||||
|
case 'JUMP':
|
||||||
|
return hopCount * WORK_POINTS.JUMP_PER_HOP
|
||||||
|
case 'EXPLORE':
|
||||||
|
return WORK_POINTS.EXPLORE
|
||||||
|
case 'RESEARCH':
|
||||||
|
return WORK_POINTS.RESEARCH
|
||||||
|
default:
|
||||||
|
return WORK_POINTS.SHIP_WORK // SHIP_UPGRADE | SHIP_EXPAND | SHIP_BUILD
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// One trait's modifier for a lead on an action type: its per-type entry plus the 'ANY' entry.
|
||||||
|
// Traits without a map entry contribute 0.
|
||||||
|
function traitModifier(trait: string, type: TaskType): number {
|
||||||
|
const mods = TRAIT_DURATION_MODIFIERS[trait]
|
||||||
|
if (!mods) return 0
|
||||||
|
return (mods[type] ?? 0) + (mods['ANY'] ?? 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// duration = max(1, ceil(work / totalPower) + mismatchPenalty + traitModifierSum) — spec §4.
|
||||||
|
// totalPower = Σ powerOf over the WHOLE team (lead + helpers); the default powerOf is the
|
||||||
|
// constant 1 until PR B feeds the skill band. The mismatch penalty and the trait modifiers
|
||||||
|
// apply to the LEAD only — helpers contribute power, are never penalised, and their traits do
|
||||||
|
// not apply. `hopCount` is only meaningful for JUMP (pass 1 for the other types).
|
||||||
|
export function computeDuration(
|
||||||
|
type: TaskType,
|
||||||
|
hopCount: number,
|
||||||
|
lead: CrewMember,
|
||||||
|
helpers: CrewMember[],
|
||||||
|
powerOf: (m: CrewMember) => number = () => 1,
|
||||||
|
): number {
|
||||||
|
const totalPower = Math.max(1, [lead, ...helpers].reduce((sum, m) => sum + powerOf(m), 0))
|
||||||
|
const mismatchPenalty = lead.traitGood === MISMATCH_CANCEL_TRAIT || PREFERRED_ROLES[type].includes(lead.role) ? 0 : 1
|
||||||
|
const traitModifierSum = traitModifier(lead.traitGood, type) + traitModifier(lead.traitBad, type)
|
||||||
|
return Math.max(1, Math.ceil(workPoints(type, hopCount) / totalPower) + mismatchPenalty + traitModifierSum)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Queueing: validation + row construction (pure, no DB) -------------------------------
|
||||||
|
//
|
||||||
|
// queueTask runs over a plain snapshot of the save (QueueState) and decides whether a new
|
||||||
|
// task can be queued and what row it becomes. Pure like crew.ts / ship-costs.ts — the route
|
||||||
|
// (a later task) maps schema rows into QueueState, calls queueTask, and persists the result:
|
||||||
|
// insert the task row (adding `id` + `saveId` at the DB boundary) and the deducted hold.
|
||||||
|
|
||||||
|
// Carries an HTTP status so route handlers can map failures to responses without re-parsing
|
||||||
|
// (same pattern as JumpError / ShipError / ResearchError / ExploreError).
|
||||||
|
export class TaskError extends Error {
|
||||||
|
constructor(
|
||||||
|
public readonly status: number,
|
||||||
|
message: string,
|
||||||
|
) {
|
||||||
|
super(message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The queueing request — the existing endpoints' bodies plus the crew team. Payload field
|
||||||
|
// names follow the routes (the spec's names differ):
|
||||||
|
// JUMP { systemId, hops } — the route computes `hops` with jumpToSystem's logic
|
||||||
|
// (reachableWithin + NAV AI) and passes it in; the body field is `systemId`, not `toSystemId`
|
||||||
|
// EXPLORE { planetId }
|
||||||
|
// SHIP_UPGRADE { systemId } · SHIP_EXPAND { systemId } · SHIP_BUILD { type }
|
||||||
|
// RESEARCH { techId } — the tech row's id, not the slug
|
||||||
|
export interface QueueTaskRequest {
|
||||||
|
type: TaskType
|
||||||
|
payload: Record<string, unknown>
|
||||||
|
leadCrewId: number
|
||||||
|
helperCrewIds: number[]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Plain per-save snapshot the decision runs over — the route maps schema rows into these
|
||||||
|
// (same row↔domain boundary as the tasks table in save.ts).
|
||||||
|
export interface QueueState {
|
||||||
|
turn: number
|
||||||
|
crew: CrewDto[]
|
||||||
|
tasks: Task[]
|
||||||
|
inventory: InventoryItemDto[] // cargo hold, id order (oldest first)
|
||||||
|
shipSystems: { id: number; type: string; level: number; capacity: number }[] // UPGRADE/EXPAND costs scale with the target's current level/capacity
|
||||||
|
tech: { id: number; slug: string }[] // RESEARCH cost comes from the matching TECHS def, like research.ts
|
||||||
|
}
|
||||||
|
|
||||||
|
// The new row minus the two values only the DB boundary knows: `id` (autoincrement) and
|
||||||
|
// `saveId` (filled in by save.ts's row↔Task mapping on insert).
|
||||||
|
export interface QueueResult {
|
||||||
|
task: Omit<Task, 'id' | 'saveId'>
|
||||||
|
inventory: InventoryItemDto[] // unchanged for JUMP/EXPLORE; deducted for SHIP_* / RESEARCH
|
||||||
|
}
|
||||||
|
|
||||||
|
// Queue a task. Validation order: unknown crew (404) → busy (409) → in transit (409, all
|
||||||
|
// types) → second jump (409) → cost (422, SHIP_* / RESEARCH only). Never advances the turn.
|
||||||
|
export function queueTask(state: QueueState, req: QueueTaskRequest): QueueResult {
|
||||||
|
const lead = state.crew.find((c) => c.id === req.leadCrewId)
|
||||||
|
if (!lead) throw new TaskError(404, `Unknown crew member ${req.leadCrewId}`)
|
||||||
|
const helpers: CrewDto[] = []
|
||||||
|
for (const id of req.helperCrewIds) {
|
||||||
|
const helper = state.crew.find((c) => c.id === id)
|
||||||
|
if (!helper) throw new TaskError(404, `Unknown crew member ${id}`)
|
||||||
|
helpers.push(helper)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Busy (409). Spec §3: one ACTIVE task per crew member, and a lead may chain one PENDING
|
||||||
|
// task behind it (FIFO — auto-starts when the current one completes). So: any crew member
|
||||||
|
// committed to a PENDING task is blocked; a helper on an ACTIVE task is blocked; a lead on
|
||||||
|
// an ACTIVE task passes and the new task is queued PENDING behind it.
|
||||||
|
const inStatus = (id: number, status: TaskStatus) => state.tasks.some((t) => t.status === status && (t.leadCrewId === id || t.helpers.includes(id)))
|
||||||
|
const checkBusy = (c: CrewDto, isLead: boolean) => {
|
||||||
|
if (inStatus(c.id, 'PENDING')) throw new TaskError(409, `${c.name} is already committed to a pending task`)
|
||||||
|
if (!isLead && inStatus(c.id, 'ACTIVE')) throw new TaskError(409, `${c.name} is already busy`)
|
||||||
|
}
|
||||||
|
checkBusy(lead, true)
|
||||||
|
for (const helper of helpers) checkBusy(helper, false)
|
||||||
|
|
||||||
|
// In transit (409): while any JUMP is ACTIVE, no new tasks of any type (spec §3).
|
||||||
|
const jumps = state.tasks.filter((t) => t.type === 'JUMP')
|
||||||
|
if (jumps.some((t) => t.status === 'ACTIVE')) throw new TaskError(409, 'A jump is in transit — no new tasks can be queued')
|
||||||
|
// Only one JUMP at a time, active or pending (two arrivals could never resolve on one tick).
|
||||||
|
// The ACTIVE half is already caught above, so this fires on a pending jump.
|
||||||
|
if (req.type === 'JUMP' && jumps.some((t) => t.status !== 'DONE')) throw new TaskError(409, 'A jump is already queued')
|
||||||
|
|
||||||
|
// Costs deduct at queue time (spec §3) — the existing cost logic from ship-costs.ts /
|
||||||
|
// tech.ts and spendItems' 422. JUMP/EXPLORE have no resource cost. Target existence and
|
||||||
|
// the 409 gates (max level / capacity, not built, already built, build gate, tech prereqs)
|
||||||
|
// stay in the routes with their existing codes — the route resolves ids before calling.
|
||||||
|
let inventory = state.inventory
|
||||||
|
if (req.type === 'SHIP_UPGRADE' || req.type === 'SHIP_EXPAND') {
|
||||||
|
const system = state.shipSystems.find((s) => s.id === req.payload.systemId)!
|
||||||
|
inventory = deduct(inventory, 'resource', req.type === 'SHIP_UPGRADE' ? upgradeCost(system.level) : expandCost(system.capacity))
|
||||||
|
} else if (req.type === 'SHIP_BUILD') {
|
||||||
|
inventory = deduct(inventory, 'part', BUILD_PART_COST)
|
||||||
|
} else if (req.type === 'RESEARCH') {
|
||||||
|
const def = TECHS.find((t) => t.slug === state.tech.find((r) => r.id === req.payload.techId)?.slug)!
|
||||||
|
inventory = deduct(inventory, def.costKind, def.costQty)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Success: duration from the Task-1 formula, status from what the team is doing right now.
|
||||||
|
// A crew member is "free" when on no ACTIVE/PENDING task; after the checks above only a
|
||||||
|
// lead chaining behind its own ACTIVE can be non-free.
|
||||||
|
const free = (id: number) => !inStatus(id, 'ACTIVE') && !inStatus(id, 'PENDING')
|
||||||
|
const hops = req.type === 'JUMP' ? (req.payload.hops as number) : 0
|
||||||
|
const duration = computeDuration(req.type, hops, lead, helpers)
|
||||||
|
const status: TaskStatus = [lead, ...helpers].every((c) => free(c.id)) ? 'ACTIVE' : 'PENDING'
|
||||||
|
|
||||||
|
return {
|
||||||
|
task: {
|
||||||
|
type: req.type,
|
||||||
|
payload: JSON.stringify(req.payload),
|
||||||
|
leadCrewId: req.leadCrewId,
|
||||||
|
helpers: req.helperCrewIds,
|
||||||
|
duration,
|
||||||
|
remaining: duration,
|
||||||
|
status,
|
||||||
|
queuedAtTurn: state.turn, // queueing is free — the turn advances only on the tick
|
||||||
|
},
|
||||||
|
inventory,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pure version of spendItems' consumption (lib/game/ship.ts): the total is checked up front
|
||||||
|
// (shortfall → the same 422 spendItems throws), then the oldest rows first (array order = id
|
||||||
|
// order); rows that hit zero are dropped. The input array is never mutated.
|
||||||
|
function deduct(items: InventoryItemDto[], kind: 'resource' | 'part', amount: number): InventoryItemDto[] {
|
||||||
|
if (totalQty(items, kind) < amount) {
|
||||||
|
throw new TaskError(422, `Insufficient ${kind === 'resource' ? 'resources' : 'parts'} in the cargo hold — need ${amount}`)
|
||||||
|
}
|
||||||
|
let remaining = amount
|
||||||
|
const out: InventoryItemDto[] = []
|
||||||
|
for (const item of items) {
|
||||||
|
if (item.kind !== kind) {
|
||||||
|
out.push(item)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const take = Math.min(item.qty, remaining)
|
||||||
|
remaining -= take
|
||||||
|
if (take < item.qty) out.push({ ...item, qty: item.qty - take })
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- The turn tick: decrement, resolve, FIFO auto-start (pure — no DB) -------------------
|
||||||
|
//
|
||||||
|
// tickTurn is the whole §3 tick over the same plain QueueState queueTask consumes. It owns
|
||||||
|
// the turn increment and nothing else: it applies no effect and runs no mission logic —
|
||||||
|
// the save.ts orchestrator (runTurn) calls the 4a resolvers for the returned `completed`
|
||||||
|
// tasks, in the order returned.
|
||||||
|
export interface TickResult {
|
||||||
|
turn: number // state.turn + 1 — the tick IS the turn increment
|
||||||
|
tasks: Task[] // every task, updated: ACTIVE decremented, finished → DONE, started PENDING → ACTIVE
|
||||||
|
completed: Task[] // the tasks that hit 0 this tick, in resolution order
|
||||||
|
}
|
||||||
|
|
||||||
|
const byQueueOrder = (a: Task, b: Task) => a.queuedAtTurn - b.queuedAtTurn || a.id - b.id
|
||||||
|
|
||||||
|
export function tickTurn(state: QueueState): TickResult {
|
||||||
|
const turn = state.turn + 1
|
||||||
|
const tasks = state.tasks.map((t) => ({ ...t })) // never mutate the input (house style — deduct)
|
||||||
|
|
||||||
|
// (a) every ACTIVE task ages by one; PENDING/DONE rows do not age.
|
||||||
|
for (const t of tasks) if (t.status === 'ACTIVE') t.remaining -= 1
|
||||||
|
|
||||||
|
// (b) everything that hit 0 resolves this tick. Marking DONE frees the whole team
|
||||||
|
// (busyness is derived from the tasks table — there is no crew status column to update).
|
||||||
|
// <= 0, not === 0: a corrupt row at or below zero still completes on the next tick
|
||||||
|
// instead of dead-ending the queue (spec focus 4: no dead ends).
|
||||||
|
const completed = tasks
|
||||||
|
.filter((t) => t.status === 'ACTIVE' && t.remaining <= 0)
|
||||||
|
.sort(byQueueOrder)
|
||||||
|
for (const t of completed) t.status = 'DONE'
|
||||||
|
|
||||||
|
// (c) auto-start: ONE forward pass over PENDING in (queuedAtTurn ASC, id ASC). A task starts
|
||||||
|
// (PENDING → ACTIVE, remaining unchanged — it keeps its full duration; its first decrement
|
||||||
|
// lands on the next tick) when its FULL team (lead + all helpers) is free: no member on an
|
||||||
|
// ACTIVE task, and no member committed to an EARLIER (queuedAtTurn, id) PENDING that is still
|
||||||
|
// pending. A member on a LATER PENDING does not block — this task has first claim, and once
|
||||||
|
// started it holds that member via the ACTIVE clause, blocking the later PENDING in the same
|
||||||
|
// pass. Under queueTask's invariants (one PENDING per member) the PENDING clause only bites
|
||||||
|
// on admin-corrupted rows, where it keeps the pass deterministic: of a contested member's
|
||||||
|
// PENDINGs the earliest (queuedAtTurn, id) always gets first claim, so at most ONE of their
|
||||||
|
// PENDINGs starts per tick (the FIFO chain of spec §3), and no PENDING starves behind a peer.
|
||||||
|
// A start only makes its team busier — never frees anyone — so a task that cannot start at
|
||||||
|
// its position cannot start later in the same pass: one pass is complete.
|
||||||
|
for (const t of tasks.filter((t) => t.status === 'PENDING').sort(byQueueOrder)) {
|
||||||
|
const free = (id: number) =>
|
||||||
|
!tasks.some((o) => o.status === 'ACTIVE' && (o.leadCrewId === id || o.helpers.includes(id))) &&
|
||||||
|
!tasks.some((o) => o.status === 'PENDING' && o.id !== t.id && byQueueOrder(o, t) < 0 && (o.leadCrewId === id || o.helpers.includes(id)))
|
||||||
|
if ([t.leadCrewId, ...t.helpers].every(free)) t.status = 'ACTIVE'
|
||||||
|
}
|
||||||
|
|
||||||
|
return { turn, tasks, completed }
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
// Shared fixture suite for the game tests (save.test.ts, the 5a route tests, and the later
|
||||||
|
// ship/research route tests): one deterministic world — seed '42', save stamped at the
|
||||||
|
// current schema version so no backfill runs — plus the crew and task-row minters the
|
||||||
|
// queueing tests use. Ids line up across worlds built in fresh files (same insert order),
|
||||||
|
// so two fixture worlds are comparable row for row.
|
||||||
|
import type { GameDb } from '@/lib/db/client'
|
||||||
|
import * as schema from '@/lib/db/schema'
|
||||||
|
import { SCHEMA_VERSION } from './save'
|
||||||
|
|
||||||
|
// Fixed so a fixture's event rows carry a stable created_at (tests never assert on it, but
|
||||||
|
// a wall-clock Date would make two fixture worlds differ byte-for-byte).
|
||||||
|
export const T0 = '2026-10-01T00:00:00.000Z'
|
||||||
|
|
||||||
|
// Origin (s0, id 1, current) — Outpost (s1, one hop: the jump target) — Farpoint (s2, two
|
||||||
|
// hops: beyond one-hop range, so the unreachable pre-check has a target to 409 on; with
|
||||||
|
// NAVIGATION AI researched it would be reachable). p0 'Alder' in s0, p1 'Basalt' in s1.
|
||||||
|
// No crew, tasks, ship, or tech rows — the caller mints exactly what a test needs.
|
||||||
|
export async function buildWorldFixture(
|
||||||
|
db: GameDb,
|
||||||
|
outpostDiscovered = false,
|
||||||
|
): Promise<{ sys1: number; p0: number; p1: number; farSystem: number }> {
|
||||||
|
const [save] = await db.db
|
||||||
|
.insert(schema.saves)
|
||||||
|
.values({ seed: '42', turn: 0, createdAt: T0, schemaVersion: SCHEMA_VERSION })
|
||||||
|
.returning()
|
||||||
|
const [s0] = await db.db
|
||||||
|
.insert(schema.solarSystems)
|
||||||
|
.values({ saveId: save.id, name: 'Origin', x: 50, y: 50, discovered: true, isCurrent: true })
|
||||||
|
.returning({ id: schema.solarSystems.id })
|
||||||
|
const [s1] = await db.db
|
||||||
|
.insert(schema.solarSystems)
|
||||||
|
.values({ saveId: save.id, name: 'Outpost', x: 55, y: 50, discovered: outpostDiscovered })
|
||||||
|
.returning({ id: schema.solarSystems.id })
|
||||||
|
const [s2] = await db.db
|
||||||
|
.insert(schema.solarSystems)
|
||||||
|
.values({ saveId: save.id, name: 'Farpoint', x: 60, y: 50, discovered: false })
|
||||||
|
.returning({ id: schema.solarSystems.id })
|
||||||
|
await db.db.insert(schema.jumpRoutes).values({ fromSystem: s0.id, toSystem: s1.id })
|
||||||
|
await db.db.insert(schema.jumpRoutes).values({ fromSystem: s1.id, toSystem: s0.id })
|
||||||
|
await db.db.insert(schema.jumpRoutes).values({ fromSystem: s1.id, toSystem: s2.id })
|
||||||
|
await db.db.insert(schema.jumpRoutes).values({ fromSystem: s2.id, toSystem: s1.id })
|
||||||
|
const [p0] = await db.db
|
||||||
|
.insert(schema.planets)
|
||||||
|
.values({ systemId: s0.id, parentId: null, name: 'Alder', type: 'ROCKY', hazard: false })
|
||||||
|
.returning({ id: schema.planets.id })
|
||||||
|
const [p1] = await db.db
|
||||||
|
.insert(schema.planets)
|
||||||
|
.values({ systemId: s1.id, parentId: null, name: 'Basalt', type: 'GAS', hazard: false })
|
||||||
|
.returning({ id: schema.planets.id })
|
||||||
|
return { sys1: s1.id, p0: p0.id, p1: p1.id, farSystem: s2.id }
|
||||||
|
}
|
||||||
|
|
||||||
|
// `count` identical crew members, in insertion order — the queueing tests need real crew
|
||||||
|
// ids to lead and help with.
|
||||||
|
export async function addCrew(db: GameDb, count: number): Promise<number[]> {
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const ids: number[] = []
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
const [row] = await db.db
|
||||||
|
.insert(schema.crew)
|
||||||
|
.values({ saveId: save.id, name: `CREW ${i + 1}`, role: 'PILOT', traitGood: 'QUICK HANDS', traitBad: 'OVERCAUTIOUS', origin: 'STARTING CREW' })
|
||||||
|
.returning({ id: schema.crew.id })
|
||||||
|
ids.push(row.id)
|
||||||
|
}
|
||||||
|
return ids
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mint one tasks-table row with a chosen state — the queueing/tick tests seed the queue
|
||||||
|
// directly instead of going through the routes (which would run the same validation).
|
||||||
|
export async function insertTaskRow(
|
||||||
|
db: GameDb,
|
||||||
|
over: { type: string; payload: object; leadCrewId: number; helpers: number[]; duration: number; remaining: number; status: string; queuedAtTurn: number },
|
||||||
|
): Promise<number> {
|
||||||
|
const [save] = await db.db.select().from(schema.saves).limit(1)
|
||||||
|
const [row] = await db.db
|
||||||
|
.insert(schema.tasks)
|
||||||
|
.values({ saveId: save.id, type: over.type, payload: JSON.stringify(over.payload), leadCrewId: over.leadCrewId, helpers: JSON.stringify(over.helpers), duration: over.duration, remaining: over.remaining, status: over.status, queuedAtTurn: over.queuedAtTurn })
|
||||||
|
.returning({ id: schema.tasks.id })
|
||||||
|
return row.id
|
||||||
|
}
|
||||||
+80
-3
@@ -20,6 +20,7 @@ describe('OpenAPI spec', () => {
|
|||||||
'/api/ship/upgrade',
|
'/api/ship/upgrade',
|
||||||
'/api/system',
|
'/api/system',
|
||||||
'/api/tech',
|
'/api/tech',
|
||||||
|
'/api/turn',
|
||||||
'/api/version',
|
'/api/version',
|
||||||
'/api/world',
|
'/api/world',
|
||||||
]);
|
]);
|
||||||
@@ -44,6 +45,23 @@ describe('OpenAPI spec', () => {
|
|||||||
expect(post.responses[status].content['application/json'].schema.$ref).toBe('#/components/schemas/Error');
|
expect(post.responses[status].content['application/json'].schema.$ref).toBe('#/components/schemas/Error');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The queued-ship-work requests: the action target plus the crew team (lead required,
|
||||||
|
// helpers optional) — the same team fields as JumpRequest / ExploreRequest.
|
||||||
|
const upgradeReq = openApiSpec.components.schemas.UpgradeRequest as { properties: Record<string, unknown>; required: string[] };
|
||||||
|
expect(Object.keys(upgradeReq.properties)).toEqual(['systemId', 'leadCrewId', 'helperCrewIds']);
|
||||||
|
expect(upgradeReq.required).toEqual(['systemId', 'leadCrewId']);
|
||||||
|
expect((upgradeReq.properties.helperCrewIds as { items: { type: string } }).items.type).toBe('integer');
|
||||||
|
|
||||||
|
const expandReq = openApiSpec.components.schemas.ExpandRequest as { properties: Record<string, unknown>; required: string[] };
|
||||||
|
expect(Object.keys(expandReq.properties)).toEqual(['systemId', 'leadCrewId', 'helperCrewIds']);
|
||||||
|
expect(expandReq.required).toEqual(['systemId', 'leadCrewId']);
|
||||||
|
expect((expandReq.properties.helperCrewIds as { items: { type: string } }).items.type).toBe('integer');
|
||||||
|
|
||||||
|
const buildReq = openApiSpec.components.schemas.BuildRequest as { properties: Record<string, unknown>; required: string[] };
|
||||||
|
expect(Object.keys(buildReq.properties)).toEqual(['type', 'leadCrewId', 'helperCrewIds']);
|
||||||
|
expect(buildReq.required).toEqual(['type', 'leadCrewId']);
|
||||||
|
expect((buildReq.properties.helperCrewIds as { items: { type: string } }).items.type).toBe('integer');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('describes the tech endpoints: GET /api/tech → Tech[], POST /api/research with error responses', () => {
|
it('describes the tech endpoints: GET /api/tech → Tech[], POST /api/research with error responses', () => {
|
||||||
@@ -61,6 +79,12 @@ describe('OpenAPI spec', () => {
|
|||||||
for (const status of ['400', '404', '409', '422'] as const) {
|
for (const status of ['400', '404', '409', '422'] as const) {
|
||||||
expect(post.responses[status].content['application/json'].schema.$ref).toBe('#/components/schemas/Error');
|
expect(post.responses[status].content['application/json'].schema.$ref).toBe('#/components/schemas/Error');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The queued-research request: the tech target plus the crew team (lead required, helpers optional).
|
||||||
|
const researchReq = openApiSpec.components.schemas.ResearchRequest as { properties: Record<string, unknown>; required: string[] };
|
||||||
|
expect(Object.keys(researchReq.properties)).toEqual(['techId', 'leadCrewId', 'helperCrewIds']);
|
||||||
|
expect(researchReq.required).toEqual(['techId', 'leadCrewId']);
|
||||||
|
expect((researchReq.properties.helperCrewIds as { items: { type: string } }).items.type).toBe('integer');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('describes the mission endpoints: GET /api/missions → Mission[], POST accept with error responses', () => {
|
it('describes the mission endpoints: GET /api/missions → Mission[], POST accept with error responses', () => {
|
||||||
@@ -96,10 +120,22 @@ describe('OpenAPI spec', () => {
|
|||||||
expect(get.responses['400'].content['application/json'].schema.$ref).toBe('#/components/schemas/Error');
|
expect(get.responses['400'].content['application/json'].schema.$ref).toBe('#/components/schemas/Error');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('describes /api/crew as an array of CrewMember and crewFound on ExploreResult', () => {
|
it('describes /api/crew as the CrewState { crew, tasks } object and crewFound on ExploreResult', () => {
|
||||||
const crew = openApiSpec.paths['/api/crew'].get.responses[200].content['application/json'].schema;
|
const crew = openApiSpec.paths['/api/crew'].get.responses[200].content['application/json'].schema;
|
||||||
expect(crew.type).toBe('array');
|
expect(crew.$ref).toBe('#/components/schemas/CrewState');
|
||||||
expect((crew.items as { $ref: string }).$ref).toBe('#/components/schemas/CrewMember');
|
|
||||||
|
const crewState = openApiSpec.components.schemas.CrewState as { properties: Record<string, unknown>; required: string[] };
|
||||||
|
expect(Object.keys(crewState.properties)).toEqual(['crew', 'tasks']);
|
||||||
|
expect(crewState.required).toEqual(['crew', 'tasks']);
|
||||||
|
expect((crewState.properties.crew as { items: { $ref: string } }).items.$ref).toBe('#/components/schemas/CrewMember');
|
||||||
|
expect((crewState.properties.tasks as { items: { $ref: string } }).items.$ref).toBe('#/components/schemas/TaskDto');
|
||||||
|
|
||||||
|
const taskDto = openApiSpec.components.schemas.TaskDto as { properties: Record<string, unknown>; required: string[] };
|
||||||
|
expect(Object.keys(taskDto.properties)).toEqual(['id', 'type', 'targetLabel', 'leadName', 'helperNames', 'remaining', 'status', 'leadCrewId', 'helperCrewIds']);
|
||||||
|
expect(taskDto.required).toEqual(['id', 'type', 'targetLabel', 'leadName', 'helperNames', 'remaining', 'status', 'leadCrewId', 'helperCrewIds']);
|
||||||
|
expect((taskDto.properties.type as { enum: string[] }).enum).toEqual(['JUMP', 'EXPLORE', 'SHIP_UPGRADE', 'SHIP_EXPAND', 'SHIP_BUILD', 'RESEARCH']);
|
||||||
|
expect((taskDto.properties.status as { enum: string[] }).enum).toEqual(['ACTIVE', 'PENDING']);
|
||||||
|
expect((taskDto.properties.helperCrewIds as { items: { type: string } }).items.type).toBe('integer');
|
||||||
|
|
||||||
const member = openApiSpec.components.schemas.CrewMember.properties;
|
const member = openApiSpec.components.schemas.CrewMember.properties;
|
||||||
expect(Object.keys(member)).toEqual(['id', 'name', 'role', 'trait_good', 'trait_bad', 'origin']);
|
expect(Object.keys(member)).toEqual(['id', 'name', 'role', 'trait_good', 'trait_bad', 'origin']);
|
||||||
@@ -113,6 +149,11 @@ describe('OpenAPI spec', () => {
|
|||||||
const system = openApiSpec.paths['/api/system'].get.responses[200].content['application/json'].schema;
|
const system = openApiSpec.paths['/api/system'].get.responses[200].content['application/json'].schema;
|
||||||
expect(system.$ref).toBe('#/components/schemas/SystemState');
|
expect(system.$ref).toBe('#/components/schemas/SystemState');
|
||||||
|
|
||||||
|
// The snapshot carries the active + pending task queue.
|
||||||
|
const systemState = openApiSpec.components.schemas.SystemState as { properties: Record<string, unknown>; required: string[] };
|
||||||
|
expect(systemState.required).toEqual(['systemId', 'systemName', 'planets', 'inventory', 'turn', 'tasks']);
|
||||||
|
expect((systemState.properties.tasks as { items: { $ref: string } }).items.$ref).toBe('#/components/schemas/TaskDto');
|
||||||
|
|
||||||
const explore = openApiSpec.paths['/api/explore'].post;
|
const explore = openApiSpec.paths['/api/explore'].post;
|
||||||
expect(explore.requestBody.content['application/json'].schema.$ref).toBe('#/components/schemas/ExploreRequest');
|
expect(explore.requestBody.content['application/json'].schema.$ref).toBe('#/components/schemas/ExploreRequest');
|
||||||
expect(explore.responses[200].content['application/json'].schema.$ref).toBe('#/components/schemas/ExploreResult');
|
expect(explore.responses[200].content['application/json'].schema.$ref).toBe('#/components/schemas/ExploreResult');
|
||||||
@@ -122,18 +163,54 @@ describe('OpenAPI spec', () => {
|
|||||||
for (const status of ['400', '404', '409'] as const) {
|
for (const status of ['400', '404', '409'] as const) {
|
||||||
expect(explore.responses[status].content['application/json'].schema.$ref).toBe('#/components/schemas/Error');
|
expect(explore.responses[status].content['application/json'].schema.$ref).toBe('#/components/schemas/Error');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The queued-scan request: the scan target plus the crew team (lead required, helpers optional).
|
||||||
|
const exploreReq = openApiSpec.components.schemas.ExploreRequest as { properties: Record<string, unknown>; required: string[] };
|
||||||
|
expect(Object.keys(exploreReq.properties)).toEqual(['planetId', 'leadCrewId', 'helperCrewIds']);
|
||||||
|
expect(exploreReq.required).toEqual(['planetId', 'leadCrewId']);
|
||||||
|
expect((exploreReq.properties.helperCrewIds as { items: { type: string } }).items.type).toBe('integer');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('describes the world endpoints as WorldState in and out', () => {
|
it('describes the world endpoints as WorldState in and out', () => {
|
||||||
const world = openApiSpec.paths['/api/world'].get.responses[200].content['application/json'].schema;
|
const world = openApiSpec.paths['/api/world'].get.responses[200].content['application/json'].schema;
|
||||||
expect(world.$ref).toBe('#/components/schemas/WorldState');
|
expect(world.$ref).toBe('#/components/schemas/WorldState');
|
||||||
|
|
||||||
|
// The snapshot carries the active + pending task queue.
|
||||||
|
const worldState = openApiSpec.components.schemas.WorldState as { properties: Record<string, unknown>; required: string[] };
|
||||||
|
expect(worldState.required).toEqual(['systems', 'edges', 'turn', 'tasks']);
|
||||||
|
expect((worldState.properties.tasks as { items: { $ref: string } }).items.$ref).toBe('#/components/schemas/TaskDto');
|
||||||
|
|
||||||
const jump = openApiSpec.paths['/api/jump'].post;
|
const jump = openApiSpec.paths['/api/jump'].post;
|
||||||
expect(jump.requestBody.content['application/json'].schema.$ref).toBe('#/components/schemas/JumpRequest');
|
expect(jump.requestBody.content['application/json'].schema.$ref).toBe('#/components/schemas/JumpRequest');
|
||||||
expect(jump.responses[200].content['application/json'].schema.$ref).toBe('#/components/schemas/WorldState');
|
expect(jump.responses[200].content['application/json'].schema.$ref).toBe('#/components/schemas/WorldState');
|
||||||
for (const status of ['400', '404', '409'] as const) {
|
for (const status of ['400', '404', '409'] as const) {
|
||||||
expect(jump.responses[status].content['application/json'].schema.$ref).toBe('#/components/schemas/Error');
|
expect(jump.responses[status].content['application/json'].schema.$ref).toBe('#/components/schemas/Error');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The queued-jump request: the jump target plus the crew team (lead required, helpers optional).
|
||||||
|
const jumpReq = openApiSpec.components.schemas.JumpRequest as { properties: Record<string, unknown>; required: string[] };
|
||||||
|
expect(Object.keys(jumpReq.properties)).toEqual(['systemId', 'leadCrewId', 'helperCrewIds']);
|
||||||
|
expect(jumpReq.required).toEqual(['systemId', 'leadCrewId']);
|
||||||
|
expect((jumpReq.properties.helperCrewIds as { items: { type: string } }).items.type).toBe('integer');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('describes the turn endpoint: POST /api/turn with no body → WorldState + tasks, 500 on internal error', () => {
|
||||||
|
const post = openApiSpec.paths['/api/turn'].post;
|
||||||
|
expect(post).not.toHaveProperty('requestBody');
|
||||||
|
expect(post.responses[200].content['application/json'].schema.$ref).toBe('#/components/schemas/TurnResult');
|
||||||
|
expect(post.responses[500].content['application/json'].schema.$ref).toBe('#/components/schemas/Error');
|
||||||
|
|
||||||
|
// TurnResult extends WorldState with the task queue after the tick.
|
||||||
|
const turnResult = openApiSpec.components.schemas.TurnResult as { allOf: unknown[] };
|
||||||
|
expect((turnResult.allOf[0] as { $ref: string }).$ref).toBe('#/components/schemas/WorldState');
|
||||||
|
const extra = (turnResult.allOf[1] as { properties: Record<string, unknown> }).properties;
|
||||||
|
expect(Object.keys(extra)).toEqual(['tasks']);
|
||||||
|
|
||||||
|
const props = openApiSpec.components.schemas.Task.properties;
|
||||||
|
expect(Object.keys(props)).toEqual(['id', 'saveId', 'type', 'payload', 'leadCrewId', 'helpers', 'duration', 'remaining', 'status', 'queuedAtTurn']);
|
||||||
|
expect((props.type as { enum: string[] }).enum).toEqual(['JUMP', 'EXPLORE', 'SHIP_UPGRADE', 'SHIP_EXPAND', 'SHIP_BUILD', 'RESEARCH']);
|
||||||
|
expect((props.status as { enum: string[] }).enum).toEqual(['ACTIVE', 'PENDING', 'DONE']);
|
||||||
|
expect((props.helpers as { items: { type: string } }).items.type).toBe('integer');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('keeps info.version in sync with package.json', () => {
|
it('keeps info.version in sync with package.json', () => {
|
||||||
|
|||||||
+205
-51
@@ -1,4 +1,5 @@
|
|||||||
import pkg from '@/package.json';
|
import pkg from '@/package.json';
|
||||||
|
import { MAX_TEAM_SIZE } from './game/crew';
|
||||||
|
|
||||||
// OpenAPI 3.1 document for the app's public JSON API, kept in code so it can be
|
// OpenAPI 3.1 document for the app's public JSON API, kept in code so it can be
|
||||||
// served machine-readable at /api/openapi (see AGENTS.md "## API"). Must be updated
|
// served machine-readable at /api/openapi (see AGENTS.md "## API"). Must be updated
|
||||||
@@ -8,7 +9,7 @@ export const openApiSpec = {
|
|||||||
info: {
|
info: {
|
||||||
title: 'SpaceWanderer API',
|
title: 'SpaceWanderer API',
|
||||||
description:
|
description:
|
||||||
'JSON API for SpaceWanderer — a single-player turn-based space adventure (one save, no accounts). World endpoints: read the generated world state and jump between solar systems within range (adjacent by default; two hops once NAVIGATION AI is researched).',
|
'JSON API for SpaceWanderer — a single-player turn-based space adventure (one save, no accounts). World endpoints: read the generated world state. Jump, exploration, ship work and research queue a crew team (lead + helpers) and their effects land when the task completes on the turn tick — queueing spends no turn (jump range is adjacent by default, two hops once NAVIGATION AI is researched); mission accept is instant and free (no turn).',
|
||||||
// Sourced from package.json so it stays in sync with every version bump.
|
// Sourced from package.json so it stays in sync with every version bump.
|
||||||
version: pkg.version,
|
version: pkg.version,
|
||||||
},
|
},
|
||||||
@@ -50,11 +51,37 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
'/api/turn': {
|
||||||
|
post: {
|
||||||
|
summary: 'Advance exactly one turn (manual tick)',
|
||||||
|
description:
|
||||||
|
"Ticks the queue one turn — no request body: every ACTIVE task ages by one, tasks that reach 0 resolve (jump, scan, ship-work or research effects land, mission checks run for what resolved) and PENDING successors auto-start in FIFO order. An empty queue is a FREE SKIP — turn +1 with nothing else changed, always 200 (the UI's NEXT TURN button is never disabled; a task that fails to resolve simply does not land its effect). Returns the same world snapshot as GET /api/world, plus the task queue after the tick.",
|
||||||
|
operationId: 'nextTurn',
|
||||||
|
responses: {
|
||||||
|
200: {
|
||||||
|
description: 'World state after the tick, plus the task queue (every task row: ACTIVE, PENDING, DONE)',
|
||||||
|
content: {
|
||||||
|
'application/json': {
|
||||||
|
schema: { $ref: '#/components/schemas/TurnResult' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
500: {
|
||||||
|
description: 'Internal error — no domain failures escape the tick (a failed task is silently dropped, not an error)',
|
||||||
|
content: {
|
||||||
|
'application/json': {
|
||||||
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
'/api/jump': {
|
'/api/jump': {
|
||||||
post: {
|
post: {
|
||||||
summary: 'Jump to a solar system within range',
|
summary: 'Queue a jump to a solar system within range',
|
||||||
description:
|
description:
|
||||||
'Validates that the target is within jump range of the current system — one hop away, or two hops once NAVIGATION AI is researched (#35) — sets it as current (discovering it if new and generating its neighbours), advances the turn counter by the hop count and writes a jump event. Returns the fresh world state.',
|
'Queues a JUMP task with the given crew team (lead + helpers): validates that the target is within jump range of the current system (one hop away, or two hops once NAVIGATION AI is researched — #35) and that the team is free, then the move — target becomes current, discovered if new with its neighbours generated, jump event — lands when the task completes on the turn tick. Queueing spends no turn. Returns the fresh world state.',
|
||||||
operationId: 'jumpToSystem',
|
operationId: 'jumpToSystem',
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
@@ -66,7 +93,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
responses: {
|
responses: {
|
||||||
200: {
|
200: {
|
||||||
description: 'Fresh world state after the jump',
|
description: 'Fresh world state — the jump itself lands when the task completes on the turn tick',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/WorldState' },
|
schema: { $ref: '#/components/schemas/WorldState' },
|
||||||
@@ -74,7 +101,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
400: {
|
400: {
|
||||||
description: 'Malformed body or non-integer systemId',
|
description: 'Malformed body, a non-integer systemId/leadCrewId, a non-integer-array helperCrewIds, duplicate crew ids, or a team over the size cap',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -82,7 +109,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
404: {
|
404: {
|
||||||
description: 'Unknown system id',
|
description: 'Unknown system id or unknown crew member',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -90,7 +117,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
409: {
|
409: {
|
||||||
description: 'Target is outside jump range of the current system — more than one hop away, or more than two hops without NAVIGATION AI researched (or is the current system itself)',
|
description: 'Target is outside jump range of the current system (more than one hop away, or more than two without NAVIGATION AI; or is the current system itself) — or the crew team is blocked (a member committed to a pending task, a helper already busy, a jump in transit, or a jump already queued)',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -120,9 +147,9 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
'/api/explore': {
|
'/api/explore': {
|
||||||
post: {
|
post: {
|
||||||
summary: 'Explore a planet or moon',
|
summary: 'Queue a scan of a planet or moon',
|
||||||
description:
|
description:
|
||||||
'Scans one body of the save with a deterministic haul (a resource and/or a part, or nothing), marks it explored, increments the turn counter, accumulates finds into inventory and writes an explore event. Returns the fresh system state plus this scan outcome.',
|
'Queues an EXPLORE task with the given crew team (lead + helpers): validates that the body exists and has not been scanned yet, and that the team is free, then the scan — a deterministic haul into the cargo hold, the explored flag, the ~18% crew roll and the explore event — lands when the task completes on the turn tick. Queueing spends no turn. Returns the fresh system state, with the outcome key empty and crewFound null until the scan resolves.',
|
||||||
operationId: 'explorePlanet',
|
operationId: 'explorePlanet',
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
@@ -134,7 +161,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
responses: {
|
responses: {
|
||||||
200: {
|
200: {
|
||||||
description: 'Fresh system state plus the scan outcome',
|
description: 'Fresh system state — the scan itself lands when the task completes on the turn tick (outcome empty, crewFound null)',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/ExploreResult' },
|
schema: { $ref: '#/components/schemas/ExploreResult' },
|
||||||
@@ -142,7 +169,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
400: {
|
400: {
|
||||||
description: 'Malformed body or non-integer planetId',
|
description: 'Malformed body, a non-integer planetId/leadCrewId, a non-integer-array helperCrewIds, duplicate crew ids, or a team over the size cap',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -150,7 +177,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
404: {
|
404: {
|
||||||
description: 'Unknown planet id',
|
description: 'Unknown planet id or unknown crew member',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -158,7 +185,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
409: {
|
409: {
|
||||||
description: 'Body was already explored (each can only be scanned once)',
|
description: 'Body was already explored (each can only be scanned once) — or the crew team is blocked (a member committed to a pending task, a helper already busy, a jump in transit, or a jump already queued)',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -172,14 +199,14 @@ export const openApiSpec = {
|
|||||||
get: {
|
get: {
|
||||||
summary: 'Crew roster',
|
summary: 'Crew roster',
|
||||||
description:
|
description:
|
||||||
'The ship crew in join order — the starting crew (seeded on new game) plus members found while exploring planets/moons. Each member has one good and one bad trait and an origin. Auto-initializes a new game when no save exists yet.',
|
'The ship crew in join order — the starting crew (seeded on new game) plus members found while exploring planets/moons — returned as the { crew, tasks } object, wrapped with the active + pending task queue. Each member has one good and one bad trait and an origin. Auto-initializes a new game when no save exists yet.',
|
||||||
operationId: 'getCrew',
|
operationId: 'getCrew',
|
||||||
responses: {
|
responses: {
|
||||||
200: {
|
200: {
|
||||||
description: 'Crew roster',
|
description: 'Crew roster plus the active + pending task queue',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { type: 'array', items: { $ref: '#/components/schemas/CrewMember' } },
|
schema: { $ref: '#/components/schemas/CrewState' },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -208,7 +235,7 @@ export const openApiSpec = {
|
|||||||
post: {
|
post: {
|
||||||
summary: 'Upgrade a ship system',
|
summary: 'Upgrade a ship system',
|
||||||
description:
|
description:
|
||||||
"Level up a built ship system by one (capped at max level). Costs `level` units of any resource, consumed from the oldest cargo row first, plus a turn. Returns the fresh ship state.",
|
"Level up a built ship system by one (capped at max level). Assign the crew team and queue the SHIP_UPGRADE task — the cost (`level` units of any resource) is deducted at queue time and the level-up lands when the task completes on the turn tick; queueing spends no turn. Returns the fresh ship state.",
|
||||||
operationId: 'upgradeShipSystem',
|
operationId: 'upgradeShipSystem',
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
@@ -220,7 +247,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
responses: {
|
responses: {
|
||||||
200: {
|
200: {
|
||||||
description: 'Fresh ship state after the upgrade',
|
description: 'Fresh ship state — the upgrade lands when the task completes on the turn tick',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/ShipState' },
|
schema: { $ref: '#/components/schemas/ShipState' },
|
||||||
@@ -228,7 +255,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
400: {
|
400: {
|
||||||
description: 'Malformed body or non-integer systemId',
|
description: 'Malformed body, a non-integer systemId/leadCrewId, a non-integer-array helperCrewIds, duplicate crew ids, or a team over the size cap',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -236,7 +263,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
404: {
|
404: {
|
||||||
description: 'Unknown ship system id',
|
description: 'Unknown ship system id or unknown crew member',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -244,7 +271,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
409: {
|
409: {
|
||||||
description: 'System is not built or already at max level',
|
description: 'System is not built or already at max level — or the crew team is blocked (a member committed to a pending task, a helper already busy, a jump in transit, or a jump already queued)',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -266,7 +293,7 @@ export const openApiSpec = {
|
|||||||
post: {
|
post: {
|
||||||
summary: 'Expand a ship system',
|
summary: 'Expand a ship system',
|
||||||
description:
|
description:
|
||||||
"Raise a built ship system's capacity by one (capped at max capacity). Costs `capacity` units of any resource, consumed from the oldest cargo row first, plus a turn. Returns the fresh ship state.",
|
"Raise a built ship system's capacity by one (capped at max capacity). Assign the crew team and queue the SHIP_EXPAND task — the cost (`capacity` units of any resource) is deducted at queue time and the capacity bump lands when the task completes on the turn tick; queueing spends no turn. Returns the fresh ship state.",
|
||||||
operationId: 'expandShipSystem',
|
operationId: 'expandShipSystem',
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
@@ -278,7 +305,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
responses: {
|
responses: {
|
||||||
200: {
|
200: {
|
||||||
description: 'Fresh ship state after the expansion',
|
description: 'Fresh ship state — the expansion lands when the task completes on the turn tick',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/ShipState' },
|
schema: { $ref: '#/components/schemas/ShipState' },
|
||||||
@@ -286,7 +313,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
400: {
|
400: {
|
||||||
description: 'Malformed body or non-integer systemId',
|
description: 'Malformed body, a non-integer systemId/leadCrewId, a non-integer-array helperCrewIds, duplicate crew ids, or a team over the size cap',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -294,7 +321,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
404: {
|
404: {
|
||||||
description: 'Unknown ship system id',
|
description: 'Unknown ship system id or unknown crew member',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -302,7 +329,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
409: {
|
409: {
|
||||||
description: 'System is not built or already at max capacity',
|
description: 'System is not built or already at max capacity — or the crew team is blocked (a member committed to a pending task, a helper already busy, a jump in transit, or a jump already queued)',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -324,7 +351,7 @@ export const openApiSpec = {
|
|||||||
post: {
|
post: {
|
||||||
summary: 'Build a ship system',
|
summary: 'Build a ship system',
|
||||||
description:
|
description:
|
||||||
'Build an unbuilt ship system type at base values. Costs a flat amount of parts, consumed from the oldest cargo row first, plus a turn. Returns the fresh ship state.',
|
'Build an unbuilt ship system type at base values. Assign the crew team and queue the SHIP_BUILD task — the flat parts cost is deducted at queue time and the build lands when the task completes on the turn tick; queueing spends no turn. Returns the fresh ship state.',
|
||||||
operationId: 'buildShipSystem',
|
operationId: 'buildShipSystem',
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
@@ -336,7 +363,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
responses: {
|
responses: {
|
||||||
200: {
|
200: {
|
||||||
description: 'Fresh ship state after the build',
|
description: 'Fresh ship state — the build lands when the task completes on the turn tick',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/ShipState' },
|
schema: { $ref: '#/components/schemas/ShipState' },
|
||||||
@@ -344,7 +371,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
400: {
|
400: {
|
||||||
description: 'Malformed body or empty type',
|
description: 'Malformed body, a non-string or empty type, a non-integer leadCrewId, a non-integer-array helperCrewIds, duplicate crew ids, or a team over the size cap',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -352,7 +379,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
404: {
|
404: {
|
||||||
description: 'Unknown ship system type',
|
description: 'Unknown ship system type or unknown crew member',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -360,7 +387,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
409: {
|
409: {
|
||||||
description: 'System is already built',
|
description: 'System is already built, or the build-gate tech is not researched yet — or the crew team is blocked (a member committed to a pending task, a helper already busy, a jump in transit, or a jump already queued)',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -400,7 +427,7 @@ export const openApiSpec = {
|
|||||||
post: {
|
post: {
|
||||||
summary: 'Research a tech',
|
summary: 'Research a tech',
|
||||||
description:
|
description:
|
||||||
"Validates the prerequisites (409, naming what is missing) and the cost against the cargo hold (422), spends the cost from the oldest row first, marks the tech researched, increments the turn counter and writes a research event. Returns the fresh tech tree state.",
|
"Validates the prerequisites (409, naming what is missing) and assigns the crew team, queueing the RESEARCH task — the tech cost is deducted at queue time and the tech is marked researched (unlock effect included) when the task completes on the turn tick; queueing spends no turn. Returns the fresh tech tree state.",
|
||||||
operationId: 'researchTech',
|
operationId: 'researchTech',
|
||||||
requestBody: {
|
requestBody: {
|
||||||
required: true,
|
required: true,
|
||||||
@@ -412,7 +439,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
responses: {
|
responses: {
|
||||||
200: {
|
200: {
|
||||||
description: 'Fresh tech tree state after the research',
|
description: 'Fresh tech tree state — the research lands when the task completes on the turn tick',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { type: 'array', items: { $ref: '#/components/schemas/Tech' } },
|
schema: { type: 'array', items: { $ref: '#/components/schemas/Tech' } },
|
||||||
@@ -420,7 +447,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
400: {
|
400: {
|
||||||
description: 'Malformed body or non-integer techId',
|
description: 'Malformed body, a non-integer techId/leadCrewId, a non-integer-array helperCrewIds, duplicate crew ids, or a team over the size cap',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -428,7 +455,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
404: {
|
404: {
|
||||||
description: 'Unknown tech id',
|
description: 'Unknown tech id or unknown crew member',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -436,7 +463,7 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
409: {
|
409: {
|
||||||
description: 'Tech is already researched or a prerequisite is not researched yet (message names the missing prereq)',
|
description: 'Tech is already researched or a prerequisite is not researched yet (message names the missing prereq) — or the crew team is blocked (a member committed to a pending task, a helper already busy, a jump in transit, or a jump already queued)',
|
||||||
content: {
|
content: {
|
||||||
'application/json': {
|
'application/json': {
|
||||||
schema: { $ref: '#/components/schemas/Error' },
|
schema: { $ref: '#/components/schemas/Error' },
|
||||||
@@ -476,7 +503,7 @@ export const openApiSpec = {
|
|||||||
post: {
|
post: {
|
||||||
summary: 'Accept a mission',
|
summary: 'Accept a mission',
|
||||||
description:
|
description:
|
||||||
"Makes an AVAILABLE contract the single ACTIVE one (409 while another is active, or when it isn't AVAILABLE). Costs a turn and writes a mission event. Returns the fresh board.",
|
"Makes an AVAILABLE contract the single ACTIVE one (409 while another is active, or when it isn't AVAILABLE). Instant and free — no turn, no body — and writes a mission event at the current turn. Returns the fresh board.",
|
||||||
operationId: 'acceptMission',
|
operationId: 'acceptMission',
|
||||||
parameters: [
|
parameters: [
|
||||||
{
|
{
|
||||||
@@ -827,16 +854,91 @@ export const openApiSpec = {
|
|||||||
maxItems: 2,
|
maxItems: 2,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
turn: { type: 'integer', description: 'Turn counter — one per jump' },
|
turn: { type: 'integer', description: 'Turn counter — advances on the turn tick; queued actions (jump, exploration, ship work, research) cost no turn, and mission accept is free' },
|
||||||
|
tasks: {
|
||||||
|
type: 'array',
|
||||||
|
description: 'The active + pending task queue — the ACTIVE block first, then the PENDING block, each ordered by (queuedAtTurn, id); DONE rows never appear',
|
||||||
|
items: { $ref: '#/components/schemas/TaskDto' },
|
||||||
},
|
},
|
||||||
required: ['systems', 'edges', 'turn'],
|
},
|
||||||
|
required: ['systems', 'edges', 'turn', 'tasks'],
|
||||||
|
},
|
||||||
|
TurnResult: {
|
||||||
|
allOf: [
|
||||||
|
{ $ref: '#/components/schemas/WorldState' },
|
||||||
|
{
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
tasks: {
|
||||||
|
type: 'array',
|
||||||
|
description:
|
||||||
|
'Every task row after the tick — ACTIVE (decremented this turn, or auto-started this turn), PENDING (waiting for its team to free) and DONE (resolved this tick or earlier)',
|
||||||
|
items: { $ref: '#/components/schemas/Task' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
required: ['tasks'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
Task: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
id: { type: 'integer' },
|
||||||
|
saveId: { type: 'integer' },
|
||||||
|
type: { type: 'string', enum: ['JUMP', 'EXPLORE', 'SHIP_UPGRADE', 'SHIP_EXPAND', 'SHIP_BUILD', 'RESEARCH'] },
|
||||||
|
payload: {
|
||||||
|
type: 'string',
|
||||||
|
description: 'JSON per type: JUMP {systemId, hops} · SHIP_UPGRADE/EXPAND {systemId} · SHIP_BUILD {type} · RESEARCH {techId} · EXPLORE {planetId}',
|
||||||
|
},
|
||||||
|
leadCrewId: { type: 'integer', description: 'crew.id of the team lead' },
|
||||||
|
helpers: { type: 'array', description: 'crew.id of the supporting crew (empty when none)', items: { type: 'integer' } },
|
||||||
|
duration: { type: 'integer' },
|
||||||
|
remaining: { type: 'integer' },
|
||||||
|
status: { type: 'string', enum: ['ACTIVE', 'PENDING', 'DONE'] },
|
||||||
|
queuedAtTurn: { type: 'integer' },
|
||||||
|
},
|
||||||
|
required: ['id', 'saveId', 'type', 'payload', 'leadCrewId', 'helpers', 'duration', 'remaining', 'status', 'queuedAtTurn'],
|
||||||
|
},
|
||||||
|
TaskDto: {
|
||||||
|
type: 'object',
|
||||||
|
description: 'One row of the snapshot task queue — the ACTIVE + PENDING rows of the tasks table as the GET snapshots expose them (DONE rows never appear)',
|
||||||
|
properties: {
|
||||||
|
id: { type: 'integer' },
|
||||||
|
type: { type: 'string', enum: ['JUMP', 'EXPLORE', 'SHIP_UPGRADE', 'SHIP_EXPAND', 'SHIP_BUILD', 'RESEARCH'] },
|
||||||
|
targetLabel: {
|
||||||
|
type: 'string',
|
||||||
|
description:
|
||||||
|
'The task target by display name — the jump destination, the scanned body, the ship system with the verb suffixed (e.g. Origin — upgrade), the built system type, or the researched tech; `unknown` when the target row no longer exists',
|
||||||
|
},
|
||||||
|
leadName: { type: 'string', description: 'The team lead by name; `unknown` when the crew row no longer exists' },
|
||||||
|
helperNames: { type: 'array', description: 'The supporting crew by name (empty when none)', items: { type: 'string' } },
|
||||||
|
remaining: { type: 'integer', description: 'Turns left — the stored row value (a pure read, not recomputed)' },
|
||||||
|
status: {
|
||||||
|
type: 'string',
|
||||||
|
enum: ['ACTIVE', 'PENDING'],
|
||||||
|
description: 'The row state — the ACTIVE block precedes the PENDING block in the array',
|
||||||
|
},
|
||||||
|
leadCrewId: { type: 'integer', description: 'crew.id of the team lead' },
|
||||||
|
helperCrewIds: {
|
||||||
|
type: 'array',
|
||||||
|
description: 'crew.id of the supporting crew (empty when none)',
|
||||||
|
items: { type: 'integer' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
required: ['id', 'type', 'targetLabel', 'leadName', 'helperNames', 'remaining', 'status', 'leadCrewId', 'helperCrewIds'],
|
||||||
},
|
},
|
||||||
JumpRequest: {
|
JumpRequest: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
systemId: { type: 'integer', description: 'solar_systems.id of the jump target' },
|
systemId: { type: 'integer', description: 'solar_systems.id of the jump target' },
|
||||||
|
leadCrewId: { type: 'integer', description: 'crew.id of the team lead — the member the queued task is committed to first' },
|
||||||
|
helperCrewIds: {
|
||||||
|
type: 'array',
|
||||||
|
description: `Optional supporting crew (crew.id) — the whole team, lead + helpers, holds at most ${MAX_TEAM_SIZE} distinct members, all of them free`,
|
||||||
|
items: { type: 'integer' },
|
||||||
},
|
},
|
||||||
required: ['systemId'],
|
},
|
||||||
|
required: ['systemId', 'leadCrewId'],
|
||||||
},
|
},
|
||||||
Planet: {
|
Planet: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
@@ -880,6 +982,23 @@ export const openApiSpec = {
|
|||||||
},
|
},
|
||||||
required: ['id', 'name', 'role', 'trait_good', 'trait_bad', 'origin'],
|
required: ['id', 'name', 'role', 'trait_good', 'trait_bad', 'origin'],
|
||||||
},
|
},
|
||||||
|
CrewState: {
|
||||||
|
type: 'object',
|
||||||
|
description: 'GET /api/crew response — the roster wrapped with the snapshot task queue (a bare array cannot carry a sibling tasks field)',
|
||||||
|
properties: {
|
||||||
|
crew: {
|
||||||
|
type: 'array',
|
||||||
|
description: 'The ship crew in join order — the starting crew (seeded on new game) plus members found while exploring',
|
||||||
|
items: { $ref: '#/components/schemas/CrewMember' },
|
||||||
|
},
|
||||||
|
tasks: {
|
||||||
|
type: 'array',
|
||||||
|
description: 'The active + pending task queue — the ACTIVE block first, then the PENDING block, each ordered by (queuedAtTurn, id); DONE rows never appear',
|
||||||
|
items: { $ref: '#/components/schemas/TaskDto' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
required: ['crew', 'tasks'],
|
||||||
|
},
|
||||||
ShipSystem: {
|
ShipSystem: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
@@ -900,7 +1019,7 @@ export const openApiSpec = {
|
|||||||
items: { $ref: '#/components/schemas/ShipSystem' },
|
items: { $ref: '#/components/schemas/ShipSystem' },
|
||||||
},
|
},
|
||||||
inventory: { type: 'array', items: { $ref: '#/components/schemas/InventoryItem' } },
|
inventory: { type: 'array', items: { $ref: '#/components/schemas/InventoryItem' } },
|
||||||
turn: { type: 'integer', description: 'Turn counter — one per jump, exploration or ship action' },
|
turn: { type: 'integer', description: 'Turn counter — advances on the turn tick; queued actions (jump, exploration, ship work, research) cost no turn, and mission accept is free' },
|
||||||
},
|
},
|
||||||
required: ['systems', 'inventory', 'turn'],
|
required: ['systems', 'inventory', 'turn'],
|
||||||
},
|
},
|
||||||
@@ -931,8 +1050,14 @@ export const openApiSpec = {
|
|||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
techId: { type: 'integer', description: 'tech.id of the tech to research' },
|
techId: { type: 'integer', description: 'tech.id of the tech to research' },
|
||||||
|
leadCrewId: { type: 'integer', description: 'crew.id of the team lead — the member the queued task is committed to first' },
|
||||||
|
helperCrewIds: {
|
||||||
|
type: 'array',
|
||||||
|
description: `Optional supporting crew (crew.id) — the whole team, lead + helpers, holds at most ${MAX_TEAM_SIZE} distinct members, all of them free`,
|
||||||
|
items: { type: 'integer' },
|
||||||
},
|
},
|
||||||
required: ['techId'],
|
},
|
||||||
|
required: ['techId', 'leadCrewId'],
|
||||||
},
|
},
|
||||||
Mission: {
|
Mission: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
@@ -954,7 +1079,7 @@ export const openApiSpec = {
|
|||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
id: { type: 'integer' },
|
id: { type: 'integer' },
|
||||||
turn: { type: 'integer', description: 'The save turn the action cost (new_game is 0)' },
|
turn: { type: 'integer', description: 'The save turn the event was written (new_game is 0)' },
|
||||||
type: { type: 'string', enum: ['new_game', 'jump', 'explore', 'research', 'upgrade', 'expand', 'build', 'mission'] },
|
type: { type: 'string', enum: ['new_game', 'jump', 'explore', 'research', 'upgrade', 'expand', 'build', 'mission'] },
|
||||||
message: { type: 'string' },
|
message: { type: 'string' },
|
||||||
createdAt: { type: 'string', description: 'ISO 8601 timestamp' },
|
createdAt: { type: 'string', description: 'ISO 8601 timestamp' },
|
||||||
@@ -965,22 +1090,40 @@ export const openApiSpec = {
|
|||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
systemId: { type: 'integer', description: 'ship_systems.id of the built system to level up' },
|
systemId: { type: 'integer', description: 'ship_systems.id of the built system to level up' },
|
||||||
|
leadCrewId: { type: 'integer', description: 'crew.id of the team lead — the member the queued task is committed to first' },
|
||||||
|
helperCrewIds: {
|
||||||
|
type: 'array',
|
||||||
|
description: `Optional supporting crew (crew.id) — the whole team, lead + helpers, holds at most ${MAX_TEAM_SIZE} distinct members, all of them free`,
|
||||||
|
items: { type: 'integer' },
|
||||||
},
|
},
|
||||||
required: ['systemId'],
|
},
|
||||||
|
required: ['systemId', 'leadCrewId'],
|
||||||
},
|
},
|
||||||
ExpandRequest: {
|
ExpandRequest: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
systemId: { type: 'integer', description: 'ship_systems.id of the built system to expand' },
|
systemId: { type: 'integer', description: 'ship_systems.id of the built system to expand' },
|
||||||
|
leadCrewId: { type: 'integer', description: 'crew.id of the team lead — the member the queued task is committed to first' },
|
||||||
|
helperCrewIds: {
|
||||||
|
type: 'array',
|
||||||
|
description: `Optional supporting crew (crew.id) — the whole team, lead + helpers, holds at most ${MAX_TEAM_SIZE} distinct members, all of them free`,
|
||||||
|
items: { type: 'integer' },
|
||||||
},
|
},
|
||||||
required: ['systemId'],
|
},
|
||||||
|
required: ['systemId', 'leadCrewId'],
|
||||||
},
|
},
|
||||||
BuildRequest: {
|
BuildRequest: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
type: { type: 'string', description: "Ship system type to build, e.g. WEAPONS (see ShipSystem.type)" },
|
type: { type: 'string', description: "Ship system type to build, e.g. WEAPONS (see ShipSystem.type)" },
|
||||||
|
leadCrewId: { type: 'integer', description: 'crew.id of the team lead — the member the queued task is committed to first' },
|
||||||
|
helperCrewIds: {
|
||||||
|
type: 'array',
|
||||||
|
description: `Optional supporting crew (crew.id) — the whole team, lead + helpers, holds at most ${MAX_TEAM_SIZE} distinct members, all of them free`,
|
||||||
|
items: { type: 'integer' },
|
||||||
},
|
},
|
||||||
required: ['type'],
|
},
|
||||||
|
required: ['type', 'leadCrewId'],
|
||||||
},
|
},
|
||||||
SystemState: {
|
SystemState: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
@@ -993,16 +1136,27 @@ export const openApiSpec = {
|
|||||||
items: { $ref: '#/components/schemas/Planet' },
|
items: { $ref: '#/components/schemas/Planet' },
|
||||||
},
|
},
|
||||||
inventory: { type: 'array', items: { $ref: '#/components/schemas/InventoryItem' } },
|
inventory: { type: 'array', items: { $ref: '#/components/schemas/InventoryItem' } },
|
||||||
turn: { type: 'integer', description: 'Turn counter — one per jump or exploration' },
|
turn: { type: 'integer', description: 'Turn counter — advances on the turn tick; queued actions (jump, exploration, ship work, research) cost no turn, and mission accept is free' },
|
||||||
|
tasks: {
|
||||||
|
type: 'array',
|
||||||
|
description: 'The active + pending task queue — the ACTIVE block first, then the PENDING block, each ordered by (queuedAtTurn, id); DONE rows never appear',
|
||||||
|
items: { $ref: '#/components/schemas/TaskDto' },
|
||||||
},
|
},
|
||||||
required: ['systemId', 'systemName', 'planets', 'inventory', 'turn'],
|
},
|
||||||
|
required: ['systemId', 'systemName', 'planets', 'inventory', 'turn', 'tasks'],
|
||||||
},
|
},
|
||||||
ExploreRequest: {
|
ExploreRequest: {
|
||||||
type: 'object',
|
type: 'object',
|
||||||
properties: {
|
properties: {
|
||||||
planetId: { type: 'integer', description: 'planets.id of the body to scan (planet or moon)' },
|
planetId: { type: 'integer', description: 'planets.id of the body to scan (planet or moon)' },
|
||||||
|
leadCrewId: { type: 'integer', description: 'crew.id of the team lead — the member the queued task is committed to first' },
|
||||||
|
helperCrewIds: {
|
||||||
|
type: 'array',
|
||||||
|
description: `Optional supporting crew (crew.id) — the whole team, lead + helpers, holds at most ${MAX_TEAM_SIZE} distinct members, all of them free`,
|
||||||
|
items: { type: 'integer' },
|
||||||
},
|
},
|
||||||
required: ['planetId'],
|
},
|
||||||
|
required: ['planetId', 'leadCrewId'],
|
||||||
},
|
},
|
||||||
ExploreResult: {
|
ExploreResult: {
|
||||||
allOf: [
|
allOf: [
|
||||||
@@ -1012,11 +1166,11 @@ export const openApiSpec = {
|
|||||||
properties: {
|
properties: {
|
||||||
outcome: {
|
outcome: {
|
||||||
type: 'array',
|
type: 'array',
|
||||||
description: 'What this scan found — may be empty (some scans find nothing)',
|
description: 'What this scan found — always empty in the queueing response; populated only once the scan resolves on the turn tick (a resolved scan may still find nothing)',
|
||||||
items: { $ref: '#/components/schemas/FoundItem' },
|
items: { $ref: '#/components/schemas/FoundItem' },
|
||||||
},
|
},
|
||||||
crewFound: {
|
crewFound: {
|
||||||
description: 'A crew member who joined the ship on this scan (~18% of scans), null when none',
|
description: 'A crew member who joined the ship on this scan (~18% of scans), null when none — always null in the queueing response',
|
||||||
anyOf: [{ $ref: '#/components/schemas/CrewMember' }, { type: 'null' }],
|
anyOf: [{ $ref: '#/components/schemas/CrewMember' }, { type: 'null' }],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "space-wanderer",
|
"name": "space-wanderer",
|
||||||
"version": "0.9.12",
|
"version": "0.10.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev -p 3000",
|
"dev": "next dev -p 3000",
|
||||||
|
|||||||
Reference in New Issue
Block a user