mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
style: apply prettier across the tree
One-shot prettier pass so the new format:check gate starts from a clean baseline. Formatting only — no behaviour change. Generator-owned and vendored artifacts stay untouched via .prettierignore.
This commit is contained in:
1 parent
b3fea2ef59
commit
1f4ba5939d
1000 files changed
+12130
-8385
No files matched your search
@@ -365,7 +365,8 @@ describe("Codex slug fallback chain", () => {
|
||||
} finally {
|
||||
if (origModel === undefined) delete process.env.CODEX_MODEL;
|
||||
else process.env.CODEX_MODEL = origModel;
|
||||
if (origChain === undefined) delete process.env.CODEX_MODEL_FALLBACK_CHAIN;
|
||||
if (origChain === undefined)
|
||||
delete process.env.CODEX_MODEL_FALLBACK_CHAIN;
|
||||
else process.env.CODEX_MODEL_FALLBACK_CHAIN = origChain;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -49,7 +49,10 @@ describe("chainRequiresServerManagedConsent", () => {
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
chainRequiresServerManagedConsent([entry("openai"), entry("admin-openai")]),
|
||||
chainRequiresServerManagedConsent([
|
||||
entry("openai"),
|
||||
entry("admin-openai"),
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
|
||||
@@ -28,10 +28,7 @@ describe("isLocalAiHostAllowed", () => {
|
||||
});
|
||||
|
||||
it("permits ONLY the listed hosts when given a comma-separated allowlist", () => {
|
||||
vi.stubEnv(
|
||||
"ALLOW_LOCAL_AI_PRIVATE_HOSTS",
|
||||
"ollama.lan, 10.0.0.5",
|
||||
);
|
||||
vi.stubEnv("ALLOW_LOCAL_AI_PRIVATE_HOSTS", "ollama.lan, 10.0.0.5");
|
||||
expect(isLocalAiHostAllowed("http://ollama.lan:11434/v1")).toBe(true);
|
||||
expect(isLocalAiHostAllowed("http://10.0.0.5:11434/v1")).toBe(true);
|
||||
// A different private host is still rejected — the metadata endpoint and
|
||||
|
||||
@@ -57,7 +57,13 @@ describe("coach clusters", () => {
|
||||
it("expands the default clusters to the legacy core sources + additive members", () => {
|
||||
const sources = clusterSourcesFromPrefs(undefined);
|
||||
// Legacy five domains' sources are all present.
|
||||
for (const core of ["bp", "weight", "pulse", "mood", "compliance"] as const) {
|
||||
for (const core of [
|
||||
"bp",
|
||||
"weight",
|
||||
"pulse",
|
||||
"mood",
|
||||
"compliance",
|
||||
] as const) {
|
||||
expect(sources.has(core)).toBe(true);
|
||||
}
|
||||
// Additive members ride inside cardio/body.
|
||||
|
||||
@@ -121,7 +121,8 @@ describe("refreshConversationSummary", () => {
|
||||
});
|
||||
|
||||
it("(c) merge path passes the decrypted prior summary into the user prompt", async () => {
|
||||
const prior = "Earlier: user wants better sleep and dislikes evening caffeine.";
|
||||
const prior =
|
||||
"Earlier: user wants better sleep and dislikes evening caffeine.";
|
||||
// 30 turns, no prior summaryTurnCount → forces a generation.
|
||||
const { client } = makePrisma(
|
||||
makeConversation(30, {
|
||||
@@ -162,7 +163,9 @@ describe("refreshConversationSummary", () => {
|
||||
|
||||
it("(e) success path encrypts and persists summaryEncrypted + turn count + updatedAt", async () => {
|
||||
const now = new Date("2026-06-04T08:00:00.000Z");
|
||||
const { client, update } = makePrisma(makeConversation(30, { summaryTurnCount: 0 }));
|
||||
const { client, update } = makePrisma(
|
||||
makeConversation(30, { summaryTurnCount: 0 }),
|
||||
);
|
||||
const runCompletion = vi.fn().mockResolvedValue(okCompletion);
|
||||
|
||||
const result = await refreshConversationSummary("conv-1", "user-1", {
|
||||
@@ -185,9 +188,7 @@ describe("refreshConversationSummary", () => {
|
||||
|
||||
describe("buildSummaryUserPrompt", () => {
|
||||
it("uses (none) when no prior summary is supplied", () => {
|
||||
const out = buildSummaryUserPrompt(null, [
|
||||
{ role: "user", content: "hi" },
|
||||
]);
|
||||
const out = buildSummaryUserPrompt(null, [{ role: "user", content: "hi" }]);
|
||||
expect(out).toContain("PRIOR SUMMARY\n(none)");
|
||||
expect(out).toContain("user: hi");
|
||||
});
|
||||
|
||||
@@ -73,7 +73,9 @@ function rhrMeasurements() {
|
||||
out.push({
|
||||
type: "RESTING_HEART_RATE",
|
||||
value: v + (i % 3) * 0.5,
|
||||
measuredAt: new Date(`2026-03-${String(i).padStart(2, "0")}T12:00:00.000Z`),
|
||||
measuredAt: new Date(
|
||||
`2026-03-${String(i).padStart(2, "0")}T12:00:00.000Z`,
|
||||
),
|
||||
source: "APPLE_HEALTH",
|
||||
deviceType: null,
|
||||
});
|
||||
@@ -176,6 +178,8 @@ describe("buildCycleSnapshotBlock", () => {
|
||||
expect(block!.phaseInsight).not.toBeNull();
|
||||
expect(block!.phaseInsight!.metric).toBe("resting heart rate");
|
||||
expect(block!.phaseInsight!.delta).toBeGreaterThan(0);
|
||||
expect(block!.phaseInsight!.interpretation).toMatch(/descriptive pattern, not a cause/);
|
||||
expect(block!.phaseInsight!.interpretation).toMatch(
|
||||
/descriptive pattern, not a cause/,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/insights/derived", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/insights/derived")>();
|
||||
const actual =
|
||||
await importOriginal<typeof import("@/lib/insights/derived")>();
|
||||
return { ...actual, computeDerivedMetric: vi.fn() };
|
||||
});
|
||||
|
||||
@@ -14,8 +15,9 @@ import { prisma } from "@/lib/db";
|
||||
import { buildDerivedSnapshotBlock } from "../derived-snapshot";
|
||||
|
||||
const compute = computeDerivedMetric as unknown as ReturnType<typeof vi.fn>;
|
||||
const whoopFindFirst = prisma.measurement
|
||||
.findFirst as unknown as ReturnType<typeof vi.fn>;
|
||||
const whoopFindFirst = prisma.measurement.findFirst as unknown as ReturnType<
|
||||
typeof vi.fn
|
||||
>;
|
||||
/** Make the WHOOP-native recovery probe report present / absent. */
|
||||
function setWhoopNativePresent(present: boolean) {
|
||||
whoopFindFirst.mockResolvedValue(present ? { id: "whoop-1" } : null);
|
||||
@@ -29,13 +31,28 @@ function ok(value: Record<string, unknown>, historyDays = 14) {
|
||||
value,
|
||||
coverage: { requiredInputs: 1, presentInputs: 1, historyDays, missing: [] },
|
||||
confidence: { score: 88, band: "high" as const },
|
||||
provenance: { inputs: [], source: "DAY" as const, windowDays: 14, computedAt: "x" },
|
||||
provenance: {
|
||||
inputs: [],
|
||||
source: "DAY" as const,
|
||||
windowDays: 14,
|
||||
computedAt: "x",
|
||||
},
|
||||
};
|
||||
}
|
||||
const insufficient = {
|
||||
status: "insufficient" as const,
|
||||
coverage: { requiredInputs: 1, presentInputs: 0, historyDays: 0, missing: [] },
|
||||
provenance: { inputs: [], source: "none" as const, windowDays: 0, computedAt: "x" },
|
||||
coverage: {
|
||||
requiredInputs: 1,
|
||||
presentInputs: 0,
|
||||
historyDays: 0,
|
||||
missing: [],
|
||||
},
|
||||
provenance: {
|
||||
inputs: [],
|
||||
source: "none" as const,
|
||||
windowDays: 0,
|
||||
computedAt: "x",
|
||||
},
|
||||
reason: "no_score_in_window",
|
||||
};
|
||||
|
||||
@@ -59,8 +76,10 @@ describe("buildDerivedSnapshotBlock", () => {
|
||||
// alongside readiness (the dedup only drops the COMPUTED proxy).
|
||||
setWhoopNativePresent(true);
|
||||
compute.mockImplementation(async (args?: { metric?: string }) => {
|
||||
if (args?.metric === "READINESS") return ok({ score: 64, band: "yellow" });
|
||||
if (args?.metric === "RECOVERY_SCORE") return ok({ score: 72, band: "green" });
|
||||
if (args?.metric === "READINESS")
|
||||
return ok({ score: 64, band: "yellow" });
|
||||
if (args?.metric === "RECOVERY_SCORE")
|
||||
return ok({ score: 72, band: "green" });
|
||||
return insufficient;
|
||||
});
|
||||
const block = await buildDerivedSnapshotBlock("u1", PROFILE, NOW);
|
||||
@@ -87,8 +106,10 @@ describe("buildDerivedSnapshotBlock", () => {
|
||||
// same number twice, so the recovery line is dropped.
|
||||
setWhoopNativePresent(false);
|
||||
compute.mockImplementation(async (args?: { metric?: string }) => {
|
||||
if (args?.metric === "READINESS") return ok({ score: 64, band: "yellow" });
|
||||
if (args?.metric === "RECOVERY_SCORE") return ok({ score: 64, band: "yellow" });
|
||||
if (args?.metric === "READINESS")
|
||||
return ok({ score: 64, band: "yellow" });
|
||||
if (args?.metric === "RECOVERY_SCORE")
|
||||
return ok({ score: 64, band: "yellow" });
|
||||
return insufficient;
|
||||
});
|
||||
const block = await buildDerivedSnapshotBlock("u1", PROFILE, NOW);
|
||||
@@ -103,8 +124,10 @@ describe("buildDerivedSnapshotBlock", () => {
|
||||
// source-aware drop keeps it because a WHOOP-native row exists.
|
||||
setWhoopNativePresent(true);
|
||||
compute.mockImplementation(async (args?: { metric?: string }) => {
|
||||
if (args?.metric === "READINESS") return ok({ score: 64, band: "yellow" });
|
||||
if (args?.metric === "RECOVERY_SCORE") return ok({ score: 64, band: "yellow" });
|
||||
if (args?.metric === "READINESS")
|
||||
return ok({ score: 64, band: "yellow" });
|
||||
if (args?.metric === "RECOVERY_SCORE")
|
||||
return ok({ score: 64, band: "yellow" });
|
||||
return insufficient;
|
||||
});
|
||||
const block = await buildDerivedSnapshotBlock("u1", PROFILE, NOW);
|
||||
@@ -115,8 +138,10 @@ describe("buildDerivedSnapshotBlock", () => {
|
||||
it("keeps RECOVERY_SCORE when a WHOOP-native value differs from READINESS", async () => {
|
||||
setWhoopNativePresent(true);
|
||||
compute.mockImplementation(async (args?: { metric?: string }) => {
|
||||
if (args?.metric === "READINESS") return ok({ score: 64, band: "yellow" });
|
||||
if (args?.metric === "RECOVERY_SCORE") return ok({ score: 80, band: "green" });
|
||||
if (args?.metric === "READINESS")
|
||||
return ok({ score: 64, band: "yellow" });
|
||||
if (args?.metric === "RECOVERY_SCORE")
|
||||
return ok({ score: 80, band: "green" });
|
||||
return insufficient;
|
||||
});
|
||||
const block = await buildDerivedSnapshotBlock("u1", PROFILE, NOW);
|
||||
@@ -127,12 +152,18 @@ describe("buildDerivedSnapshotBlock", () => {
|
||||
it("isolates a per-metric compute failure", async () => {
|
||||
compute.mockImplementation(async (args?: { metric?: string }) => {
|
||||
if (args?.metric === "READINESS") throw new Error("boom");
|
||||
if (args?.metric === "SLEEP_SCORE") return ok({ score: 80, band: "green" });
|
||||
if (args?.metric === "SLEEP_SCORE")
|
||||
return ok({ score: 80, band: "green" });
|
||||
return insufficient;
|
||||
});
|
||||
const block = await buildDerivedSnapshotBlock("u1", PROFILE, NOW);
|
||||
expect(block).toEqual({
|
||||
SLEEP_SCORE: { value: 80, band: "green", confidence: 88, historyDays: 14 },
|
||||
SLEEP_SCORE: {
|
||||
value: 80,
|
||||
band: "green",
|
||||
confidence: 88,
|
||||
historyDays: 14,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -59,15 +59,22 @@ describe("buildCoachFactsBlock", () => {
|
||||
});
|
||||
|
||||
expect(block).not.toBeNull();
|
||||
expect(block!.facts.map((f) => f.text)).toEqual(["newer high", "older high", "low"]);
|
||||
expect(block!.facts.map((f) => f.text)).toEqual([
|
||||
"newer high",
|
||||
"older high",
|
||||
"low",
|
||||
]);
|
||||
});
|
||||
|
||||
it("takes only the top N", async () => {
|
||||
const seed: SeedRow[] = Array.from({ length: FACTS_INJECT_TOP_N + 4 }, (_, i) => ({
|
||||
text: `fact ${i}`,
|
||||
confidence: 100 - i,
|
||||
updatedAt: new Date(2026, 0, 1 + i),
|
||||
}));
|
||||
const seed: SeedRow[] = Array.from(
|
||||
{ length: FACTS_INJECT_TOP_N + 4 },
|
||||
(_, i) => ({
|
||||
text: `fact ${i}`,
|
||||
confidence: 100 - i,
|
||||
updatedAt: new Date(2026, 0, 1 + i),
|
||||
}),
|
||||
);
|
||||
const { prisma } = makeFakePrisma(seed);
|
||||
|
||||
const block = await buildCoachFactsBlock("user-1", {
|
||||
@@ -92,8 +99,18 @@ describe("buildCoachFactsBlock", () => {
|
||||
it("skips undecryptable rows fault-isolated (never throws)", async () => {
|
||||
// One row whose codec throws on decrypt; the helper must skip it.
|
||||
const findMany = vi.fn(async () => [
|
||||
{ factEncrypted: bytes("good fact"), category: "goal", confidence: 80, updatedAt: new Date() },
|
||||
{ factEncrypted: bytes("__throw__"), category: "goal", confidence: 70, updatedAt: new Date() },
|
||||
{
|
||||
factEncrypted: bytes("good fact"),
|
||||
category: "goal",
|
||||
confidence: 80,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
{
|
||||
factEncrypted: bytes("__throw__"),
|
||||
category: "goal",
|
||||
confidence: 70,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
]);
|
||||
// Re-point the codec mock to throw for the sentinel payload.
|
||||
const codec = await import("../bytes-codec");
|
||||
|
||||
@@ -85,8 +85,10 @@ describe("extractDeterministicFacts", () => {
|
||||
|
||||
it("matches German intolerance statements", () => {
|
||||
expect(
|
||||
extractDeterministicFacts("ich habe eine Laktoseunverträglichkeit", "de")[0]
|
||||
?.fact,
|
||||
extractDeterministicFacts(
|
||||
"ich habe eine Laktoseunverträglichkeit",
|
||||
"de",
|
||||
)[0]?.fact,
|
||||
).toContain("Laktose");
|
||||
expect(
|
||||
extractDeterministicFacts("ich bin laktoseintolerant", "de")[0]?.fact,
|
||||
@@ -139,7 +141,10 @@ describe("extractDeterministicFacts", () => {
|
||||
[],
|
||||
);
|
||||
expect(
|
||||
extractDeterministicFacts("meine Schwester hat eine Katzenhaarallergie", "de"),
|
||||
extractDeterministicFacts(
|
||||
"meine Schwester hat eine Katzenhaarallergie",
|
||||
"de",
|
||||
),
|
||||
).toEqual([]);
|
||||
expect(
|
||||
extractDeterministicFacts("what is an allergy exactly?", "en"),
|
||||
|
||||
@@ -47,7 +47,12 @@ function bytes(s: string): Uint8Array {
|
||||
}
|
||||
|
||||
function makeFakePrisma(opts: {
|
||||
activeFacts?: Array<{ id?: string; text: string; category?: string; confidence?: number }>;
|
||||
activeFacts?: Array<{
|
||||
id?: string;
|
||||
text: string;
|
||||
category?: string;
|
||||
confidence?: number;
|
||||
}>;
|
||||
turns?: Array<{ role: string; content: string }>;
|
||||
conversationExists?: boolean;
|
||||
}) {
|
||||
@@ -87,7 +92,13 @@ function makeFakePrisma(opts: {
|
||||
}
|
||||
|
||||
function ok(content: string): StatusProviderResult {
|
||||
return { kind: "ok", content, providerType: "mock", model: "m", tokensUsed: 1 };
|
||||
return {
|
||||
kind: "ok",
|
||||
content,
|
||||
providerType: "mock",
|
||||
model: "m",
|
||||
tokensUsed: 1,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -97,12 +108,21 @@ beforeEach(() => {
|
||||
describe("extractAndStoreFacts", () => {
|
||||
it("(a) parses durable facts and persists them field-by-field", async () => {
|
||||
const { prisma, createCalls } = makeFakePrisma({
|
||||
turns: [{ role: "user", content: "I prefer morning workouts and I'm vegetarian." }],
|
||||
turns: [
|
||||
{
|
||||
role: "user",
|
||||
content: "I prefer morning workouts and I'm vegetarian.",
|
||||
},
|
||||
],
|
||||
});
|
||||
const runCompletion = vi.fn(async () =>
|
||||
ok(
|
||||
JSON.stringify([
|
||||
{ category: "preference", fact: "Prefers morning workouts", confidence: 90 },
|
||||
{
|
||||
category: "preference",
|
||||
fact: "Prefers morning workouts",
|
||||
confidence: 90,
|
||||
},
|
||||
{ category: "preference", fact: "Is vegetarian", confidence: 80 },
|
||||
]),
|
||||
),
|
||||
@@ -120,7 +140,13 @@ describe("extractAndStoreFacts", () => {
|
||||
// Field-by-field — exact key set, no spread of the parsed object.
|
||||
for (const data of createCalls) {
|
||||
expect(Object.keys(data).sort()).toEqual(
|
||||
["category", "confidence", "factEncrypted", "sourceConversationId", "userId"].sort(),
|
||||
[
|
||||
"category",
|
||||
"confidence",
|
||||
"factEncrypted",
|
||||
"sourceConversationId",
|
||||
"userId",
|
||||
].sort(),
|
||||
);
|
||||
expect(data.userId).toBe("user-1");
|
||||
expect(data.sourceConversationId).toBe("conv-1");
|
||||
@@ -128,7 +154,9 @@ describe("extractAndStoreFacts", () => {
|
||||
}
|
||||
// Annotation carries counts/ids only.
|
||||
const extracted = annotateMock.mock.calls.find(
|
||||
(c) => (c[0] as { action?: { name?: string } }).action?.name === "coach.facts.extracted",
|
||||
(c) =>
|
||||
(c[0] as { action?: { name?: string } }).action?.name ===
|
||||
"coach.facts.extracted",
|
||||
);
|
||||
expect(extracted).toBeTruthy();
|
||||
expect((extracted![0] as { meta: Record<string, unknown> }).meta).toEqual({
|
||||
@@ -181,7 +209,9 @@ describe("extractAndStoreFacts", () => {
|
||||
expect(res).toEqual({ status: "none", count: 0 });
|
||||
expect(createCalls).toHaveLength(0);
|
||||
const failed = annotateMock.mock.calls.find(
|
||||
(c) => (c[0] as { action?: { name?: string } }).action?.name === "coach.facts.parse_failed",
|
||||
(c) =>
|
||||
(c[0] as { action?: { name?: string } }).action?.name ===
|
||||
"coach.facts.parse_failed",
|
||||
);
|
||||
expect(failed).toBeTruthy();
|
||||
expect((failed![0] as { meta: Record<string, unknown> }).meta).toEqual({
|
||||
@@ -197,8 +227,16 @@ describe("extractAndStoreFacts", () => {
|
||||
const runCompletion = vi.fn(async () =>
|
||||
ok(
|
||||
JSON.stringify([
|
||||
{ category: "preference", fact: "prefers morning workouts", confidence: 90 }, // dup
|
||||
{ category: "goal", fact: "Wants to run a 10k in autumn", confidence: 85 }, // new
|
||||
{
|
||||
category: "preference",
|
||||
fact: "prefers morning workouts",
|
||||
confidence: 90,
|
||||
}, // dup
|
||||
{
|
||||
category: "goal",
|
||||
fact: "Wants to run a 10k in autumn",
|
||||
confidence: 85,
|
||||
}, // new
|
||||
]),
|
||||
),
|
||||
);
|
||||
@@ -229,7 +267,11 @@ describe("extractAndStoreFacts", () => {
|
||||
ok(
|
||||
JSON.stringify([
|
||||
{ category: "goal", fact: "low confidence newcomer", confidence: 20 }, // ≤30 → skip
|
||||
{ category: "goal", fact: "high confidence newcomer", confidence: 95 }, // >30 → store
|
||||
{
|
||||
category: "goal",
|
||||
fact: "high confidence newcomer",
|
||||
confidence: 95,
|
||||
}, // >30 → store
|
||||
]),
|
||||
),
|
||||
);
|
||||
@@ -251,7 +293,9 @@ describe("extractAndStoreFacts", () => {
|
||||
const { prisma, createCalls } = makeFakePrisma({
|
||||
turns: [{ role: "user", content: "talk" }],
|
||||
});
|
||||
const runCompletion = vi.fn(async () => ({ kind }) as StatusProviderResult);
|
||||
const runCompletion = vi.fn(
|
||||
async () => ({ kind }) as StatusProviderResult,
|
||||
);
|
||||
const res = await extractAndStoreFacts("conv-1", "user-1", {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
prisma: prisma as any,
|
||||
|
||||
@@ -93,7 +93,11 @@ describe("buildCoachMemoryBlock", () => {
|
||||
expect(block?.priorNarrative?.headline).toContain("Ruhepuls");
|
||||
expect(block?.priorNarrative?.drivers).toEqual([]);
|
||||
expect(block?.trendMemory).toEqual({
|
||||
HEART_RATE: { priorBand: "in", currentBand: "above", priorPeriod: "month" },
|
||||
HEART_RATE: {
|
||||
priorBand: "in",
|
||||
currentBand: "above",
|
||||
priorPeriod: "month",
|
||||
},
|
||||
WEIGHT: { priorBand: "in", currentBand: "in", priorPeriod: "month" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,8 +9,8 @@ const txCreate = {
|
||||
};
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
$transaction: vi.fn(
|
||||
async (cb: (tx: typeof txCreate) => Promise<unknown>) => cb(txCreate),
|
||||
$transaction: vi.fn(async (cb: (tx: typeof txCreate) => Promise<unknown>) =>
|
||||
cb(txCreate),
|
||||
),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -40,7 +40,9 @@ const BRAND_TOKENS = [
|
||||
|
||||
describe("buildReferenceGroundingBlock", () => {
|
||||
it("returns null when no metric is covered by the backbone", () => {
|
||||
expect(buildReferenceGroundingBlock({ metrics: [], hasDiabetes: false })).toBeNull();
|
||||
expect(
|
||||
buildReferenceGroundingBlock({ metrics: [], hasDiabetes: false }),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("cites the ESH 2023 source for blood pressure and never the US/ESC line", () => {
|
||||
@@ -74,9 +76,7 @@ describe("buildReferenceGroundingBlock", () => {
|
||||
})!;
|
||||
expect(block).toContain("general guidance");
|
||||
expect(block).toContain("not a diagnosis");
|
||||
expect(block.toLowerCase()).toContain(
|
||||
"not personal medical advice",
|
||||
);
|
||||
expect(block.toLowerCase()).toContain("not personal medical advice");
|
||||
// The closing reminder line is present.
|
||||
expect(block).toMatch(/general guidance, not personal medical advice\.$/);
|
||||
});
|
||||
@@ -150,7 +150,9 @@ describe("buildReferenceGroundingBlock", () => {
|
||||
metrics: [{ metric: "PULSE_PRESSURE", value: 40 }],
|
||||
hasDiabetes: false,
|
||||
})!;
|
||||
const line = block.split("\n").find((l) => l.startsWith("- pulse pressure:"))!;
|
||||
const line = block
|
||||
.split("\n")
|
||||
.find((l) => l.startsWith("- pulse pressure:"))!;
|
||||
// The normal "Typical at rest" band (25–60), not the first "Narrow" band.
|
||||
expect(line).toContain("25–60 mmHg");
|
||||
expect(line).toContain("sits inside the general reference band");
|
||||
|
||||
@@ -33,9 +33,9 @@ vi.mock("@/lib/modules/gate", () => ({
|
||||
// with the same resolved map the tests drive via `resolveModuleMap`.
|
||||
isModuleEnabled: vi.fn(async (...args: [string, ModuleKey]) => {
|
||||
const key = args[1];
|
||||
const map = await (resolveModuleMap as unknown as () => Promise<
|
||||
Record<ModuleKey, boolean>
|
||||
>)();
|
||||
const map = await (
|
||||
resolveModuleMap as unknown as () => Promise<Record<ModuleKey, boolean>>
|
||||
)();
|
||||
return map[key] !== false;
|
||||
}),
|
||||
}));
|
||||
|
||||
@@ -44,9 +44,9 @@ vi.mock("@/lib/modules/gate", () => ({
|
||||
// with the same resolved map the tests drive via `resolveModuleMap`.
|
||||
isModuleEnabled: vi.fn(async (...args: [string, ModuleKey]) => {
|
||||
const key = args[1];
|
||||
const map = await (resolveModuleMap as unknown as () => Promise<
|
||||
Record<ModuleKey, boolean>
|
||||
>)();
|
||||
const map = await (
|
||||
resolveModuleMap as unknown as () => Promise<Record<ModuleKey, boolean>>
|
||||
)();
|
||||
return map[key] !== false;
|
||||
}),
|
||||
}));
|
||||
@@ -406,7 +406,10 @@ describe("buildCoachSnapshot — WHOOP-native day strain (v1.17.0)", () => {
|
||||
mockByType({
|
||||
HEART_RATE_VARIABILITY: [daysAgo(2, 64, "HEART_RATE_VARIABILITY")],
|
||||
// Ascending (oldest first), mirroring the `orderBy: measuredAt asc` read.
|
||||
DAY_STRAIN: [daysAgo(3, 11.8, "DAY_STRAIN"), daysAgo(1, 14.2, "DAY_STRAIN")],
|
||||
DAY_STRAIN: [
|
||||
daysAgo(3, 11.8, "DAY_STRAIN"),
|
||||
daysAgo(1, 14.2, "DAY_STRAIN"),
|
||||
],
|
||||
});
|
||||
|
||||
const out = await buildCoachSnapshot("user-1", {
|
||||
|
||||
@@ -46,9 +46,9 @@ vi.mock("@/lib/modules/gate", () => ({
|
||||
// cycle block (operator/user kill-switch parity) without a DB read.
|
||||
isModuleEnabled: vi.fn(async (...args: [string, ModuleKey]) => {
|
||||
const key = args[1];
|
||||
const map = await (resolveModuleMap as unknown as () => Promise<
|
||||
Record<ModuleKey, boolean>
|
||||
>)();
|
||||
const map = await (
|
||||
resolveModuleMap as unknown as () => Promise<Record<ModuleKey, boolean>>
|
||||
)();
|
||||
return map[key] !== false;
|
||||
}),
|
||||
}));
|
||||
@@ -319,12 +319,12 @@ describe("buildCoachSnapshot", () => {
|
||||
// The compliance query and the GLP-1 query share this mock; only the
|
||||
// compliance one (no `treatmentClass` filter) gets the fixture so the
|
||||
// GLP-1 block — which selects `doseChanges` etc. — sees no rows.
|
||||
prismaMock.medication.findMany.mockImplementation((args?: {
|
||||
where?: { treatmentClass?: string };
|
||||
}) => {
|
||||
if (args?.where?.treatmentClass === "GLP1") return Promise.resolve([]);
|
||||
return Promise.resolve([medication]);
|
||||
});
|
||||
prismaMock.medication.findMany.mockImplementation(
|
||||
(args?: { where?: { treatmentClass?: string } }) => {
|
||||
if (args?.where?.treatmentClass === "GLP1") return Promise.resolve([]);
|
||||
return Promise.resolve([medication]);
|
||||
},
|
||||
);
|
||||
prismaMock.user.findUnique.mockResolvedValue({
|
||||
coachPrefsJson: null,
|
||||
timezone: "Europe/Berlin",
|
||||
@@ -339,7 +339,11 @@ describe("buildCoachSnapshot", () => {
|
||||
// Independent authority over the same window the coach uses (30-day
|
||||
// default scope), same ledger context — the coach rate must equal it.
|
||||
const now = new Date();
|
||||
const ctx = buildComplianceMedicationContext(medication, null, "Europe/Berlin");
|
||||
const ctx = buildComplianceMedicationContext(
|
||||
medication,
|
||||
null,
|
||||
"Europe/Berlin",
|
||||
);
|
||||
const authority = calculateCompliance(
|
||||
intakeEvents,
|
||||
[schedule],
|
||||
@@ -672,9 +676,8 @@ describe("buildCoachSnapshot", () => {
|
||||
recovery: false,
|
||||
});
|
||||
const { buildDerivedSnapshotBlock } = await import("../derived-snapshot");
|
||||
const { buildTrajectorySnapshotBlock } = await import(
|
||||
"../trajectory-snapshot"
|
||||
);
|
||||
const { buildTrajectorySnapshotBlock } =
|
||||
await import("../trajectory-snapshot");
|
||||
|
||||
prismaMock.measurement.findMany.mockResolvedValue([]);
|
||||
featuresMock.mockResolvedValue({
|
||||
@@ -850,8 +853,7 @@ describe("Coach snapshot — free-text fields wrap through sanitizeForPrompt (L-
|
||||
if (violations.length > 0) {
|
||||
const formatted = violations
|
||||
.map(
|
||||
(v) =>
|
||||
` ${filePath}:${v.line} — \`${v.fieldName}\`: ${v.snippet}`,
|
||||
(v) => ` ${filePath}:${v.line} — \`${v.fieldName}\`: ${v.snippet}`,
|
||||
)
|
||||
.join("\n");
|
||||
throw new Error(
|
||||
|
||||
@@ -42,7 +42,10 @@ describe("decideFromPrefs", () => {
|
||||
|
||||
it("suppresses a dismissed cadence (dismissal memory)", () => {
|
||||
const d = decideFromPrefs(
|
||||
{ ...DEFAULT_REMINDER_SUGGESTION_PREFS, dismissedCadences: ["weight_daily"] },
|
||||
{
|
||||
...DEFAULT_REMINDER_SUGGESTION_PREFS,
|
||||
dismissedCadences: ["weight_daily"],
|
||||
},
|
||||
"weight_daily",
|
||||
NOW,
|
||||
);
|
||||
@@ -131,8 +134,11 @@ describe("gateSuggestion", () => {
|
||||
now: NOW,
|
||||
});
|
||||
expect(
|
||||
(prisma as unknown as { measurementReminder: { findFirst: ReturnType<typeof vi.fn> } })
|
||||
.measurementReminder.findFirst,
|
||||
(
|
||||
prisma as unknown as {
|
||||
measurementReminder: { findFirst: ReturnType<typeof vi.fn> };
|
||||
}
|
||||
).measurementReminder.findFirst,
|
||||
).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -61,8 +61,7 @@ describe("parseSuggestReminder", () => {
|
||||
});
|
||||
|
||||
it("flags malformed and strips the block on an unknown cadence id", () => {
|
||||
const raw =
|
||||
"text\n---SUGGEST-REMINDER---\ncadence: bp_hourly\n---END---";
|
||||
const raw = "text\n---SUGGEST-REMINDER---\ncadence: bp_hourly\n---END---";
|
||||
const r = parseSuggestReminder(raw);
|
||||
expect(r.cadence).toBeNull();
|
||||
expect(r.malformed).toBe(true);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
vi.mock("@/lib/insights/derived", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/lib/insights/derived")>();
|
||||
const actual =
|
||||
await importOriginal<typeof import("@/lib/insights/derived")>();
|
||||
return { ...actual, computeTrajectory: vi.fn() };
|
||||
});
|
||||
|
||||
@@ -26,20 +27,52 @@ function okTrajectory(type: string) {
|
||||
sampleDays: 20,
|
||||
lastValue: 61.44,
|
||||
projection: [
|
||||
{ dayOffset: 1, date: "2026-06-03", projected: 61.5, bandLow: 60.1, bandHigh: 62.9 },
|
||||
{ dayOffset: 14, date: "2026-06-16", projected: 63.16, bandLow: 60.02, bandHigh: 66.34 },
|
||||
{
|
||||
dayOffset: 1,
|
||||
date: "2026-06-03",
|
||||
projected: 61.5,
|
||||
bandLow: 60.1,
|
||||
bandHigh: 62.9,
|
||||
},
|
||||
{
|
||||
dayOffset: 14,
|
||||
date: "2026-06-16",
|
||||
projected: 63.16,
|
||||
bandLow: 60.02,
|
||||
bandHigh: 66.34,
|
||||
},
|
||||
],
|
||||
method: "ols" as const,
|
||||
},
|
||||
coverage: { requiredInputs: 1, presentInputs: 1, historyDays: 20, missing: [] },
|
||||
coverage: {
|
||||
requiredInputs: 1,
|
||||
presentInputs: 1,
|
||||
historyDays: 20,
|
||||
missing: [],
|
||||
},
|
||||
confidence: { score: 71, band: "moderate" as const },
|
||||
provenance: { inputs: [type], source: "DAY" as const, windowDays: 30, computedAt: "x" },
|
||||
provenance: {
|
||||
inputs: [type],
|
||||
source: "DAY" as const,
|
||||
windowDays: 30,
|
||||
computedAt: "x",
|
||||
},
|
||||
};
|
||||
}
|
||||
const insufficient = {
|
||||
status: "insufficient" as const,
|
||||
coverage: { requiredInputs: 1, presentInputs: 0, historyDays: 4, missing: [] },
|
||||
provenance: { inputs: [], source: "none" as const, windowDays: 30, computedAt: "x" },
|
||||
coverage: {
|
||||
requiredInputs: 1,
|
||||
presentInputs: 0,
|
||||
historyDays: 4,
|
||||
missing: [],
|
||||
},
|
||||
provenance: {
|
||||
inputs: [],
|
||||
source: "none" as const,
|
||||
windowDays: 30,
|
||||
computedAt: "x",
|
||||
},
|
||||
reason: "insufficient_fit_for_projection",
|
||||
};
|
||||
|
||||
|
||||
@@ -27,10 +27,7 @@
|
||||
* Server-only — reads `@/lib/db`.
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import {
|
||||
decryptFromBytes,
|
||||
encryptToBytes,
|
||||
} from "@/lib/ai/coach/bytes-codec";
|
||||
import { decryptFromBytes, encryptToBytes } from "@/lib/ai/coach/bytes-codec";
|
||||
import {
|
||||
SELF_REPORT_FENCE_START,
|
||||
SELF_REPORT_FENCE_END,
|
||||
@@ -87,11 +84,15 @@ export async function getSelfContextForUser(
|
||||
coachFocus: decryptOrNull(row?.coachFocusEncrypted ?? null),
|
||||
};
|
||||
} catch {
|
||||
return { aboutMe: null, conditions: null, allergies: null, coachFocus: null };
|
||||
return {
|
||||
aboutMe: null,
|
||||
conditions: null,
|
||||
allergies: null,
|
||||
coachFocus: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** Whole years between `dateOfBirth` and `now`; null when unknown. */
|
||||
export function deriveAgeYears(
|
||||
dateOfBirth: Date | null,
|
||||
@@ -142,9 +143,7 @@ export function composeSelfContextText(
|
||||
}
|
||||
}
|
||||
if (facts.length > 0) {
|
||||
lines.push(
|
||||
(de ? "Profil: " : "Profile: ") + facts.join(" · "),
|
||||
);
|
||||
lines.push((de ? "Profil: " : "Profile: ") + facts.join(" · "));
|
||||
}
|
||||
|
||||
if (ctx.conditions) {
|
||||
|
||||
@@ -84,13 +84,13 @@ export function buildSummaryUserPrompt(
|
||||
foldedTurns: SummaryFoldTurn[],
|
||||
locale: "de" | "en" = "en",
|
||||
): string {
|
||||
const priorLabel = locale === "de" ? "FRÜHERE ZUSAMMENFASSUNG" : "PRIOR SUMMARY";
|
||||
const priorLabel =
|
||||
locale === "de" ? "FRÜHERE ZUSAMMENFASSUNG" : "PRIOR SUMMARY";
|
||||
const turnsLabel = locale === "de" ? "NEUE WORTWECHSEL" : "NEW TURNS";
|
||||
const none = locale === "de" ? "(keine)" : "(none)";
|
||||
|
||||
const priorBlock = priorSummary && priorSummary.trim().length > 0
|
||||
? priorSummary.trim()
|
||||
: none;
|
||||
const priorBlock =
|
||||
priorSummary && priorSummary.trim().length > 0 ? priorSummary.trim() : none;
|
||||
|
||||
const turnsBlock = foldedTurns
|
||||
.map((t) => `${t.role}: ${t.content}`)
|
||||
@@ -182,9 +182,7 @@ export async function refreshConversationSummary(
|
||||
// fail-closed like every other decrypt in the Coach stack.
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{ role: m.role === "assistant" ? "assistant" : "user", content },
|
||||
];
|
||||
return [{ role: m.role === "assistant" ? "assistant" : "user", content }];
|
||||
});
|
||||
|
||||
// 5. Run the user's provider chain. Best-effort: non-ok leaves the old
|
||||
|
||||
@@ -21,10 +21,7 @@
|
||||
* day" claim.
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import {
|
||||
predictCycle,
|
||||
type NightlyTempInput,
|
||||
} from "@/lib/cycle";
|
||||
import { predictCycle, type NightlyTempInput } from "@/lib/cycle";
|
||||
import { LUTEAL_DEFAULT, type CyclePhase } from "@/lib/cycle/types";
|
||||
import {
|
||||
phaseForDate,
|
||||
|
||||
@@ -68,11 +68,17 @@ function summariseValue(
|
||||
case "STRESS_SCORE":
|
||||
case "STRAIN_SCORE":
|
||||
return typeof v.score === "number"
|
||||
? { value: v.score, band: typeof v.band === "string" ? v.band : undefined }
|
||||
? {
|
||||
value: v.score,
|
||||
band: typeof v.band === "string" ? v.band : undefined,
|
||||
}
|
||||
: null;
|
||||
case "HRV_BALANCE":
|
||||
return typeof v.recentAvg === "number"
|
||||
? { value: Math.round(v.recentAvg), band: typeof v.band === "string" ? v.band : undefined }
|
||||
? {
|
||||
value: Math.round(v.recentAvg),
|
||||
band: typeof v.band === "string" ? v.band : undefined,
|
||||
}
|
||||
: null;
|
||||
case "FITNESS_AGE":
|
||||
return typeof v.vo2Max === "number"
|
||||
@@ -119,7 +125,10 @@ export async function buildDerivedSnapshotBlock(
|
||||
const computed = await Promise.all(
|
||||
SNAPSHOT_METRICS.map(async (metric) => {
|
||||
try {
|
||||
return { metric, derived: await computeDerivedMetric({ metric, userId, profile, now }) };
|
||||
return {
|
||||
metric,
|
||||
derived: await computeDerivedMetric({ metric, userId, profile, now }),
|
||||
};
|
||||
} catch {
|
||||
return { metric, derived: null };
|
||||
}
|
||||
|
||||
+38
-14
@@ -89,11 +89,7 @@ function extractionSystemPrompt(locale: string | undefined): string {
|
||||
|
||||
const rawFactSchema = z.object({
|
||||
category: z.enum(COACH_FACT_CATEGORIES),
|
||||
fact: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(FACT_MAX_CHARS),
|
||||
fact: z.string().trim().min(1).max(FACT_MAX_CHARS),
|
||||
confidence: z.coerce.number().int().min(0).max(100),
|
||||
});
|
||||
|
||||
@@ -110,7 +106,9 @@ interface ParsedFact {
|
||||
* top-level JSON is unparseable (the caller then annotates `parse_failed`);
|
||||
* individual malformed items are dropped silently, not fatal.
|
||||
*/
|
||||
function parseFacts(content: string): { facts: ParsedFact[]; dropped: number } | null {
|
||||
function parseFacts(
|
||||
content: string,
|
||||
): { facts: ParsedFact[]; dropped: number } | null {
|
||||
let json: unknown;
|
||||
try {
|
||||
json = JSON.parse(content.trim());
|
||||
@@ -129,7 +127,10 @@ function parseFacts(content: string): { facts: ParsedFact[]; dropped: number } |
|
||||
facts.push({
|
||||
category: parsed.data.category,
|
||||
fact: parsed.data.fact,
|
||||
confidence: Math.max(0, Math.min(100, Math.round(parsed.data.confidence))),
|
||||
confidence: Math.max(
|
||||
0,
|
||||
Math.min(100, Math.round(parsed.data.confidence)),
|
||||
),
|
||||
});
|
||||
} else {
|
||||
dropped += 1;
|
||||
@@ -169,7 +170,8 @@ function isNearDuplicate(candidate: string, existing: string[]): boolean {
|
||||
const cNorm = candidate.trim().toLowerCase();
|
||||
for (const ex of existing) {
|
||||
if (ex.trim().toLowerCase() === cNorm) return true;
|
||||
if (tokenOverlap(cTokens, tokenSet(ex)) >= DEDUP_OVERLAP_THRESHOLD) return true;
|
||||
if (tokenOverlap(cTokens, tokenSet(ex)) >= DEDUP_OVERLAP_THRESHOLD)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -197,17 +199,29 @@ interface ActiveFactRow {
|
||||
async function loadActiveFacts(
|
||||
db: PrismaLike,
|
||||
userId: string,
|
||||
): Promise<Array<{ id: string; text: string; category: string; confidence: number }>> {
|
||||
): Promise<
|
||||
Array<{ id: string; text: string; category: string; confidence: number }>
|
||||
> {
|
||||
const rows = (await db.coachFact.findMany({
|
||||
where: { userId, deletedAt: null },
|
||||
select: { id: true, factEncrypted: true, category: true, confidence: true },
|
||||
})) as ActiveFactRow[];
|
||||
|
||||
const out: Array<{ id: string; text: string; category: string; confidence: number }> = [];
|
||||
const out: Array<{
|
||||
id: string;
|
||||
text: string;
|
||||
category: string;
|
||||
confidence: number;
|
||||
}> = [];
|
||||
for (const r of rows) {
|
||||
const text = decryptOrNull(r.factEncrypted);
|
||||
if (text === null) continue;
|
||||
out.push({ id: r.id, text, category: r.category, confidence: r.confidence });
|
||||
out.push({
|
||||
id: r.id,
|
||||
text,
|
||||
category: r.category,
|
||||
confidence: r.confidence,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -341,7 +355,9 @@ export async function extractAndStoreFacts(
|
||||
|
||||
const toStore: ParsedFact[] = [];
|
||||
// Highest-confidence candidates first so a tight cap admits the best.
|
||||
for (const cand of [...accepted].sort((a, b) => b.confidence - a.confidence)) {
|
||||
for (const cand of [...accepted].sort(
|
||||
(a, b) => b.confidence - a.confidence,
|
||||
)) {
|
||||
if (remainingCapacity > 0) {
|
||||
toStore.push(cand);
|
||||
remainingCapacity -= 1;
|
||||
@@ -529,7 +545,10 @@ const DETERMINISTIC_PATTERNS: DeterministicPattern[] = [
|
||||
];
|
||||
|
||||
function cleanCapture(raw: string): string | null {
|
||||
const cleaned = raw.replace(/\s+/g, " ").replace(/[.,;:!?]+$/u, "").trim();
|
||||
const cleaned = raw
|
||||
.replace(/\s+/g, " ")
|
||||
.replace(/[.,;:!?]+$/u, "")
|
||||
.trim();
|
||||
if (cleaned.length < 2 || cleaned.length > 60) return null;
|
||||
return cleaned;
|
||||
}
|
||||
@@ -653,7 +672,12 @@ export async function buildCoachFactsBlock(
|
||||
const rows = (await db.coachFact.findMany({
|
||||
where: { userId, deletedAt: null },
|
||||
orderBy: [{ confidence: "desc" }, { updatedAt: "desc" }],
|
||||
select: { factEncrypted: true, category: true, confidence: true, updatedAt: true },
|
||||
select: {
|
||||
factEncrypted: true,
|
||||
category: true,
|
||||
confidence: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
})) as RankFactRow[];
|
||||
|
||||
const facts: Array<{ category: string; text: string }> = [];
|
||||
|
||||
@@ -70,7 +70,6 @@ function deriveDrugNames(raw: string): { display: string; generic: string } {
|
||||
return { display, generic };
|
||||
}
|
||||
|
||||
|
||||
function parseDaysOfWeek(raw: string | null): number[] {
|
||||
if (!raw) return [];
|
||||
return raw
|
||||
@@ -437,4 +436,3 @@ export async function buildGlp1SnapshotBlock(
|
||||
medications,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -72,7 +72,12 @@ export async function buildIllnessSnapshotBlock(
|
||||
|
||||
const [activeRows, resolvedRows] = await Promise.all([
|
||||
prisma.illnessEpisode.findMany({
|
||||
where: { userId, deletedAt: null, resolvedAt: null, onsetAt: { lte: now } },
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
resolvedAt: null,
|
||||
onsetAt: { lte: now },
|
||||
},
|
||||
orderBy: { onsetAt: "asc" },
|
||||
select: { label: true, type: true, lifecycle: true, onsetAt: true },
|
||||
}),
|
||||
|
||||
@@ -78,10 +78,7 @@ export const medicationExtractionSchema = z
|
||||
intervalMonths: z.number().int().min(1).max(12).optional(),
|
||||
dayOfMonth: z.number().int().min(1).max(31).optional(),
|
||||
rollingIntervalDays: z.number().int().min(1).max(365).optional(),
|
||||
timesOfDay: z
|
||||
.array(z.string().regex(HH_MM_RE, "HH:MM"))
|
||||
.max(12)
|
||||
.optional(),
|
||||
timesOfDay: z.array(z.string().regex(HH_MM_RE, "HH:MM")).max(12).optional(),
|
||||
startsOn: z.string().regex(ISO_DATE_RE, "YYYY-MM-DD").optional(),
|
||||
endsOn: z.string().regex(ISO_DATE_RE, "YYYY-MM-DD").optional(),
|
||||
oneShot: z.boolean().optional(),
|
||||
@@ -120,7 +117,7 @@ export function buildMedicationExtractionSystemPrompt(): string {
|
||||
"Every field is optional — omit a field rather than guess. Keys:",
|
||||
"",
|
||||
" name — medication brand or active substance, verbatim",
|
||||
" dose — numeric portion only, as a string: \"5\", \"7.5\"",
|
||||
' dose — numeric portion only, as a string: "5", "7.5"',
|
||||
" doseUnit — one of: mg | ml | iu | tablets | drops | puffs | sprays",
|
||||
" cadenceKind — one of: daily | weekdays | everyNWeeks |",
|
||||
" monthly | everyNMonths | yearly | rolling |",
|
||||
@@ -130,9 +127,9 @@ export function buildMedicationExtractionSystemPrompt(): string {
|
||||
" intervalWeeks — 1..52, used with everyNWeeks",
|
||||
" intervalMonths — 1..12, used with everyNMonths",
|
||||
" dayOfMonth — 1..31, used with monthly / everyNMonths",
|
||||
" rollingIntervalDays — 1..365, used with rolling (\"every N days",
|
||||
" from the last intake\")",
|
||||
" timesOfDay — array of \"HH:MM\" wall-clock strings (24h)",
|
||||
' rollingIntervalDays — 1..365, used with rolling ("every N days',
|
||||
' from the last intake")',
|
||||
' timesOfDay — array of "HH:MM" wall-clock strings (24h)',
|
||||
" startsOn — ISO YYYY-MM-DD, course start date",
|
||||
" endsOn — ISO YYYY-MM-DD, course end date",
|
||||
" oneShot — true when the user describes a single-time",
|
||||
@@ -147,26 +144,26 @@ export function buildMedicationExtractionSystemPrompt(): string {
|
||||
" not state a numeric dose, omit `dose` and `doseUnit`.",
|
||||
"",
|
||||
" 2. Map vague time-of-day words to canonical 24h slots:",
|
||||
" morning → \"08:00\", noon / midday → \"12:00\",",
|
||||
" afternoon → \"14:00\", evening → \"18:00\", night → \"22:00\".",
|
||||
' morning → "08:00", noon / midday → "12:00",',
|
||||
' afternoon → "14:00", evening → "18:00", night → "22:00".',
|
||||
" Multiple times in one description → emit each as its own entry.",
|
||||
"",
|
||||
" 3. \"Every day\" / \"daily\" / \"once a day\" → `cadenceKind:",
|
||||
" \"daily\"`. \"Twice a day\" / \"3 times a day\" → still",
|
||||
' 3. "Every day" / "daily" / "once a day" → `cadenceKind:',
|
||||
' "daily"`. "Twice a day" / "3 times a day" → still',
|
||||
" `daily` with the right `timesOfDay[]` count; never invent a",
|
||||
" weekly cadence.",
|
||||
"",
|
||||
" 4. \"Every N days from my last injection / dose\" /",
|
||||
" \"7 days after the previous one\" → `rolling` with",
|
||||
' 4. "Every N days from my last injection / dose" /',
|
||||
' "7 days after the previous one" → `rolling` with',
|
||||
" `rollingIntervalDays = N`. This is distinct from",
|
||||
" `everyNWeeks` (calendar-anchored).",
|
||||
"",
|
||||
" 5. Single-shot wording (\"single flu shot\", \"one-off dose\",",
|
||||
" \"on October 15 only\") → `oneShot: true` and a `startsOn`",
|
||||
' 5. Single-shot wording ("single flu shot", "one-off dose",',
|
||||
' "on October 15 only") → `oneShot: true` and a `startsOn`',
|
||||
" date. Do not also emit `cadenceKind`.",
|
||||
"",
|
||||
" 6. Resolve relative dates against today's date supplied in the",
|
||||
" CONTEXT block. \"Next Monday\", \"tomorrow\", \"in 2 weeks\"",
|
||||
' CONTEXT block. "Next Monday", "tomorrow", "in 2 weeks"',
|
||||
" become absolute ISO dates.",
|
||||
"",
|
||||
" 7. If a field is ambiguous, leave it empty. The wizard prefers",
|
||||
@@ -206,9 +203,10 @@ export function buildMedicationExtractionUserPrompt(
|
||||
* payload without having to glue the two helpers together at every call
|
||||
* site.
|
||||
*/
|
||||
export function buildMedicationExtractionPrompt(
|
||||
args: BuildUserPromptArgs,
|
||||
): { systemPrompt: string; userPrompt: string } {
|
||||
export function buildMedicationExtractionPrompt(args: BuildUserPromptArgs): {
|
||||
systemPrompt: string;
|
||||
userPrompt: string;
|
||||
} {
|
||||
return {
|
||||
systemPrompt: buildMedicationExtractionSystemPrompt(),
|
||||
userPrompt: buildMedicationExtractionUserPrompt(args),
|
||||
|
||||
@@ -166,11 +166,7 @@ export async function buildCoachMemoryBlock(
|
||||
facts = undefined;
|
||||
}
|
||||
|
||||
if (
|
||||
!priorNarrative &&
|
||||
Object.keys(trendMemory).length === 0 &&
|
||||
!facts
|
||||
) {
|
||||
if (!priorNarrative && Object.keys(trendMemory).length === 0 && !facts) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -360,4 +360,3 @@ export async function deleteConversation(
|
||||
await prisma.coachConversation.delete({ where: { id: row.id } });
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -249,8 +249,8 @@ export function buildReferenceGroundingBlock(
|
||||
"These are published POPULATION reference bands for context only — they",
|
||||
"are not personal medical advice, not a diagnosis, and not a target set",
|
||||
"for this user. The user's own baseline always leads the read. Cite a",
|
||||
"band only to orient a reply (\"the general reference range is …\"); never",
|
||||
"tell the user they \"have\" or \"don't have\" a condition from a band.",
|
||||
'band only to orient a reply ("the general reference range is …"); never',
|
||||
'tell the user they "have" or "don\'t have" a condition from a band.',
|
||||
"Blood pressure follows the European ESH 2023 line; US (ACC/AHA) and",
|
||||
"ESC framings differ and are context, not the call. This block does not",
|
||||
"change any safety rule above — keep deferring dose / diagnosis / drug-",
|
||||
|
||||
@@ -21,10 +21,7 @@
|
||||
*
|
||||
* Server-only — reads `@/lib/db` through the provider resolver.
|
||||
*/
|
||||
import {
|
||||
hasAnyConfiguredProvider,
|
||||
resolveProvider,
|
||||
} from "@/lib/ai/provider";
|
||||
import { hasAnyConfiguredProvider, resolveProvider } from "@/lib/ai/provider";
|
||||
import {
|
||||
buildDateKey,
|
||||
getDailyTokenSpend,
|
||||
|
||||
+220
-53
@@ -201,13 +201,14 @@ const CORE_CLUSTERS: ReadonlySet<CoachDataCluster> = new Set<CoachDataCluster>([
|
||||
* a data domain. `labs` / `achievements` / `insights` / `doctorReport`
|
||||
* own no coach-snapshot data domain.
|
||||
*/
|
||||
const MODULE_EXCLUDED_SOURCES: Partial<Record<ModuleKey, CoachScopeSource[]>> = {
|
||||
mood: ["mood"],
|
||||
sleep: ["sleep"],
|
||||
glucose: ["glucose"],
|
||||
workouts: ["workouts"],
|
||||
recovery: ["hrv", "resting_hr", "vo2_max"],
|
||||
};
|
||||
const MODULE_EXCLUDED_SOURCES: Partial<Record<ModuleKey, CoachScopeSource[]>> =
|
||||
{
|
||||
mood: ["mood"],
|
||||
sleep: ["sleep"],
|
||||
glucose: ["glucose"],
|
||||
workouts: ["workouts"],
|
||||
recovery: ["hrv", "resting_hr", "vo2_max"],
|
||||
};
|
||||
|
||||
const WEEKDAY_KEYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const;
|
||||
|
||||
@@ -420,12 +421,18 @@ async function buildCoarseTimelineTail(
|
||||
return undefined;
|
||||
}
|
||||
const monthly = series.monthBand.map(
|
||||
(b) => [b.bucketStart, b.mean, b.min, b.max] as [string, number, number, number],
|
||||
(b) =>
|
||||
[b.bucketStart, b.mean, b.min, b.max] as [string, number, number, number],
|
||||
);
|
||||
const yearly = series.yearBand.map(
|
||||
(b) => [b.bucketStart, b.mean, b.min, b.max] as [string, number, number, number],
|
||||
(b) =>
|
||||
[b.bucketStart, b.mean, b.min, b.max] as [string, number, number, number],
|
||||
);
|
||||
if (monthly.length === 0 && yearly.length === 0 && series.anomalies.length === 0) {
|
||||
if (
|
||||
monthly.length === 0 &&
|
||||
yearly.length === 0 &&
|
||||
series.anomalies.length === 0
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
@@ -523,7 +530,10 @@ const snapshotCache = new Map<
|
||||
{ expiresAt: number; result: CoachSnapshotResult }
|
||||
>();
|
||||
|
||||
function snapshotCacheKey(userId: string, scope: CoachScope | undefined): string {
|
||||
function snapshotCacheKey(
|
||||
userId: string,
|
||||
scope: CoachScope | undefined,
|
||||
): string {
|
||||
// v1.7.0 — when the request pins an explicit source list, key on it.
|
||||
// Otherwise the source set is derived from the user's saved
|
||||
// `dataClusters`, which we don't read here (the cache must stay
|
||||
@@ -1523,42 +1533,202 @@ async function buildCoachSnapshotImpl(
|
||||
// so accounts without that data never see a void section.
|
||||
const valueBlocks: ValueBlock[] = [
|
||||
// ── cardio ──
|
||||
{ metric: "hrv", source: "hrv", snapshotKey: "heartRateVariability", type: "HEART_RATE_VARIABILITY" },
|
||||
{ metric: "resting_hr", source: "resting_hr", snapshotKey: "restingHeartRate", type: "RESTING_HEART_RATE" },
|
||||
{ metric: "walking_hr", source: "walking_hr", snapshotKey: "walkingHeartRateAverage", type: "WALKING_HEART_RATE_AVERAGE" },
|
||||
{ metric: "respiratory_rate", source: "respiratory_rate", snapshotKey: "respiratoryRate", type: "RESPIRATORY_RATE" },
|
||||
{ metric: "spo2", source: "spo2", snapshotKey: "oxygenSaturation", type: "OXYGEN_SATURATION" },
|
||||
{ metric: "pulse_wave_velocity", source: "pulse_wave_velocity", snapshotKey: "pulseWaveVelocity", type: "PULSE_WAVE_VELOCITY" },
|
||||
{ metric: "vascular_age", source: "vascular_age", snapshotKey: "vascularAge", type: "VASCULAR_AGE" },
|
||||
{
|
||||
metric: "hrv",
|
||||
source: "hrv",
|
||||
snapshotKey: "heartRateVariability",
|
||||
type: "HEART_RATE_VARIABILITY",
|
||||
},
|
||||
{
|
||||
metric: "resting_hr",
|
||||
source: "resting_hr",
|
||||
snapshotKey: "restingHeartRate",
|
||||
type: "RESTING_HEART_RATE",
|
||||
},
|
||||
{
|
||||
metric: "walking_hr",
|
||||
source: "walking_hr",
|
||||
snapshotKey: "walkingHeartRateAverage",
|
||||
type: "WALKING_HEART_RATE_AVERAGE",
|
||||
},
|
||||
{
|
||||
metric: "respiratory_rate",
|
||||
source: "respiratory_rate",
|
||||
snapshotKey: "respiratoryRate",
|
||||
type: "RESPIRATORY_RATE",
|
||||
},
|
||||
{
|
||||
metric: "spo2",
|
||||
source: "spo2",
|
||||
snapshotKey: "oxygenSaturation",
|
||||
type: "OXYGEN_SATURATION",
|
||||
},
|
||||
{
|
||||
metric: "pulse_wave_velocity",
|
||||
source: "pulse_wave_velocity",
|
||||
snapshotKey: "pulseWaveVelocity",
|
||||
type: "PULSE_WAVE_VELOCITY",
|
||||
},
|
||||
{
|
||||
metric: "vascular_age",
|
||||
source: "vascular_age",
|
||||
snapshotKey: "vascularAge",
|
||||
type: "VASCULAR_AGE",
|
||||
},
|
||||
// ── body composition ──
|
||||
{ metric: "body_fat", source: "body_fat", snapshotKey: "bodyFat", type: "BODY_FAT" },
|
||||
{ metric: "fat_mass", source: "fat_mass", snapshotKey: "fatMass", type: "FAT_MASS" },
|
||||
{ metric: "fat_free_mass", source: "fat_free_mass", snapshotKey: "fatFreeMass", type: "FAT_FREE_MASS" },
|
||||
{ metric: "muscle_mass", source: "muscle_mass", snapshotKey: "muscleMass", type: "MUSCLE_MASS" },
|
||||
{ metric: "lean_body_mass", source: "lean_body_mass", snapshotKey: "leanBodyMass", type: "LEAN_BODY_MASS" },
|
||||
{ metric: "bone_mass", source: "bone_mass", snapshotKey: "boneMass", type: "BONE_MASS" },
|
||||
{ metric: "total_body_water", source: "total_body_water", snapshotKey: "totalBodyWater", type: "TOTAL_BODY_WATER" },
|
||||
{ metric: "bmi", source: "bmi", snapshotKey: "bodyMassIndex", type: "BODY_MASS_INDEX" },
|
||||
{ metric: "visceral_fat", source: "visceral_fat", snapshotKey: "visceralFat", type: "VISCERAL_FAT" },
|
||||
{
|
||||
metric: "body_fat",
|
||||
source: "body_fat",
|
||||
snapshotKey: "bodyFat",
|
||||
type: "BODY_FAT",
|
||||
},
|
||||
{
|
||||
metric: "fat_mass",
|
||||
source: "fat_mass",
|
||||
snapshotKey: "fatMass",
|
||||
type: "FAT_MASS",
|
||||
},
|
||||
{
|
||||
metric: "fat_free_mass",
|
||||
source: "fat_free_mass",
|
||||
snapshotKey: "fatFreeMass",
|
||||
type: "FAT_FREE_MASS",
|
||||
},
|
||||
{
|
||||
metric: "muscle_mass",
|
||||
source: "muscle_mass",
|
||||
snapshotKey: "muscleMass",
|
||||
type: "MUSCLE_MASS",
|
||||
},
|
||||
{
|
||||
metric: "lean_body_mass",
|
||||
source: "lean_body_mass",
|
||||
snapshotKey: "leanBodyMass",
|
||||
type: "LEAN_BODY_MASS",
|
||||
},
|
||||
{
|
||||
metric: "bone_mass",
|
||||
source: "bone_mass",
|
||||
snapshotKey: "boneMass",
|
||||
type: "BONE_MASS",
|
||||
},
|
||||
{
|
||||
metric: "total_body_water",
|
||||
source: "total_body_water",
|
||||
snapshotKey: "totalBodyWater",
|
||||
type: "TOTAL_BODY_WATER",
|
||||
},
|
||||
{
|
||||
metric: "bmi",
|
||||
source: "bmi",
|
||||
snapshotKey: "bodyMassIndex",
|
||||
type: "BODY_MASS_INDEX",
|
||||
},
|
||||
{
|
||||
metric: "visceral_fat",
|
||||
source: "visceral_fat",
|
||||
snapshotKey: "visceralFat",
|
||||
type: "VISCERAL_FAT",
|
||||
},
|
||||
// ── activity ──
|
||||
{ metric: "steps", source: "steps", snapshotKey: "steps", type: "ACTIVITY_STEPS" },
|
||||
{ metric: "active_energy", source: "active_energy", snapshotKey: "activeEnergy", type: "ACTIVE_ENERGY_BURNED" },
|
||||
{ metric: "flights", source: "flights", snapshotKey: "flightsClimbed", type: "FLIGHTS_CLIMBED" },
|
||||
{ metric: "distance", source: "distance", snapshotKey: "walkingRunningDistance", type: "WALKING_RUNNING_DISTANCE" },
|
||||
{ metric: "vo2_max", source: "vo2_max", snapshotKey: "vo2Max", type: "VO2_MAX" },
|
||||
{
|
||||
metric: "steps",
|
||||
source: "steps",
|
||||
snapshotKey: "steps",
|
||||
type: "ACTIVITY_STEPS",
|
||||
},
|
||||
{
|
||||
metric: "active_energy",
|
||||
source: "active_energy",
|
||||
snapshotKey: "activeEnergy",
|
||||
type: "ACTIVE_ENERGY_BURNED",
|
||||
},
|
||||
{
|
||||
metric: "flights",
|
||||
source: "flights",
|
||||
snapshotKey: "flightsClimbed",
|
||||
type: "FLIGHTS_CLIMBED",
|
||||
},
|
||||
{
|
||||
metric: "distance",
|
||||
source: "distance",
|
||||
snapshotKey: "walkingRunningDistance",
|
||||
type: "WALKING_RUNNING_DISTANCE",
|
||||
},
|
||||
{
|
||||
metric: "vo2_max",
|
||||
source: "vo2_max",
|
||||
snapshotKey: "vo2Max",
|
||||
type: "VO2_MAX",
|
||||
},
|
||||
// ── mobility & gait ──
|
||||
{ metric: "walking_steadiness", source: "walking_steadiness", snapshotKey: "walkingSteadiness", type: "WALKING_STEADINESS" },
|
||||
{ metric: "walking_asymmetry", source: "walking_asymmetry", snapshotKey: "walkingAsymmetry", type: "WALKING_ASYMMETRY" },
|
||||
{ metric: "walking_double_support", source: "walking_double_support", snapshotKey: "walkingDoubleSupport", type: "WALKING_DOUBLE_SUPPORT" },
|
||||
{ metric: "walking_step_length", source: "walking_step_length", snapshotKey: "walkingStepLength", type: "WALKING_STEP_LENGTH" },
|
||||
{ metric: "walking_speed", source: "walking_speed", snapshotKey: "walkingSpeed", type: "WALKING_SPEED" },
|
||||
{
|
||||
metric: "walking_steadiness",
|
||||
source: "walking_steadiness",
|
||||
snapshotKey: "walkingSteadiness",
|
||||
type: "WALKING_STEADINESS",
|
||||
},
|
||||
{
|
||||
metric: "walking_asymmetry",
|
||||
source: "walking_asymmetry",
|
||||
snapshotKey: "walkingAsymmetry",
|
||||
type: "WALKING_ASYMMETRY",
|
||||
},
|
||||
{
|
||||
metric: "walking_double_support",
|
||||
source: "walking_double_support",
|
||||
snapshotKey: "walkingDoubleSupport",
|
||||
type: "WALKING_DOUBLE_SUPPORT",
|
||||
},
|
||||
{
|
||||
metric: "walking_step_length",
|
||||
source: "walking_step_length",
|
||||
snapshotKey: "walkingStepLength",
|
||||
type: "WALKING_STEP_LENGTH",
|
||||
},
|
||||
{
|
||||
metric: "walking_speed",
|
||||
source: "walking_speed",
|
||||
snapshotKey: "walkingSpeed",
|
||||
type: "WALKING_SPEED",
|
||||
},
|
||||
// ── environment / exposure ──
|
||||
{ metric: "audio_env", source: "audio_env", snapshotKey: "audioExposureEnvironment", type: "AUDIO_EXPOSURE_ENV" },
|
||||
{ metric: "audio_headphone", source: "audio_headphone", snapshotKey: "audioExposureHeadphone", type: "AUDIO_EXPOSURE_HEADPHONE" },
|
||||
{ metric: "audio_event", source: "audio_event", snapshotKey: "audioExposureEvent", type: "AUDIO_EXPOSURE_EVENT" },
|
||||
{ metric: "daylight", source: "daylight", snapshotKey: "timeInDaylight", type: "TIME_IN_DAYLIGHT" },
|
||||
{ metric: "skin_temp", source: "skin_temp", snapshotKey: "skinTemperature", type: "SKIN_TEMPERATURE" },
|
||||
{ metric: "body_temp", source: "body_temp", snapshotKey: "bodyTemperature", type: "BODY_TEMPERATURE" },
|
||||
{
|
||||
metric: "audio_env",
|
||||
source: "audio_env",
|
||||
snapshotKey: "audioExposureEnvironment",
|
||||
type: "AUDIO_EXPOSURE_ENV",
|
||||
},
|
||||
{
|
||||
metric: "audio_headphone",
|
||||
source: "audio_headphone",
|
||||
snapshotKey: "audioExposureHeadphone",
|
||||
type: "AUDIO_EXPOSURE_HEADPHONE",
|
||||
},
|
||||
{
|
||||
metric: "audio_event",
|
||||
source: "audio_event",
|
||||
snapshotKey: "audioExposureEvent",
|
||||
type: "AUDIO_EXPOSURE_EVENT",
|
||||
},
|
||||
{
|
||||
metric: "daylight",
|
||||
source: "daylight",
|
||||
snapshotKey: "timeInDaylight",
|
||||
type: "TIME_IN_DAYLIGHT",
|
||||
},
|
||||
{
|
||||
metric: "skin_temp",
|
||||
source: "skin_temp",
|
||||
snapshotKey: "skinTemperature",
|
||||
type: "SKIN_TEMPERATURE",
|
||||
},
|
||||
{
|
||||
metric: "body_temp",
|
||||
source: "body_temp",
|
||||
snapshotKey: "bodyTemperature",
|
||||
type: "BODY_TEMPERATURE",
|
||||
},
|
||||
];
|
||||
for (const block of valueBlocks) {
|
||||
if (!sources.has(block.source)) continue;
|
||||
@@ -1765,10 +1935,11 @@ async function buildCoachSnapshotImpl(
|
||||
// then convert each resulting figure ONCE (parity with the series
|
||||
// DTO + detail page + FHIR). mg/dL users stay byte-identical because
|
||||
// the conversion is skipped entirely.
|
||||
const recent = buildDailyValueRows(rows, recentCutoff, userTz).map((d) =>
|
||||
glucoseUnit === "mmol/L"
|
||||
? { ...d, value: convertGlucose(d.value, glucoseUnit) }
|
||||
: d,
|
||||
const recent = buildDailyValueRows(rows, recentCutoff, userTz).map(
|
||||
(d) =>
|
||||
glucoseUnit === "mmol/L"
|
||||
? { ...d, value: convertGlucose(d.value, glucoseUnit) }
|
||||
: d,
|
||||
);
|
||||
const weekly = bucketWeekly(
|
||||
rows.filter((r) => r.measuredAt < recentCutoff),
|
||||
@@ -1960,9 +2131,7 @@ async function buildCoachSnapshotImpl(
|
||||
const ctx = features.context;
|
||||
if (
|
||||
ctx &&
|
||||
(ctx.heightCm !== null ||
|
||||
ctx.ageYears !== null ||
|
||||
ctx.gender !== null)
|
||||
(ctx.heightCm !== null || ctx.ageYears !== null || ctx.gender !== null)
|
||||
) {
|
||||
snapshot.anthropometrics = {
|
||||
heightCm: ctx.heightCm,
|
||||
@@ -2293,9 +2462,7 @@ function degradeToBudget(
|
||||
}
|
||||
|
||||
if (degraded.length > 0) {
|
||||
const droppedClusters = Array.from(
|
||||
new Set(degraded.map((d) => d.cluster)),
|
||||
);
|
||||
const droppedClusters = Array.from(new Set(degraded.map((d) => d.cluster)));
|
||||
annotate({
|
||||
action: { name: "coach.snapshot.truncated" },
|
||||
meta: {
|
||||
|
||||
@@ -171,8 +171,7 @@ export function parseSuggestReminder(raw: string): SuggestReminderParseResult {
|
||||
const closeRel = afterOpen.indexOf(CLOSE_SENTINEL);
|
||||
// Cap the payload before parsing regardless of whether the close marker
|
||||
// is present (a missing close marker treats the rest as the body).
|
||||
const bodyRaw =
|
||||
closeRel === -1 ? afterOpen : afterOpen.slice(0, closeRel);
|
||||
const bodyRaw = closeRel === -1 ? afterOpen : afterOpen.slice(0, closeRel);
|
||||
const body =
|
||||
bodyRaw.length > SENTINEL_BYTE_CAP
|
||||
? bodyRaw.slice(0, SENTINEL_BYTE_CAP)
|
||||
@@ -183,9 +182,7 @@ export function parseSuggestReminder(raw: string): SuggestReminderParseResult {
|
||||
// it. Only the sentinel block itself is stripped; when the close marker is
|
||||
// missing there is no trailing text to recover.
|
||||
const after =
|
||||
closeRel === -1
|
||||
? ""
|
||||
: afterOpen.slice(closeRel + CLOSE_SENTINEL.length);
|
||||
closeRel === -1 ? "" : afterOpen.slice(closeRel + CLOSE_SENTINEL.length);
|
||||
const prose = `${before}${after}`.replace(/^\s+|\s+$/gu, "");
|
||||
|
||||
const cadenceId = extractCadenceId(body);
|
||||
|
||||
@@ -101,7 +101,10 @@ export async function buildTrajectorySnapshotBlock(
|
||||
continue;
|
||||
}
|
||||
if (!isDerivedOk(derived)) continue; // omit insufficient — no projection noise
|
||||
const summary = summariseTrajectory(derived.value, derived.confidence.score);
|
||||
const summary = summariseTrajectory(
|
||||
derived.value,
|
||||
derived.confidence.score,
|
||||
);
|
||||
if (!summary) continue;
|
||||
block[type] = summary;
|
||||
}
|
||||
|
||||
+44
-40
@@ -291,47 +291,51 @@ export class CodexClient implements AIProvider {
|
||||
): Promise<Response> {
|
||||
const sessionId = randomUUID();
|
||||
const threadId = randomUUID();
|
||||
return safeFetch(CODEX_ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "text/event-stream",
|
||||
Authorization: `Bearer ${this.accessToken}`,
|
||||
"ChatGPT-Account-ID": this.accountId,
|
||||
originator: ORIGINATOR,
|
||||
"User-Agent": USER_AGENT,
|
||||
session_id: sessionId,
|
||||
"session-id": sessionId,
|
||||
thread_id: threadId,
|
||||
"thread-id": threadId,
|
||||
return safeFetch(
|
||||
CODEX_ENDPOINT,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "text/event-stream",
|
||||
Authorization: `Bearer ${this.accessToken}`,
|
||||
"ChatGPT-Account-ID": this.accountId,
|
||||
originator: ORIGINATOR,
|
||||
"User-Agent": USER_AGENT,
|
||||
session_id: sessionId,
|
||||
"session-id": sessionId,
|
||||
thread_id: threadId,
|
||||
"thread-id": threadId,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: slug,
|
||||
instructions: params.systemPrompt,
|
||||
input: [
|
||||
{
|
||||
type: "message",
|
||||
role: "user",
|
||||
content: [{ type: "input_text", text: params.userPrompt }],
|
||||
},
|
||||
],
|
||||
tools: [],
|
||||
tool_choice: "auto",
|
||||
parallel_tool_calls: false,
|
||||
// Reasoning is required-but-nullable on the wire. We don't ask
|
||||
// for reasoning summaries — emit `null` so the JSON has the
|
||||
// field present and the server stops complaining about a
|
||||
// missing key (it returned 400 in earlier iterations).
|
||||
reasoning: null,
|
||||
store: false,
|
||||
stream: true,
|
||||
// Required field; empty array when not asking for reasoning.
|
||||
include: [],
|
||||
}),
|
||||
// SSE streaming completion — match the 60 s budget the other AI
|
||||
// clients use so a long generation is not clipped by the 15 s
|
||||
// default while still bounding a tar-pit upstream.
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: slug,
|
||||
instructions: params.systemPrompt,
|
||||
input: [
|
||||
{
|
||||
type: "message",
|
||||
role: "user",
|
||||
content: [{ type: "input_text", text: params.userPrompt }],
|
||||
},
|
||||
],
|
||||
tools: [],
|
||||
tool_choice: "auto",
|
||||
parallel_tool_calls: false,
|
||||
// Reasoning is required-but-nullable on the wire. We don't ask
|
||||
// for reasoning summaries — emit `null` so the JSON has the
|
||||
// field present and the server stops complaining about a
|
||||
// missing key (it returned 400 in earlier iterations).
|
||||
reasoning: null,
|
||||
store: false,
|
||||
stream: true,
|
||||
// Required field; empty array when not asking for reasoning.
|
||||
include: [],
|
||||
}),
|
||||
// SSE streaming completion — match the 60 s budget the other AI
|
||||
// clients use so a long generation is not clipped by the 15 s
|
||||
// default while still bounding a tar-pit upstream.
|
||||
}, { timeoutMs: 60_000 });
|
||||
{ timeoutMs: 60_000 },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -106,10 +106,7 @@ export interface CoachFeedbackAttribution extends FeedbackAttribution {
|
||||
metricSourceType: string;
|
||||
}
|
||||
|
||||
function buildCoachMetricSourceType(
|
||||
tone: string,
|
||||
verbosity: string,
|
||||
): string {
|
||||
function buildCoachMetricSourceType(tone: string, verbosity: string): string {
|
||||
return `coach:tone=${tone}:verbosity=${verbosity}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -72,25 +72,28 @@ describe("getCoachSystemPrompt — native AI-initial locales", () => {
|
||||
expect(prompt).toMatch(/BLOK DOWODÓW/);
|
||||
});
|
||||
|
||||
it.each(NATIVE_LOCALES)("%s carries every GROUND RULE body verbatim", (locale) => {
|
||||
const matrix = loadSafetyContracts(locale);
|
||||
const prompt = getCoachSystemPrompt(locale);
|
||||
for (const key of Object.keys(matrix.ground_rules) as Array<
|
||||
keyof typeof matrix.ground_rules
|
||||
>) {
|
||||
const rule = matrix.ground_rules[key];
|
||||
// Coach uses surface = "coach" or "both" rules.
|
||||
if (rule.surface === "insights") continue;
|
||||
const body = rule.locale ?? rule.en;
|
||||
expect(body).toBeDefined();
|
||||
// Match on a representative substring (first 80 chars of body).
|
||||
const sample = body!.trim().slice(0, 80);
|
||||
expect(
|
||||
prompt,
|
||||
`coach prompt for ${locale} dropped ${key} (looking for "${sample}")`,
|
||||
).toContain(sample);
|
||||
}
|
||||
});
|
||||
it.each(NATIVE_LOCALES)(
|
||||
"%s carries every GROUND RULE body verbatim",
|
||||
(locale) => {
|
||||
const matrix = loadSafetyContracts(locale);
|
||||
const prompt = getCoachSystemPrompt(locale);
|
||||
for (const key of Object.keys(matrix.ground_rules) as Array<
|
||||
keyof typeof matrix.ground_rules
|
||||
>) {
|
||||
const rule = matrix.ground_rules[key];
|
||||
// Coach uses surface = "coach" or "both" rules.
|
||||
if (rule.surface === "insights") continue;
|
||||
const body = rule.locale ?? rule.en;
|
||||
expect(body).toBeDefined();
|
||||
// Match on a representative substring (first 80 chars of body).
|
||||
const sample = body!.trim().slice(0, 80);
|
||||
expect(
|
||||
prompt,
|
||||
`coach prompt for ${locale} dropped ${key} (looking for "${sample}")`,
|
||||
).toContain(sample);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(NATIVE_LOCALES)(
|
||||
"%s preserves the ---KEYVALUES--- / ---END--- sentinels",
|
||||
|
||||
@@ -52,38 +52,10 @@ const DRUG_LEVEL_RULE_KEY = "ground_rule_15_drug_level_refusal" as const;
|
||||
const DRUG_LEVEL_CONCEPT_TOKENS: Record<Locale, readonly string[]> = {
|
||||
en: ["level", "concentration", "peak", "trough", "Cmax", "therapeutic"],
|
||||
de: ["Spiegel", "Konzentration", "Peak", "Trough", "Cmax", "therapeutisch"],
|
||||
fr: [
|
||||
"niveau",
|
||||
"concentration",
|
||||
"pic",
|
||||
"creux",
|
||||
"Cmax",
|
||||
"thérapeutique",
|
||||
],
|
||||
es: [
|
||||
"nivel",
|
||||
"concentración",
|
||||
"pico",
|
||||
"valle",
|
||||
"Cmax",
|
||||
"terapéutica",
|
||||
],
|
||||
it: [
|
||||
"livello",
|
||||
"concentrazione",
|
||||
"picco",
|
||||
"valle",
|
||||
"Cmax",
|
||||
"terapeutica",
|
||||
],
|
||||
pl: [
|
||||
"poziom",
|
||||
"stężeni",
|
||||
"szczyt",
|
||||
"minimum",
|
||||
"Cmax",
|
||||
"terapeutyczn",
|
||||
],
|
||||
fr: ["niveau", "concentration", "pic", "creux", "Cmax", "thérapeutique"],
|
||||
es: ["nivel", "concentración", "pico", "valle", "Cmax", "terapéutica"],
|
||||
it: ["livello", "concentrazione", "picco", "valle", "Cmax", "terapeutica"],
|
||||
pl: ["poziom", "stężeni", "szczyt", "minimum", "Cmax", "terapeutyczn"],
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -196,9 +168,10 @@ describe("drug-level refusal — adversarial trigger probes survive assembly", (
|
||||
// this locale. Today the prompt is static per locale, so this
|
||||
// is structurally equivalent across probes; the loop pins the
|
||||
// invariant against future per-turn prompt mutation.
|
||||
const matched = matrix.drug_level_refusal.expected_refusal_keywords.some(
|
||||
(keyword) => prompt.includes(keyword),
|
||||
);
|
||||
const matched =
|
||||
matrix.drug_level_refusal.expected_refusal_keywords.some((keyword) =>
|
||||
prompt.includes(keyword),
|
||||
);
|
||||
expect(
|
||||
matched,
|
||||
`${locale} probe="${probe.slice(0, 40)}..." found no expected refusal keyword in the Coach prompt`,
|
||||
|
||||
@@ -24,8 +24,12 @@ describe("base-system assessment prompt — locale skeleton parity", () => {
|
||||
it("every section carries both EN and DE fragments, none blank", () => {
|
||||
expect(ASSESSMENT_SECTION_PAIRS.length).toBeGreaterThan(0);
|
||||
for (const s of ASSESSMENT_SECTION_PAIRS) {
|
||||
expect(s.en.trim().length, `EN fragment for "${s.id}"`).toBeGreaterThan(0);
|
||||
expect(s.de.trim().length, `DE fragment for "${s.id}"`).toBeGreaterThan(0);
|
||||
expect(s.en.trim().length, `EN fragment for "${s.id}"`).toBeGreaterThan(
|
||||
0,
|
||||
);
|
||||
expect(s.de.trim().length, `DE fragment for "${s.id}"`).toBeGreaterThan(
|
||||
0,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -49,8 +53,12 @@ describe("insight system prompt — locale skeleton parity", () => {
|
||||
it("every section carries both EN and DE fragments, none blank", () => {
|
||||
expect(INSIGHT_PROMPT_SECTION_PAIRS.length).toBeGreaterThan(0);
|
||||
for (const s of INSIGHT_PROMPT_SECTION_PAIRS) {
|
||||
expect(s.en.trim().length, `EN fragment for "${s.id}"`).toBeGreaterThan(0);
|
||||
expect(s.de.trim().length, `DE fragment for "${s.id}"`).toBeGreaterThan(0);
|
||||
expect(s.en.trim().length, `EN fragment for "${s.id}"`).toBeGreaterThan(
|
||||
0,
|
||||
);
|
||||
expect(s.de.trim().length, `DE fragment for "${s.id}"`).toBeGreaterThan(
|
||||
0,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -57,4 +57,3 @@ Schreibe eine kurze Gesamteinschätzung über die verfügbaren Gesundheitsdaten:
|
||||
|
||||
${snapshotJson}`;
|
||||
}
|
||||
|
||||
@@ -27,10 +27,7 @@ import type {
|
||||
MetricStatusMeta,
|
||||
} from "@/lib/insights/metric-status-registry";
|
||||
|
||||
function directionPhrase(
|
||||
meta: MetricStatusMeta,
|
||||
locale: Locale,
|
||||
): string {
|
||||
function directionPhrase(meta: MetricStatusMeta, locale: Locale): string {
|
||||
if (locale === "en") {
|
||||
switch (meta.direction) {
|
||||
case "higher-better":
|
||||
@@ -78,10 +75,7 @@ function metaBlock(meta: MetricStatusMeta, locale: Locale): string {
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
const ARCHETYPE_SECTION: Record<
|
||||
MetricArchetype,
|
||||
{ de: string; en: string }
|
||||
> = {
|
||||
const ARCHETYPE_SECTION: Record<MetricArchetype, { de: string; en: string }> = {
|
||||
"physiological-vital": {
|
||||
en: "ARCHETYPE — PHYSIOLOGICAL VITAL:\n- This is a point-in-time physiological reading. Name the recent level, place it against both the user's own baseline (recent vs monthly/yearly mean) and, when a reference band is given, that band.\n- A single out-of-band reading is rarely a finding; a sustained shift across the recent window against the user's baseline is. Note an out-of-band trend without alarm.\n- Frame any direction (rising/falling) as a possible explanation (fitness, stress, sleep, illness, medication), never a diagnosis.",
|
||||
de: "ARCHETYP — PHYSIOLOGISCHER VITALWERT:\n- Das ist ein Momentanwert. Benenne das aktuelle Niveau und ordne es sowohl gegen die eigene Baseline (recent vs. Monats-/Jahresmittel) als auch — falls ein Referenzband vorliegt — gegen dieses Band ein.\n- Ein einzelner Wert außerhalb des Bands ist selten ein Befund; eine anhaltende Verschiebung über das recent-Fenster gegen die Baseline schon. Erwähne einen Trend außerhalb des Bands sachlich, ohne zu alarmieren.\n- Formuliere jede Richtung (steigend/fallend) als mögliche Erklärung (Fitness, Stress, Schlaf, Krankheit, Medikament), nie als Diagnose.",
|
||||
|
||||
@@ -195,10 +195,7 @@ export function loadSafetyContracts(locale: Locale): SafetyContractMatrix {
|
||||
* `.locale`. Throws if the rule has no body for the requested locale
|
||||
* (this indicates a translation gap and is caught by the parity test).
|
||||
*/
|
||||
export function getGroundRuleBody(
|
||||
locale: Locale,
|
||||
key: GroundRuleKey,
|
||||
): string {
|
||||
export function getGroundRuleBody(locale: Locale, key: GroundRuleKey): string {
|
||||
const matrix = loadSafetyContracts(locale);
|
||||
const rule = matrix.ground_rules[key];
|
||||
const body = locale === "en" ? rule.en : rule.locale;
|
||||
|
||||
@@ -51,16 +51,12 @@ export function getStatusBatchSystemPrompt(
|
||||
const en = `BATCHED OUTPUT — you are assessing SEVERAL of this user's metrics in one pass. Each metric below carries its OWN graded snapshot under a "### <key>" heading; assess each one STRICTLY from its own snapshot block, applying every rule above per metric. Do NOT let one metric's finding leak into another. Do NOT invent a metric: assess ONLY the keys present below.
|
||||
|
||||
OUTPUT FORMAT: Reply with valid JSON only, in exactly this schema. "perMetric" carries one short assessment (2-4 sentences each, the same contract as a single card) per present key:
|
||||
{ "perMetric": { ${presentKeys
|
||||
.map((k) => `"${k}": "..."`)
|
||||
.join(", ")} } }
|
||||
{ "perMetric": { ${presentKeys.map((k) => `"${k}": "..."`).join(", ")} } }
|
||||
Include a key ONLY if its snapshot block is present below (keys present: ${keyList}). Omit any metric whose block is absent — never fabricate one.`;
|
||||
const de = `GEBÜNDELTE AUSGABE — du bewertest in einem Durchgang MEHRERE Metriken dieses Nutzers. Jede Metrik unten trägt ihren EIGENEN graded snapshot unter einer Überschrift "### <key>"; bewerte jede ausschließlich aus ihrem eigenen Snapshot-Block und wende alle obigen Regeln pro Metrik an. Lass den Befund einer Metrik NICHT in eine andere überlaufen. Erfinde KEINE Metrik: bewerte NUR die unten vorhandenen Keys.
|
||||
|
||||
AUSGABEFORMAT: Antworte ausschließlich mit validem JSON in genau diesem Schema. "perMetric" enthält je vorhandenem Key eine kurze Einschätzung (je 2-4 Sätze, derselbe Vertrag wie eine Einzelkarte):
|
||||
{ "perMetric": { ${presentKeys
|
||||
.map((k) => `"${k}": "..."`)
|
||||
.join(", ")} } }
|
||||
{ "perMetric": { ${presentKeys.map((k) => `"${k}": "..."`).join(", ")} } }
|
||||
Nimm einen Key NUR auf, wenn sein Snapshot-Block unten vorhanden ist (vorhandene Keys: ${keyList}). Lass jede Metrik ohne Block weg — erfinde niemals eine.`;
|
||||
return `${base}\n\n${locale === "en" ? en : de}`;
|
||||
}
|
||||
|
||||
@@ -72,7 +72,9 @@ export interface ProviderSkipHint {
|
||||
export interface ProviderHealthLedger {
|
||||
/** Providers to skip right now for this user, keyed by chain type.
|
||||
* Fails open (empty) on any error. */
|
||||
getSkipHints(userId: string): Promise<Map<ProviderChainType, ProviderSkipHint>>;
|
||||
getSkipHints(
|
||||
userId: string,
|
||||
): Promise<Map<ProviderChainType, ProviderSkipHint>>;
|
||||
/** Record a successful generation — clears any negative cache. */
|
||||
recordSuccess(userId: string, providerType: ProviderChainType): Promise<void>;
|
||||
/** Record a hard failure. `httpStatus` null = network/transport. */
|
||||
@@ -285,7 +287,8 @@ export function createInMemoryProviderHealthLedger(): ProviderHealthLedger & {
|
||||
async recordFailure(userId, providerType, httpStatus) {
|
||||
const { result, cooldownMs } = classifyFailure(httpStatus);
|
||||
const prev = rowsFor(userId).get(providerType);
|
||||
const priorCount = prev && prev.result !== "ok" ? prev.consecutiveFailures : 0;
|
||||
const priorCount =
|
||||
prev && prev.result !== "ok" ? prev.consecutiveFailures : 0;
|
||||
rowsFor(userId).set(providerType, {
|
||||
result,
|
||||
status: httpStatus,
|
||||
|
||||
@@ -418,10 +418,7 @@ export async function hasAnyConfiguredProvider(
|
||||
where: { id: "singleton" },
|
||||
select: { adminAiKeyEncrypted: true },
|
||||
});
|
||||
return userRowHasProviderCredential(
|
||||
userRow,
|
||||
!!settings?.adminAiKeyEncrypted,
|
||||
);
|
||||
return userRowHasProviderCredential(userRow, !!settings?.adminAiKeyEncrypted);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user