diff --git a/src/lib/fairshare.test.ts b/src/lib/fairshare.test.ts index d03f38f..9862f9f 100644 --- a/src/lib/fairshare.test.ts +++ b/src/lib/fairshare.test.ts @@ -6,10 +6,12 @@ import { computeAllocationTrend, computeFairshareAllocation, FAIRSHARE_RESOURCES, + getAllocationHistory, InvalidFairshareFloorError, InvalidFairshareNeedError, postFairshareFloor, postFairshareNeed, + settleAllocationCycle, } from "./fairshare"; beforeEach(async () => { @@ -389,6 +391,102 @@ describe("computeFairshareAllocation (adversarial robustness)", () => { }); }); +describe("settleAllocationCycle (power/cooling allocation-cycle write path)", () => { + it("appends a real fairshare.allocation.cycle event for power and builds a real 2-point trend from it", async () => { + await seedResource("power", 100); + await reportNeed("agent-a", "power", 1); + + // Before any settlement, the trend is honestly empty - no cycle event + // has ever been written for power. + expect(computeAllocationTrend(await readAll(), "power").status).toBe("no-trend-yet"); + + const first = await settleAllocationCycle("power"); + expect(first.cycleEntry.payload).toMatchObject({ + type: "fairshare.allocation.cycle", + resource: "power", + totalAllocated: 100, + }); + expect(first.totalAllocated).toBe(100); + + // The re-solved total genuinely changes when the seeded supply changes - + // this is a real re-solve, not an echoed/fabricated value. + await seedResource("power", 200); + const second = await settleAllocationCycle("power"); + expect(second.totalAllocated).toBe(200); + expect(second.cycleEntry.payload).toMatchObject({ + type: "fairshare.allocation.cycle", + resource: "power", + totalAllocated: 200, + }); + + const entries = await readAll(); + const cycleEvents = entries.filter( + (e) => (e.payload as { type?: string }).type === "fairshare.allocation.cycle", + ); + expect(cycleEvents).toHaveLength(2); + expect(cycleEvents.every((e) => (e.payload as { resource?: string }).resource === "power")).toBe( + true, + ); + + const history = getAllocationHistory(entries, "power"); + expect(history.map((p) => p.totalAllocated)).toEqual([100, 200]); + + const trend = computeAllocationTrend(entries, "power"); + expect(trend.status).toBe("trend"); + if (trend.status === "trend") { + expect(trend.points).toBe(2); + expect(trend.slope).toBeCloseTo(100, 6); + } + }); + + it("appends a real fairshare.allocation.cycle event for cooling and builds a real 2-point trend from it", async () => { + await seedResource("cooling", 50); + await reportNeed("agent-a", "cooling", 1); + await reportNeed("agent-b", "cooling", 1); + + expect(computeAllocationTrend(await readAll(), "cooling").status).toBe("no-trend-yet"); + + const first = await settleAllocationCycle("cooling"); + expect(first.totalAllocated).toBeCloseTo(50, 6); + expect(first.cycleEntry.payload).toMatchObject({ + type: "fairshare.allocation.cycle", + resource: "cooling", + }); + + await seedResource("cooling", 90); + const second = await settleAllocationCycle("cooling"); + expect(second.totalAllocated).toBeCloseTo(90, 6); + + const entries = await readAll(); + const history = getAllocationHistory(entries, "cooling"); + expect(history).toHaveLength(2); + expect(history[0].totalAllocated).toBeCloseTo(50, 6); + expect(history[1].totalAllocated).toBeCloseTo(90, 6); + + const trend = computeAllocationTrend(entries, "cooling"); + expect(trend.status).toBe("trend"); + if (trend.status === "trend") { + expect(trend.points).toBe(2); + expect(trend.slope).toBeCloseTo(40, 6); + } + + // Water and food must stay untouched by this power/cooling settlement - + // no event of any kind was ever written for either resource here. + const waterCycles = entries.filter( + (e) => + (e.payload as { type?: string; resource?: string }).type === "fairshare.allocation.cycle" && + (e.payload as { resource?: string }).resource === "water", + ); + const foodCycles = entries.filter( + (e) => + (e.payload as { type?: string; resource?: string }).type === "fairshare.allocation.cycle" && + (e.payload as { resource?: string }).resource === "food", + ); + expect(waterCycles).toHaveLength(0); + expect(foodCycles).toHaveLength(0); + }); +}); + describe("computeAllocationTrend", () => { it("reports 'no trend yet' at exactly 1 history entry", async () => { await append({ type: "fairshare.allocation.cycle", resource: "food", totalAllocated: 50 }); diff --git a/src/lib/fairshare.ts b/src/lib/fairshare.ts index ff2481a..3008722 100644 --- a/src/lib/fairshare.ts +++ b/src/lib/fairshare.ts @@ -1,5 +1,5 @@ import type { StoredEventLogEntry } from "./eventlog"; -import { append } from "./eventlog"; +import { append, readAll } from "./eventlog"; import { sortForReplay } from "./ledger"; import { solveCeeiWaterFilling } from "./ceeiSpike"; import { trySyncWithBackend } from "./sync"; @@ -469,6 +469,55 @@ export function computeFairshareAllocation( }; } +/** The full result of settling one real allocation cycle via `settleAllocationCycle`. */ +export interface AllocationCycleSettlement { + /** The real `fairshare.allocation.cycle` event recording the re-solve. */ + cycleEntry: StoredEventLogEntry; + /** Sum of every agent's re-solved quantity for `resource` in this cycle, as written to `cycleEntry`. */ + totalAllocated: number; +} + +/** + * Settles one real allocation-history cycle for `resource` directly off a + * live CEEI re-solve - for `power` and `cooling`, which (unlike `water` via + * `settleCorroboratedReading` in waterwatch/corroboration.ts, and `food` via + * `settleFarmsForecast` in farms.ts) have no dedicated cross-app settlement + * chain of their own to trigger off of. Mirrors those two functions' tail + * 1:1: re-reads the full signed Event Log, re-solves via + * `computeFairshareAllocation`, and appends the real re-solved total as a + * new `fairshare.allocation.cycle` history point - the same real write path + * `TrendChart`/`computeAllocationTrend` replay, never a fabricated or + * hand-computed point. + * + * This function itself does not guard against a redundant re-fire on an + * unchanged value (there is no prior "credit event" here to gate on, unlike + * the water/food settlement chains) - callers (see `ResourceTiles.tsx`) are + * responsible for only invoking this once per genuinely new `totalAllocated` + * value, the same "new value, not a re-render echo" guard `FarmsScreen.tsx` + * already uses via `lastSettledForecastRef`. + */ +export async function settleAllocationCycle( + resource: FairshareResource, + deps: { append?: typeof append; readAll?: typeof readAll } = {}, +): Promise { + const appendFn = deps.append ?? append; + const readAllFn = deps.readAll ?? readAll; + + const entries = await readAllFn(); + const allocation = computeFairshareAllocation(entries); + const totalAllocated = allocation.agents.reduce( + (sum, agent) => sum + allocation.allocation[agent][resource], + 0, + ); + const cycleEntry = await appendFn({ + type: "fairshare.allocation.cycle", + resource, + totalAllocated, + }); + + return { cycleEntry, totalAllocated }; +} + export type AllocationTrend = | { status: "no-trend-yet"; points: number } | { status: "trend"; points: number; slope: number; average: number }; diff --git a/src/miniapps/fairshare/ResourceTiles.test.tsx b/src/miniapps/fairshare/ResourceTiles.test.tsx index ea8b549..286956f 100644 --- a/src/miniapps/fairshare/ResourceTiles.test.tsx +++ b/src/miniapps/fairshare/ResourceTiles.test.tsx @@ -4,7 +4,12 @@ import { cleanup, render, screen, waitFor } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { db } from "../../lib/db"; import { append, readAll } from "../../lib/eventlog"; -import { computeFairshareAllocation, FAIRSHARE_RESOURCES } from "../../lib/fairshare"; +import { + computeAllocationTrend, + computeFairshareAllocation, + FAIRSHARE_RESOURCES, + getAllocationHistory, +} from "../../lib/fairshare"; import { getPublicKey, init } from "../../lib/identity"; import { toAccountId } from "../../shell/accountId"; import { ResourceTiles } from "./ResourceTiles"; @@ -17,6 +22,30 @@ beforeEach(async () => { await db.open(); }); +/** + * `ResourceTiles` now fires its own fire-and-forget power/cooling + * `fairshare.allocation.cycle` settlement (see `ResourceTiles.tsx`'s + * `lastSettledCycleRef` effect) on every render whose CEEI re-solve yields + * a genuinely new total - including every happy-path test below that + * seeds power/cooling with a real need. A test that ends (and lets + * `afterEach(cleanup)` unmount) before that background write actually + * lands would leave it racing against the NEXT test's `beforeEach` + * database reset, risking a write landing in the wrong test's fresh log. + * This waits on the real, already-landed event count - never a fixed + * sleep - so every test quiesces its own triggered writes before ending. + */ +async function waitForAllocationCycleCount(resource: string, min: number): Promise { + await waitFor(async () => { + const entries = await readAll(); + const count = entries.filter( + (e) => + (e.payload as { type?: string }).type === "fairshare.allocation.cycle" && + (e.payload as { resource?: string }).resource === resource, + ).length; + expect(count).toBeGreaterThanOrEqual(min); + }); +} + describe("ResourceTiles (happy path - 4-resource allocation cycle)", () => { it("renders all 4 tiles with bars matching the CEEI engine output and a live ledger balance", async () => { await init(); @@ -58,6 +87,12 @@ describe("ResourceTiles (happy path - 4-resource allocation cycle)", () => { `width: ${expectedFraction}%`, ); } + + // Quiesce this test's own triggered power/cooling settlement writes + // before letting `afterEach(cleanup)` unmount and the next test's + // `beforeEach` reset the database out from under them. + await waitForAllocationCycleCount("power", 1); + await waitForAllocationCycleCount("cooling", 1); }); it("updates reactively when a new allocation cycle event is appended after render", async () => { @@ -81,6 +116,137 @@ describe("ResourceTiles (happy path - 4-resource allocation cycle)", () => { await waitFor(() => { expect(screen.getByTestId("tile-power-allocation")).toHaveTextContent(String(expectedQty)); }); + + // Quiesce this test's own triggered power settlement write (conserved + // total stays 100 across both agents, so exactly 1 cycle event fires) + // before the next test's database reset. + await waitForAllocationCycleCount("power", 1); + }); +}); + +describe("ResourceTiles (power/cooling allocation-cycle coherence fix)", () => { + it("writes a real fairshare.allocation.cycle event for power when the allocation genuinely changes, and the power trend chart builds a real 2-point trend from it", async () => { + await init(); + const accountId = toAccountId(await getPublicKey()); + + // Simulates the admin seed panel's `seed.resource.power` write (the + // audit's named trigger): a resident has already reported a need, so + // the very first seeded supply already yields a real, non-zero solve. + await append({ type: "seed.resource.power", resource: "power", value: 100 }); + await append({ type: "fairshare.need", agent: accountId, resource: "power", value: 1 }); + + render(); + + // Before any power allocation change has ever been settled into a + // second cycle, the trend is honestly "no trend yet" - exactly the gap + // the audit found (never fabricated, never pre-populated). + await waitFor(() => { + expect(screen.getByTestId("tile-power-allocation")).toHaveTextContent("100"); + }); + + // A second real `seed.resource.power` change (e.g. posted from the + // admin seed panel) is the trigger: the CEEI re-solve's total for power + // genuinely changes, so the UI's own settlement effect must append a + // fresh `fairshare.allocation.cycle` event for it - no manual call into + // the engine, no test-only shortcut. + await append({ type: "seed.resource.power", resource: "power", value: 250 }); + + await waitFor(() => { + expect(screen.getByTestId("tile-power-allocation")).toHaveTextContent("250"); + }); + + // The real Event Log now carries 2 real `fairshare.allocation.cycle` + // events for power - not fabricated, not pinned strings - and + // `getAllocationHistory`/`computeAllocationTrend` (the exact functions + // `TrendChart.tsx` renders from) can build a real trend from them. + await waitFor(async () => { + const entries = await readAll(); + const history = getAllocationHistory(entries, "power"); + expect(history.length).toBeGreaterThanOrEqual(2); + }); + + const entries = await readAll(); + const history = getAllocationHistory(entries, "power"); + expect(history.map((p) => p.totalAllocated)).toEqual([100, 250]); + + const trend = computeAllocationTrend(entries, "power"); + expect(trend.status).toBe("trend"); + if (trend.status === "trend") { + expect(trend.points).toBe(2); + expect(trend.slope).toBeCloseTo(150, 6); + } + + // The rendered TrendChart for power has genuinely left the "no trend + // yet" empty state - this is the user-visible symptom the audit named. + await waitFor(() => { + expect( + screen.getByTestId("fairshare-trend-power").querySelector('[data-testid="trend-empty"]'), + ).toBeNull(); + expect( + screen.getByTestId("fairshare-trend-power").querySelector('[data-testid="trend-chart"]'), + ).not.toBeNull(); + }); + }); + + it("writes a real fairshare.allocation.cycle event for cooling when the allocation genuinely changes, and the cooling trend chart builds a real 2-point trend from it", async () => { + await init(); + const accountId = toAccountId(await getPublicKey()); + + await append({ type: "seed.resource.cooling", resource: "cooling", value: 40 }); + await append({ type: "fairshare.need", agent: accountId, resource: "cooling", value: 1 }); + + render(); + + await waitFor(() => { + expect(screen.getByTestId("tile-cooling-allocation")).toHaveTextContent("40"); + }); + + await append({ type: "seed.resource.cooling", resource: "cooling", value: 70 }); + + await waitFor(() => { + expect(screen.getByTestId("tile-cooling-allocation")).toHaveTextContent("70"); + }); + + await waitFor(async () => { + const entries = await readAll(); + const history = getAllocationHistory(entries, "cooling"); + expect(history.length).toBeGreaterThanOrEqual(2); + }); + + const entries = await readAll(); + const history = getAllocationHistory(entries, "cooling"); + expect(history.map((p) => p.totalAllocated)).toEqual([40, 70]); + + const trend = computeAllocationTrend(entries, "cooling"); + expect(trend.status).toBe("trend"); + if (trend.status === "trend") { + expect(trend.points).toBe(2); + expect(trend.slope).toBeCloseTo(30, 6); + } + + await waitFor(() => { + expect( + screen.getByTestId("fairshare-trend-cooling").querySelector('[data-testid="trend-empty"]'), + ).toBeNull(); + expect( + screen.getByTestId("fairshare-trend-cooling").querySelector('[data-testid="trend-chart"]'), + ).not.toBeNull(); + }); + + // Water and food must stay untouched by the power/cooling fix: no + // event of any kind was written for either here. + const waterCycles = entries.filter( + (e) => + (e.payload as { type?: string }).type === "fairshare.allocation.cycle" && + (e.payload as { resource?: string }).resource === "water", + ); + const foodCycles = entries.filter( + (e) => + (e.payload as { type?: string }).type === "fairshare.allocation.cycle" && + (e.payload as { resource?: string }).resource === "food", + ); + expect(waterCycles).toHaveLength(0); + expect(foodCycles).toHaveLength(0); }); }); @@ -112,5 +278,9 @@ describe("ResourceTiles (failure path - no ledger balance yet)", () => { "No allocation yet", ); } + + // `someone-else` has a real power need against a real seeded pool, so + // this test's own settlement effect fires too - quiesce it. + await waitForAllocationCycleCount("power", 1); }); }); diff --git a/src/miniapps/fairshare/ResourceTiles.tsx b/src/miniapps/fairshare/ResourceTiles.tsx index e56a976..edac40b 100644 --- a/src/miniapps/fairshare/ResourceTiles.tsx +++ b/src/miniapps/fairshare/ResourceTiles.tsx @@ -1,9 +1,10 @@ -import { useEffect, useState, type FormEvent } from "react"; +import { useEffect, useRef, useState, type FormEvent } from "react"; import { balanceOf, computeBalances } from "../../lib/ledger"; import { computeFairshareAllocation, FAIRSHARE_RESOURCES, postFairshareNeed, + settleAllocationCycle, type FairshareResource, } from "../../lib/fairshare"; import { trySyncWithBackend } from "../../lib/sync"; @@ -20,6 +21,15 @@ const RESOURCE_META: Record 0 && allocation.agents.length > 0`). + const lastSettledCycleRef = useRef>>({}); + useEffect(() => { + for (const resource of RESOURCES_NEEDING_UI_SETTLEMENT) { + if (allocation.agents.length === 0 || allocation.supply[resource] <= 0) { + continue; + } + const totalAllocated = allocation.agents.reduce( + (sum, agent) => sum + allocation.allocation[agent][resource], + 0, + ); + if (lastSettledCycleRef.current[resource] === totalAllocated) { + continue; + } + lastSettledCycleRef.current[resource] = totalAllocated; + void settleAllocationCycle(resource) + .then(() => { + void trySyncWithBackend(); + }) + .catch(() => { + // Best-effort settlement: a not-yet-initialized local identity or + // a transient Event Log failure must never break tile rendering. + }); + } + }, [allocation]); + const [needResource, setNeedResource] = useState("power"); const [needAmount, setNeedAmount] = useState(""); const [needStatus, setNeedStatus] = useState();