mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-09 13:01:00 +00:00
test(backup): guard that a backed-up model travels both ways
The classification guard proved every model has an opinion and would have passed unchanged while a model classified as carried was read into the payload and never written back — which is what happened to the nutrient day totals, the custom mood tags and the custom cycle symptoms, three releases running. Split BACKED_UP into the models with both ends and the models without, each of the latter carrying what an account loses meanwhile, so the debt is a register rather than a silence. The check reads declared writer and restore files rather than grepping for a route, because the route delegates: a review that grepped only the route concluded the cycle data was never restored and had to be retracted. Declaring the file list caught its own first omission — measurements are read through the pager, not directly. Adds a round trip that builds a real payload, parses it through the wire schema and drives the real restore, asserting on the rows written rather than on the payload. Dropping the cycle section spread makes it fail the way production did: the restore throws on a symptom key nothing wrote back.
This commit is contained in:
1 parent
c6593b292f
commit
faa89ef54b
4 files changed
+693
-15
No files matched your search
@@ -129,3 +129,169 @@ describe("every schema model has a backup verdict", () => {
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The second half of the guard: a `BACKED_UP` model either travels BOTH ways or
|
||||
* is named as debt.
|
||||
*
|
||||
* The first half above proves every model has an opinion. It would pass
|
||||
* unchanged while a model classified as carried was read into the payload and
|
||||
* never written back — which is not a hypothetical, it is what happened to the
|
||||
* nutrient day totals, to the custom mood tags, and to the custom cycle
|
||||
* symptoms, three releases running.
|
||||
*
|
||||
* The check reads the declared writer and restore files rather than grepping
|
||||
* for a route, BECAUSE the route delegates. A review that grepped only
|
||||
* `restore/route.ts` concluded the cycle data was never restored and had to be
|
||||
* retracted; `restoreCycleData` and `restoreProfileData` both live elsewhere.
|
||||
* Following the helpers is the entire difficulty of this question, so the file
|
||||
* list is declared next to the verdicts and checked to exist.
|
||||
*/
|
||||
|
||||
import {
|
||||
BACKUP_RESTORE_FILES,
|
||||
BACKUP_WRITER_FILES,
|
||||
COVERAGE_PENDING,
|
||||
TWO_ENDED_MODELS,
|
||||
} from "@/lib/export/backup-plan";
|
||||
|
||||
const REPO_ROOT = resolve(__dirname, "../..");
|
||||
|
||||
function read(relativePath: string): string {
|
||||
return readFileSync(resolve(REPO_ROOT, relativePath), "utf8");
|
||||
}
|
||||
|
||||
/** `Measurement` → `measurement`, the Prisma delegate name. */
|
||||
function delegateName(model: string): string {
|
||||
return model[0].toLowerCase() + model.slice(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Relation fields on OTHER models whose type is `model`.
|
||||
*
|
||||
* A child rides its parent — `include: { schedules: true }` on the way out,
|
||||
* `schedules: { create: [...] }` on the way back — so a delegate-only search
|
||||
* would report every nested child as uncarried and the guard would be noise.
|
||||
*/
|
||||
function relationFieldNames(model: string): string[] {
|
||||
const source = readFileSync(SCHEMA_PATH, "utf8");
|
||||
const names = new Set<string>();
|
||||
for (const [, body] of source.matchAll(/^model\s+\w+\s*\{([\s\S]*?)^\}/gm)) {
|
||||
for (const line of body.split("\n")) {
|
||||
const match = /^\s*(\w+)\s+(\w+)(\[\])?\??\s*(@|$)/.exec(line);
|
||||
if (match && match[2] === model) names.add(match[1]);
|
||||
}
|
||||
}
|
||||
return [...names];
|
||||
}
|
||||
|
||||
const READ_OPS = /(findMany|findUnique|findFirst|findUniqueOrThrow|groupBy)/;
|
||||
const WRITE_OPS = /(create|createMany|upsert|update|updateMany)/;
|
||||
|
||||
/** Does any of `files` touch `model` with an operation matching `ops`? */
|
||||
function touches(
|
||||
files: readonly string[],
|
||||
model: string,
|
||||
ops: RegExp,
|
||||
): boolean {
|
||||
const delegate = delegateName(model);
|
||||
const relations = relationFieldNames(model);
|
||||
return files.some((file) => {
|
||||
// Whitespace-flattened so a call broken across lines still matches.
|
||||
const source = read(file).replace(/\s+/g, " ");
|
||||
for (const match of source.matchAll(
|
||||
new RegExp(`\\.${delegate}\\s*\\.\\s*(\\w+)`, "g"),
|
||||
)) {
|
||||
if (ops.test(match[1])) return true;
|
||||
}
|
||||
// A nested relation key: `schedules: {`, `dayLogs: [`, `entries: true`.
|
||||
return relations.some((relation) =>
|
||||
new RegExp(`\\b${relation}\\s*:\\s*[{[t]`).test(source),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
describe("every backed-up model travels both ways, or is named as debt", () => {
|
||||
it("declares writer and restore files that exist", () => {
|
||||
for (const file of [...BACKUP_WRITER_FILES, ...BACKUP_RESTORE_FILES]) {
|
||||
expect(() => read(file), `${file} is declared but missing`).not.toThrow();
|
||||
}
|
||||
// A grep of the restore ROUTE alone is the mistake this list prevents, so
|
||||
// the list has to name more than the route.
|
||||
expect(BACKUP_RESTORE_FILES.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it("splits BACKED_UP into exactly two-ended and pending, with no overlap", () => {
|
||||
const backedUp = new Set<string>(BACKED_UP_MODELS);
|
||||
const twoEnded = new Set(TWO_ENDED_MODELS);
|
||||
const pending = new Set(Object.keys(COVERAGE_PENDING));
|
||||
|
||||
const both = [...twoEnded].filter((m) => pending.has(m));
|
||||
expect(
|
||||
both,
|
||||
"a model cannot be both proven and pending — that is how a gap hides",
|
||||
).toEqual([]);
|
||||
|
||||
const unaccounted = [...backedUp].filter(
|
||||
(m) => !twoEnded.has(m) && !pending.has(m),
|
||||
);
|
||||
expect(
|
||||
unaccounted,
|
||||
"add each to TWO_ENDED_MODELS once its reader AND restore branch land, " +
|
||||
"or to COVERAGE_PENDING with what an account loses meanwhile",
|
||||
).toEqual([]);
|
||||
|
||||
const foreign = [...twoEnded, ...pending].filter((m) => !backedUp.has(m));
|
||||
expect(
|
||||
foreign,
|
||||
"only a BACKED_UP model has two ends to have; these are not on that list",
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("finds a payload reader for every model claimed two-ended", () => {
|
||||
const missing = TWO_ENDED_MODELS.filter(
|
||||
(model) => !touches(BACKUP_WRITER_FILES, model, READ_OPS),
|
||||
);
|
||||
expect(
|
||||
missing,
|
||||
"claimed carried, but no backup writer reads it — the restore branch has " +
|
||||
"nothing feeding it and a restore silently rebuilds the account without it",
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("finds a restore branch for every model claimed two-ended", () => {
|
||||
const missing = TWO_ENDED_MODELS.filter(
|
||||
(model) => !touches(BACKUP_RESTORE_FILES, model, WRITE_OPS),
|
||||
);
|
||||
expect(
|
||||
missing,
|
||||
"claimed carried, but nothing writes it back — the export is a file the " +
|
||||
"restore reads past, which is the worst of both: the data is in the " +
|
||||
"backup and not in the account",
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("gives every pending model a reason that says what is lost", () => {
|
||||
const thin = Object.entries(COVERAGE_PENDING)
|
||||
.filter(([, reason]) => reason.trim().length < 60)
|
||||
.map(([model]) => model);
|
||||
expect(
|
||||
thin,
|
||||
"'not yet' is not a reason — say what an account loses, so the debt can " +
|
||||
"be ordered by cost to a person rather than by ease of writing",
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("proves the two named this release are on the covered side", () => {
|
||||
// Prerequisites for the structured-profile work: both were classified
|
||||
// BACKED_UP and carried by nothing, and the custom metric was live loss.
|
||||
for (const model of [
|
||||
"UserHealthProfile",
|
||||
"CustomMetric",
|
||||
"CustomMetricEntry",
|
||||
]) {
|
||||
expect(TWO_ENDED_MODELS).toContain(model);
|
||||
expect(COVERAGE_PENDING).not.toHaveProperty(model);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,369 @@
|
||||
/**
|
||||
* Export → wire schema → restore, driven end to end.
|
||||
*
|
||||
* Every other test around the backup proves ONE end. `full-backup-payload.test.ts`
|
||||
* proves the builder emits a key; the restore tests prove the route refuses a
|
||||
* bad file. Between them sits the gap that lost three domains in a row: a key
|
||||
* the builder emits, the schema drops or nobody reads, and the restore reports
|
||||
* success over.
|
||||
*
|
||||
* So this test does not assert on the payload. It builds a real payload from a
|
||||
* populated account, serialises it, parses it back through the REAL
|
||||
* `parseBackupPayload`, hands it to the REAL route, and asserts on the rows the
|
||||
* restore tried to write. A field that survives that survives a restore.
|
||||
*
|
||||
* The transaction stand-in is deliberately not inert: `cycleSymptom.findMany`
|
||||
* answers from what the restore actually upserted. If the account's own symptom
|
||||
* definitions do not ride the file, the link resolution finds nothing and the
|
||||
* restore throws — which is what a real instance does, and is exactly how the
|
||||
* inert v1.33.1 fix behaved in production.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
process.env.ENCRYPTION_KEY =
|
||||
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
decrypt: vi.fn(),
|
||||
transaction: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: (fn: unknown) => fn,
|
||||
HttpError: class extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
},
|
||||
requireAdmin: vi.fn(async () => ({ user: { id: "admin-1" } })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
dataBackup: { findUnique: vi.fn() },
|
||||
user: { findUnique: vi.fn() },
|
||||
$transaction: mocks.transaction,
|
||||
},
|
||||
}));
|
||||
|
||||
// Only `decrypt` is stubbed — it stands in for reading the stored backup blob.
|
||||
// The rest of the module stays real, so the ciphertext this test builds and the
|
||||
// ciphertext the restore writes are produced by the same code an instance runs.
|
||||
vi.mock("@/lib/crypto", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/lib/crypto")>()),
|
||||
decrypt: mocks.decrypt,
|
||||
}));
|
||||
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
|
||||
vi.mock("@/lib/logging/context", () => ({
|
||||
annotate: vi.fn(),
|
||||
getEvent: vi.fn(() => null),
|
||||
}));
|
||||
vi.mock("@/lib/idempotency", () => ({
|
||||
withIdempotency: (fn: unknown) => fn,
|
||||
defaultUserIdResolver: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/cache/invalidate", () => ({ invalidateUserData: vi.fn() }));
|
||||
vi.mock("@/lib/rollups/mood-rollups", () => ({
|
||||
recomputeUserMoodRollups: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/rollups/medication-compliance-rollups", () => ({
|
||||
recomputeUserMedicationCompliance: vi.fn(),
|
||||
MEDICATION_COMPLIANCE_BACKFILL_DAYS: 30,
|
||||
}));
|
||||
vi.mock("@/lib/rollups/measurement-rollups", () => ({
|
||||
recomputeUserRollups: vi.fn(),
|
||||
}));
|
||||
|
||||
import { POST } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { buildFullBackupPayload } from "@/lib/export/full-backup-payload";
|
||||
import { encryptToBytes } from "@/lib/ai/coach/bytes-codec";
|
||||
|
||||
const OWNER = "user-A";
|
||||
|
||||
/* ── the account being backed up ────────────────────────────────────── */
|
||||
|
||||
function sourceClient() {
|
||||
const empty = { findMany: vi.fn().mockResolvedValue([]) };
|
||||
return {
|
||||
appSettings: { findUnique: vi.fn().mockResolvedValue(null) },
|
||||
measurement: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
medication: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
medicationIntakeEvent: empty,
|
||||
moodEntry: empty,
|
||||
moodTag: empty,
|
||||
nutrientIntakeDay: empty,
|
||||
// Cycle: one day-log whose symptom is one the ACCOUNT defined, which is
|
||||
// the case the payload assembly used to drop.
|
||||
cycleProfile: { findUnique: vi.fn().mockResolvedValue(null) },
|
||||
menstrualCycle: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
cycleDayLog: {
|
||||
findMany: vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: "day-1",
|
||||
date: "2026-07-19",
|
||||
cycleId: null,
|
||||
flow: null,
|
||||
intermenstrualBleeding: false,
|
||||
basalBodyTempC: null,
|
||||
temperatureExcluded: false,
|
||||
ovulationTest: null,
|
||||
cervicalMucus: null,
|
||||
cervixPosition: null,
|
||||
cervixFirmness: null,
|
||||
cervixOpening: null,
|
||||
sexualActivity: false,
|
||||
protectedSex: null,
|
||||
pregnancyTest: null,
|
||||
progesteroneTest: null,
|
||||
contraceptive: null,
|
||||
sensitiveEncrypted: null,
|
||||
notesEncrypted: null,
|
||||
source: "MANUAL",
|
||||
externalId: null,
|
||||
tz: null,
|
||||
syncVersion: 0,
|
||||
deletedAt: null,
|
||||
createdAt: new Date("2026-07-19T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-19T00:00:00.000Z"),
|
||||
symptomLinks: [{ symptom: { key: "custom:jaw_tension" } }],
|
||||
},
|
||||
]),
|
||||
},
|
||||
cycleSymptom: {
|
||||
findMany: vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: "sym-1",
|
||||
key: "custom:jaw_tension",
|
||||
labelKey: "custom",
|
||||
categoryId: "cat-1",
|
||||
icon: null,
|
||||
sortOrder: 0,
|
||||
isActive: true,
|
||||
labelEncrypted: "envelope",
|
||||
},
|
||||
]),
|
||||
},
|
||||
// Records section: empty, exercised by its own suite.
|
||||
labResult: empty,
|
||||
biomarker: empty,
|
||||
illnessEpisode: empty,
|
||||
allergy: empty,
|
||||
familyHistoryEntry: empty,
|
||||
workout: empty,
|
||||
inboundDocument: empty,
|
||||
// The two domains this stream adds.
|
||||
userHealthProfile: {
|
||||
findUnique: vi.fn().mockResolvedValue({
|
||||
id: "profile-1",
|
||||
userId: OWNER,
|
||||
aboutMeEncrypted: encryptToBytes("desk job, two kids"),
|
||||
conditionsEncrypted: null,
|
||||
allergiesEncrypted: encryptToBytes("penicillin"),
|
||||
coachFocusEncrypted: null,
|
||||
pendingQuestionsEncrypted: encryptToBytes('["How is your sleep?"]'),
|
||||
createdAt: new Date("2026-07-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-19T00:00:00.000Z"),
|
||||
}),
|
||||
},
|
||||
customMetric: {
|
||||
findMany: vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: "metric-1",
|
||||
userId: OWNER,
|
||||
name: "Morning grip strength",
|
||||
unit: "kg",
|
||||
targetLow: 40,
|
||||
targetHigh: null,
|
||||
decimals: 1,
|
||||
description: "Right hand, before breakfast",
|
||||
createdAt: new Date("2026-07-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-19T00:00:00.000Z"),
|
||||
deletedAt: null,
|
||||
entries: [
|
||||
{
|
||||
id: "entry-1",
|
||||
value: 44.5,
|
||||
unit: "kg",
|
||||
measuredAt: new Date("2026-07-19T06:30:00.000Z"),
|
||||
note: "felt strong",
|
||||
createdAt: new Date("2026-07-19T06:31:00.000Z"),
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/* ── the instance being restored into ───────────────────────────────── */
|
||||
|
||||
interface Written {
|
||||
model: string;
|
||||
op: string;
|
||||
data: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function recordingTx(written: Written[]) {
|
||||
// Symptom definitions the restore has written back, so link resolution can
|
||||
// only succeed if the definitions actually rode the file.
|
||||
const restoredSymptoms = new Map<string, string>();
|
||||
|
||||
const delegate = (model: string) =>
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_t, op: string) {
|
||||
return async (args: Record<string, unknown> = {}) => {
|
||||
if (op === "deleteMany") return { count: 0 };
|
||||
if (op === "findMany") {
|
||||
if (model === "cycleSymptom") {
|
||||
return [...restoredSymptoms].map(([key, id]) => ({ id, key }));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
if (op === "findFirst" || op === "findUnique") return null;
|
||||
const data = (args.data ?? args.create ?? {}) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
if (op === "create" || op === "upsert" || op === "createMany") {
|
||||
if (model === "cycleSymptom" && typeof data.key === "string") {
|
||||
restoredSymptoms.set(data.key, (data.id as string) ?? "new-id");
|
||||
}
|
||||
written.push({ model, op, data });
|
||||
}
|
||||
return { id: (data.id as string) ?? `${model}-created` };
|
||||
};
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return new Proxy({} as Record<string, unknown>, {
|
||||
get: (_t, model: string) => delegate(model),
|
||||
});
|
||||
}
|
||||
|
||||
function request(): NextRequest {
|
||||
return new NextRequest("http://localhost/api/admin/backups/b-1/restore", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ confirm: "RESTORE" }),
|
||||
});
|
||||
}
|
||||
|
||||
/** Build a real backup for the account above, then restore it. */
|
||||
async function roundTrip(): Promise<{ res: Response; written: Written[] }> {
|
||||
const { payload } = await buildFullBackupPayload(
|
||||
sourceClient() as never,
|
||||
OWNER,
|
||||
{ purpose: "disaster-recovery" },
|
||||
);
|
||||
|
||||
// The file as it lands on disk: JSON, nothing else.
|
||||
mocks.decrypt.mockReturnValue(JSON.stringify(payload));
|
||||
|
||||
const written: Written[] = [];
|
||||
mocks.transaction.mockImplementation(
|
||||
async (fn: (tx: unknown) => Promise<unknown>) => fn(recordingTx(written)),
|
||||
);
|
||||
|
||||
const res = await (
|
||||
POST as unknown as (r: NextRequest, c: unknown) => Promise<Response>
|
||||
)(request(), { params: Promise.resolve({ id: "b-1" }) });
|
||||
|
||||
return { res, written };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(prisma.dataBackup.findUnique).mockResolvedValue({
|
||||
id: "b-1",
|
||||
userId: OWNER,
|
||||
data: "cipher",
|
||||
user: { id: OWNER, username: "owner" },
|
||||
} as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
id: OWNER,
|
||||
username: "owner",
|
||||
timezone: "UTC",
|
||||
} as never);
|
||||
});
|
||||
|
||||
describe("backup round trip — export, wire schema, restore", () => {
|
||||
it("completes without the restore reporting a failure", async () => {
|
||||
const { res } = await roundTrip();
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("writes the durable self-context back with its ciphertext intact", async () => {
|
||||
const { written } = await roundTrip();
|
||||
|
||||
const profile = written.find((w) => w.model === "userHealthProfile");
|
||||
expect(
|
||||
profile,
|
||||
"the profile reached the file and nothing wrote it back",
|
||||
).toBeDefined();
|
||||
expect(profile!.data.userId).toBe(OWNER);
|
||||
// The envelope round-trips as bytes, not as a re-encryption of plaintext
|
||||
// the DR file never carried.
|
||||
expect(profile!.data.aboutMeEncrypted).toBeInstanceOf(Uint8Array);
|
||||
expect(profile!.data.conditionsEncrypted).toBeNull();
|
||||
expect(profile!.data.pendingQuestionsEncrypted).toBeInstanceOf(Uint8Array);
|
||||
});
|
||||
|
||||
it("writes each custom metric back with its readings", async () => {
|
||||
const { written } = await roundTrip();
|
||||
|
||||
const metric = written.find((w) => w.model === "customMetric");
|
||||
expect(
|
||||
metric,
|
||||
"the metric reached the file and nothing wrote it back",
|
||||
).toBeDefined();
|
||||
expect(metric!.data).toMatchObject({
|
||||
userId: OWNER,
|
||||
name: "Morning grip strength",
|
||||
unit: "kg",
|
||||
targetLow: 40,
|
||||
decimals: 1,
|
||||
description: "Right hand, before breakfast",
|
||||
});
|
||||
|
||||
// The readings are the half that would go missing quietly: a metric with
|
||||
// no entries renders as an empty chart rather than as an error.
|
||||
const entries = (
|
||||
metric!.data.entries as { create: Array<Record<string, unknown>> }
|
||||
).create;
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]).toMatchObject({
|
||||
value: 44.5,
|
||||
unit: "kg",
|
||||
note: "felt strong",
|
||||
});
|
||||
});
|
||||
|
||||
it("writes the account's own cycle symptom back before resolving its links", async () => {
|
||||
const { written, res } = await roundTrip();
|
||||
|
||||
// The definition has to land, or the link lookup below finds nothing.
|
||||
expect(
|
||||
written.find(
|
||||
(w) =>
|
||||
w.model === "cycleSymptom" && w.data.key === "custom:jaw_tension",
|
||||
),
|
||||
"the custom symptom definition never reached the restore",
|
||||
).toBeDefined();
|
||||
|
||||
// And the day-log that references it restores rather than throwing on an
|
||||
// unresolvable key — the failure a real account hit while the fix was inert.
|
||||
expect(res.status).toBe(200);
|
||||
expect(written.find((w) => w.model === "cycleDayLog")).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -77,9 +77,13 @@ function mkReq(url: string): NextRequest {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
// `resetAllMocks` clears the inline default, and the full-backup payload
|
||||
// builder reads this unconditionally.
|
||||
// `resetAllMocks` clears the inline defaults, and the full-backup payload
|
||||
// builder reads these unconditionally.
|
||||
vi.mocked(prisma.nutrientIntakeDay.findMany).mockResolvedValue([] as never);
|
||||
vi.mocked(prisma.userHealthProfile.findUnique).mockResolvedValue(
|
||||
null as never,
|
||||
);
|
||||
vi.mocked(prisma.customMetric.findMany).mockResolvedValue([] as never);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
+152
-13
@@ -21,21 +21,18 @@
|
||||
*
|
||||
* `BACKED_UP` — the account would lose something real if this were missing.
|
||||
*
|
||||
* **Read this as "must be", not "is".** Today the guard beside
|
||||
* this file checks only that every model HAS a verdict. The
|
||||
* two-ended check — that each `BACKED_UP` model has both a
|
||||
* payload reader and a restore branch — does not exist yet,
|
||||
* and roughly 31 of the models listed here have neither end.
|
||||
* Three were closed in v1.33.1 (custom cycle symptoms,
|
||||
* nutrient day totals, custom mood tags); the rest are named
|
||||
* here so the gap is written down instead of invisible, which
|
||||
* is the only honest thing this list can do before the guard
|
||||
* exists.
|
||||
* Split in two below, because "must be carried" and "is
|
||||
* carried" are different claims and this file used to make
|
||||
* only the first. {@link TWO_ENDED_MODELS} names the models
|
||||
* with BOTH a payload reader and a restore branch, checked by
|
||||
* the guard beside this file. {@link COVERAGE_PENDING} names
|
||||
* the rest, each with what an account loses meanwhile.
|
||||
*
|
||||
* An earlier draft of this comment claimed the two-ended guard
|
||||
* in the present tense. It did not exist then either. That is
|
||||
* the same defect this file was written to prevent, so it is
|
||||
* recorded rather than quietly corrected.
|
||||
* in the present tense. It did not exist then. That is the same
|
||||
* defect this file was written to prevent, so it is recorded
|
||||
* rather than quietly corrected — and it is why the guard now
|
||||
* reads the source rather than trusting a list.
|
||||
* `DERIVED` — recomputable from `BACKED_UP` rows. Leaving it out keeps the
|
||||
* file smaller and cannot lose anything; the reason names what
|
||||
* recomputes it.
|
||||
@@ -130,6 +127,148 @@ export const BACKED_UP_MODELS = [
|
||||
"ConsentReceipt",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* The files that carry a backed-up model OUT of the database, and the files
|
||||
* that put one back.
|
||||
*
|
||||
* Declared rather than discovered, because discovery is what keeps going
|
||||
* wrong here. A previous review grepped the restore ROUTE, concluded the cycle
|
||||
* data was never restored, and had to retract it publicly: the route delegates
|
||||
* to `restoreCycleData`, and a grep of the route alone lies. The profile and
|
||||
* custom-metric pair added later delegates the same way, on purpose.
|
||||
*
|
||||
* Keeping both lists here means a new section has to say where its two ends
|
||||
* live, and the guard reads those files instead of guessing which ones matter.
|
||||
*/
|
||||
export const BACKUP_WRITER_FILES: readonly string[] = [
|
||||
"src/lib/export/full-backup-payload.ts",
|
||||
// Measurements are read through this pager, not directly. The guard caught
|
||||
// its absence from this list on the first run — the same "the caller
|
||||
// delegates" mistake the list exists to prevent, made while writing the list.
|
||||
"src/lib/export/paged-measurements.ts",
|
||||
"src/lib/export/records-backup.ts",
|
||||
"src/lib/export/profile-backup.ts",
|
||||
"src/lib/cycle/backup.ts",
|
||||
];
|
||||
|
||||
export const BACKUP_RESTORE_FILES: readonly string[] = [
|
||||
"src/app/api/admin/backups/[id]/restore/route.ts",
|
||||
"src/lib/export/profile-backup.ts",
|
||||
"src/lib/cycle/backup.ts",
|
||||
];
|
||||
|
||||
/**
|
||||
* Backed-up models that genuinely travel BOTH ways.
|
||||
*
|
||||
* The guard checks each of these against the files above: a read in a writer
|
||||
* file and a write in a restore file, counting a relation carried inside its
|
||||
* parent (`include: { schedules: true }` out, `schedules: { create: … }` back)
|
||||
* as covered, because that is how the child rows actually ride.
|
||||
*
|
||||
* A model moves onto this list when its two ends land, never before. That is
|
||||
* the whole point of the split — a verdict of `BACKED_UP` is an intention, and
|
||||
* an intention is what the nutrient day totals had while a restore was throwing
|
||||
* them away and reporting success.
|
||||
*/
|
||||
export const TWO_ENDED_MODELS: readonly string[] = [
|
||||
"Measurement",
|
||||
"Medication",
|
||||
"MedicationSchedule",
|
||||
"MedicationIntakeEvent",
|
||||
"MoodEntry",
|
||||
"MoodEntryTagLink",
|
||||
"MoodTag",
|
||||
"LabResult",
|
||||
"Biomarker",
|
||||
"Allergy",
|
||||
"FamilyHistoryEntry",
|
||||
"IllnessEpisode",
|
||||
"IllnessDayLog",
|
||||
"IllnessSymptomLink",
|
||||
"UserHealthProfile",
|
||||
"CycleProfile",
|
||||
"MenstrualCycle",
|
||||
"CycleDayLog",
|
||||
"CycleSymptom",
|
||||
"CycleSymptomLink",
|
||||
"CustomMetric",
|
||||
"CustomMetricEntry",
|
||||
"Workout",
|
||||
"NutrientIntakeDay",
|
||||
"InboundDocument",
|
||||
];
|
||||
|
||||
/**
|
||||
* Backed-up models that do NOT travel yet, each with what an account loses
|
||||
* until it does.
|
||||
*
|
||||
* This is a debt register, not a design. Every line is a restore that comes
|
||||
* back short without saying so, which is the failure mode the whole file
|
||||
* exists to make visible. The reasons say what goes missing rather than
|
||||
* "not yet", so the next person can order the work by what it costs a person
|
||||
* rather than by what is cheapest to write.
|
||||
*/
|
||||
export const COVERAGE_PENDING: Readonly<Record<string, string>> = {
|
||||
MedicationScheduleRevision:
|
||||
"The history of how a schedule changed. Without it a restored medication keeps today's schedule and loses the record of when the dose or timing moved, which is the part a doctor asks about.",
|
||||
MedicationDoseChange:
|
||||
"Titration history — when a dose went up or down and by how much. A restore rebuilds the current dose and drops the ramp that led to it.",
|
||||
MedicationPauseEra:
|
||||
"The spans where a medication was deliberately paused. Without them the compliance recomputation counts a deliberate pause as missed doses and the restored account looks non-adherent.",
|
||||
MedicationSideEffect:
|
||||
"Side effects the person recorded against a drug. Restoring the drug without them loses the reason someone may have stopped taking it.",
|
||||
MedicationEfficacyTarget:
|
||||
"What a medication was supposed to move, and by how much. The drug comes back with no statement of what it was for.",
|
||||
MedicationInventoryItem:
|
||||
"Pack sizes and remaining stock. A restored account reports no supply and every low-stock reminder has to be reconstructed by hand.",
|
||||
MedicationInventoryEvent:
|
||||
"The ledger of refills and consumption behind the stock count. Without it the count above cannot be rebuilt even in principle.",
|
||||
MoodTagCategory:
|
||||
"Categories a person created to group their own mood factors. Custom tags restore into a grouping that no longer exists.",
|
||||
MoodTagHidden:
|
||||
"Which seeded mood tags the account chose to hide. A restore un-hides every one, so the mood editor comes back cluttered with tags the person removed on purpose.",
|
||||
MentalHealthAssessment:
|
||||
"Completed WHO-5, PHQ and GAD instruments with their scores and dates. Clinically meaningful history that no integration can re-sync, and the single largest gap on this list.",
|
||||
EcgRecording:
|
||||
"ECG traces and their rhythm classification. The originating device may still hold them, but a self-hoster who exported and wiped has nothing to re-sync from.",
|
||||
MeasurementReminder:
|
||||
"Per-metric reminder cadences the person configured. A restore leaves the account silent until each one is set up again.",
|
||||
WorkoutRoute:
|
||||
"GPS traces. Deliberately absent from the payload today and DISCLOSED as absent in the file's own manifest, which is why this is a documented exclusion rather than a silent one — but it is still a loss for a self-hoster with no other copy.",
|
||||
WorkoutSamples:
|
||||
"Per-sample heart-rate and pace series behind a workout summary. Same disclosed-exclusion status as the routes above, same cost.",
|
||||
PersonalRecord:
|
||||
"Bests the account accumulated. Recomputable in principle from measurements and workouts, but nothing recomputes them today, so in practice they are lost.",
|
||||
UserAchievement:
|
||||
"Milestones the account earned, with the date each was reached. The date is the part that cannot be recovered.",
|
||||
EnvironmentContext:
|
||||
"Per-day environmental readings joined to the record. Re-fetchable for recent days only; older history is gone once the provider window closes.",
|
||||
EnvironmentTravelLocation:
|
||||
"Where the person was on a given day, which is what makes the environmental readings mean anything. Never re-derivable.",
|
||||
DocumentConditionLink:
|
||||
"Which documents were filed against which condition. Documents and conditions both restore; the filing between them does not, so a restored vault is unsorted.",
|
||||
ExtractedFact:
|
||||
"Facts read out of a document by the AI pass, with their provenance back to the page. Re-derivable only by re-running the extraction against a provider, at the operator's cost.",
|
||||
CoachConversation:
|
||||
"The thread structure of past coaching conversations — which messages belong together and what each exchange was about. Without it the messages below, if they were ever carried, would restore as one undifferentiated pile.",
|
||||
CoachMessage:
|
||||
"The messages themselves, encrypted at rest. The largest volume of free text an account owns after its documents.",
|
||||
CoachConversationDocument:
|
||||
"Which documents a conversation was grounded in — the provenance that makes an old answer checkable.",
|
||||
CoachFact:
|
||||
"Durable facts the Coach was told to remember. A restore makes the account re-tell its history.",
|
||||
CoachPlan:
|
||||
"An agreed plan and its progress. Restoring the conversation without the plan keeps the talk and loses the commitment.",
|
||||
CoachReminder:
|
||||
"Reminders the Coach agreed to send. A restored account silently stops sending them.",
|
||||
NotificationPreference:
|
||||
"Per-event channel and quiet-hours choices. A restore reverts to defaults, so an account that had deliberately silenced a category starts being notified again.",
|
||||
ReminderPhaseConfig:
|
||||
"Custom reminder phase timings. Same shape of loss as the preferences above.",
|
||||
ConsentReceipt:
|
||||
"The record of what the account agreed to and when. Arguably belongs with the instance rather than the account, and that question has to be settled before this one can be carried either way.",
|
||||
};
|
||||
|
||||
/**
|
||||
* Recomputable from backed-up rows. The reason names what rebuilds it, so a
|
||||
* future reader can check the claim rather than trust it.
|
||||
|
||||
Reference in new issue
Block a user