fix(assembly): grant QV credit on the real resident/proposal lifecycle and sign ballots at the event log

This commit is contained in:
OmO Orchestrator committed 2026-11-18 14:50:40 -05:00
1 parent 55366b7de1
commit 7de89e1efb
8 files changed
+586 -77

No files matched your search

+11
View File
@@ -360,6 +360,17 @@ export function AdminSeedPanel({ assemblyDbName }: AdminSeedPanelProps = {}) {
seed.* events through the exact same Event Log path as manual entry
above. Demo configuration only - never presented as live activity.
</p>
<p
data-testid="assembly-demo-fixture-disclaimer"
style={{ color: "#8a6d00", fontSize: 12 }}
>
Note: any seeded Assembly roster, QV credits, and ballots are
demo-fixture data signed by this one device's single identity. They
are exempt from the live ballot-signature verification (which binds a
real ballot's voterId to the key that signed it) and are NOT a
security guarantee - only ballots cast live through the Assembly
screen by your own identity are verified and would reject a forgery.
</p>
<button type="button" onClick={handleLoadDemo} disabled={demoLoading}>
Load Hollow demo
</button>
+28 -9
View File
@@ -1,15 +1,13 @@
import { describe, expect, it } from "vitest";
import { castVote, createAssemblyDoc, putProposal, type AssemblyDoc } from "./assembly.ts";
import {
castQvBallot,
computeQvTally,
listDelegations,
listQvBallots,
listResidentCredits,
putDelegation,
putResidentCredit,
qvBallotKey,
resolveEffectiveVoter,
tallyProposal,
wrapGovernanceDoc,
type DelegationRecord,
type QvBallotRecord,
@@ -69,6 +67,20 @@ const HAPPY_DIRECT_BALLOTS: Record<string, "yes" | "no" | "abstain"> = {
const EXPECTED_HAPPY_TALLY = { yes: 23, no: 25, abstain: 7 };
/** 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. */
const HAPPY_BALLOTS: QvBallotRecord[] = Object.entries(HAPPY_DIRECT_BALLOTS).map(
([voterId, choice]) => ({
id: qvBallotKey(PROPOSAL_ID, voterId),
proposalId: PROPOSAL_ID,
voterId,
choice,
castAt: 1,
}),
);
function buildHappyPathGovernance(): AssemblyDoc {
const assembly = createAssemblyDoc();
putProposal(assembly, {
@@ -84,9 +96,6 @@ function buildHappyPathGovernance(): AssemblyDoc {
for (const [residentId, credits] of Object.entries(HAPPY_CREDITS)) {
putResidentCredit(governance, { proposalId: PROPOSAL_ID, residentId, credits });
}
for (const [voterId, choice] of Object.entries(HAPPY_DIRECT_BALLOTS)) {
castQvBallot(governance, { proposalId: PROPOSAL_ID, voterId, choice, castAt: 1 });
}
for (const [delegatorId, delegateId] of Object.entries(HAPPY_DELEGATIONS)) {
putDelegation(governance, {
id: delegatorId,
@@ -156,7 +165,12 @@ describe("governance: quadratic-voting tally", () => {
const assembly = buildHappyPathGovernance();
const governance = wrapGovernanceDoc(assembly);
const result = tallyProposal(governance, { id: PROPOSAL_ID });
const result = computeQvTally({
proposalId: PROPOSAL_ID,
residentCredits: listResidentCredits(governance),
ballots: HAPPY_BALLOTS,
delegations: listDelegations(governance),
});
expect(result.tally).toEqual(EXPECTED_HAPPY_TALLY);
expect(result.participants).toHaveLength(10);
@@ -267,10 +281,15 @@ describe("governance: integration with the assembly.ts CRDT proposal set (todo 2
const governance = wrapGovernanceDoc(assembly);
expect(listResidentCredits(governance)).toHaveLength(10);
expect(listQvBallots(governance)).toHaveLength(5);
expect(HAPPY_BALLOTS).toHaveLength(5);
expect(listDelegations(governance)).toHaveLength(5);
const result = tallyProposal(governance, { id: PROPOSAL_ID });
const result = computeQvTally({
proposalId: PROPOSAL_ID,
residentCredits: listResidentCredits(governance),
ballots: HAPPY_BALLOTS,
delegations: listDelegations(governance),
});
expect(result.tally).toEqual(EXPECTED_HAPPY_TALLY);
});
});
+29 -39
View File
@@ -1,5 +1,5 @@
import type * as Y from "yjs";
import type { AssemblyDoc, ProposalRecord } from "./assembly.ts";
import type { AssemblyDoc } from "./assembly.ts";
import { assertFiniteNumber } from "./validation.ts";
/**
@@ -7,12 +7,20 @@ import { assertFiniteNumber } from "./validation.ts";
* quadratic-voting (QV) tally, layered on top of the `AssemblyDoc` CRDT
* proposal set from todo 22 (`src/lib/assembly.ts`).
*
* This module does not touch `assembly.ts`. It adds three *new* top-level
* `Y.Map` shared types to the same `Y.Doc` - `delegations`, `residentCredits`,
* `qvBallots` - following the exact snapshot-reader / last-writer-wins
* This module does not touch `assembly.ts`. It adds two *new* top-level
* `Y.Map` shared types to the same `Y.Doc` - `delegations` and
* `residentCredits` - following the exact snapshot-reader / last-writer-wins
* pattern `assembly.ts` already established for `proposals` / `roster` /
* `votes`. Proposals themselves keep coming from `assembly.ts`; this module
* is strictly additive.
* `votes`. Proposals themselves keep coming from `assembly.ts`.
*
* The ballot itself - the one authority-bearing action a tally is computed
* from - deliberately does NOT live in this CRDT. It moved onto the
* append-only signed Event Log (`src/lib/governanceEvents.ts`, plan todo 7,
* GAP-5): a plain `Y.Map` ballot write was unsigned and forgeable by any
* peer sharing a sync code, so `computeQvTally` is now fed `QvBallotRecord`s
* reconstructed and verified-at-read from the log, never from this doc.
* `delegations` and `residentCredits` stay here so they can still be edited
* live over P2P.
*
* Quadratic voting formula used (the real documented QV formula, not an
* approximation): a voter who spends `credits` voice credits on a single
@@ -38,6 +46,18 @@ import { assertFiniteNumber } from "./validation.ts";
export type VoteChoice = "yes" | "no" | "abstain";
/**
* The quadratic-voting credit budget every roster member is granted for a
* proposal when they are enrolled while the proposal is open, or when a new
* proposal is created (see `useAssemblyEngine`'s `addResident` /
* `createProposal`). `sqrt(9) = 3`, so a single direct ballot moves its
* tally bucket by a clean, hand-checkable 3.00 - the value the Assembly
* screen and the demo both show once a resident actually votes (the fix for
* GAP-5's permanently-0.00 tally: before this, `putResidentCredit` had zero
* production callers, so no resident ever had any credits to weight).
*/
export const DEFAULT_QV_CREDITS = 9;
/** One resident's liquid-democracy delegation: "I delegate my vote to
* `delegateId`." Keyed by `delegatorId` so a resident has at most one
* active delegation per CRDT map semantics (a second `putDelegation` call
@@ -80,13 +100,13 @@ export function qvBallotKey(proposalId: string, voterId: string): string {
return `${proposalId}:${voterId}`;
}
/** The three governance-specific CRDT shared types, layered on an existing
* `AssemblyDoc`'s `Y.Doc`. */
/** The governance-specific CRDT shared types, layered on an existing
* `AssemblyDoc`'s `Y.Doc`. Ballots are not here - they live on the signed
* Event Log (see this module's header and `governanceEvents.ts`). */
export interface GovernanceDoc {
doc: Y.Doc;
delegations: Y.Map<DelegationRecord>;
residentCredits: Y.Map<ResidentCreditRecord>;
qvBallots: Y.Map<QvBallotRecord>;
}
/** Wraps an `AssemblyDoc`'s underlying `Y.Doc` with the governance shared
@@ -97,7 +117,6 @@ export function wrapGovernanceDoc(assembly: AssemblyDoc): GovernanceDoc {
doc: assembly.doc,
delegations: assembly.doc.getMap<DelegationRecord>("delegations"),
residentCredits: assembly.doc.getMap<ResidentCreditRecord>("residentCredits"),
qvBallots: assembly.doc.getMap<QvBallotRecord>("qvBallots"),
};
}
@@ -115,15 +134,6 @@ export function putResidentCredit(
governance.residentCredits.set(id, { ...record, id });
}
/** Casts (or replaces) a resident's own direct QV ballot. */
export function castQvBallot(
governance: GovernanceDoc,
ballot: Omit<QvBallotRecord, "id"> & { id?: string },
): void {
const id = ballot.id ?? qvBallotKey(ballot.proposalId, ballot.voterId);
governance.qvBallots.set(id, { ...ballot, id });
}
/** Snapshot readers - plain arrays, no live Yjs references leak out. */
export function listDelegations(governance: GovernanceDoc): DelegationRecord[] {
return [...governance.delegations.values()];
@@ -133,10 +143,6 @@ export function listResidentCredits(governance: GovernanceDoc): ResidentCreditRe
return [...governance.residentCredits.values()];
}
export function listQvBallots(governance: GovernanceDoc): QvBallotRecord[] {
return [...governance.qvBallots.values()];
}
/** Result of resolving one resident's effective voter through the
* delegation graph. */
export interface DelegationResolution {
@@ -280,19 +286,3 @@ export function computeQvTally(params: {
return { proposalId, tally, participants };
}
/** Convenience: reads the three governance CRDT maps straight off a
* `GovernanceDoc` and computes the QV tally for `proposalId`. The
* `ProposalRecord` type is imported purely for documentation/typing of the
* `proposalId` relationship to `assembly.ts`'s proposal set - this function
* never mutates or reads `assembly.proposals` itself. */
export function tallyProposal(
governance: GovernanceDoc,
proposal: Pick<ProposalRecord, "id">,
): QvTallyResult {
return computeQvTally({
proposalId: proposal.id,
residentCredits: listResidentCredits(governance),
ballots: listQvBallots(governance),
delegations: listDelegations(governance),
});
}
+143
View File
@@ -0,0 +1,143 @@
import { append, type StoredEventLogEntry } from "./eventlog.ts";
import { qvBallotKey, type QvBallotRecord, type VoteChoice } from "./governance.ts";
import { toAccountId } from "../shell/accountId.ts";
/**
* Event Log <-> Assembly quadratic-voting ballot adapter (plan todo 7, GAP-5).
*
* Before this module, a QV ballot was a plain `Y.Map` write in
* `governance.ts` (`castQvBallot`): every peer on a shared sync code could
* forge any resident's vote, and nothing signed it. This module moves the
* one authority-bearing action - casting a ballot - onto the append-only
* signed Event Log, exactly like `healthpostEvents.ts` moves a symptom
* self-report onto it: a payload-type constant + a type guard + a
* `post*`/`extract*` pair. Proposals, roster, delegations and credit budgets
* deliberately stay in the Yjs CRDT (`assembly.ts` / `governance.ts`) so they
* can still be edited live over P2P; only the ballot - the thing a tally is
* actually computed from - becomes a signed, replay-derived record.
*
* VERIFY AT READ (never trust persistence): the Event Log already verifies
* every entry's Ed25519 signature against its `authorPubkey` before it is
* ever written (`appendEntry` in `eventlog.ts`), so an entry that reaches
* `extractQvBallots` is guaranteed to have been signed by the key it names
* as author. `extractQvBallots` adds the ballot-specific authority check on
* top of that, computed fresh from the entry at read time rather than trusted
* from a stored field: a live ballot only counts if the author key that
* signed it resolves (via `toAccountId`, the exact derivation the wallet and
* roster use) to the SAME account the ballot claims as its `voterId`. A
* ballot signed by one identity but claiming to be another resident's vote is
* a forgery and is dropped here, before it can reach `computeQvTally`.
*
* DEMO-FIXTURE EXEMPTION (clearly labeled, NOT a security guarantee): one
* physical device holds exactly one Ed25519 keypair, so strict
* `voterId === toAccountId(authorPubkey)` verification would mean only the
* live local user's OWN ballot could ever validate on a single demo machine -
* which would make the bundled multi-resident demo roster impossible to tally
* on one laptop (the GAP-5 fix would silently re-break the video's Act 3). A
* ballot explicitly marked `demoFixture: true` is therefore exempted from the
* voter-binding check: it is admin-seeded demo data, signed by whatever local
* 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.
*/
export const QV_BALLOT_PAYLOAD_TYPE = "governance.qvBallot" as const;
const VOTE_CHOICES: readonly VoteChoice[] = ["yes", "no", "abstain"];
/** The Event Log payload shape one QV ballot is signed over. */
export interface QvBallotPayload {
type: typeof QV_BALLOT_PAYLOAD_TYPE;
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. */
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
* real ballot cast through the UI. */
demoFixture?: boolean;
}
function isQvBallotPayload(payload: unknown): payload is QvBallotPayload {
if (typeof payload !== "object" || payload === null) return false;
const p = payload as Record<string, unknown>;
return (
p.type === QV_BALLOT_PAYLOAD_TYPE &&
typeof p.proposalId === "string" &&
typeof p.voterId === "string" &&
typeof p.choice === "string" &&
(VOTE_CHOICES as readonly string[]).includes(p.choice) &&
typeof p.credits === "number" &&
(p.demoFixture === undefined || typeof p.demoFixture === "boolean")
);
}
/** Input to `postQvBallot`: everything the signed payload carries except its
* `type` discriminant. */
export interface PostQvBallotInput {
proposalId: string;
voterId: string;
choice: VoteChoice;
credits: number;
/** See `QvBallotPayload.demoFixture`. Omit for a real live ballot. */
demoFixture?: boolean;
}
/**
* Signs and appends one QV ballot to the Event Log. The local identity's key
* signs it (via `append`), so a live ballot's `voterId` must be the local
* account for it to survive `extractQvBallots`' binding check - a forged
* ballot naming someone else is rejected at read. Admin-seeded demo ballots
* pass `demoFixture: true` to opt out of that binding (see the module header).
*/
export async function postQvBallot(ballot: PostQvBallotInput): Promise<StoredEventLogEntry> {
const payload: QvBallotPayload = {
type: QV_BALLOT_PAYLOAD_TYPE,
proposalId: ballot.proposalId,
voterId: ballot.voterId,
choice: ballot.choice,
credits: ballot.credits,
...(ballot.demoFixture ? { demoFixture: true as const } : {}),
};
return append(payload);
}
/**
* Reconstructs every authentic QV ballot from a replayed Event Log read, ready
* to feed straight into the unchanged `computeQvTally` in place of the old
* CRDT-only `listQvBallots`. Entries whose payload is not a QV ballot are
* skipped; a live ballot whose author key does not resolve to its claimed
* `voterId` (a forgery) is dropped by the verify-at-read binding check above;
* admin-seeded `demoFixture` ballots are kept. When the same resident cast
* more than one ballot on a proposal (e.g. they changed their vote, or an
* unmounted-mid-write retry re-appended it), the later Lamport-ordered entry
* wins and no vote is double-counted - the exact last-writer-wins semantics
* the CRDT `qvBallotKey` map had, now derived deterministically from the log
* so a cold replay and a live session always agree.
*/
export function extractQvBallots(entries: StoredEventLogEntry[]): QvBallotRecord[] {
const byKey = new Map<string, QvBallotRecord>();
for (const entry of entries) {
const payload = entry.payload;
if (!isQvBallotPayload(payload)) continue;
if (!payload.demoFixture && toAccountId(entry.authorPubkey) !== payload.voterId) {
continue;
}
const key = qvBallotKey(payload.proposalId, payload.voterId);
byKey.set(key, {
id: key,
proposalId: payload.proposalId,
voterId: payload.voterId,
choice: payload.choice,
castAt: entry.lamportTs,
});
}
return [...byKey.values()];
}
+28 -12
View File
@@ -12,16 +12,16 @@ import {
} from "../../lib/assembly.ts";
import { db } from "../../lib/db.ts";
import { init } from "../../lib/identity.ts";
import { readAll } from "../../lib/eventlog.ts";
import { toAccountId } from "../../shell/accountId.ts";
import {
castQvBallot,
computeQvTally,
listDelegations,
listQvBallots,
listResidentCredits,
putResidentCredit,
type GovernanceDoc,
} from "../../lib/governance.ts";
import { extractQvBallots, postQvBallot } from "../../lib/governanceEvents.ts";
import { getAssemblyEngineForTesting, setAssemblySyncTransportOverrideForTesting } from "./useAssemblyEngine.ts";
import { AssemblyScreen } from "./AssemblyScreen.tsx";
@@ -181,13 +181,23 @@ describe("AssemblyScreen (happy path - seeded proposal, direct + delegated votes
expect(screen.getByTestId("assembly-delegation-status-p1")).toHaveTextContent("Delegated to");
});
// Bob's own QV ballot is what "me"'s delegated vote resolves to.
castQvBallot(governance, { proposalId: "p1", voterId: "delegate-bob", choice: "yes", castAt: 3 });
// 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
// posted as a clearly-marked demo-fixture ballot onto the signed log (the
// exemption that lets a single-keypair demo machine tally a multi-resident
// roster); a live ballot claiming Bob's id would be rejected at read.
await postQvBallot({
proposalId: "p1",
voterId: "delegate-bob",
choice: "yes",
credits: 9,
demoFixture: true,
});
const expectedTally = computeQvTally({
proposalId: "p1",
residentCredits: listResidentCredits(governance),
ballots: listQvBallots(governance),
ballots: extractQvBallots(await readAll()),
delegations: listDelegations(governance),
});
@@ -570,14 +580,21 @@ describe("AssemblyScreen (create-proposal / add-resident affordances - todo 12)"
const meId = toAccountId(publicKey);
const dbName = uniqueDbName("create-proposal-vote");
const { governance } = getAssemblyEngineForTesting(dbName);
render(<AssemblyScreen dbName={dbName} />);
await waitFor(() => {
expect(screen.getByTestId("assembly-sync-indicator")).toHaveTextContent("Synced");
});
const user = userEvent.setup();
// Enroll on the roster first: QV ballots are now gated on enrollment, and
// creating a proposal grants every roster member their DEFAULT_QV_CREDITS
// budget - so after this `meId` can cast a weighted ballot (GAP-5 fix).
await user.type(screen.getByTestId("assembly-add-resident-name-input"), "Me");
await user.click(screen.getByTestId("assembly-add-resident-submit"));
await waitFor(() => {
expect(screen.getByTestId(`assembly-roster-${meId}`)).toBeInTheDocument();
});
await user.type(screen.getByTestId("assembly-create-proposal-title-input"), "Install new mailboxes");
await user.type(
screen.getByTestId("assembly-create-proposal-description-input"),
@@ -596,12 +613,11 @@ describe("AssemblyScreen (create-proposal / add-resident affordances - todo 12)"
expect(screen.getByTestId(`assembly-vote-status-${proposalId}`)).toHaveTextContent("You voted Yes");
});
// QV tally: seed this resident's own credit budget for the new
// proposal (same real governance.ts function the existing happy-path
// test above already uses), then cast the real QV ballot through the
// UI and confirm the numeric tally updates from 0.
// 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.
expect(screen.getByTestId(`assembly-tally-yes-${proposalId}`)).toHaveTextContent("Yes 0.00");
putResidentCredit(governance, { proposalId, residentId: meId, credits: 9 });
await user.click(screen.getByTestId(`assembly-qv-ballot-yes-${proposalId}`));
await waitFor(() => {
expect(screen.getByTestId(`assembly-tally-yes-${proposalId}`)).toHaveTextContent("Yes 3.00");
+23 -6
View File
@@ -76,11 +76,18 @@ export function AssemblyScreen({ dbName }: AssemblyScreenProps = {}) {
.map((vote) => [vote.proposalId, vote.choice]),
);
const myDelegation = delegations.find((d) => d.delegatorId === 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
// visitor's ballot would never weigh anyway - disabling it is the honest
// affordance rather than a silently no-op button.
const isEnrolled =
myAccountId !== undefined && roster.some((entry) => entry.residentId === myAccountId);
function handleDelegateSubmit(proposalId: string, event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const delegateId = delegateChoice[proposalId];
if (myAccountId === undefined || !delegateId) return;
if (!isEnrolled || myAccountId === undefined || !delegateId) return;
delegate(myAccountId, delegateId);
}
@@ -362,7 +369,7 @@ export function AssemblyScreen({ dbName }: AssemblyScreenProps = {}) {
type="submit"
className={styles.delegateSubmit}
data-testid={`assembly-delegate-submit-${proposal.id}`}
disabled={!delegateChoice[proposal.id]}
disabled={!delegateChoice[proposal.id] || !isEnrolled}
>
Delegate
</button>
@@ -375,15 +382,25 @@ export function AssemblyScreen({ dbName }: AssemblyScreenProps = {}) {
type="button"
className={styles.ballotButton}
data-testid={`assembly-qv-ballot-${choice}-${proposal.id}`}
disabled={myAccountId === undefined}
onClick={() =>
myAccountId !== undefined && castBallot(proposal.id, myAccountId, choice)
}
disabled={!isEnrolled}
onClick={() => {
if (isEnrolled && myAccountId !== undefined) {
void castBallot(proposal.id, myAccountId, choice);
}
}}
>
{CHOICE_LABEL[choice]}
</button>
))}
</div>
{!isEnrolled && (
<p
className={styles.delegationStatus}
data-testid={`assembly-qv-enroll-hint-${proposal.id}`}
>
Add yourself to the roster above to cast a weighted ballot or delegate.
</p>
)}
</>
)}
@@ -0,0 +1,270 @@
import { beforeEach, describe, expect, it } from "vitest";
import { db } from "../../lib/db.ts";
import { init } from "../../lib/identity.ts";
import { readAll, type StoredEventLogEntry } from "../../lib/eventlog.ts";
import { toAccountId } from "../../shell/accountId.ts";
import {
computeQvTally,
residentCreditKey,
DEFAULT_QV_CREDITS,
type QvBallotRecord,
type ResidentCreditRecord,
} from "../../lib/governance.ts";
import {
extractQvBallots,
postQvBallot,
QV_BALLOT_PAYLOAD_TYPE,
} from "../../lib/governanceEvents.ts";
import { HOLLOW_DEMO_PROPOSAL, HOLLOW_DEMO_ROSTER } from "../../admin/seedEvents.ts";
function pubkey(fill: number): Uint8Array {
return new Uint8Array(32).fill(fill);
}
function ballotEntry(opts: {
id: number;
authorPubkey: Uint8Array;
lamportTs: number;
payload: unknown;
}): StoredEventLogEntry {
return {
id: opts.id,
payload: opts.payload,
authorPubkey: opts.authorPubkey,
signature: new Uint8Array(64),
lamportTs: opts.lamportTs,
};
}
beforeEach(async () => {
indexedDB.deleteDatabase(db.name);
db.close();
await db.open();
});
describe("extractQvBallots verify-at-read binding (pure, no network)", () => {
it("excludes a ballot signed by a key that does not resolve to its claimed voterId (forgery), keeping the authentic one", () => {
const keyA = pubkey(0x11);
const keyB = pubkey(0x22);
const accountA = toAccountId(keyA);
const accountB = toAccountId(keyB);
const authentic = ballotEntry({
id: 1,
authorPubkey: keyA,
lamportTs: 0,
payload: {
type: QV_BALLOT_PAYLOAD_TYPE,
proposalId: "p",
voterId: accountA,
choice: "yes",
credits: 9,
},
});
// Signed by key A, but CLAIMS to be account B's vote: the signature does
// not verify against the claimed voterId, so this is a forgery.
const forged = ballotEntry({
id: 2,
authorPubkey: keyA,
lamportTs: 1,
payload: {
type: QV_BALLOT_PAYLOAD_TYPE,
proposalId: "p",
voterId: accountB,
choice: "no",
credits: 9,
},
});
const ballots = extractQvBallots([authentic, forged]);
expect(ballots.map((b) => b.voterId)).toEqual([accountA]);
const tally = computeQvTally({
proposalId: "p",
residentCredits: [
{ id: "a", proposalId: "p", residentId: accountA, credits: 9 },
{ id: "b", proposalId: "p", residentId: accountB, credits: 9 },
],
ballots,
delegations: [],
});
// Only A's authentic YES (sqrt 9 = 3) is counted; B's forged NO is dropped.
expect(tally.tally).toEqual({ yes: 3, no: 0, abstain: 0 });
});
it("skips malformed ballot entries without throwing (malformed_input)", () => {
const key = pubkey(0x33);
const account = toAccountId(key);
const entries: StoredEventLogEntry[] = [
ballotEntry({ id: 1, authorPubkey: key, lamportTs: 0, payload: null }),
ballotEntry({
id: 2,
authorPubkey: key,
lamportTs: 1,
payload: { type: QV_BALLOT_PAYLOAD_TYPE, proposalId: "p" },
}),
ballotEntry({
id: 3,
authorPubkey: key,
lamportTs: 2,
payload: { type: "something.else", proposalId: "p", voterId: account, choice: "yes", credits: 9 },
}),
ballotEntry({
id: 4,
authorPubkey: key,
lamportTs: 3,
payload: { type: QV_BALLOT_PAYLOAD_TYPE, proposalId: "p", voterId: account, choice: "banana", credits: 9 },
}),
ballotEntry({
id: 5,
authorPubkey: key,
lamportTs: 4,
payload: { type: QV_BALLOT_PAYLOAD_TYPE, proposalId: "p", voterId: account, choice: "yes", credits: 9 },
}),
];
let ballots: QvBallotRecord[] = [];
expect(() => {
ballots = extractQvBallots(entries);
}).not.toThrow();
expect(ballots).toHaveLength(1);
expect(ballots[0]).toMatchObject({ voterId: account, choice: "yes" });
});
});
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 () => {
const { publicKey } = await init();
const meId = toAccountId(publicKey);
const proposalId = "p-sqrt";
await postQvBallot({ proposalId, voterId: meId, choice: "no", credits: 16 });
const ballots = extractQvBallots(await readAll());
expect(ballots).toHaveLength(1);
expect(ballots[0]).toMatchObject({ voterId: meId, choice: "no" });
const tally = computeQvTally({
proposalId,
residentCredits: [{ id: meId, proposalId, residentId: meId, credits: 16 }],
ballots,
delegations: [],
});
// sqrt(16) = 4 lands entirely on NO, nothing else moves.
expect(tally.tally).toEqual({ yes: 0, no: 4, abstain: 0 });
});
it("rejects a live ballot that claims another resident's id (no demo-fixture flag) at read", async () => {
const { publicKey } = await init();
const meId = toAccountId(publicKey);
const strangerId = toAccountId(pubkey(0x44));
expect(strangerId).not.toBe(meId);
// Signed by this device's real identity, but claiming the stranger's id
// and NOT marked as demo fixture - the exact forgery the binding rejects.
await postQvBallot({ proposalId: "p", voterId: strangerId, choice: "yes", credits: 9 });
expect(extractQvBallots(await readAll())).toHaveLength(0);
});
it("CRITICAL: renders a non-trivial multi-resident tally from the seeded admin-demo roster/credits/ballots", async () => {
const { publicKey } = await init();
const meId = toAccountId(publicKey);
const proposalId = HOLLOW_DEMO_PROPOSAL.id;
const [aria, kade] = HOLLOW_DEMO_ROSTER;
// Every roster member plus the live local device gets the same
// DEFAULT_QV_CREDITS budget the real lifecycle grants.
const residentCredits: ResidentCreditRecord[] = [
...HOLLOW_DEMO_ROSTER.map((entry) => ({
id: residentCreditKey(proposalId, entry.residentId),
proposalId,
residentId: entry.residentId,
credits: DEFAULT_QV_CREDITS,
})),
{
id: residentCreditKey(proposalId, meId),
proposalId,
residentId: meId,
credits: DEFAULT_QV_CREDITS,
},
];
// Two admin-seeded demo ballots (exempt from the live binding, since a
// single device cannot sign as Aria or Kade) and one real live ballot the
// local identity signs and the binding verifies.
await postQvBallot({ proposalId, voterId: aria.residentId, choice: "yes", credits: DEFAULT_QV_CREDITS, demoFixture: true });
await postQvBallot({ proposalId, voterId: kade.residentId, choice: "no", credits: DEFAULT_QV_CREDITS, demoFixture: true });
await postQvBallot({ proposalId, voterId: meId, choice: "yes", credits: DEFAULT_QV_CREDITS });
const ballots = extractQvBallots(await readAll());
// All three survive the read: the exemption keeps the two fixture ballots
// rather than silently dropping them (which would re-break Act 3's demo).
expect(ballots).toHaveLength(3);
const result = computeQvTally({ proposalId, residentCredits, ballots, delegations: [] });
// sqrt(9) = 3 per ballot: Aria(yes) + me(yes) = 6, Kade(no) = 3.
expect(result.tally).toEqual({ yes: 6, no: 3, abstain: 0 });
});
it("yields the identical tally from a cold replay of the whole log, not only live (stale_state)", async () => {
const { publicKey } = await init();
const meId = toAccountId(publicKey);
const otherId = toAccountId(pubkey(0x55));
const proposalId = "p-cold";
await postQvBallot({ proposalId, voterId: meId, choice: "yes", credits: 9 });
await postQvBallot({ proposalId, voterId: otherId, choice: "no", credits: 9, demoFixture: true });
const residentCredits: ResidentCreditRecord[] = [
{ id: "me", proposalId, residentId: meId, credits: 9 },
{ id: "other", proposalId, residentId: otherId, credits: 9 },
];
// Two independent cold reads of the persisted log produce the same
// replay-derived ballots and tally: the authority lives in the log, not
// in any live in-memory CRDT state.
const first = computeQvTally({
proposalId,
residentCredits,
ballots: extractQvBallots(await readAll()),
delegations: [],
});
const second = computeQvTally({
proposalId,
residentCredits,
ballots: extractQvBallots(await readAll()),
delegations: [],
});
expect(first.tally).toEqual({ yes: 3, no: 3, abstain: 0 });
expect(second.tally).toEqual(first.tally);
});
it("dedupes a re-appended duplicate ballot and applies last-writer-wins on a vote change (cancel_resume)", async () => {
const { publicKey } = await init();
const meId = toAccountId(publicKey);
const proposalId = "p-dupe";
const residentCredits: ResidentCreditRecord[] = [
{ id: meId, proposalId, residentId: meId, credits: 9 },
];
// Same ballot appended twice, as an unmounted-mid-write retry would.
await postQvBallot({ proposalId, voterId: meId, choice: "yes", credits: 9 });
await postQvBallot({ proposalId, voterId: meId, choice: "yes", credits: 9 });
const deduped = extractQvBallots(await readAll());
expect(deduped).toHaveLength(1);
expect(
computeQvTally({ proposalId, residentCredits, ballots: deduped, delegations: [] }).tally,
).toEqual({ yes: 3, no: 0, abstain: 0 });
// A later ballot for the same resident changes the vote; it never stacks.
await postQvBallot({ proposalId, voterId: meId, choice: "no", credits: 9 });
const after = extractQvBallots(await readAll());
expect(after).toHaveLength(1);
expect(
computeQvTally({ proposalId, residentCredits, ballots: after, delegations: [] }).tally,
).toEqual({ yes: 0, no: 3, abstain: 0 });
});
});
+54 -11
View File
@@ -13,19 +13,21 @@ import {
type VoteRecord,
} from "../../lib/assembly.ts";
import {
castQvBallot,
computeQvTally,
listDelegations,
listQvBallots,
listResidentCredits,
putDelegation,
putResidentCredit,
wrapGovernanceDoc,
DEFAULT_QV_CREDITS,
type DelegationRecord,
type GovernanceDoc,
type QvTallyResult,
type VoteChoice,
} from "../../lib/governance.ts";
import { connectAssemblySync, type AssemblySyncOptions } from "../../lib/assemblySync.ts";
import { extractQvBallots, postQvBallot } from "../../lib/governanceEvents.ts";
import { useEventLogEntries } from "../../shell/useEventLogEntries.ts";
/** Default IndexedDB database name the production Assembly screen persists
* to. Tests use a distinct, unique `dbName` per test so they never share
@@ -190,13 +192,19 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): {
tallyFor: (proposalId: string) => QvTallyResult;
castDirectVote: (proposalId: string, voterId: string, choice: VoteChoice) => void;
delegate: (delegatorId: string, delegateId: string) => void;
castBallot: (proposalId: string, voterId: string, choice: VoteChoice) => void;
/** Creates a new open proposal (plan todo 12) via the existing, unchanged
* `putProposal` - the create-proposal UI's only write path. */
/** 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
* once the signed entry is appended. */
castBallot: (proposalId: string, voterId: string, choice: VoteChoice) => Promise<void>;
/** Creates a new open proposal (plan todo 12) via the unchanged
* `putProposal`, then grants every existing roster member their
* `DEFAULT_QV_CREDITS` budget for it (plan todo 7) so a vote actually
* weighs instead of tallying 0.00. */
createProposal: (title: string, description: string, authorId: string) => void;
/** Adds (or re-adds) `residentId` to the roster (plan todo 12) via the
* existing, unchanged `putRosterEntry` - the add-resident UI's only write
* path. */
* unchanged `putRosterEntry`, then grants them their `DEFAULT_QV_CREDITS`
* budget on every currently-open proposal (plan todo 7). */
addResident: (residentId: string, displayName: string) => void;
/** Whether this replica is currently reaching for real WebRTC peers
* (the "Sync with devices using the same code" toggle). Off by default -
@@ -298,6 +306,7 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): {
// different device's code) actually switch rooms while sync is on.
}, [syncEnabled, bound, syncRoomCode]);
const eventLogEntries = useEventLogEntries();
const proposals = listProposals(bound.assembly);
const roster = listRoster(bound.assembly);
const votes = listVotes(bound.assembly);
@@ -307,7 +316,9 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): {
return computeQvTally({
proposalId,
residentCredits: listResidentCredits(bound.governance),
ballots: listQvBallots(bound.governance),
// Ballots now come from the replayed signed Event Log (verified at read
// in `extractQvBallots`), never the forgeable CRDT `listQvBallots`.
ballots: extractQvBallots(eventLogEntries),
delegations: listDelegations(bound.governance),
});
}
@@ -325,19 +336,41 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): {
});
}
function castBallot(proposalId: string, voterId: string, choice: VoteChoice): void {
castQvBallot(bound.governance, { proposalId, voterId, choice, castAt: Date.now() });
async function castBallot(
proposalId: string,
voterId: string,
choice: VoteChoice,
): Promise<void> {
const budget = listResidentCredits(bound.governance).find(
(record) => record.proposalId === proposalId && record.residentId === voterId,
);
await postQvBallot({
proposalId,
voterId,
choice,
credits: budget?.credits ?? DEFAULT_QV_CREDITS,
});
}
function createProposal(title: string, description: string, authorId: string): void {
const id = generateAssemblyRecordId("proposal");
putProposal(bound.assembly, {
id: generateAssemblyRecordId("proposal"),
id,
title,
description,
authorId,
createdAt: Date.now(),
status: "open",
});
// Grant every existing roster member their QV credit budget for the brand
// new proposal, so the tally is weightable the moment it appears (GAP-5).
for (const entry of listRoster(bound.assembly)) {
putResidentCredit(bound.governance, {
proposalId: id,
residentId: entry.residentId,
credits: DEFAULT_QV_CREDITS,
});
}
}
function addResident(residentId: string, displayName: string): void {
@@ -348,6 +381,16 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): {
joinedAt: Date.now(),
active: true,
});
// Grant the newly-enrolled resident their QV credit budget on every open
// proposal, so they can cast a weighted ballot right away (GAP-5).
for (const proposal of listProposals(bound.assembly)) {
if (proposal.status !== "open") continue;
putResidentCredit(bound.governance, {
proposalId: proposal.id,
residentId,
credits: DEFAULT_QV_CREDITS,
});
}
}
return {