fix(theclimb): persist the return plan to the signed log + anchor the tie-break
The Climb held its plan in useState (wiped on reload, never collective) and its Fair Draw tie-break used Math.random with commit+reveal+verify in one call (self-theater, non-reproducible). The plan is now theclimb.plan.propose/commit signed events replayed on mount (survives reload, identical on a second identity); the tie-break seed is derived deterministically from signed log content, the commit is appended before the reveal, and verifyClimbTieBreakAudit re-checks it from the log. Plus inline input validation.
This commit is contained in:
1 parent
cee6565525
commit
190f2d96f1
7 files changed
+1010
-46
No files matched your search
+168
-1
@@ -1,10 +1,22 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { db } from "./db";
|
||||
import { readAll } from "./eventlog";
|
||||
import { init } from "./identity";
|
||||
import {
|
||||
computeWaveSchedule,
|
||||
extractClimbPlans,
|
||||
fairDrawTieBreaker,
|
||||
isClimbTieBreakCommitPayload,
|
||||
isClimbTieBreakRevealPayload,
|
||||
recordClimbPlan,
|
||||
reconstructLatestClimbPlan,
|
||||
verifyClimbTieBreakAudit,
|
||||
type ClimbTieBreakCommitPayload,
|
||||
type ClimbTieBreakRevealPayload,
|
||||
type ScheduleInput,
|
||||
type WaveTieBreaker,
|
||||
} from "./theclimb";
|
||||
import { verify } from "./fairdraw";
|
||||
|
||||
// Two sectors (A, B) each send a 5-person wave into a single surface node.
|
||||
// Both shafts take exactly 1 period and the modeled horizon is only 2
|
||||
@@ -221,3 +233,158 @@ describe("computeWaveSchedule - capacity invariant (regression for tie-break pat
|
||||
});
|
||||
});
|
||||
|
||||
// A genuinely contested fixture: SectorA and SectorB each send a 5-person wave
|
||||
// at period 0 toward a single surface node whose only capacity (5, at period 1)
|
||||
// can take just one of them. Exactly one wave wins the contested slot, so the
|
||||
// solve MUST resolve at least one tie - the right shape to exercise the real
|
||||
// deterministic + logged tie-break path.
|
||||
function contestedInputs(): ScheduleInput {
|
||||
return {
|
||||
horizonPeriods: 2,
|
||||
shafts: [
|
||||
{ id: "shaftA", from: "SectorA", to: "Surface", capacityPerPeriod: 10, travelPeriods: 1, costPerPerson: 1 },
|
||||
{ id: "shaftB", from: "SectorB", to: "Surface", capacityPerPeriod: 10, travelPeriods: 1, costPerPerson: 1 },
|
||||
],
|
||||
demands: [
|
||||
{ id: "waveA", sectorId: "SectorA", readyPeriod: 0, count: 5 },
|
||||
{ id: "waveB", sectorId: "SectorB", readyPeriod: 0, count: 5 },
|
||||
],
|
||||
surfaceNodeId: "Surface",
|
||||
surfaceCapacity: [{ period: 1, capacity: 5 }],
|
||||
};
|
||||
}
|
||||
|
||||
describe("The Climb Event Log persistence - a committed plan survives reload and replays identically", () => {
|
||||
beforeEach(async () => {
|
||||
indexedDB.deleteDatabase(db.name);
|
||||
db.close();
|
||||
await db.open();
|
||||
await init();
|
||||
});
|
||||
|
||||
it("persists a propose+commit pair and reconstructs the identical schedule from a cold replay of readAll()", async () => {
|
||||
const { planId, schedule } = await recordClimbPlan(contestedInputs());
|
||||
|
||||
// Cold replay: read the log back from scratch (what a fresh page load does)
|
||||
// and rebuild the plan purely from the signed events - no re-solve.
|
||||
const plan = reconstructLatestClimbPlan(await readAll());
|
||||
expect(plan).toBeDefined();
|
||||
expect(plan?.planId).toBe(planId);
|
||||
expect(plan?.schedule).toEqual(schedule);
|
||||
// The committed inputs are carried back too, so the form repopulates.
|
||||
expect(plan?.inputs.horizonPeriods).toBe(2);
|
||||
expect(plan?.inputs.shafts).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("reconstructs the same committed plan for a second, different identity replaying the same log", async () => {
|
||||
const { schedule } = await recordClimbPlan(contestedInputs());
|
||||
const entriesAsAuthor = await readAll();
|
||||
const firstIdentity = await init();
|
||||
|
||||
// Simulate a second device/resident: drop the local keypair and generate a
|
||||
// brand-new identity, while the signed log (authored by the first
|
||||
// identity) stays intact - exactly what cross-device sync delivers.
|
||||
await db.identity.clear();
|
||||
const secondIdentity = await init();
|
||||
expect(secondIdentity.publicKey).not.toEqual(firstIdentity.publicKey);
|
||||
|
||||
const entriesAsSecondIdentity = await readAll();
|
||||
const plan = reconstructLatestClimbPlan(entriesAsSecondIdentity);
|
||||
expect(plan?.schedule).toEqual(schedule);
|
||||
// Replay is identity-independent: same bytes in, same plan out.
|
||||
expect(reconstructLatestClimbPlan(entriesAsAuthor)?.schedule).toEqual(plan?.schedule);
|
||||
});
|
||||
|
||||
it("loads the LATEST committed plan when several have been committed", async () => {
|
||||
await recordClimbPlan(contestedInputs());
|
||||
const second = await recordClimbPlan({
|
||||
...contestedInputs(),
|
||||
surfaceCapacity: [{ period: 1, capacity: 3 }],
|
||||
});
|
||||
|
||||
const plans = extractClimbPlans(await readAll());
|
||||
expect(plans).toHaveLength(2);
|
||||
const latest = reconstructLatestClimbPlan(await readAll());
|
||||
expect(latest?.planId).toBe(second.planId);
|
||||
expect(latest?.schedule.totalDelivered).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("The Climb tie-break anchoring - deterministic, published, and auditable from the log", () => {
|
||||
beforeEach(async () => {
|
||||
indexedDB.deleteDatabase(db.name);
|
||||
db.close();
|
||||
await db.open();
|
||||
await init();
|
||||
});
|
||||
|
||||
it("produces the identical contested-slot winner across two solves of the same committed input", async () => {
|
||||
const first = await recordClimbPlan(contestedInputs());
|
||||
const second = await recordClimbPlan(contestedInputs());
|
||||
|
||||
// The draw is seeded deterministically from the plan's inputs hash + the
|
||||
// contested slot, so the same committed input always picks the same winner.
|
||||
expect(first.inputsHash).toBe(second.inputsHash);
|
||||
expect(second.schedule.shaftFlows).toEqual(first.schedule.shaftFlows);
|
||||
expect(second.schedule.demandOutcomes).toEqual(first.schedule.demandOutcomes);
|
||||
expect(first.schedule.tieBreaksResolved.length).toBeGreaterThan(0);
|
||||
expect(second.schedule.tieBreaksResolved.map((r) => r.chosenIndex)).toEqual(
|
||||
first.schedule.tieBreaksResolved.map((r) => r.chosenIndex),
|
||||
);
|
||||
});
|
||||
|
||||
it("publishes each tie-break commit to the log BEFORE its reveal, and the published hash verifies against the revealed seed", async () => {
|
||||
const { planId } = await recordClimbPlan(contestedInputs());
|
||||
const entries = await readAll();
|
||||
|
||||
const commits = entries.filter(
|
||||
(e) => isClimbTieBreakCommitPayload(e.payload) && e.payload.planId === planId,
|
||||
);
|
||||
const reveals = entries.filter(
|
||||
(e) => isClimbTieBreakRevealPayload(e.payload) && e.payload.planId === planId,
|
||||
);
|
||||
expect(commits.length).toBeGreaterThan(0);
|
||||
expect(reveals.length).toBe(commits.length);
|
||||
|
||||
for (const revealEntry of reveals) {
|
||||
const revealPayload = revealEntry.payload as ClimbTieBreakRevealPayload;
|
||||
const commitEntry = commits.find(
|
||||
(c) => (c.payload as ClimbTieBreakCommitPayload).drawId === revealPayload.drawId,
|
||||
);
|
||||
expect(commitEntry).toBeDefined();
|
||||
const commitPayload = commitEntry!.payload as ClimbTieBreakCommitPayload;
|
||||
// Commit was genuinely published BEFORE the reveal.
|
||||
expect(commitEntry!.lamportTs).toBeLessThan(revealEntry.lamportTs);
|
||||
// The published commit hash verifies against the seed read back from the log.
|
||||
await expect(
|
||||
verify(commitPayload.commitHash, revealPayload.seed, revealPayload.salt),
|
||||
).resolves.toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("passes the full log-only tie-break audit (commit-before-reveal + hash + reproducible winner)", async () => {
|
||||
const { planId } = await recordClimbPlan(contestedInputs());
|
||||
await expect(verifyClimbTieBreakAudit(await readAll(), planId)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("rejects the audit when a reveal's seed does not match its published commit (tamper detection)", async () => {
|
||||
const { planId } = await recordClimbPlan(contestedInputs());
|
||||
const entries = await readAll();
|
||||
const tampered = entries.map((e) => {
|
||||
if (isClimbTieBreakRevealPayload(e.payload) && e.payload.planId === planId) {
|
||||
return { ...e, payload: { ...e.payload, seed: `${e.payload.seed}-tampered` } };
|
||||
}
|
||||
return e;
|
||||
});
|
||||
await expect(verifyClimbTieBreakAudit(tampered, planId)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("never leaves a dangling propose in the log when the plan is invalid (rejected before any append)", async () => {
|
||||
const before = (await readAll()).length;
|
||||
await expect(
|
||||
recordClimbPlan({ ...contestedInputs(), horizonPeriods: 0 }),
|
||||
).rejects.toThrow(/horizonPeriods must be a positive integer/);
|
||||
expect((await readAll()).length).toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
+495
-31
@@ -35,6 +35,9 @@
|
||||
*/
|
||||
|
||||
import { commit, drawOutcome, reveal, verify } from "./fairdraw";
|
||||
import { append, type StoredEventLogEntry } from "./eventlog";
|
||||
import { sortForReplay } from "./ledger";
|
||||
import { trySyncWithBackend } from "./sync";
|
||||
|
||||
/** One shaft/elevator/tunnel connecting two physical nodes. */
|
||||
export interface ShaftEdge {
|
||||
@@ -80,6 +83,13 @@ export interface TieBreakContext {
|
||||
distance: number;
|
||||
/** Which augmentation round of the solve this tie was found in. */
|
||||
iteration: number;
|
||||
/** Deterministic SHA-256 hex over the committed plan inputs (see
|
||||
* `hashScheduleInputs`). The tie-break seed is derived from this plus the
|
||||
* contested slot's identity, so the draw outcome is a pure function of the
|
||||
* signed plan content - the same committed plan always resolves the same
|
||||
* contested slot the same way, and anyone replaying the log can recompute
|
||||
* it. */
|
||||
planInputsHash: string;
|
||||
}
|
||||
|
||||
export interface TieBreakRecord extends TieBreakContext {
|
||||
@@ -125,37 +135,194 @@ export interface WaveSchedule {
|
||||
tieBreaksResolved: readonly TieBreakRecord[];
|
||||
}
|
||||
|
||||
function toHex(bytes: ArrayBuffer): string {
|
||||
return Array.from(new Uint8Array(bytes))
|
||||
.map((b) => b.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** Plain, serializable snapshot of the plan inputs an engine solves over -
|
||||
* everything except the (non-serializable, test-only) `tieBreaker`. This is
|
||||
* exactly what a `theclimb.plan.propose` event carries and what the screen
|
||||
* replays back on reload. */
|
||||
export interface ClimbPlanInputs {
|
||||
horizonPeriods: number;
|
||||
surfaceNodeId: string;
|
||||
shafts: ShaftEdge[];
|
||||
demands: WaveDemandGroup[];
|
||||
surfaceCapacity: SurfaceCapacityPeriod[];
|
||||
}
|
||||
|
||||
/** Strips the non-serializable `tieBreaker` off a `ScheduleInput`, leaving the
|
||||
* plain plan inputs that get signed into the log and replayed on reload. */
|
||||
export function toClimbPlanInputs(input: ScheduleInput): ClimbPlanInputs {
|
||||
return {
|
||||
horizonPeriods: input.horizonPeriods,
|
||||
surfaceNodeId: input.surfaceNodeId,
|
||||
shafts: input.shafts.map((shaft) => ({ ...shaft })),
|
||||
demands: input.demands.map((demand) => ({ ...demand })),
|
||||
surfaceCapacity: input.surfaceCapacity.map((entry) => ({ ...entry })),
|
||||
};
|
||||
}
|
||||
|
||||
/** A field-order- and array-order-independent canonical form of the plan
|
||||
* inputs, so `hashScheduleInputs` yields the same digest for the same plan
|
||||
* regardless of the order shafts/demands/capacity happened to be entered in. */
|
||||
function canonicalPlanInputs(input: ScheduleInput): ClimbPlanInputs {
|
||||
return {
|
||||
horizonPeriods: input.horizonPeriods,
|
||||
surfaceNodeId: input.surfaceNodeId,
|
||||
shafts: input.shafts
|
||||
.map((shaft) => ({
|
||||
id: shaft.id,
|
||||
from: shaft.from,
|
||||
to: shaft.to,
|
||||
capacityPerPeriod: shaft.capacityPerPeriod,
|
||||
travelPeriods: shaft.travelPeriods,
|
||||
costPerPerson: shaft.costPerPerson ?? shaft.travelPeriods,
|
||||
}))
|
||||
.sort((a, b) => a.id.localeCompare(b.id)),
|
||||
demands: input.demands
|
||||
.map((demand) => ({
|
||||
id: demand.id,
|
||||
sectorId: demand.sectorId,
|
||||
readyPeriod: demand.readyPeriod,
|
||||
count: demand.count,
|
||||
}))
|
||||
.sort((a, b) => a.id.localeCompare(b.id)),
|
||||
surfaceCapacity: input.surfaceCapacity
|
||||
.map((entry) => ({ period: entry.period, capacity: entry.capacity }))
|
||||
.sort((a, b) => a.period - b.period),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The default `WaveTieBreaker`: uses Fair Draw's real commit/reveal/verify
|
||||
* protocol to produce a verifiably-not-rigged seed, then
|
||||
* `drawOutcome(seed, optionCount)` to pick the winning candidate. Any
|
||||
* verification failure throws rather than falling back to a guess.
|
||||
*
|
||||
* KNOWN GAP (follow-up, out of scope here - see
|
||||
* .omo/plans/fix-miniapp-gaps-and-demo-video.md): the seed/salt below are
|
||||
* generated with `Math.random()` purely in-memory and never published via
|
||||
* `append()` to the signed event log before this resolver commits/reveals
|
||||
* them. That is the same unpublished-commit gap documented for Fair Draw
|
||||
* itself - a verifier has no independently-anchored commit to check this
|
||||
* draw against. Not fixed here; this comment only records it as a named
|
||||
* follow-up.
|
||||
* Deterministic SHA-256 (lowercase hex) over the canonical plan inputs. This
|
||||
* is the "signed log content" the tie-break seed is anchored to: two solves of
|
||||
* the same committed plan hash to the same value, so they derive the same
|
||||
* contested-slot seeds and therefore pick the same winners. Nothing random
|
||||
* ever enters it.
|
||||
*/
|
||||
export async function hashScheduleInputs(input: ScheduleInput): Promise<string> {
|
||||
const digest = await crypto.subtle.digest(
|
||||
"SHA-256",
|
||||
new TextEncoder().encode(JSON.stringify(canonicalPlanInputs(input))) as BufferSource,
|
||||
);
|
||||
return toHex(digest);
|
||||
}
|
||||
|
||||
/** The contested slot's identity inside the time-expanded solve. */
|
||||
export interface ClimbTieBreakSlot {
|
||||
node: string;
|
||||
distance: number;
|
||||
iteration: number;
|
||||
}
|
||||
|
||||
/** The seed a contested slot's draw is resolved from - a pure function of the
|
||||
* committed plan's inputs hash and the slot's identity, with no randomness. */
|
||||
function deriveTieBreakSeed(context: TieBreakContext): string {
|
||||
return `theclimb-tie:${context.planInputsHash}:${context.node}:${context.distance}:${context.iteration}`;
|
||||
}
|
||||
|
||||
/** The commit salt for a contested slot's draw - likewise deterministic. */
|
||||
function deriveTieBreakSalt(context: TieBreakContext): string {
|
||||
return `theclimb-salt:${context.planInputsHash}:${context.node}:${context.iteration}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The default `WaveTieBreaker`: a PURE, deterministic, reproducible draw. The
|
||||
* seed is derived from the committed plan's inputs hash and the contested
|
||||
* slot's identity (never `Math.random()`), so `drawOutcome(seed, optionCount)`
|
||||
* is a pure function of the signed plan content - two solves of the same
|
||||
* committed plan pick the same winner, and anyone replaying the log can
|
||||
* recompute it. It performs NO append and NO sham self-verification; the
|
||||
* published, auditable commit/reveal trail is produced by
|
||||
* `createLoggingTieBreaker` (used by `recordClimbPlan`) when a plan is
|
||||
* actually committed to the shared log. This default is for the live
|
||||
* pre-commit preview and for pure-engine tests.
|
||||
*/
|
||||
export const fairDrawTieBreaker: WaveTieBreaker = {
|
||||
async resolve(optionCount, context) {
|
||||
const seed = `theclimb-tie:${context.node}:${context.distance}:${context.iteration}:${Math.random().toString(36).slice(2)}`;
|
||||
const salt = `theclimb-salt:${Math.random().toString(36).slice(2)}`;
|
||||
const commitHash = await commit(seed, salt);
|
||||
const revealed = reveal(seed, salt);
|
||||
const verified = await verify(commitHash, revealed.seed, revealed.salt);
|
||||
if (!verified) {
|
||||
throw new Error(
|
||||
"theclimb: Fair Draw commit/reveal verification failed - refusing to resolve a contested wave-slot tie without a verifiable draw",
|
||||
);
|
||||
}
|
||||
return drawOutcome(revealed.seed, optionCount);
|
||||
return drawOutcome(deriveTieBreakSeed(context), optionCount);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds a `WaveTieBreaker` that anchors every contested-slot draw in the
|
||||
* signed Event Log, in the order the commit-reveal protocol requires:
|
||||
*
|
||||
* 1. derive the deterministic seed/salt from the committed plan's inputs
|
||||
* hash + the contested slot (identical to `fairDrawTieBreaker`);
|
||||
* 2. compute the SHA-256 `commitHash` and PUBLISH a `theclimb.tiebreak.commit`
|
||||
* event via `append()` BEFORE the draw is resolved;
|
||||
* 3. reveal the seed/salt, `verify()` them against the just-published
|
||||
* commit (fails closed if they ever disagree), and compute the winner
|
||||
* with `drawOutcome()`;
|
||||
* 4. PUBLISH a `theclimb.tiebreak.reveal` event recording the revealed
|
||||
* seed/salt, option count, and chosen index.
|
||||
*
|
||||
* The result: every contested wave-slot draw is reproducible (deterministic
|
||||
* seed) AND auditable from the log alone - a verifier reads the commit back,
|
||||
* reads the reveal back, re-checks the hash, and re-runs `drawOutcome` to
|
||||
* confirm the recorded winner. See `verifyClimbTieBreakAudit`.
|
||||
*/
|
||||
export function createLoggingTieBreaker(deps: {
|
||||
planId: string;
|
||||
append: (payload: unknown) => Promise<StoredEventLogEntry>;
|
||||
}): WaveTieBreaker {
|
||||
return {
|
||||
async resolve(optionCount, context) {
|
||||
const seed = deriveTieBreakSeed(context);
|
||||
const salt = deriveTieBreakSalt(context);
|
||||
const commitHash = await commit(seed, salt);
|
||||
const drawId = crypto.randomUUID();
|
||||
const slot: ClimbTieBreakSlot = {
|
||||
node: context.node,
|
||||
distance: context.distance,
|
||||
iteration: context.iteration,
|
||||
};
|
||||
|
||||
// Publish the commit BEFORE resolving the draw - the whole point of the
|
||||
// protocol. A verifier later checks this commit's lamportTs precedes
|
||||
// the matching reveal's.
|
||||
const commitPayload: ClimbTieBreakCommitPayload = {
|
||||
type: "theclimb.tiebreak.commit",
|
||||
planId: deps.planId,
|
||||
drawId,
|
||||
inputsHash: context.planInputsHash,
|
||||
slot,
|
||||
commitHash,
|
||||
committedAt: Date.now(),
|
||||
};
|
||||
await deps.append(commitPayload);
|
||||
|
||||
const revealed = reveal(seed, salt);
|
||||
const verified = await verify(commitHash, revealed.seed, revealed.salt);
|
||||
if (!verified) {
|
||||
throw new Error(
|
||||
"theclimb: tie-break commit/reveal verification failed - refusing to resolve a contested wave-slot tie without a verifiable draw",
|
||||
);
|
||||
}
|
||||
const chosenIndex = await drawOutcome(revealed.seed, optionCount);
|
||||
|
||||
const revealPayload: ClimbTieBreakRevealPayload = {
|
||||
type: "theclimb.tiebreak.reveal",
|
||||
planId: deps.planId,
|
||||
drawId,
|
||||
inputsHash: context.planInputsHash,
|
||||
slot,
|
||||
seed: revealed.seed,
|
||||
salt: revealed.salt,
|
||||
optionCount,
|
||||
chosenIndex,
|
||||
};
|
||||
await deps.append(revealPayload);
|
||||
|
||||
return chosenIndex;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const SOURCE = "\u0000S";
|
||||
const SINK = "\u0000T";
|
||||
const EPS = 1e-9;
|
||||
@@ -199,13 +366,18 @@ function sectorPeriodNode(nodeId: string, period: number): string {
|
||||
return `${nodeId}@${period}`;
|
||||
}
|
||||
|
||||
function buildTimeExpandedGraph(input: ScheduleInput): ResidualGraph {
|
||||
const { horizonPeriods, shafts, demands, surfaceNodeId, surfaceCapacity } = input;
|
||||
/**
|
||||
* Pure, side-effect-free validation of a plan's inputs - the same positivity /
|
||||
* integrality / in-horizon checks the graph build relies on, extracted so
|
||||
* `recordClimbPlan` can reject a malformed plan BEFORE it appends any event
|
||||
* (never leaving a dangling `theclimb.plan.propose` with no matching commit),
|
||||
* and so the input form can surface the same rules as inline field errors.
|
||||
*/
|
||||
export function validateScheduleInput(input: ScheduleInput): void {
|
||||
const { horizonPeriods, shafts, demands } = input;
|
||||
if (!Number.isInteger(horizonPeriods) || horizonPeriods < 1) {
|
||||
throw new RangeError("theclimb: horizonPeriods must be a positive integer");
|
||||
}
|
||||
|
||||
const physicalNodes = new Set<string>([surfaceNodeId]);
|
||||
for (const shaft of shafts) {
|
||||
if (!Number.isFinite(shaft.capacityPerPeriod) || !(shaft.capacityPerPeriod > 0)) {
|
||||
throw new RangeError(`theclimb: shaft ${shaft.id} capacityPerPeriod must be > 0`);
|
||||
@@ -213,8 +385,6 @@ function buildTimeExpandedGraph(input: ScheduleInput): ResidualGraph {
|
||||
if (!Number.isInteger(shaft.travelPeriods) || shaft.travelPeriods < 1) {
|
||||
throw new RangeError(`theclimb: shaft ${shaft.id} travelPeriods must be a positive integer`);
|
||||
}
|
||||
physicalNodes.add(shaft.from);
|
||||
physicalNodes.add(shaft.to);
|
||||
}
|
||||
for (const demand of demands) {
|
||||
if (!Number.isFinite(demand.count) || !(demand.count > 0)) {
|
||||
@@ -226,6 +396,19 @@ function buildTimeExpandedGraph(input: ScheduleInput): ResidualGraph {
|
||||
if (demand.readyPeriod < 0 || demand.readyPeriod >= horizonPeriods) {
|
||||
throw new RangeError(`theclimb: demand ${demand.id} readyPeriod is outside the modeled horizon`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildTimeExpandedGraph(input: ScheduleInput): ResidualGraph {
|
||||
validateScheduleInput(input);
|
||||
const { shafts, demands, surfaceNodeId, surfaceCapacity, horizonPeriods } = input;
|
||||
|
||||
const physicalNodes = new Set<string>([surfaceNodeId]);
|
||||
for (const shaft of shafts) {
|
||||
physicalNodes.add(shaft.from);
|
||||
physicalNodes.add(shaft.to);
|
||||
}
|
||||
for (const demand of demands) {
|
||||
physicalNodes.add(demand.sectorId);
|
||||
}
|
||||
|
||||
@@ -302,6 +485,7 @@ async function findAugmentingPath(
|
||||
graph: ResidualGraph,
|
||||
tieBreaker: WaveTieBreaker,
|
||||
iteration: number,
|
||||
planInputsHash: string,
|
||||
): Promise<AugmentingPath | null> {
|
||||
const dist = new Map<string, number>([[SOURCE, 0]]);
|
||||
const predecessors = new Map<string, PathStep[]>();
|
||||
@@ -375,6 +559,7 @@ async function findAugmentingPath(
|
||||
node,
|
||||
distance: dist.get(node) as number,
|
||||
iteration,
|
||||
planInputsHash,
|
||||
});
|
||||
if (!Number.isInteger(chosenLocal) || chosenLocal < 0 || chosenLocal >= viable.length) {
|
||||
throw new Error(
|
||||
@@ -385,6 +570,7 @@ async function findAugmentingPath(
|
||||
node,
|
||||
distance: dist.get(node) as number,
|
||||
iteration,
|
||||
planInputsHash,
|
||||
optionCount: viable.length,
|
||||
chosenIndex: chosenLocal,
|
||||
};
|
||||
@@ -425,13 +611,14 @@ async function findAugmentingPath(
|
||||
export async function computeWaveSchedule(input: ScheduleInput): Promise<WaveSchedule> {
|
||||
const graph = buildTimeExpandedGraph(input);
|
||||
const tieBreaker = input.tieBreaker ?? fairDrawTieBreaker;
|
||||
const planInputsHash = await hashScheduleInputs(input);
|
||||
|
||||
const tieBreaksResolved: TieBreakRecord[] = [];
|
||||
let totalDelivered = 0;
|
||||
let iteration = 0;
|
||||
|
||||
while (iteration < MAX_ITERATIONS) {
|
||||
const path = await findAugmentingPath(graph, tieBreaker, iteration);
|
||||
const path = await findAugmentingPath(graph, tieBreaker, iteration, planInputsHash);
|
||||
if (!path) break;
|
||||
|
||||
const bottleneck = Math.min(...path.steps.map((step) => step.edge.cap));
|
||||
@@ -504,3 +691,280 @@ export async function computeWaveSchedule(input: ScheduleInput): Promise<WaveSch
|
||||
tieBreaksResolved,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Signed Event Log persistence (plan: The Climb has no persistence).
|
||||
//
|
||||
// The Climb plans the MASS return - an inherently collective decision - so its
|
||||
// plan belongs in the one shared, signed, replayable Event Log like every
|
||||
// other mini-app's state, not in ephemeral component `useState`. A plan is two
|
||||
// signed events, mirroring Housing's `housing.assignment` reducer shape:
|
||||
//
|
||||
// - `theclimb.plan.propose` carries the raw inputs (shafts/demands/capacity/
|
||||
// horizon) a solve will run over, plus their deterministic `inputsHash`.
|
||||
// - `theclimb.plan.commit` carries the SOLVED `WaveSchedule` for that plan.
|
||||
//
|
||||
// Rebuilding the screen is a pure replay of `readAll()` (see
|
||||
// `reconstructLatestClimbPlan`): the committed schedule is read straight back
|
||||
// out of the log, so a committed plan survives reload and replays IDENTICALLY
|
||||
// on any other identity - two residents converge on one return plan. None of
|
||||
// this touches eventlog.ts's append/read/replay path; it only consumes the
|
||||
// sanctioned `append()`/`readAll()` surface, exactly like `housing.ts`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ClimbPlanProposePayload {
|
||||
type: "theclimb.plan.propose";
|
||||
planId: string;
|
||||
inputs: ClimbPlanInputs;
|
||||
inputsHash: string;
|
||||
proposedAt: number;
|
||||
}
|
||||
|
||||
export interface ClimbPlanCommitPayload {
|
||||
type: "theclimb.plan.commit";
|
||||
planId: string;
|
||||
inputsHash: string;
|
||||
schedule: WaveSchedule;
|
||||
committedAt: number;
|
||||
}
|
||||
|
||||
export interface ClimbTieBreakCommitPayload {
|
||||
type: "theclimb.tiebreak.commit";
|
||||
planId: string;
|
||||
drawId: string;
|
||||
inputsHash: string;
|
||||
slot: ClimbTieBreakSlot;
|
||||
commitHash: string;
|
||||
committedAt: number;
|
||||
}
|
||||
|
||||
export interface ClimbTieBreakRevealPayload {
|
||||
type: "theclimb.tiebreak.reveal";
|
||||
planId: string;
|
||||
drawId: string;
|
||||
inputsHash: string;
|
||||
slot: ClimbTieBreakSlot;
|
||||
seed: string;
|
||||
salt: string;
|
||||
optionCount: number;
|
||||
chosenIndex: number;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
export function isClimbPlanProposePayload(payload: unknown): payload is ClimbPlanProposePayload {
|
||||
if (!isRecord(payload)) return false;
|
||||
return (
|
||||
payload.type === "theclimb.plan.propose" &&
|
||||
typeof payload.planId === "string" &&
|
||||
typeof payload.inputsHash === "string" &&
|
||||
typeof payload.proposedAt === "number" &&
|
||||
isRecord(payload.inputs) &&
|
||||
typeof (payload.inputs as Record<string, unknown>).horizonPeriods === "number" &&
|
||||
typeof (payload.inputs as Record<string, unknown>).surfaceNodeId === "string" &&
|
||||
Array.isArray((payload.inputs as Record<string, unknown>).shafts) &&
|
||||
Array.isArray((payload.inputs as Record<string, unknown>).demands) &&
|
||||
Array.isArray((payload.inputs as Record<string, unknown>).surfaceCapacity)
|
||||
);
|
||||
}
|
||||
|
||||
export function isClimbPlanCommitPayload(payload: unknown): payload is ClimbPlanCommitPayload {
|
||||
if (!isRecord(payload)) return false;
|
||||
return (
|
||||
payload.type === "theclimb.plan.commit" &&
|
||||
typeof payload.planId === "string" &&
|
||||
typeof payload.inputsHash === "string" &&
|
||||
typeof payload.committedAt === "number" &&
|
||||
isRecord(payload.schedule) &&
|
||||
Array.isArray((payload.schedule as Record<string, unknown>).shaftFlows) &&
|
||||
Array.isArray((payload.schedule as Record<string, unknown>).surfaceArrivals) &&
|
||||
Array.isArray((payload.schedule as Record<string, unknown>).demandOutcomes) &&
|
||||
typeof (payload.schedule as Record<string, unknown>).totalDelivered === "number"
|
||||
);
|
||||
}
|
||||
|
||||
export function isClimbTieBreakCommitPayload(
|
||||
payload: unknown,
|
||||
): payload is ClimbTieBreakCommitPayload {
|
||||
if (!isRecord(payload)) return false;
|
||||
return (
|
||||
payload.type === "theclimb.tiebreak.commit" &&
|
||||
typeof payload.planId === "string" &&
|
||||
typeof payload.drawId === "string" &&
|
||||
typeof payload.inputsHash === "string" &&
|
||||
typeof payload.commitHash === "string" &&
|
||||
isRecord(payload.slot)
|
||||
);
|
||||
}
|
||||
|
||||
export function isClimbTieBreakRevealPayload(
|
||||
payload: unknown,
|
||||
): payload is ClimbTieBreakRevealPayload {
|
||||
if (!isRecord(payload)) return false;
|
||||
return (
|
||||
payload.type === "theclimb.tiebreak.reveal" &&
|
||||
typeof payload.planId === "string" &&
|
||||
typeof payload.drawId === "string" &&
|
||||
typeof payload.inputsHash === "string" &&
|
||||
typeof payload.seed === "string" &&
|
||||
typeof payload.salt === "string" &&
|
||||
typeof payload.optionCount === "number" &&
|
||||
typeof payload.chosenIndex === "number"
|
||||
);
|
||||
}
|
||||
|
||||
/** One committed Climb plan, extracted from the Event Log: its stored inputs
|
||||
* and the stored solved schedule, reconstructed purely by replay. */
|
||||
export interface ClimbPlanRecord {
|
||||
planId: string;
|
||||
inputs: ClimbPlanInputs;
|
||||
inputsHash: string;
|
||||
schedule: WaveSchedule;
|
||||
lamportTs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays the Event Log into the list of committed Climb plans, in the
|
||||
* deterministic replay order shared with every other reducer in this app
|
||||
* (`sortForReplay`, src/lib/ledger.ts). Each committed plan is paired with the
|
||||
* inputs from its own `theclimb.plan.propose` event (matched by `planId`); a
|
||||
* commit with no matching proposal is skipped (its inputs are unknown, so the
|
||||
* form/congestion could not be rebuilt honestly).
|
||||
*/
|
||||
export function extractClimbPlans(entries: readonly StoredEventLogEntry[]): ClimbPlanRecord[] {
|
||||
const ordered = sortForReplay(entries);
|
||||
const proposalsByPlanId = new Map<string, ClimbPlanInputs>();
|
||||
for (const entry of ordered) {
|
||||
if (isClimbPlanProposePayload(entry.payload)) {
|
||||
proposalsByPlanId.set(entry.payload.planId, entry.payload.inputs);
|
||||
}
|
||||
}
|
||||
const plans: ClimbPlanRecord[] = [];
|
||||
for (const entry of ordered) {
|
||||
if (!isClimbPlanCommitPayload(entry.payload)) continue;
|
||||
const inputs = proposalsByPlanId.get(entry.payload.planId);
|
||||
if (!inputs) continue;
|
||||
plans.push({
|
||||
planId: entry.payload.planId,
|
||||
inputs,
|
||||
inputsHash: entry.payload.inputsHash,
|
||||
schedule: entry.payload.schedule,
|
||||
lamportTs: entry.lamportTs,
|
||||
});
|
||||
}
|
||||
return plans;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconstructs the most recently committed Climb plan (the last one in replay
|
||||
* order) - what the screen loads on mount so a committed plan survives reload
|
||||
* and replays identically on a second identity. `undefined` if no complete
|
||||
* plan (propose + commit) has been recorded yet.
|
||||
*/
|
||||
export function reconstructLatestClimbPlan(
|
||||
entries: readonly StoredEventLogEntry[],
|
||||
): ClimbPlanRecord | undefined {
|
||||
const plans = extractClimbPlans(entries);
|
||||
return plans.length === 0 ? undefined : plans[plans.length - 1];
|
||||
}
|
||||
|
||||
export interface RecordClimbPlanResult {
|
||||
planId: string;
|
||||
inputsHash: string;
|
||||
schedule: WaveSchedule;
|
||||
proposeEntry: StoredEventLogEntry;
|
||||
commitEntry: StoredEventLogEntry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Solves `input` and persists it to the signed Event Log as a `propose` + a
|
||||
* `commit` pair (plus one `theclimb.tiebreak.commit`/`theclimb.tiebreak.reveal`
|
||||
* pair per contested wave slot, published by `createLoggingTieBreaker` DURING
|
||||
* the solve). Mirrors `housing.ts`'s `recordHousingAssignmentCycle`: the inputs
|
||||
* are validated up front so a malformed plan is rejected BEFORE anything is
|
||||
* appended (never a dangling propose), the solve runs through the real
|
||||
* `append()` path, and `trySyncWithBackend()` is fired best-effort afterwards
|
||||
* (never blocking the local-first write). `deps.append` is a test seam.
|
||||
*/
|
||||
export async function recordClimbPlan(
|
||||
input: ScheduleInput,
|
||||
deps: { append?: typeof append; planId?: string } = {},
|
||||
): Promise<RecordClimbPlanResult> {
|
||||
const appendFn = deps.append ?? append;
|
||||
// Reject a malformed plan before ANY event is appended - never leave a
|
||||
// `theclimb.plan.propose` in the log with no matching commit.
|
||||
validateScheduleInput(input);
|
||||
|
||||
const planId = deps.planId ?? crypto.randomUUID();
|
||||
const inputsHash = await hashScheduleInputs(input);
|
||||
|
||||
const proposePayload: ClimbPlanProposePayload = {
|
||||
type: "theclimb.plan.propose",
|
||||
planId,
|
||||
inputs: toClimbPlanInputs(input),
|
||||
inputsHash,
|
||||
proposedAt: Date.now(),
|
||||
};
|
||||
const proposeEntry = await appendFn(proposePayload);
|
||||
|
||||
const tieBreaker = createLoggingTieBreaker({ planId, append: appendFn });
|
||||
const schedule = await computeWaveSchedule({ ...input, tieBreaker });
|
||||
|
||||
const commitPayload: ClimbPlanCommitPayload = {
|
||||
type: "theclimb.plan.commit",
|
||||
planId,
|
||||
inputsHash,
|
||||
schedule,
|
||||
committedAt: Date.now(),
|
||||
};
|
||||
const commitEntry = await appendFn(commitPayload);
|
||||
|
||||
// Best-effort cross-device sync (plan todo 3): fire-and-forget, never blocks
|
||||
// or affects the local-first write that just completed above.
|
||||
void trySyncWithBackend();
|
||||
|
||||
return { planId, inputsHash, schedule, proposeEntry, commitEntry };
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only, replay-only audit of a plan's contested-slot draws: for every
|
||||
* `theclimb.tiebreak.reveal` recorded for `planId`, confirms (1) a matching
|
||||
* `theclimb.tiebreak.commit` (same `drawId`) was PUBLISHED strictly before it,
|
||||
* (2) the revealed seed/salt re-hash to that published `commitHash`, and (3)
|
||||
* re-running `drawOutcome` over the revealed seed reproduces the recorded
|
||||
* winner. Proves every draw was both anchored (commit-before-reveal) and
|
||||
* reproducible from the log alone. Returns `false` (never throws) for any
|
||||
* missing/out-of-order/mismatched draw, and for a plan with no draws at all.
|
||||
*/
|
||||
export async function verifyClimbTieBreakAudit(
|
||||
entries: readonly StoredEventLogEntry[],
|
||||
planId: string,
|
||||
): Promise<boolean> {
|
||||
const ordered = sortForReplay(entries);
|
||||
const commits = ordered.filter(
|
||||
(e) => isClimbTieBreakCommitPayload(e.payload) && e.payload.planId === planId,
|
||||
);
|
||||
const reveals = ordered.filter(
|
||||
(e) => isClimbTieBreakRevealPayload(e.payload) && e.payload.planId === planId,
|
||||
);
|
||||
if (reveals.length === 0) return false;
|
||||
|
||||
for (const revealEntry of reveals) {
|
||||
const revealPayload = revealEntry.payload as ClimbTieBreakRevealPayload;
|
||||
const commitEntry = commits.find(
|
||||
(c) => (c.payload as ClimbTieBreakCommitPayload).drawId === revealPayload.drawId,
|
||||
);
|
||||
if (!commitEntry) return false;
|
||||
// The commit must have been published strictly BEFORE its reveal.
|
||||
if (commitEntry.lamportTs >= revealEntry.lamportTs) return false;
|
||||
const commitPayload = commitEntry.payload as ClimbTieBreakCommitPayload;
|
||||
const hashOk = await verify(commitPayload.commitHash, revealPayload.seed, revealPayload.salt);
|
||||
if (!hashOk) return false;
|
||||
// The recorded winner must be reproducible from the revealed seed alone.
|
||||
const recomputed = await drawOutcome(revealPayload.seed, revealPayload.optionCount);
|
||||
if (recomputed !== revealPayload.chosenIndex) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -114,3 +114,10 @@
|
||||
line-height: 1.4;
|
||||
color: var(--color-ink-faint);
|
||||
}
|
||||
|
||||
.fieldError {
|
||||
margin: 0;
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.4;
|
||||
color: var(--color-negative);
|
||||
}
|
||||
@@ -55,6 +55,35 @@ export function ScheduleInputForm({
|
||||
const [capacityPeriod, setCapacityPeriod] = useState("");
|
||||
const [capacityValue, setCapacityValue] = useState("");
|
||||
|
||||
// Inline validation state: a single typo must show a field-level error here
|
||||
// rather than feeding an invalid value to the engine and blanking the whole
|
||||
// schedule with a raw RangeError. The horizon is validated as the user types
|
||||
// (it drives the engine immediately); the shaft/demand/capacity rows are
|
||||
// validated on "Add" (the same rules `validateScheduleInput` enforces).
|
||||
// While the typed horizon is a valid integer the box simply mirrors the
|
||||
// committed `horizonPeriods` prop (so a plan replayed in on mount shows its
|
||||
// horizon with no sync effect); an invalid keystroke is held in `horizonDraft`
|
||||
// alongside a field error instead of being pushed to the engine.
|
||||
const [horizonDraft, setHorizonDraft] = useState<string | null>(null);
|
||||
const [horizonError, setHorizonError] = useState<string>();
|
||||
const [shaftError, setShaftError] = useState<string>();
|
||||
const [demandError, setDemandError] = useState<string>();
|
||||
const [capacityError, setCapacityError] = useState<string>();
|
||||
|
||||
const horizonValue = horizonDraft ?? String(horizonPeriods);
|
||||
|
||||
function handleHorizonChange(raw: string) {
|
||||
const parsed = Number(raw);
|
||||
if (raw.trim() === "" || !Number.isInteger(parsed) || parsed < 1) {
|
||||
setHorizonDraft(raw);
|
||||
setHorizonError("Horizon must be a whole number of 1 or more.");
|
||||
return;
|
||||
}
|
||||
setHorizonError(undefined);
|
||||
setHorizonDraft(null);
|
||||
onHorizonPeriodsChange(parsed);
|
||||
}
|
||||
|
||||
const canAddShaft = shaftId !== "" && shaftFrom !== "" && shaftTo !== "" && shaftCapacity !== "" && shaftTravel !== "";
|
||||
const canAddDemand = demandId !== "" && demandSector !== "" && demandReadyPeriod !== "" && demandCount !== "";
|
||||
const canAddCapacity = capacityPeriod !== "" && capacityValue !== "";
|
||||
@@ -62,12 +91,23 @@ export function ScheduleInputForm({
|
||||
function handleAddShaft(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!canAddShaft) return;
|
||||
const capacityPerPeriod = Number(shaftCapacity);
|
||||
const travelPeriods = Number(shaftTravel);
|
||||
if (!Number.isFinite(capacityPerPeriod) || capacityPerPeriod <= 0) {
|
||||
setShaftError("Capacity/period must be a number greater than 0.");
|
||||
return;
|
||||
}
|
||||
if (!Number.isInteger(travelPeriods) || travelPeriods < 1) {
|
||||
setShaftError("Travel periods must be a whole number of 1 or more.");
|
||||
return;
|
||||
}
|
||||
setShaftError(undefined);
|
||||
onAddShaft({
|
||||
id: shaftId,
|
||||
from: shaftFrom,
|
||||
to: shaftTo,
|
||||
capacityPerPeriod: Number(shaftCapacity),
|
||||
travelPeriods: Number(shaftTravel),
|
||||
capacityPerPeriod,
|
||||
travelPeriods,
|
||||
});
|
||||
setShaftId("");
|
||||
setShaftFrom("");
|
||||
@@ -79,11 +119,24 @@ export function ScheduleInputForm({
|
||||
function handleAddDemand(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!canAddDemand) return;
|
||||
const readyPeriod = Number(demandReadyPeriod);
|
||||
const count = Number(demandCount);
|
||||
if (!Number.isInteger(readyPeriod) || readyPeriod < 0 || readyPeriod >= horizonPeriods) {
|
||||
setDemandError(
|
||||
`Ready period must be a whole number between 0 and ${horizonPeriods - 1} (within the modeled horizon).`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!Number.isFinite(count) || count <= 0) {
|
||||
setDemandError("Count must be a number greater than 0.");
|
||||
return;
|
||||
}
|
||||
setDemandError(undefined);
|
||||
onAddDemand({
|
||||
id: demandId,
|
||||
sectorId: demandSector,
|
||||
readyPeriod: Number(demandReadyPeriod),
|
||||
count: Number(demandCount),
|
||||
readyPeriod,
|
||||
count,
|
||||
});
|
||||
setDemandId("");
|
||||
setDemandSector("");
|
||||
@@ -94,7 +147,20 @@ export function ScheduleInputForm({
|
||||
function handleAddCapacity(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!canAddCapacity) return;
|
||||
onAddSurfaceCapacity({ period: Number(capacityPeriod), capacity: Number(capacityValue) });
|
||||
const period = Number(capacityPeriod);
|
||||
const capacity = Number(capacityValue);
|
||||
if (!Number.isInteger(period) || period < 0 || period >= horizonPeriods) {
|
||||
setCapacityError(
|
||||
`Period must be a whole number between 0 and ${horizonPeriods - 1} (within the modeled horizon).`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!Number.isFinite(capacity) || capacity <= 0) {
|
||||
setCapacityError("Capacity must be a number greater than 0.");
|
||||
return;
|
||||
}
|
||||
setCapacityError(undefined);
|
||||
onAddSurfaceCapacity({ period, capacity });
|
||||
setCapacityPeriod("");
|
||||
setCapacityValue("");
|
||||
}
|
||||
@@ -109,9 +175,15 @@ export function ScheduleInputForm({
|
||||
<input
|
||||
type="number"
|
||||
data-testid="theclimb-horizon-periods"
|
||||
value={horizonPeriods}
|
||||
onChange={(event) => onHorizonPeriodsChange(Number(event.target.value))}
|
||||
value={horizonValue}
|
||||
aria-invalid={horizonError !== undefined}
|
||||
onChange={(event) => handleHorizonChange(event.target.value)}
|
||||
/>
|
||||
{horizonError !== undefined && (
|
||||
<p className={styles.fieldError} data-testid="theclimb-horizon-error" role="alert">
|
||||
{horizonError}
|
||||
</p>
|
||||
)}
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<span>Surface node id</span>
|
||||
@@ -161,6 +233,11 @@ export function ScheduleInputForm({
|
||||
Add
|
||||
</button>
|
||||
</form>
|
||||
{shaftError !== undefined && (
|
||||
<p className={styles.fieldError} data-testid="theclimb-shaft-error" role="alert">
|
||||
{shaftError}
|
||||
</p>
|
||||
)}
|
||||
{shafts.length === 0 ? (
|
||||
<p className={styles.emptyState} data-testid="theclimb-shafts-empty">
|
||||
No shafts entered yet. Add at least one shaft to model the return journey.
|
||||
@@ -226,6 +303,11 @@ export function ScheduleInputForm({
|
||||
Add
|
||||
</button>
|
||||
</form>
|
||||
{demandError !== undefined && (
|
||||
<p className={styles.fieldError} data-testid="theclimb-demand-error" role="alert">
|
||||
{demandError}
|
||||
</p>
|
||||
)}
|
||||
{demands.length === 0 ? (
|
||||
<p className={styles.emptyState} data-testid="theclimb-demands-empty">
|
||||
No wave demand entered yet. Add at least one wave to schedule.
|
||||
@@ -281,6 +363,11 @@ export function ScheduleInputForm({
|
||||
Add
|
||||
</button>
|
||||
</form>
|
||||
{capacityError !== undefined && (
|
||||
<p className={styles.fieldError} data-testid="theclimb-capacity-error" role="alert">
|
||||
{capacityError}
|
||||
</p>
|
||||
)}
|
||||
{surfaceCapacity.length === 0 ? (
|
||||
<p className={styles.emptyState} data-testid="theclimb-capacity-empty">
|
||||
No surface capacity entered yet. Add at least one period's absorption limit.
|
||||
|
||||
@@ -25,3 +25,45 @@
|
||||
line-height: 1.5;
|
||||
color: var(--color-negative);
|
||||
}
|
||||
|
||||
.commitCard {
|
||||
margin: 0 1rem;
|
||||
padding: 1rem 1.25rem;
|
||||
border-radius: 16px;
|
||||
background: #ffffff;
|
||||
box-shadow: var(--shadow-card);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.commitButton {
|
||||
appearance: none;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
padding: 0.75rem 1rem;
|
||||
background: var(--color-brand, #1677ff);
|
||||
color: #ffffff;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.commitButton:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.commitStatus {
|
||||
margin: 0;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.45;
|
||||
color: var(--color-ink-faint);
|
||||
}
|
||||
|
||||
.commitError {
|
||||
margin: 0;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.45;
|
||||
color: var(--color-negative);
|
||||
}
|
||||
@@ -2,14 +2,38 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { db } from "../../lib/db.ts";
|
||||
import { readAll } from "../../lib/eventlog.ts";
|
||||
import { init } from "../../lib/identity.ts";
|
||||
import { isClimbPlanCommitPayload, recordClimbPlan, type ScheduleInput } from "../../lib/theclimb.ts";
|
||||
import { TheClimbScreen } from "./TheClimbScreen.tsx";
|
||||
|
||||
beforeEach(async () => {
|
||||
indexedDB.deleteDatabase(db.name);
|
||||
db.close();
|
||||
await db.open();
|
||||
await init();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
// Surface capacity exists only at period 2 (no period-1 entry), so the shaft's
|
||||
// only feasible departure is period 1 - forced by feasibility, not a tie, so
|
||||
// the schedule is deterministic regardless of the tie-break path.
|
||||
function deterministicPlan(): ScheduleInput {
|
||||
return {
|
||||
horizonPeriods: 6,
|
||||
surfaceNodeId: "Surface",
|
||||
shafts: [{ id: "shaft1", from: "SectorA", to: "Surface", capacityPerPeriod: 10, travelPeriods: 1 }],
|
||||
demands: [{ id: "wave1", sectorId: "SectorA", readyPeriod: 0, count: 5 }],
|
||||
surfaceCapacity: [{ period: 2, capacity: 10 }],
|
||||
};
|
||||
}
|
||||
|
||||
describe("TheClimbScreen (QA failure path - no schedule data entered)", () => {
|
||||
it("renders the honest no-schedule-yet empty state rather than a fabricated/placeholder schedule", () => {
|
||||
render(<TheClimbScreen />);
|
||||
@@ -68,6 +92,81 @@ describe("TheClimbScreen (QA happy path - entered wave/shaft/capacity data produ
|
||||
});
|
||||
});
|
||||
|
||||
describe("TheClimbScreen Event Log persistence (plan: committed plan survives reload)", () => {
|
||||
it("rebuilds the schedule from a committed plan replayed off the signed log on mount", async () => {
|
||||
await recordClimbPlan(deterministicPlan());
|
||||
|
||||
render(<TheClimbScreen />);
|
||||
|
||||
// No typing: the inputs + schedule come purely from the replayed log.
|
||||
expect(await screen.findByTestId("theclimb-total-delivered")).toHaveTextContent("5");
|
||||
expect(screen.getByTestId("theclimb-timeline-table")).toHaveTextContent("shaft1");
|
||||
expect(screen.getByTestId("theclimb-shafts")).toHaveTextContent("shaft1");
|
||||
expect(screen.getByTestId("theclimb-commit-status")).toHaveTextContent(/committed/i);
|
||||
expect(screen.queryByTestId("theclimb-no-schedule-yet")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("commits the entered plan to the signed log when the resident commits it", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<TheClimbScreen />);
|
||||
|
||||
await user.type(screen.getByTestId("theclimb-shaft-id"), "shaft1");
|
||||
await user.type(screen.getByTestId("theclimb-shaft-from"), "SectorA");
|
||||
await user.type(screen.getByTestId("theclimb-shaft-to"), "Surface");
|
||||
await user.type(screen.getByTestId("theclimb-shaft-capacity"), "10");
|
||||
await user.type(screen.getByTestId("theclimb-shaft-travel"), "1");
|
||||
await user.click(screen.getByTestId("theclimb-shaft-add"));
|
||||
|
||||
await user.type(screen.getByTestId("theclimb-demand-id"), "wave1");
|
||||
await user.type(screen.getByTestId("theclimb-demand-sector"), "SectorA");
|
||||
await user.type(screen.getByTestId("theclimb-demand-ready-period"), "0");
|
||||
await user.type(screen.getByTestId("theclimb-demand-count"), "5");
|
||||
await user.click(screen.getByTestId("theclimb-demand-add"));
|
||||
|
||||
await user.type(screen.getByTestId("theclimb-capacity-period"), "2");
|
||||
await user.type(screen.getByTestId("theclimb-capacity-value"), "10");
|
||||
await user.click(screen.getByTestId("theclimb-capacity-add"));
|
||||
|
||||
await screen.findByTestId("theclimb-commit-plan");
|
||||
await user.click(screen.getByTestId("theclimb-commit-plan"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("theclimb-commit-status")).toHaveTextContent(/committed/i);
|
||||
});
|
||||
const commits = (await readAll()).filter((e) => isClimbPlanCommitPayload(e.payload));
|
||||
expect(commits).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("TheClimbScreen inline input validation (a typo shows a field error, never a blank schedule)", () => {
|
||||
it("shows a field error for an out-of-range demand ready period and does not add the demand", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<TheClimbScreen />);
|
||||
|
||||
await user.type(screen.getByTestId("theclimb-demand-id"), "wave1");
|
||||
await user.type(screen.getByTestId("theclimb-demand-sector"), "SectorA");
|
||||
await user.type(screen.getByTestId("theclimb-demand-ready-period"), "99");
|
||||
await user.type(screen.getByTestId("theclimb-demand-count"), "5");
|
||||
await user.click(screen.getByTestId("theclimb-demand-add"));
|
||||
|
||||
expect(screen.getByTestId("theclimb-demand-error")).toHaveTextContent(/within the modeled horizon/i);
|
||||
expect(screen.getByTestId("theclimb-demands-empty")).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("theclimb-demands")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a field error for a non-positive horizon instead of blanking the schedule with a raw engine throw", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<TheClimbScreen />);
|
||||
|
||||
const horizon = screen.getByTestId("theclimb-horizon-periods");
|
||||
await user.clear(horizon);
|
||||
await user.type(horizon, "0");
|
||||
|
||||
expect(screen.getByTestId("theclimb-horizon-error")).toHaveTextContent(/whole number of 1 or more/i);
|
||||
expect(screen.queryByTestId("theclimb-error")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("TheClimbScreen backend sync wiring (plan todo 3, mount-time pull only - no write path exists)", () => {
|
||||
it("calls trySyncWithBackend() on mount, without altering the honest no-schedule-yet render", async () => {
|
||||
const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED"));
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { computeWaveSchedule, type ScheduleInput, type ShaftEdge, type SurfaceCapacityPeriod, type WaveDemandGroup, type WaveSchedule } from "../../lib/theclimb.ts";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
computeWaveSchedule,
|
||||
recordClimbPlan,
|
||||
reconstructLatestClimbPlan,
|
||||
type ScheduleInput,
|
||||
type ShaftEdge,
|
||||
type SurfaceCapacityPeriod,
|
||||
type WaveDemandGroup,
|
||||
type WaveSchedule,
|
||||
} from "../../lib/theclimb.ts";
|
||||
import { simulateCongestion, type CongestionTimeline } from "../../lib/theclimbCongestion.ts";
|
||||
import { readAll } from "../../lib/eventlog.ts";
|
||||
import { trySyncWithBackend } from "../../lib/sync.ts";
|
||||
import { CongestionHeatmap } from "./CongestionHeatmap.tsx";
|
||||
import { ScheduleInputForm } from "./ScheduleInputForm.tsx";
|
||||
@@ -13,6 +23,26 @@ type Computation =
|
||||
| { status: "computed"; schedule: WaveSchedule; congestion: CongestionTimeline }
|
||||
| { status: "error"; message: string };
|
||||
|
||||
type CommitStatus =
|
||||
| { status: "idle" }
|
||||
| { status: "committing" }
|
||||
| { status: "error"; message: string };
|
||||
|
||||
/** A stable signature of the current plan inputs, used to tell whether what's
|
||||
* on screen still matches the plan that was last committed to the signed log
|
||||
* (so the "committed" confirmation disappears the moment the resident edits an
|
||||
* input, without being wrongly cleared when a committed plan is replayed in on
|
||||
* mount). */
|
||||
function planSignature(input: ScheduleInput): string {
|
||||
return JSON.stringify({
|
||||
horizonPeriods: input.horizonPeriods,
|
||||
surfaceNodeId: input.surfaceNodeId,
|
||||
shafts: input.shafts,
|
||||
demands: input.demands,
|
||||
surfaceCapacity: input.surfaceCapacity,
|
||||
});
|
||||
}
|
||||
|
||||
const DEFAULT_SURFACE_NODE_ID = "Surface";
|
||||
const DEFAULT_HORIZON_PERIODS = 6;
|
||||
|
||||
@@ -23,13 +53,41 @@ export function TheClimbScreen() {
|
||||
const [demands, setDemands] = useState<WaveDemandGroup[]>([]);
|
||||
const [surfaceCapacity, setSurfaceCapacity] = useState<SurfaceCapacityPeriod[]>([]);
|
||||
const [computation, setComputation] = useState<Computation>({ status: "no-schedule-yet" });
|
||||
const [commit, setCommit] = useState<CommitStatus>({ status: "idle" });
|
||||
// Signature of the plan last persisted to the signed log (via mount replay or
|
||||
// a commit), or null if nothing is committed. Compared against the current
|
||||
// inputs to decide whether the on-screen plan is the committed one.
|
||||
const [committedSignature, setCommittedSignature] = useState<string | null>(null);
|
||||
|
||||
// The Climb has no resident-facing write path into the signed Event Log
|
||||
// today (its schedule/congestion engine is pure local component state,
|
||||
// never persisted) - so this is a mount-time pull only (plan todo 3),
|
||||
// best-effort and fire-and-forget.
|
||||
const currentSignature = useMemo(
|
||||
() => planSignature({ horizonPeriods, surfaceNodeId, shafts, demands, surfaceCapacity }),
|
||||
[horizonPeriods, surfaceNodeId, shafts, demands, surfaceCapacity],
|
||||
);
|
||||
const isCommitted = committedSignature !== null && committedSignature === currentSignature;
|
||||
|
||||
// Rebuild screen state by replaying the signed Event Log on mount: the most
|
||||
// recently committed plan's inputs are loaded back into the form (the live
|
||||
// preview below then re-derives its schedule identically, since the
|
||||
// tie-break is deterministic over the committed inputs), so a committed plan
|
||||
// survives reload and shows the same return plan on any identity. The
|
||||
// best-effort cross-device sync (plan todo 3) is fired in the same mount
|
||||
// effect, fire-and-forget, never blocking this replay or the local-first log.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
const plan = reconstructLatestClimbPlan(await readAll());
|
||||
if (cancelled || !plan) return;
|
||||
setHorizonPeriods(plan.inputs.horizonPeriods);
|
||||
setSurfaceNodeId(plan.inputs.surfaceNodeId);
|
||||
setShafts(plan.inputs.shafts);
|
||||
setDemands(plan.inputs.demands);
|
||||
setSurfaceCapacity(plan.inputs.surfaceCapacity);
|
||||
setCommittedSignature(planSignature({ ...plan.inputs }));
|
||||
})();
|
||||
void trySyncWithBackend();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -65,6 +123,22 @@ export function TheClimbScreen() {
|
||||
};
|
||||
}, [horizonPeriods, surfaceNodeId, shafts, demands, surfaceCapacity]);
|
||||
|
||||
async function handleCommitPlan() {
|
||||
if (computation.status !== "computed") return;
|
||||
const input: ScheduleInput = { horizonPeriods, surfaceNodeId, shafts, demands, surfaceCapacity };
|
||||
setCommit({ status: "committing" });
|
||||
try {
|
||||
await recordClimbPlan(input);
|
||||
setCommittedSignature(planSignature(input));
|
||||
setCommit({ status: "idle" });
|
||||
} catch (error: unknown) {
|
||||
setCommit({
|
||||
status: "error",
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className={styles.screen} aria-label="The Climb">
|
||||
{computation.status === "no-schedule-yet" && (
|
||||
@@ -90,6 +164,30 @@ export function TheClimbScreen() {
|
||||
<>
|
||||
<ScheduleTimeline schedule={computation.schedule} />
|
||||
<CongestionHeatmap congestion={computation.congestion} horizonPeriods={horizonPeriods} />
|
||||
<div className={styles.commitCard} data-testid="theclimb-commit-card">
|
||||
<button
|
||||
type="button"
|
||||
className={styles.commitButton}
|
||||
data-testid="theclimb-commit-plan"
|
||||
disabled={commit.status === "committing"}
|
||||
onClick={() => {
|
||||
void handleCommitPlan();
|
||||
}}
|
||||
>
|
||||
{commit.status === "committing" ? "Committing..." : "Commit return plan to the shared log"}
|
||||
</button>
|
||||
{commit.status !== "error" && isCommitted && (
|
||||
<p className={styles.commitStatus} data-testid="theclimb-commit-status" role="status">
|
||||
Return plan committed to the shared signed log - it will survive reload and show the
|
||||
same plan to every resident.
|
||||
</p>
|
||||
)}
|
||||
{commit.status === "error" && (
|
||||
<p className={styles.commitError} data-testid="theclimb-commit-status" role="status">
|
||||
{commit.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
Reference in new issue
Block a user