/** * Pure validation + event-shape logic for the admin manual-entry seed panel * (plan todo 8). This module never touches IndexedDB or the Event Log * itself - it only decides whether a form submission is well-formed and, if * so, what `seed.*` payload should be handed to `eventlog.append()`. * * Per draft decision D11: seed data is starting configuration only * (population counts, resource pools, baseline historical readings), never * outcome/result data. There is intentionally no "category" here for a * final/outcome metric. */ import type { MiniappManifest } from "../lib/miniappManifest"; import type { ProposalRecord, RosterEntry } from "../lib/assembly"; import type { HousingPreference, HousingSlot, SolveHousingInput } from "../lib/housing"; import type { HazardReportInput } from "../lib/tunnelsafety"; import type { PlantingPlot, CropMaturityWindow, TemperatureEntry } from "../lib/farms"; export const RESOURCE_TYPES = ["power", "water", "food", "cooling"] as const; export type ResourceType = (typeof RESOURCE_TYPES)[number]; export type SeedCategory = "population" | "resource" | "baseline"; /** Raw, unvalidated values straight off the admin form. */ export interface SeedFormInput { category: SeedCategory; /** Used when category === "population". */ populationCount?: string; /** Used when category === "resource". */ resource?: string; resourceAmount?: string; /** Used when category === "baseline". */ baselineChannel?: string; baselineValue?: string; } export type SeedPayload = | { type: "seed.population"; value: number } | { type: `seed.resource.${ResourceType}`; resource: ResourceType; value: number } | { type: "seed.baseline"; channel: string; value: number }; export type SeedValidationResult = | { valid: true; payload: SeedPayload } | { valid: false; error: string }; /** A single baseline reading inside the bundled demo fixture. */ export interface DemoFixtureBaselineReading { channel: string; value: number; } /** * Shape of the bundled demo-seed fixture (plan todo 9): starting * configuration only - population, resource pools, baseline readings - * never outcome/result data, matching the same D11 constraint that governs * manual seed entry above. */ export interface DemoFixture { population: number; resources: Record; baselines: DemoFixtureBaselineReading[]; } /** * The bundled "Hollow demo" fixture: a single honest, non-fabricated * starting configuration so a cold visitor never lands on an empty app. * These are plausible starting numbers for a small settlement, not a claim * about any real outcome. */ export const HOLLOW_DEMO_FIXTURE: DemoFixture = { population: 4200, resources: { power: 850, water: 620, food: 410, cooling: 300, }, baselines: [ { channel: "water-ph", value: 7.1 }, { channel: "grid-frequency-hz", value: 59.98 }, { channel: "ambient-temp-c", value: 21.4 }, ], }; /** * Plausible baseline demand (a non-negative linear utility weight per * `src/lib/fairshare.ts`'s CEEI engine) for whichever identity clicks * "Load Hollow demo". Every resource gets the same modest weight - these * numbers say nothing about any real agent's actual need, only that the * demo-loading identity participates in the market for all four resources * instead of a cold visitor seeing an allocation engine with zero * registered agents (and therefore empty allocation bars) right after * loading the bundled demo. */ export const HOLLOW_DEMO_NEEDS: Record = { power: 10, water: 10, food: 10, cooling: 10, }; /** One `fairshare.need` payload (plan todo 14's engine input), built the * same way `buildDemoFixturePayloads` builds `seed.*` payloads - data only, * no Event Log access. */ export interface DemoNeedPayload { type: "fairshare.need"; agent: string; resource: ResourceType; value: number; } /** * Build one `fairshare.need` payload per resource for `agent` (the * demo-loading identity's own account id), so loading the bundled demo * seed also registers that identity as a real participant in the fairshare * engine - without this, `computeFairshareAllocation` sees zero agents and * every allocation bar stays at "no allocation yet" even though the * resource pools are seeded. */ export function buildDemoNeedPayloads( agent: string, needs: Record = HOLLOW_DEMO_NEEDS, ): DemoNeedPayload[] { return RESOURCE_TYPES.map((resource) => ({ type: "fairshare.need", agent, resource, value: needs[resource], })); } /** * Starting wallet balance + a couple of transactions for the Hollow demo * fixture (plan todo 13): a modest one-time welcome grant for the * demo-loading identity, plus a small symbolic contribution to a shared * "commons fund" account - so the wallet card is never "0 / No * transactions yet" cold. Same D11 reasoning as `HOLLOW_DEMO_FIXTURE` * above: this is starting configuration, not a claim about any real * resolved civic action (a real resolved action - winning Fair Draw - is * wired separately in `src/miniapps/fairdraw/RevealDraw.tsx`). */ export const HOLLOW_DEMO_WALLET_WELCOME_GRANT = 50; export const HOLLOW_DEMO_WALLET_COMMONS_CONTRIBUTION = 10; export const HOLLOW_DEMO_COMMONS_FUND_ACCOUNT = "hollow-commons-fund"; /** One `wallet.issue`/`wallet.transfer` payload (plan todo 13's starting * balance), built the same way `buildDemoNeedPayloads` builds * `fairshare.need` payloads - data only, no Event Log access. */ export type DemoWalletPayload = | { type: "wallet.issue"; account: string; amount: number } | { type: "wallet.transfer"; from: string; to: string; amount: number }; /** * Build the demo-loading identity's starting wallet.issue grant plus one * wallet.transfer contribution to the shared commons fund, in that order, * so the wallet card shows a real non-zero balance and two real * transaction-history rows the moment the demo loads. */ export function buildDemoWalletPayloads(agent: string): DemoWalletPayload[] { return [ { type: "wallet.issue", account: agent, amount: HOLLOW_DEMO_WALLET_WELCOME_GRANT }, { type: "wallet.transfer", from: agent, to: HOLLOW_DEMO_COMMONS_FUND_ACCOUNT, amount: HOLLOW_DEMO_WALLET_COMMONS_CONTRIBUTION, }, ]; } /** * Marker payload appended once a demo fixture has been loaded, so a second * click can detect the fixture is already present and skip re-appending it * (idempotency) instead of duplicating events. */ export interface DemoFixtureMarkerPayload { type: "seed.demo.loaded"; fixtureId: string; } export const DEMO_FIXTURE_MARKER: DemoFixtureMarkerPayload = { type: "seed.demo.loaded", fixtureId: "hollow-demo-v1", }; /** * One minimal, genuinely-working sample mini-app package bundled into the * Hollow demo (plan todo 10, Wave 2 upload visibility): installed alongside * the rest of the demo fixture via the real `uploadMiniapp()` storage path * (same validation, same zero-isolation mount path, unchanged), so the * installed-tile + share-QR + mount pipeline is visible cold without * requiring a judge to use the new upload form first. It genuinely reads * the real wallet balance and genuinely appends/reads real signed events * through `window.commons` - not a static placeholder. */ export const DEMO_SAMPLE_MINIAPP_MANIFEST: MiniappManifest = { name: "Hollow Welcome", icon: "\uD83D\uDC4B", entryPoint: "index.html", permissions: ["ledger.read", "eventlog.read", "eventlog.write"], }; export const DEMO_SAMPLE_MINIAPP_HTML = `

Welcome to the Hollow

Your wallet balance: loading\u2026

Greetings sent so far: 0

`; /** * Small, provably-feasible housing-cycle input for the Hollow demo fixture * (plan todo 15): the demo-loading identity plus two symbolic neighbor * residents, one slot each, scored the same identity-matrix way * `src/lib/housing.test.ts` already exercises (resident `i` scores their * own slot `i` highest) so the optimal/feasible solve is hand-checkable - * never a fabricated "everyone wins" shortcut. Built the same way * `buildDemoNeedPayloads`/`buildDemoWalletPayloads` build their payloads: * data only, no Event Log/solver access here. */ export const HOLLOW_DEMO_HOUSING_SLOTS: HousingSlot[] = [ { id: "hollow-housing-slot-1", capacity: 1 }, { id: "hollow-housing-slot-2", capacity: 1 }, { id: "hollow-housing-slot-3", capacity: 1 }, ]; export const HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS = [ "hollow-housing-demo-resident-b", "hollow-housing-demo-resident-c", ]; /** * Builds `recordHousingAssignmentCycle`'s input for the demo-loading * identity (`agent`) plus the fixed demo neighbor residents above - the * caller (`AdminSeedPanel.handleLoadDemo`, or the standalone admin-panel * housing-cycle trigger) is expected to pass this straight to * `recordHousingAssignmentCycle()` from `src/lib/housing.ts`. */ export function buildDemoHousingCycleInput( agent: string, ): Omit { const residents = [agent, ...HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS]; const slots = HOLLOW_DEMO_HOUSING_SLOTS; const preferences: HousingPreference[] = []; for (let i = 0; i < residents.length; i++) { for (let j = 0; j < slots.length; j++) { preferences.push({ residentId: residents[i], slotId: slots[j].id, score: i === j ? 10 : 1, }); } } return { residents, slots, preferences }; } /** * One `seed.skillHolder` payload per seeded skill, built the same * data-only way as `buildDemoNeedPayloads`/`buildDemoWalletPayloads` above - * the real payload shape `src/lib/mentor.ts`'s `buildSkillHolderDataSource` * consumes (plan todo 15/47). Values mirror the exact fixture * `MentorScreen.test.tsx` already exercises: `well-repair` (2 real * dependents in `MENTOR_SKILL_GRAPH`, held by only 1 resident) crosses the * at-risk threshold, `electrician` (well-held at 6) does not - so the demo * fixture shows at least one real at-risk skill cold without fabricating a * holder count for every skill in the graph. */ export interface DemoSkillHolderPayload { type: "seed.skillHolder"; skillId: string; holderCount: number; } export const HOLLOW_DEMO_SKILL_HOLDERS: ReadonlyArray<{ skillId: string; holderCount: number }> = [ { skillId: "well-repair", holderCount: 1 }, { skillId: "electrician", holderCount: 6 }, ]; export function buildDemoSkillHolderPayloads(): DemoSkillHolderPayload[] { return HOLLOW_DEMO_SKILL_HOLDERS.map(({ skillId, holderCount }) => ({ type: "seed.skillHolder", skillId, holderCount, })); } /** * One real hazard report for the Hollow demo fixture, appended through the * same real `reportHazard()` path `ReportHazardForm` uses - so Tunnel * Safety's map shows a genuinely closed segment and a genuinely rerouted * path cold, instead of the default no-hazards state. */ export const HOLLOW_DEMO_HAZARD_REPORT: HazardReportInput = { segmentId: "seg-market-bypass", status: "flooded", }; /** * A small, provably-feasible Farms planting input for the Hollow demo * fixture: five real entered daily temperature readings (mean 20C against * a 10C base = 10 GDD/day, 50 cumulative) feeding one plot and one crop * whose maturity requirement (40 GDD) is reachable within that budget, so * `solveFarmsPlantingOptimizer` reaches a genuine "optimal" schedule - * never a fabricated forecast number. */ export const HOLLOW_DEMO_FARMS_BASE_TEMP_C = 10; export const HOLLOW_DEMO_FARMS_TEMPERATURES: TemperatureEntry[] = [ { date: "2026-05-01", tmin: 15, tmax: 25 }, { date: "2026-05-02", tmin: 15, tmax: 25 }, { date: "2026-05-03", tmin: 15, tmax: 25 }, { date: "2026-05-04", tmin: 15, tmax: 25 }, { date: "2026-05-05", tmin: 15, tmax: 25 }, ]; export const HOLLOW_DEMO_FARMS_PLOTS: PlantingPlot[] = [{ plotId: "plot-1", areaM2: 10 }]; export const HOLLOW_DEMO_FARMS_CROPS: CropMaturityWindow[] = [ { cropId: "lamp-greens", maturityGdd: 40, yieldKgPerM2: 2, kWhPerM2: 1 }, ]; /** * One real Mentor skill review for the Hollow demo fixture, appended * through the same real `postSkillReview()` path `MentorScreen` uses - so * the well-repair skill (already seeded as at-risk above) shows a genuine * review history/next-due-date instead of "No review history yet". */ export const HOLLOW_DEMO_MENTOR_REVIEW_SKILL_ID = "well-repair"; /** * The bundled "Hollow demo" fixture's starting Assembly roster (plan todo * 12): two plausible founding residents, matching the same D11 "starting * configuration only" rule as `HOLLOW_DEMO_FIXTURE` above - never a claim * about any real resident. Assembly persists through its own Yjs CRDT * document (`src/lib/assembly.ts`), not the Event Log, so these are * written via the real, unchanged `putRosterEntry()` directly rather than * as `seed.*` Event Log payloads - see `AdminSeedPanel.tsx`'s * `handleLoadDemo`. */ export const HOLLOW_DEMO_ROSTER: RosterEntry[] = [ { id: "hollow-founding-resident-aria", residentId: "hollow-founding-resident-aria", displayName: "Aria (founding resident)", joinedAt: 0, active: true, }, { id: "hollow-founding-resident-kade", residentId: "hollow-founding-resident-kade", displayName: "Kade (founding resident)", joinedAt: 0, active: true, }, ]; /** * The bundled "Hollow demo" fixture's starting open proposal (plan todo * 12), authored by the first `HOLLOW_DEMO_ROSTER` entry, so Assembly is * never empty cold - written via the real, unchanged `putProposal()` * directly, same reasoning as `HOLLOW_DEMO_ROSTER` above. */ export const HOLLOW_DEMO_PROPOSAL: ProposalRecord = { id: "hollow-demo-proposal-well-pump", title: "Repair the shared well pump", description: "The well pump has been making noise for a week and needs servicing before it fails.", authorId: HOLLOW_DEMO_ROSTER[0].id, createdAt: 0, status: "open", }; /** * Real starting votes on the bundled demo proposal, cast by the same two * founding residents `HOLLOW_DEMO_ROSTER` seeds - written through the real, * unchanged `castVote()` directly onto the Assembly CRDT doc (same reasoning * as `HOLLOW_DEMO_ROSTER`/`HOLLOW_DEMO_PROPOSAL` above: Assembly has no * Event Log write path of its own), so the seeded proposal shows a genuine, * non-zero tally cold instead of "No vote cast yet" for every resident. */ export const HOLLOW_DEMO_VOTES: ReadonlyArray<{ voterId: string; choice: "yes" | "no" | "abstain" }> = [ { voterId: HOLLOW_DEMO_ROSTER[0].id, choice: "yes" }, { voterId: HOLLOW_DEMO_ROSTER[1].id, choice: "yes" }, ]; /** * Build the exact `seed.*` payloads for a demo fixture, in the same shape * `validateSeedInput` produces for manual entries. The caller is expected * to append each payload (plus `DEMO_FIXTURE_MARKER`) through the same * `eventlog.append()` path manual entries use - this function only builds * data, it never touches the Event Log. */ export function buildDemoFixturePayloads( fixture: DemoFixture = HOLLOW_DEMO_FIXTURE, ): SeedPayload[] { const payloads: SeedPayload[] = [ { type: "seed.population", value: fixture.population }, ]; for (const resource of RESOURCE_TYPES) { payloads.push({ type: `seed.resource.${resource}`, resource, value: fixture.resources[resource], }); } for (const baseline of fixture.baselines) { payloads.push({ type: "seed.baseline", channel: baseline.channel, value: baseline.value, }); } return payloads; } /** * Whether `DEMO_FIXTURE_MARKER` (or a given marker) is already present * among `entries`' payloads - used to make "Load Hollow demo" idempotent: * a second click must not duplicate the fixture's events. */ export function hasDemoFixtureBeenLoaded( entries: ReadonlyArray<{ payload: unknown }>, marker: Pick = DEMO_FIXTURE_MARKER, ): boolean { return entries.some((entry) => { const payload = entry.payload; return ( typeof payload === "object" && payload !== null && (payload as { type?: unknown }).type === marker.type && (payload as { fixtureId?: unknown }).fixtureId === marker.fixtureId ); }); } function parseFiniteNumber(raw: string | undefined): number | null { if (raw === undefined || raw.trim() === "") return null; const n = Number(raw); return Number.isFinite(n) ? n : null; } /** * Validate a raw form submission and, if valid, build the exact `seed.*` * payload that should be signed and appended to the Event Log. Rejects * malformed/incomplete input with a human-readable error and builds no * payload - the caller must never append on a `valid: false` result. */ export function validateSeedInput(input: SeedFormInput): SeedValidationResult { switch (input.category) { case "population": { const count = parseFiniteNumber(input.populationCount); if (count === null) { return { valid: false, error: "Population count is required and must be a number." }; } if (!Number.isInteger(count) || count <= 0) { return { valid: false, error: "Population count must be a positive whole number.", }; } return { valid: true, payload: { type: "seed.population", value: count } }; } case "resource": { const resource = input.resource as ResourceType | undefined; if (!resource || !RESOURCE_TYPES.includes(resource)) { return { valid: false, error: `Resource must be one of: ${RESOURCE_TYPES.join(", ")}.`, }; } const amount = parseFiniteNumber(input.resourceAmount); if (amount === null) { return { valid: false, error: "Resource pool amount is required and must be a number." }; } if (amount < 0) { return { valid: false, error: "Resource pool amount cannot be negative." }; } return { valid: true, payload: { type: `seed.resource.${resource}`, resource, value: amount }, }; } case "baseline": { const channel = input.baselineChannel?.trim(); if (!channel) { return { valid: false, error: "Baseline channel name is required." }; } const value = parseFiniteNumber(input.baselineValue); if (value === null) { return { valid: false, error: "Baseline reading value is required and must be a number." }; } return { valid: true, payload: { type: "seed.baseline", channel, value } }; } default: return { valid: false, error: "Unknown seed category." }; } }