Files
patriothacks/src/admin/AdminSeedPanel.test.tsx
T
OmO Orchestrator b7a2c5bb6e fix(seed): demo the fixed Assembly/Housing/Tunnel/Mentor behavior via the real signed-log path
The demo seed predated the recent fixes: Assembly tally showed 0.00 (dead castVote path removed), Housing never rotated fairness-debt (identity-matrix prefs), Tunnel never corroborated (one signer), Mentor had no reachable match. Now: founding residents are enrolled with putResidentCredit + cast real signed QV ballots (yes 6.00); the demo identity and a neighbour contest one single-capacity slot so debt accrues then flips; a genuinely foreign-signed corroborating hazard (appendEntry, re-verified) makes seg-market-bypass Confirmed by 2; the local identity is a still-learning apprentice and a foreign-signed mentor Good review yields one real match. Fixture bumped to hollow-demo-v2.
2026-11-20 04:06:07 -05:00

429 lines
18 KiB
TypeScript

// @vitest-environment happy-dom
import "@testing-library/jest-dom/vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { db } from "../lib/db";
import { getPublicKey, init } from "../lib/identity";
import { readAll } from "../lib/eventlog";
import { listProposals, listRoster } from "../lib/assembly";
import {
computeQvTally,
listDelegations,
listResidentCredits,
} from "../lib/governance";
import { extractQvBallots } from "../lib/governanceEvents";
import { computeHazardReports, computeSegmentCorroboration } from "../lib/tunnelsafety";
import {
buildSkillHolderDataSource,
computeSkillCriticality,
rankAtRiskSkills,
} from "../lib/mentor";
import {
buildApprenticeNeedsFromReviews,
buildMentorProfilesFromReviews,
matchApprenticesToMentors,
} from "../lib/mentorMatching";
import { MENTOR_SKILL_GRAPH } from "../miniapps/mentor/mentorEvents";
import { getAssemblyEngineForTesting } from "../miniapps/assembly/useAssemblyEngine";
import { AdminSeedPanel } from "./AdminSeedPanel";
import {
DEMO_FIXTURE_MARKER,
DEMO_SAMPLE_MINIAPP_MANIFEST,
HOLLOW_DEMO_COMMONS_FUND_ACCOUNT,
HOLLOW_DEMO_FIXTURE,
HOLLOW_DEMO_HAZARD_REPORT,
HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS,
HOLLOW_DEMO_PROPOSAL,
HOLLOW_DEMO_ROSTER,
HOLLOW_DEMO_SKILL_HOLDERS,
HOLLOW_DEMO_VOTES,
HOLLOW_DEMO_WALLET_COMMONS_CONTRIBUTION,
HOLLOW_DEMO_WALLET_WELCOME_GRANT,
RESOURCE_TYPES,
} from "./seedEvents";
import { HOUSING_ASSIGNMENT_CREDIT_AMOUNT, extractHousingCycles } from "../lib/housing";
import { toAccountId } from "../shell/accountId";
function uniqueAssemblyDbName(label: string): string {
return `admin-seed-panel-assembly-${label}-${Math.random().toString(36).slice(2)}`;
}
beforeEach(async () => {
indexedDB.deleteDatabase(db.name);
db.close();
await db.open();
await init();
});
afterEach(cleanup);
describe("AdminSeedPanel", () => {
it("appends a correctly-signed seed.population entry retrievable via readAll()", async () => {
render(<AdminSeedPanel />);
fireEvent.change(screen.getByLabelText("Population count"), {
target: { value: "500" },
});
fireEvent.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => screen.getByTestId("seed-success"));
const entries = await readAll();
expect(entries).toHaveLength(1);
expect(entries[0].payload).toEqual({ type: "seed.population", value: 500 });
expect(entries[0].authorPubkey).toEqual(await getPublicKey());
expect(entries[0].signature).toBeInstanceOf(Uint8Array);
});
it("appends a correctly-signed seed.resource.power entry retrievable via readAll()", async () => {
render(<AdminSeedPanel />);
fireEvent.change(screen.getByLabelText("Category"), {
target: { value: "resource" },
});
fireEvent.change(screen.getByLabelText("Resource"), {
target: { value: "power" },
});
fireEvent.change(screen.getByLabelText("Pool amount"), {
target: { value: "1000" },
});
fireEvent.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => screen.getByTestId("seed-success"));
const entries = await readAll();
expect(entries).toHaveLength(1);
expect(entries[0].payload).toEqual({
type: "seed.resource.power",
resource: "power",
value: 1000,
});
});
it("rejects a submission with a negative population count client-side, without persisting it", async () => {
render(<AdminSeedPanel />);
fireEvent.change(screen.getByLabelText("Population count"), {
target: { value: "-5" },
});
fireEvent.click(screen.getByRole("button", { name: "Submit" }));
const alert = await screen.findByRole("alert");
expect(alert).toHaveTextContent("Population count must be a positive whole number.");
expect(screen.queryByTestId("seed-success")).not.toBeInTheDocument();
expect(await readAll()).toHaveLength(0);
});
it("rejects a resource submission missing an amount, without persisting it", async () => {
render(<AdminSeedPanel />);
fireEvent.change(screen.getByLabelText("Category"), {
target: { value: "resource" },
});
fireEvent.change(screen.getByLabelText("Resource"), {
target: { value: "water" },
});
fireEvent.click(screen.getByRole("button", { name: "Submit" }));
const alert = await screen.findByRole("alert");
expect(alert).toHaveTextContent(
"Resource pool amount is required and must be a number.",
);
expect(await readAll()).toHaveLength(0);
});
});
describe("AdminSeedPanel - Load Hollow demo", () => {
it("happy: clicking on a fresh Event Log appends the full fixture as signed seed.* events and shows the demo-data label", async () => {
render(<AdminSeedPanel />);
expect(screen.getByTestId("demo-data-label")).toHaveTextContent("Demo data");
expect(await readAll()).toHaveLength(0);
fireEvent.click(screen.getByRole("button", { name: "Load Hollow demo" }));
await waitFor(() => screen.getByTestId("demo-load-status"));
const entries = await readAll();
const housingResidentCount = 1 + HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS.length;
// No Water Watch readings: this app has no real sensor network, so the
// demo seed deliberately leaves it at its honest "No sensor readings yet"
// empty state rather than injecting fixture data standing in for hardware
// that doesn't exist.
const expectedCount =
1 + // seed.population
Object.keys(HOLLOW_DEMO_FIXTURE.resources).length + // seed.resource.*
HOLLOW_DEMO_FIXTURE.baselines.length + // seed.baseline
RESOURCE_TYPES.length + // fairshare.need (one per resource)
2 + // wallet.issue welcome grant + wallet.transfer commons contribution
HOLLOW_DEMO_SKILL_HOLDERS.length + // seed.skillHolder
1 + // housing.assignment cycle
housingResidentCount + // one wallet.issue housing credit per housed resident
HOLLOW_DEMO_VOTES.length + // one signed governance.qvBallot per demo vote
1 + // local tunnelsafety.hazard.report
1 + // foreign-signed corroborating tunnelsafety.hazard.report
2 + // farms settlement (seed.resource.food + fairshare.allocation.cycle)
1 + // local mentor.skillReview (apprentice, still-learning)
1 + // foreign-signed mentor.skillReview (proficient mentor)
1; // seed.demo.loaded marker
expect(entries).toHaveLength(expectedCount);
const payloadTypes = entries.map((e) => (e.payload as { type: string }).type);
expect(payloadTypes).toContain("seed.population");
expect(payloadTypes).toContain(DEMO_FIXTURE_MARKER.type);
const populationEntry = entries.find(
(e) => (e.payload as { type: string }).type === "seed.population",
);
expect((populationEntry!.payload as { value: number }).value).toBe(
HOLLOW_DEMO_FIXTURE.population,
);
expect(populationEntry!.authorPubkey).toEqual(await getPublicKey());
expect(populationEntry!.signature).toBeInstanceOf(Uint8Array);
// The demo-loading identity itself is registered as a fairshare
// participant (one fairshare.need per resource, keyed to its own
// account id) so the Fair Share mini-app shows a real allocation
// instead of "no allocation yet" right after loading the demo.
const accountId = toAccountId(await getPublicKey());
const needEntries = entries.filter(
(e) => (e.payload as { type: string }).type === "fairshare.need",
);
expect(needEntries).toHaveLength(RESOURCE_TYPES.length);
for (const entry of needEntries) {
expect((entry.payload as { agent: string }).agent).toBe(accountId);
expect((entry.payload as { value: number }).value).toBeGreaterThan(0);
}
// Starting wallet balance + a couple of real signed transactions (plan
// todo 13): a welcome grant for the demo-loading identity's own
// account, then a symbolic contribution to the shared commons fund.
const walletIssueEntry = entries.find(
(e) => (e.payload as { type: string }).type === "wallet.issue",
);
const walletTransferEntry = entries.find(
(e) => (e.payload as { type: string }).type === "wallet.transfer",
);
expect(walletIssueEntry).toBeDefined();
expect((walletIssueEntry!.payload as { account: string; amount: number })).toEqual({
type: "wallet.issue",
account: accountId,
amount: HOLLOW_DEMO_WALLET_WELCOME_GRANT,
});
expect(walletTransferEntry).toBeDefined();
expect(
walletTransferEntry!.payload as { from: string; to: string; amount: number },
).toEqual({
type: "wallet.transfer",
from: accountId,
to: HOLLOW_DEMO_COMMONS_FUND_ACCOUNT,
amount: HOLLOW_DEMO_WALLET_COMMONS_CONTRIBUTION,
});
// Skill-holder-count seed data (plan todo 15) so Mentor's dependents-
// count engine sees a real holder population.
const skillHolderEntries = entries.filter(
(e) => (e.payload as { type: string }).type === "seed.skillHolder",
);
expect(skillHolderEntries).toHaveLength(HOLLOW_DEMO_SKILL_HOLDERS.length);
for (const { skillId, holderCount } of HOLLOW_DEMO_SKILL_HOLDERS) {
expect(skillHolderEntries).toContainEqual(
expect.objectContaining({ payload: { type: "seed.skillHolder", skillId, holderCount } }),
);
}
// A real housing assignment cycle ran once (plan todo 15): the
// demo-loading identity itself has a real room-slot assignment, and
// every resident in that cycle (including it) received a real
// wallet.issue credit for getting housed.
const housingCycles = extractHousingCycles(entries);
expect(housingCycles).toHaveLength(1);
expect(housingCycles[0].assignments.some((a) => a.residentId === accountId)).toBe(true);
const housingWalletCredits = entries.filter(
(e) =>
(e.payload as { type?: string }).type === "wallet.issue" &&
(e.payload as { amount?: number }).amount === HOUSING_ASSIGNMENT_CREDIT_AMOUNT,
);
expect(housingWalletCredits).toHaveLength(housingCycles[0].assignments.length);
expect(
housingWalletCredits.some(
(e) => (e.payload as { account?: string }).account === accountId,
),
).toBe(true);
// Assembly: the two demo ballots are real signed governance.qvBallot
// entries (the dead castVote CRDT path was removed), the source the live
// QV tally reads.
const qvBallots = entries.filter(
(e) => (e.payload as { type?: string }).type === "governance.qvBallot",
);
expect(qvBallots).toHaveLength(HOLLOW_DEMO_VOTES.length);
// Tunnel Safety: a SECOND, genuinely distinct identity corroborates the
// SAME segment, so it reads as crowd-confirmed by 2 distinct reporters.
const corroboration = computeSegmentCorroboration(computeHazardReports(entries));
const seg = corroboration.get(HOLLOW_DEMO_HAZARD_REPORT.segmentId);
expect(seg?.distinctReporterCount).toBe(2);
expect(seg?.corroborated).toBe(true);
// Mentor: the local apprentice need plus the seeded second-account mentor
// produce at least one real proposed apprentice->mentor match (unreachable
// when the only review was the local identity's own).
const holderSource = buildSkillHolderDataSource(entries);
const atRiskIds = new Set(
rankAtRiskSkills(computeSkillCriticality(MENTOR_SKILL_GRAPH, holderSource)).map(
(s) => s.skillId,
),
);
const mentorMatches = matchApprenticesToMentors(
buildMentorProfilesFromReviews(entries),
buildApprenticeNeedsFromReviews(entries, atRiskIds),
MENTOR_SKILL_GRAPH,
);
expect(mentorMatches.some((m) => m.status === "matched")).toBe(true);
expect(screen.getByTestId("demo-load-status")).toHaveTextContent("Demo data loaded");
// The bundled sample mini-app (plan todo 10) installs through the same
// real uploadMiniapp() storage path the new upload screen uses, so the
// installed-tile + mount pipeline is visible cold.
const packages = await db.miniappPackages.toArray();
expect(packages).toHaveLength(1);
expect(packages[0].manifest).toEqual(DEMO_SAMPLE_MINIAPP_MANIFEST);
});
it("failure: clicking Load Hollow demo twice does not duplicate events or the sample package", async () => {
render(<AdminSeedPanel />);
fireEvent.click(screen.getByRole("button", { name: "Load Hollow demo" }));
await waitFor(() => screen.getByTestId("demo-load-status"));
const countAfterFirstClick = (await readAll()).length;
expect(countAfterFirstClick).toBeGreaterThan(0);
expect(await db.miniappPackages.toArray()).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Load Hollow demo" }));
await waitFor(() =>
expect(screen.getByTestId("demo-load-status")).toHaveTextContent("already loaded"),
);
const countAfterSecondClick = (await readAll()).length;
expect(countAfterSecondClick).toBe(countAfterFirstClick);
expect(await db.miniappPackages.toArray()).toHaveLength(1);
});
it("happy: clicking Load Hollow demo seeds Assembly's starting roster + proposal via the real putRosterEntry/putProposal (plan todo 12)", async () => {
const assemblyDbName = uniqueAssemblyDbName("happy");
render(<AdminSeedPanel assemblyDbName={assemblyDbName} />);
fireEvent.click(screen.getByRole("button", { name: "Load Hollow demo" }));
await waitFor(() => screen.getByTestId("demo-load-status"));
const { assembly, governance } = getAssemblyEngineForTesting(assemblyDbName);
const roster = listRoster(assembly);
const proposals = listProposals(assembly);
expect(roster).toHaveLength(HOLLOW_DEMO_ROSTER.length);
for (const expected of HOLLOW_DEMO_ROSTER) {
expect(roster).toContainEqual(expected);
}
expect(proposals).toHaveLength(1);
expect(proposals[0]).toEqual(HOLLOW_DEMO_PROPOSAL);
// Each founding resident is enrolled with their QV credit budget - the
// membership the signed tally reads (without it every ballot weighs 0.00).
const credits = listResidentCredits(governance).filter(
(c) => c.proposalId === HOLLOW_DEMO_PROPOSAL.id,
);
expect(credits).toHaveLength(HOLLOW_DEMO_ROSTER.length);
// The two signed demo ballots produce a genuine live QV tally: two `yes`
// ballots at DEFAULT_QV_CREDITS each weigh sqrt(9)=3, so yes = 6.00.
const ballots = extractQvBallots(await readAll());
expect(ballots.filter((b) => b.proposalId === HOLLOW_DEMO_PROPOSAL.id)).toHaveLength(
HOLLOW_DEMO_VOTES.length,
);
const tally = computeQvTally({
proposalId: HOLLOW_DEMO_PROPOSAL.id,
residentCredits: listResidentCredits(governance),
ballots,
delegations: listDelegations(governance),
});
expect(tally.tally.yes).toBeCloseTo(6);
expect(tally.tally.no).toBe(0);
});
it("failure: clicking Load Hollow demo twice does not duplicate Assembly's seeded roster/proposal", async () => {
const assemblyDbName = uniqueAssemblyDbName("idempotent");
render(<AdminSeedPanel assemblyDbName={assemblyDbName} />);
fireEvent.click(screen.getByRole("button", { name: "Load Hollow demo" }));
await waitFor(() => screen.getByTestId("demo-load-status"));
fireEvent.click(screen.getByRole("button", { name: "Load Hollow demo" }));
await waitFor(() =>
expect(screen.getByTestId("demo-load-status")).toHaveTextContent("already loaded"),
);
const { assembly } = getAssemblyEngineForTesting(assemblyDbName);
expect(listRoster(assembly)).toHaveLength(HOLLOW_DEMO_ROSTER.length);
expect(listProposals(assembly)).toHaveLength(1);
});
});
describe("AdminSeedPanel - Run housing assignment cycle (standalone admin trigger, plan todo 15)", () => {
it("happy: clicking the standalone trigger on a fresh log records a feasible cycle and credits every assigned resident's wallet", async () => {
render(<AdminSeedPanel />);
expect(await readAll()).toHaveLength(0);
fireEvent.click(screen.getByRole("button", { name: "Run housing assignment cycle" }));
await waitFor(() => screen.getByTestId("housing-cycle-status"));
expect(screen.getByTestId("housing-cycle-status")).toHaveTextContent("recorded");
const entries = await readAll();
const accountId = toAccountId(await getPublicKey());
const housingCycles = extractHousingCycles(entries);
expect(housingCycles).toHaveLength(1);
expect(housingCycles[0].assignments.some((a) => a.residentId === accountId)).toBe(true);
const walletCredits = entries.filter(
(e) =>
(e.payload as { type?: string }).type === "wallet.issue" &&
(e.payload as { amount?: number }).amount === HOUSING_ASSIGNMENT_CREDIT_AMOUNT,
);
expect(walletCredits).toHaveLength(housingCycles[0].assignments.length);
expect(
walletCredits.some((e) => (e.payload as { account?: string }).account === accountId),
).toBe(true);
});
it("is not resident-facing: has its own distinct button/testid, separate from the Load Hollow demo button", async () => {
render(<AdminSeedPanel />);
expect(
screen.getByRole("button", { name: "Run housing assignment cycle" }),
).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Load Hollow demo" })).toBeInTheDocument();
});
it("re-clicking runs a SECOND cycle (not idempotent like Load Hollow demo - it is a repeatable cycle-level action)", async () => {
render(<AdminSeedPanel />);
fireEvent.click(screen.getByRole("button", { name: "Run housing assignment cycle" }));
await waitFor(() => screen.getByTestId("housing-cycle-status"));
expect(extractHousingCycles(await readAll())).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Run housing assignment cycle" }));
await waitFor(async () => {
expect(extractHousingCycles(await readAll())).toHaveLength(2);
});
const housingCycles = extractHousingCycles(await readAll());
expect(housingCycles).toHaveLength(2);
expect(new Set(housingCycles.map((c) => c.cycle)).size).toBe(2);
});
});