diff --git a/src/lib/governance.test.ts b/src/lib/governance.test.ts index a6f3b6e..2eac89c 100644 --- a/src/lib/governance.test.ts +++ b/src/lib/governance.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { castVote, createAssemblyDoc, putProposal, type AssemblyDoc } from "./assembly.ts"; import { computeQvTally, + DEFAULT_QV_CREDITS, listDelegations, listResidentCredits, putDelegation, @@ -17,24 +18,29 @@ import { const PROPOSAL_ID = "p-tally"; /** - * Hand-computed happy-path fixture: 10 residents, every credit budget a - * perfect square so `sqrt(credits)` is an exact integer and the expected - * tally can be checked by hand. + * Hand-computed happy-path fixture: 10 residents. Weight now comes ONLY from + * tamper-evident data (GAP-C): a direct voter weighs `sqrt(min(their SIGNED + * ballot's credits, DEFAULT_QV_CREDITS=9))`, and a pure delegator (no ballot of + * their own) contributes the full fixed civic budget `sqrt(9) = 3`. The + * `HAPPY_CREDITS` enrollment rows below are DELIBERATELY absurd, varied values + * (100, 64, ...) to prove the tally ignores the forgeable CRDT + * `residentCredits.credits` entirely - if they still drove weight this fixture + * would read 23/25/7 (the pre-fix numbers), not 10/10/6. * - * R1 100 credits -> direct YES -> weight 10 -> YES - * R2 64 credits -> direct NO -> weight 8 -> NO - * R3 36 credits -> delegates to R1 (R1 -> YES) -> weight 6 -> YES - * R4 9 credits -> direct YES -> weight 3 -> YES - * R5 49 credits -> delegates to R2 (R2 -> NO) -> weight 7 -> NO - * R6 16 credits -> delegates to R4 (R4 -> YES) -> weight 4 -> YES - * R7 25 credits -> direct ABSTAIN -> weight 5 -> ABSTAIN - * R8 4 credits -> delegates to R7 (R7 -> ABSTAIN) -> weight 2 -> ABSTAIN - * R9 81 credits -> direct NO -> weight 9 -> NO - * R10 1 credit -> delegates to R9 (R9 -> NO) -> weight 1 -> NO + * R1 ballot YES, 9 credits -> sqrt(min(9,9)) = 3 -> YES + * R2 ballot NO, 4 credits -> sqrt(min(4,9)) = 2 -> NO + * R3 delegates to R1 (-> YES) -> full civic budget sqrt(9) = 3 -> YES + * R4 ballot YES, 1 credit -> sqrt(min(1,9)) = 1 -> YES + * R5 delegates to R2 (-> NO) -> full civic budget sqrt(9) = 3 -> NO + * R6 delegates to R4 (-> YES) -> full civic budget sqrt(9) = 3 -> YES + * R7 ballot ABSTAIN, 9 credits -> sqrt(min(9,9)) = 3 -> ABSTAIN + * R8 delegates to R7 (-> ABSTAIN) -> full civic budget sqrt(9) = 3 -> ABSTAIN + * R9 ballot NO, 4 credits -> sqrt(min(4,9)) = 2 -> NO + * R10 delegates to R9 (-> NO) -> full civic budget sqrt(9) = 3 -> NO * - * YES = 10 (R1) + 6 (R3) + 3 (R4) + 4 (R6) = 23 - * NO = 8 (R2) + 7 (R5) + 9 (R9) + 1 (R10) = 25 - * ABSTAIN = 5 (R7) + 2 (R8) = 7 + * YES = 3 (R1) + 3 (R3) + 1 (R4) + 3 (R6) = 10 + * NO = 2 (R2) + 3 (R5) + 2 (R9) + 3 (R10) = 10 + * ABSTAIN = 3 (R7) + 3 (R8) = 6 */ const HAPPY_CREDITS: Record = { r1: 100, @@ -65,18 +71,31 @@ const HAPPY_DIRECT_BALLOTS: Record = { r9: "no", }; -const EXPECTED_HAPPY_TALLY = { yes: 23, no: 25, abstain: 7 }; +/** Each direct voter's SIGNED ballot credit spend - all at or below the fixed + * civic budget, so no clamp bites here (the clamp itself is proved separately + * below). These are the authoritative weight source, NOT `HAPPY_CREDITS`. */ +const HAPPY_BALLOT_CREDITS: Record = { + r1: 9, + r2: 4, + r4: 1, + r7: 9, + r9: 4, +}; + +const EXPECTED_HAPPY_TALLY = { yes: 10, no: 10, abstain: 6 }; /** The happy-path direct ballots as the signed-log-shaped `QvBallotRecord[]` * that `computeQvTally` now consumes (`extractQvBallots` produces this exact - * shape in production). Ballots no longer live in the CRDT, so the fixture - * hands them to the reducer directly, exactly as the hook feeds it the log. */ + * shape - including the signed `credits` field - in production). Ballots no + * longer live in the CRDT, so the fixture hands them to the reducer directly, + * exactly as the hook feeds it the log. */ const HAPPY_BALLOTS: QvBallotRecord[] = Object.entries(HAPPY_DIRECT_BALLOTS).map( ([voterId, choice]) => ({ id: qvBallotKey(PROPOSAL_ID, voterId), proposalId: PROPOSAL_ID, voterId, choice, + credits: HAPPY_BALLOT_CREDITS[voterId], castAt: 1, }), ); @@ -176,10 +195,12 @@ describe("governance: quadratic-voting tally", () => { expect(result.participants).toHaveLength(10); expect(result.participants.every((p) => !p.cycleDetected)).toBe(true); - // Each resident's own sqrt(credits) weight landed on the choice their - // effective voter cast directly (spot-check a delegated resident). + // Each resident's own civic-budget weight landed on the choice their + // effective voter cast directly (spot-check a delegated resident): r3 + // delegates to r1, so r3 contributes the full fixed civic budget + // sqrt(9)=3 - NOT sqrt(its forgeable HAPPY_CREDITS=36)=6 - onto r1's YES. const r3 = result.participants.find((p) => p.residentId === "r3")!; - expect(r3).toMatchObject({ effectiveVoterId: "r1", choice: "yes", voteWeight: 6 }); + expect(r3).toMatchObject({ effectiveVoterId: "r1", choice: "yes", voteWeight: 3 }); }); it("failure - a delegation cycle is detected and each cycle member's vote falls back to their own direct vote rather than looping, with a deterministic resulting tally", () => { @@ -187,14 +208,16 @@ describe("governance: quadratic-voting tally", () => { // (A -> B -> C -> A). Cycle detection must make each of them fall back // to their own ballot instead of hanging or losing a vote. const residentCredits: ResidentCreditRecord[] = [ - { id: "a", proposalId: PROPOSAL_ID, residentId: "a", credits: 100 }, // sqrt = 10 - { id: "b", proposalId: PROPOSAL_ID, residentId: "b", credits: 64 }, // sqrt = 8 - { id: "c", proposalId: PROPOSAL_ID, residentId: "c", credits: 36 }, // sqrt = 6 + { id: "a", proposalId: PROPOSAL_ID, residentId: "a", credits: 100 }, + { id: "b", proposalId: PROPOSAL_ID, residentId: "b", credits: 64 }, + { id: "c", proposalId: PROPOSAL_ID, residentId: "c", credits: 36 }, ]; + // Each falls back to their OWN signed ballot: weight is sqrt(min(ballot + // credits, 9)) from that ballot, never the forgeable residentCredits. const ballots: QvBallotRecord[] = [ - { id: "a", proposalId: PROPOSAL_ID, voterId: "a", choice: "yes", castAt: 0 }, - { id: "b", proposalId: PROPOSAL_ID, voterId: "b", choice: "no", castAt: 0 }, - { id: "c", proposalId: PROPOSAL_ID, voterId: "c", choice: "yes", castAt: 0 }, + { id: "a", proposalId: PROPOSAL_ID, voterId: "a", choice: "yes", credits: 9, castAt: 0 }, // sqrt 9 = 3 + { id: "b", proposalId: PROPOSAL_ID, voterId: "b", choice: "no", credits: 4, castAt: 0 }, // sqrt 4 = 2 + { id: "c", proposalId: PROPOSAL_ID, voterId: "c", choice: "yes", credits: 9, castAt: 0 }, // sqrt 9 = 3 ]; const delegations: DelegationRecord[] = [ { id: "a", delegatorId: "a", delegateId: "b", createdAt: 0 }, @@ -211,8 +234,8 @@ describe("governance: quadratic-voting tally", () => { } // Fallback must use each resident's OWN direct ballot, not loop or drop - // votes: YES = A(10) + C(6) = 16, NO = B(8). - expect(result.tally).toEqual({ yes: 16, no: 8, abstain: 0 }); + // votes: YES = A(3) + C(3) = 6, NO = B(2). + expect(result.tally).toEqual({ yes: 6, no: 2, abstain: 0 }); }); it("a resident who delegates into a chain whose terminal voter never cast a ballot does not vote (no tally weight added)", () => { @@ -226,12 +249,15 @@ describe("governance: quadratic-voting tally", () => { const result = computeQvTally({ proposalId: PROPOSAL_ID, residentCredits, ballots: [], delegations }); expect(result.tally).toEqual({ yes: 0, no: 0, abstain: 0 }); + // x delegates to y (who never voted), so x's weight lands nowhere - but x + // still carries their full fixed civic budget sqrt(9)=3 (NOT sqrt(the + // forgeable residentCredits=25)=5), proving weight ignores that CRDT field. expect(result.participants[0]).toMatchObject({ residentId: "x", effectiveVoterId: "y", cycleDetected: false, choice: null, - voteWeight: 5, + voteWeight: 3, }); }); @@ -244,45 +270,86 @@ describe("governance: quadratic-voting tally", () => { { id: "row-2", proposalId: PROPOSAL_ID, residentId: "a", credits: 9 }, ]; const ballots: QvBallotRecord[] = [ - { id: "a", proposalId: PROPOSAL_ID, voterId: "a", choice: "yes", castAt: 0 }, + { id: "a", proposalId: PROPOSAL_ID, voterId: "a", choice: "yes", credits: 9, castAt: 0 }, ]; const result = computeQvTally({ proposalId: PROPOSAL_ID, residentCredits, ballots, delegations: [] }); expect(result.tally).toEqual({ yes: 3, no: 0, abstain: 0 }); expect(result.participants).toHaveLength(1); }); - it("rejects a negative credit budget rather than silently miscounting", () => { + it("clamps a forged high-credit ballot to the fixed civic budget (GAP-C: no vote-weight inflation)", () => { + // The decisive governance exploit: a ballot (or the old CRDT credits row) + // declaring 1_000_000 credits must NOT weigh sqrt(1e6)=1000 and dominate + // the tally - it weighs sqrt(min(1e6, DEFAULT_QV_CREDITS)) = sqrt(9) = 3, + // exactly the same as an honest full-budget ballot. const residentCredits: ResidentCreditRecord[] = [ - { id: "x", proposalId: PROPOSAL_ID, residentId: "x", credits: -1 }, + { id: "forger", proposalId: PROPOSAL_ID, residentId: "forger", credits: 9 }, + { id: "honest", proposalId: PROPOSAL_ID, residentId: "honest", credits: 9 }, + ]; + const ballots: QvBallotRecord[] = [ + { id: "forger", proposalId: PROPOSAL_ID, voterId: "forger", choice: "yes", credits: 1_000_000, castAt: 0 }, + { id: "honest", proposalId: PROPOSAL_ID, voterId: "honest", choice: "no", credits: 9, castAt: 0 }, + ]; + const result = computeQvTally({ proposalId: PROPOSAL_ID, residentCredits, ballots, delegations: [] }); + const forger = result.participants.find((p) => p.residentId === "forger")!; + expect(forger.voteWeight).toBe(Math.sqrt(DEFAULT_QV_CREDITS)); + expect(forger.voteWeight).toBe(3); + // The forged ballot cannot out-weigh the honest one: both count exactly 3. + expect(result.tally).toEqual({ yes: 3, no: 3, abstain: 0 }); + }); + + it("ignores the unsigned CRDT residentCredits.credits entirely when weighing a tally (GAP-C root cause)", () => { + // A peer who has set their P2P-synced residentCredits row to 1_000_000 + // gains NO extra weight: the row is only a membership marker, and weight + // comes solely from the signed ballot (clamped). Were residentCredits still + // the weight source, this would read sqrt(1e6)=1000 on YES. + const residentCredits: ResidentCreditRecord[] = [ + { id: "a", proposalId: PROPOSAL_ID, residentId: "a", credits: 1_000_000 }, + ]; + const ballots: QvBallotRecord[] = [ + { id: "a", proposalId: PROPOSAL_ID, voterId: "a", choice: "yes", credits: 9, castAt: 0 }, + ]; + const result = computeQvTally({ proposalId: PROPOSAL_ID, residentCredits, ballots, delegations: [] }); + expect(result.tally).toEqual({ yes: 3, no: 0, abstain: 0 }); + }); + + it("rejects a negative signed-ballot credit spend rather than silently miscounting", () => { + const residentCredits: ResidentCreditRecord[] = [ + { id: "x", proposalId: PROPOSAL_ID, residentId: "x", credits: 9 }, + ]; + const ballots: QvBallotRecord[] = [ + { id: "x", proposalId: PROPOSAL_ID, voterId: "x", choice: "yes", credits: -1, castAt: 0 }, ]; expect(() => - computeQvTally({ proposalId: PROPOSAL_ID, residentCredits, ballots: [], delegations: [] }), + computeQvTally({ proposalId: PROPOSAL_ID, residentCredits, ballots, delegations: [] }), ).toThrow(/negative/); }); - it("rejects a NaN credit budget rather than poisoning the whole tally", () => { - // Draft repro: one resident's NaN credits previously made - // `Math.sqrt(NaN)` NaN, which poisoned `tally.yes` (and every bucket a - // NaN-weighted ballot landed in) for every voter on the proposal. + it("rejects a NaN signed-ballot credit spend rather than poisoning the whole tally", () => { + // A NaN credit spend previously made `Math.sqrt(NaN)` NaN, which poisoned + // every bucket a NaN-weighted ballot landed in for every voter. const residentCredits: ResidentCreditRecord[] = [ - { id: "a", proposalId: PROPOSAL_ID, residentId: "a", credits: 100 }, - { id: "bad", proposalId: PROPOSAL_ID, residentId: "bad", credits: Number.NaN }, + { id: "a", proposalId: PROPOSAL_ID, residentId: "a", credits: 9 }, + { id: "bad", proposalId: PROPOSAL_ID, residentId: "bad", credits: 9 }, ]; const ballots: QvBallotRecord[] = [ - { id: "a", proposalId: PROPOSAL_ID, voterId: "a", choice: "yes", castAt: 0 }, - { id: "bad", proposalId: PROPOSAL_ID, voterId: "bad", choice: "yes", castAt: 0 }, + { id: "a", proposalId: PROPOSAL_ID, voterId: "a", choice: "yes", credits: 9, castAt: 0 }, + { id: "bad", proposalId: PROPOSAL_ID, voterId: "bad", choice: "yes", credits: Number.NaN, castAt: 0 }, ]; expect(() => computeQvTally({ proposalId: PROPOSAL_ID, residentCredits, ballots, delegations: [] }), ).toThrow(/non-finite/); }); - it("rejects an Infinity credit budget rather than poisoning the whole tally", () => { + it("rejects an Infinity signed-ballot credit spend rather than poisoning the whole tally", () => { const residentCredits: ResidentCreditRecord[] = [ - { id: "x", proposalId: PROPOSAL_ID, residentId: "x", credits: Number.POSITIVE_INFINITY }, + { id: "x", proposalId: PROPOSAL_ID, residentId: "x", credits: 9 }, + ]; + const ballots: QvBallotRecord[] = [ + { id: "x", proposalId: PROPOSAL_ID, voterId: "x", choice: "yes", credits: Number.POSITIVE_INFINITY, castAt: 0 }, ]; expect(() => - computeQvTally({ proposalId: PROPOSAL_ID, residentCredits, ballots: [], delegations: [] }), + computeQvTally({ proposalId: PROPOSAL_ID, residentCredits, ballots, delegations: [] }), ).toThrow(/non-finite/); }); }); diff --git a/src/lib/governance.ts b/src/lib/governance.ts index 1a852f3..45cc955 100644 --- a/src/lib/governance.ts +++ b/src/lib/governance.ts @@ -86,6 +86,14 @@ export interface QvBallotRecord { proposalId: string; voterId: string; choice: VoteChoice; + /** The voter's declared credit spend, carried through verbatim from the + * SIGNED Event Log ballot (`QvBallotPayload.credits`, verified at read in + * `extractQvBallots`). This value - clamped to `DEFAULT_QV_CREDITS` - is the + * authoritative tally-weight source for a direct voter, NOT the unsigned, + * P2P-forgeable CRDT `residentCredits.credits` (closing GAP-C: a peer who + * set their CRDT credits to 1_000_000 could otherwise make `sqrt(1e6)=1000` + * dominate every tally). */ + credits: number; castAt: number; } @@ -125,6 +133,12 @@ export function putDelegation(governance: GovernanceDoc, delegation: DelegationR governance.delegations.set(delegation.delegatorId, delegation); } +/** Revokes a resident's delegation so their own ballot counts again. A no-op + * if `delegatorId` has no active delegation. */ +export function removeDelegation(governance: GovernanceDoc, delegatorId: string): void { + governance.delegations.delete(delegatorId); +} + /** Sets (or replaces) a resident's QV credit budget for a proposal. */ export function putResidentCredit( governance: GovernanceDoc, @@ -212,8 +226,12 @@ export interface QvParticipant { * voter never cast a direct ballot (counts as not voting - no weight is * added to any tally bucket). */ choice: VoteChoice | null; - /** This resident's own vote weight, `sqrt(credits)` - always computed - * from the resident's *own* credit budget, never the delegate's. */ + /** This resident's own vote weight, always their *own* tamper-evident + * civic voice (never the delegate's, and never the forgeable CRDT + * `residentCredits.credits`): `sqrt(min(their SIGNED ballot's credits, + * DEFAULT_QV_CREDITS))` for a resident who cast their own ballot, or + * `sqrt(DEFAULT_QV_CREDITS)` - the full fixed civic budget - for one who + * only delegates and has no ballot of their own. */ voteWeight: number; } @@ -224,15 +242,29 @@ export interface QvTallyResult { } /** - * Computes the quadratic-voting tally for `proposalId`: every resident in - * `residentCredits` resolves their effective voter (following + * Computes the quadratic-voting tally for `proposalId`: every enrolled + * resident in `residentCredits` resolves their effective voter (following * `delegations`, cycle-safe per `resolveEffectiveVoter`), and - if that - * effective voter cast a direct `qvBallots` entry for this proposal - adds - * `sqrt(resident's own credits)` to that choice's tally bucket. + * effective voter cast a signed ballot for this proposal - adds the + * resident's own `voteWeight` to that choice's tally bucket. + * + * WEIGHT IS TAMPER-EVIDENT (GAP-C fix): a resident's weight is derived ONLY + * from signed, verify-at-read data - never from the unsigned, P2P-synced CRDT + * `residentCredits.credits`, which any peer sharing a sync code could set to an + * arbitrary value to inflate their own vote (`sqrt(1e6)=1000` dominating every + * tally). `residentCredits` is used here solely as the MEMBERSHIP set (who is + * enrolled to vote on this proposal); its `credits` field is deliberately + * ignored. Under THE COMMONS' civic equal-budget model (ECONOMY.md section 3) every + * resident's legitimate allowance is the same fixed `DEFAULT_QV_CREDITS`, so: + * - a resident who cast their OWN signed ballot weighs + * `sqrt(min(ballot.credits, DEFAULT_QV_CREDITS))` - the clamp means a forged + * 1_000_000-credit ballot still weighs no more than an honest full-budget one; + * - a resident who only delegates has no ballot of their own, so they + * contribute their full fixed civic budget `sqrt(DEFAULT_QV_CREDITS)`, + * redirected (by `resolveEffectiveVoter`) onto their delegate's choice. * * QV formula applied: `votes = sqrt(credits)` (`credits = votes^2`), the - * standard quadratic cost curve, applied per resident to their own credit - * budget regardless of whose choice they end up counting toward. + * standard quadratic cost curve. */ export function computeQvTally(params: { proposalId: string; @@ -248,11 +280,14 @@ export function computeQvTally(params: { ballotByVoter.set(ballot.voterId, ballot); } - // One credit budget per (proposalId, residentId), last-writer-wins - + // One enrolled resident per (proposalId, residentId), last-writer-wins - // mirrors the Y.Map `residentCredits` key semantics (`residentCreditKey`). - // Collapsing here is a security boundary: the credits CRDT is P2P-synced - // and a peer can inject a second row for a resident under a different map - // id; counting both would double that resident's quadratic weight. + // This is the MEMBERSHIP set (who may vote on this proposal), not the weight + // source - the `.credits` field on these rows is forgeable and deliberately + // never read for weight (see this function's header). Collapsing duplicate + // rows here is still a security boundary: the credits CRDT is P2P-synced and + // a peer can inject a second row for a resident under a different map id; + // counting both would let that resident appear - and so vote - twice. const creditByResident = new Map(); for (const resident of residentCredits) { if (resident.proposalId !== proposalId) continue; @@ -263,32 +298,39 @@ export function computeQvTally(params: { const participants: QvParticipant[] = []; for (const resident of creditByResident.values()) { - assertFiniteNumber( - resident.credits, - `QV credit budget for resident ${resident.residentId} on proposal ${proposalId}`, - ); - if (resident.credits < 0) { - throw new Error( - `negative QV credit budget for resident ${resident.residentId} on proposal ${proposalId}`, - ); - } - const { effectiveVoterId, cycleDetected } = resolveEffectiveVoter( resident.residentId, delegations, ); - const ballot = ballotByVoter.get(effectiveVoterId); - const voteWeight = Math.sqrt(resident.credits); + const effectiveBallot = ballotByVoter.get(effectiveVoterId); - if (ballot) { - tally[ballot.choice] += voteWeight; + // This resident's OWN tamper-evident civic voice. A direct voter spends + // what their SIGNED ballot attests (clamped to the fixed civic budget so a + // forged high-credit ballot cannot out-weigh an honest one); a pure + // delegator has no ballot and contributes the full fixed civic budget. + // The forgeable CRDT `residentCredits.credits` is never read here. + const ownBallot = ballotByVoter.get(resident.residentId); + const declaredCredits = ownBallot ? ownBallot.credits : DEFAULT_QV_CREDITS; + assertFiniteNumber( + declaredCredits, + `QV ballot credits for resident ${resident.residentId} on proposal ${proposalId}`, + ); + if (declaredCredits < 0) { + throw new Error( + `negative QV ballot credits for resident ${resident.residentId} on proposal ${proposalId}`, + ); + } + const voteWeight = Math.sqrt(Math.min(declaredCredits, DEFAULT_QV_CREDITS)); + + if (effectiveBallot) { + tally[effectiveBallot.choice] += voteWeight; } participants.push({ residentId: resident.residentId, effectiveVoterId, cycleDetected, - choice: ballot?.choice ?? null, + choice: effectiveBallot?.choice ?? null, voteWeight, }); } diff --git a/src/lib/governanceEvents.ts b/src/lib/governanceEvents.ts index 25c164a..6f54366 100644 --- a/src/lib/governanceEvents.ts +++ b/src/lib/governanceEvents.ts @@ -39,8 +39,17 @@ import { toAccountId } from "../shell/accountId.ts"; * identity loaded the fixture, and is never claimed to be an authentic vote by * the resident it names. The security claim is scoped to ballots cast LIVE * through the UI by the local identity (`demoFixture` absent) - those are - * verified and a forged one is rejected. Self-issued credit forgery remains a - * disclosed, out-of-scope residual risk and is NOT addressed here. + * verified and a forged one is rejected. + * + * CREDIT-WEIGHT INFLATION (GAP-C) IS CLOSED HERE + IN `computeQvTally`: the + * signed `credits` this module carries is clamped to the fixed civic budget + * `DEFAULT_QV_CREDITS` when weighed, and the tally reads that signed, clamped + * value instead of the unsigned, P2P-synced CRDT `residentCredits.credits` a + * peer could set to 1_000_000 to dominate a vote. What REMAINS a disclosed, + * out-of-scope residual (ECONOMY.md's "What this system does NOT guarantee") + * is Sybil/self-enrollment: a peer can still forge a roster/credit MEMBERSHIP + * row to gain one extra vote - but only ever at the same clamped weight as an + * honest resident, never an inflated one. */ export const QV_BALLOT_PAYLOAD_TYPE = "governance.qvBallot" as const; @@ -53,11 +62,13 @@ export interface QvBallotPayload { proposalId: string; voterId: string; choice: VoteChoice; - /** The resident's declared credit spend for this ballot, carried in the - * signed record for audit/tamper-evidence. The authoritative tally weight - * is still `sqrt(resident's own credit budget)` from `residentCredits` - * (`computeQvTally` is unchanged); this field documents what the voter - * attested to at cast time. */ + /** The resident's declared credit spend for this ballot, signed over and + * tamper-evident. This is the AUTHORITATIVE tally-weight source: `computeQvTally` + * weighs a direct voter by `sqrt(min(ballot.credits, DEFAULT_QV_CREDITS))` from + * this field (carried through `extractQvBallots` into `QvBallotRecord.credits`), + * NOT the unsigned, forgeable CRDT `residentCredits.credits` (GAP-C). The clamp + * means even a ballot that declares 1_000_000 credits weighs no more than an + * honest full-budget one. */ credits: number; /** Marks an admin-seeded demo ballot, exempt from the live voter-binding * check (see the module header's DEMO-FIXTURE EXEMPTION). Absent for every @@ -136,6 +147,9 @@ export function extractQvBallots(entries: StoredEventLogEntry[]): QvBallotRecord proposalId: payload.proposalId, voterId: payload.voterId, choice: payload.choice, + // Carry the SIGNED credit spend through to the tally: `computeQvTally` + // clamps and weighs by this (GAP-C), never the forgeable CRDT credits. + credits: payload.credits, castAt: entry.lamportTs, }); } diff --git a/src/miniapps/assembly/AssemblyScreen.module.css b/src/miniapps/assembly/AssemblyScreen.module.css index 1c3287f..d92a769 100644 --- a/src/miniapps/assembly/AssemblyScreen.module.css +++ b/src/miniapps/assembly/AssemblyScreen.module.css @@ -266,37 +266,11 @@ line-height: 1.4; } -.voteRow { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 0.5rem; - padding-bottom: 0.75rem; - border-bottom: 1px solid var(--color-border); -} - -.voteButton, -.voteButtonActive { - padding: 0.4rem 0.9rem; - border-radius: 999px; - border: 1px solid var(--color-border); - background: #ffffff; - font-size: 0.78rem; - font-weight: 700; - color: var(--color-ink); - cursor: pointer; -} - -.voteButtonActive { - background: var(--color-accent); - border-color: var(--color-accent); - color: #ffffff; -} - .voteStatus { margin-left: auto; font-size: 0.72rem; color: var(--color-ink-faint); + align-self: center; } .qvCard { @@ -315,6 +289,8 @@ .delegateForm { display: flex; + flex-wrap: wrap; + align-items: center; gap: 0.5rem; } @@ -339,12 +315,14 @@ .ballotRow { display: flex; + align-items: center; + flex-wrap: wrap; gap: 0.5rem; } -.ballotButton { - flex: 1; - padding: 0.4rem; +.ballotButton, +.ballotButtonActive { + padding: 0.4rem 0.9rem; border-radius: 10px; border: 1px dashed var(--color-accent); background: #f0f6ff; @@ -354,6 +332,18 @@ cursor: pointer; } +.ballotButtonActive { + background: var(--color-accent); + border-style: solid; + border-color: var(--color-accent); + color: #ffffff; +} + +.ballotButton:disabled { + opacity: 0.5; + cursor: not-allowed; +} + .tally { display: flex; gap: 0.75rem; diff --git a/src/miniapps/assembly/AssemblyScreen.test.tsx b/src/miniapps/assembly/AssemblyScreen.test.tsx index b3cc4d2..bdf4ef0 100644 --- a/src/miniapps/assembly/AssemblyScreen.test.tsx +++ b/src/miniapps/assembly/AssemblyScreen.test.tsx @@ -5,7 +5,6 @@ import userEvent from "@testing-library/user-event"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import * as Y from "yjs"; import { - castVote, putProposal, putRosterEntry, type AssemblyDoc, @@ -154,10 +153,10 @@ describe("AssemblyScreen (happy path - seeded proposal, direct + delegated votes status: "open", }); - // Direct (non-QV) vote, cast before render to exercise real replay. - castVote(assembly, { proposalId: "p1", voterId: meId, choice: "yes", castAt: 2 }); - // Delegated QV vote: "me" delegates to Bob, and Bob casts the QV ballot. + // "me"'s enrollment row is DELIBERATELY credits:4 (not 9) to prove the + // tally ignores the forgeable CRDT value - "me" still delegates her full + // fixed civic budget sqrt(9)=3, never sqrt(4)=2 (GAP-C). putResidentCredit(governance, { proposalId: "p1", residentId: meId, credits: 4 }); putResidentCredit(governance, { proposalId: "p1", residentId: "delegate-bob", credits: 9 }); @@ -171,15 +170,19 @@ describe("AssemblyScreen (happy path - seeded proposal, direct + delegated votes expect(screen.getByTestId("assembly-roster-delegate-bob")).toHaveTextContent("Bob"); expect(screen.getByTestId("assembly-proposal-p1")).toHaveTextContent("Repair the shared well pump"); - expect(screen.getByTestId("assembly-vote-status-p1")).toHaveTextContent("You voted Yes"); + // Delegation is a single GLOBAL control (keyed by delegator, applies to + // every proposal) - not the old per-proposal widget that misrepresented + // global state as per-proposal. const user = userEvent.setup(); - await user.selectOptions(screen.getByTestId("assembly-delegate-select-p1"), "delegate-bob"); - await user.click(screen.getByTestId("assembly-delegate-submit-p1")); + await user.selectOptions(screen.getByTestId("assembly-delegate-select"), "delegate-bob"); + await user.click(screen.getByTestId("assembly-delegate-submit")); await waitFor(() => { - expect(screen.getByTestId("assembly-delegation-status-p1")).toHaveTextContent("Delegated to"); + expect(screen.getByTestId("assembly-delegation-status")).toHaveTextContent("Delegated to"); }); + // While delegated, the direct ballot control is honestly disabled. + expect(screen.getByTestId("assembly-qv-ballot-yes-p1")).toBeDisabled(); // Bob's own QV ballot is what "me"'s delegated vote resolves to. Bob is a // seeded demo resident, not this device's live identity, so his ballot is @@ -212,9 +215,10 @@ describe("AssemblyScreen (happy path - seeded proposal, direct + delegated votes expect(screen.getByTestId("assembly-tally-abstain-p1")).toHaveTextContent( `Abstain ${expectedTally.tally.abstain.toFixed(2)}`, ); - // sqrt(4) + sqrt(9) = 2 + 3 = 5, both delegated-through and direct Bob - // ballot count toward "yes" exactly once each (no double count). - expect(expectedTally.tally.yes).toBe(5); + // me delegates her full fixed civic budget sqrt(9)=3 (NOT sqrt(her + // forgeable residentCredits=4)=2) onto Bob's YES, and Bob's own signed + // ballot adds sqrt(9)=3: 3 + 3 = 6, each counted once (no double count). + expect(expectedTally.tally.yes).toBe(6); await user.type( screen.getByTestId("testimony-text-input"), @@ -275,13 +279,14 @@ describe("AssemblyScreen (WebRTC sync toggle - todo 11)", () => { expect(toggle.checked).toBe(false); expect(screen.queryByTestId("assembly-peer-count")).not.toBeInTheDocument(); - // Fully offline/local-first behavior (roster + direct vote) still works - // with the toggle untouched. + // Fully offline/local-first behavior (roster + the single signed QV + // ballot control) still works with the toggle untouched - casting a + // ballot is a local Event Log append, no network. await waitFor(() => { expect(screen.getByTestId(`assembly-roster-${meId}`)).toHaveTextContent("Me"); }); const user = userEvent.setup(); - await user.click(screen.getByTestId("assembly-vote-yes-p-offline")); + await user.click(screen.getByTestId("assembly-qv-ballot-yes-p-offline")); await waitFor(() => { expect(screen.getByTestId("assembly-vote-status-p-offline")).toHaveTextContent("You voted Yes"); }); @@ -575,7 +580,7 @@ describe("AssemblyScreen (create-proposal / add-resident affordances - todo 12)" expect(screen.getByTestId("assembly-roster-empty")).toBeInTheDocument(); }); - it("casting a direct vote and a QV ballot on a newly-created proposal updates the vote status and QV tally live", async () => { + it("casting the single QV ballot control on a newly-created proposal updates the vote status and QV tally live", async () => { const { publicKey } = await init(); const meId = toAccountId(publicKey); const dbName = uniqueDbName("create-proposal-vote"); @@ -607,20 +612,85 @@ describe("AssemblyScreen (create-proposal / add-resident affordances - todo 12)" expect(article).not.toBeNull(); const proposalId = article!.getAttribute("data-testid")!.replace("assembly-proposal-", ""); - // Direct vote: vote-status readout updates live. - await user.click(screen.getByTestId(`assembly-vote-yes-${proposalId}`)); - await waitFor(() => { - expect(screen.getByTestId(`assembly-vote-status-${proposalId}`)).toHaveTextContent("You voted Yes"); - }); - - // QV tally: creating the proposal above already granted `meId` the - // DEFAULT_QV_CREDITS budget (9), so casting the real QV ballot through the - // UI - now a signed Event Log append, not a CRDT write - moves the tally - // from 0.00 to sqrt(9) = 3.00. + // ONE voting control: the signed QV ballot. Its tally starts at 0.00 and + // the vote-status readout is derived from that SAME signed ballot - there + // is no longer a separate dead CRDT direct-vote row. expect(screen.getByTestId(`assembly-tally-yes-${proposalId}`)).toHaveTextContent("Yes 0.00"); + expect(screen.getByTestId(`assembly-vote-status-${proposalId}`)).toHaveTextContent( + "No vote cast yet", + ); + + // Creating the proposal above already granted `meId` the DEFAULT_QV_CREDITS + // budget (9), so casting the real QV ballot through the UI - a signed Event + // Log append, not a CRDT write - moves the tally from 0.00 to sqrt(9)=3.00 + // AND updates the ballot-derived status. await user.click(screen.getByTestId(`assembly-qv-ballot-yes-${proposalId}`)); await waitFor(() => { expect(screen.getByTestId(`assembly-tally-yes-${proposalId}`)).toHaveTextContent("Yes 3.00"); }); + expect(screen.getByTestId(`assembly-vote-status-${proposalId}`)).toHaveTextContent( + "You voted Yes", + ); + }); +}); + +describe("AssemblyScreen (global delegation + revoke - GAP-A)", () => { + it("delegating disables the direct ballot control globally, shows the single global delegation status, and revoking re-enables it", async () => { + const { publicKey } = await init(); + const meId = toAccountId(publicKey); + const dbName = uniqueDbName("delegation-revoke"); + + const { assembly, governance }: { assembly: AssemblyDoc; governance: GovernanceDoc } = + getAssemblyEngineForTesting(dbName); + putRosterEntry(assembly, { id: meId, residentId: meId, displayName: "Me", joinedAt: 0, active: true }); + putRosterEntry(assembly, { + id: "delegate-bob", + residentId: "delegate-bob", + displayName: "Bob", + joinedAt: 0, + active: true, + }); + putProposal(assembly, { + id: "p1", + title: "Repair the shared well pump", + description: "The pump has been making noise for a week.", + authorId: meId, + createdAt: 1, + status: "open", + }); + putResidentCredit(governance, { proposalId: "p1", residentId: meId, credits: 9 }); + putResidentCredit(governance, { proposalId: "p1", residentId: "delegate-bob", credits: 9 }); + + render(); + await waitFor(() => { + expect(screen.getByTestId("assembly-sync-indicator")).toHaveTextContent("Synced"); + }); + + // Before delegating: the single QV ballot control is enabled and the + // global delegation picker is present. + expect(screen.getByTestId("assembly-qv-ballot-yes-p1")).toBeEnabled(); + expect(screen.getByTestId("assembly-delegate-select")).toBeInTheDocument(); + + const user = userEvent.setup(); + await user.selectOptions(screen.getByTestId("assembly-delegate-select"), "delegate-bob"); + await user.click(screen.getByTestId("assembly-delegate-submit")); + + // Delegated: ONE global delegation status (not a per-proposal widget), and + // the direct ballot control is honestly disabled on the proposal. + await waitFor(() => { + expect(screen.getByTestId("assembly-delegation-status")).toHaveTextContent("Delegated to"); + }); + expect(screen.getAllByTestId("assembly-delegation-status")).toHaveLength(1); + expect(screen.getByTestId("assembly-qv-ballot-yes-p1")).toBeDisabled(); + expect(screen.getByTestId("assembly-vote-status-p1")).toHaveTextContent("Delegated to"); + expect(screen.queryByTestId("assembly-delegate-select")).not.toBeInTheDocument(); + + // Revoke: the direct ballot control is enabled again and the picker returns. + await user.click(screen.getByTestId("assembly-revoke-delegation")); + await waitFor(() => { + expect(screen.getByTestId("assembly-qv-ballot-yes-p1")).toBeEnabled(); + }); + expect(screen.getByTestId("assembly-delegate-select")).toBeInTheDocument(); + expect(screen.queryByTestId("assembly-revoke-delegation")).not.toBeInTheDocument(); }); }); diff --git a/src/miniapps/assembly/AssemblyScreen.tsx b/src/miniapps/assembly/AssemblyScreen.tsx index 272c4dc..7acd272 100644 --- a/src/miniapps/assembly/AssemblyScreen.tsx +++ b/src/miniapps/assembly/AssemblyScreen.tsx @@ -29,11 +29,11 @@ export function AssemblyScreen({ dbName }: AssemblyScreenProps = {}) { synced, proposals, roster, - votes, + ballots, delegations, tallyFor, - castDirectVote, delegate, + revokeDelegation, castBallot, createProposal, addResident, @@ -44,7 +44,7 @@ export function AssemblyScreen({ dbName }: AssemblyScreenProps = {}) { setSyncRoomCode, } = useAssemblyEngine(dbName); - const [delegateChoice, setDelegateChoice] = useState>({}); + const [delegateChoice, setDelegateChoice] = useState(""); const [joinCodeInput, setJoinCodeInput] = useState(""); const [syncCodeQrDataUrl, setSyncCodeQrDataUrl] = useState(); @@ -70,12 +70,16 @@ export function AssemblyScreen({ dbName }: AssemblyScreenProps = {}) { const [proposalDescription, setProposalDescription] = useState(""); const [proposalError, setProposalError] = useState(null); - const myVoteByProposal = new Map( - votes - .filter((vote) => vote.voterId === myAccountId) - .map((vote) => [vote.proposalId, vote.choice]), + // The local resident's own choice is derived from their SIGNED ballot on the + // Event Log (the single real voting path), never the old dead CRDT `votes` + // map that `castDirectVote` used to write and nothing ever tallied. + const myBallotByProposal = new Map( + ballots + .filter((ballot) => ballot.voterId === myAccountId) + .map((ballot) => [ballot.proposalId, ballot.choice]), ); const myDelegation = delegations.find((d) => d.delegatorId === myAccountId); + const otherResidents = roster.filter((entry) => entry.residentId !== myAccountId); // QV ballots and delegations are authority-bearing: gate them on actually // being on the roster, not merely on having a local identity (plan todo 7). // A credit budget is only granted to roster members, so an un-enrolled @@ -84,11 +88,16 @@ export function AssemblyScreen({ dbName }: AssemblyScreenProps = {}) { const isEnrolled = myAccountId !== undefined && roster.some((entry) => entry.residentId === myAccountId); - function handleDelegateSubmit(proposalId: string, event: FormEvent) { + function handleDelegateSubmit(event: FormEvent) { event.preventDefault(); - const delegateId = delegateChoice[proposalId]; - if (!isEnrolled || myAccountId === undefined || !delegateId) return; - delegate(myAccountId, delegateId); + if (!isEnrolled || myAccountId === undefined || !delegateChoice) return; + delegate(myAccountId, delegateChoice); + setDelegateChoice(""); + } + + function handleRevokeDelegation() { + if (myAccountId === undefined) return; + revokeDelegation(myAccountId); } function handleJoinCodeSubmit(event: FormEvent) { @@ -292,6 +301,63 @@ export function AssemblyScreen({ dbName }: AssemblyScreenProps = {}) { )} +
+
Your delegation
+ {!isEnrolled ? ( +

+ Add yourself to the roster above to delegate your Assembly vote. +

+ ) : myDelegation ? ( +
+

+ Delegated to {shortId(myDelegation.delegateId)} - your delegate's choice counts for + you on every proposal until you revoke it. +

+ +
+ ) : ( + <> +
+ + +
+

+ Delegation is global: it applies to every proposal at once, not one at a time. While + delegated you cannot also cast your own ballot - revoke first to vote directly. +

+ + )} +
+
{proposals.length === 0 ? (

@@ -300,8 +366,14 @@ export function AssemblyScreen({ dbName }: AssemblyScreenProps = {}) { ) : ( proposals.map((proposal) => { const tally = tallyFor(proposal.id); - const myVote = myVoteByProposal.get(proposal.id); - const otherResidents = roster.filter((entry) => entry.residentId !== myAccountId); + const myBallot = myBallotByProposal.get(proposal.id); + // ONE voting control: the signed QV ballot (the only path the tally + // reads). Disabled when not enrolled, or when this resident has a + // global delegation active - delegating and casting your own ballot + // are mutually exclusive, so the direct affordance is honestly off + // while delegated. The old inert `castDirectVote` CRDT row that + // never moved any tally is gone (GAP-A dead UI). + const canVoteDirectly = isEnrolled && myDelegation === undefined; return (

{proposal.description}

-
- {(["yes", "no", "abstain"] as VoteChoice[]).map((choice) => ( - + ))} + - {CHOICE_LABEL[choice]} - - ))} - - {myVote ? `You voted ${CHOICE_LABEL[myVote]}` : "No vote cast yet"} - -
- -
- {myDelegation ? ( + {myDelegation + ? `Delegated to ${shortId(myDelegation.delegateId)}` + : myBallot + ? `You voted ${CHOICE_LABEL[myBallot]}` + : "No vote cast yet"} + +
+ {!isEnrolled && (

- Delegated to {shortId(myDelegation.delegateId)} + Add yourself to the roster above to cast a weighted ballot or delegate.

- ) : ( - <> -
handleDelegateSubmit(proposal.id, event)} - > - - -
- -
- {(["yes", "no", "abstain"] as VoteChoice[]).map((choice) => ( - - ))} -
- {!isEnrolled && ( -

- Add yourself to the roster above to cast a weighted ballot or delegate. -

- )} - )}
diff --git a/src/miniapps/assembly/governanceEvents.test.ts b/src/miniapps/assembly/governanceEvents.test.ts index 83e5929..498d948 100644 --- a/src/miniapps/assembly/governanceEvents.test.ts +++ b/src/miniapps/assembly/governanceEvents.test.ts @@ -133,25 +133,28 @@ describe("extractQvBallots verify-at-read binding (pure, no network)", () => { }); describe("signed QV ballots through the Event Log (todo 7, GAP-5)", () => { - it("a validly-signed local ballot moves the correct tally bucket by exactly sqrt(credits)", async () => { + it("weighs a validly-signed local ballot by sqrt of its OWN signed credit spend, not the CRDT budget", async () => { const { publicKey } = await init(); const meId = toAccountId(publicKey); const proposalId = "p-sqrt"; - await postQvBallot({ proposalId, voterId: meId, choice: "no", credits: 16 }); + // Ballot attests a 4-credit spend; the (forgeable) CRDT membership row + // below says 9. Weight must come from the SIGNED ballot: sqrt(4)=2, not + // sqrt(9)=3 - proving the tally reads the signed credits, never the CRDT. + await postQvBallot({ proposalId, voterId: meId, choice: "no", credits: 4 }); const ballots = extractQvBallots(await readAll()); expect(ballots).toHaveLength(1); - expect(ballots[0]).toMatchObject({ voterId: meId, choice: "no" }); + expect(ballots[0]).toMatchObject({ voterId: meId, choice: "no", credits: 4 }); const tally = computeQvTally({ proposalId, - residentCredits: [{ id: meId, proposalId, residentId: meId, credits: 16 }], + residentCredits: [{ id: meId, proposalId, residentId: meId, credits: 9 }], ballots, delegations: [], }); - // sqrt(16) = 4 lands entirely on NO, nothing else moves. - expect(tally.tally).toEqual({ yes: 0, no: 4, abstain: 0 }); + // sqrt(4) = 2 lands entirely on NO, nothing else moves. + expect(tally.tally).toEqual({ yes: 0, no: 2, abstain: 0 }); }); it("rejects a live ballot that claims another resident's id (no demo-fixture flag) at read", async () => { diff --git a/src/miniapps/assembly/useAssemblyEngine.ts b/src/miniapps/assembly/useAssemblyEngine.ts index cb5afb4..a210edc 100644 --- a/src/miniapps/assembly/useAssemblyEngine.ts +++ b/src/miniapps/assembly/useAssemblyEngine.ts @@ -1,16 +1,13 @@ import { useEffect, useMemo, useReducer, useState } from "react"; import { - castVote, listProposals, listRoster, - listVotes, openPersistedAssemblyDoc, putProposal, putRosterEntry, type AssemblyDoc, type ProposalRecord, type RosterEntry, - type VoteRecord, } from "../../lib/assembly.ts"; import { computeQvTally, @@ -18,10 +15,12 @@ import { listResidentCredits, putDelegation, putResidentCredit, + removeDelegation, wrapGovernanceDoc, DEFAULT_QV_CREDITS, type DelegationRecord, type GovernanceDoc, + type QvBallotRecord, type QvTallyResult, type VoteChoice, } from "../../lib/governance.ts"; @@ -187,11 +186,18 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): { synced: boolean; proposals: ProposalRecord[]; roster: RosterEntry[]; - votes: VoteRecord[]; + /** Every authentic QV ballot reconstructed from the signed Event Log + * (verified at read in `extractQvBallots`). The single source the UI uses + * both for the live tally and for the local resident's own "your choice" + * indicator - the forgeable CRDT `votes` map (the old dead direct-vote + * path) is no longer read or written. */ + ballots: QvBallotRecord[]; delegations: DelegationRecord[]; tallyFor: (proposalId: string) => QvTallyResult; - castDirectVote: (proposalId: string, voterId: string, choice: VoteChoice) => void; delegate: (delegatorId: string, delegateId: string) => void; + /** Revokes the local resident's global delegation so their own signed + * ballot counts again (via `removeDelegation`). */ + revokeDelegation: (delegatorId: string) => void; /** Casts the local resident's own QV ballot by signing it onto the Event * Log (plan todo 7, GAP-5) via `postQvBallot` - NOT a plain CRDT write any * more, so a peer can no longer forge another resident's vote. Resolves @@ -309,24 +315,21 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): { const eventLogEntries = useEventLogEntries(); const proposals = listProposals(bound.assembly); const roster = listRoster(bound.assembly); - const votes = listVotes(bound.assembly); const delegations = listDelegations(bound.governance); + // Ballots come from the replayed signed Event Log (verified at read in + // `extractQvBallots`), never the forgeable CRDT. Computed once per render so + // the tally and the local resident's own-choice indicator share one source. + const ballots = extractQvBallots(eventLogEntries); function tallyFor(proposalId: string): QvTallyResult { return computeQvTally({ proposalId, residentCredits: listResidentCredits(bound.governance), - // Ballots now come from the replayed signed Event Log (verified at read - // in `extractQvBallots`), never the forgeable CRDT `listQvBallots`. - ballots: extractQvBallots(eventLogEntries), + ballots, delegations: listDelegations(bound.governance), }); } - function castDirectVote(proposalId: string, voterId: string, choice: VoteChoice): void { - castVote(bound.assembly, { proposalId, voterId, choice, castAt: Date.now() }); - } - function delegate(delegatorId: string, delegateId: string): void { putDelegation(bound.governance, { id: delegatorId, @@ -336,6 +339,10 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): { }); } + function revokeDelegation(delegatorId: string): void { + removeDelegation(bound.governance, delegatorId); + } + async function castBallot( proposalId: string, voterId: string, @@ -399,11 +406,11 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): { synced, proposals, roster, - votes, + ballots, delegations, tallyFor, - castDirectVote, delegate, + revokeDelegation, castBallot, createProposal, addResident,