mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
Merge branch 'release/v1.45.0' into fix/v145-sheet-motion
# Conflicts: # src/__tests__/baselines/source-file-lines.json # src/__tests__/baselines/source-function-lines.json # src/__tests__/baselines/version-stamp-comments.json
This commit is contained in:
commit
32b71a7df9
111 files changed
+9035
-3718
No files matched your search
@@ -16,7 +16,11 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { readSourceText, walkSourceFiles } from "./helpers/source-files";
|
||||
import {
|
||||
readSource,
|
||||
readSourceText,
|
||||
walkSourceFiles,
|
||||
} from "./helpers/source-files";
|
||||
|
||||
const SRC = join(process.cwd(), "src");
|
||||
|
||||
@@ -176,7 +180,7 @@ describe("the cookie-only helpers cannot see the acting account", () => {
|
||||
const COOKIE_ONLY = ["requireAdmin", "requireCookieAuth", "requireFreshMfa"];
|
||||
|
||||
it.each(COOKIE_ONLY)("%s resolves the actor and nothing else", (name) => {
|
||||
const body = functionBody(read("lib/api-handler.ts"), name);
|
||||
const body = functionBody(readSource("src/lib/api-handler.ts", name), name);
|
||||
|
||||
// Non-zero proof, twice over: the slice found a function, and the slice is
|
||||
// the function it claims to be. A renamed helper must fail here rather
|
||||
@@ -190,7 +194,7 @@ describe("the cookie-only helpers cannot see the acting account", () => {
|
||||
});
|
||||
|
||||
it("substitutes a data-scope user in exactly two functions", () => {
|
||||
const src = read("lib/api-handler.ts");
|
||||
const src = readSource("src/lib/api-handler.ts", "requireRecordAuth");
|
||||
const record = functionBody(src, "requireRecordAuth");
|
||||
expect(record).toContain("readActingCarrier");
|
||||
|
||||
@@ -291,7 +295,7 @@ describe("ending a grant and clearing the switch are one act", () => {
|
||||
|
||||
it("runs the transition and the cleanup in one transaction", () => {
|
||||
const body = privateFunctionBody(
|
||||
read("lib/sharing/grants.ts"),
|
||||
readSource("src/lib/sharing/grants.ts", "endAndClear"),
|
||||
"endAndClear",
|
||||
);
|
||||
// Non-zero proof: a renamed helper fails here rather than asserting
|
||||
@@ -308,7 +312,7 @@ describe("ending a grant and clearing the switch are one act", () => {
|
||||
// claim's own transaction (it takes `tx`), so the guard here is that the
|
||||
// cleanup is part of the same function as the ending.
|
||||
const body = functionBody(
|
||||
read("lib/sharing/grants.ts"),
|
||||
readSource("src/lib/sharing/grants.ts", "settleHandoverGuardianGrant"),
|
||||
"settleHandoverGuardianGrant",
|
||||
);
|
||||
expect(body.length).toBeGreaterThan(0);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$comment": "Production files over 800 lines and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
|
||||
"count": 124,
|
||||
"total": 146508,
|
||||
"count": 123,
|
||||
"total": 145551,
|
||||
"entries": {
|
||||
"app/api/dashboard/summary/route.ts": 1032,
|
||||
"app/api/documents/inbound/route.ts": 811,
|
||||
@@ -10,7 +10,7 @@
|
||||
"app/api/measurements/route.ts": 938,
|
||||
"app/api/medications/[id]/route.ts": 1281,
|
||||
"app/api/medications/intake/bulk/route.ts": 1044,
|
||||
"app/api/workouts/batch/route.ts": 971,
|
||||
"app/api/workouts/batch/route.ts": 958,
|
||||
"app/medications/page-client.tsx": 839,
|
||||
"app/page-client.tsx": 2324,
|
||||
"components/admin/backups-section.tsx": 1462,
|
||||
@@ -44,7 +44,7 @@
|
||||
"lib/ai/coach/coach-prose-grounding.ts": 1079,
|
||||
"lib/ai/coach/persistence.ts": 1219,
|
||||
"lib/ai/coach/results/metric-table-tool.ts": 1102,
|
||||
"lib/ai/coach/snapshot.ts": 1362,
|
||||
"lib/ai/coach/snapshot.ts": 1347,
|
||||
"lib/ai/coach/stream-events.ts": 817,
|
||||
"lib/ai/coach/tools/executor.ts": 1522,
|
||||
"lib/ai/coach/turn/model.ts": 820,
|
||||
@@ -65,7 +65,7 @@
|
||||
"lib/daily/today-overview.ts": 838,
|
||||
"lib/dashboard-layout.ts": 971,
|
||||
"lib/dashboard/snapshot.ts": 1550,
|
||||
"lib/day/records.ts": 1175,
|
||||
"lib/day/records.ts": 1174,
|
||||
"lib/doctor-report/collect.ts": 803,
|
||||
"lib/export/backup-plan.ts": 853,
|
||||
"lib/export/coach-backup.ts": 1070,
|
||||
@@ -90,9 +90,8 @@
|
||||
"lib/insights/mood-aggregates.ts": 1055,
|
||||
"lib/insights/mood-status.ts": 814,
|
||||
"lib/insights/status-cache.ts": 812,
|
||||
"lib/insights/strain-score.ts": 832,
|
||||
"lib/integrations/status.ts": 1445,
|
||||
"lib/jobs/apple-health-import-worker.ts": 863,
|
||||
"lib/jobs/apple-health-import-worker.ts": 801,
|
||||
"lib/jobs/backup-restore.ts": 888,
|
||||
"lib/jobs/coach-nudge.ts": 1089,
|
||||
"lib/jobs/insight-pregenerate.ts": 1266,
|
||||
@@ -115,7 +114,7 @@
|
||||
"lib/medications/scheduling/slot-upsert.ts": 926,
|
||||
"lib/notifications/senders/apns.ts": 1100,
|
||||
"lib/oura/client.ts": 1360,
|
||||
"lib/oura/sync.ts": 917,
|
||||
"lib/oura/sync.ts": 902,
|
||||
"lib/polar/client.ts": 1010,
|
||||
"lib/rollups/measurement-rollups.ts": 1496,
|
||||
"lib/search/search-records.ts": 996,
|
||||
@@ -124,7 +123,7 @@
|
||||
"lib/telegram-webhook-handlers.ts": 1341,
|
||||
"lib/validations/inbound-documents.ts": 1130,
|
||||
"lib/whoop/client.ts": 917,
|
||||
"lib/withings/sync-sleep.ts": 903,
|
||||
"lib/withings/sync-sleep.ts": 884,
|
||||
"lib/withings/sync.ts": 978,
|
||||
"proxy.ts": 870
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$comment": "Production functions over 200 lines, keyed \"file :: name\", and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
|
||||
"count": 411,
|
||||
"total": 148298,
|
||||
"total": 148137,
|
||||
"entries": {
|
||||
"app/achievements/page.tsx :: AchievementsPage": 206,
|
||||
"app/api/admin/backups/upload/route.ts :: apiHandler(arg)": 314,
|
||||
@@ -64,8 +64,8 @@
|
||||
"app/api/sync/changes/route.ts :: apiHandler(arg)": 427,
|
||||
"app/api/user/ai-provider/route.ts :: apiHandler(arg) #2": 252,
|
||||
"app/api/withings/callback/route.ts :: apiHandler(arg)": 247,
|
||||
"app/api/workouts/[id]/route.ts :: apiHandler(arg)": 313,
|
||||
"app/api/workouts/batch/route.ts :: postBatch": 722,
|
||||
"app/api/workouts/[id]/route.ts :: apiHandler(arg)": 297,
|
||||
"app/api/workouts/batch/route.ts :: postBatch": 709,
|
||||
"app/auth/login/page.tsx :: LoginPage": 576,
|
||||
"app/auth/register/page.tsx :: RegisterPage": 285,
|
||||
"app/coach/conversations/page.tsx :: CoachConversationsBody": 249,
|
||||
@@ -287,7 +287,7 @@
|
||||
"lib/ai/anthropic-client.ts :: generateCompletion": 294,
|
||||
"lib/ai/coach/cycle-snapshot.ts :: buildCycleSnapshotBlock": 218,
|
||||
"lib/ai/coach/glp1-snapshot.ts :: buildGlp1SnapshotBlock": 218,
|
||||
"lib/ai/coach/snapshot.ts :: buildCoachSnapshotImpl": 898,
|
||||
"lib/ai/coach/snapshot.ts :: buildCoachSnapshotImpl": 882,
|
||||
"lib/ai/coach/tools/loop.ts :: runCoachToolLoop": 438,
|
||||
"lib/ai/coach/turn/model.ts :: runTurnModel": 560,
|
||||
"lib/ai/coach/turn/pipeline.ts :: runTurn": 274,
|
||||
@@ -305,7 +305,7 @@
|
||||
"lib/api-handler.ts :: apiHandler > wrapped": 201,
|
||||
"lib/auth/profile-update.ts :: applyProfileUpdate": 353,
|
||||
"lib/cache/server-cache.ts :: createServerCaches": 230,
|
||||
"lib/cycle/backup.ts :: restoreCycleData": 243,
|
||||
"lib/cycle/backup.ts :: restoreCycleData": 224,
|
||||
"lib/cycle/day-log-write.ts :: writeDayLog": 311,
|
||||
"lib/daily/digest.ts :: buildDailyDigest": 227,
|
||||
"lib/daily/load-digest.ts :: loadDailyDigest": 452,
|
||||
@@ -350,7 +350,7 @@
|
||||
"lib/insights/weight-status.ts :: prepareWeightStatusForUser": 598,
|
||||
"lib/integrations/connection-health-load.ts :: loadConnectionFacts": 227,
|
||||
"lib/integrations/status.ts :: recordSyncFailure": 292,
|
||||
"lib/jobs/apple-health-import-worker.ts :: handleAppleHealthImport": 357,
|
||||
"lib/jobs/apple-health-import-worker.ts :: handleAppleHealthImport": 300,
|
||||
"lib/jobs/coach-nudge.ts :: findTriggerForUser": 279,
|
||||
"lib/jobs/coach-nudge.ts :: runCoachNudgeTick": 292,
|
||||
"lib/jobs/coach-reminder-sweep.ts :: runCoachReminderSweep": 222,
|
||||
@@ -409,9 +409,9 @@
|
||||
"lib/targets/vitals-builder.ts :: buildVitalTargets": 324,
|
||||
"lib/telegram-webhook-handlers.ts :: handleCallback": 599,
|
||||
"lib/telegram-webhook-handlers.ts :: handleTextMessage": 337,
|
||||
"lib/withings/sync-activity.ts :: syncUserActivity": 391,
|
||||
"lib/withings/sync-ecg.ts :: syncUserEcg": 213,
|
||||
"lib/withings/sync-sleep.ts :: syncUserSleep": 429,
|
||||
"lib/withings/sync-activity.ts :: syncUserActivity": 377,
|
||||
"lib/withings/sync-ecg.ts :: syncUserEcg": 202,
|
||||
"lib/withings/sync-sleep.ts :: syncUserSleep": 414,
|
||||
"lib/withings/sync.ts :: syncUserMeasurements": 373,
|
||||
"proxy.ts :: proxy": 499
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$comment": "as never casts in tests, per test file under src/. Maintained by src/__tests__/test-realism-ratchet.test.ts.",
|
||||
"count": 524,
|
||||
"total": 5496,
|
||||
"total": 5495,
|
||||
"entries": {
|
||||
"__tests__/api/auth/login/mfa-branch.test.ts": 10,
|
||||
"__tests__/api/auth/mfa/verify.test.ts": 9,
|
||||
@@ -253,7 +253,7 @@
|
||||
"app/api/withings/credentials/__tests__/route.test.ts": 4,
|
||||
"app/api/withings/webhook/__tests__/route.test.ts": 26,
|
||||
"app/api/withings/webhook/[token]/__tests__/route.test.ts": 8,
|
||||
"app/api/workouts/__tests__/batch-create.test.ts": 14,
|
||||
"app/api/workouts/__tests__/batch-create.test.ts": 13,
|
||||
"app/api/workouts/__tests__/canonical-dedup.test.ts": 20,
|
||||
"app/api/workouts/batch/__tests__/unstable-external-id.test.ts": 4,
|
||||
"app/c/[token]/__tests__/report-download.test.ts": 11,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$comment": "Comment lines that open with a release version, per file under src/. Maintained by src/__tests__/version-stamp-ratchet.test.ts.",
|
||||
"count": 2954,
|
||||
"total": 10508,
|
||||
"total": 10504,
|
||||
"entries": {
|
||||
"__tests__/account-payload-consumer-guard.test.ts": 2,
|
||||
"__tests__/acting-account-boundary-guard.test.ts": 7,
|
||||
@@ -1706,7 +1706,7 @@
|
||||
"lib/ai/coach/snapshot-cache.ts": 2,
|
||||
"lib/ai/coach/snapshot-prelude.ts": 17,
|
||||
"lib/ai/coach/snapshot-series.ts": 5,
|
||||
"lib/ai/coach/snapshot.ts": 42,
|
||||
"lib/ai/coach/snapshot.ts": 41,
|
||||
"lib/ai/coach/source-measurement-types.ts": 1,
|
||||
"lib/ai/coach/suggest-action.ts": 1,
|
||||
"lib/ai/coach/suggest-gate.ts": 1,
|
||||
@@ -2341,7 +2341,7 @@
|
||||
"lib/jobs/__tests__/whoop-resource-sync.test.ts": 1,
|
||||
"lib/jobs/__tests__/withings-queues.test.ts": 2,
|
||||
"lib/jobs/__tests__/workout-insight-queue.test.ts": 1,
|
||||
"lib/jobs/apple-health-import-worker.ts": 5,
|
||||
"lib/jobs/apple-health-import-worker.ts": 4,
|
||||
"lib/jobs/coach-message-cleanup.ts": 1,
|
||||
"lib/jobs/coach-nudge-ai.ts": 3,
|
||||
"lib/jobs/coach-nudge.ts": 17,
|
||||
@@ -2948,9 +2948,9 @@
|
||||
"lib/withings/client.ts": 5,
|
||||
"lib/withings/oauth-state.ts": 1,
|
||||
"lib/withings/response-classifier.ts": 1,
|
||||
"lib/withings/sync-activity.ts": 8,
|
||||
"lib/withings/sync-activity.ts": 7,
|
||||
"lib/withings/sync-ecg.ts": 4,
|
||||
"lib/withings/sync-sleep.ts": 10,
|
||||
"lib/withings/sync-sleep.ts": 9,
|
||||
"lib/withings/sync.ts": 9,
|
||||
"lib/withings/webhook-handler.ts": 3,
|
||||
"lib/workouts/list-read.ts": 1,
|
||||
|
||||
@@ -15,7 +15,11 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { readSourceText, walkSourceFiles } from "./helpers/source-files";
|
||||
import {
|
||||
readSource,
|
||||
readSourceText,
|
||||
walkSourceFiles,
|
||||
} from "./helpers/source-files";
|
||||
|
||||
const SRC = join(process.cwd(), "src");
|
||||
|
||||
@@ -276,7 +280,10 @@ describe("T1 — the Bearer resolution set is frozen", () => {
|
||||
});
|
||||
|
||||
it("the resolver exposes exactly one authorisation arm", () => {
|
||||
const src = read("lib/auth/bearer.ts");
|
||||
const src = readSource(
|
||||
"src/lib/auth/bearer.ts",
|
||||
'permissions.includes("*")',
|
||||
);
|
||||
// One wildcard escape hatch, guarding one deny block. If a second
|
||||
// `permissions.includes("*")` short-circuit appears, the arm has forked.
|
||||
const wildcardChecks = src.match(/permissions\.includes\("\*"\)/g) ?? [];
|
||||
@@ -375,7 +382,10 @@ describe("T3 — the mint sites are frozen", () => {
|
||||
// does not contradict this: what was retired is a mint at THIS path that
|
||||
// named no scope and answered for the whole API. A child path minting one
|
||||
// named scope, listed in `MINT_SITES` above, is the shape that replaced it.
|
||||
const tokensRoute = read("app/api/tokens/route.ts");
|
||||
const tokensRoute = readSource(
|
||||
"src/app/api/tokens/route.ts",
|
||||
"export const GET",
|
||||
);
|
||||
expect(tokensRoute).not.toMatch(/export const POST/);
|
||||
expect(tokensRoute).toMatch(/export const GET/);
|
||||
});
|
||||
@@ -442,12 +452,18 @@ describe("T4b — `documents:write` opens exactly two doors", () => {
|
||||
]);
|
||||
// Within the upload file, once: the GET list beside the POST must not
|
||||
// name it.
|
||||
const upload = read("app/api/documents/inbound/route.ts");
|
||||
const upload = readSource(
|
||||
"src/app/api/documents/inbound/route.ts",
|
||||
"DOCUMENTS_WRITE_SCOPE",
|
||||
);
|
||||
expect(
|
||||
requireAuthScopes(upload).filter((x) => x === "DOCUMENTS_WRITE_SCOPE"),
|
||||
).toHaveLength(1);
|
||||
// And the lookup is a read of one key and nothing else: a single GET.
|
||||
const lookup = read("app/api/documents/inbound/source/route.ts");
|
||||
const lookup = readSource(
|
||||
"src/app/api/documents/inbound/source/route.ts",
|
||||
"export const GET",
|
||||
);
|
||||
expect(
|
||||
[...lookup.matchAll(/export const (GET|POST|PUT|PATCH|DELETE)\b/g)].map(
|
||||
(m) => m[1],
|
||||
@@ -469,7 +485,10 @@ describe("T4c — `workouts:write` opens exactly one door", () => {
|
||||
);
|
||||
});
|
||||
expect(declaring).toEqual(["app/api/workouts/batch/route.ts"]);
|
||||
const batch = read("app/api/workouts/batch/route.ts");
|
||||
const batch = readSource(
|
||||
"src/app/api/workouts/batch/route.ts",
|
||||
"WORKOUTS_WRITE_SCOPE",
|
||||
);
|
||||
expect(
|
||||
requireAuthScopes(batch).filter((x) => x === "WORKOUTS_WRITE_SCOPE"),
|
||||
).toHaveLength(1);
|
||||
@@ -524,7 +543,7 @@ describe("T5 — a delegable route naming a Bearer scope is frozen", () => {
|
||||
// it and every other leg in this file stays green while a single-purpose
|
||||
// token gains delegated write — so the refusal is asserted where it lives,
|
||||
// not only through the behaviour that depends on it.
|
||||
const src = read("lib/api-handler.ts");
|
||||
const src = readSource("src/lib/api-handler.ts", "narrow_scope_selector");
|
||||
expect(src).toMatch(/narrow_scope_selector/);
|
||||
expect(src).toMatch(/isScopedCredential\(auth\)/);
|
||||
});
|
||||
|
||||
@@ -21,6 +21,7 @@ import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
readSource,
|
||||
readSourceText,
|
||||
stripComments,
|
||||
walkSourceFiles,
|
||||
@@ -59,8 +60,14 @@ describe("one Pearson correlation", () => {
|
||||
});
|
||||
|
||||
it("both homes still hold their function", () => {
|
||||
const engine = readSourceText(join(SRC, "lib/insights/correlations.ts"));
|
||||
const wrapper = readSourceText(join(SRC, "lib/analytics/correlations.ts"));
|
||||
const engine = readSource(
|
||||
"src/lib/insights/correlations.ts",
|
||||
"export function pearson",
|
||||
);
|
||||
const wrapper = readSource(
|
||||
"src/lib/analytics/correlations.ts",
|
||||
"export function significantPearsonCorrelation",
|
||||
);
|
||||
expect(engine).toMatch(/export function pearson\s*\(/);
|
||||
expect(wrapper).toMatch(
|
||||
/export function significantPearsonCorrelation\s*\(/,
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
mayBeCycleContext,
|
||||
parse,
|
||||
} from "./helpers/cycle-verdict-derivation";
|
||||
import { readSourceText } from "./helpers/source-files";
|
||||
import { readSource, readSourceText } from "./helpers/source-files";
|
||||
|
||||
const ROOT = process.cwd();
|
||||
|
||||
@@ -110,19 +110,21 @@ describe("the surfaces that show the verdict actually read it", () => {
|
||||
// The BBT chart used to walk the calendar itself to find the cycle start,
|
||||
// which was a second copy of the same walk. It now takes the resolved
|
||||
// value as a prop, and the cycle page feeds it from the verdict.
|
||||
const chart = readSourceText(
|
||||
join(ROOT, "src/components/cycle/bbt-chart.tsx"),
|
||||
const chart = readSource(
|
||||
"src/components/cycle/bbt-chart.tsx",
|
||||
"cycleStartDate",
|
||||
);
|
||||
expect(chart).toContain("cycleStartDate");
|
||||
|
||||
const paths = accessPaths(parseFile("src/components/cycle/cycle-view.tsx"));
|
||||
const view = "src/components/cycle/cycle-view.tsx";
|
||||
const paths = accessPaths(parse(view, readSource(view, "verdict")));
|
||||
expect([...paths]).toContain("verdict.cycleStartDate");
|
||||
});
|
||||
|
||||
it("the calendar response type declares the verdict as always present", () => {
|
||||
// An optional verdict is a plausible default that lets a client fall back
|
||||
// to deriving its own.
|
||||
const types = readSourceText(join(ROOT, "src/components/cycle/types.ts"));
|
||||
const types = readSource("src/components/cycle/types.ts", "CycleVerdict");
|
||||
expect(types).toContain("verdict: CycleVerdict;");
|
||||
expect(types).not.toContain("verdict?:");
|
||||
});
|
||||
|
||||
@@ -24,7 +24,11 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { readSourceText, walkSourceFiles } from "./helpers/source-files";
|
||||
import {
|
||||
readSource,
|
||||
readSourceText,
|
||||
walkSourceFiles,
|
||||
} from "./helpers/source-files";
|
||||
|
||||
const SRC = join(process.cwd(), "src");
|
||||
const VALIDATOR_MODULE = "@/lib/validations/external-id";
|
||||
@@ -280,9 +284,9 @@ describe("identities derived outside a Zod schema stay inside the floor", () =>
|
||||
const b = body("lib/import/csv-measurements.ts");
|
||||
expect(b).toContain("isStableExternalId");
|
||||
expect(b).toContain('skip("unstable_external_id")');
|
||||
expect(read("lib/import/csv-measurements.ts")).toContain(
|
||||
'| "unstable_external_id"',
|
||||
);
|
||||
expect(
|
||||
readSource("src/lib/import/csv-measurements.ts", "unstable_external_id"),
|
||||
).toContain('| "unstable_external_id"');
|
||||
});
|
||||
|
||||
it("the MCP write path checks the key BEFORE it is hashed into an identity", () => {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* The nightly property runs multiply each property's own case count instead
|
||||
* of replacing it. A nightly count of 100 for every property ran the backup
|
||||
* round trip, which states twelve cases for its cost, eight times over
|
||||
* against a timeout sized for twelve.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
async function loadWith(factor: string | undefined) {
|
||||
vi.resetModules();
|
||||
if (factor === undefined) vi.stubEnv("FC_RUNS_FACTOR", "");
|
||||
else vi.stubEnv("FC_RUNS_FACTOR", factor);
|
||||
return import("../../tests/property/fast-check");
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("FC_RUNS_FACTOR", () => {
|
||||
it("keeps each property's own count on a pull request", async () => {
|
||||
const { propertyParameters, propertyTimeout } = await loadWith(undefined);
|
||||
expect(propertyParameters(12).numRuns).toBe(12);
|
||||
expect(propertyParameters().numRuns).toBe(100);
|
||||
expect(propertyTimeout(60_000)).toBe(60_000);
|
||||
});
|
||||
|
||||
it("multiplies each property's count and the timeout it was given", async () => {
|
||||
const { propertyParameters, propertyTimeout } = await loadWith("4");
|
||||
expect(propertyParameters(12).numRuns).toBe(48);
|
||||
expect(propertyParameters(300).numRuns).toBe(1200);
|
||||
expect(propertyTimeout(60_000)).toBe(240_000);
|
||||
});
|
||||
|
||||
it("ignores a value that is not a positive number", async () => {
|
||||
const { propertyParameters } = await loadWith("-3");
|
||||
expect(propertyParameters(12).numRuns).toBe(12);
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,11 @@
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { readSourceText, walkSourceFiles } from "./helpers/source-files";
|
||||
import {
|
||||
readSource,
|
||||
readSourceText,
|
||||
walkSourceFiles,
|
||||
} from "./helpers/source-files";
|
||||
|
||||
const SRC = join(process.cwd(), "src");
|
||||
|
||||
@@ -65,7 +69,12 @@ describe("one least-squares line", () => {
|
||||
// The implementation itself matches, so the sweep read real files.
|
||||
expect(
|
||||
HAND_ROLLED_SLOPE.test(
|
||||
stripComments(readSourceText(join(SRC, "lib/stats/linear-fit.ts"))),
|
||||
stripComments(
|
||||
readSource(
|
||||
"src/lib/stats/linear-fit.ts",
|
||||
"export function linearFit",
|
||||
),
|
||||
),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
@@ -22,7 +22,11 @@ import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { readSourceText, walkSourceFiles } from "./helpers/source-files";
|
||||
import {
|
||||
readSource,
|
||||
readSourceText,
|
||||
walkSourceFiles,
|
||||
} from "./helpers/source-files";
|
||||
|
||||
const SRC = join(process.cwd(), "src");
|
||||
const MEMORY = "lib/ai/coach/memory";
|
||||
@@ -59,18 +63,21 @@ function checksBeforeRead(body: string, check: RegExp): boolean {
|
||||
|
||||
describe("memory block egress guard", () => {
|
||||
const block = functionBody(
|
||||
read(`${MEMORY}/context-block.ts`),
|
||||
readSource(`src/${MEMORY}/context-block.ts`, "buildMemoryContextBlock"),
|
||||
"buildMemoryContextBlock",
|
||||
);
|
||||
const lines = functionBody(
|
||||
read(`${MEMORY}/plan-progress.ts`),
|
||||
readSource(`src/${MEMORY}/plan-progress.ts`, "buildPlanProgressLines"),
|
||||
"buildPlanProgressLines",
|
||||
);
|
||||
|
||||
it("the memory block checks egress before it reads anything", () => {
|
||||
expect(block.length).toBeGreaterThan(200);
|
||||
expect(checksBeforeRead(block, /egressAllowed\(/)).toBe(true);
|
||||
const helper = read(`${MEMORY}/context-block.ts`);
|
||||
const helper = readSource(
|
||||
`src/${MEMORY}/context-block.ts`,
|
||||
"aiEgressRefusal",
|
||||
);
|
||||
expect(helper).toMatch(/aiEgressRefusal\(\s*"coach"/);
|
||||
expect(helper).toMatch(/aiCapabilityForRecord\(args\.userId, "coach"\)/);
|
||||
// Broken on purpose: the check moved below the reads.
|
||||
|
||||
@@ -55,18 +55,12 @@ const EXCLUDED_MOOD_CONTEXT_COLUMNS: Record<string, string> = {
|
||||
moodEntryId:
|
||||
"re-bound to the restored parent row's id; the context rides inside its entry",
|
||||
userId: "user-scoped backup; owner is re-derived from the restoring account",
|
||||
createdAt:
|
||||
"the sub-row's own bookkeeping stamp; the entry carries the moment the person logged the day, and the context has nothing separate to say about when it was typed",
|
||||
updatedAt:
|
||||
"the sub-row's own bookkeeping stamp, moved by every write; a restore re-stamps it and nothing reads the old value",
|
||||
};
|
||||
|
||||
const EXCLUDED_TAG_LINK_COLUMNS: Record<string, string> = {
|
||||
moodEntryId: "re-bound to the restored parent row's id, never carried",
|
||||
moodTagId:
|
||||
"the link travels by the tag's key; a source-instance id need not exist in the target catalogue",
|
||||
createdAt:
|
||||
"the link's own row stamp; the entry carries the moment the person logged it, and a key-only BINARY tag has nowhere to put a second one",
|
||||
};
|
||||
|
||||
function modelBlock(schema: string, model: string): string {
|
||||
|
||||
@@ -16,7 +16,11 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { readSourceText, walkSourceFiles } from "./helpers/source-files";
|
||||
import {
|
||||
readSource,
|
||||
readSourceText,
|
||||
walkSourceFiles,
|
||||
} from "./helpers/source-files";
|
||||
|
||||
const SRC = join(process.cwd(), "src");
|
||||
|
||||
@@ -181,7 +185,10 @@ describe("the recent-proof gate", () => {
|
||||
});
|
||||
|
||||
it("the gate reads the session's own stamps, and only a second factor on an enrolled account", () => {
|
||||
const src = read("lib/api-handler.ts");
|
||||
const src = readSource(
|
||||
"src/lib/api-handler.ts",
|
||||
"export async function assertRecentCookieProof(",
|
||||
);
|
||||
const start = src.indexOf("export async function assertRecentCookieProof(");
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
const body = src.slice(start, src.indexOf("\nexport ", start + 1));
|
||||
|
||||
@@ -41,7 +41,11 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { readSourceText, walkSourceFiles } from "./helpers/source-files";
|
||||
import {
|
||||
readSource,
|
||||
readSourceText,
|
||||
walkSourceFiles,
|
||||
} from "./helpers/source-files";
|
||||
|
||||
const SRC = join(process.cwd(), "src");
|
||||
|
||||
@@ -80,7 +84,10 @@ function functionBody(src: string, name: string): string {
|
||||
return "";
|
||||
}
|
||||
|
||||
const API_HANDLER = read("lib/api-handler.ts");
|
||||
const API_HANDLER = readSource("src/lib/api-handler.ts", [
|
||||
"requireRecordAuth",
|
||||
"requireGuardianAuth",
|
||||
]);
|
||||
|
||||
/** The two helpers that resolve a record and therefore must consult the fence. */
|
||||
const FENCED_RESOLVERS = ["requireRecordAuth", "requireGuardianAuth"] as const;
|
||||
@@ -180,8 +187,11 @@ describe("the fence runs in exactly two auth helpers", () => {
|
||||
// client's context is unknown; the switch endpoint is the way out of a
|
||||
// context that cannot be proved. Fencing either would make an unprovable
|
||||
// context unrecoverable.
|
||||
const me = read("app/api/auth/me/route.ts");
|
||||
const sw = read("app/api/account/switch/route.ts");
|
||||
const me = readSource("src/app/api/auth/me/route.ts", "requireActorAuth");
|
||||
const sw = readSource(
|
||||
"src/app/api/account/switch/route.ts",
|
||||
"requireActorAuth",
|
||||
);
|
||||
expect(me).toContain("requireActorAuth");
|
||||
expect(sw).toContain("requireActorAuth");
|
||||
expect(me).not.toContain("assertRecordSessionFence");
|
||||
@@ -228,7 +238,10 @@ describe("the epoch has one writer and a closed reader set", () => {
|
||||
});
|
||||
|
||||
it("is consulted by the idempotency wrapper, above the cache", () => {
|
||||
const src = read("lib/idempotency.ts");
|
||||
const src = readSource(
|
||||
"src/lib/idempotency.ts",
|
||||
"refuseStaleRecordSessionClaim(claim)",
|
||||
);
|
||||
const fence = src.indexOf("refuseStaleRecordSessionClaim(claim)");
|
||||
const cache = src.indexOf("findCached(ctx)");
|
||||
const claimRow = src.indexOf("claimKey(ctx)");
|
||||
|
||||
@@ -20,6 +20,7 @@ import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
readSource,
|
||||
readSourceText,
|
||||
stripComments,
|
||||
walkSourceFiles,
|
||||
@@ -87,10 +88,17 @@ describe("one standard deviation", () => {
|
||||
});
|
||||
|
||||
it("the series API and the AI and MCP payload report the same spread", () => {
|
||||
expect(read("app/api/measurements/series/route.ts")).toMatch(
|
||||
/standardDeviation\(\s*values,\s*READING_SPREAD\s*\)/,
|
||||
expect(
|
||||
stripComments(
|
||||
readSource(
|
||||
"src/app/api/measurements/series/route.ts",
|
||||
"READING_SPREAD",
|
||||
),
|
||||
),
|
||||
).toMatch(/standardDeviation\(\s*values,\s*READING_SPREAD\s*\)/);
|
||||
const features = stripComments(
|
||||
readSource("src/lib/insights/features.ts", "READING_SPREAD"),
|
||||
);
|
||||
const features = read("lib/insights/features.ts");
|
||||
expect(
|
||||
features.match(/roundedSpread\(\s*vals,\s*READING_SPREAD\s*\)/g),
|
||||
).toHaveLength(2);
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
import { readdirSync, statSync } from "node:fs";
|
||||
import { join, relative } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readSourceText } from "./helpers/source-files";
|
||||
import { readSource, readSourceText } from "./helpers/source-files";
|
||||
|
||||
const ROOT = join(__dirname, "..", "..");
|
||||
const SRC = join(ROOT, "src");
|
||||
@@ -85,7 +85,7 @@ function bareReads(): string[] {
|
||||
describe("raw SQL clock reads are anchored to UTC", () => {
|
||||
it("finds the anchored form across the swept files", () => {
|
||||
// The matcher must see something, or a broken walk would pass.
|
||||
const passkey = readSourceText(join(SRC, "lib/auth/passkey.ts"));
|
||||
const passkey = readSource("src/lib/auth/passkey.ts", ANCHORED);
|
||||
expect(passkey.match(ANCHORED)?.length).toBeGreaterThanOrEqual(3);
|
||||
expect(SQL_CLOCK.test("AND expires_at > NOW()")).toBe(true);
|
||||
expect(SQL_CLOCK.test("updated_at = now()")).toBe(true);
|
||||
|
||||
@@ -25,7 +25,11 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { readSourceText, walkSourceFiles } from "./helpers/source-files";
|
||||
import {
|
||||
readSource,
|
||||
readSourceText,
|
||||
walkSourceFiles,
|
||||
} from "./helpers/source-files";
|
||||
|
||||
const SRC = join(process.cwd(), "src");
|
||||
|
||||
@@ -256,7 +260,10 @@ describe("S6 — the erasure routes accept a fresh-factor elevation", () => {
|
||||
// A password-proved elevation must not erase an account, and the gate
|
||||
// must not grow a second, inline factor check beside the elevation: one
|
||||
// mint surface, one redemption path.
|
||||
const src = read("lib/api-handler.ts");
|
||||
const src = readSource(
|
||||
"src/lib/api-handler.ts",
|
||||
"export async function requireFreshMfaOrElevationIfEnrolled(",
|
||||
);
|
||||
const start = src.indexOf(
|
||||
"export async function requireFreshMfaOrElevationIfEnrolled(",
|
||||
);
|
||||
@@ -307,7 +314,10 @@ describe("S2 — mint and redeem happen in exactly one place each", () => {
|
||||
|
||||
describe("S3 — requireAdmin stays cookie-only", () => {
|
||||
it("resolves through getSession and nothing else", () => {
|
||||
const src = read("lib/api-handler.ts");
|
||||
const src = readSource("src/lib/api-handler.ts", [
|
||||
"export async function requireAdmin(",
|
||||
"export async function requireCookieAuth(",
|
||||
]);
|
||||
const body = src.slice(
|
||||
src.indexOf("export async function requireAdmin("),
|
||||
src.indexOf("export async function requireCookieAuth("),
|
||||
@@ -335,7 +345,10 @@ describe("S4 — the mint surface refuses a cookie", () => {
|
||||
});
|
||||
|
||||
it("requireBearerAuth never consults the session cookie", () => {
|
||||
const src = read("lib/api-handler.ts");
|
||||
const src = readSource("src/lib/api-handler.ts", [
|
||||
"export async function requireBearerAuth(",
|
||||
"export const STEP_UP_ELEVATION_HEADER",
|
||||
]);
|
||||
const body = src.slice(
|
||||
src.indexOf("export async function requireBearerAuth("),
|
||||
src.indexOf("export const STEP_UP_ELEVATION_HEADER"),
|
||||
@@ -372,7 +385,10 @@ describe("S5 — a password proof cannot satisfy a fresh-factor gate", () => {
|
||||
});
|
||||
|
||||
it("the claim re-checks the factor rather than trusting the validation", () => {
|
||||
const src = read("lib/auth/step-up.ts");
|
||||
const src = readSource(
|
||||
"src/lib/auth/step-up.ts",
|
||||
"export async function claimStepUpElevation(",
|
||||
);
|
||||
const claim = src.slice(
|
||||
src.indexOf("export async function claimStepUpElevation("),
|
||||
);
|
||||
|
||||
@@ -19,6 +19,9 @@
|
||||
* assertion then passes for the wrong reason. New ones go through
|
||||
* `readSource(path, anchors)` or `readSourceFolder(dir, { floor })` in
|
||||
* `helpers/source-files.ts`, which this count does not include.
|
||||
* `readSourceText` is the unanchored reader the sweeps use; called with a
|
||||
* fixed source path, directly or through a local wrapper that is, it is
|
||||
* the same read without the anchors, and it counts.
|
||||
*
|
||||
* A new offender fails; one that disappears (or loses casts) fails until
|
||||
* the lower number is written back with
|
||||
@@ -29,7 +32,10 @@
|
||||
* the Prisma client entry itself, or a spy on every delegate, is not a
|
||||
* pattern in use and is not matched. The source-read check is a text
|
||||
* heuristic: a file that calls `readFileSync`/`readFile` and names a source
|
||||
* path (a literal ending in `.ts`, `.tsx`, `.js` or `.mjs`).
|
||||
* path (a literal ending in `.ts`, `.tsx`, `.js` or `.mjs`), or that calls
|
||||
* `readSourceText` with such a literal, or calls a local one-parameter wrapper
|
||||
* of `readSourceText` with one. A wrapper fed from a list of paths is not
|
||||
* matched.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import ts from "typescript";
|
||||
@@ -45,6 +51,26 @@ const DB_MOCK =
|
||||
const HANDLER_STUB = /vi\.(?:do)?[mM]ock\(\s*["'`]@\/lib\/api-handler["'`]/;
|
||||
const READS_FILE = /\b(?:readFileSync|readFile)\s*\(/;
|
||||
const SOURCE_PATH = /["'`][^"'`\n]*\.(?:tsx?|mjs|js)["'`]/;
|
||||
/** `readSourceText(...)` whose argument names a source path literal. */
|
||||
const READ_SOURCE_TEXT_FIXED = new RegExp(
|
||||
String.raw`\breadSourceText\(\s*(?:join\([^)]*?)?` + SOURCE_PATH.source,
|
||||
);
|
||||
/** A local wrapper whose one parameter becomes the `readSourceText` path. */
|
||||
const READ_SOURCE_TEXT_WRAPPER =
|
||||
/(?:function\s+(\w+)|(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?)\s*\(\s*(\w+)\s*(?::\s*string)?[^)]*\)[^{=]*(?:=>|\{)[\s\S]{0,160}?readSourceText\(\s*(?:join\([^)]*?\b\3\b|\3\b)/g;
|
||||
|
||||
/** Whether a test reads a fixed source path through `readSourceText`. */
|
||||
function readsSourceTextByPath(text: string): boolean {
|
||||
if (!text.includes("readSourceText")) return false;
|
||||
if (READ_SOURCE_TEXT_FIXED.test(text)) return true;
|
||||
for (const m of text.matchAll(READ_SOURCE_TEXT_WRAPPER)) {
|
||||
const name = m[1] ?? m[2];
|
||||
if (new RegExp(`\\b${name}\\(\\s*` + SOURCE_PATH.source).test(text)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function asNeverCount(rel: string, text: string): number {
|
||||
if (!text.includes("as never")) return 0;
|
||||
@@ -68,7 +94,9 @@ function classifyTest(rel: string, text: string) {
|
||||
dbMock: routeTest && DB_MOCK.test(text),
|
||||
handlerStub: routeTest && HANDLER_STUB.test(text),
|
||||
asNever: asNeverCount(rel, text),
|
||||
sourceRead: READS_FILE.test(text) && SOURCE_PATH.test(text),
|
||||
sourceRead:
|
||||
(READS_FILE.test(text) && SOURCE_PATH.test(text)) ||
|
||||
readsSourceTextByPath(text),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -143,6 +171,8 @@ describe("test realism ratchet", () => {
|
||||
});
|
||||
|
||||
const READ_CALL = ["read", "File", "Sync"].join("");
|
||||
// Split for the same reason: this file must not match its own pattern.
|
||||
const READ_TEXT = ["read", "Source", "Text"].join("");
|
||||
|
||||
describe("the classifier", () => {
|
||||
it("sees the shapes it counts", () => {
|
||||
@@ -182,6 +212,32 @@ describe("the classifier", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("counts a fixed path read through the unanchored reader", () => {
|
||||
const direct = `const src = ${READ_TEXT}(join(SRC, "lib/x.ts"));`;
|
||||
const wrapped = [
|
||||
`function read(rel: string): string {`,
|
||||
` return ${READ_TEXT}(join(SRC, rel));`,
|
||||
`}`,
|
||||
`const src = read("lib/api-handler.ts");`,
|
||||
].join("\n");
|
||||
expect(classifyTest("__tests__/a.test.ts", direct).sourceRead).toBe(true);
|
||||
expect(classifyTest("__tests__/a.test.ts", wrapped).sourceRead).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves an anchored read and a sweep through the reader alone", () => {
|
||||
const anchored = 'const src = readSource("src/lib/x.ts", "anchor");';
|
||||
const sweep = [
|
||||
`function read(rel: string): string {`,
|
||||
` return ${READ_TEXT}(join(SRC, rel));`,
|
||||
`}`,
|
||||
`for (const rel of walkSourceFiles(SRC, { floor: 10 })) read(rel);`,
|
||||
].join("\n");
|
||||
expect(classifyTest("__tests__/a.test.ts", anchored).sourceRead).toBe(
|
||||
false,
|
||||
);
|
||||
expect(classifyTest("__tests__/a.test.ts", sweep).sourceRead).toBe(false);
|
||||
});
|
||||
|
||||
it("counts a relative database mock and only under app/api", () => {
|
||||
expect(
|
||||
classifyTest(
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* `scripts/verify-message-catalogs.mjs`, which the image build runs in the
|
||||
* builder and again in the runner stage, passes the shipped catalogs and fails
|
||||
* on a missing or corrupt one. A check that cannot fail would let an image
|
||||
* without its catalogs through, so both directions are pinned.
|
||||
*/
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
const SCRIPT = join(process.cwd(), "scripts", "verify-message-catalogs.mjs");
|
||||
const CONFIG = join(process.cwd(), "src", "lib", "i18n", "config.ts");
|
||||
|
||||
function run(args: string[]) {
|
||||
return spawnSync(process.execPath, [SCRIPT, ...args], { encoding: "utf8" });
|
||||
}
|
||||
|
||||
let scratch: string | null = null;
|
||||
afterEach(() => {
|
||||
if (scratch) rmSync(scratch, { recursive: true, force: true });
|
||||
scratch = null;
|
||||
});
|
||||
|
||||
describe("verify-message-catalogs", () => {
|
||||
it("passes the catalogs in the tree and writes the locale list", () => {
|
||||
scratch = mkdtempSync(join(tmpdir(), "hl-catalog-check-"));
|
||||
const list = join(scratch, "locales");
|
||||
const res = run([
|
||||
"--dir",
|
||||
join(process.cwd(), "messages"),
|
||||
"--config",
|
||||
CONFIG,
|
||||
"--write",
|
||||
list,
|
||||
]);
|
||||
expect(res.status).toBe(0);
|
||||
expect(res.stdout).toMatch(/message catalogs ok: .*\ben\b/);
|
||||
|
||||
// The runner-stage form, against the list the builder wrote.
|
||||
expect(
|
||||
run(["--dir", join(process.cwd(), "messages"), "--locales", list]).status,
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
it("fails on a missing catalog and on one that does not parse", () => {
|
||||
scratch = mkdtempSync(join(tmpdir(), "hl-catalog-check-"));
|
||||
const dir = join(scratch, "messages");
|
||||
mkdirSync(dir);
|
||||
writeFileSync(join(dir, "en.json"), "{}");
|
||||
writeFileSync(join(dir, "de.json"), '{"common": ');
|
||||
const list = join(scratch, "locales");
|
||||
writeFileSync(list, "en\nde\nfr\n");
|
||||
|
||||
const res = run(["--dir", dir, "--locales", list]);
|
||||
expect(res.status).toBe(1);
|
||||
expect(res.stderr).toMatch(/de\.json: does not parse/);
|
||||
expect(res.stderr).toMatch(/fr\.json: missing/);
|
||||
expect(res.stderr).not.toMatch(/en\.json/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* A workflow step that pipes a command into `tee` runs with pipefail.
|
||||
*
|
||||
* GitHub runs a `run:` script with `bash -e {0}` unless the step names a
|
||||
* shell, and without pipefail a pipeline's exit status is its last command's.
|
||||
* `tee` always succeeds, so `node scripts/mutation-floors.mjs | tee -a
|
||||
* "$GITHUB_STEP_SUMMARY"` passed whatever the floors said. A step that names
|
||||
* `shell: bash` runs as `bash --noprofile --norc -eo pipefail {0}`; this guard
|
||||
* asks for that and for `set -o pipefail` in the script as well, so the
|
||||
* intent is visible where the pipe is.
|
||||
*/
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import YAML from "yaml";
|
||||
|
||||
const WORKFLOWS = join(process.cwd(), ".github", "workflows");
|
||||
|
||||
interface Step {
|
||||
name?: string;
|
||||
run?: string;
|
||||
shell?: string;
|
||||
}
|
||||
|
||||
/** Whether a script pipes something into `tee` on a line that is not a comment. */
|
||||
function pipesIntoTee(script: string): boolean {
|
||||
return script
|
||||
.split("\n")
|
||||
.some((line) => !/^\s*#/.test(line) && /[^|]\|\s*tee\b/.test(line));
|
||||
}
|
||||
|
||||
/** The steps of a workflow that pipe into `tee` without pipefail. */
|
||||
function offenders(file: string, text: string): string[] {
|
||||
const doc = YAML.parse(text) as {
|
||||
defaults?: { run?: { shell?: string } };
|
||||
jobs?: Record<
|
||||
string,
|
||||
{ defaults?: { run?: { shell?: string } }; steps?: Step[] }
|
||||
>;
|
||||
};
|
||||
const out: string[] = [];
|
||||
for (const [jobName, job] of Object.entries(doc.jobs ?? {})) {
|
||||
(job.steps ?? []).forEach((step, index) => {
|
||||
if (!step.run || !pipesIntoTee(step.run)) return;
|
||||
const shell =
|
||||
step.shell ?? job.defaults?.run?.shell ?? doc.defaults?.run?.shell;
|
||||
const ok = shell === "bash" && /\bset -o pipefail\b/.test(step.run);
|
||||
if (!ok) out.push(`${file} ${jobName} #${index} ${step.name ?? ""}`);
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function workflowFiles(): string[] {
|
||||
return readdirSync(WORKFLOWS).filter((f) => /\.ya?ml$/.test(f));
|
||||
}
|
||||
|
||||
describe("workflow steps that pipe into tee", () => {
|
||||
it("reads the workflows it claims to check", () => {
|
||||
expect(workflowFiles().length).toBeGreaterThan(10);
|
||||
const teeSteps = workflowFiles().filter((f) =>
|
||||
pipesIntoTee(readFileSync(join(WORKFLOWS, f), "utf8")),
|
||||
);
|
||||
expect(teeSteps.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("run with pipefail", () => {
|
||||
const found = workflowFiles().flatMap((f) =>
|
||||
offenders(f, readFileSync(join(WORKFLOWS, f), "utf8")),
|
||||
);
|
||||
expect(found).toEqual([]);
|
||||
});
|
||||
|
||||
it("catches the shape it guards against", () => {
|
||||
const bad = [
|
||||
"jobs:",
|
||||
" check:",
|
||||
" steps:",
|
||||
" - name: floors",
|
||||
' run: node scripts/mutation-floors.mjs | tee -a "$GITHUB_STEP_SUMMARY"',
|
||||
].join("\n");
|
||||
expect(offenders("bad.yml", bad)).toEqual(["bad.yml check #0 floors"]);
|
||||
const good = [
|
||||
"jobs:",
|
||||
" check:",
|
||||
" steps:",
|
||||
" - name: floors",
|
||||
" shell: bash",
|
||||
" run: |",
|
||||
" set -o pipefail",
|
||||
' node scripts/mutation-floors.mjs | tee -a "$GITHUB_STEP_SUMMARY"',
|
||||
].join("\n");
|
||||
expect(offenders("good.yml", good)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -31,11 +31,21 @@ const SRC = join(process.cwd(), "src");
|
||||
const PICKER = "lib/measurements/pick-canonical-workout-rows.ts";
|
||||
|
||||
/**
|
||||
* Every production call site of the picker, frozen.
|
||||
* The only module that hands rows to the picker: the windowed reader, which
|
||||
* picks over rows it read with the duplicate-window margin. Every surface goes
|
||||
* through it, and its output types make a read without the margin a compile
|
||||
* error. The strain engine's per-cluster impulse sum lives there too and is
|
||||
* handed the rows of the engine's own windowed read.
|
||||
*/
|
||||
const PICKER_CALLERS = ["lib/workouts/canonical-read.ts"];
|
||||
|
||||
/**
|
||||
* Every production read that decides which workout is canonical, frozen.
|
||||
*
|
||||
* Adding a surface that collapses workouts is a deliberate act: it must fetch
|
||||
* the identity fields or it silently disagrees with every other surface. Adding
|
||||
* the file here is the acknowledgement.
|
||||
* Adding a surface that collapses workouts is a deliberate act: it must read
|
||||
* through `readWorkoutsAroundRange` and fetch the identity fields, or it
|
||||
* silently disagrees with every other surface. Adding the file here is the
|
||||
* acknowledgement. The value is the file that owns the read's `select`.
|
||||
*/
|
||||
const IDENTITY_OWNER: Record<string, string> = {
|
||||
"app/api/workouts/[id]/route.ts": "app/api/workouts/[id]/route.ts",
|
||||
@@ -49,15 +59,15 @@ const IDENTITY_OWNER: Record<string, string> = {
|
||||
// The activity calendar counts workouts per day; a session two devices
|
||||
// recorded must count once there, as it does in the list.
|
||||
"lib/activity/calendar-read.ts": "lib/activity/calendar-read.ts",
|
||||
// The only indirection in the set. The Coach block is handed rows it does not
|
||||
// read itself; the snapshot builder fetches them in parallel with every other
|
||||
// block's data. Recording the owner here rather than assuming the call site
|
||||
// owns its own select is the whole point of this map.
|
||||
"lib/ai/coach/snapshot-blocks/workouts-block.ts": "lib/ai/coach/snapshot.ts",
|
||||
// The write path: the batch route runs the same picker over the rows it is
|
||||
// about to insert, so a duplicate inside one batch is dropped by the rule
|
||||
// the list later applies.
|
||||
"app/api/workouts/batch/route.ts": "app/api/workouts/batch/route.ts",
|
||||
// The Coach block is handed rows it does not read itself; the snapshot
|
||||
// builder fetches them through this read in parallel with every other
|
||||
// block's data.
|
||||
"lib/ai/coach/snapshot-blocks/workouts-read.ts":
|
||||
"lib/ai/coach/snapshot-blocks/workouts-read.ts",
|
||||
// The write path: the batch route clusters the rows it is about to insert
|
||||
// together with the stored rows around them, so a duplicate is dropped by
|
||||
// the rule the list later applies.
|
||||
"lib/workouts/batch-dedup.ts": "lib/workouts/batch-dedup.ts",
|
||||
// The day-total training impulse, the briefing's workout tally and the day
|
||||
// view's workout section: each counted a session synced by two services
|
||||
// twice while the list showed it once.
|
||||
@@ -72,10 +82,16 @@ const IDENTITY_OWNER: Record<string, string> = {
|
||||
|
||||
/**
|
||||
* How a call site proves its rows carry the duration. A read selects the
|
||||
* column; the batch route maps it off the row it computed for the insert.
|
||||
* column; the batch route also maps it off the row it computed for the insert.
|
||||
*/
|
||||
const IDENTITY_PROOF: Record<string, string> = {
|
||||
"app/api/workouts/batch/route.ts": "durationSec: p.row.durationSec",
|
||||
const IDENTITY_PROOF: Record<string, string[]> = {
|
||||
// These two select `WORKOUT_PICK_SELECT`, whose duration is checked below.
|
||||
"lib/day/records.ts": ["select: WORKOUT_PICK_SELECT"],
|
||||
"lib/insights/correlation-channel-series.ts": ["select: WORKOUT_PICK_SELECT"],
|
||||
"lib/workouts/batch-dedup.ts": [
|
||||
"durationSec: true",
|
||||
"durationSec: p.row.durationSec",
|
||||
],
|
||||
};
|
||||
|
||||
const EXPECTED_CALL_SITES = Object.keys(IDENTITY_OWNER).sort();
|
||||
@@ -93,17 +109,13 @@ function read(rel: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Lines that actually invoke the picker. Comment lines are excluded: a
|
||||
* docblock that names the picker is documentation rather than a call.
|
||||
* Lines that actually invoke `call`. Comment lines are excluded: a docblock
|
||||
* that names the function is documentation rather than a call.
|
||||
*/
|
||||
function invokesPicker(source: string): boolean {
|
||||
function invokes(source: string, call: string): boolean {
|
||||
return source
|
||||
.split("\n")
|
||||
.some(
|
||||
(line) =>
|
||||
line.includes("pickCanonicalWorkoutRows(") &&
|
||||
!/^\s*(\*|\/\/|\/\*)/.test(line),
|
||||
);
|
||||
.some((line) => line.includes(call) && !/^\s*(\*|\/\/|\/\*)/.test(line));
|
||||
}
|
||||
|
||||
describe("the picker's call-site set is frozen", () => {
|
||||
@@ -114,13 +126,29 @@ describe("the picker's call-site set is frozen", () => {
|
||||
expect(sourceFiles().length).toBeGreaterThan(1500);
|
||||
});
|
||||
|
||||
it("has exactly the call sites this file acknowledges", () => {
|
||||
it("hands rows to the picker only from the windowed reader", () => {
|
||||
const found = sourceFiles()
|
||||
.filter((rel) => rel !== PICKER)
|
||||
.filter((rel) => invokesPicker(read(rel)));
|
||||
.filter((rel) => invokes(read(rel), "pickCanonicalWorkoutRows("));
|
||||
|
||||
expect(found).toEqual(PICKER_CALLERS);
|
||||
});
|
||||
|
||||
it("has exactly the windowed reads this file acknowledges", () => {
|
||||
const found = sourceFiles()
|
||||
.filter((rel) => rel !== "lib/workouts/canonical-read.ts")
|
||||
.filter((rel) => invokes(read(rel), "readWorkoutsAroundRange("));
|
||||
|
||||
expect(found).toEqual(EXPECTED_CALL_SITES);
|
||||
});
|
||||
|
||||
it("scores strain only on the sessions of the windowed range", () => {
|
||||
// The strain engine sums impulses over the rows of its windowed read; it
|
||||
// must keep the sessions its range owns, not every cluster the margin read.
|
||||
expect(read("lib/insights/strain-score.ts")).toContain(
|
||||
"(at) => startsInRange(workouts.range, at)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("every call site fetches the session identity", () => {
|
||||
@@ -130,9 +158,20 @@ describe("every call site fetches the session identity", () => {
|
||||
// rows came from. Coarse in the safe direction — it can only fail to catch
|
||||
// a second unrelated select in the same file, never pass a caller that
|
||||
// fetches no duration at all.
|
||||
expect(read(IDENTITY_OWNER[rel])).toContain(
|
||||
IDENTITY_PROOF[rel] ?? "durationSec: true",
|
||||
for (const proof of IDENTITY_PROOF[rel] ?? ["durationSec: true"]) {
|
||||
expect(read(IDENTITY_OWNER[rel])).toContain(proof);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("the shared pick select carries the identity", () => {
|
||||
it("selects durationSec", () => {
|
||||
const reader = read("lib/workouts/canonical-read.ts");
|
||||
const select = reader.slice(
|
||||
reader.indexOf("export const WORKOUT_PICK_SELECT"),
|
||||
reader.indexOf("} as const;"),
|
||||
);
|
||||
expect(select).toContain("durationSec: true");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user