/** * Mission-scoped zone and faction pressure (task 7). * * Pressure is an additive strategic ledger over map zones: each settled * operation end may apply ONE delta to ONE declared zone, attributed to the * faction, mission, and source effect that caused it. The zone's strategic * state is a deterministic function of the decayed pressure sum. * * Decay is computational, not stored: each delta's weight halves per elapsed * decay period (7 days), so `effectivePressure` is deterministic for any * `now` and needs no sweeper. * * Downstream mechanics (declared per plan: one at a time): route risk and * resource-yield multipliers derive from the state. They are pure and tested * here; wiring them into shipping/production consumers is deferred until the * dirty uncommitted map/shipping/production baseline lands (task-1 ownership * manifest forbids editing those files). * * Territory/border zone semantics are untouched: pressure never changes * placement rules (terrain/resource validation in `src/lib/map/placement.ts` * remains the only placement gate). */ import type { Payload, PayloadRequest } from "payload"; /** Half-life of a pressure delta, in days. */ export const PRESSURE_DECAY_PERIOD_DAYS = 7; /** Documented state thresholds over the effective (decayed) pressure sum. */ export const PRESSURE_STATE_THRESHOLDS = { /** pressure >= 80: the hostile faction holds the zone. */ controlled: 80, /** pressure >= 40: actively fought over. */ contested: 40, } as const; /** * Effective pressure below this is strategically nothing: the state is * neutral. Halving decay never reaches exactly zero, so the state machine * needs a convergence floor. */ export const PRESSURE_NEUTRAL_FLOOR = 0.5; /** Documented deltas applied per operation outcome. */ export const PRESSURE_OUTCOME_DELTAS = { /** Mission failure: hostile activity gains a foothold. */ failure: 40, /** Mission success: the zone is pushed back toward neutral. */ success: -25, } as const; export type ZonePressureState = | "controlled" | "contested" | "recovering" | "neutral"; export interface PressureRow { delta: number; createdAt: string; } export interface ZoneState { /** Decayed pressure sum, rounded to one decimal. */ pressure: number; state: ZonePressureState; routeRiskMultiplier: number; yieldMultiplier: number; /** Number of live (non-fully-decayed) pressure rows. */ activeRows: number; } const MULTIPLIERS: Record = { controlled: { routeRisk: 1.5, yield: 0.75 }, contested: { routeRisk: 1.25, yield: 0.9 }, recovering: { routeRisk: 1, yield: 1 }, neutral: { routeRisk: 1, yield: 1 }, }; /** Effective pressure of one delta, halved per full decay period elapsed. */ export function decayedDelta(delta: number, createdAt: string, now: Date): number { const created = new Date(createdAt).getTime(); const elapsedDays = Math.max(0, (now.getTime() - created) / 86_400_000); const periods = Math.floor(elapsedDays / PRESSURE_DECAY_PERIOD_DAYS); return delta / 2 ** periods; } /** Deterministic strategic state from the decayed pressure sum. */ export function stateFromPressure(pressure: number): ZoneState { const rounded = Math.round(pressure * 10) / 10; const state: ZonePressureState = rounded >= PRESSURE_STATE_THRESHOLDS.controlled ? "controlled" : rounded >= PRESSURE_STATE_THRESHOLDS.contested ? "contested" : rounded >= PRESSURE_NEUTRAL_FLOOR ? "recovering" : "neutral"; return { pressure: rounded, state, routeRiskMultiplier: MULTIPLIERS[state].routeRisk, yieldMultiplier: MULTIPLIERS[state].yield, activeRows: 0, }; } /** * Sum decayed deltas from raw pressure rows (deterministic given `now`). * Deltas decay toward zero symmetrically: hostile gains fade, and so do * friendly reductions, so a zone naturally returns to neutral over time. */ export function effectivePressure(rows: PressureRow[], now: Date): ZoneState { const pressure = rows.reduce((sum, row) => sum + decayedDelta(row.delta, row.createdAt, now), 0); return stateFromPressure(pressure); } // --------------------------------------------------------------------------- // Payload interaction // --------------------------------------------------------------------------- type PayloadType = Awaited>; export interface ApplyZonePressureInput { zoneId: number; factionId?: number; operationId: string; missionId?: number; /** The settled operation-end effect driving this delta (idempotency key). */ sourceEffectId: number; delta: number; note?: string; } /** * Apply one pressure delta, exactly once per source effect. A replay of the * same effect is a no-op returning the existing row. */ export async function applyZonePressure( payload: PayloadType, input: ApplyZonePressureInput, req?: PayloadRequest, ): Promise<{ id: number; created: boolean }> { const existing = await payload.find({ collection: "zone-pressure", where: { sourceEffect: { equals: input.sourceEffectId } }, limit: 1, depth: 0, overrideAccess: true, req, }); if (existing.docs.length > 0) { return { id: existing.docs[0].id, created: false }; } try { const row = await payload.create({ collection: "zone-pressure", data: { zone: input.zoneId, faction: input.factionId ?? null, operationId: input.operationId, mission: input.missionId ?? null, sourceEffect: input.sourceEffectId, delta: input.delta, note: input.note ?? null, }, overrideAccess: true, depth: 0, req, }); return { id: row.id, created: true }; } catch (error) { const code = (error as { cause?: { code?: string } })?.cause?.code; if (code === "23505") { // Unique-constraint race on sourceEffect: the other writer won. const raced = await payload.find({ collection: "zone-pressure", where: { sourceEffect: { equals: input.sourceEffectId } }, limit: 1, depth: 0, overrideAccess: true, req, }); if (raced.docs.length > 0) return { id: raced.docs[0].id, created: false }; } throw error; } } /** * Compute a zone's strategic state from its live pressure ledger. Deterministic * for a given `now`; defaults to the current time. */ export async function computeZoneState( payload: PayloadType, zoneId: number, now: Date = new Date(), ): Promise { const rows = await payload.find({ collection: "zone-pressure", where: { zone: { equals: zoneId } }, limit: 1000, depth: 0, overrideAccess: true, }); const live: PressureRow[] = []; let activeRows = 0; for (const doc of rows.docs as unknown as { delta: number; createdAt: string }[]) { const effective = decayedDelta(doc.delta, doc.createdAt, now); if (Math.abs(effective) >= 0.1) activeRows += 1; live.push({ delta: doc.delta, createdAt: doc.createdAt }); } const state = effectivePressure(live, now); return { ...state, activeRows }; }