diff --git a/src/admin/AdminSeedPanel.test.tsx b/src/admin/AdminSeedPanel.test.tsx index 3e14184..b70af38 100644 --- a/src/admin/AdminSeedPanel.test.tsx +++ b/src/admin/AdminSeedPanel.test.tsx @@ -6,6 +6,24 @@ 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 { @@ -13,10 +31,12 @@ import { 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, @@ -127,28 +147,26 @@ describe("AdminSeedPanel - Load Hollow demo", () => { const entries = await readAll(); const housingResidentCount = 1 + HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS.length; - // population + 4 resources + 3 baselines + 4 fairshare.need + 1 wallet.issue - // + 1 wallet.transfer + skillHolder seeds + 1 housing.assignment cycle - // + 1 wallet.issue credit per housing resident + 1 marker - // + 1 tunnelsafety.hazard.report (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) - // + 2 farms settlement (seed.resource.food credit + fairshare.allocation.cycle) - // + 1 mentor.skillReview + // 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 + - Object.keys(HOLLOW_DEMO_FIXTURE.resources).length + - HOLLOW_DEMO_FIXTURE.baselines.length + - RESOURCE_TYPES.length + - 2 + - HOLLOW_DEMO_SKILL_HOLDERS.length + - 1 + - housingResidentCount + - 1 + - 1 + - 2 + - 1; + 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); @@ -235,6 +253,37 @@ describe("AdminSeedPanel - Load Hollow demo", () => { ), ).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 @@ -271,7 +320,7 @@ describe("AdminSeedPanel - Load Hollow demo", () => { fireEvent.click(screen.getByRole("button", { name: "Load Hollow demo" })); await waitFor(() => screen.getByTestId("demo-load-status")); - const { assembly } = getAssemblyEngineForTesting(assemblyDbName); + const { assembly, governance } = getAssemblyEngineForTesting(assemblyDbName); const roster = listRoster(assembly); const proposals = listProposals(assembly); @@ -281,6 +330,28 @@ describe("AdminSeedPanel - Load Hollow demo", () => { } 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 () => { diff --git a/src/admin/AdminSeedPanel.tsx b/src/admin/AdminSeedPanel.tsx index b1efaf1..45d69af 100644 --- a/src/admin/AdminSeedPanel.tsx +++ b/src/admin/AdminSeedPanel.tsx @@ -1,9 +1,11 @@ import { useState } from "react"; -import { append, readAll } from "../lib/eventlog"; +import { append, appendEntry, readAll } from "../lib/eventlog"; import { init as initIdentity } from "../lib/identity"; import { uploadMiniapp } from "../lib/miniappUpload"; -import { castVote, putProposal, putRosterEntry } from "../lib/assembly"; +import { putProposal, putRosterEntry } from "../lib/assembly"; import { recordHousingAssignmentCycle } from "../lib/housing"; +import { DEFAULT_QV_CREDITS, putResidentCredit } from "../lib/governance"; +import { postQvBallot } from "../lib/governanceEvents"; import { FAIRSHARE_RESOURCES, postFairshareFloor, @@ -13,7 +15,6 @@ import { computeGdd, settleFarmsForecast, solveFarmsPlantingOptimizer } from ".. import { reportHazard } from "../lib/tunnelsafety"; import { DEFAULT_ASSEMBLY_DB_NAME, getAssemblyEngine } from "../miniapps/assembly/useAssemblyEngine"; import { postSkillReview } from "../miniapps/mentor/mentorEvents"; -import { Rating } from "../lib/mentorSchedule"; import { toAccountId } from "../shell/accountId"; import { AdminAggregatePanel } from "./AdminAggregatePanel"; import { @@ -31,8 +32,11 @@ import { HOLLOW_DEMO_FARMS_PLOTS, HOLLOW_DEMO_FARMS_TEMPERATURES, HOLLOW_DEMO_HAZARD_REPORT, + HOLLOW_DEMO_MENTOR_APPRENTICE_RATING, HOLLOW_DEMO_MENTOR_REVIEW_SKILL_ID, HOLLOW_DEMO_PROPOSAL, + buildDemoCorroboratingHazardEntry, + buildDemoMentorReviewEntry, HOLLOW_DEMO_ROSTER, HOLLOW_DEMO_VOTES, hasDemoFixtureBeenLoaded, @@ -44,6 +48,18 @@ import { const emptyInput: SeedFormInput = { category: "population" }; +/** + * Next Lamport timestamp to assign to a genuinely foreign-signed demo entry: + * one past the highest already in the log (`readAll()` is lamportTs-ordered). + * Used only for the two second-identity entries that go through + * `appendEntry()` (a corroborating hazard report and a mentor's skill + * review); the real local `append()` path assigns its own. + */ +async function nextDemoLamportTs(): Promise { + const entries = await readAll(); + return entries.length === 0 ? 0 : entries[entries.length - 1].lamportTs + 1; +} + export interface AdminSeedPanelProps { /** Test seam: seeds Assembly's starting roster + proposal onto a * specific `y-indexeddb` database name instead of the production @@ -142,20 +158,37 @@ export function AdminSeedPanel({ assemblyDbName, aggregateEndpoint }: AdminSeedP // `hasDemoFixtureBeenLoaded` early return, so a second click never // re-adds duplicate roster entries (upserts are idempotent by id // regardless). - const { assembly } = getAssemblyEngine(assemblyDbName ?? DEFAULT_ASSEMBLY_DB_NAME); + const { assembly, governance } = getAssemblyEngine( + assemblyDbName ?? DEFAULT_ASSEMBLY_DB_NAME, + ); for (const entry of HOLLOW_DEMO_ROSTER) { putRosterEntry(assembly, entry); } putProposal(assembly, HOLLOW_DEMO_PROPOSAL); - // Real starting votes (plan: richer demo data) on the seeded proposal - // from the same two founding residents, through the real, unchanged - // castVote() - never a fabricated tally. + // Enroll each founding resident with their fixed QV credit budget - the + // real membership the signed QV tally reads. Without enrollment every + // ballot weighs 0.00 (the dead `castVote` CRDT path was removed), so + // this is what makes the seeded proposal show a live tally. + for (const member of HOLLOW_DEMO_ROSTER) { + putResidentCredit(governance, { + proposalId: HOLLOW_DEMO_PROPOSAL.id, + residentId: member.residentId, + credits: DEFAULT_QV_CREDITS, + }); + } + // Cast each founding resident's real signed QV ballot onto the Event Log + // via the same `postQvBallot()` path the live Assembly screen uses, so + // the seeded proposal shows a genuine live tally (two yes ballots -> + // yes 6.00). `demoFixture: true` exempts these admin-seeded ballots from + // the live voter-binding check (one device holds one key), exactly as + // `governanceEvents.ts` documents - never a fabricated tally. for (const vote of HOLLOW_DEMO_VOTES) { - castVote(assembly, { + await postQvBallot({ proposalId: HOLLOW_DEMO_PROPOSAL.id, voterId: vote.voterId, choice: vote.choice, - castAt: Date.now(), + credits: DEFAULT_QV_CREDITS, + demoFixture: true, }); } @@ -173,6 +206,14 @@ export function AdminSeedPanel({ assemblyDbName, aggregateEndpoint }: AdminSeedP // reportHazard() path ReportHazardForm uses - Tunnel Safety's map and // routing show a genuinely closed segment cold. await reportHazard(HOLLOW_DEMO_HAZARD_REPORT); + // A SECOND, genuinely distinct identity independently reports the SAME + // segment, foreign-signed and persisted through appendEntry() (the one + // sanctioned path for a pre-verified foreign entry, which re-verifies + // the signature) - so the segment crosses the 2-distinct-reporter bar + // and Tunnel Safety shows a real crowd-confirmed hazard cold. append() + // cannot be used: it would re-sign with THIS device's key, collapsing + // the two reporters into one, which can never corroborate. + await appendEntry(await buildDemoCorroboratingHazardEntry(await nextDemoLamportTs())); // A real, provably-feasible Farms planting forecast (plan: richer demo // data), through the same solveFarmsPlantingOptimizer + @@ -187,11 +228,21 @@ export function AdminSeedPanel({ assemblyDbName, aggregateEndpoint }: AdminSeedP }); await settleFarmsForecast(farmsComputation); - // One real Mentor skill review (plan: richer demo data), through the - // same postSkillReview() path MentorScreen uses, from the demo-loading - // identity itself - so well-repair (already seeded at-risk above) - // shows a genuine review/next-due-date instead of no history. - await postSkillReview(HOLLOW_DEMO_MENTOR_REVIEW_SKILL_ID, accountId, Rating.Good); + // The demo-loading identity rates the at-risk skill as still-learning, + // through the same postSkillReview() path MentorScreen uses - so + // well-repair shows a genuine review/next-due-date AND the local + // identity becomes a real apprentice NEED on it. + await postSkillReview( + HOLLOW_DEMO_MENTOR_REVIEW_SKILL_ID, + accountId, + HOLLOW_DEMO_MENTOR_APPRENTICE_RATING, + ); + // A SECOND, genuinely distinct identity's foreign-signed "Good" review of + // the same skill (appendEntry, re-verified) - the proficient mentor. + // Together with the apprentice need above this produces one real proposed + // apprentice->mentor match cold, which was unreachable when the only + // review was the local identity's own (a mentor can never match itself). + await appendEntry(await buildDemoMentorReviewEntry(await nextDemoLamportTs())); await append(DEMO_FIXTURE_MARKER); setDemoStatus("Demo data loaded into the Event Log."); diff --git a/src/admin/seedEvents.test.ts b/src/admin/seedEvents.test.ts index d2c9af6..14b5124 100644 --- a/src/admin/seedEvents.test.ts +++ b/src/admin/seedEvents.test.ts @@ -1,7 +1,16 @@ import { describe, expect, it } from "vitest"; import { assertValidManifest } from "../lib/miniappManifest"; +import { verifyEntrySignature } from "../lib/eventlog"; +import { Rating } from "../lib/mentorSchedule"; +import { toAccountId } from "../shell/accountId"; import { DEMO_FIXTURE_MARKER, + HOLLOW_DEMO_CORROBORATING_HAZARD, + HOLLOW_DEMO_HAZARD_REPORT, + HOLLOW_DEMO_MENTOR_APPRENTICE_RATING, + HOLLOW_DEMO_MENTOR_REVIEW_SKILL_ID, + buildDemoCorroboratingHazardEntry, + buildDemoMentorReviewEntry, DEMO_SAMPLE_MINIAPP_HTML, DEMO_SAMPLE_MINIAPP_MANIFEST, HOLLOW_DEMO_COMMONS_FUND_ACCOUNT, @@ -266,6 +275,72 @@ describe("buildDemoHousingCycleInput", () => { const second = buildDemoHousingCycleInput("deadbeef"); expect(first).toEqual(second); }); + + it("makes two residents contest one slot so fairness debt accrues to the loser and flips the slot next cycle", () => { + const input = buildDemoHousingCycleInput("agent-demo"); + + const cycle0 = solveHousingAssignment(input); + expect(cycle0.status).toBe("optimal"); + if (cycle0.status !== "optimal") return; + + // Exactly one resident is denied their top-ranked slot and accrues real, + // positive fairness debt (the loser of the contested slot). + const debtors = Object.entries(cycle0.updatedFairnessDebt).filter(([, debt]) => debt > 0); + expect(debtors).toHaveLength(1); + const [loser] = debtors[0]; + const loserSlotCycle0 = cycle0.assignments.find((a) => a.residentId === loser)!.slotId; + + // Carry the real debt ledger forward exactly as the Event Log would. + const cycle1 = solveHousingAssignment({ ...input, fairnessDebt: cycle0.updatedFairnessDebt }); + expect(cycle1.status).toBe("optimal"); + if (cycle1.status !== "optimal") return; + + // The accrued debt flips the contested slot to last cycle's loser... + const loserSlotCycle1 = cycle1.assignments.find((a) => a.residentId === loser)!.slotId; + expect(loserSlotCycle1).not.toBe(loserSlotCycle0); + // ...and getting their best slot this time resets their debt to zero. + expect(cycle1.updatedFairnessDebt[loser]).toBe(0); + }); +}); + +describe("buildDemoCorroboratingHazardEntry", () => { + it("builds a foreign-signed report on the same segment, by a DIFFERENT reporter, that verifies", async () => { + const entry = await buildDemoCorroboratingHazardEntry(7); + + expect(entry.lamportTs).toBe(7); + expect(entry.payload).toMatchObject({ + type: "tunnelsafety.hazard.report", + segmentId: HOLLOW_DEMO_HAZARD_REPORT.segmentId, + }); + // Same segment as the local report, so the two corroborate. + expect(HOLLOW_DEMO_CORROBORATING_HAZARD.segmentId).toBe(HOLLOW_DEMO_HAZARD_REPORT.segmentId); + // The signature really verifies against the foreign author key - a genuine + // second identity, not this device re-signing its own report. + expect(entry.authorPubkey).toHaveLength(32); + expect(await verifyEntrySignature(entry)).toBe(true); + }); +}); + +describe("buildDemoMentorReviewEntry", () => { + it("builds a foreign-signed Good review attributed to a distinct mentor account, that verifies", async () => { + const entry = await buildDemoMentorReviewEntry(9); + + expect(await verifyEntrySignature(entry)).toBe(true); + const payload = entry.payload as { + type: string; + skillId: string; + rating: number; + learnerId: string; + }; + expect(payload.type).toBe("mentor.skillReview"); + expect(payload.skillId).toBe(HOLLOW_DEMO_MENTOR_REVIEW_SKILL_ID); + expect(payload.rating).toBe(Rating.Good); + // Attributed to the foreign identity's own account id, not the local one. + expect(payload.learnerId).toBe(toAccountId(entry.authorPubkey)); + // The local demo review is a still-learning grade, so the two reviews form + // a real apprentice/mentor pair, never two mentors with nobody to match. + expect(HOLLOW_DEMO_MENTOR_APPRENTICE_RATING).not.toBe(Rating.Good); + }); }); describe("buildDemoSkillHolderPayloads", () => { diff --git a/src/admin/seedEvents.ts b/src/admin/seedEvents.ts index b43954f..a49d8d1 100644 --- a/src/admin/seedEvents.ts +++ b/src/admin/seedEvents.ts @@ -10,11 +10,16 @@ * final/outcome metric. */ +import * as ed from "@noble/ed25519"; 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 { HazardReportInput, HazardReportPayload } from "../lib/tunnelsafety"; import type { PlantingPlot, CropMaturityWindow, TemperatureEntry } from "../lib/farms"; +import type { UnsignedEventLogEntry } from "../lib/eventlog"; +import { Rating } from "../lib/mentorSchedule"; +import type { SkillReviewSeedPayload } from "../lib/mentorSchedule"; +import { toAccountId } from "../shell/accountId"; export const RESOURCE_TYPES = ["power", "water", "food", "cooling"] as const; export type ResourceType = (typeof RESOURCE_TYPES)[number]; @@ -180,7 +185,7 @@ export interface DemoFixtureMarkerPayload { export const DEMO_FIXTURE_MARKER: DemoFixtureMarkerPayload = { type: "seed.demo.loaded", - fixtureId: "hollow-demo-v1", + fixtureId: "hollow-demo-v2", }; /** @@ -241,12 +246,15 @@ export const DEMO_SAMPLE_MINIAPP_HTML = ` { const residents = [agent, ...HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS]; const slots = HOLLOW_DEMO_HOUSING_SLOTS; + // Best-first slot ranking per resident, indexed by position in `residents`. + // The demo-loading identity (index 0) and the first neighbor (index 1) both + // rank the first single-capacity slot highest, so they genuinely contest it; + // the second neighbor ranks a different slot highest, so it stays + // uncontested and the instance remains feasible and hand-checkable. + const rankings: string[][] = [ + [slots[0].id, slots[1].id, slots[2].id], // demo identity: slot 1 best (contested) + [slots[0].id, slots[1].id, slots[2].id], // neighbor B: slot 1 best (contested) + [slots[2].id, slots[1].id, slots[0].id], // neighbor C: slot 3 best (uncontested) + ]; 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, - }); + const ranking = rankings[i]; + for (const slot of slots) { + // Top-ranked slot scores highest, each lower rank one less - so a + // resident denied their top slot has a real, positive preference + // shortfall (= fairness debt), never the uniform score that pinned every + // shortfall to zero. + const score = slots.length - ranking.indexOf(slot.id); + preferences.push({ residentId: residents[i], slotId: slot.id, score }); } } return { residents, slots, preferences }; @@ -325,6 +345,75 @@ export const HOLLOW_DEMO_HAZARD_REPORT: HazardReportInput = { status: "flooded", }; +/** + * Canonical signed-message bytes for one Event Log entry - the EXACT shape + * `src/lib/eventlog.ts` signs over and re-verifies (`JSON({payload, + * lamportTs})`). Replicated here (not imported) only because eventlog.ts + * keeps its own `canonicalMessage` private; this must stay byte-for-byte + * identical or `appendEntry()` would reject the foreign entry below. + */ +function canonicalEntryMessage(payload: unknown, lamportTs: number): Uint8Array { + return new TextEncoder().encode(JSON.stringify({ payload, lamportTs })); +} + +/** + * Builds a genuinely foreign-signed Event Log entry: `secretKey` (a demo + * identity DISTINCT from this device's own) signs the canonical message, so + * the entry's `authorPubkey` is a second real identity's key. The caller + * persists it through `appendEntry()` - the one sanctioned path for a + * pre-verified foreign entry, which re-verifies the signature exactly as it + * would a peer's synced entry. `append()` cannot be used for these: it would + * re-sign with THIS device's key, collapsing a second identity into the + * local one. No Event Log/DB access here (signing is pure crypto). + */ +export async function buildForeignSignedEntry( + secretKey: Uint8Array, + payload: unknown, + lamportTs: number, +): Promise { + const authorPubkey = await ed.getPublicKeyAsync(secretKey); + const signature = await ed.signAsync(canonicalEntryMessage(payload, lamportTs), secretKey); + return { payload, authorPubkey, signature, lamportTs }; +} + +/** + * A SECOND, distinct demo identity's fixed Ed25519 secret key - a different + * resident than this device's own identity - used to foreign-sign the + * corroborating hazard report below. Tunnel Safety's crowd-corroboration + * requires `CORROBORATION_MIN_DISTINCT_REPORTERS` (2) DISTINCT signing + * identities on one still-open segment; one resident reporting a segment + * twice can never self-corroborate it. Fixed (not random) so the demo + * resident is stable across reloads. + */ +export const HOLLOW_DEMO_SECOND_REPORTER_SECRET_KEY: Uint8Array = new Uint8Array(32).fill(0x5a); + +/** + * The corroborating hazard report: the SAME segment as + * `HOLLOW_DEMO_HAZARD_REPORT`, reported by the second demo identity above, + * so that segment crosses the 2-distinct-reporter bar and shows as + * crowd-confirmed ("Confirmed by 2 residents") cold. + */ +export const HOLLOW_DEMO_CORROBORATING_HAZARD: HazardReportInput = { + segmentId: HOLLOW_DEMO_HAZARD_REPORT.segmentId, + status: "blocked", +}; + +/** + * Builds the foreign-signed `tunnelsafety.hazard.report` entry for the second + * reporter at `lamportTs`. The caller appends it via `appendEntry()`. + */ +export async function buildDemoCorroboratingHazardEntry( + lamportTs: number, +): Promise { + const payload: HazardReportPayload = { + type: "tunnelsafety.hazard.report", + segmentId: HOLLOW_DEMO_CORROBORATING_HAZARD.segmentId, + status: HOLLOW_DEMO_CORROBORATING_HAZARD.status, + reportedAt: Date.now(), + }; + return buildForeignSignedEntry(HOLLOW_DEMO_SECOND_REPORTER_SECRET_KEY, payload, lamportTs); +} + /** * A small, provably-feasible Farms planting input for the Hollow demo * fixture: five real entered daily temperature readings (mean 20C against @@ -354,6 +443,48 @@ export const HOLLOW_DEMO_FARMS_CROPS: CropMaturityWindow[] = [ */ export const HOLLOW_DEMO_MENTOR_REVIEW_SKILL_ID = "well-repair"; +/** + * The demo-loading identity's own rating on `HOLLOW_DEMO_MENTOR_REVIEW_SKILL_ID`. + * Deliberately a STILL-LEARNING grade (not proficient): it makes the local + * identity a real apprentice NEED on this at-risk skill. A proficient + * (Good/Easy) self-review would instead make the local identity a mentor + * with nobody to match - which is exactly why apprentice-matching was + * unreachable before. Paired with the foreign-signed mentor review below (a + * distinct identity who IS proficient), this yields one genuine proposed + * apprentice->mentor match cold. + */ +export const HOLLOW_DEMO_MENTOR_APPRENTICE_RATING = Rating.Again; + +/** + * A SECOND, distinct demo identity's fixed Ed25519 secret key - a resident + * who is proficient at `HOLLOW_DEMO_MENTOR_REVIEW_SKILL_ID`. Foreign-signs a + * "Good" review (below) so apprentice-matching has a real mentor to propose + * for the local apprentice need; a mentor can never be matched to itself, so + * without a second account the match has no signal. Fixed (not random) so + * the demo mentor is stable across reloads. + */ +export const HOLLOW_DEMO_MENTOR_SECRET_KEY: Uint8Array = new Uint8Array(32).fill(0x3c); + +/** + * Builds the foreign-signed `mentor.skillReview` entry for the proficient + * second identity at `lamportTs`: a real "Good" review of the at-risk skill, + * attributed (via `learnerId`, which the mentor engine keys on) to that + * second identity's own account id. The caller appends it via `appendEntry()`. + */ +export async function buildDemoMentorReviewEntry( + lamportTs: number, +): Promise { + const mentorPubkey = await ed.getPublicKeyAsync(HOLLOW_DEMO_MENTOR_SECRET_KEY); + const payload: SkillReviewSeedPayload = { + type: "mentor.skillReview", + skillId: HOLLOW_DEMO_MENTOR_REVIEW_SKILL_ID, + learnerId: toAccountId(mentorPubkey), + rating: Rating.Good, + reviewedAt: new Date().toISOString(), + }; + return buildForeignSignedEntry(HOLLOW_DEMO_MENTOR_SECRET_KEY, payload, lamportTs); +} + /** * The bundled "Hollow demo" fixture's starting Assembly roster (plan todo * 12): two plausible founding residents, matching the same D11 "starting @@ -399,11 +530,14 @@ export const HOLLOW_DEMO_PROPOSAL: ProposalRecord = { /** * 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. + * founding residents `HOLLOW_DEMO_ROSTER` seeds. These now route through the + * REAL signed quadratic-voting tally path (GAP-5 fix): each founding resident + * is first enrolled with their fixed QV credit budget via `putResidentCredit` + * (the membership the tally reads), then each vote is cast as a signed + * `postQvBallot` onto the Event Log - never the removed dead `castVote` CRDT + * path. Two `yes` ballots at `DEFAULT_QV_CREDITS` each weigh `sqrt(9) = 3`, so + * the seeded proposal shows a genuine live `yes 6.00` tally cold. See + * `AdminSeedPanel.handleLoadDemo`. */ export const HOLLOW_DEMO_VOTES: ReadonlyArray<{ voterId: string; choice: "yes" | "no" | "abstain" }> = [ { voterId: HOLLOW_DEMO_ROSTER[0].id, choice: "yes" },