diff --git a/src/lib/theclimb.test.ts b/src/lib/theclimb.test.ts index d0ff0a2..b12c4af 100644 --- a/src/lib/theclimb.test.ts +++ b/src/lib/theclimb.test.ts @@ -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); + }); +}); + diff --git a/src/lib/theclimb.ts b/src/lib/theclimb.ts index 5c34a5e..9d91e14 100644 --- a/src/lib/theclimb.ts +++ b/src/lib/theclimb.ts @@ -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 { + 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; +}): 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([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([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 { const dist = new Map([[SOURCE, 0]]); const predecessors = new Map(); @@ -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 { 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 { + 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).horizonPeriods === "number" && + typeof (payload.inputs as Record).surfaceNodeId === "string" && + Array.isArray((payload.inputs as Record).shafts) && + Array.isArray((payload.inputs as Record).demands) && + Array.isArray((payload.inputs as Record).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).shaftFlows) && + Array.isArray((payload.schedule as Record).surfaceArrivals) && + Array.isArray((payload.schedule as Record).demandOutcomes) && + typeof (payload.schedule as Record).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(); + 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 { + 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 { + 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; +} diff --git a/src/miniapps/theclimb/ScheduleInputForm.module.css b/src/miniapps/theclimb/ScheduleInputForm.module.css index b35bb11..754b9de 100644 --- a/src/miniapps/theclimb/ScheduleInputForm.module.css +++ b/src/miniapps/theclimb/ScheduleInputForm.module.css @@ -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); +} diff --git a/src/miniapps/theclimb/ScheduleInputForm.tsx b/src/miniapps/theclimb/ScheduleInputForm.tsx index 4926045..d44b46e 100644 --- a/src/miniapps/theclimb/ScheduleInputForm.tsx +++ b/src/miniapps/theclimb/ScheduleInputForm.tsx @@ -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(null); + const [horizonError, setHorizonError] = useState(); + const [shaftError, setShaftError] = useState(); + const [demandError, setDemandError] = useState(); + const [capacityError, setCapacityError] = useState(); + + 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) { 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) { 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) { 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({ onHorizonPeriodsChange(Number(event.target.value))} + value={horizonValue} + aria-invalid={horizonError !== undefined} + onChange={(event) => handleHorizonChange(event.target.value)} /> + {horizonError !== undefined && ( +

+ {horizonError} +

+ )}