fix(housing): wire real accessibility + medical-proximity hard constraints
Coherence-audit gap (.omo/evidence/coherence-audit/housing.md): README/doc-comment named "accessibility, family cohesion, medical proximity" as enforced constraints, but HousingSlot/HousingPreference carried no such fields and the only production preference-builder (buildRankedCyclePreferences) kept every resident eligible for every slot, differentiating purely by self-reported ranking. - HousingSlot gains stepFree/distanceToMedicalMeters; HousingResidentNeeds (requiresStepFree/medicalUrgency) is a new per-resident type. - isSlotEligibleForResidentNeeds is the real eligibility gate; wired into buildRankedCyclePreferences so an ineligible (resident, slot) pair is hard- omitted from the solver's input, never a soft preference. - HousingSlotPreferenceInput/Payload and HousingSpaceReportInput/Payload both carry the new fields end to end (validate -> sign -> append -> replay via computeResidentHousingNeeds / discoverAvailableSlots), so both the resident- run cycle and the admin demo exercise the same real constraint. - FloorPlanScreen: SlotPreferenceForm gets a step-free checkbox + medical- urgency select; ReportSpaceForm gets a step-free checkbox + medical-distance field for self-reported idle spaces. - buildDemoHousingCycleInput (seedEvents.ts) now calls the real production buildRankedCyclePreferences instead of a hand-rolled score matrix, and one demo slot is non-step-free while one demo neighbor requires step-free access - provably excluded from their own top-ranked slot. - New behavioral tests in housing.test.ts prove the solver's actual eligible- pair set changes (never a mocked call): a step-free-requiring or high- medical-urgency resident is never assigned an ineligible slot even when it's their top-ranked preference, and infeasible when zero eligible slots remain. seedEvents.test.ts adds a demo-fixture-level proof of the same. Family cohesion remains unimplemented (no familyGroupId field/grouping rule) - disclosed as a known remaining gap, not fabricated. Full suite: 92 files / 836 tests passing. Build and oxlint clean.
This commit is contained in:
1 parent
e321949195
commit
b7f34c27bf
5 files changed
+465
-46
No files matched your search
@@ -276,6 +276,26 @@ describe("buildDemoHousingCycleInput", () => {
|
||||
expect(first).toEqual(second);
|
||||
});
|
||||
|
||||
it("excludes the accessibility-requiring neighbor from the non-step-free slot even when it is their top-ranked choice (constraint genuinely enforced, not prose)", () => {
|
||||
const input = buildDemoHousingCycleInput("agent-demo");
|
||||
const [, stepFreeRequiringResident] = HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS;
|
||||
const nonStepFreeSlot = HOLLOW_DEMO_HOUSING_SLOTS.find((slot) => !slot.stepFree)!;
|
||||
|
||||
// The hard-exclusion mechanism: no preference entry at all for this pair.
|
||||
expect(
|
||||
input.preferences.some(
|
||||
(p) => p.residentId === stepFreeRequiringResident && p.slotId === nonStepFreeSlot.id,
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
const result = solveHousingAssignment(input);
|
||||
expect(result.status).toBe("optimal");
|
||||
if (result.status !== "optimal") return;
|
||||
expect(
|
||||
result.assignments.find((a) => a.residentId === stepFreeRequiringResident)?.slotId,
|
||||
).not.toBe(nonStepFreeSlot.id);
|
||||
});
|
||||
|
||||
it("makes two residents contest one slot so fairness debt accrues to the loser and flips the slot next cycle", () => {
|
||||
const input = buildDemoHousingCycleInput("agent-demo");
|
||||
|
||||
|
||||
+30
-27
@@ -13,7 +13,8 @@
|
||||
import * as ed from "@noble/ed25519";
|
||||
import type { MiniappManifest } from "../lib/miniappManifest";
|
||||
import type { ProposalRecord, RosterEntry } from "../lib/assembly";
|
||||
import type { HousingPreference, HousingSlot, SolveHousingInput } from "../lib/housing";
|
||||
import { buildRankedCyclePreferences } from "../lib/housing";
|
||||
import type { HousingResidentNeeds, HousingSlot, SolveHousingInput } from "../lib/housing";
|
||||
import type { HazardReportInput, HazardReportPayload } from "../lib/tunnelsafety";
|
||||
import type { PlantingPlot, CropMaturityWindow, TemperatureEntry } from "../lib/farms";
|
||||
import type { UnsignedEventLogEntry } from "../lib/eventlog";
|
||||
@@ -260,9 +261,9 @@ export const DEMO_SAMPLE_MINIAPP_HTML = `<html xmlns="http://www.w3.org/1999/xht
|
||||
* 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 },
|
||||
{ id: "hollow-housing-slot-1", capacity: 1, stepFree: true, distanceToMedicalMeters: 60 },
|
||||
{ id: "hollow-housing-slot-2", capacity: 1, stepFree: true, distanceToMedicalMeters: 150 },
|
||||
{ id: "hollow-housing-slot-3", capacity: 1, stepFree: false, distanceToMedicalMeters: 500 },
|
||||
];
|
||||
|
||||
export const HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS = [
|
||||
@@ -275,35 +276,37 @@ export const HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS = [
|
||||
* 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`.
|
||||
* `recordHousingAssignmentCycle()` from `src/lib/housing.ts`. Preferences
|
||||
* are built through the SAME production preference-builder
|
||||
* (`buildRankedCyclePreferences`) the resident-run cycle uses - not a
|
||||
* hand-rolled score matrix - so the demo fixture exercises the exact
|
||||
* accessibility hard-exclusion a real cycle would apply.
|
||||
*/
|
||||
export function buildDemoHousingCycleInput(
|
||||
agent: string,
|
||||
): Omit<SolveHousingInput, "fairnessDebt"> {
|
||||
const residents = [agent, ...HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS];
|
||||
const slots = HOLLOW_DEMO_HOUSING_SLOTS;
|
||||
// Best-first slot ranking per resident, indexed by position in `residents`.
|
||||
// The demo-loading identity (index 0) and the first neighbor (index 1) both
|
||||
// rank the first single-capacity slot highest, so they genuinely contest it;
|
||||
// the second neighbor ranks a different slot highest, so it stays
|
||||
// uncontested and the instance remains feasible and hand-checkable.
|
||||
const rankings: string[][] = [
|
||||
[slots[0].id, slots[1].id, slots[2].id], // demo identity: slot 1 best (contested)
|
||||
[slots[0].id, slots[1].id, slots[2].id], // neighbor B: slot 1 best (contested)
|
||||
[slots[2].id, slots[1].id, slots[0].id], // neighbor C: slot 3 best (uncontested)
|
||||
];
|
||||
const preferences: HousingPreference[] = [];
|
||||
for (let i = 0; i < residents.length; i++) {
|
||||
const ranking = rankings[i];
|
||||
for (const slot of slots) {
|
||||
// Top-ranked slot scores highest, each lower rank one less - so a
|
||||
// resident denied their top slot has a real, positive preference
|
||||
// shortfall (= fairness debt), never the uniform score that pinned every
|
||||
// shortfall to zero.
|
||||
const score = slots.length - ranking.indexOf(slot.id);
|
||||
preferences.push({ residentId: residents[i], slotId: slot.id, score });
|
||||
}
|
||||
}
|
||||
const [neighborB, neighborC] = HOLLOW_DEMO_HOUSING_NEIGHBOR_RESIDENTS;
|
||||
// Best-first slot ranking per resident. The demo-loading identity and
|
||||
// neighbor B both genuinely rank slot 1 highest, so they contest it -
|
||||
// same fairness-debt-rotation shape this fixture has always exercised
|
||||
// (see the "makes two residents contest one slot" test below). Neighbor
|
||||
// C's genuine top choice is slot 3 - but slot 3 is NOT step-free
|
||||
// (`HOLLOW_DEMO_HOUSING_SLOTS` above) and neighbor C requires step-free
|
||||
// access (`residentNeeds` below), so `buildRankedCyclePreferences` hard-
|
||||
// excludes that pair: neighbor C is never assigned slot 3, no matter how
|
||||
// highly they rank it - a real, provable accessibility exclusion, not
|
||||
// prose.
|
||||
const rankings = new Map<string, string[]>([
|
||||
[agent, [slots[0].id, slots[1].id, slots[2].id]],
|
||||
[neighborB, [slots[0].id, slots[1].id, slots[2].id]],
|
||||
[neighborC, [slots[2].id, slots[1].id, slots[0].id]],
|
||||
]);
|
||||
const residentNeeds = new Map<string, HousingResidentNeeds>([
|
||||
[neighborC, { residentId: neighborC, requiresStepFree: true }],
|
||||
]);
|
||||
const preferences = buildRankedCyclePreferences({ residents, slots, rankings, residentNeeds });
|
||||
return { residents, slots, preferences };
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { init } from "./identity";
|
||||
import {
|
||||
buildRankedCyclePreferences,
|
||||
computeFairnessDebtLedger,
|
||||
computeResidentHousingNeeds,
|
||||
computeSlotPreferenceRankings,
|
||||
discoverAvailableSlots,
|
||||
extractHousingCycles,
|
||||
@@ -14,12 +15,14 @@ import {
|
||||
isHousingAssignmentPayload,
|
||||
isHousingSlotPreferencePayload,
|
||||
isHousingSpaceReportPayload,
|
||||
isSlotEligibleForResidentNeeds,
|
||||
nextHousingCycleNumber,
|
||||
recordHousingAssignmentCycle,
|
||||
recordSlotPreference,
|
||||
reportIdleSpace,
|
||||
solveHousingAssignment,
|
||||
type HousingPreference,
|
||||
type HousingResidentNeeds,
|
||||
type HousingSlot,
|
||||
} from "./housing";
|
||||
|
||||
@@ -785,3 +788,168 @@ describe("housing fairness-debt rotation moves from in-app rankings (H2 fix)", (
|
||||
expect(ledger.r1).toBe(1); // r1 is now the loser - the rotation moved
|
||||
});
|
||||
});
|
||||
|
||||
describe("accessibility and medical-proximity are real, enforced hard constraints (coherence-audit fix)", () => {
|
||||
it("isSlotEligibleForResidentNeeds excludes a non-step-free slot for a resident who requires step-free access", () => {
|
||||
const stepFreeSlot: HousingSlot = { id: "ramped", capacity: 1, stepFree: true };
|
||||
const stairsOnlySlot: HousingSlot = { id: "stairs-only", capacity: 1, stepFree: false };
|
||||
const needs: HousingResidentNeeds = { residentId: "r1", requiresStepFree: true };
|
||||
|
||||
expect(isSlotEligibleForResidentNeeds(stepFreeSlot, needs)).toBe(true);
|
||||
expect(isSlotEligibleForResidentNeeds(stairsOnlySlot, needs)).toBe(false);
|
||||
// A slot with no stepFree assertion at all is never assumed step-free.
|
||||
expect(isSlotEligibleForResidentNeeds({ id: "unknown", capacity: 1 }, needs)).toBe(false);
|
||||
});
|
||||
|
||||
it("isSlotEligibleForResidentNeeds excludes a slot beyond the high-medical-urgency distance threshold", () => {
|
||||
const near: HousingSlot = { id: "near", capacity: 1, distanceToMedicalMeters: 50 };
|
||||
const far: HousingSlot = { id: "far", capacity: 1, distanceToMedicalMeters: 1000 };
|
||||
const needs: HousingResidentNeeds = { residentId: "r1", medicalUrgency: "high" };
|
||||
|
||||
expect(isSlotEligibleForResidentNeeds(near, needs)).toBe(true);
|
||||
expect(isSlotEligibleForResidentNeeds(far, needs)).toBe(false);
|
||||
// Unknown distance is never assumed close enough for a high-urgency need.
|
||||
expect(isSlotEligibleForResidentNeeds({ id: "unmeasured", capacity: 1 }, needs)).toBe(false);
|
||||
});
|
||||
|
||||
it("a resident with no needs stays eligible for every slot regardless of stepFree/distance - the filter only narrows", () => {
|
||||
const slot: HousingSlot = { id: "any", capacity: 1, stepFree: false, distanceToMedicalMeters: 9999 };
|
||||
expect(isSlotEligibleForResidentNeeds(slot, undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("buildRankedCyclePreferences never assigns a step-free-requiring resident to a non-step-free slot, even when it is their top-ranked preference and would otherwise win the contested slot", () => {
|
||||
const slots: HousingSlot[] = [
|
||||
{ id: "ramped", capacity: 1, stepFree: true, distanceToMedicalMeters: 50 },
|
||||
{ id: "stairs-only", capacity: 1, stepFree: false, distanceToMedicalMeters: 50 },
|
||||
];
|
||||
const rankings = new Map<string, string[]>([
|
||||
// r1's genuine top choice is the non-step-free slot.
|
||||
["r1", ["stairs-only", "ramped"]],
|
||||
["r2", ["ramped", "stairs-only"]],
|
||||
]);
|
||||
const residentNeeds = new Map<string, HousingResidentNeeds>([
|
||||
["r1", { residentId: "r1", requiresStepFree: true }],
|
||||
]);
|
||||
const preferences = buildRankedCyclePreferences({
|
||||
residents: ["r1", "r2"],
|
||||
slots,
|
||||
rankings,
|
||||
residentNeeds,
|
||||
});
|
||||
|
||||
// The hard-exclusion mechanism: r1 has NO preference entry at all for
|
||||
// the non-step-free slot, even though they ranked it first.
|
||||
expect(
|
||||
preferences.find((p) => p.residentId === "r1" && p.slotId === "stairs-only"),
|
||||
).toBeUndefined();
|
||||
|
||||
const result = solveHousingAssignment({ residents: ["r1", "r2"], slots, preferences });
|
||||
expect(result.status).toBe("optimal");
|
||||
if (result.status !== "optimal") return;
|
||||
expect(result.assignments).toContainEqual(
|
||||
expect.objectContaining({ residentId: "r1", slotId: "ramped" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("buildRankedCyclePreferences never assigns a high-medical-urgency resident to a slot beyond the proximity threshold, even when it is their top-ranked preference", () => {
|
||||
const slots: HousingSlot[] = [
|
||||
{ id: "near-medical", capacity: 1, stepFree: true, distanceToMedicalMeters: 50 },
|
||||
{ id: "far-from-medical", capacity: 1, stepFree: true, distanceToMedicalMeters: 1000 },
|
||||
];
|
||||
const rankings = new Map<string, string[]>([
|
||||
["r1", ["far-from-medical", "near-medical"]],
|
||||
["r2", ["near-medical", "far-from-medical"]],
|
||||
]);
|
||||
const residentNeeds = new Map<string, HousingResidentNeeds>([
|
||||
["r1", { residentId: "r1", medicalUrgency: "high" }],
|
||||
]);
|
||||
const preferences = buildRankedCyclePreferences({
|
||||
residents: ["r1", "r2"],
|
||||
slots,
|
||||
rankings,
|
||||
residentNeeds,
|
||||
});
|
||||
|
||||
expect(
|
||||
preferences.find((p) => p.residentId === "r1" && p.slotId === "far-from-medical"),
|
||||
).toBeUndefined();
|
||||
|
||||
const result = solveHousingAssignment({ residents: ["r1", "r2"], slots, preferences });
|
||||
expect(result.status).toBe("optimal");
|
||||
if (result.status !== "optimal") return;
|
||||
expect(result.assignments).toContainEqual(
|
||||
expect.objectContaining({ residentId: "r1", slotId: "near-medical" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports infeasible (never force-fits) when a step-free-requiring resident has zero step-free slots available", () => {
|
||||
const slots: HousingSlot[] = [
|
||||
{ id: "stairs-only", capacity: 1, stepFree: false, distanceToMedicalMeters: 50 },
|
||||
];
|
||||
const rankings = new Map<string, string[]>([["r1", ["stairs-only"]]]);
|
||||
const residentNeeds = new Map<string, HousingResidentNeeds>([
|
||||
["r1", { residentId: "r1", requiresStepFree: true }],
|
||||
]);
|
||||
const preferences = buildRankedCyclePreferences({
|
||||
residents: ["r1"],
|
||||
slots,
|
||||
rankings,
|
||||
residentNeeds,
|
||||
});
|
||||
|
||||
const result = solveHousingAssignment({ residents: ["r1"], slots, preferences });
|
||||
expect(result.status).toBe("infeasible");
|
||||
if (result.status !== "infeasible") return;
|
||||
expect(result.reason).toContain("r1");
|
||||
});
|
||||
|
||||
it("a resident who expresses no accessibility/medical need stays eligible for every slot, unchanged from before this fix", () => {
|
||||
const slots: HousingSlot[] = [
|
||||
{ id: "a", capacity: 1, stepFree: false, distanceToMedicalMeters: 9999 },
|
||||
{ id: "b", capacity: 1, stepFree: true, distanceToMedicalMeters: 10 },
|
||||
];
|
||||
const rankings = new Map<string, string[]>([["r1", ["a", "b"]]]);
|
||||
const preferences = buildRankedCyclePreferences({ residents: ["r1"], slots, rankings });
|
||||
expect(preferences).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("recordSlotPreference / computeResidentHousingNeeds (accessibility + medical-urgency write + replay path)", () => {
|
||||
it("persists requiresStepFree/medicalUrgency on the signed housing.preference event and replays them back as the resident's needs", async () => {
|
||||
await recordSlotPreference({
|
||||
residentId: "r1",
|
||||
ranking: ["good"],
|
||||
requiresStepFree: true,
|
||||
medicalUrgency: "high",
|
||||
});
|
||||
|
||||
const all = await readAll();
|
||||
expect(isHousingSlotPreferencePayload(all[0].payload)).toBe(true);
|
||||
expect(all[0].payload).toMatchObject({ requiresStepFree: true, medicalUrgency: "high" });
|
||||
expect(computeResidentHousingNeeds(all).get("r1")).toEqual({
|
||||
residentId: "r1",
|
||||
requiresStepFree: true,
|
||||
medicalUrgency: "high",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an invalid medicalUrgency value before signing, persisting nothing", async () => {
|
||||
await expect(
|
||||
recordSlotPreference({
|
||||
residentId: "r1",
|
||||
ranking: ["good"],
|
||||
medicalUrgency: "urgent" as unknown as "high",
|
||||
}),
|
||||
).rejects.toThrow(InvalidHousingSlotPreferenceError);
|
||||
expect(await readAll()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("leaves requiresStepFree/medicalUrgency unset when a resident never submitted a need, so they stay eligible for every slot", async () => {
|
||||
await recordSlotPreference({ residentId: "r1", ranking: ["good"] });
|
||||
const all = await readAll();
|
||||
const needs = computeResidentHousingNeeds(all).get("r1");
|
||||
expect(needs?.requiresStepFree).toBeFalsy();
|
||||
expect(needs?.medicalUrgency).not.toBe("high");
|
||||
expect(isSlotEligibleForResidentNeeds({ id: "any", capacity: 1 }, needs)).toBe(true);
|
||||
});
|
||||
});
|
||||
+184
-18
@@ -21,13 +21,24 @@ import { trySyncWithBackend } from "./sync";
|
||||
* weighted by each resident's accumulated fairness debt.
|
||||
*
|
||||
* Hard constraints (capacity, and which slots a resident is even eligible
|
||||
* for - step-free access, family cohesion, medical proximity, etc., all
|
||||
* expressed by simply omitting an ineligible resident/slot pair from
|
||||
* `preferences`) are never relaxed to force a feasible solution: an
|
||||
* instance that cannot satisfy every resident's exactly-one-slot
|
||||
* requirement together with every slot's capacity is reported back as
|
||||
* `status: "infeasible"` with a reason, never silently truncated or
|
||||
* force-fit (finding: must not hide infeasibility).
|
||||
* for - step-free access and medical proximity, expressed by simply
|
||||
* omitting an ineligible resident/slot pair from `preferences`) are never
|
||||
* relaxed to force a feasible solution: an instance that cannot satisfy
|
||||
* every resident's exactly-one-slot requirement together with every
|
||||
* slot's capacity is reported back as `status: "infeasible"` with a
|
||||
* reason, never silently truncated or force-fit (finding: must not hide
|
||||
* infeasibility).
|
||||
*
|
||||
* Accessibility and medical-proximity are genuinely wired, not prose:
|
||||
* `HousingSlot` carries `stepFree`/`distanceToMedicalMeters`, a resident's
|
||||
* own `HousingResidentNeeds` (requiresStepFree/medicalUrgency, captured by
|
||||
* `SlotPreferenceForm` and replayed via `computeResidentHousingNeeds`) is
|
||||
* read alongside their ranking, and `buildRankedCyclePreferences` omits
|
||||
* any (resident, slot) pair that fails either requirement via
|
||||
* `isSlotEligibleForResidentNeeds` - a real hard exclusion that changes
|
||||
* the solver's actual eligible-pair set. Family cohesion is NOT yet
|
||||
* implemented (no `familyGroupId` field or grouping rule exists anywhere)
|
||||
* - a disclosed gap, not a claimed capability.
|
||||
*
|
||||
* Fairness over time: a `housing.assignment` event signed through the
|
||||
* real Event Log `append()` path (src/lib/eventlog.ts) carries the
|
||||
@@ -45,6 +56,16 @@ import { trySyncWithBackend } from "./sync";
|
||||
export interface HousingSlot {
|
||||
id: string;
|
||||
capacity: number;
|
||||
/** Whether this slot is step-free/wheelchair-accessible. Omitted (or
|
||||
* `false`) means NOT asserted step-free - a slot is only ever treated as
|
||||
* step-free when this is explicitly `true`, never assumed from absence
|
||||
* of information (see `isSlotEligibleForResidentNeeds`). */
|
||||
stepFree?: boolean;
|
||||
/** Straight-line distance from this slot to the nearest staffed medical
|
||||
* post, in meters. Omitted means unknown/unmeasured - treated as NOT
|
||||
* provably close enough for a high-medical-urgency resident, the same
|
||||
* "absence is never assumed favorable" rule as `stepFree`. */
|
||||
distanceToMedicalMeters?: number;
|
||||
}
|
||||
|
||||
/** One resident's eligibility + preference score for one slot. A
|
||||
@@ -58,6 +79,61 @@ export interface HousingPreference {
|
||||
score: number;
|
||||
}
|
||||
|
||||
/** One resident's own accessibility/medical-urgency need, read alongside
|
||||
* their slot preferences. Captured from a real resident input
|
||||
* (`SlotPreferenceForm`'s step-free checkbox + medical-urgency select,
|
||||
* `src/miniapps/housing/FloorPlanScreen.tsx`) or the admin demo fixture -
|
||||
* never a hardcoded default baked into the solver. */
|
||||
export interface HousingResidentNeeds {
|
||||
residentId: string;
|
||||
/** True if this resident requires a step-free/wheelchair-accessible
|
||||
* slot. A slot without `HousingSlot.stepFree === true` is a hard
|
||||
* exclusion for this resident, never a soft preference. */
|
||||
requiresStepFree?: boolean;
|
||||
/** How urgently this resident needs to stay close to medical care.
|
||||
* `"high"` hard-excludes any slot farther than
|
||||
* `HIGH_MEDICAL_URGENCY_MAX_DISTANCE_METERS` from the nearest medical
|
||||
* post. */
|
||||
medicalUrgency?: "none" | "moderate" | "high";
|
||||
}
|
||||
|
||||
/**
|
||||
* Distance beyond which a slot is excluded for a resident with
|
||||
* `medicalUrgency: "high"` - chosen as a brisk ~2-3 minute walk/wheel at a
|
||||
* typical indoor pace (roughly 60-100m/min for someone with a mobility
|
||||
* need), the rough window within which an emergency escort to the medical
|
||||
* post still matters. A documented engineering judgment call, not a
|
||||
* clinical standard.
|
||||
*/
|
||||
export const HIGH_MEDICAL_URGENCY_MAX_DISTANCE_METERS = 200;
|
||||
|
||||
/**
|
||||
* The real eligibility gate behind the solver's "omit an ineligible pair"
|
||||
* mechanism (this file's top doc comment): `false` means `slot` must never
|
||||
* appear in `buildRankedCyclePreferences`'s output for this resident, a
|
||||
* hard exclusion the MILP can never relax. `needs === undefined` means the
|
||||
* resident expressed no accessibility/medical requirement, so every slot
|
||||
* stays eligible (physical eligibility unchanged, exactly today's
|
||||
* behavior for a resident who never filled in the new fields).
|
||||
*/
|
||||
export function isSlotEligibleForResidentNeeds(
|
||||
slot: HousingSlot,
|
||||
needs: HousingResidentNeeds | undefined,
|
||||
): boolean {
|
||||
if (needs === undefined) return true;
|
||||
if (needs.requiresStepFree === true && slot.stepFree !== true) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
needs.medicalUrgency === "high" &&
|
||||
(slot.distanceToMedicalMeters === undefined ||
|
||||
slot.distanceToMedicalMeters > HIGH_MEDICAL_URGENCY_MAX_DISTANCE_METERS)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export interface SolveHousingInput {
|
||||
residents: string[];
|
||||
slots: HousingSlot[];
|
||||
@@ -144,6 +220,14 @@ export interface HousingSpaceReportInput {
|
||||
location: string;
|
||||
capacity: number;
|
||||
idleHoursPerDay: number;
|
||||
/** Whether this reported space is step-free/wheelchair-accessible.
|
||||
* Optional - a space reported with no assertion is never treated as
|
||||
* step-free for a resident who requires it. */
|
||||
stepFree?: boolean;
|
||||
/** Straight-line distance from this space to the nearest staffed
|
||||
* medical post, in meters. Optional - a space with no known distance is
|
||||
* never treated as within reach of a high-medical-urgency resident. */
|
||||
distanceToMedicalMeters?: number;
|
||||
}
|
||||
|
||||
export interface HousingSpaceReportPayload {
|
||||
@@ -152,6 +236,8 @@ export interface HousingSpaceReportPayload {
|
||||
location: string;
|
||||
capacity: number;
|
||||
idleHoursPerDay: number;
|
||||
stepFree?: boolean;
|
||||
distanceToMedicalMeters?: number;
|
||||
reportedAt: number;
|
||||
}
|
||||
|
||||
@@ -195,6 +281,14 @@ export function validateHousingSpaceReportInput(input: HousingSpaceReportInput):
|
||||
`idleHoursPerDay must be between 0 and 24, got ${input.idleHoursPerDay}`,
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.distanceToMedicalMeters !== undefined &&
|
||||
(!Number.isFinite(input.distanceToMedicalMeters) || input.distanceToMedicalMeters < 0)
|
||||
) {
|
||||
throw new InvalidHousingSpaceReportError(
|
||||
`distanceToMedicalMeters must be a non-negative finite number when provided, got ${input.distanceToMedicalMeters}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function isHousingSpaceReportPayload(
|
||||
@@ -215,6 +309,11 @@ export function isHousingSpaceReportPayload(
|
||||
Number.isFinite(p.idleHoursPerDay) &&
|
||||
p.idleHoursPerDay >= 0 &&
|
||||
p.idleHoursPerDay <= 24 &&
|
||||
(p.stepFree === undefined || typeof p.stepFree === "boolean") &&
|
||||
(p.distanceToMedicalMeters === undefined ||
|
||||
(typeof p.distanceToMedicalMeters === "number" &&
|
||||
Number.isFinite(p.distanceToMedicalMeters) &&
|
||||
p.distanceToMedicalMeters >= 0)) &&
|
||||
typeof p.reportedAt === "number"
|
||||
);
|
||||
}
|
||||
@@ -235,6 +334,8 @@ export async function reportIdleSpace(
|
||||
location: input.location,
|
||||
capacity: input.capacity,
|
||||
idleHoursPerDay: input.idleHoursPerDay,
|
||||
stepFree: input.stepFree,
|
||||
distanceToMedicalMeters: input.distanceToMedicalMeters,
|
||||
reportedAt: Date.now(),
|
||||
};
|
||||
const entry = await append(payload);
|
||||
@@ -258,8 +359,13 @@ export function discoverAvailableSlots(entries: readonly StoredEventLogEntry[]):
|
||||
const slots = new Map<string, HousingSlot>();
|
||||
for (const entry of sortForReplay(entries)) {
|
||||
if (!isHousingSpaceReportPayload(entry.payload)) continue;
|
||||
const { spaceId, capacity, idleHoursPerDay } = entry.payload;
|
||||
slots.set(spaceId, { id: spaceId, capacity: capacity * (idleHoursPerDay / 24) });
|
||||
const { spaceId, capacity, idleHoursPerDay, stepFree, distanceToMedicalMeters } = entry.payload;
|
||||
slots.set(spaceId, {
|
||||
id: spaceId,
|
||||
capacity: capacity * (idleHoursPerDay / 24),
|
||||
stepFree,
|
||||
distanceToMedicalMeters,
|
||||
});
|
||||
}
|
||||
return [...slots.values()];
|
||||
}
|
||||
@@ -279,12 +385,21 @@ export interface HousingSlotPreferenceInput {
|
||||
residentId: string;
|
||||
/** Slot ids best-first. Must be non-empty, unique, non-blank strings. */
|
||||
ranking: string[];
|
||||
/** True if this resident requires a step-free/wheelchair-accessible
|
||||
* slot - a real hard constraint, not a ranking preference. */
|
||||
requiresStepFree?: boolean;
|
||||
/** This resident's medical urgency. `"high"` hard-excludes any slot
|
||||
* farther than `HIGH_MEDICAL_URGENCY_MAX_DISTANCE_METERS` from medical
|
||||
* care. */
|
||||
medicalUrgency?: "none" | "moderate" | "high";
|
||||
}
|
||||
|
||||
export interface HousingSlotPreferencePayload {
|
||||
type: "housing.preference";
|
||||
residentId: string;
|
||||
ranking: string[];
|
||||
requiresStepFree?: boolean;
|
||||
medicalUrgency?: "none" | "moderate" | "high";
|
||||
reportedAt: number;
|
||||
}
|
||||
|
||||
@@ -324,6 +439,16 @@ export function validateHousingSlotPreferenceInput(input: HousingSlotPreferenceI
|
||||
}
|
||||
seen.add(slotId);
|
||||
}
|
||||
if (
|
||||
input.medicalUrgency !== undefined &&
|
||||
input.medicalUrgency !== "none" &&
|
||||
input.medicalUrgency !== "moderate" &&
|
||||
input.medicalUrgency !== "high"
|
||||
) {
|
||||
throw new InvalidHousingSlotPreferenceError(
|
||||
`medicalUrgency must be "none", "moderate", or "high", got "${input.medicalUrgency}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function isHousingSlotPreferencePayload(
|
||||
@@ -338,6 +463,11 @@ export function isHousingSlotPreferencePayload(
|
||||
Array.isArray(p.ranking) &&
|
||||
p.ranking.length > 0 &&
|
||||
p.ranking.every((id) => typeof id === "string" && id.trim().length > 0) &&
|
||||
(p.requiresStepFree === undefined || typeof p.requiresStepFree === "boolean") &&
|
||||
(p.medicalUrgency === undefined ||
|
||||
p.medicalUrgency === "none" ||
|
||||
p.medicalUrgency === "moderate" ||
|
||||
p.medicalUrgency === "high") &&
|
||||
typeof p.reportedAt === "number"
|
||||
);
|
||||
}
|
||||
@@ -356,6 +486,8 @@ export async function recordSlotPreference(
|
||||
type: "housing.preference",
|
||||
residentId: input.residentId,
|
||||
ranking: [...input.ranking],
|
||||
requiresStepFree: input.requiresStepFree,
|
||||
medicalUrgency: input.medicalUrgency,
|
||||
reportedAt: Date.now(),
|
||||
};
|
||||
const entry = await append(payload);
|
||||
@@ -383,6 +515,31 @@ export function computeSlotPreferenceRankings(
|
||||
return rankings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays the signed Event Log into each resident's current
|
||||
* accessibility/medical-urgency need, folded in deterministic
|
||||
* `sortForReplay` order so a later preference submission for the same
|
||||
* resident supersedes an earlier one - the same fold-and-overwrite-by-key
|
||||
* replay shape `computeSlotPreferenceRankings` uses for rankings. A
|
||||
* resident who never submitted `requiresStepFree`/`medicalUrgency` has no
|
||||
* entry here, so `isSlotEligibleForResidentNeeds` treats them as having no
|
||||
* requirement (every slot stays eligible, unchanged from today).
|
||||
*/
|
||||
export function computeResidentHousingNeeds(
|
||||
entries: readonly StoredEventLogEntry[],
|
||||
): Map<string, HousingResidentNeeds> {
|
||||
const needs = new Map<string, HousingResidentNeeds>();
|
||||
for (const entry of sortForReplay(entries)) {
|
||||
if (!isHousingSlotPreferencePayload(entry.payload)) continue;
|
||||
needs.set(entry.payload.residentId, {
|
||||
residentId: entry.payload.residentId,
|
||||
requiresStepFree: entry.payload.requiresStepFree,
|
||||
medicalUrgency: entry.payload.medicalUrgency,
|
||||
});
|
||||
}
|
||||
return needs;
|
||||
}
|
||||
|
||||
/** Baseline fit score for a slot a resident has expressed no ranking over -
|
||||
* kept at 1 (not 0) so every resident stays eligible for every discovered
|
||||
* commons slot and a ranked slot always scores strictly above an unranked
|
||||
@@ -391,27 +548,36 @@ export const UNRANKED_SLOT_SCORE = 1;
|
||||
|
||||
/**
|
||||
* Turns per-resident slot rankings into the real, differentiated
|
||||
* `HousingPreference[]` a cycle solves over (H2 fix). Every resident stays
|
||||
* eligible for every discovered slot (physical eligibility is unchanged -
|
||||
* preference, not eligibility, is what differentiates), but a resident's
|
||||
* top-ranked slot scores highest and each lower-ranked slot scores one
|
||||
* less, with any slot they did not rank falling to `UNRANKED_SLOT_SCORE`.
|
||||
* A resident with no recorded ranking gets the flat baseline over every
|
||||
* slot (no expressed preference => no grievance => zero shortfall), so the
|
||||
* fairness-debt rotation only moves for residents who actually voiced a
|
||||
* preference. Pure: no Event Log/DB access.
|
||||
* `HousingPreference[]` a cycle solves over (H2 fix), hard-excluding any
|
||||
* (resident, slot) pair that fails the resident's own accessibility/
|
||||
* medical-proximity need (`residentNeeds`, via
|
||||
* `isSlotEligibleForResidentNeeds`) - the solver's documented "omit an
|
||||
* ineligible pair" mechanism, genuinely wired. A resident with no entry in
|
||||
* `residentNeeds` (or no accessibility/medical requirement) stays eligible
|
||||
* for every discovered slot exactly as before - this filter only narrows,
|
||||
* never widens, who a resident can be assigned to. Among the slots that
|
||||
* remain eligible, a resident's top-ranked slot scores highest and each
|
||||
* lower-ranked slot scores one less, with any slot they did not rank
|
||||
* falling to `UNRANKED_SLOT_SCORE`. A resident with no recorded ranking
|
||||
* gets the flat baseline over every eligible slot (no expressed preference
|
||||
* => no grievance => zero shortfall), so the fairness-debt rotation only
|
||||
* moves for residents who actually voiced a preference. Pure: no Event
|
||||
* Log/DB access.
|
||||
*/
|
||||
export function buildRankedCyclePreferences(input: {
|
||||
residents: string[];
|
||||
slots: HousingSlot[];
|
||||
rankings: Map<string, string[]>;
|
||||
residentNeeds?: Map<string, HousingResidentNeeds>;
|
||||
}): HousingPreference[] {
|
||||
const slotIds = new Set(input.slots.map((slot) => slot.id));
|
||||
const preferences: HousingPreference[] = [];
|
||||
for (const residentId of input.residents) {
|
||||
const ranking = (input.rankings.get(residentId) ?? []).filter((id) => slotIds.has(id));
|
||||
const rankIndex = new Map(ranking.map((id, index) => [id, index]));
|
||||
const needs = input.residentNeeds?.get(residentId);
|
||||
for (const slot of input.slots) {
|
||||
if (!isSlotEligibleForResidentNeeds(slot, needs)) continue;
|
||||
const index = rankIndex.get(slot.id);
|
||||
const score =
|
||||
index === undefined
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useState, type FormEvent } from "react";
|
||||
import { readAll } from "../../lib/eventlog.ts";
|
||||
import {
|
||||
buildRankedCyclePreferences,
|
||||
computeResidentHousingNeeds,
|
||||
computeSlotPreferenceRankings,
|
||||
discoverAvailableSlots,
|
||||
extractHousingCycles,
|
||||
@@ -32,6 +33,8 @@ function ReportSpaceForm() {
|
||||
const [location, setLocation] = useState("");
|
||||
const [capacity, setCapacity] = useState("1");
|
||||
const [idleHoursPerDay, setIdleHoursPerDay] = useState("8");
|
||||
const [stepFree, setStepFree] = useState(false);
|
||||
const [distanceToMedicalMeters, setDistanceToMedicalMeters] = useState("");
|
||||
const [submitStatus, setSubmitStatus] = useState<ReportSubmitStatus>("idle");
|
||||
const [errorMessage, setErrorMessage] = useState<string>();
|
||||
|
||||
@@ -45,10 +48,15 @@ function ReportSpaceForm() {
|
||||
location,
|
||||
capacity: Number(capacity),
|
||||
idleHoursPerDay: Number(idleHoursPerDay),
|
||||
stepFree,
|
||||
distanceToMedicalMeters:
|
||||
distanceToMedicalMeters.trim() === "" ? undefined : Number(distanceToMedicalMeters),
|
||||
});
|
||||
setSubmitStatus("submitted");
|
||||
setSpaceId("");
|
||||
setLocation("");
|
||||
setStepFree(false);
|
||||
setDistanceToMedicalMeters("");
|
||||
} catch (error) {
|
||||
setSubmitStatus("error");
|
||||
setErrorMessage(
|
||||
@@ -107,6 +115,26 @@ function ReportSpaceForm() {
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className={styles.field}>
|
||||
<span>Step-free access</span>
|
||||
<input
|
||||
type="checkbox"
|
||||
data-testid="housing-report-step-free"
|
||||
checked={stepFree}
|
||||
onChange={(event) => setStepFree(event.target.checked)}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className={styles.field}>
|
||||
<span>Distance to nearest medical post (meters)</span>
|
||||
<input
|
||||
type="number"
|
||||
data-testid="housing-report-medical-distance"
|
||||
value={distanceToMedicalMeters}
|
||||
onChange={(event) => setDistanceToMedicalMeters(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className={styles.submit}
|
||||
@@ -137,6 +165,8 @@ function ReportSpaceForm() {
|
||||
*/
|
||||
function SlotPreferenceForm({ accountId, slots }: { accountId: string; slots: HousingSlot[] }) {
|
||||
const [ranks, setRanks] = useState<Record<string, string>>({});
|
||||
const [requiresStepFree, setRequiresStepFree] = useState(false);
|
||||
const [medicalUrgency, setMedicalUrgency] = useState<"none" | "moderate" | "high">("none");
|
||||
const [submitStatus, setSubmitStatus] = useState<ReportSubmitStatus>("idle");
|
||||
const [errorMessage, setErrorMessage] = useState<string>();
|
||||
|
||||
@@ -155,7 +185,12 @@ function SlotPreferenceForm({ accountId, slots }: { accountId: string; slots: Ho
|
||||
)
|
||||
.sort((a, b) => a.rank - b.rank)
|
||||
.map((entry) => entry.slotId);
|
||||
await recordSlotPreference({ residentId: accountId, ranking });
|
||||
await recordSlotPreference({
|
||||
residentId: accountId,
|
||||
ranking,
|
||||
requiresStepFree,
|
||||
medicalUrgency,
|
||||
});
|
||||
setSubmitStatus("submitted");
|
||||
} catch (error) {
|
||||
setSubmitStatus("error");
|
||||
@@ -205,6 +240,31 @@ function SlotPreferenceForm({ accountId, slots }: { accountId: string; slots: Ho
|
||||
</label>
|
||||
))}
|
||||
|
||||
<label className={styles.field}>
|
||||
<span>I require step-free access</span>
|
||||
<input
|
||||
type="checkbox"
|
||||
data-testid="housing-pref-step-free"
|
||||
checked={requiresStepFree}
|
||||
onChange={(event) => setRequiresStepFree(event.target.checked)}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className={styles.field}>
|
||||
<span>Medical urgency</span>
|
||||
<select
|
||||
data-testid="housing-pref-medical-urgency"
|
||||
value={medicalUrgency}
|
||||
onChange={(event) =>
|
||||
setMedicalUrgency(event.target.value as "none" | "moderate" | "high")
|
||||
}
|
||||
>
|
||||
<option value="none">None</option>
|
||||
<option value="moderate">Moderate</option>
|
||||
<option value="high">High</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className={styles.submit}
|
||||
@@ -353,10 +413,12 @@ export function FloorPlanScreen() {
|
||||
// slots now scores their top choice highest; one who voiced no
|
||||
// preference keeps the flat baseline (no grievance, zero shortfall).
|
||||
const rankings = computeSlotPreferenceRankings(freshEntries);
|
||||
const residentNeeds = computeResidentHousingNeeds(freshEntries);
|
||||
const preferences = buildRankedCyclePreferences({
|
||||
residents: residentList,
|
||||
slots,
|
||||
rankings,
|
||||
residentNeeds,
|
||||
});
|
||||
const { result } = await recordHousingAssignmentCycle({
|
||||
residents: residentList,
|
||||
|
||||
Reference in new issue
Block a user