fix(findfamily): resident self-registration into the searchable directory

Closes the confirmed coherence gap in .omo/evidence/coherence-audit/findfamily.md
(finding #2): SEED_DIRECTORY was the only directory source anywhere, with no
append path and no findfamily.* Event Log payload type, so no resident could
ever be found however sound the PSI crypto was.

- Add findfamily.register payload type + type guard, and registerInDirectory()
  / extractRegisteredDirectoryEntries() in a new findfamilyEvents.ts, following
  the exact per-mini-app local-payload pattern (skyMemoryWall.ts/testimony.ts) -
  no central payload union exists in eventlog.ts to extend.
- registerInDirectory() signs and appends through the real append() (the sole
  local-signing write path) - never bypasses it.
- SearchScreen.tsx now reads the live Event Log via useEventLogEntries(),
  merges findfamily.register entries with SEED_DIRECTORY fresh on every
  render (same replay-only pattern as ledger.ts), and feeds the merged
  directory into both the local PSI channel and the nearby-device WebRTC
  channel. Added a "Register yourself or a missing family member" form with
  honest success/error states matching the search form's own pattern.
- Added findfamily.register to sync.ts's PUSH_TYPE_ALLOWLIST under the real
  identity key: a resident voluntarily registering as findable is the same
  "public community data" category as sky.memoryWall/testimony (not personal
  data like lightclock.*), and the whole point is being found by OTHER
  devices - documented reasoning inline, including why this does not
  reintroduce the plaintext-query leak directory.ts's doc comment warns
  about (that guarantee is unconditional regardless of where entries came
  from).
- README.md: one-line clarification that the privacy guarantee is on the
  searcher's query, not on directory membership.

Tests:
- findfamilyEvents.test.ts (new): payload guard, append+extract round trip,
  validation, distinct ids per registration, sync-wiring, and the real
  end-to-end behavioral proof - a name registered via registerInDirectory()
  is found by a genuine findFamilyMember()/PSI search merged with
  SEED_DIRECTORY, with every seed fixture still searchable unchanged.
- SearchScreen.test.tsx: three new tests driving the real UI form (register
  -> search -> match), confirming seed fixtures still work after an
  unrelated registration, and the empty-name guard.
- sync.test.ts: new test proving findfamily.register is now pushed under
  the real identity key (not a pseudonym), following the existing
  sky.memoryWall.entry/testimony.statement allowlist test pattern.

QA: targeted vitest (5 files / 44 tests) green, full npm run test green
(93 files / 848 tests), tsc -b clean for all touched files, oxlint has no
new errors (pre-existing warning baseline unchanged). npm run build
currently fails on src/miniapps/farms/FarmsScreen.tsx - that is unrelated,
uncommitted WIP from a concurrent session editing this same checkout
(confirmed via git diff; not part of this change, not staged here).
This commit is contained in:
OmO Orchestrator committed 2026-11-20 17:50:27 -05:00
1 parent eb726256ac
commit dd49df8e26
7 files changed
+469 -7

No files matched your search

+1 -1
View File
@@ -90,7 +90,7 @@ honest mechanism instead of shipping three thin, disconnected tools:
| P5 | Keep tunnels safe | **Tunnel Safety** (`ma-tunnelsafety`) | Crowd-sourced hazard reports plus A* routing around closed tunnel segments |
| P6 | Find/share space | **Housing** (`ma-housing`) | Constraint-based assignment engine (accessibility, family cohesion, medical proximity) with a fairness-debt ledger carried across cycles |
| P7, P13 | Organize without the network; prove the surface is safe | **Assembly** (`ma-assembly`) | Yjs CRDT for offline-first proposals/rosters/votes with liquid-democracy tally, a 3-layer resilience model (local-first, WebRTC partition-and-heal, QR-sneakernet air-gapped fallback), and a signed public testimony board reusing the same event-log infrastructure as group voting |
| P8 | Reconnect families | **Find Family** (`ma-findfamily`) | Private-set-intersection search so neither the relay nor the other party learns who searched unless there's a real match |
| P8 | Reconnect families | **Find Family** (`ma-findfamily`) | Private-set-intersection search so neither the relay nor the other party learns who searched unless there's a real match; a resident registers themselves or a missing family member to be found (a signed, publicly-synced `findfamily.register` event) - the privacy guarantee is on the *searcher's query*, not on directory membership |
| P9, P10 | Track outbreak, route supplies; care without a clinic | **Health Post** (`ma-healthpost`) | WHO-IMCI protocol-guided triage chat backed by real crowd symptom self-reports aggregated into a dispatch-facing tally |
| P11 | Life without sunlight | **Light Clock** (`ma-lightclock`) | Circadian phase-response model from a manual sleep/wake log or device actigraphy (rest/activity from the motion sensor); it never claims to measure light (the Hollow has none); a personal wellness tracker only, never wired to ration anything |
| P12 | Grow/share food | **Farms** (`ma-farms`) | Growing-degree-day model plus an LP planting optimizer under a fixed grow-light power budget, feeding Fair Share's food number |
+31
View File
@@ -267,6 +267,37 @@ describe("trySyncWithBackend", () => {
expect(moraleEntry.authorPubkey).not.toBe(symptomEntry.authorPubkey);
});
it("pushes a resident's Find Family self-registration under the REAL identity key (coherence-audit fix)", async () => {
// Find Family's registration (coherence-audit fix, findfamily.md finding
// #2): a resident voluntarily making themselves findable is public
// community data, same category as the memory wall/testimony board
// above - it pushes, and under the real identity key (no privacy
// benefit to hiding WHO registered a name, unlike mood/symptom data).
await append({ type: "findfamily.register", id: "fh-test1234", name: "Priya Nair" });
const realPublicKeyHex = hex(await getPublicKey());
let pushedBatch: Array<{ payload: { type?: string }; authorPubkey: string }> = [];
vi.stubGlobal(
"fetch",
vi.fn(async (_url: string, opts: { body: string }) => {
pushedBatch = (
JSON.parse(opts.body) as {
push: Array<{ payload: { type?: string }; authorPubkey: string }>;
}
).push;
return okResponse({ stored: pushedBatch.length, entries: [], cursor: 0 });
}),
);
const result = await trySyncWithBackend({ endpoint: "http://relay/api/sync" });
expect(result.ok).toBe(true);
expect(result.pushed).toBe(1);
const registerEntry = pushedBatch.find((e) => e.payload.type === "findfamily.register")!;
expect(registerEntry).toBeDefined();
expect(registerEntry.authorPubkey).toBe(realPublicKeyHex);
});
it("pulls another resident's memory-wall entry and testimony statement into the local replay", async () => {
// The flip side of the allowlist change: a peer's own-signed wall/board
// entries must actually land in THIS device's log via appendEntry's
+23
View File
@@ -145,6 +145,29 @@ export const PUSH_TYPE_ALLOWLIST: readonly string[] = [
// already calls `trySyncWithBackend()`; this allowlist entry is what makes
// that call actually leave the device.
"sky.memoryWall",
// Find Family's resident self-registration (coherence-audit fix,
// `.omo/evidence/coherence-audit/findfamily.md` finding #2): a resident
// voluntarily registering themselves or a missing family member as
// findable is exactly the "deliberate, consent-bearing" act this list's
// doc comment already describes `healthpost.referral` as - and the whole
// point of `findfamily.register` is to BE FOUND BY OTHER DEVICES/
// RESIDENTS, which is impossible if it never leaves this device. This is
// the same "public community data" category as `sky.memoryWall`/
// `testimony` above (not personal/passive data like `lightclock.*`): a
// resident who registers is explicitly choosing visibility, the same way
// a memory-wall post or testimony statement is. It syncs under the REAL
// identity key, not a pseudonym - unlike `healthpost.symptomReport`/
// `sky.morale.pulse`, there is no privacy benefit to hiding WHO registered
// a name (the name itself is the whole point of being findable), so a
// pseudonym would only add complexity with no payoff. This does not
// reintroduce the plaintext-roster leak `directory.ts`'s doc comment
// warns about: that warning is about the PSI *search query* never
// leaving a searcher's device, which `findfamily.ts`'s protocol still
// guarantees unconditionally regardless of where directory entries came
// from - it says nothing about registered *names* needing to stay secret
// from peers, any more than `sky.memoryWall.entry`/`testimony.statement`
// do.
"findfamily.register",
];
/**
+66 -1
View File
@@ -2,11 +2,20 @@
import "@testing-library/jest-dom/vitest";
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createLocalDirectoryChannel, type SearchRequest } from "../../lib/findfamily.ts";
import { db } from "../../lib/db.ts";
import { init } from "../../lib/identity.ts";
import { SEED_DIRECTORY } from "./directory.ts";
import { SearchScreen } from "./SearchScreen.tsx";
beforeEach(async () => {
indexedDB.deleteDatabase(db.name);
db.close();
await db.open();
await init();
});
afterEach(cleanup);
function spiedLocalChannel() {
@@ -163,3 +172,59 @@ describe("SearchScreen (nearby search failure - honest error, not a fabricated n
expect(screen.queryByTestId("findfamily-result-match")).not.toBeInTheDocument();
});
});
describe("SearchScreen (coherence-audit fix - real resident self-registration, findfamily.md finding #2)", () => {
it("a name registered through the real UI form becomes findable via a subsequent real PSI search, and the seed fixtures still work", async () => {
const user = userEvent.setup();
render(<SearchScreen />);
await user.type(screen.getByTestId("findfamily-register-input"), "Priya Nair");
await user.click(screen.getByTestId("findfamily-register-button"));
await waitFor(() => {
expect(screen.getByTestId("findfamily-register-status")).toHaveTextContent(
"Registered - now searchable",
);
});
expect(screen.getByTestId("findfamily-register-input")).toHaveValue("");
await user.type(screen.getByTestId("findfamily-search-input"), "Priya Nair");
await user.click(screen.getByTestId("findfamily-search-button"));
await waitFor(() => {
expect(screen.getByTestId("findfamily-result-match")).toHaveTextContent("Priya Nair");
});
});
it("still finds a SEED_DIRECTORY fixture after an unrelated resident registration, unchanged", async () => {
const user = userEvent.setup();
render(<SearchScreen />);
await user.type(screen.getByTestId("findfamily-register-input"), "Diego Flores");
await user.click(screen.getByTestId("findfamily-register-button"));
await waitFor(() => {
expect(screen.getByTestId("findfamily-register-status")).toHaveTextContent("Registered");
});
await user.type(screen.getByTestId("findfamily-search-input"), "Ana Ramirez");
await user.click(screen.getByTestId("findfamily-search-button"));
await waitFor(() => {
expect(screen.getByTestId("findfamily-result-match")).toHaveTextContent("Ana Ramirez");
});
});
it("rejects an empty-name registration without touching the Event Log, leaving existing search unaffected", async () => {
const user = userEvent.setup();
render(<SearchScreen />);
expect(screen.getByTestId("findfamily-register-button")).toBeDisabled();
await user.type(screen.getByTestId("findfamily-search-input"), "Jane Doe");
await user.click(screen.getByTestId("findfamily-search-button"));
await waitFor(() => {
expect(screen.getByTestId("findfamily-result-match")).toHaveTextContent("Jane Doe");
});
});
});
+97 -5
View File
@@ -1,14 +1,20 @@
import { useEffect, useState, type FormEvent } from "react";
import { useEffect, useMemo, useState, type FormEvent } from "react";
import {
createLocalDirectoryChannel,
findFamilyMember,
type DirectoryChannel,
type DirectoryEntry,
} from "../../lib/findfamily.ts";
import {
connectDirectorySync,
hasRealtimeDirectorySyncTransport,
} from "./findFamilySync.ts";
import { findDirectoryEntryById, SEED_DIRECTORY } from "./directory.ts";
import {
extractRegisteredDirectoryEntries,
registerInDirectory,
} from "./findfamilyEvents.ts";
import { useEventLogEntries } from "../../shell/useEventLogEntries.ts";
import styles from "./SearchScreen.module.css";
/** The one-line disclaimer finding D5 mandates: it must render in every
@@ -57,14 +63,37 @@ type SearchResult =
* do, so the plaintext query has nowhere to leak from this UI's surface.
*/
export function SearchScreen({
directoryChannel = createLocalDirectoryChannel(SEED_DIRECTORY),
directoryChannel: directoryChannelProp,
}: {
directoryChannel?: DirectoryChannel;
}) {
// Coherence-audit fix (finding #2): the searchable directory is no longer
// just the frozen `SEED_DIRECTORY` fixture - it is `SEED_DIRECTORY` plus
// whatever this device's own replayed Event Log holds as
// `findfamily.register` entries, read fresh on every render exactly like
// `ledger.ts`'s replay-only balances (see `findfamilyEvents.ts`).
const entries = useEventLogEntries();
const registeredEntries = useMemo(
() => extractRegisteredDirectoryEntries(entries),
[entries],
);
const directory = useMemo<DirectoryEntry[]>(
() => [...SEED_DIRECTORY, ...registeredEntries],
[registeredEntries],
);
const localChannel = useMemo(() => createLocalDirectoryChannel(directory), [directory]);
const directoryChannel = directoryChannelProp ?? localChannel;
const [queryName, setQueryName] = useState("");
const [result, setResult] = useState<SearchResult>({ status: "idle" });
const [isSearching, setIsSearching] = useState(false);
const [registerName, setRegisterName] = useState("");
const [registerStatus, setRegisterStatus] = useState<
"idle" | "registering" | "success" | "error"
>("idle");
const [registerError, setRegisterError] = useState("");
// "Search nearby devices" toggle (off by default, mirroring
// `useAssemblyEngine.ts`'s own `syncEnabled`/`hasRealtimeTransport()`
// pattern): while off, `activeChannel` below is always exactly
@@ -101,7 +130,7 @@ export function SearchScreen({
return undefined;
}
const sync = connectDirectorySync(nearbyCode, SEED_DIRECTORY);
const sync = connectDirectorySync(nearbyCode, directory);
setNearbyChannel(() => sync.channel);
function updatePeerCount() {
@@ -118,7 +147,7 @@ export function SearchScreen({
setPeerCount(0);
setNearbyChannel(null);
};
}, [nearbySearchEnabled, nearbyCode]);
}, [nearbySearchEnabled, nearbyCode, directory]);
const activeChannel: DirectoryChannel =
nearbySearchEnabled && nearbyChannel ? nearbyChannel : directoryChannel;
@@ -130,6 +159,22 @@ export function SearchScreen({
setJoinCodeInput("");
}
async function handleRegisterSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const trimmed = registerName.trim();
if (trimmed === "") return;
setRegisterStatus("registering");
try {
await registerInDirectory(trimmed);
setRegisterName("");
setRegisterStatus("success");
} catch (error) {
setRegisterStatus("error");
setRegisterError(error instanceof Error ? error.message : "Could not register.");
}
}
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const trimmed = queryName.trim();
@@ -142,7 +187,7 @@ export function SearchScreen({
setResult({ status: "no-match" });
return;
}
const matchedEntry = findDirectoryEntryById(SEED_DIRECTORY, matchId);
const matchedEntry = findDirectoryEntryById(directory, matchId);
setResult({
status: "match",
name: matchedEntry?.name ?? matchId,
@@ -224,6 +269,53 @@ export function SearchScreen({
)}
</div>
<form
className={styles.searchCard}
onSubmit={(event) => void handleRegisterSubmit(event)}
aria-label="Register yourself or a missing family member"
>
<div className={styles.cardLabel}>Register yourself or a missing family member</div>
<div className={styles.searchRow}>
<input
className={styles.searchInput}
type="text"
placeholder="Full name"
value={registerName}
onChange={(event) => {
setRegisterName(event.target.value);
if (registerStatus !== "idle") setRegisterStatus("idle");
}}
data-testid="findfamily-register-input"
/>
<button
className={styles.searchButton}
type="submit"
disabled={registerStatus === "registering" || registerName.trim() === ""}
data-testid="findfamily-register-button"
>
{registerStatus === "registering" ? "Registering\u2026" : "Register"}
</button>
</div>
{registerStatus === "success" && (
<p
className={styles.peerStatusConnected}
data-testid="findfamily-register-status"
role="status"
>
Registered - now searchable on this device (and any device that syncs this log).
</p>
)}
{registerStatus === "error" && (
<p
className={styles.resultEmpty}
data-testid="findfamily-register-status"
role="alert"
>
{registerError}
</p>
)}
</form>
<form className={styles.searchCard} onSubmit={handleSubmit}>
<div className={styles.cardLabel}>Search for a family member</div>
<div className={styles.searchRow}>
@@ -0,0 +1,126 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { db } from "../../lib/db.ts";
import { init } from "../../lib/identity.ts";
import { readAll } from "../../lib/eventlog.ts";
import { createLocalDirectoryChannel, findFamilyMember } from "../../lib/findfamily.ts";
import { SEED_DIRECTORY } from "./directory.ts";
import {
extractRegisteredDirectoryEntries,
FindFamilyRegistrationError,
isFindFamilyRegisterPayload,
registerInDirectory,
} from "./findfamilyEvents.ts";
beforeEach(async () => {
indexedDB.deleteDatabase(db.name);
db.close();
await db.open();
await init();
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("isFindFamilyRegisterPayload", () => {
it("accepts a well-formed registration payload", () => {
expect(
isFindFamilyRegisterPayload({ type: "findfamily.register", id: "fh-abc123", name: "Lucia Mendez" }),
).toBe(true);
});
it("rejects empty id/name or a different event type", () => {
expect(isFindFamilyRegisterPayload({ type: "findfamily.register", id: "", name: "Lucia" })).toBe(false);
expect(isFindFamilyRegisterPayload({ type: "findfamily.register", id: "fh-1", name: " " })).toBe(false);
expect(isFindFamilyRegisterPayload({ type: "wallet.issue", account: "a", amount: 1 })).toBe(false);
expect(isFindFamilyRegisterPayload(null)).toBe(false);
});
});
describe("registerInDirectory + extractRegisteredDirectoryEntries", () => {
it("signs and appends a real Event Log entry, then extracts it back as a DirectoryEntry", async () => {
const stored = await registerInDirectory("Lucia Mendez");
expect(stored.payload).toMatchObject({ type: "findfamily.register", name: "Lucia Mendez" });
const entries = await readAll();
const registered = extractRegisteredDirectoryEntries(entries);
expect(registered).toHaveLength(1);
expect(registered[0].name).toBe("Lucia Mendez");
expect(registered[0].id).toMatch(/^fh-/);
// The id never embeds the plaintext name (same opaque-handle design as
// SEED_DIRECTORY - see directory.ts's own doc comment).
expect(registered[0].id.toLowerCase()).not.toContain("lucia");
});
it("rejects an empty-name registration before it ever reaches the Event Log", async () => {
await expect(registerInDirectory(" ")).rejects.toBeInstanceOf(FindFamilyRegistrationError);
expect(await readAll()).toHaveLength(0);
});
it("ignores entries belonging to other event types during extraction", async () => {
await registerInDirectory("Noah Castillo");
const entries = await readAll();
const mixed = [
...entries,
{ ...entries[0], id: 999, payload: { type: "wallet.issue", account: "a", amount: 1 } },
];
expect(extractRegisteredDirectoryEntries(mixed)).toHaveLength(1);
});
it("mints a distinct id per registration even for the same name", async () => {
await registerInDirectory("Sofia Reyes");
await registerInDirectory("Sofia Reyes");
const registered = extractRegisteredDirectoryEntries(await readAll());
expect(registered).toHaveLength(2);
expect(registered[0].id).not.toBe(registered[1].id);
});
});
describe("registerInDirectory backend sync wiring", () => {
it("observably calls trySyncWithBackend() after the write, without delaying or altering the local-first append", async () => {
const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED"));
vi.stubGlobal("fetch", fetchMock);
const stored = await registerInDirectory("Camila Torres");
expect(stored.payload).toMatchObject({ type: "findfamily.register", name: "Camila Torres" });
expect(await readAll()).toHaveLength(1);
await Promise.resolve();
await Promise.resolve();
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock.mock.calls[0][0]).toBe("/api/sync");
});
});
describe("coherence-audit fix (findfamily.md finding #2): a real resident registration is genuinely findable", () => {
it("a name registered through registerInDirectory is found by a real PSI search merged with SEED_DIRECTORY, and every seed fixture still works", async () => {
// The exact write path a resident's device uses: sign + append a real
// findfamily.register event - never a fixture, never a mock.
await registerInDirectory("Priya Nair");
const registered = extractRegisteredDirectoryEntries(await readAll());
const mergedDirectory = [...SEED_DIRECTORY, ...registered];
const channel = createLocalDirectoryChannel(mergedDirectory);
// The newly-registered name is found via the REAL DH-PSI engine
// (prepareSearch/respondToSearch/finalizeSearch under the hood) - not a
// mocked match.
const newResult = await findFamilyMember("Priya Nair", channel);
expect(newResult.matchId).toBe(registered[0].id);
// Every SEED_DIRECTORY fixture entry is still searchable unchanged after
// the merge - registration is additive, not a replacement.
for (const fixture of SEED_DIRECTORY) {
const fixtureResult = await findFamilyMember(fixture.name, channel);
expect(fixtureResult.matchId).toBe(fixture.id);
}
// And a name nobody registered or seeded still gets an honest no-match.
const noMatch = await findFamilyMember("Nobody Registered This", channel);
expect(noMatch.matchId).toBeNull();
});
});
+125
View File
@@ -0,0 +1,125 @@
/**
* Find Family: resident self-registration into the searchable directory
* (coherence-audit fix, finding #2 in
* `.omo/evidence/coherence-audit/findfamily.md`).
*
* `directory.ts`'s `SEED_DIRECTORY` is a frozen 4-entry demo fixture with no
* append path anywhere - meaning no real resident could ever be found by
* `src/lib/findfamily.ts`'s PSI search, however sound the cryptography is.
* This module is the resident-facing write path that closes that gap, using
* the exact same signed-Event-Log pattern every other mini-app's own write
* path uses (see `src/lib/skyMemoryWall.ts`'s `postMemoryWallEntry` /
* `src/lib/testimony.ts`'s `postTestimony`): a small local payload type +
* type guard, a function that signs and appends it through the real
* `append()` (src/lib/eventlog.ts, the sole local-signing write path), and
* an extractor that reconstructs the registered roster from a replayed read
* - never a parallel, persisted "directory" store of its own.
*
* This does NOT reintroduce the plaintext-roster leak `directory.ts`'s own
* doc comment warns about. That warning is about the PSI *search*
* mechanism's threat model: a plaintext *query* name must never leave the
* searcher's device, and `respondToSearch()`/`finalizeSearch()` already
* guarantee that regardless of where the directory's entries came from. It
* says nothing about directory *membership* being secret - being findable
* necessarily requires a resident to have made their own name findable
* somewhere non-secret, exactly like `sky.memoryWall.entry`/
* `testimony.statement` are voluntary, author-attributed public posts (see
* `src/lib/sync.ts`'s `PUSH_TYPE_ALLOWLIST` doc comment). PSI protects the
* *searcher's query*, not the *registrant's* anonymity - nobody claims the
* opposite.
*/
import { append, type StoredEventLogEntry } from "../../lib/eventlog.ts";
import type { DirectoryEntry } from "../../lib/findfamily.ts";
import { trySyncWithBackend } from "../../lib/sync.ts";
export const FINDFAMILY_REGISTER_PAYLOAD_TYPE = "findfamily.register" as const;
/** The Event Log payload shape one resident self-registration is signed
* over. `id` is a stable, opaque handle (never derived from `name`, so the
* id itself cannot leak the name the way an older `res-jane-doe`-style id
* would - matching `directory.ts`'s own `SEED_DIRECTORY` id design). */
export interface FindFamilyRegisterPayload {
type: typeof FINDFAMILY_REGISTER_PAYLOAD_TYPE;
id: string;
name: string;
}
export function isFindFamilyRegisterPayload(
payload: unknown,
): payload is FindFamilyRegisterPayload {
if (typeof payload !== "object" || payload === null) return false;
const p = payload as Record<string, unknown>;
return (
p.type === FINDFAMILY_REGISTER_PAYLOAD_TYPE &&
typeof p.id === "string" &&
p.id.length > 0 &&
typeof p.name === "string" &&
p.name.trim().length > 0
);
}
export class FindFamilyRegistrationError extends Error {
constructor(message: string) {
super(message);
this.name = "FindFamilyRegistrationError";
}
}
function generateEntryId(): string {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return `fh-${crypto.randomUUID().replace(/-/g, "")}`;
}
return `fh-${Date.now().toString(16)}${Math.random().toString(16).slice(2)}`;
}
/**
* Signs `name` with the local identity and appends it to the shared Event
* Log via the real `append()` path (src/lib/eventlog.ts) - the only way a
* resident registering themselves or a missing family member ever reaches
* the searchable directory. Mirrors `postMemoryWallEntry`/`postTestimony`'s
* shape exactly: validate non-empty, build the payload, append, then
* best-effort fire-and-forget sync.
*/
export async function registerInDirectory(
name: string,
deps: { append?: typeof append; generateId?: () => string } = {},
): Promise<StoredEventLogEntry> {
const appendFn = deps.append ?? append;
const generateId = deps.generateId ?? generateEntryId;
const trimmed = name.trim();
if (trimmed.length === 0) {
throw new FindFamilyRegistrationError(
"A name is required to register yourself or a family member.",
);
}
const payload: FindFamilyRegisterPayload = {
type: FINDFAMILY_REGISTER_PAYLOAD_TYPE,
id: generateId(),
name: trimmed,
};
const entry = await appendFn(payload);
// Best-effort cross-device sync (same fire-and-forget pattern as every
// other mini-app's write path): never blocks or affects the local-first
// write that just completed above.
void trySyncWithBackend();
return entry;
}
/**
* Reconstructs every resident-registered directory entry from a replayed
* Event Log read - the same cold-replay reconstruction
* `extractMemoryWallEntries`/`extractTestimonyStatements` perform, never a
* separately persisted store. Entries are returned in the same order
* `readAll()` yields them (Lamport timestamp ascending), each shaped as the
* `DirectoryEntry` `src/lib/findfamily.ts`'s PSI engine already consumes -
* so a caller merges this straight into `SEED_DIRECTORY` with no adapter.
*/
export function extractRegisteredDirectoryEntries(
entries: readonly StoredEventLogEntry[],
): DirectoryEntry[] {
return entries
.filter((entry): entry is StoredEventLogEntry & { payload: FindFamilyRegisterPayload } =>
isFindFamilyRegisterPayload(entry.payload),
)
.map((entry) => ({ id: entry.payload.id, name: entry.payload.name }));
}