fix(farms): source grow-light power budget from Fair Share's live allocation

coherence-audit/farms.md #3: FarmsScreen.tsx's energyBudgetKwh was a
free-text number the grower typed, fully disconnected from Fair Share's
real power supply/allocation despite the README calling it "a fixed
grow-light power budget".

- FarmsScreen.tsx: replace the energyBudgetInput text state with a live
  read via useActiveAccountId + useEventLogEntries + computeFairshareAllocation
  (mirrors ResourceTiles.tsx's own live-allocation read and
  settleFarmsForecast's readAll()+computeFairshareAllocation call pattern),
  gated on allocation.supply.power > 0 so an account that merely
  participates in some OTHER resource market (e.g. food) before any power
  market exists doesn't get a fabricated hard-zero budget from that map's
  zero-initialized default. solveFarmsPlantingOptimizer's constraint logic
  is untouched.
- The manual number input becomes a read-only display of the resolved
  Fair Share figure ("No Fair Share power allocation yet (unlimited)" when
  absent).
- ceeiSpike.ts: fixes a real pre-existing divide-by-zero in
  solveCeeiWaterFilling, surfaced by this wiring - a market good with zero
  total bids (price 0 despite positive supply, i.e. no agent currently
  wants it) produced 0/0 = NaN that poisoned every later iteration and
  every other resource's allocation for that agent. Zero demand now
  allocates zero honestly instead of propagating NaN.
- FarmsScreen.test.tsx: new test proves the LP schedule re-solves when
  Fair Share's real power allocation changes (1 kWh -> 2.00 kg forecast,
  10 kWh -> 20.00 kg), with no manual budget entry.
This commit is contained in:
OmO Orchestrator committed 2026-11-20 17:58:03 -05:00
1 parent 21bae7495c
commit 68df7f0761
3 files changed
+110 -18

No files matched your search

