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.
This commit is contained in:
OmO Orchestrator committed 2026-11-20 03:14:49 -05:00
1 parent 38c15c2919
commit d21e2dfe34
7 files changed
+152 -16

No files matched your search

+32 -1
View File
@@ -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<string, number> = {
+55
View File
@@ -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<string, unknown>;
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<FairshareResource, number>();
// 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<FairshareResource, Map<string, number>>();
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();
+17 -3
View File
@@ -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
});
});
+9 -7
View File
@@ -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>`
* 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;
+27 -2
View File
@@ -29,9 +29,16 @@ export function FarmsScreen() {
const [temperatureEntries, setTemperatureEntries] = useState<TemperatureEntry[]>([]);
const [plots, setPlots] = useState<PlantingPlot[]>([]);
const [crops, setCrops] = useState<CropMaturityWindow[]>([]);
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 (
<section className={styles.screen} aria-label="Farms">
<ForecastPanel computation={computation} />
<ForecastPanel computation={computation} energyBudgetKwh={energyBudgetKwh} />
<div
style={{ display: "flex", gap: 8, alignItems: "center", margin: "4px 2px 0" }}
>
<label htmlFor="farms-energy-budget" style={{ fontSize: 13, color: "#555" }}>
Grow-light power budget (kWh, optional)
</label>
<input
id="farms-energy-budget"
data-testid="farms-energy-budget"
type="number"
min="0"
value={energyBudgetInput}
onChange={(e) => setEnergyBudgetInput(e.target.value)}
placeholder="unlimited"
style={{ flex: 1, padding: 8, border: "1px solid #d0d5dd", borderRadius: 8 }}
/>
</div>
<TemperatureEntryForm
baseTempC={baseTempC}
+10 -1
View File
@@ -3,9 +3,11 @@ import styles from "./ForecastPanel.module.css";
export interface ForecastPanelProps {
computation: FarmsPlantingComputation;
/** Grow-light power budget the plan was solved under, if the grower set one. */
energyBudgetKwh?: number;
}
export function ForecastPanel({ computation }: ForecastPanelProps) {
export function ForecastPanel({ computation, energyBudgetKwh }: ForecastPanelProps) {
if (computation.insufficientData) {
return (
<div className={styles.card} aria-label="Harvest forecast">
@@ -40,6 +42,13 @@ export function ForecastPanel({ computation }: ForecastPanelProps) {
{computation.cumulativeGdd.toFixed(2)}
</span>
</div>
<div className={styles.gddRow}>
<span>Grow-light energy</span>
<span className={styles.gddValue} data-testid="farms-forecast-energy">
{computation.totalEnergyKwh.toFixed(2)} kWh
{energyBudgetKwh !== undefined ? ` / ${energyBudgetKwh.toFixed(2)} budget` : ""}
</span>
</div>
</div>
);
}
@@ -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);