feat(assembly): enact a passed proposal into a signed, binding community decision
Governance had no teeth: a passed QV tally produced no recorded consequence. A proposal with Yes weight strictly greater than No can now be Enacted by any enrolled resident, appending a signed governance.proposal.enacted event; the proposal then shows an Enacted badge with the frozen tally and honest copy (the Assembly records a binding decision, it cannot force anyone - there is no server underground). Derived purely by replay (extractEnactedProposalIds), idempotent, and allowlisted so the decision syncs cross-device like ballots. Verified on the real surface (self-enroll -> Enact -> badge replaces button). 47 governance/assembly tests + the sync allowlist test; full gate 790 tests + build green.
This commit is contained in:
1 parent
fbb0882ac4
commit
2f6a6ba907
12 files changed
+447
-2
No files matched your search
Binary file not shown.
|
After Width: | Height: | Size: 152 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 238 KiB |
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { castVote, createAssemblyDoc, putProposal, type AssemblyDoc } from "./assembly.ts";
|
||||
import {
|
||||
computeQvTally,
|
||||
isProposalPassed,
|
||||
DEFAULT_QV_CREDITS,
|
||||
listDelegations,
|
||||
listResidentCredits,
|
||||
@@ -354,6 +355,36 @@ describe("governance: quadratic-voting tally", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("governance: isProposalPassed (the enactment gate)", () => {
|
||||
function tallyResult(yes: number, no: number, abstain: number) {
|
||||
return { proposalId: PROPOSAL_ID, tally: { yes, no, abstain }, participants: [] };
|
||||
}
|
||||
|
||||
it("passes when Yes weight is STRICTLY greater than No weight", () => {
|
||||
expect(isProposalPassed(tallyResult(6, 0, 0))).toBe(true);
|
||||
expect(isProposalPassed(tallyResult(3.01, 3, 0))).toBe(true);
|
||||
});
|
||||
|
||||
it("does not pass on an exact Yes/No tie (not a majority of weighted voice)", () => {
|
||||
expect(isProposalPassed(tallyResult(3, 3, 0))).toBe(false);
|
||||
});
|
||||
|
||||
it("does not pass when No weight meets or exceeds Yes weight", () => {
|
||||
expect(isProposalPassed(tallyResult(2, 3, 0))).toBe(false);
|
||||
});
|
||||
|
||||
it("does not pass a proposal with no votes at all (0 === 0)", () => {
|
||||
expect(isProposalPassed(tallyResult(0, 0, 0))).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores abstain weight entirely when deciding a pass", () => {
|
||||
// A large abstain block neither helps nor blocks: only Yes-vs-No decides.
|
||||
expect(isProposalPassed(tallyResult(3, 0, 100))).toBe(true);
|
||||
expect(isProposalPassed(tallyResult(0, 3, 100))).toBe(false);
|
||||
expect(isProposalPassed(tallyResult(0, 0, 100))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("governance: integration with the assembly.ts CRDT proposal set (todo 22)", () => {
|
||||
it("governance CRDT maps live alongside (not instead of) assembly.ts's proposals/roster/votes on the same Y.Doc", () => {
|
||||
const assembly = buildHappyPathGovernance();
|
||||
|
||||
@@ -338,3 +338,21 @@ export function computeQvTally(params: {
|
||||
return { proposalId, tally, participants };
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides whether a proposal has PASSED from its QV tally: Yes weight must be
|
||||
* STRICTLY greater than No weight. Abstain is deliberately ignored (an abstain
|
||||
* is a recorded non-position, never a vote against), and an exact tie
|
||||
* (`yes === no`, including the all-abstain or no-votes 0 === 0 case) is NOT a
|
||||
* pass - a binding decision requires a real majority of weighted voice, not a
|
||||
* stalemate.
|
||||
*
|
||||
* This is the pure gate the UI/engine ask "is this proposal passed?" with
|
||||
* before offering to enact it; "is it enacted?" is the separate, replay-derived
|
||||
* membership check against `extractEnactedProposalIds` (governanceEvents.ts).
|
||||
* Keeping passing a pure function of the signed-log tally means a passed
|
||||
* proposal is a fact every replica derives identically, never a stored flag.
|
||||
*/
|
||||
export function isProposalPassed(tally: QvTallyResult): boolean {
|
||||
return tally.tally.yes > tally.tally.no;
|
||||
}
|
||||
|
||||
@@ -155,3 +155,76 @@ export function extractQvBallots(entries: StoredEventLogEntry[]): QvBallotRecord
|
||||
}
|
||||
return [...byKey.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Event Log payload type for an ENACTMENT: the signed, replay-derived record
|
||||
* that a proposal which passed its QV tally has been closed into the
|
||||
* community's binding decision (the "teeth" a passed vote previously lacked).
|
||||
*
|
||||
* A proposal passing its tally is a fact derived purely from the signed
|
||||
* ballots (`computeQvTally` + `isProposalPassed`); it is not, on its own, a
|
||||
* recorded CONSEQUENCE. This event is that consequence: a resident who sees a
|
||||
* proposal has passed signs one `governance.proposal.enacted` entry onto the
|
||||
* same append-only log the ballots live on, and from then on every replica -
|
||||
* live or cold-replayed - derives the proposal's enacted status identically
|
||||
* from the log (`extractEnactedProposalIds`), exactly as it derives the tally.
|
||||
* Nothing is enforced underground: THE COMMONS has no server and no
|
||||
* enforcement arm, so an enactment is honestly a tamper-evident RECORDED
|
||||
* decision every resident can independently verify, not a command.
|
||||
*/
|
||||
export const GOVERNANCE_ENACTED_PAYLOAD_TYPE = "governance.proposal.enacted" as const;
|
||||
|
||||
/** The Event Log payload shape one enactment is signed over. */
|
||||
export interface ProposalEnactedPayload {
|
||||
type: typeof GOVERNANCE_ENACTED_PAYLOAD_TYPE;
|
||||
proposalId: string;
|
||||
/** Wall-clock millis the enactment was signed, for display/audit only. The
|
||||
* authoritative ordering across replicas remains the entry's `lamportTs`. */
|
||||
enactedAt: number;
|
||||
}
|
||||
|
||||
export function isProposalEnactedPayload(payload: unknown): payload is ProposalEnactedPayload {
|
||||
if (typeof payload !== "object" || payload === null) return false;
|
||||
const p = payload as Record<string, unknown>;
|
||||
return (
|
||||
p.type === GOVERNANCE_ENACTED_PAYLOAD_TYPE &&
|
||||
typeof p.proposalId === "string" &&
|
||||
typeof p.enactedAt === "number"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs and appends one enactment to the Event Log (the local identity's key
|
||||
* signs it, via `append`, just like `postQvBallot`). Callers gate this on the
|
||||
* proposal actually having passed and not already being enacted
|
||||
* (`useAssemblyEngine`'s `enact`); re-appending an enactment for the same
|
||||
* proposal is harmless because `extractEnactedProposalIds` dedupes by
|
||||
* `proposalId` - enactment is idempotent at read.
|
||||
*/
|
||||
export async function postEnactment(proposalId: string): Promise<StoredEventLogEntry> {
|
||||
const payload: ProposalEnactedPayload = {
|
||||
type: GOVERNANCE_ENACTED_PAYLOAD_TYPE,
|
||||
proposalId,
|
||||
enactedAt: Date.now(),
|
||||
};
|
||||
return append(payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconstructs the set of enacted proposal ids from a replayed Event Log read.
|
||||
* Entries whose payload is not an enactment are skipped; multiple enactment
|
||||
* entries for the same proposal (a re-append, or two residents both enacting)
|
||||
* collapse to a single set member, so enacted status is idempotent and
|
||||
* identical on a cold replay and a live session. The signature of every entry
|
||||
* reaching here was already verified at write/read by the Event Log itself, so
|
||||
* a membership in this set is a tamper-evident, independently verifiable fact.
|
||||
*/
|
||||
export function extractEnactedProposalIds(entries: StoredEventLogEntry[]): Set<string> {
|
||||
const enacted = new Set<string>();
|
||||
for (const entry of entries) {
|
||||
if (isProposalEnactedPayload(entry.payload)) {
|
||||
enacted.add(entry.payload.proposalId);
|
||||
}
|
||||
}
|
||||
return enacted;
|
||||
}
|
||||
@@ -170,6 +170,7 @@ describe("trySyncWithBackend", () => {
|
||||
await append({ type: "mentor.match", apprentice: "a", mentor: "b" });
|
||||
await append({ type: "theclimb.tiebreak.commit", hash: "abc" });
|
||||
await append({ type: "fairdraw.reveal", drawId: "d1" });
|
||||
await append({ type: "governance.proposal.enacted", proposalId: "p1", enactedAt: 1 });
|
||||
|
||||
let pushedBatch: Array<{ payload: { type?: string } }> = [];
|
||||
vi.stubGlobal(
|
||||
@@ -189,6 +190,7 @@ describe("trySyncWithBackend", () => {
|
||||
expect(types).toContain("mentor.match");
|
||||
expect(types).toContain("theclimb.tiebreak.commit");
|
||||
expect(types).toContain("fairdraw.reveal");
|
||||
expect(types).toContain("governance.proposal.enacted");
|
||||
expect(types).not.toContain("healthpost.symptomReport");
|
||||
});
|
||||
});
|
||||
@@ -75,6 +75,10 @@ export const PUSH_TYPE_ALLOWLIST: readonly string[] = [
|
||||
"housing",
|
||||
// Quadratic-voting ballots: public governance tallies.
|
||||
"governance.qvBallot",
|
||||
// Enacted decisions: a passed proposal's binding, signed community decision
|
||||
// must reach every device so the decision is visible everywhere (public
|
||||
// governance, like the ballots above). extractEnactedProposalIds dedupes.
|
||||
"governance.proposal.enacted",
|
||||
// Health Post clinician referral: a resident's deliberate, consent-bearing
|
||||
// handoff of their OWN triage result to a clinician on another device. The
|
||||
// referral loop is cross-device by contract (see ReferralQueue.tsx). This
|
||||
|
||||
@@ -364,3 +364,43 @@
|
||||
letter-spacing: 0.04em;
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
.enactButton {
|
||||
align-self: flex-start;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 10px;
|
||||
border: none;
|
||||
background: var(--color-positive);
|
||||
color: #ffffff;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.enactedBadge {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
padding: 0.7rem 0.85rem;
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--color-positive);
|
||||
background: var(--color-positive-bg);
|
||||
}
|
||||
|
||||
.enactedTitle {
|
||||
font-size: 0.82rem;
|
||||
font-weight: 700;
|
||||
color: var(--color-positive);
|
||||
}
|
||||
|
||||
.enactedTally {
|
||||
font-size: 0.78rem;
|
||||
color: var(--color-ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.enactedNote {
|
||||
font-size: 0.72rem;
|
||||
color: var(--color-ink-faint);
|
||||
line-height: 1.35;
|
||||
}
|
||||
@@ -20,7 +20,12 @@ import {
|
||||
putResidentCredit,
|
||||
type GovernanceDoc,
|
||||
} from "../../lib/governance.ts";
|
||||
import { extractQvBallots, postQvBallot } from "../../lib/governanceEvents.ts";
|
||||
import {
|
||||
extractQvBallots,
|
||||
postEnactment,
|
||||
postQvBallot,
|
||||
GOVERNANCE_ENACTED_PAYLOAD_TYPE,
|
||||
} from "../../lib/governanceEvents.ts";
|
||||
import { getAssemblyEngineForTesting, setAssemblySyncTransportOverrideForTesting } from "./useAssemblyEngine.ts";
|
||||
import { AssemblyScreen } from "./AssemblyScreen.tsx";
|
||||
|
||||
@@ -694,3 +699,129 @@ describe("AssemblyScreen (global delegation + revoke - GAP-A)", () => {
|
||||
expect(screen.queryByTestId("assembly-revoke-delegation")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("AssemblyScreen (enactment - governance teeth)", () => {
|
||||
/** Seeds a passed proposal: roster (me + Bob), an open proposal, equal
|
||||
* credit budgets, and two YES ballots (me's live, Bob's demo-fixture) so the
|
||||
* QV tally reads Yes 6.00 > No 0.00 - the passing condition. */
|
||||
async function seedPassedProposal(dbName: string, meId: string, proposalId: string) {
|
||||
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: proposalId,
|
||||
title: "Repave the courtyard",
|
||||
description: "Cracked stones are a tripping hazard.",
|
||||
authorId: meId,
|
||||
createdAt: 1,
|
||||
status: "open",
|
||||
});
|
||||
putResidentCredit(governance, { proposalId, residentId: meId, credits: 9 });
|
||||
putResidentCredit(governance, { proposalId, residentId: "delegate-bob", credits: 9 });
|
||||
await postQvBallot({ proposalId, voterId: meId, choice: "yes", credits: 9 });
|
||||
await postQvBallot({ proposalId, voterId: "delegate-bob", choice: "yes", credits: 9, demoFixture: true });
|
||||
}
|
||||
|
||||
it("shows the Enact button on a PASSED proposal (Yes 6 > No 0) and enacting it appends exactly one signed enactment, flips to the Enacted badge, and hides the button", async () => {
|
||||
const { publicKey } = await init();
|
||||
const meId = toAccountId(publicKey);
|
||||
const dbName = uniqueDbName("enact-passed");
|
||||
await seedPassedProposal(dbName, meId, "p1");
|
||||
|
||||
render(<AssemblyScreen dbName={dbName} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("assembly-tally-yes-p1")).toHaveTextContent("Yes 6.00");
|
||||
});
|
||||
|
||||
// Passed + enrolled -> the Enact affordance is offered, no Enacted badge yet.
|
||||
const enactButton = screen.getByTestId("assembly-enact-p1");
|
||||
expect(enactButton).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("assembly-enacted-p1")).not.toBeInTheDocument();
|
||||
|
||||
const user = userEvent.setup();
|
||||
await user.click(enactButton);
|
||||
|
||||
// The Enacted badge appears (with the frozen tally + honest copy) and the
|
||||
// Enact button is gone.
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("assembly-enacted-p1")).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByTestId("assembly-enacted-p1")).toHaveTextContent("binding recorded decision");
|
||||
expect(screen.getByTestId("assembly-enacted-p1")).toHaveTextContent("there is no server underground");
|
||||
expect(screen.getByTestId("assembly-enacted-tally-p1")).toHaveTextContent("Yes 6.00");
|
||||
expect(screen.queryByTestId("assembly-enact-p1")).not.toBeInTheDocument();
|
||||
|
||||
// Exactly one governance.proposal.enacted entry was signed onto the log.
|
||||
const enactedEntries = (await readAll()).filter(
|
||||
(entry) => (entry.payload as { type?: unknown } | null)?.type === GOVERNANCE_ENACTED_PAYLOAD_TYPE,
|
||||
);
|
||||
expect(enactedEntries).toHaveLength(1);
|
||||
expect(enactedEntries[0]!.payload).toMatchObject({ proposalId: "p1" });
|
||||
});
|
||||
|
||||
it("offers NO Enact action on a not-passed proposal (Yes 3 === No 3 is not a pass)", async () => {
|
||||
const { publicKey } = await init();
|
||||
const meId = toAccountId(publicKey);
|
||||
const dbName = uniqueDbName("enact-tie");
|
||||
|
||||
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: "p-tie",
|
||||
title: "Split proposal",
|
||||
description: "Residents are evenly divided.",
|
||||
authorId: meId,
|
||||
createdAt: 1,
|
||||
status: "open",
|
||||
});
|
||||
putResidentCredit(governance, { proposalId: "p-tie", residentId: meId, credits: 9 });
|
||||
putResidentCredit(governance, { proposalId: "p-tie", residentId: "delegate-bob", credits: 9 });
|
||||
// Yes 3 (me) vs No 3 (Bob) -> a tie, which is NOT a pass.
|
||||
await postQvBallot({ proposalId: "p-tie", voterId: meId, choice: "yes", credits: 9 });
|
||||
await postQvBallot({ proposalId: "p-tie", voterId: "delegate-bob", choice: "no", credits: 9, demoFixture: true });
|
||||
|
||||
render(<AssemblyScreen dbName={dbName} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("assembly-tally-no-p-tie")).toHaveTextContent("No 3.00");
|
||||
});
|
||||
expect(screen.getByTestId("assembly-tally-yes-p-tie")).toHaveTextContent("Yes 3.00");
|
||||
|
||||
// Neither the Enact button nor the Enacted badge is ever shown.
|
||||
expect(screen.queryByTestId("assembly-enact-p-tie")).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId("assembly-enacted-p-tie")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the Enacted badge (and never the Enact button) for an already-enacted proposal, proving enact is idempotent at the UI", async () => {
|
||||
const { publicKey } = await init();
|
||||
const meId = toAccountId(publicKey);
|
||||
const dbName = uniqueDbName("enact-already");
|
||||
await seedPassedProposal(dbName, meId, "p-done");
|
||||
// The proposal was already enacted before this screen ever mounted.
|
||||
await postEnactment("p-done");
|
||||
|
||||
render(<AssemblyScreen dbName={dbName} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("assembly-enacted-p-done")).toBeInTheDocument();
|
||||
});
|
||||
// No second Enact affordance is offered - the recorded decision stands.
|
||||
expect(screen.queryByTestId("assembly-enact-p-done")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -32,6 +32,8 @@ export function AssemblyScreen({ dbName }: AssemblyScreenProps = {}) {
|
||||
ballots,
|
||||
delegations,
|
||||
tallyFor,
|
||||
decisionFor,
|
||||
enact,
|
||||
delegate,
|
||||
revokeDelegation,
|
||||
castBallot,
|
||||
@@ -366,6 +368,7 @@ export function AssemblyScreen({ dbName }: AssemblyScreenProps = {}) {
|
||||
) : (
|
||||
proposals.map((proposal) => {
|
||||
const tally = tallyFor(proposal.id);
|
||||
const { passed, enacted } = decisionFor(proposal.id);
|
||||
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
|
||||
@@ -439,6 +442,43 @@ export function AssemblyScreen({ dbName }: AssemblyScreenProps = {}) {
|
||||
Abstain {tally.tally.abstain.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* The vote's teeth: a passed proposal can be closed into a
|
||||
signed, replay-derived recorded decision; once enacted it
|
||||
shows the frozen tally and honest copy about the limits of
|
||||
that decision. A not-passed proposal is never offered an
|
||||
Enact action. */}
|
||||
{enacted ? (
|
||||
<div
|
||||
className={styles.enactedBadge}
|
||||
data-testid={`assembly-enacted-${proposal.id}`}
|
||||
role="status"
|
||||
>
|
||||
<span className={styles.enactedTitle}>
|
||||
Enacted - the community's binding recorded decision
|
||||
</span>
|
||||
<span
|
||||
className={styles.enactedTally}
|
||||
data-testid={`assembly-enacted-tally-${proposal.id}`}
|
||||
>
|
||||
Recorded tally: Yes {tally.tally.yes.toFixed(2)} · No{" "}
|
||||
{tally.tally.no.toFixed(2)} · Abstain {tally.tally.abstain.toFixed(2)}
|
||||
</span>
|
||||
<span className={styles.enactedNote}>
|
||||
The Assembly records decisions; it cannot force anyone - there is no
|
||||
server underground.
|
||||
</span>
|
||||
</div>
|
||||
) : passed && isEnrolled ? (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.enactButton}
|
||||
data-testid={`assembly-enact-${proposal.id}`}
|
||||
onClick={() => void enact(proposal.id)}
|
||||
>
|
||||
Enact decision
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
|
||||
@@ -12,7 +12,10 @@ import {
|
||||
} from "../../lib/governance.ts";
|
||||
import {
|
||||
extractQvBallots,
|
||||
extractEnactedProposalIds,
|
||||
postEnactment,
|
||||
postQvBallot,
|
||||
GOVERNANCE_ENACTED_PAYLOAD_TYPE,
|
||||
QV_BALLOT_PAYLOAD_TYPE,
|
||||
} from "../../lib/governanceEvents.ts";
|
||||
import { HOLLOW_DEMO_PROPOSAL, HOLLOW_DEMO_ROSTER } from "../../admin/seedEvents.ts";
|
||||
@@ -271,3 +274,66 @@ describe("signed QV ballots through the Event Log (todo 7, GAP-5)", () => {
|
||||
).toEqual({ yes: 0, no: 3, abstain: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("signed enactment events through the Event Log (governance teeth)", () => {
|
||||
it("postEnactment appends exactly one governance.proposal.enacted entry and extractEnactedProposalIds derives it on replay", async () => {
|
||||
await init();
|
||||
expect(extractEnactedProposalIds(await readAll())).toEqual(new Set());
|
||||
|
||||
await postEnactment("p-enact");
|
||||
|
||||
const entries = await readAll();
|
||||
const enactedEntries = entries.filter(
|
||||
(entry) =>
|
||||
(entry.payload as { type?: unknown } | null)?.type === GOVERNANCE_ENACTED_PAYLOAD_TYPE,
|
||||
);
|
||||
expect(enactedEntries).toHaveLength(1);
|
||||
expect(enactedEntries[0]!.payload).toMatchObject({ type: GOVERNANCE_ENACTED_PAYLOAD_TYPE, proposalId: "p-enact" });
|
||||
expect(typeof (enactedEntries[0]!.payload as { enactedAt: number }).enactedAt).toBe("number");
|
||||
|
||||
// Replay-derived from the log, not a stored flag.
|
||||
expect(extractEnactedProposalIds(await readAll())).toEqual(new Set(["p-enact"]));
|
||||
});
|
||||
|
||||
it("collapses multiple enactment entries for the same proposal to a single set member (idempotent at read)", async () => {
|
||||
await init();
|
||||
// Two enactment appends for the same proposal (a re-append, or two
|
||||
// residents both enacting) - the enacted status is idempotent.
|
||||
await postEnactment("p-dupe");
|
||||
await postEnactment("p-dupe");
|
||||
await postEnactment("p-other");
|
||||
|
||||
const enacted = extractEnactedProposalIds(await readAll());
|
||||
expect(enacted).toEqual(new Set(["p-dupe", "p-other"]));
|
||||
});
|
||||
|
||||
it("ignores non-enactment entries (qv ballots, malformed payloads) when deriving the enacted set", () => {
|
||||
const key = pubkey(0x66);
|
||||
const account = toAccountId(key);
|
||||
const entries: StoredEventLogEntry[] = [
|
||||
ballotEntry({
|
||||
id: 1,
|
||||
authorPubkey: key,
|
||||
lamportTs: 0,
|
||||
payload: { type: QV_BALLOT_PAYLOAD_TYPE, proposalId: "p", voterId: account, choice: "yes", credits: 9 },
|
||||
}),
|
||||
ballotEntry({ id: 2, authorPubkey: key, lamportTs: 1, payload: null }),
|
||||
ballotEntry({
|
||||
id: 3,
|
||||
authorPubkey: key,
|
||||
lamportTs: 2,
|
||||
payload: { type: GOVERNANCE_ENACTED_PAYLOAD_TYPE, proposalId: "p-real" },
|
||||
}),
|
||||
ballotEntry({
|
||||
id: 4,
|
||||
authorPubkey: key,
|
||||
lamportTs: 3,
|
||||
payload: { type: GOVERNANCE_ENACTED_PAYLOAD_TYPE, proposalId: "p-real", enactedAt: 123 },
|
||||
}),
|
||||
];
|
||||
|
||||
// id:3 is malformed (no enactedAt) and dropped; only the well-formed
|
||||
// id:4 contributes. Ballots and null payloads never leak in.
|
||||
expect(extractEnactedProposalIds(entries)).toEqual(new Set(["p-real"]));
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
putResidentCredit,
|
||||
removeDelegation,
|
||||
wrapGovernanceDoc,
|
||||
isProposalPassed,
|
||||
DEFAULT_QV_CREDITS,
|
||||
type DelegationRecord,
|
||||
type GovernanceDoc,
|
||||
@@ -25,7 +26,12 @@ import {
|
||||
type VoteChoice,
|
||||
} from "../../lib/governance.ts";
|
||||
import { connectAssemblySync, type AssemblySyncOptions } from "../../lib/assemblySync.ts";
|
||||
import { extractQvBallots, postQvBallot } from "../../lib/governanceEvents.ts";
|
||||
import {
|
||||
extractQvBallots,
|
||||
extractEnactedProposalIds,
|
||||
postEnactment,
|
||||
postQvBallot,
|
||||
} from "../../lib/governanceEvents.ts";
|
||||
import { useEventLogEntries } from "../../shell/useEventLogEntries.ts";
|
||||
|
||||
/** Default IndexedDB database name the production Assembly screen persists
|
||||
@@ -194,6 +200,19 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): {
|
||||
ballots: QvBallotRecord[];
|
||||
delegations: DelegationRecord[];
|
||||
tallyFor: (proposalId: string) => QvTallyResult;
|
||||
/** The replay-derived governance decision for a proposal: `passed` is a pure
|
||||
* function of its signed-log QV tally (Yes weight strictly greater than No,
|
||||
* via `isProposalPassed`), and `enacted` is membership in the signed
|
||||
* `governance.proposal.enacted` set (`extractEnactedProposalIds`). Both are
|
||||
* derived from the Event Log, never stored flags - a passed/enacted proposal
|
||||
* is a fact every replica computes identically. */
|
||||
decisionFor: (proposalId: string) => { passed: boolean; enacted: boolean };
|
||||
/** Closes a PASSED proposal into the community's binding recorded decision
|
||||
* by signing one `governance.proposal.enacted` entry onto the Event Log (via
|
||||
* `postEnactment`). Guarded to a no-op unless the proposal is currently
|
||||
* passed and not already enacted, so it is safe to call idempotently - a
|
||||
* second call once the enactment is in the log appends nothing. */
|
||||
enact: (proposalId: string) => Promise<void>;
|
||||
delegate: (delegatorId: string, delegateId: string) => void;
|
||||
/** Revokes the local resident's global delegation so their own signed
|
||||
* ballot counts again (via `removeDelegation`). */
|
||||
@@ -320,6 +339,10 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): {
|
||||
// `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);
|
||||
// The set of proposals already enacted, derived from the same signed log the
|
||||
// ballots come from (never a CRDT flag) so a cold replay and a live session
|
||||
// always agree on what has been decided.
|
||||
const enactedProposalIds = extractEnactedProposalIds(eventLogEntries);
|
||||
|
||||
function tallyFor(proposalId: string): QvTallyResult {
|
||||
return computeQvTally({
|
||||
@@ -330,6 +353,21 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): {
|
||||
});
|
||||
}
|
||||
|
||||
function decisionFor(proposalId: string): { passed: boolean; enacted: boolean } {
|
||||
return {
|
||||
passed: isProposalPassed(tallyFor(proposalId)),
|
||||
enacted: enactedProposalIds.has(proposalId),
|
||||
};
|
||||
}
|
||||
|
||||
async function enact(proposalId: string): Promise<void> {
|
||||
const { passed, enacted } = decisionFor(proposalId);
|
||||
// Only a passed, not-yet-enacted proposal can be enacted. Re-enacting is a
|
||||
// silent no-op (idempotent): the enactment already lives in the log.
|
||||
if (!passed || enacted) return;
|
||||
await postEnactment(proposalId);
|
||||
}
|
||||
|
||||
function delegate(delegatorId: string, delegateId: string): void {
|
||||
putDelegation(bound.governance, {
|
||||
id: delegatorId,
|
||||
@@ -409,6 +447,8 @@ export function useAssemblyEngine(dbName: string = DEFAULT_ASSEMBLY_DB_NAME): {
|
||||
ballots,
|
||||
delegations,
|
||||
tallyFor,
|
||||
decisionFor,
|
||||
enact,
|
||||
delegate,
|
||||
revokeDelegation,
|
||||
castBallot,
|
||||
|
||||
Reference in new issue
Block a user