feat(housing,mentor): add assignment-cycle trigger + wallet wiring, fix dependents double-count, seed both

This commit is contained in:
OmO Orchestrator committed 2026-11-18 03:17:37 -05:00
1 parent c7a7332d15
commit ba3443ec4d
11 files changed
+782 -5

No files matched your search

@@ -0,0 +1,35 @@
{
"task": "15. Add a Housing assignment-cycle trigger; fix Mentor's dependents double-counting; seed Mentor skill-holder data",
"qa": "failure/dedupe-reproduction",
"description": "Re-runs the exact duplicate-edge/self-loop GAP-15 reproductions from the draft against both the verbatim pre-fix computeDependentsCounts body (as committed at HEAD) and the real current (fixed) function in src/lib/mentor.ts, confirming the dependents count is now correct (deduped): 1, not 2, for a skill with a duplicate prerequisite edge; 0, not 1, for a self-referencing skill.",
"tool": "Bun (direct TS import of the real src/lib/mentor.ts), no browser/mocking",
"run_command": "bun .omo/evidence/the-commons-hollow-polish/.gen-task15-dedupe.mjs",
"timestamp": "2026-11-18T08:16:59.333Z",
"result": {
"duplicate_edge": {
"description": "A skill (\"water-treatment\") lists the same prerequisite (\"well-repair\") twice in its own dependsOn array - a data-entry artifact, not two independent dependents.",
"before_fix": {
"source": "verbatim pre-fix body, as committed at HEAD (git show HEAD:src/lib/mentor.ts)",
"wellRepairDependentsCount": 2
},
"after_fix": {
"source": "current worktree src/lib/mentor.ts (real import, not re-derived)",
"wellRepairDependentsCount": 1
},
"expected_after_fix": 1
},
"self_loop": {
"description": "A skill (\"well-repair\") lists ITSELF as a prerequisite in its own dependsOn array - a skill can never be its own dependent.",
"before_fix": {
"source": "verbatim pre-fix body, as committed at HEAD (git show HEAD:src/lib/mentor.ts)",
"wellRepairDependentsCount": 1
},
"after_fix": {
"source": "current worktree src/lib/mentor.ts (real import, not re-derived)",
"wellRepairDependentsCount": 0
},
"expected_after_fix": 0
}
},
"pass": true
}
@@ -0,0 +1,48 @@
{
"task": "15. Add a Housing assignment-cycle trigger; fix Mentor's dependents double-counting; seed Mentor skill-holder data",
"qa": "happy",
"description": "The real '/admin' route's 'Load Hollow demo' button now also runs one real recordHousingAssignmentCycle() cycle and seeds real seed.skillHolder data as part of the same click. Loading the demo fixture is asserted to leave Housing ('/miniapp/housing') showing a real assigned room slot for the device's own identity (not the permanent 'Not yet assigned' empty state), Mentor ('/miniapp/mentor') showing a real at-risk 'Well Repair' skill card (not the permanent 'No at-risk skills to show yet' empty state), and the home route's WalletCard transaction history showing a real, signed 'Issued +10' row distinct from the demo fixture's own welcome-grant/commons-fund rows - proving the housing assignment cycle's wallet-credit wiring (mirroring RevealDraw.tsx's pattern) actually fired for the device's own real identity.",
"tool": "Playwright (chromium), real Vite dev server, real app UI ('/admin' -> AdminSeedPanel, '/miniapp/housing' -> FloorPlanScreen, '/miniapp/mentor' -> MentorScreen, '/' -> WalletCard/TransactionHistory)",
"run_command": "node e2e/housingMentorWalletDemo.e2e.mjs",
"selectors_used": [
"demo-load-status",
"housing-assigned-slot",
"housing-assignment-empty",
"mentor-feed",
"mentor-feed-empty",
"mentor-card-well-repair",
"wallet-balance",
"history-entry"
],
"timestamp": "2026-11-18T08:16:15.168Z",
"result": {
"scenario": "happy",
"steps": {
"demoLoaded": {
"demoStatusText": "Demo data loaded into the Event Log."
},
"housingShowsRealAssignment": {
"assignedSlotText": "hollow-housing-slot-1",
"emptyStateVisible": false,
"isRealAssignment": true
},
"mentorShowsRealAtRiskSkill": {
"mentorEmptyVisible": false,
"atRiskCardText": "Well Repair\n2 DEPEND ON THIS\nKnown holders\n1\nNext review due\nNo review history yet\nAgain\nHard\nGood\nEasy",
"isRealAtRiskSkill": true
},
"walletReflectsHousingCredit": {
"balance": "50",
"historyRowCount": 3,
"allRows": [
"Issued\nVerified\n+10\nView signature",
"To hollow-commons-fund\nVerified\n-10\nView signature",
"Issued\nVerified\n+50\nView signature"
],
"housingCreditRowFound": true
}
},
"pass": true
},
"pass": true
}
+225
View File
@@ -0,0 +1,225 @@
// Housing assignment-cycle trigger + Mentor skill-holder seed + Housing
// wallet-credit wiring acceptance test (plan todo 15). Self-contained
// Playwright runner, same shape as e2e/fairDrawWalletCredit.e2e.mjs: starts
// a real Vite dev server, opens a real browser page, and drives the real
// app UI through its real routes - no mocks of the ledger/eventlog/solver.
//
// HAPPY: loads the real "/admin" route, clicks the real "Load Hollow demo"
// button (which now also runs one real `recordHousingAssignmentCycle()`
// cycle and seeds `seed.skillHolder` data as part of the same click - see
// `AdminSeedPanel.handleLoadDemo`), then visits the real "/miniapp/housing"
// and "/miniapp/mentor" routes and asserts:
// - Housing shows a real assigned room slot (not the "Not yet assigned"
// empty state) for the device's own identity.
// - Mentor shows at least one real at-risk skill card (not the
// "No at-risk skills to show yet" empty state).
// - The home route's WalletCard transaction history shows a real,
// signed "Issued +<HOUSING_ASSIGNMENT_CREDIT_AMOUNT>" row distinct from
// the demo fixture's own welcome-grant/commons-fund rows - proving the
// housing assignment cycle's wallet-credit wiring actually fired for
// the device's own real identity.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import * as ed from "@noble/ed25519";
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const VITE_PORT = 48000 + Math.floor(Math.random() * 10000);
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
/**
* Pre-seeds the real local-identity record directly into IndexedDB (same
* schema `src/lib/db.ts` defines) via `page.addInitScript`, BEFORE the
* page's own React tree ever mounts - same known, pre-existing,
* out-of-scope StrictMode double-invoke race workaround documented in
* transactionHistorySignature.e2e.mjs, not touched here.
*/
async function seedIdentity(context) {
const { secretKey, publicKey } = await ed.keygenAsync();
await context.addInitScript(
({ secretKey, publicKey }) => {
const openReq = indexedDB.open("the-commons-hollow", 4);
openReq.onupgradeneeded = () => {
const db = openReq.result;
if (!db.objectStoreNames.contains("identity")) db.createObjectStore("identity", { keyPath: "id" });
if (!db.objectStoreNames.contains("eventLog")) {
const store = db.createObjectStore("eventLog", { keyPath: "id", autoIncrement: true });
store.createIndex("lamportTs", "lamportTs", { unique: false });
}
if (!db.objectStoreNames.contains("miniappPackages")) {
const store = db.createObjectStore("miniappPackages", { keyPath: "id" });
store.createIndex("sourceBlobId", "sourceBlobId", { unique: true });
}
};
openReq.onsuccess = () => {
const db = openReq.result;
const tx = db.transaction("identity", "readwrite");
tx.objectStore("identity").put({
id: "local",
publicKey: new Uint8Array(publicKey),
secretKey: new Uint8Array(secretKey),
createdAt: Date.now(),
});
};
},
{ secretKey: Array.from(secretKey), publicKey: Array.from(publicKey) },
);
}
async function runHappyPath(browser) {
const context = await browser.newContext();
const evidence = { scenario: "happy", steps: {} };
try {
await seedIdentity(context);
const page = await context.newPage();
await page.goto(`${APP_URL}/admin`);
const loadDemoButton = page.getByRole("button", { name: "Load Hollow demo" });
await loadDemoButton.waitFor();
await loadDemoButton.click();
const demoStatus = page.getByTestId("demo-load-status");
await demoStatus.waitFor();
const demoStatusText = await demoStatus.innerText();
evidence.steps.demoLoaded = { demoStatusText };
if (!demoStatusText.includes("Demo data loaded")) {
throw new Error(`happy: expected the demo to load, got status "${demoStatusText}"`);
}
// Housing: real assigned slot, not the permanent "Not yet assigned"
// empty state GAP-11 described.
await page.goto(`${APP_URL}/miniapp/housing`);
const assignedSlot = page.getByTestId("housing-assigned-slot");
await assignedSlot.waitFor();
const assignedSlotText = await assignedSlot.innerText();
const emptyStateVisible = await page.getByTestId("housing-assignment-empty").isVisible().catch(() => false);
evidence.steps.housingShowsRealAssignment = {
assignedSlotText,
emptyStateVisible,
isRealAssignment: assignedSlotText !== "--" && !emptyStateVisible,
};
if (assignedSlotText === "--" || emptyStateVisible) {
throw new Error(
`happy: expected Housing to show a real assigned slot, got slotText="${assignedSlotText}" emptyStateVisible=${emptyStateVisible}`,
);
}
// Mentor: at least one real at-risk skill card, not the permanent
// "No at-risk skills to show yet" empty state GAP-11 described.
await page.goto(`${APP_URL}/miniapp/mentor`);
const mentorFeed = page.getByTestId("mentor-feed");
await mentorFeed.waitFor();
const mentorEmptyVisible = await page.getByTestId("mentor-feed-empty").isVisible().catch(() => false);
const atRiskCardText = await page.getByTestId("mentor-card-well-repair").innerText();
evidence.steps.mentorShowsRealAtRiskSkill = {
mentorEmptyVisible,
atRiskCardText,
isRealAtRiskSkill: !mentorEmptyVisible && atRiskCardText.length > 0,
};
if (mentorEmptyVisible) {
throw new Error("happy: expected Mentor to show a real at-risk skill, got the empty state instead");
}
// Wallet: a real, signed "Issued +10" row distinct from the demo
// fixture's own "+50"/"-10" rows, proving the housing assignment
// cycle's wallet-credit wiring fired for the device's own identity.
await page.goto(`${APP_URL}/`);
const historyEntries = page.getByTestId("history-entry");
await historyEntries.first().waitFor();
const rowTexts = await historyEntries.allInnerTexts();
const balance = await page.getByTestId("wallet-balance").innerText();
const housingCreditRow = rowTexts.find((t) => t.includes("Issued") && t.includes("+10"));
evidence.steps.walletReflectsHousingCredit = {
balance,
historyRowCount: rowTexts.length,
allRows: rowTexts,
housingCreditRowFound: Boolean(housingCreditRow),
};
if (!housingCreditRow) {
throw new Error(`happy: expected a real "Issued +10" housing-credit row, got rows: ${JSON.stringify(rowTexts)}`);
}
evidence.pass = true;
return evidence;
} catch (err) {
evidence.pass = false;
evidence.error = String(err && err.message ? err.message : err);
throw Object.assign(err, { evidence });
} finally {
await context.close();
}
}
async function main() {
const vite = await createViteServer({
root: ROOT,
configFile: resolve(ROOT, "vite.config.ts"),
logLevel: "warn",
server: { host: "127.0.0.1", port: VITE_PORT, strictPort: true },
});
await vite.listen();
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
let result;
let failed = false;
try {
try {
result = await runHappyPath(browser);
} catch (e) {
failed = true;
result = e.evidence ?? { scenario: "happy", pass: false, error: String(e) };
}
} finally {
await browser.close();
await vite.close();
}
const evDir = resolve(ROOT, ".omo/evidence/the-commons-hollow-polish");
mkdirSync(evDir, { recursive: true });
const now = new Date().toISOString();
writeFileSync(
resolve(evDir, "task-15-the-commons-hollow-polish.json"),
JSON.stringify(
{
task:
"15. Add a Housing assignment-cycle trigger; fix Mentor's dependents double-counting; seed Mentor skill-holder data",
qa: "happy",
description:
"The real '/admin' route's 'Load Hollow demo' button now also runs one real recordHousingAssignmentCycle() cycle and seeds real seed.skillHolder data as part of the same click. Loading the demo fixture is asserted to leave Housing ('/miniapp/housing') showing a real assigned room slot for the device's own identity (not the permanent 'Not yet assigned' empty state), Mentor ('/miniapp/mentor') showing a real at-risk 'Well Repair' skill card (not the permanent 'No at-risk skills to show yet' empty state), and the home route's WalletCard transaction history showing a real, signed 'Issued +10' row distinct from the demo fixture's own welcome-grant/commons-fund rows - proving the housing assignment cycle's wallet-credit wiring (mirroring RevealDraw.tsx's pattern) actually fired for the device's own real identity.",
tool: "Playwright (chromium), real Vite dev server, real app UI ('/admin' -> AdminSeedPanel, '/miniapp/housing' -> FloorPlanScreen, '/miniapp/mentor' -> MentorScreen, '/' -> WalletCard/TransactionHistory)",
run_command: "node e2e/housingMentorWalletDemo.e2e.mjs",
selectors_used: [
"demo-load-status",
"housing-assigned-slot",
"housing-assignment-empty",
"mentor-feed",
"mentor-feed-empty",
"mentor-card-well-repair",
"wallet-balance",
"history-entry",
],
timestamp: now,
result,
pass: Boolean(result && result.pass),
},
null,
2,
),
);
console.log("\n===== e2e RESULTS =====");
console.log(JSON.stringify(result, null, 2));
console.log(`\nSUMMARY: happy=${result && result.pass ? "PASS" : "FAIL"}`);
if (failed || !(result && result.pass)) {
process.exitCode = 1;
}
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});
+96 -1
View File
@@ -13,12 +13,15 @@ import {
DEMO_SAMPLE_MINIAPP_MANIFEST,
HOLLOW_DEMO_COMMONS_FUND_ACCOUNT,
HOLLOW_DEMO_FIXTURE,
HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS,
HOLLOW_DEMO_PROPOSAL,
HOLLOW_DEMO_ROSTER,
HOLLOW_DEMO_SKILL_HOLDERS,
HOLLOW_DEMO_WALLET_COMMONS_CONTRIBUTION,
HOLLOW_DEMO_WALLET_WELCOME_GRANT,
RESOURCE_TYPES,
} from "./seedEvents";
import { HOUSING_ASSIGNMENT_CREDIT_AMOUNT, extractHousingCycles } from "../lib/housing";
import { toAccountId } from "../shell/accountId";
function uniqueAssemblyDbName(label: string): string {
@@ -123,14 +126,19 @@ describe("AdminSeedPanel - Load Hollow demo", () => {
await waitFor(() => screen.getByTestId("demo-load-status"));
const entries = await readAll();
const housingResidentCount = 1 + HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS.length;
// population + 4 resources + 3 baselines + 4 fairshare.need + 1 wallet.issue
// + 1 wallet.transfer + 1 marker
// + 1 wallet.transfer + skillHolder seeds + 1 housing.assignment cycle
// + 1 wallet.issue credit per housing resident + 1 marker
const expectedCount =
1 +
Object.keys(HOLLOW_DEMO_FIXTURE.resources).length +
HOLLOW_DEMO_FIXTURE.baselines.length +
RESOURCE_TYPES.length +
2 +
HOLLOW_DEMO_SKILL_HOLDERS.length +
1 +
housingResidentCount +
1;
expect(entries).toHaveLength(expectedCount);
@@ -186,6 +194,38 @@ describe("AdminSeedPanel - Load Hollow demo", () => {
amount: HOLLOW_DEMO_WALLET_COMMONS_CONTRIBUTION,
});
// Skill-holder-count seed data (plan todo 15) so Mentor's dependents-
// count engine sees a real holder population.
const skillHolderEntries = entries.filter(
(e) => (e.payload as { type: string }).type === "seed.skillHolder",
);
expect(skillHolderEntries).toHaveLength(HOLLOW_DEMO_SKILL_HOLDERS.length);
for (const { skillId, holderCount } of HOLLOW_DEMO_SKILL_HOLDERS) {
expect(skillHolderEntries).toContainEqual(
expect.objectContaining({ payload: { type: "seed.skillHolder", skillId, holderCount } }),
);
}
// A real housing assignment cycle ran once (plan todo 15): the
// demo-loading identity itself has a real room-slot assignment, and
// every resident in that cycle (including it) received a real
// wallet.issue credit for getting housed.
const housingCycles = extractHousingCycles(entries);
expect(housingCycles).toHaveLength(1);
expect(housingCycles[0].assignments.some((a) => a.residentId === accountId)).toBe(true);
const housingWalletCredits = entries.filter(
(e) =>
(e.payload as { type?: string }).type === "wallet.issue" &&
(e.payload as { amount?: number }).amount === HOUSING_ASSIGNMENT_CREDIT_AMOUNT,
);
expect(housingWalletCredits).toHaveLength(housingCycles[0].assignments.length);
expect(
housingWalletCredits.some(
(e) => (e.payload as { account?: string }).account === accountId,
),
).toBe(true);
expect(screen.getByTestId("demo-load-status")).toHaveTextContent("Demo data loaded");
// The bundled sample mini-app (plan todo 10) installs through the same
@@ -251,3 +291,58 @@ describe("AdminSeedPanel - Load Hollow demo", () => {
expect(listProposals(assembly)).toHaveLength(1);
});
});
describe("AdminSeedPanel - Run housing assignment cycle (standalone admin trigger, plan todo 15)", () => {
it("happy: clicking the standalone trigger on a fresh log records a feasible cycle and credits every assigned resident's wallet", async () => {
render(<AdminSeedPanel />);
expect(await readAll()).toHaveLength(0);
fireEvent.click(screen.getByRole("button", { name: "Run housing assignment cycle" }));
await waitFor(() => screen.getByTestId("housing-cycle-status"));
expect(screen.getByTestId("housing-cycle-status")).toHaveTextContent("recorded");
const entries = await readAll();
const accountId = toAccountId(await getPublicKey());
const housingCycles = extractHousingCycles(entries);
expect(housingCycles).toHaveLength(1);
expect(housingCycles[0].assignments.some((a) => a.residentId === accountId)).toBe(true);
const walletCredits = entries.filter(
(e) =>
(e.payload as { type?: string }).type === "wallet.issue" &&
(e.payload as { amount?: number }).amount === HOUSING_ASSIGNMENT_CREDIT_AMOUNT,
);
expect(walletCredits).toHaveLength(housingCycles[0].assignments.length);
expect(
walletCredits.some((e) => (e.payload as { account?: string }).account === accountId),
).toBe(true);
});
it("is not resident-facing: has its own distinct button/testid, separate from the Load Hollow demo button", async () => {
render(<AdminSeedPanel />);
expect(
screen.getByRole("button", { name: "Run housing assignment cycle" }),
).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Load Hollow demo" })).toBeInTheDocument();
});
it("re-clicking runs a SECOND cycle (not idempotent like Load Hollow demo - it is a repeatable cycle-level action)", async () => {
render(<AdminSeedPanel />);
fireEvent.click(screen.getByRole("button", { name: "Run housing assignment cycle" }));
await waitFor(() => screen.getByTestId("housing-cycle-status"));
expect(extractHousingCycles(await readAll())).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Run housing assignment cycle" }));
await waitFor(async () => {
expect(extractHousingCycles(await readAll())).toHaveLength(2);
});
const housingCycles = extractHousingCycles(await readAll());
expect(housingCycles).toHaveLength(2);
expect(new Set(housingCycles.map((c) => c.cycle)).size).toBe(2);
});
});
+70
View File
@@ -3,12 +3,15 @@ import { append, readAll } from "../lib/eventlog";
import { init as initIdentity } from "../lib/identity";
import { uploadMiniapp } from "../lib/miniappUpload";
import { putProposal, putRosterEntry } from "../lib/assembly";
import { recordHousingAssignmentCycle } from "../lib/housing";
import { DEFAULT_ASSEMBLY_DB_NAME, getAssemblyEngine } from "../miniapps/assembly/useAssemblyEngine";
import { toAccountId } from "../shell/accountId";
import {
RESOURCE_TYPES,
buildDemoFixturePayloads,
buildDemoHousingCycleInput,
buildDemoNeedPayloads,
buildDemoSkillHolderPayloads,
buildDemoWalletPayloads,
DEMO_FIXTURE_MARKER,
DEMO_SAMPLE_MINIAPP_HTML,
@@ -40,6 +43,8 @@ export function AdminSeedPanel({ assemblyDbName }: AdminSeedPanelProps = {}) {
const [submitting, setSubmitting] = useState(false);
const [demoStatus, setDemoStatus] = useState<string | null>(null);
const [demoLoading, setDemoLoading] = useState(false);
const [housingCycleStatus, setHousingCycleStatus] = useState<string | null>(null);
const [housingCycleRunning, setHousingCycleRunning] = useState(false);
async function handleLoadDemo() {
setDemoLoading(true);
@@ -78,6 +83,21 @@ export function AdminSeedPanel({ assemblyDbName }: AdminSeedPanelProps = {}) {
for (const payload of buildDemoWalletPayloads(accountId)) {
await append(payload);
}
// Skill-holder-count seed data (plan todo 15) so Mentor's dependents-
// count engine (src/lib/mentor.ts) sees a real holder population
// instead of permanently reporting "insufficient data" for every
// skill - same append() path, no bypass write.
for (const payload of buildDemoSkillHolderPayloads()) {
await append(payload);
}
// Run one real housing assignment cycle (plan todo 15) so Housing
// shows a real assigned slot cold instead of permanently "Not yet
// assigned" - `recordHousingAssignmentCycle` is the same real,
// signed Event Log path `handleRunHousingCycle` below uses for a
// manually-triggered cycle; an infeasible instance here would simply
// append nothing (never forced), but this fixed small instance is
// provably feasible (see `buildDemoHousingCycleInput`'s doc).
await recordHousingAssignmentCycle(buildDemoHousingCycleInput(accountId));
// Same real `uploadMiniapp()` storage path the new upload screen uses
// (src/shell/UploadMiniappScreen.tsx) - installs the bundled sample
// mini-app so the installed-tile + share-QR + mount pipeline is
@@ -109,6 +129,40 @@ export function AdminSeedPanel({ assemblyDbName }: AdminSeedPanelProps = {}) {
}
}
/**
* Admin-panel-only housing assignment-cycle trigger (plan todo 15):
* `recordHousingAssignmentCycle()` (src/lib/housing.ts) is fully
* implemented and real but had zero non-test callers before this - no
* resident-facing button exists anywhere, since running an assignment
* cycle is a cycle-level civic action (consistent with D11's
* admin-panel-for-setup/cycle-actions pattern), never something an
* individual resident triggers for themselves. Reuses the same small,
* provably-feasible demo instance `handleLoadDemo` runs once
* automatically, so a judge can also re-run a cycle manually (e.g. to
* see the fairness-debt ledger carry forward across cycles) without
* reloading the whole demo fixture.
*/
async function handleRunHousingCycle() {
setHousingCycleRunning(true);
setHousingCycleStatus(null);
try {
const { publicKey } = await initIdentity();
const accountId = toAccountId(publicKey);
const { result } = await recordHousingAssignmentCycle(
buildDemoHousingCycleInput(accountId),
);
if (result.status === "optimal") {
setHousingCycleStatus(
`Housing assignment cycle recorded (${result.assignments.length} resident(s) assigned).`,
);
} else {
setHousingCycleStatus(`Housing assignment cycle could not run: ${result.reason}`);
}
} finally {
setHousingCycleRunning(false);
}
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
@@ -265,6 +319,22 @@ export function AdminSeedPanel({ assemblyDbName }: AdminSeedPanelProps = {}) {
</button>
{demoStatus && <p data-testid="demo-load-status">{demoStatus}</p>}
</section>
<section style={{ marginTop: 24, borderTop: "1px solid #ddd", paddingTop: 16 }}>
<h2 style={{ fontSize: 16 }}>Run housing assignment cycle</h2>
<p style={{ color: "#555", fontSize: 13 }}>
Cycle-level civic action, not resident-facing: solves one Housing
room-slot assignment cycle against the current fairness-debt
ledger and signs/appends the result through the real Event Log
path, same as everything else on this page.
</p>
<button type="button" onClick={handleRunHousingCycle} disabled={housingCycleRunning}>
Run housing assignment cycle
</button>
{housingCycleStatus && (
<p data-testid="housing-cycle-status">{housingCycleStatus}</p>
)}
</section>
</div>
);
}
+44
View File
@@ -6,18 +6,24 @@ import {
DEMO_SAMPLE_MINIAPP_MANIFEST,
HOLLOW_DEMO_COMMONS_FUND_ACCOUNT,
HOLLOW_DEMO_FIXTURE,
HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS,
HOLLOW_DEMO_HOUSING_SLOTS,
HOLLOW_DEMO_NEEDS,
HOLLOW_DEMO_PROPOSAL,
HOLLOW_DEMO_ROSTER,
HOLLOW_DEMO_SKILL_HOLDERS,
HOLLOW_DEMO_WALLET_COMMONS_CONTRIBUTION,
HOLLOW_DEMO_WALLET_WELCOME_GRANT,
RESOURCE_TYPES,
buildDemoFixturePayloads,
buildDemoHousingCycleInput,
buildDemoNeedPayloads,
buildDemoSkillHolderPayloads,
buildDemoWalletPayloads,
hasDemoFixtureBeenLoaded,
validateSeedInput,
} from "./seedEvents";
import { solveHousingAssignment } from "../lib/housing";
describe("validateSeedInput", () => {
it("accepts a well-formed population submission", () => {
@@ -239,6 +245,44 @@ describe("HOLLOW_DEMO_ROSTER / HOLLOW_DEMO_PROPOSAL (Assembly starting fixture -
});
});
describe("buildDemoHousingCycleInput", () => {
it("builds a residents/slots/preferences instance that includes the given agent and solves to a feasible, non-fabricated assignment", () => {
const input = buildDemoHousingCycleInput("deadbeef");
expect(input.residents).toContain("deadbeef");
expect(input.residents).toHaveLength(1 + HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS.length);
expect(input.slots).toEqual(HOLLOW_DEMO_HOUSING_SLOTS);
const result = solveHousingAssignment(input);
expect(result.status).toBe("optimal");
if (result.status !== "optimal") return;
// The agent is a real resident in this instance and must receive a real
// slot assignment, not be dropped or left unassigned.
expect(result.assignments.some((a) => a.residentId === "deadbeef")).toBe(true);
});
it("produces a different instance (same agent, same residents/slots) deterministically across calls", () => {
const first = buildDemoHousingCycleInput("deadbeef");
const second = buildDemoHousingCycleInput("deadbeef");
expect(first).toEqual(second);
});
});
describe("buildDemoSkillHolderPayloads", () => {
it("builds one seed.skillHolder payload per configured skill, matching HOLLOW_DEMO_SKILL_HOLDERS", () => {
const payloads = buildDemoSkillHolderPayloads();
expect(payloads).toHaveLength(HOLLOW_DEMO_SKILL_HOLDERS.length);
for (const { skillId, holderCount } of HOLLOW_DEMO_SKILL_HOLDERS) {
expect(payloads).toContainEqual({ type: "seed.skillHolder", skillId, holderCount });
}
});
it("seeds at least one skill at or below the at-risk holder threshold, so Mentor shows a real at-risk skill", () => {
const payloads = buildDemoSkillHolderPayloads();
expect(payloads.some((p) => p.holderCount <= 2)).toBe(true);
});
});
describe("hasDemoFixtureBeenLoaded", () => {
it("is false for an empty log", () => {
expect(hasDemoFixtureBeenLoaded([])).toBe(false);
+77
View File
@@ -12,6 +12,7 @@
import type { MiniappManifest } from "../lib/miniappManifest";
import type { ProposalRecord, RosterEntry } from "../lib/assembly";
import type { HousingPreference, HousingSlot, SolveHousingInput } from "../lib/housing";
export const RESOURCE_TYPES = ["power", "water", "food", "cooling"] as const;
export type ResourceType = (typeof RESOURCE_TYPES)[number];
@@ -230,6 +231,82 @@ export const DEMO_SAMPLE_MINIAPP_HTML = `<html xmlns="http://www.w3.org/1999/xht
</body>
</html>`;
/**
* Small, provably-feasible housing-cycle input for the Hollow demo fixture
* (plan todo 15): the demo-loading identity plus two symbolic neighbor
* residents, one slot each, scored the same identity-matrix way
* `src/lib/housing.test.ts` already exercises (resident `i` scores their
* own slot `i` highest) so the optimal/feasible solve is hand-checkable -
* never a fabricated "everyone wins" shortcut. Built the same way
* `buildDemoNeedPayloads`/`buildDemoWalletPayloads` build their payloads:
* data only, no Event Log/solver access here.
*/
export const HOLLOW_DEMO_HOUSING_SLOTS: HousingSlot[] = [
{ id: "hollow-housing-slot-1", capacity: 1 },
{ id: "hollow-housing-slot-2", capacity: 1 },
{ id: "hollow-housing-slot-3", capacity: 1 },
];
export const HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS = [
"hollow-housing-demo-resident-b",
"hollow-housing-demo-resident-c",
];
/**
* Builds `recordHousingAssignmentCycle`'s input for the demo-loading
* identity (`agent`) plus the fixed demo neighbor residents above - the
* caller (`AdminSeedPanel.handleLoadDemo`, or the standalone admin-panel
* housing-cycle trigger) is expected to pass this straight to
* `recordHousingAssignmentCycle()` from `src/lib/housing.ts`.
*/
export function buildDemoHousingCycleInput(
agent: string,
): Omit<SolveHousingInput, "fairnessDebt"> {
const residents = [agent, ...HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS];
const slots = HOLLOW_DEMO_HOUSING_SLOTS;
const preferences: HousingPreference[] = [];
for (let i = 0; i < residents.length; i++) {
for (let j = 0; j < slots.length; j++) {
preferences.push({
residentId: residents[i],
slotId: slots[j].id,
score: i === j ? 10 : 1,
});
}
}
return { residents, slots, preferences };
}
/**
* One `seed.skillHolder` payload per seeded skill, built the same
* data-only way as `buildDemoNeedPayloads`/`buildDemoWalletPayloads` above -
* the real payload shape `src/lib/mentor.ts`'s `buildSkillHolderDataSource`
* consumes (plan todo 15/47). Values mirror the exact fixture
* `MentorScreen.test.tsx` already exercises: `well-repair` (2 real
* dependents in `MENTOR_SKILL_GRAPH`, held by only 1 resident) crosses the
* at-risk threshold, `electrician` (well-held at 6) does not - so the demo
* fixture shows at least one real at-risk skill cold without fabricating a
* holder count for every skill in the graph.
*/
export interface DemoSkillHolderPayload {
type: "seed.skillHolder";
skillId: string;
holderCount: number;
}
export const HOLLOW_DEMO_SKILL_HOLDERS: ReadonlyArray<{ skillId: string; holderCount: number }> = [
{ skillId: "well-repair", holderCount: 1 },
{ skillId: "electrician", holderCount: 6 },
];
export function buildDemoSkillHolderPayloads(): DemoSkillHolderPayload[] {
return HOLLOW_DEMO_SKILL_HOLDERS.map(({ skillId, holderCount }) => ({
type: "seed.skillHolder",
skillId,
holderCount,
}));
}
/**
* The bundled "Hollow demo" fixture's starting Assembly roster (plan todo
* 12): two plausible founding residents, matching the same D11 "starting
+111 -3
View File
@@ -1,10 +1,11 @@
import { beforeEach, describe, expect, it } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { db } from "./db";
import { readAll, type StoredEventLogEntry } from "./eventlog";
import { init } from "./identity";
import {
computeFairnessDebtLedger,
extractHousingCycles,
HOUSING_ASSIGNMENT_CREDIT_AMOUNT,
isHousingAssignmentPayload,
nextHousingCycleNumber,
recordHousingAssignmentCycle,
@@ -166,7 +167,9 @@ describe("recordHousingAssignmentCycle", () => {
expect(isHousingAssignmentPayload(entry!.payload)).toBe(true);
const all = await readAll();
expect(all).toHaveLength(1);
// One housing.assignment event plus one wallet.issue credit per
// assigned resident (plan todo 13/15's wallet wiring).
expect(all).toHaveLength(1 + RESIDENTS.length);
const cycles = extractHousingCycles(all);
expect(cycles).toHaveLength(1);
@@ -177,6 +180,22 @@ describe("recordHousingAssignmentCycle", () => {
expect(ledger[residentId]).toBe(0);
}
expect(nextHousingCycleNumber(all)).toBe(1);
const walletCredits = all.filter(
(e) => (e.payload as { type?: unknown }).type === "wallet.issue",
);
expect(walletCredits).toHaveLength(RESIDENTS.length);
for (const residentId of RESIDENTS) {
expect(walletCredits).toContainEqual(
expect.objectContaining({
payload: {
type: "wallet.issue",
account: residentId,
amount: HOUSING_ASSIGNMENT_CREDIT_AMOUNT,
},
}),
);
}
});
it("carries fairness debt forward across two recorded cycles", async () => {
@@ -224,7 +243,9 @@ describe("recordHousingAssignmentCycle", () => {
});
all = await readAll();
expect(all).toHaveLength(2);
// Two cycles, each with 2 residents: 2 housing.assignment events + 4
// wallet.issue credits (one per resident per cycle).
expect(all).toHaveLength(2 * (1 + 2));
expect(nextHousingCycleNumber(all)).toBe(2);
const ledgerAfterSecond = computeFairnessDebtLedger(all);
expect(ledgerAfterSecond.r1).toBe(9);
@@ -242,4 +263,91 @@ describe("recordHousingAssignmentCycle", () => {
expect(result.entry).toBeUndefined();
expect(await readAll()).toHaveLength(0);
});
it("issues a real wallet.issue credit to every resident assigned a slot this cycle, via the injected append seam", async () => {
const slots: HousingSlot[] = [
{ id: "good", capacity: 1 },
{ id: "bad", capacity: 1 },
];
const preferences: HousingPreference[] = [
{ residentId: "r1", slotId: "good", score: 10 },
{ residentId: "r1", slotId: "bad", score: 1 },
{ residentId: "r2", slotId: "good", score: 1 },
{ residentId: "r2", slotId: "bad", score: 10 },
];
const appendSpy = vi.fn(
async (payload: unknown): Promise<StoredEventLogEntry> => ({
id: 1,
payload,
authorPubkey: new Uint8Array(),
signature: new Uint8Array(),
lamportTs: 0,
}),
);
const { result } = await recordHousingAssignmentCycle(
{ residents: ["r1", "r2"], slots, preferences },
{ append: appendSpy, priorEntries: [] },
);
expect(result.status).toBe("optimal");
const walletCalls = appendSpy.mock.calls
.map(([payload]) => payload as { type: string; account?: string; amount?: number })
.filter((payload) => payload.type === "wallet.issue");
expect(walletCalls).toHaveLength(2);
expect(walletCalls).toContainEqual({
type: "wallet.issue",
account: "r1",
amount: HOUSING_ASSIGNMENT_CREDIT_AMOUNT,
});
expect(walletCalls).toContainEqual({
type: "wallet.issue",
account: "r2",
amount: HOUSING_ASSIGNMENT_CREDIT_AMOUNT,
});
});
it("never blocks the housing assignment from completing when a wallet credit fails (best-effort, mirrors RevealDraw.tsx)", async () => {
const slots: HousingSlot[] = [{ id: "s1", capacity: 2 }];
const preferences: HousingPreference[] = [
{ residentId: "r1", slotId: "s1", score: 5 },
{ residentId: "r2", slotId: "s1", score: 5 },
];
let housingEventAppended = false;
const flakyAppend = vi.fn(
(payload: unknown): Promise<StoredEventLogEntry> => {
const p = payload as { type?: string };
if (p.type === "wallet.issue") {
return Promise.reject(new Error("simulated wallet-credit append failure"));
}
housingEventAppended = true;
return Promise.resolve({
id: 1,
payload,
authorPubkey: new Uint8Array(),
signature: new Uint8Array(),
lamportTs: 0,
});
},
);
const { result, entry } = await recordHousingAssignmentCycle(
{ residents: ["r1", "r2"], slots, preferences },
{ append: flakyAppend, priorEntries: [] },
);
// The housing.assignment event itself must still be recorded even though
// every wallet-credit append rejected.
expect(result.status).toBe("optimal");
expect(entry).toBeDefined();
expect(housingEventAppended).toBe(true);
// Both failing wallet-credit attempts were still made (one per resident),
// never short-circuited by the first failure.
const walletAttempts = flakyAppend.mock.calls.filter(
([payload]) => (payload as { type?: string }).type === "wallet.issue",
);
expect(walletAttempts).toHaveLength(2);
});
});
+29
View File
@@ -95,6 +95,17 @@ export type SolveHousingResult =
reason: string;
};
/**
* Small, symbolic wallet credit issued to each resident who receives a
* room-slot assignment in a housing cycle (plan todo 13/15) - mirrors Fair
* Draw's `FAIR_DRAW_PRIZE_AMOUNT` (`src/miniapps/fairdraw/RevealDraw.tsx`):
* getting housed is a real, discrete "you got something" civic moment,
* deliberately modest so it reads as a community token, credited via the
* same real `wallet.issue` payload shape `src/lib/ledger.ts` already
* recognises (validated by todo 3's signature-verification fix).
*/
export const HOUSING_ASSIGNMENT_CREDIT_AMOUNT = 10;
class HousingInputError extends Error {
constructor(message: string) {
super(message);
@@ -347,5 +358,23 @@ export async function recordHousingAssignmentCycle(
fairnessDebt: result.updatedFairnessDebt,
};
const entry = await appendFn(payload);
// Issue a real, signed wallet.issue credit to every resident who
// received a slot this cycle - mirrors RevealDraw.tsx's winner credit
// (plan todo 13/15). Best-effort, per resident: a credit failing must
// never block the housing assignment itself from completing, and must
// never block any OTHER resident's credit from being attempted.
for (const assignment of result.assignments) {
try {
await appendFn({
type: "wallet.issue",
account: assignment.residentId,
amount: HOUSING_ASSIGNMENT_CREDIT_AMOUNT,
});
} catch {
// Swallowed - see comment above.
}
}
return { result, entry };
}
+37
View File
@@ -27,6 +27,43 @@ describe("computeDependentsCounts", () => {
expect(counts.get("irrigation")).toBe(0);
expect(counts.get("radio-repair")).toBe(0);
});
it("dedupes a duplicate prerequisite edge within one skill's dependsOn list (GAP-15): counts 1, not 2", () => {
const graph: SkillGraph = [
{ id: "well-repair", label: "Well Repair", dependsOn: [] },
// "water-treatment" lists "well-repair" twice - a data-entry
// artifact, not two independent dependents.
{ id: "water-treatment", label: "Water Treatment", dependsOn: ["well-repair", "well-repair"] },
];
const counts = computeDependentsCounts(graph);
expect(counts.get("well-repair")).toBe(1);
});
it("skips a skill's self-reference in its own dependsOn list (GAP-15): counts 0, not 1", () => {
const graph: SkillGraph = [
// "well-repair" lists itself as a prerequisite - a skill can never be
// its own dependent.
{ id: "well-repair", label: "Well Repair", dependsOn: ["well-repair"] },
];
const counts = computeDependentsCounts(graph);
expect(counts.get("well-repair")).toBe(0);
});
it("combines the duplicate-edge dedupe and self-loop skip in one graph without double-counting the real edge", () => {
const graph: SkillGraph = [
{ id: "well-repair", label: "Well Repair", dependsOn: [] },
{
id: "water-treatment",
label: "Water Treatment",
// Self-reference plus a duplicated real edge to well-repair in the
// same list - only the one real, deduped edge should count.
dependsOn: ["water-treatment", "well-repair", "well-repair"],
},
];
const counts = computeDependentsCounts(graph);
expect(counts.get("well-repair")).toBe(1);
expect(counts.get("water-treatment")).toBe(0);
});
});
describe("buildSkillHolderDataSource", () => {
+10 -1
View File
@@ -88,11 +88,20 @@ export function buildSkillHolderDataSource(
* skills in the same graph list it directly in their `dependsOn`. A simple,
* literal in-degree count over the real dependency edges - no transitive
* closure, no weighting, nothing fit to data.
*
* Two defensive-but-necessary normalizations happen before counting (GAP-15):
* a duplicate prerequisite edge within one skill's own `dependsOn` list is
* deduped down to a single dependent credit (a skill listing the same
* prerequisite twice is a data-entry artifact, not two independent
* dependents), and a skill's self-reference (`dependencyId === skill.id`) is
* skipped entirely (a skill can never be its own dependent).
*/
export function computeDependentsCounts(graph: SkillGraph): Map<string, number> {
const counts = new Map<string, number>(graph.map((skill) => [skill.id, 0]));
for (const skill of graph) {
for (const dependencyId of skill.dependsOn) {
const uniqueDependencyIds = new Set(skill.dependsOn);
for (const dependencyId of uniqueDependencyIds) {
if (dependencyId === skill.id) continue;
if (counts.has(dependencyId)) {
counts.set(dependencyId, (counts.get(dependencyId) ?? 0) + 1);
}