+7 -1
View File
@@ -251,7 +251,13 @@ export function solveCeeiWaterFilling(
}
for (let j = 0; j < nGoods; j++) prices[j] /= instance.supply[j];
allocation = bids.map((bid) => bid.map((b, j) => b / prices[j]));
// A good with zero total bids (price 0, despite positive supply) means
// every agent's own bid for it is also exactly 0 - nobody wants it this
// round. `0 / 0` would otherwise surface as NaN and poison every later
// iteration (gains/totalGain/nextBid all inherit it, and a NaN delta
// never satisfies the `<= tolerance` convergence check, so the result
// never recovers). Zero demand honestly allocates zero, not NaN.
allocation = bids.map((bid) => bid.map((b, j) => (prices[j] === 0 ? 0 : b / prices[j])));
let delta = 0;
const nextBids = instance.budgets.map((budget, i) => {
+72 -1
View File
@@ -4,7 +4,9 @@ import { cleanup, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { db } from "../../lib/db.ts";
import { init } from "../../lib/identity.ts";
import { append } from "../../lib/eventlog.ts";
import { getPublicKey, init } from "../../lib/identity.ts";
import { toAccountId } from "../../shell/accountId.ts";
import { FarmsScreen } from "./FarmsScreen.tsx";
afterEach(cleanup);
@@ -137,3 +139,72 @@ describe("FarmsScreen (backend sync wiring, plan todo 4)", () => {
});
});
});
describe("FarmsScreen (grow-light power budget sourced from Fair Share's live allocation, coherence-audit/farms.md #3)", () => {
beforeEach(async () => {
indexedDB.deleteDatabase(db.name);
db.close();
await db.open();
await init();
});
it("re-solves the LP schedule when Fair Share's real power allocation changes, with no manual budget entry", async () => {
const accountId = toAccountId(await getPublicKey());
// A real signed power need (the fix for coherence-audit/farms.md #3)
// is the ONLY way this account enters Fair Share's power market - with
// a single reporting agent, `computeFairshareAllocation`'s conservation
// guarantee (every resource with positive supply sums to exactly that
// supply across all agents) means the full seeded power supply goes
// entirely to this account, so seeding the power supply directly and
// deterministically controls the grower's real `energyBudgetKwh` -
// never a number the grower typed in themselves.
await append({ type: "fairshare.need", agent: accountId, resource: "power", value: 1 });
await append({ type: "seed.resource.power", resource: "power", value: 1 });
const user = userEvent.setup();
render(<FarmsScreen />);
await waitFor(() => {
expect(screen.getByTestId("farms-energy-budget")).toHaveTextContent("1 kWh");
});
await user.clear(screen.getByTestId("farms-base-temp"));
await user.type(screen.getByTestId("farms-base-temp"), "10");
await user.type(screen.getByTestId("farms-temp-date"), "2026-05-01");
await user.type(screen.getByTestId("farms-temp-tmin"), "10");
await user.type(screen.getByTestId("farms-temp-tmax"), "30");
await user.click(screen.getByTestId("farms-temp-add"));
await user.type(screen.getByTestId("farms-plot-id"), "plot-a");
await user.type(screen.getByTestId("farms-plot-area"), "1000");
await user.click(screen.getByTestId("farms-plot-add"));
await user.type(screen.getByTestId("farms-crop-id"), "wheat");
await user.type(screen.getByTestId("farms-crop-maturity-gdd"), "10");
await user.type(screen.getByTestId("farms-crop-yield"), "2");
await user.type(screen.getByTestId("farms-crop-kwh"), "1");
await user.click(screen.getByTestId("farms-crop-add"));
// Budget-constrained: 1000 m^2 of plot area is available, but only
// 1 kWh of real Fair Share power allocation - at 1 kWh/m^2, the LP can
// plant at most 1 m^2, forecasting 1 m^2 * 2 kg/m^2 = 2.00 kg, NOT the
// area-only 2000.00 kg an unlimited budget would allow.
await waitFor(() => {
expect(screen.getByTestId("farms-forecast-total")).toHaveTextContent("2.00 kg");
});
// Raising Fair Share's real seeded power supply (e.g. an admin
// provisioning more grow-light power this cycle) - with no change to
// any Farms-local temperature/plot/crop state and no text field the
// resident touches - re-solves the LP against the new live allocation.
await append({ type: "seed.resource.power", resource: "power", value: 10 });
await waitFor(() => {
expect(screen.getByTestId("farms-energy-budget")).toHaveTextContent("10 kWh");
});
await waitFor(() => {
expect(screen.getByTestId("farms-forecast-total")).toHaveTextContent("20.00 kg");
});
});
});
+31 -16
View File
@@ -7,7 +7,10 @@ import {
type PlantingPlot,
type TemperatureEntry,
} from "../../lib/farms.ts";
import { computeFairshareAllocation } from "../../lib/fairshare.ts";
import { trySyncWithBackend } from "../../lib/sync.ts";
import { useActiveAccountId } from "../../shell/useActiveAccountId.ts";
import { useEventLogEntries } from "../../shell/useEventLogEntries.ts";
import { ForecastPanel } from "./ForecastPanel.tsx";
import { PlantingInputForm } from "./PlantingInputForm.tsx";
import { ScheduleGrid } from "./ScheduleGrid.tsx";
@@ -29,12 +32,28 @@ 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);
// The grow-light power budget is the grower's real, live Fair Share power
// allocation (plan coherence-audit/farms.md #3) - never a free-typed
// number of the grower's own choosing. Read the same way `ResourceTiles`
// reads every other resource's live allocation: `useActiveAccountId` for
// the signed identity, `useEventLogEntries` (Dexie `liveQuery(readAll)`)
// for the live replayed Event Log, `computeFairshareAllocation` for the
// real CEEI solve. Gated on `supply.power > 0`: an account that reported
// a need for some OTHER resource (e.g. food) already has an `acccount`
// entry in `allocation.allocation` with `power: 0` purely as that map's
// zero-initialized default, not a genuine Fair Share-managed power
// figure - reading it as a real budget before a power market even exists
// would silently hard-zero every grower's LP, not honestly represent
// "unlimited" absent any Fair Share power provisioning yet. Once power
// IS seeded, an account's own real resolved share (0 if it never reported
// a power need) is the honest live figure.
const accountId = useActiveAccountId();
const entries = useEventLogEntries();
const allocation = computeFairshareAllocation(entries);
const energyBudgetKwh =
energyBudgetInput.trim() !== "" && Number.isFinite(parsedBudget) && parsedBudget >= 0
? parsedBudget
accountId !== undefined && allocation.supply.power > 0
? allocation.allocation[accountId]?.power
: undefined;
const gdd = computeGdd(temperatureEntries, baseTempC);
@@ -83,19 +102,15 @@ export function FarmsScreen() {
<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"
<span style={{ fontSize: 13, color: "#555" }}>Grow-light power budget (kWh, from Fair Share)</span>
<span
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 }}
/>
style={{ flex: 1, padding: 8, fontWeight: 600 }}
>
{energyBudgetKwh === undefined
? "No Fair Share power allocation yet (unlimited)"
: `${energyBudgetKwh} kWh`}
</span>
</div>
<TemperatureEntryForm