1
0
Fork 0
polaris-task-force/src/lib/operations/settlement.ts
Z8MB1E 67c993ca10 feat(operations): mission reservations and deterministic settlement
Reserve personnel, vehicles, cargo, and budget with idempotent keys and exactly-once settlement; extraction effects preflight before any write so validated HQ deposits and locker credits are final and survive mission failure. Failure sweeps touch only unextracted reservations.

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-09-20 02:43:47 -04:00

95 lines
3.4 KiB
TypeScript

import type { Payload, PayloadRequest } from "payload";
import type { OperationEffect } from "@/payload-types";
import { handleExtraction } from "./settlementExtraction";
import {
handleInventoryLoss,
handleObjective,
handleOperationEnd,
} from "./settlementFacts";
import { findByIdOrNull } from "./settlementResolve";
import { SettlementFailure } from "./settlementTypes";
/**
* Operation settlement: applies validated operation effects to real state.
*
* Extraction finality: a validated logistics extraction deposits its
* manifest at the designated HQ structure and a validated player extraction
* credits its manifest to the extractor's personal locker, immediately and
* finally. A later mission failure settles only still-reserved reservations
* (via `failOperationReservations`) and never reverses an applied effect.
*
* Exactly-once: the dispatcher re-reads the effect fresh and no-ops on
* terminal (`applied`/`reversed`) rows, so a replay applies nothing twice.
* Recoverable failures (full HQ, full locker, unresolved references) are
* recorded as `failed` effects with a structured note; the full manifest
* stays on the effect payload, so reconciliation can replay them later.
*/
/**
* Apply one operation effect. Never throws: recoverable failures are
* recorded on the effect row, and unexpected errors are marked
* `internal-error` so the ledger write path stays unbreakable.
*/
export async function applyOperationEffect(
payload: Payload,
effectId: number,
req?: PayloadRequest,
): Promise<OperationEffect | null> {
const effect = (await findByIdOrNull(
payload,
"operation-effects",
effectId,
req,
)) as unknown as OperationEffect | null;
if (!effect) return null;
if (effect.status === "applied" || effect.status === "reversed") return effect;
try {
const note = await dispatchEffect(payload, effect, req);
return (await payload.update({
collection: "operation-effects",
id: effect.id,
data: {
status: "applied",
appliedAt: new Date().toISOString(),
reconciliationNotes: note ?? null,
},
overrideAccess: true,
depth: 0,
req,
})) as unknown as OperationEffect;
} catch (error) {
const code = error instanceof SettlementFailure ? error.code : "internal-error";
const message = error instanceof Error ? error.message : "unknown error";
payload.logger.error(`[Operations] Effect ${effect.effectKey} failed (${code}): ${message}`);
return (await payload.update({
collection: "operation-effects",
id: effect.id,
data: { status: "failed", reconciliationNotes: `${code}: ${message}` },
overrideAccess: true,
depth: 0,
req,
})) as unknown as OperationEffect;
}
}
async function dispatchEffect(
payload: Payload,
effect: OperationEffect,
req?: PayloadRequest,
): Promise<string | null> {
switch (effect.effectType) {
case "operation.started":
return null;
case "operation.objective-updated":
return handleObjective(payload, effect);
case "operation.extraction-recorded":
return handleExtraction(payload, effect, req);
case "operation.inventory-recorded":
return handleInventoryLoss(payload, effect, req);
case "operation.ended":
return handleOperationEnd(payload, effect, req);
default:
throw new SettlementFailure("internal-error", `Unknown effect type "${effect.effectType}".`);
}
}