1
0
Fork 0
polaris-task-force/src/lib/economy/tick.ts
Z8MB1E 447df220f5 feat(economy): add economy tick with demand simulation and price modifiers
Add the src/lib/economy service (GM baselines, deterministic per-period demand drift, price modifier computation, event emission) and the economy-tick bin. Gated by GameRules economy.enabled; period-idempotent with a cold-start observation gate.

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

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-09-06 17:22:30 -04:00

226 lines
6.6 KiB
TypeScript

/**
* Supply & demand economy — tick orchestrator.
*
* Persists the ledger: ensures one market-state doc per enabled tradeable
* item (copied from GM baselines), then advances every doc one tick via the
* pure math in `math.ts`. Called by the `economy-tick` bin (P1c).
*/
import type { Where } from "payload";
import { getEconomySettings, resolveEconomyConfig } from "./config";
import { applyEconomyTick, shouldEmitPriceChange } from "./math";
import {
FIND_LIMIT,
findItemIds,
loadItemDocs,
marketStateWhereFor,
} from "./persistence";
import type { ItemRef } from "./persistence";
import type { EconomyKnobs } from "./types";
import { ECONOMY_DEFAULTS } from "./types";
export type { ItemRef };
export type EnsureSummary = {
created: number;
scanned: number;
};
export type PriceChange = {
itemType: ItemRef["itemType"];
itemId: number;
/** market-state doc id — used as the event-log targetId. */
stateId: number;
from: number;
to: number;
};
export type TickSummary = {
processed: number;
/** Docs skipped because they were already computed in this period. */
skipped: number;
priceChanges: PriceChange[];
errors: number;
disabled: boolean;
};
export type ProcessOptions = {
now?: Date;
rng?: () => number;
items?: ItemRef[];
/**
* Only docs whose lastComputedAt is before this boundary are processed —
* makes cron re-runs within one period idempotent no-ops.
*/
periodStart?: Date;
/** Override the GameRules master gate (hermetic tests / manual runs). */
masterGate?: boolean;
/** Override the GameRules knobs (hermetic tests / manual runs). */
knobs?: EconomyKnobs;
};
type PayloadType = Awaited<ReturnType<typeof import("payload").getPayload>>;
/**
* Create missing market-state docs for enabled tradeable items, copying the
* GM baselines from the item doc. Idempotent: existing docs are left alone.
*/
export async function ensureMarketStateDocs(
payload: PayloadType,
options: { items?: ItemRef[]; knobs?: EconomyKnobs } = {},
): Promise<EnsureSummary> {
const { knobs = ECONOMY_DEFAULTS } = options;
let created = 0;
let scanned = 0;
for (const itemType of ["resource", "asset"] as const) {
const itemIds = await findItemIds(payload, itemType, options.items);
scanned += itemIds.length;
if (itemIds.length === 0) continue;
const { docs: existing } = await payload.find({
collection: "market-state",
where: { and: [{ itemType: { equals: itemType } }, { itemId: { in: itemIds } }] },
limit: FIND_LIMIT,
depth: 0,
select: { itemId: true },
});
const have = new Set(existing.map((d) => d.itemId));
const missing = itemIds.filter((id) => !have.has(id));
if (missing.length === 0) continue;
const itemDocs = await loadItemDocs(payload, itemType, missing);
for (const itemId of missing) {
try {
const config = resolveEconomyConfig(itemType, itemDocs.get(itemId), knobs);
if (!config) continue;
await payload.create({
collection: "market-state",
data: {
itemType,
itemId,
gmBaselineSupply: config.baselineSupply,
gmBaselineDemand: config.baselineDemand,
currentSupply: config.baselineSupply,
artificialDemand: config.baselineDemand,
realDemand: 0,
priceModifier: 1,
},
overrideAccess: true,
});
created += 1;
} catch (error) {
payload.logger.error({
msg: "economy: failed to ensure market-state doc",
itemType,
itemId,
err: error,
});
}
}
}
return { created, scanned };
}
/**
* Advance every market-state doc one tick. Disabled economy (master gate)
* is a no-op. Per-item failures are logged and skipped.
*/
export async function processEconomyTick(
payload: PayloadType,
options: ProcessOptions = {},
): Promise<TickSummary> {
const { now = new Date(), rng = Math.random, items, periodStart } = options;
const settings = await getEconomySettings(payload);
const enabled = options.masterGate ?? settings.enabled;
const knobs = options.knobs ?? settings.knobs;
if (!enabled) {
return { processed: 0, skipped: 0, priceChanges: [], errors: 0, disabled: true };
}
await ensureMarketStateDocs(payload, { items, knobs });
const marketStateWhere: Where | undefined = items ? marketStateWhereFor(items) : undefined;
const { docs } = await payload.find({
collection: "market-state",
...(marketStateWhere ? { where: marketStateWhere } : {}),
limit: FIND_LIMIT,
depth: 0,
});
const resourceDocs = await loadItemDocs(
payload,
"resource",
docs.filter((d) => d.itemType === "resource").map((d) => d.itemId),
);
const assetDocs = await loadItemDocs(
payload,
"asset",
docs.filter((d) => d.itemType === "asset").map((d) => d.itemId),
);
let processed = 0;
let skipped = 0;
let errors = 0;
const priceChanges: PriceChange[] = [];
for (const doc of docs) {
if (
periodStart &&
doc.lastComputedAt &&
new Date(doc.lastComputedAt) >= periodStart
) {
skipped += 1;
continue;
}
try {
const itemDocs = doc.itemType === "resource" ? resourceDocs : assetDocs;
const config = resolveEconomyConfig(doc.itemType, itemDocs.get(doc.itemId), knobs);
if (!config) continue;
const next = applyEconomyTick(
{
currentSupply: doc.currentSupply,
artificialDemand: doc.artificialDemand,
realDemand: doc.realDemand,
priceModifier: doc.priceModifier,
},
{ baselineDemand: config.baselineDemand, priceBand: config.priceBand },
knobs,
rng,
);
if (shouldEmitPriceChange(doc.priceModifier, next.priceModifier)) {
priceChanges.push({
itemType: doc.itemType,
itemId: doc.itemId,
stateId: doc.id,
from: doc.priceModifier,
to: next.priceModifier,
});
}
await payload.update({
collection: "market-state",
id: doc.id,
data: {
currentSupply: next.currentSupply,
artificialDemand: next.artificialDemand,
realDemand: next.realDemand,
priceModifier: next.priceModifier,
lastComputedAt: now.toISOString(),
},
overrideAccess: true,
});
processed += 1;
} catch (error) {
errors += 1;
payload.logger.error({
msg: "economy: failed to process market-state doc",
itemType: doc.itemType,
itemId: doc.itemId,
err: error,
});
}
}
return { processed, skipped, priceChanges, errors, disabled: false };
}