Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down
4 changes: 3 additions & 1 deletion src/datatypes/logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
11 changes: 10 additions & 1 deletion src/mcp/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,13 @@ function withHandler<T>(
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;
Expand All @@ -101,6 +107,9 @@ type RangeInput = z.infer<typeof rangeInputSchema>;
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 };
}

Expand Down
5 changes: 4 additions & 1 deletion src/sync/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
),
});
}

Expand Down
9 changes: 6 additions & 3 deletions test/api/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
142 changes: 142 additions & 0 deletions test/oct29-regression.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
Loading