History is usually taught as a timeline, which hides the structure that explains it: families, successions, alliances. Sử Phả stores history as a graph instead, and treats uncertainty as data: each relationship has a source, a confidence level and, where historians disagree, a note saying so.
apps and shared packages
3 + 2
tests, run in CI on a real Postgres
230
additive migrations
10
Postgres schemas: kg, history, learning
3
## The problem
Questions like "how is this king related to that one?" or "who ruled between these two dates?" are hard to answer from books, because the answer is spread over many pages and the sources do not always agree. Dates are often approximate ("around 1010", "before 1225") and people go by several names: a birth name, a temple name, a posthumous name, a reign name.
I wanted a site where you can walk along those relationships, see where each fact comes from, and never be shown a guess as if it were certain.
## Architecture
A pnpm monorepo with three deployable apps and two shared packages. The core package owns the schema, the migrations and the graph algorithms, so the API, the public site and the admin app all use the same rules.
web · admin
Next.js public site, Vite + React editor
↓→
api
Express: auth, rate limits, validation
↓→
core
schema, services, graph algorithms
↓→
PostgreSQL
kg · history · learning
apps/
api/ Express REST API: public reads, admin-only writes
web/ Next.js public site: people, polities, events,
timelines, graphs, "how are A and B related?"
admin/ Vite + React admin for editing the data
packages/
core/ Drizzle schema, migrations, services, graph algorithms
ui/ design tokens and graph components (no Next or Vite)
## Data model
The database has three Postgres schemas with separate jobs. kg is the domain-free core: identity, names, sources, citations, fuzzy dates and relations. history holds what only history needs: people, polities, tenures, places, events. learning (designed, not built yet) only references kg node ids.
›One supertype table (kg.node) plus a table per kind sharing its primary key, so names, sources and citations are written once while domain rules stay real foreign keys and CHECK constraints.
›Registry tables instead of Postgres ENUMs: a new relationship type, name kind or calendar is an INSERT, not a migration.
›Relationship types know their inverse and whether they are symmetric, so only one direction is stored; is_acyclic types are checked for cycles with a recursive CTE.
›Dates are ranges with a precision, not single days, so "around 1010" and "before 1225" are stored as what they are.
›No hard deletes: duplicates are merged with a redirect, because old ids may already be linked from elsewhere.
›Migrations are additive only (expand, migrate, contract), and CI applies all of them to an empty database on every push.
## Finding how two people are related
The "how are A and B related?" page lists the cheapest chains of relationships between two nodes. A family or political relation costs 1 and holding an office costs 2, so a chain through a shared throne ranks below a chain through a shared parent. Around a hub, such as a king with dozens of relatives, a naive depth-first search explodes, so the search is pruned with exact distances.
›First, a bucketed Dijkstra (Dial’s algorithm, since costs are small integers) computes the true remaining cost from every node to the target, within the cost limit.
›Then a depth-first search walks simple paths from the source and cuts any branch whose cost so far plus the remaining cost exceeds the budget: the bound is exact, so no branch that could still finish is cut.
›The budget starts at the cheapest possible chain and rises one step at a time, like IDA*, so short chains come first and long detours are never enumerated. A visit cap marks the result as truncated instead of hanging.
/** Cheapest cost from every node to `targetId` (only nodes within `maxCost`), by bucketed Dijkstra. */
function costsTo(adjacency, targetId, maxCost, includeDisputed) {
const dist = new Map([[targetId, 0]]);
const buckets = Array.from({ length: maxCost + 1 }, () => []);
buckets[0].push(targetId);
for (let c = 0; c <= maxCost; c++) {
for (const id of buckets[c]) {
if (dist.get(id) !== c) continue;
for (const step of adjacency.get(id) ?? []) {
if (step.disputed && !includeDisputed) continue;
const next = c + step.cost;
if (next > maxCost || next >= (dist.get(step.toId) ?? Infinity)) continue;
dist.set(step.toId, next);
buckets[next].push(step.toId);
}
}
}
return dist;
}
## Naming the relationship
›Kinship: finds the nearest common ancestor and how many generations each person is below it, then names the relationship. It knows the Vietnamese terms (paternal and maternal sides, older and younger uncles and aunts) and falls back to neutral terms for families outside Vietnamese culture, where a Vietnamese word would claim a distinction that family’s language does not make.
›Family-tree layout: places people by generation and routes the connecting lines so that no line crosses another person’s box and unrelated lines do not overlap.
›Both are pure functions with golden tests, so they can be checked without a database.
## Running it in production
›CI on every push: lint, format, type check, WCAG colour contrast in light and dark themes, migrate and seed a real Postgres, tests, build, dependency audit, and a build of each Docker image.
›Railway deploys main only after CI passes.
›Admin sessions expire after 30 minutes and can be revoked; logins are rate-limited per address and per account; expensive endpoints have their own limits.
›The app refuses to start in production without complete configuration; /health checks the database; shutdown is graceful; logs are JSON with a request id.
›Backup and restore scripts, an operations runbook, and a smoke-test script for a fresh deploy.
## Trade-offs
One generic relation table instead of a table per relationship
The first version had dedicated parentage and marriage tables. Adding teachers, rivals or regents would have meant a new table and new code each time, so a migration moved everything into kg.relation.
Gain
A new relationship type is data, added from the admin app
Cost
Rules a dedicated table would enforce (no cycles in parentage) move into service code and a recursive CTE
Graph algorithms in TypeScript, not SQL
Kinship naming and path ranking have many edge cases; they need tests that are fast and readable.
Gain
Golden tests without a database; the same code runs in the API and in tests
Cost
The relevant subgraph is loaded into memory first, so searches are bounded by cost and by a visit cap
## Status
Working: the public site, the admin app and the API, with sources and confidence on every fact. Next: a review queue for submitted data, spaced-repetition learning on top of the graph, bulk import from Wikidata, images and maps.