mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-14 14:40:52 +00:00
Merge branch 'feat/ai-jobs-stored-text' into release/v1.39.0
This commit is contained in:
commit
c9534b343e
114 files changed
+6002
-2436
No files matched your search
@@ -37,6 +37,7 @@ import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { getAiCapability } from "@/lib/ai/capabilities/gate";
|
||||
import { AI_CAPABILITIES } from "@/lib/ai/capabilities/types";
|
||||
import { AI_EXTRACTION_CONSENT_KIND } from "@/lib/consent/receipts";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isP2002 } from "@/lib/prisma-errors";
|
||||
import { enqueueSummaryCatchUp } from "@/lib/jobs/document-summary-catchup";
|
||||
@@ -57,7 +58,7 @@ type DocumentsAutoAiReadResponse = {
|
||||
* master `ai_full`. The capability table lists it (with `ai_full`) as what
|
||||
* satisfies the document consent rule.
|
||||
*/
|
||||
const AUTO_READ_CONSENT_KIND = "ai_extraction";
|
||||
const AUTO_READ_CONSENT_KIND = AI_EXTRACTION_CONSENT_KIND;
|
||||
|
||||
/**
|
||||
* Mint the extraction receipt unless one that satisfies document reads is
|
||||
|
||||
@@ -1,24 +1,30 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
// v1.16.16 — `createReceipt` + `revokeLatest` run inside a transaction; the
|
||||
// mock runs the callback against the same proxy.
|
||||
// v1.16.16 — `createReceipt` and the withdrawal run inside a transaction;
|
||||
// the mock runs the callback against the same proxy. The withdrawal also
|
||||
// purges the regenerable AI text, so the proxy carries those delegates too.
|
||||
type TxFn = (tx: unknown) => unknown;
|
||||
|
||||
vi.mock("@/lib/db", () => {
|
||||
const consentReceipt = {
|
||||
create: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
update: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
};
|
||||
return {
|
||||
prisma: {
|
||||
consentReceipt,
|
||||
$transaction: vi.fn((fn: TxFn) => fn({ consentReceipt })),
|
||||
const prisma = {
|
||||
consentReceipt: {
|
||||
create: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
update: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
count: vi.fn(),
|
||||
},
|
||||
insightStatusCache: { deleteMany: vi.fn() },
|
||||
user: { updateMany: vi.fn() },
|
||||
insightNarrative: { deleteMany: vi.fn() },
|
||||
arrivalReaction: { updateMany: vi.fn() },
|
||||
workoutInsight: { deleteMany: vi.fn() },
|
||||
$transaction: vi.fn(),
|
||||
};
|
||||
prisma.$transaction.mockImplementation((fn: TxFn) => fn(prisma));
|
||||
return { prisma };
|
||||
});
|
||||
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
@@ -78,9 +84,21 @@ beforeEach(() => {
|
||||
vi.mocked(auditLog).mockResolvedValue(undefined);
|
||||
// Re-arm rate-limit + transaction pass-throughs cleared by reset.
|
||||
vi.mocked(checkConsentRateLimit).mockResolvedValue(RL_OK);
|
||||
$transaction.mockImplementation((fn: TxFn) =>
|
||||
fn({ consentReceipt: prisma.consentReceipt }),
|
||||
);
|
||||
$transaction.mockImplementation((fn: TxFn) => fn(prisma));
|
||||
// Default: another receipt still covers the analysis, so no purge runs.
|
||||
// The purge cases below set this to 0.
|
||||
vi.mocked(prisma.consentReceipt.count).mockResolvedValue(1 as never);
|
||||
for (const deleteMany of [
|
||||
prisma.insightStatusCache.deleteMany,
|
||||
prisma.insightNarrative.deleteMany,
|
||||
prisma.workoutInsight.deleteMany,
|
||||
]) {
|
||||
vi.mocked(deleteMany).mockResolvedValue({ count: 0 } as never);
|
||||
}
|
||||
vi.mocked(prisma.user.updateMany).mockResolvedValue({ count: 0 } as never);
|
||||
vi.mocked(prisma.arrivalReaction.updateMany).mockResolvedValue({
|
||||
count: 0,
|
||||
} as never);
|
||||
});
|
||||
|
||||
describe("GET /api/consent/ai/latest", () => {
|
||||
@@ -278,14 +296,15 @@ describe("DELETE /api/consent/ai/latest", () => {
|
||||
const createdAt = new Date("2026-05-18T10:00:01.000Z");
|
||||
const revokedAt = new Date("2026-05-18T11:00:00.000Z");
|
||||
|
||||
// v1.16.16 — `revokeLatest` runs per kind in `consentKindEnum.options`
|
||||
// order: ai_full → ai_insights_only → ai_coach. The `updateMany` count
|
||||
// gates the follow-up re-read. ai_full + ai_coach revoke a row;
|
||||
// ai_insights_only has none (count 0, no re-read).
|
||||
// The withdrawal runs per kind in `consentKindEnum.options` order:
|
||||
// ai_full → ai_insights_only → ai_coach → ai_extraction. The
|
||||
// `updateMany` count gates the follow-up re-read. ai_full + ai_coach
|
||||
// revoke a row; the others have none (count 0, no re-read).
|
||||
vi.mocked(prisma.consentReceipt.updateMany)
|
||||
.mockResolvedValueOnce({ count: 1 } as never) // ai_full
|
||||
.mockResolvedValueOnce({ count: 0 } as never) // ai_insights_only
|
||||
.mockResolvedValueOnce({ count: 1 } as never); // ai_coach
|
||||
.mockResolvedValueOnce({ count: 1 } as never) // ai_coach
|
||||
.mockResolvedValueOnce({ count: 0 } as never); // ai_extraction
|
||||
vi.mocked(prisma.consentReceipt.findFirst)
|
||||
.mockResolvedValueOnce({
|
||||
id: "rcpt-full",
|
||||
@@ -323,6 +342,80 @@ describe("DELETE /api/consent/ai/latest", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/consent/ai/latest — purge of regenerable AI text", () => {
|
||||
const revokedRow = {
|
||||
id: "rcpt-1",
|
||||
userId: "user-1",
|
||||
kind: "ai_insights_only",
|
||||
artefact: "PDF",
|
||||
signedAt: new Date("2026-05-18T10:00:00.000Z"),
|
||||
revokedAt: new Date("2026-05-18T11:00:00.000Z"),
|
||||
createdAt: new Date("2026-05-18T10:00:01.000Z"),
|
||||
};
|
||||
|
||||
it("deletes the regenerable text and writes a counts-only purge audit row when nothing covers the analysis any more", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.consentReceipt.updateMany).mockResolvedValue({
|
||||
count: 1,
|
||||
} as never);
|
||||
vi.mocked(prisma.consentReceipt.findFirst).mockResolvedValue(
|
||||
revokedRow as never,
|
||||
);
|
||||
vi.mocked(prisma.consentReceipt.count).mockResolvedValue(0 as never);
|
||||
vi.mocked(prisma.insightStatusCache.deleteMany).mockResolvedValue({
|
||||
count: 4,
|
||||
} as never);
|
||||
|
||||
const res = await DELETE(
|
||||
new NextRequest(
|
||||
"http://localhost/api/consent/ai/latest?kind=ai_insights_only",
|
||||
{ method: "DELETE" },
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.insightStatusCache.deleteMany).toHaveBeenCalledWith({
|
||||
where: { userId: "user-1" },
|
||||
});
|
||||
expect(prisma.workoutInsight.deleteMany).toHaveBeenCalledWith({
|
||||
where: { userId: "user-1" },
|
||||
});
|
||||
expect(auditLog).toHaveBeenCalledWith("consent.ai.purge", {
|
||||
userId: "user-1",
|
||||
details: {
|
||||
statusNotes: 4,
|
||||
briefing: 0,
|
||||
narratives: 0,
|
||||
reactionLines: 0,
|
||||
workoutParagraphs: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the text while another receipt still covers the analysis", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.consentReceipt.updateMany).mockResolvedValue({
|
||||
count: 1,
|
||||
} as never);
|
||||
vi.mocked(prisma.consentReceipt.findFirst).mockResolvedValue(
|
||||
revokedRow as never,
|
||||
);
|
||||
vi.mocked(prisma.consentReceipt.count).mockResolvedValue(1 as never);
|
||||
|
||||
const res = await DELETE(
|
||||
new NextRequest(
|
||||
"http://localhost/api/consent/ai/latest?kind=ai_insights_only",
|
||||
{ method: "DELETE" },
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.insightStatusCache.deleteMany).not.toHaveBeenCalled();
|
||||
expect(auditLog).not.toHaveBeenCalledWith(
|
||||
"consent.ai.purge",
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("append-only invariant", () => {
|
||||
/**
|
||||
* v1.4.40 SB-10 — the receipts table is the legal audit trail.
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
* DELETE /api/consent/ai/latest
|
||||
* Master toggle — revokes the latest active receipt across every
|
||||
* consent kind. Returns the list of revoked rows.
|
||||
*
|
||||
* Either DELETE also deletes the regenerable model-written text (status
|
||||
* notes, the cached briefing, model-written narratives, reaction lines,
|
||||
* workout paragraphs) when it leaves no receipt covering the analysis, in the
|
||||
* same transaction as the revoke. Coach memory and document summaries stay.
|
||||
*/
|
||||
import { NextRequest } from "next/server";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
@@ -28,8 +33,8 @@ import {
|
||||
import {
|
||||
latestActiveReceipt,
|
||||
latestActiveReceiptsByKind,
|
||||
revokeLatest,
|
||||
} from "@/lib/consent/receipts";
|
||||
import { withdrawConsent } from "@/lib/consent/withdrawal";
|
||||
import { serialiseReceipt } from "../route";
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
@@ -81,6 +86,9 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
? serialiseReceipt(byKind.ai_insights_only)
|
||||
: null,
|
||||
ai_coach: byKind.ai_coach ? serialiseReceipt(byKind.ai_coach) : null,
|
||||
ai_extraction: byKind.ai_extraction
|
||||
? serialiseReceipt(byKind.ai_extraction)
|
||||
: null,
|
||||
};
|
||||
|
||||
annotate({
|
||||
@@ -119,53 +127,50 @@ export const DELETE = apiHandler(async (request: NextRequest) => {
|
||||
|
||||
const { kind } = parsed.data;
|
||||
|
||||
if (kind) {
|
||||
const revoked = await revokeLatest(user.id, kind);
|
||||
if (!revoked) {
|
||||
// Idempotent: "no active receipt to revoke" is success-shaped.
|
||||
// The iOS toggle hammers this on every flip; returning 404
|
||||
// would surface as a spurious error in the client.
|
||||
annotate({
|
||||
action: { name: "consent.ai.revoke" },
|
||||
meta: { kind, revoked: false },
|
||||
});
|
||||
return apiSuccess({ kind, receipt: null });
|
||||
}
|
||||
// One kind, or every kind for the master "turn AI off" toggle. The revoke
|
||||
// and the purge of the regenerable text the consent covered commit
|
||||
// together (`withdrawConsent`).
|
||||
const kinds = kind ? [kind] : consentKindEnum.options;
|
||||
const { revoked, purged } = await withdrawConsent(user.id, kinds);
|
||||
|
||||
for (const { kind: k, receipt } of revoked) {
|
||||
auditLog("consent.ai.revoke", {
|
||||
userId: user.id,
|
||||
details: { kind, receiptId: revoked.id },
|
||||
details: { kind: k, receiptId: receipt.id },
|
||||
}).catch(() => {});
|
||||
annotate({
|
||||
action: { name: "consent.ai.revoke" },
|
||||
meta: { kind, receiptId: revoked.id },
|
||||
});
|
||||
return apiSuccess({ kind, receipt: serialiseReceipt(revoked) });
|
||||
}
|
||||
|
||||
// No kind specified — master "AI deaktivieren" toggle. Revoke the
|
||||
// latest active row for every kind that currently has one.
|
||||
const revokedRows: Array<{
|
||||
kind: ConsentKind;
|
||||
receipt: ReturnType<typeof serialiseReceipt>;
|
||||
}> = [];
|
||||
for (const k of consentKindEnum.options) {
|
||||
const r = await revokeLatest(user.id, k);
|
||||
if (r) {
|
||||
revokedRows.push({ kind: k, receipt: serialiseReceipt(r) });
|
||||
auditLog("consent.ai.revoke", {
|
||||
userId: user.id,
|
||||
details: { kind: k, receiptId: r.id },
|
||||
}).catch(() => {});
|
||||
}
|
||||
if (purged) {
|
||||
// Counts only, never content.
|
||||
auditLog("consent.ai.purge", {
|
||||
userId: user.id,
|
||||
details: { ...purged },
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
annotate({
|
||||
action: { name: "consent.ai.revoke" },
|
||||
meta: {
|
||||
kinds_revoked: revokedRows.map((r) => r.kind),
|
||||
count: revokedRows.length,
|
||||
kinds_revoked: revoked.map((r) => r.kind),
|
||||
count: revoked.length,
|
||||
purged: purged !== null,
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess({ revoked: revokedRows });
|
||||
if (kind) {
|
||||
// Idempotent: "no active receipt to revoke" is success-shaped. The iOS
|
||||
// toggle hammers this on every flip; returning 404 would surface as a
|
||||
// spurious error in the client.
|
||||
const receipt = revoked[0]?.receipt ?? null;
|
||||
return apiSuccess({
|
||||
kind,
|
||||
receipt: receipt ? serialiseReceipt(receipt) : null,
|
||||
});
|
||||
}
|
||||
|
||||
return apiSuccess({
|
||||
revoked: revoked.map((r) => ({
|
||||
kind: r.kind,
|
||||
receipt: serialiseReceipt(r.receipt),
|
||||
})),
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user