diff --git a/src/api/client.ts b/src/api/client.ts index 9bb47b1..5ed1bc6 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -167,6 +167,11 @@ export function createClient(opts: CreateClientOptions): VitalsApiClient { } pageToken = response.nextPageToken; } + + throw new VitalsError( + "API_HTTP", + `Reached pagination limit for ${id}; results are incomplete.` + ); } return { listDataPoints, pages }; diff --git a/src/datatypes/logs.ts b/src/datatypes/logs.ts index 76f6052..425db9e 100644 --- a/src/datatypes/logs.ts +++ b/src/datatypes/logs.ts @@ -102,7 +102,9 @@ export const nutritionLogSpec: DataTypeSpec = { if (typeof nutrient !== "string") { continue; } - const field = NUTRIENT_FIELD[nutrient]; + const field = Object.hasOwn(NUTRIENT_FIELD, nutrient) + ? NUTRIENT_FIELD[nutrient] + : undefined; if (!field) { continue; } diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts index 902411b..e484fbe 100644 --- a/src/mcp/tools.ts +++ b/src/mcp/tools.ts @@ -85,7 +85,13 @@ function withHandler( const DATE_RE = /^\d{4}-\d{2}-\d{2}$/; const dateField = z .string() - .regex(DATE_RE, "Expected date in YYYY-MM-DD format"); + .regex(DATE_RE, "Expected date in YYYY-MM-DD format") + .refine((value) => { + const ms = Date.parse(`${value}T00:00:00Z`); + return ( + Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 10) === value + ); + }, "Expected a valid calendar date"); /** Default lookback window for range-shaped tools when no bounds are given. */ const DEFAULT_RANGE_DAYS = 14; @@ -101,6 +107,9 @@ type RangeInput = z.infer; function resolveRange(input: RangeInput, defaultDays: number): DateRange { const to = input.to ?? today(); const from = input.from ?? addDays(to, -((input.days ?? defaultDays) - 1)); + if (from > to) { + throw new VitalsError("USAGE", "Range start must not be after range end."); + } return { from, to }; } diff --git a/src/sync/index.ts b/src/sync/index.ts index 40e59f7..fa7f7f1 100644 --- a/src/sync/index.ts +++ b/src/sync/index.ts @@ -160,7 +160,10 @@ async function syncOne( store.setWatermark({ dataType: spec.id, lastSyncedAt: now.toISOString(), - newestTs: newestPersisted, + newestTs: newerTimestamp( + store.getWatermark(spec.id)?.newestTs ?? null, + newestPersisted + ), }); } diff --git a/test/api/client.test.ts b/test/api/client.test.ts index a9b265d..7120a1d 100644 --- a/test/api/client.test.ts +++ b/test/api/client.test.ts @@ -90,9 +90,12 @@ describe("createClient", () => { }); let count = 0; - for await (const _page of client.pages("steps")) { - count += 1; - } + const consume = async () => { + for await (const _page of client.pages("steps")) { + count += 1; + } + }; + await expect(consume()).rejects.toMatchObject({ code: "API_HTTP" }); expect(count).toBe(500); expect(fetchImpl).toHaveBeenCalledTimes(500); diff --git a/test/oct29-regression.test.ts b/test/oct29-regression.test.ts new file mode 100644 index 0000000..7a34805 --- /dev/null +++ b/test/oct29-regression.test.ts @@ -0,0 +1,142 @@ +import { expect, it, vi } from "vitest"; +import { createClient } from "../src/api/client.js"; +import { nutritionLogSpec } from "../src/datatypes/logs.js"; +import { vitalsLogCheckin, vitalsSleep } from "../src/mcp/tools.js"; +import { openStore } from "../src/store/sqlite.js"; +import { syncAll } from "../src/sync/index.js"; + +it("reports truncated pagination instead of marking an incomplete sync successful", async () => { + let count = 0; + const client = createClient({ + fetchImpl: vi.fn(() => { + count += 1; + return Promise.resolve( + Response.json({ dataPoints: [], nextPageToken: String(count) }) + ); + }), + getToken: async () => "test-token", + }); + const store = openStore(":memory:"); + try { + const [result] = await syncAll(store, client, { dataTypes: ["steps"] }); + expect(result?.error).toContain("pagination limit"); + expect(count).toBe(500); + expect(store.getWatermark("steps")).toBeNull(); + } finally { + store.close(); + } +}); + +it("ignores unknown prototype-named nutrients without overwriting fat", () => { + const batch = nutritionLogSpec.parse([ + { + nutritionLog: { + interval: { startTime: "2026-10-01T12:00:00Z" }, + nutrients: [ + { nutrient: "FAT", quantity: { grams: "5" } }, + { nutrient: "constructor", quantity: { grams: "999" } }, + ], + }, + }, + ]); + expect(batch.nutrition[0]?.fatG).toBe(5); +}); + +it("rejects impossible MCP calendar dates before persisting check-ins", async () => { + const store = openStore(":memory:"); + try { + const result = await vitalsLogCheckin(store, { + date: "2026-02-30", + mood: 5, + }); + expect(result.isError).toBe(true); + expect(store.checkin("2026-02-30")).toBeNull(); + } finally { + store.close(); + } +}); + +it("rejects inverted MCP date ranges", async () => { + const store = openStore(":memory:"); + try { + const result = await vitalsSleep(store, { + from: "2026-10-10", + to: "2026-10-01", + }); + expect(result.isError).toBe(true); + } finally { + store.close(); + } +}); + +it("retains a newer existing watermark when backfilling older observations", async () => { + const store = openStore(":memory:"); + const newestTs = "2026-10-10T12:00:00.000Z"; + store.setWatermark({ dataType: "steps", lastSyncedAt: newestTs, newestTs }); + const client = createClient({ + fetchImpl: vi.fn(() => + Promise.resolve( + Response.json({ + dataPoints: [ + { + steps: { + count: "10", + interval: { startTime: "2026-10-01T12:00:00Z" }, + }, + }, + ], + }) + ) + ), + getToken: async () => "test-token", + }); + try { + const [result] = await syncAll(store, client, { + dataTypes: ["steps"], + since: new Date("2026-10-01T00:00:00Z"), + }); + expect(result?.error).toBeUndefined(); + expect(result?.rowsWritten).toBe(1); + expect(store.getWatermark("steps")?.newestTs).toBe(newestTs); + } finally { + store.close(); + } +}); + +it("accepts a valid leap day and an inclusive single-day range", async () => { + const store = openStore(":memory:"); + try { + const checkin = await vitalsLogCheckin(store, { + date: "2028-02-29", + mood: 5, + }); + expect(checkin.isError).toBeUndefined(); + const range = await vitalsSleep(store, { + from: "2028-02-29", + to: "2028-02-29", + }); + expect(range.isError).toBeUndefined(); + } finally { + store.close(); + } +}); + +it("completes normally when page 500 is the terminal page", async () => { + let count = 0; + const client = createClient({ + fetchImpl: vi.fn(() => { + count += 1; + return Promise.resolve( + Response.json({ + dataPoints: [], + nextPageToken: count < 500 ? String(count) : undefined, + }) + ); + }), + getToken: async () => "test-token", + }); + for await (const page of client.pages("steps")) { + expect(page.dataPoints).toEqual([]); + } + expect(count).toBe(500); +});