From d21e2dfe345f976982723ed4ff1efcd3c024c25f Mon Sep 17 00:00:00 2001 From: OmO Orchestrator Date: Fri, 20 Nov 2026 03:14:49 -0500 Subject: [PATCH] fix(farms): additive food supply (no starvation) + wire grow-light power budget Farms->Fair Share credited food via seed.resource.food (latest-wins), so the demo's 20kg forecast OVERWROTE the 410 baseline (food 410->20, the farm starved the settlement). Farms now appends a signed fairshare.contribution that Fair Share SUMS onto the baseline per-contributor-latest, so growing food only raises the pool and multiple growers sum. Also wires the advertised-but-inert grow-light power budget into FarmsScreen + shows energy vs budget in ForecastPanel. --- src/lib/fairshare.test.ts | 33 ++++++++++- src/lib/fairshare.ts | 55 +++++++++++++++++++ src/lib/farms.test.ts | 20 ++++++- src/lib/farms.ts | 16 +++--- src/miniapps/farms/FarmsScreen.tsx | 29 +++++++++- src/miniapps/farms/ForecastPanel.tsx | 11 +++- .../farms/coreLoopFoodIntegration.test.tsx | 4 +- 7 files changed, 152 insertions(+), 16 deletions(-) diff --git a/src/lib/fairshare.test.ts b/src/lib/fairshare.test.ts index 030520a..c74aa2d 100644 --- a/src/lib/fairshare.test.ts +++ b/src/lib/fairshare.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { db } from "./db"; import { init } from "./identity"; -import { append, readAll } from "./eventlog"; +import { append, readAll, type StoredEventLogEntry } from "./eventlog"; import { computeAllocationTrend, computeFairshareAllocation, @@ -33,6 +33,37 @@ async function reportNeed( await append({ type: "fairshare.need", agent, resource, value }); } +describe("fairshare.contribution (additive supply)", () => { + const entry = (id: number, payload: unknown, pk: number[]): StoredEventLogEntry => + ({ + id, + lamportTs: id, + payload, + authorPubkey: new Uint8Array(pk), + signature: new Uint8Array([id]), + }) as unknown as StoredEventLogEntry; + + it("sums contributions across distinct contributors onto the seeded baseline, latest-per-contributor", () => { + const entries = [ + entry(1, { type: "seed.resource.food", resource: "food", value: 410 }, [1]), + entry(2, { type: "fairshare.contribution", resource: "food", value: 20 }, [2]), + entry(3, { type: "fairshare.contribution", resource: "food", value: 30 }, [3]), + entry(4, { type: "fairshare.contribution", resource: "food", value: 50 }, [2]), + ]; + // 410 baseline + contributor[2] latest 50 + contributor[3] 30 = 490 (NOT 410+20+30+50) + expect(computeFairshareAllocation(entries).supply.food).toBe(490); + }); + + it("ignores a negative or non-finite contribution (never shrinks the pool)", () => { + const entries = [ + entry(1, { type: "seed.resource.food", resource: "food", value: 100 }, [1]), + entry(2, { type: "fairshare.contribution", resource: "food", value: -40 }, [2]), + entry(3, { type: "fairshare.contribution", resource: "food", value: Number.NaN }, [3]), + ]; + expect(computeFairshareAllocation(entries).supply.food).toBe(100); + }); +}); + describe("computeFairshareAllocation (happy path - 4 resources, 10 agents)", () => { it("allocates exactly the seeded supply across all 4 resources and stays envy-free", async () => { const supplies: Record = { diff --git a/src/lib/fairshare.ts b/src/lib/fairshare.ts index d698c41..8ea8c27 100644 --- a/src/lib/fairshare.ts +++ b/src/lib/fairshare.ts @@ -91,6 +91,17 @@ export interface FairshareAllocationCyclePayload { totalAllocated: number; } +/** An additive contribution to a resource's supply pool (e.g. a Farms + * harvest forecast crediting food). Unlike `seed.resource.*` (admin baseline, + * latest-wins), contributions are SUMMED on top of the baseline, so producing + * a resource can only raise its pool - never overwrite/shrink it. */ +export interface FairshareContributionPayload { + type: "fairshare.contribution"; + resource: FairshareResource; + /** Non-negative quantity the signer adds to `resource`'s supply pool. */ + value: number; +} + function isSeedResourcePayload( payload: unknown, ): payload is SeedResourcePayload { @@ -105,6 +116,27 @@ function isSeedResourcePayload( ); } +function isFairshareContributionPayload( + payload: unknown, +): payload is FairshareContributionPayload { + if (typeof payload !== "object" || payload === null) return false; + const p = payload as Record; + return ( + p.type === "fairshare.contribution" && + FAIRSHARE_RESOURCES.includes(p.resource as FairshareResource) && + typeof p.value === "number" && + Number.isFinite(p.value) && + p.value >= 0 + ); +} + +/** Stable per-signer key for a stored entry's authorPubkey so additive + * contributions sum across distinct contributors while a single contributor's + * repeat contribution only ever counts its latest value. */ +function contributorKey(authorPubkey: Uint8Array | undefined): string { + return authorPubkey ? Array.from(authorPubkey).join(",") : "anon"; +} + function isFairshareNeedPayload( payload: unknown, ): payload is FairshareNeedPayload { @@ -262,11 +294,27 @@ export function computeFairshareAllocation( const recordedFloors = new Map(); + // Additive supply contributions keyed by contributor (signer): each + // contributor's latest counts once, multiple contributors sum, folded onto + // the seeded baseline after the loop (see below). + const contributions = new Map>(); + for (const entry of ordered) { if (isSeedResourcePayload(entry.payload)) { supply[entry.payload.resource] = entry.payload.value; continue; } + if (isFairshareContributionPayload(entry.payload)) { + const { resource, value } = entry.payload; + const contributor = contributorKey(entry.authorPubkey); + let perContributor = contributions.get(resource); + if (perContributor === undefined) { + perContributor = new Map(); + contributions.set(resource, perContributor); + } + perContributor.set(contributor, value); + continue; + } if (isFairshareFloorPayload(entry.payload)) { recordedFloors.set(entry.payload.resource, entry.payload.perAgentFloor); continue; @@ -284,6 +332,13 @@ export function computeFairshareAllocation( } } + // Fold each contributor's latest contribution onto the seeded baseline. + for (const [resource, perContributor] of contributions) { + for (const value of perContributor.values()) { + supply[resource] += value; + } + } + const resources = [...FAIRSHARE_RESOURCES]; const agents = [...needs.keys()].sort(); diff --git a/src/lib/farms.test.ts b/src/lib/farms.test.ts index 01a3505..ac2ac5b 100644 --- a/src/lib/farms.test.ts +++ b/src/lib/farms.test.ts @@ -1,7 +1,8 @@ import { beforeEach, describe, expect, it } from "vitest"; import { db } from "./db.ts"; import { init } from "./identity.ts"; -import { readAll } from "./eventlog.ts"; +import { append, readAll } from "./eventlog.ts"; +import { computeFairshareAllocation } from "./fairshare.ts"; import { applyFarmsForecastToFairshare, computeGdd, @@ -321,7 +322,7 @@ describe("applyFarmsForecastToFairshare", () => { expect(await readAll()).toEqual([]); }); - it("appends a real seed.resource.food event carrying the optimizer's real forecast value", async () => { + it("appends a real fairshare.contribution event carrying the optimizer's real forecast value", async () => { const gdd = computeGdd(sampleTemps, 10); const crops: CropMaturityWindow[] = [ { cropId: "lettuce", maturityGdd: 5, yieldKgPerM2: 4, kWhPerM2: 1 }, @@ -334,9 +335,22 @@ describe("applyFarmsForecastToFairshare", () => { const entries = await readAll(); expect(entries).toHaveLength(1); expect(entries[0]!.payload).toEqual({ - type: "seed.resource.food", + type: "fairshare.contribution", resource: "food", value: 400, // 100 m^2 * 4 kg/m^2 }); }); + + it("ADDS the harvest forecast to the seeded food baseline instead of overwriting it (no starvation)", async () => { + await append({ type: "seed.resource.food", resource: "food", value: 410 }); + const gdd = computeGdd(sampleTemps, 10); + const crops: CropMaturityWindow[] = [ + { cropId: "lettuce", maturityGdd: 5, yieldKgPerM2: 4, kWhPerM2: 1 }, + ]; + const computation = solveFarmsPlantingOptimizer({ gdd, plots, crops }); + await applyFarmsForecastToFairshare(computation); // +400 kg + + const supply = computeFairshareAllocation(await readAll()).supply; + expect(supply.food).toBe(810); // 410 baseline + 400 forecast, NOT 400 + }); }); diff --git a/src/lib/farms.ts b/src/lib/farms.ts index 172b595..ebbc1fc 100644 --- a/src/lib/farms.ts +++ b/src/lib/farms.ts @@ -328,11 +328,13 @@ export function solveFarmsPlantingOptimizer( /** * The one and only code path by which a Farms harvest forecast reaches - * ma-fairshare's food resource (src/lib/fairshare.ts, todo 14): appending a - * real, signed `seed.resource.food` event carrying the optimizer's real - * `totalForecastYieldKg` - Fair Share's exact `seed.resource.` - * resource-input contract (see fairshare.ts's `SeedResourcePayload`). A - * computation that is insufficient-data or an infeasible solve is a no-op + * ma-fairshare's food resource (src/lib/fairshare.ts): appending a real, + * signed `fairshare.contribution` event carrying the optimizer's real + * `totalForecastYieldKg`. Fair Share ADDS each contributor's latest + * contribution on top of the admin-seeded food baseline (it never overwrites + * it), so a harvest forecast can only RAISE the food pool and multiple + * growers' forecasts sum - growing food can never starve the settlement. + * A computation that is insufficient-data or an infeasible solve is a no-op * here and returns `undefined`: no fabricated or partial forecast value * ever reaches Fair Share's food pool through this function or any other. */ @@ -344,7 +346,7 @@ export async function applyFarmsForecastToFairshare( return undefined; } return appendFn({ - type: "seed.resource.food", + type: "fairshare.contribution", resource: "food", value: computation.totalForecastYieldKg, }); @@ -352,7 +354,7 @@ export async function applyFarmsForecastToFairshare( /** The full result of settling one real Farms harvest forecast into Fair Share. */ export interface FarmsForecastSettlement { - /** The real `seed.resource.food` event that credited the food pool. */ + /** The real `fairshare.contribution` event that credited the food pool. */ creditEntry: StoredEventLogEntry; /** The real `fairshare.allocation.cycle` event recording the re-solve. */ cycleEntry: StoredEventLogEntry; diff --git a/src/miniapps/farms/FarmsScreen.tsx b/src/miniapps/farms/FarmsScreen.tsx index ae447c5..ddcf541 100644 --- a/src/miniapps/farms/FarmsScreen.tsx +++ b/src/miniapps/farms/FarmsScreen.tsx @@ -29,9 +29,16 @@ export function FarmsScreen() { const [temperatureEntries, setTemperatureEntries] = useState([]); const [plots, setPlots] = useState([]); const [crops, setCrops] = useState([]); + const [energyBudgetInput, setEnergyBudgetInput] = useState(""); + + const parsedBudget = Number(energyBudgetInput); + const energyBudgetKwh = + energyBudgetInput.trim() !== "" && Number.isFinite(parsedBudget) && parsedBudget >= 0 + ? parsedBudget + : undefined; const gdd = computeGdd(temperatureEntries, baseTempC); - const computation = solveFarmsPlantingOptimizer({ gdd, plots, crops }); + const computation = solveFarmsPlantingOptimizer({ gdd, plots, crops, energyBudgetKwh }); // The one and only trigger for the Farms -> Fair Share food edge // (mirrors Water Watch's `settleCorroboratedReading` wiring in @@ -71,7 +78,25 @@ export function FarmsScreen() { return (
- + + +
+ + setEnergyBudgetInput(e.target.value)} + placeholder="unlimited" + style={{ flex: 1, padding: 8, border: "1px solid #d0d5dd", borderRadius: 8 }} + /> +
@@ -40,6 +42,13 @@ export function ForecastPanel({ computation }: ForecastPanelProps) { {computation.cumulativeGdd.toFixed(2)} +
+ Grow-light energy + + {computation.totalEnergyKwh.toFixed(2)} kWh + {energyBudgetKwh !== undefined ? ` / ${energyBudgetKwh.toFixed(2)} budget` : ""} + +
); } diff --git a/src/miniapps/farms/coreLoopFoodIntegration.test.tsx b/src/miniapps/farms/coreLoopFoodIntegration.test.tsx index 4c591f2..2d4bf4f 100644 --- a/src/miniapps/farms/coreLoopFoodIntegration.test.tsx +++ b/src/miniapps/farms/coreLoopFoodIntegration.test.tsx @@ -102,7 +102,7 @@ describe("Farms -> Fair Share food integration (plan todo 16, QA happy path)", ( }); let creditEvents = entries.filter( - (e) => (e.payload as { type?: string }).type === "seed.resource.food", + (e) => (e.payload as { type?: string }).type === "fairshare.contribution", ); expect(creditEvents).toHaveLength(1); expect((creditEvents[0]!.payload as { value: number }).value).toBeCloseTo(200, 6); @@ -139,7 +139,7 @@ describe("Farms -> Fair Share food integration (plan todo 16, QA happy path)", ( }); creditEvents = entries.filter( - (e) => (e.payload as { type?: string }).type === "seed.resource.food", + (e) => (e.payload as { type?: string }).type === "fairshare.contribution", ); expect(creditEvents).toHaveLength(2); expect((creditEvents[1]!.payload as { value: number }).value).toBeCloseTo(300, 6);