Merge branch 'fix/v1475-cleanup' into release/v1.47.5

# 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:
Marc-André Bombeck committed 2026-11-11 22:51:42 +01:00
commit d5dd05b5ac
164 files changed
+1109 -15288

No files matched your search

+1 -1
View File
@@ -51,7 +51,7 @@ import {
stripComments,
walkSourceFiles,
} from "./helpers/source-files";
import { QUEUE_RUNTIME, type QueueRuntime } from "@/lib/jobs/queue-runtime";
import { QUEUE_RUNTIME, type QueueRuntime } from "./helpers/queue-runtime";
import {
COMPLETION_CEILING_MS,
COMPREHENSIVE_WARM_CEILING_MS,
@@ -10,7 +10,23 @@ import {
NOT_IN_BACKUP_MODELS,
RAW_SQL_TABLES,
} from "@/lib/export/backup-plan";
import { backupVerdict } from "@/lib/export/backup-verdict";
type BackupVerdict = "BACKED_UP" | "DERIVED" | "NOT_IN_BACKUP" | "AUTH";
/**
* The verdict for a model, or `null` when the schema carries a model the plan
* has never ruled on. The guard below turns that `null` into a failing test:
* a new model gets a decision, not a default.
*/
function backupVerdict(model: string): BackupVerdict | null {
if ((BACKED_UP_MODELS as readonly string[]).includes(model)) {
return "BACKED_UP";
}
if (model in DERIVED_MODELS) return "DERIVED";
if (model in NOT_IN_BACKUP_MODELS) return "NOT_IN_BACKUP";
if (AUTH_MODELS_OUT_OF_SCOPE.includes(model)) return "AUTH";
return null;
}
/**
* Every model in the schema has a written verdict about the backup.
@@ -1,7 +1,7 @@
{
"$comment": "Production files over 800 lines and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
"count": 84,
"total": 93830,
"total": 93802,
"entries": {
"app/medications/page-client.tsx": 839,
"components/charts/mood-chart.tsx": 1166,
@@ -13,7 +13,7 @@
"components/insights/health-score-card.tsx": 1023,
"components/insights/insights-tab-strip.tsx": 1084,
"components/measurements/measurement-form.tsx": 815,
"components/medications/detail/medication-detail-tabs.tsx": 1157,
"components/medications/detail/medication-detail-tabs.tsx": 1129,
"components/medications/medication-table.tsx": 853,
"components/medications/wizard/wizard-payload.ts": 1414,
"components/mood/mood-list.tsx": 1408,
@@ -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": 336,
"total": 109328,
"total": 109312,
"entries": {
"app/achievements/page.tsx :: AchievementsPage": 206,
"app/api/admin/backups/upload/route.ts :: apiHandler(arg)": 275,
@@ -145,10 +145,10 @@
"components/measurement-reminders/vorsorge-section.tsx :: VorsorgeSection": 352,
"components/measurements/measurement-form.tsx :: MeasurementForm": 496,
"components/medications/detail/efficacy/efficacy-chart.tsx :: EfficacyChart": 361,
"components/medications/detail/medication-detail-tabs.tsx :: MedicationDetailTabs": 767,
"components/medications/detail/medication-detail-tabs.tsx :: MedicationDetailTabs": 760,
"components/medications/dose-history-add-dialog.tsx :: LedgerAddDialog": 221,
"components/medications/dose-strength-curve.tsx :: DoseStrengthCurve": 266,
"components/medications/glp1-medication-card.tsx :: Glp1MedicationCard": 405,
"components/medications/glp1-medication-card.tsx :: Glp1MedicationCard": 396,
"components/medications/injection-site-picker.tsx :: InjectionSitePicker": 287,
"components/medications/intake-history-list-v2.tsx :: IntakeHistoryListV2": 403,
"components/medications/intake-import-dialog.tsx :: IntakeImportDialog": 201,
+2 -2
View File
@@ -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": 523,
"total": 5459,
"total": 5458,
"entries": {
"__tests__/api/auth/login/mfa-branch.test.ts": 10,
"__tests__/api/auth/mfa/verify.test.ts": 9,
@@ -496,7 +496,7 @@
"lib/medications/scheduling/__tests__/dose-history.test.ts": 1,
"lib/medications/scheduling/__tests__/pin-conflict.test.ts": 2,
"lib/modules/__tests__/measurement-scope.test.ts": 3,
"lib/notifications/__tests__/admin-locale.test.ts": 7,
"lib/notifications/__tests__/admin-locale.test.ts": 6,
"lib/notifications/__tests__/client-managed-apns.test.ts": 9,
"lib/notifications/__tests__/dispatch-localised-cache.test.ts": 5,
"lib/notifications/__tests__/dispatcher-global-channel-switch.test.ts": 8,
@@ -1,7 +1,7 @@
{
"$comment": "tests that read a source file by path, per test file under src/. Maintained by src/__tests__/test-realism-ratchet.test.ts.",
"count": 337,
"total": 337,
"count": 332,
"total": 332,
"entries": {
"__tests__/account-payload-consumer-guard.test.ts": 1,
"__tests__/admin-data-wipe-completeness.test.ts": 1,
@@ -87,7 +87,6 @@
"__tests__/module-gate-record-scoped.test.ts": 1,
"__tests__/mood-backup-completeness.test.ts": 1,
"__tests__/mood-prediction-write-surface-guard.test.ts": 1,
"__tests__/moodlog-removal-guard.test.ts": 1,
"__tests__/next-image-optimizer-guard.test.ts": 1,
"__tests__/no-server-actions-guard.test.ts": 1,
"__tests__/oidc-native-error-reasons-documented.test.ts": 1,
@@ -141,7 +140,6 @@
"__tests__/unit-preference-display-guard.test.ts": 1,
"__tests__/unit-suite-browser-install-guard.test.ts": 1,
"__tests__/utc-day-key-allowlist-guard.test.ts": 1,
"__tests__/v1341-locale-parity.test.ts": 1,
"__tests__/visit-link-guard.test.ts": 1,
"__tests__/workout-canonical-identity-guard.test.ts": 1,
"__tests__/write-rate-limit-guard.test.ts": 1,
@@ -174,7 +172,6 @@
"app/insights/__tests__/page-skeletons.test.ts": 1,
"app/insights/sleep/__tests__/empty-state-href.test.ts": 1,
"app/measurements/__tests__/add-token-resolution.test.ts": 1,
"app/medications/__tests__/detail-page-history-surface.test.ts": 1,
"components/__tests__/design-consistency-guards.test.tsx": 1,
"components/__tests__/failed-read-never-empty.test.tsx": 1,
"components/__tests__/motion-reduce-spin-coverage.test.ts": 1,
@@ -182,7 +179,6 @@
"components/admin/__tests__/notification-test-failures.test.ts": 1,
"components/charts/__tests__/chart-error-state.test.tsx": 1,
"components/charts/__tests__/health-chart-overlay-defaults.test.tsx": 1,
"components/charts/__tests__/health-chart-target-link-removed.test.ts": 1,
"components/charts/__tests__/mood-chart-polish.test.tsx": 1,
"components/charts/__tests__/touch-action-guard.test.ts": 1,
"components/cycle/__tests__/use-cycle-ring-has-dial.test.tsx": 1,
@@ -206,7 +202,6 @@
"components/insights/coach-panel/__tests__/open-at-end.test.ts": 1,
"components/insights/coach-panel/__tests__/panel-touch-targets.test.ts": 1,
"components/insights/coach-panel/__tests__/scroll-to-bottom-button.test.tsx": 1,
"components/insights/mood/__tests__/mood-notes-timeline-removed.test.ts": 1,
"components/layout/__tests__/auth-shell-coach-hoist.test.ts": 1,
"components/layout/__tests__/auth-shell-shared-record-doors.test.tsx": 1,
"components/layout/__tests__/offline-banner.test.tsx": 1,
@@ -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": 2883,
"total": 9186,
"count": 2876,
"total": 9172,
"entries": {
"__tests__/account-payload-consumer-guard.test.ts": 2,
"__tests__/acting-account-boundary-guard.test.ts": 7,
@@ -68,7 +68,6 @@
"__tests__/success-affordance-guard.test.ts": 8,
"__tests__/timezone-explicit-formatter-guard.test.ts": 1,
"__tests__/unit-preference-display-guard.test.ts": 2,
"__tests__/v1341-locale-parity.test.ts": 1,
"__tests__/v1391-additive-contract.test.ts": 1,
"__tests__/write-rate-limit-guard.test.ts": 1,
"app/__tests__/dashboard-analytics-split.test.ts": 2,
@@ -654,7 +653,6 @@
"app/mcp/__tests__/route.test.ts": 5,
"app/measurements/page.tsx": 5,
"app/medications/__tests__/category-filter.test.tsx": 2,
"app/medications/__tests__/detail-page-history-surface.test.ts": 1,
"app/medications/__tests__/list-view-toggle.test.tsx": 5,
"app/medications/__tests__/page-prefetch.test.tsx": 1,
"app/medications/__tests__/take-all-due-affordance.test.tsx": 1,
@@ -735,7 +733,6 @@
"components/charts/__tests__/health-chart-polish.test.tsx": 2,
"components/charts/__tests__/health-chart-preloaded-coverage.test.tsx": 1,
"components/charts/__tests__/health-chart-range.test.tsx": 3,
"components/charts/__tests__/health-chart-target-link-removed.test.ts": 1,
"components/charts/__tests__/health-chart-vertical-markers.test.ts": 1,
"components/charts/__tests__/medication-chart-polish.test.tsx": 1,
"components/charts/__tests__/medication-compliance-chart-empty-state-gate.test.tsx": 1,
@@ -1001,7 +998,6 @@
"components/insights/mood/__tests__/mood-discovered-relations.test.tsx": 3,
"components/insights/mood/__tests__/mood-insights-sections-in-target.test.tsx": 1,
"components/insights/mood/__tests__/mood-insights-sections-reveal.test.tsx": 1,
"components/insights/mood/__tests__/mood-notes-timeline-removed.test.ts": 4,
"components/insights/mood/__tests__/mood-tag-bars-muted.test.tsx": 1,
"components/insights/mood/mood-better-days.tsx": 2,
"components/insights/mood/mood-correlation-cards.tsx": 3,
@@ -1127,7 +1123,7 @@
"components/medications/__tests__/inventory-section-actions.test.tsx": 1,
"components/medications/__tests__/inventory-section-summary.test.tsx": 2,
"components/medications/__tests__/log-injection-site-dialog.test.tsx": 1,
"components/medications/__tests__/medication-card-glp1.test.tsx": 14,
"components/medications/__tests__/medication-card-glp1.test.tsx": 12,
"components/medications/__tests__/medication-card-header.test.tsx": 1,
"components/medications/__tests__/medication-card-next-due.test.tsx": 4,
"components/medications/__tests__/medication-card-symmetry.test.tsx": 4,
@@ -1164,7 +1160,7 @@
"components/medications/log-injection-site-dialog.tsx": 2,
"components/medications/log-intake-dialog.tsx": 4,
"components/medications/medication-card-header.tsx": 5,
"components/medications/medication-card-menu.tsx": 3,
"components/medications/medication-card-menu.tsx": 2,
"components/medications/medication-card.tsx": 37,
"components/medications/medication-categories-sheet.tsx": 1,
"components/medications/medication-category-add-row.tsx": 1,
@@ -2367,7 +2363,6 @@
"lib/labs/__tests__/note-update.test.ts": 1,
"lib/labs/biomarker-catalog.ts": 10,
"lib/labs/biomarker-store.ts": 2,
"lib/labs/homa-ir.ts": 1,
"lib/labs/lab-trend.ts": 1,
"lib/labs/local-ocr.ts": 1,
"lib/labs/note-update.ts": 1,
@@ -2691,7 +2686,7 @@
"lib/queries/use-profile-claim.ts": 4,
"lib/query-keys/admin.ts": 12,
"lib/query-keys/ai-runs.ts": 1,
"lib/query-keys/auth.ts": 9,
"lib/query-keys/auth.ts": 8,
"lib/query-keys/coach.ts": 13,
"lib/query-keys/custom-metrics.ts": 1,
"lib/query-keys/cycle.ts": 1,
@@ -2768,11 +2763,9 @@
"lib/sync/cursor.ts": 1,
"lib/targets/__tests__/builders.test.ts": 1,
"lib/targets/__tests__/glucose-targets.test.ts": 1,
"lib/targets/__tests__/mood-stability-label.test.ts": 1,
"lib/targets/__tests__/source-link.test.ts": 1,
"lib/targets/__tests__/target-unit-display.test.ts": 1,
"lib/targets/build-response.ts": 3,
"lib/targets/mood-stability-label.ts": 1,
"lib/targets/target-unit-display.ts": 2,
"lib/targets/types.ts": 2,
"lib/targets/vitals-builder.ts": 2,
@@ -215,7 +215,7 @@ describe("the customise shortcut is withheld inside somebody else's record", ()
export function Page() {
const { inSharedRecord } = useRecordCapabilities();
const wrench = !inSharedRecord ? (
<Link href="/settings/layout/vorsorge">Customise</Link>
<Link href="/settings/layout/checkups">Customise</Link>
) : null;
return wrench;
}
+626
View File
@@ -0,0 +1,626 @@
/**
* How long one job of each queue can run, and what keeps a long one safe.
*
* pg-boss gives every job an expiry, fifteen minutes unless the send says
* otherwise. Past it pg-boss fails the job, fires its abort signal and retries
* it, and it does not stop the handler, so a job that legitimately needs longer
* ends up running twice beside itself. No queue policy prevents that: the
* policies constrain job rows, and an expired row is no longer active. Every
* queue the worker registry declares is therefore declared here as one of:
*
* - `short`: a job cannot come near fifteen minutes (one account's bounded
* window, one document, a forwarder, a bounded delete). It relies on the
* default expiry, and the reason says why that is enough.
* - `budgeted`: a pass over a long history that stops itself at three
* quarters of the default expiry (`jobBudget`) and hands the rest to its
* next run, so it ends before fifteen minutes by construction.
* - `bounded`: one unit of model work (one account's note, refresh or
* memory pass, a document summary) whose calls wait the person's
* response timeout each, up to ten minutes, which can outlast fifteen
* minutes. Every call carries its own abort and most sit behind an outer
* bound, so the job's longest run is known (`modelSeconds`, from
* `model-time.ts`); it carries an explicit
* `expireInSeconds` above that on every send, and no retry can start
* beside a run that is still going (#1274).
* - `long`: a job that may run for hours. It carries an explicit
* `expireInSeconds` on every send and schedule, stops itself before that
* expiry (`jobBudget` / `jobDeadline`), and holds something per identity
* that keeps a second run from working beside it: the lock `lockedPass`
* takes, a lock of its own, or a row it claims. The one exception is a
* one-shot job with `retryLimit: 0`, which pg-boss never retries and which
* cannot stop half-way without losing its input.
*
* `src/__tests__/job-queue-runtime-guard.test.ts` holds every binding, send
* and schedule in the tree to this table.
*/
import { INTEGRATION_BACKFILL_EXPIRE_SECONDS } from "@/lib/jobs/integration-backfill-admission";
import { NIGHTLY_INSIGHT_PASS_EXPIRE_SECONDS } from "@/lib/jobs/reminder/registrar-shared";
import { INSIGHT_PREGENERATE_EXPIRE_SECONDS } from "@/lib/jobs/insight-pregenerate-shared";
import { PERIOD_NARRATIVE_EXPIRE_SECONDS } from "@/lib/jobs/period-narrative-queue";
import { PR_DETECTION_EXPIRE_SECONDS } from "@/lib/jobs/pr-detection";
import { ENCRYPTION_KEY_ROTATE_EXPIRE_SECONDS } from "@/lib/jobs/encryption-key-rotate";
import { CONTENT_INDEX_BACKFILL_EXPIRE_SECONDS } from "@/lib/jobs/document-content-index-backfill";
import { DOCUMENT_AI_RUN_EXPIRE_SECONDS } from "@/lib/jobs/document-ai-run";
import { DATA_BACKUP_SEND_OPTIONS } from "@/lib/jobs/data-backup-policy";
import { DATABASE_BACKUP_EXPIRE_SECONDS } from "@/lib/jobs/database-backup-queue";
import { OFFHOST_BACKUP_EXPIRE_SECONDS } from "@/lib/jobs/offhost-backup-queue";
import { BACKUP_RESTORE_EXPIRE_SECONDS } from "@/lib/jobs/backup-restore";
import { RESTORE_DRILL_EXPIRE_SECONDS } from "@/lib/jobs/restore-drill-queue";
import { APPLE_HEALTH_IMPORT_SEND_OPTIONS } from "@/lib/jobs/apple-health-import-worker";
import { MEDICATION_INTAKE_IMPORT_SEND_OPTIONS } from "@/lib/jobs/medication-intake-import";
import { HEALTH_CONNECT_IMPORT_SEND_OPTIONS } from "@/lib/jobs/health-connect-import-worker";
import { MEASUREMENT_MAINTENANCE_SEND_OPTIONS } from "@/lib/jobs/measurement-maintenance";
import { PULSE_DAY_MEAN_SEND_OPTIONS } from "@/lib/jobs/pulse-day-mean";
import { ROLLUP_FULL_BACKFILL_EXPIRE_SECONDS } from "@/lib/rollups/full-backfill";
import { MORNING_DIGEST_REFRESH_EXPIRE_SECONDS } from "@/lib/jobs/morning-digest-refresh-shared";
import { INSIGHT_STATUS_GENERATE_EXPIRE_SECONDS } from "@/lib/jobs/insight-status-generate-queue";
import { WORKOUT_INSIGHT_GENERATE_EXPIRE_SECONDS } from "@/lib/jobs/workout-insight-generate-shared";
import {
COACH_MEMORY_MODEL_RUNS,
COACH_MEMORY_REFRESH_EXPIRE_SECONDS,
} from "@/lib/ai/coach/coach-memory-shared";
import {
COMPLETION_CEILING_MS,
COMPREHENSIVE_WARM_CEILING_MS,
} from "@/lib/jobs/model-time";
import { DOCUMENT_INDEX_EXPIRE_SECONDS } from "@/lib/jobs/document-index-queue";
import { DOCUMENT_SUMMARY_EXPIRE_SECONDS } from "@/lib/jobs/document-summary-queue";
/** pg-boss's default job expiry, in seconds. */
export const DEFAULT_JOB_EXPIRE_SECONDS = 15 * 60;
/** Where a check lives: a function (or const) in a file under `src/`. */
export type SourceSite = { file: string; fn: string };
export type QueueRuntime =
| { runtime: "short"; why: string }
| { runtime: "budgeted"; budget: SourceSite; why: string }
| {
runtime: "bounded";
/**
* The longest the job's model work runs at the largest response-timeout
* setting, in seconds: the outer bounds in the code, not an estimate.
*/
modelSeconds: number;
expireInSeconds: number;
/** As for `long`: identifiers that carry the expiry into a send. */
expiryVia: readonly string[];
why: string;
}
| {
runtime: "long";
expireInSeconds: number;
/**
* Identifiers that carry the expiry into a send or a schedule. A site
* that names none of them must set `expireInSeconds` itself.
*/
expiryVia: readonly string[];
/** Where the handler stops on the job's budget, or `oneShot`. */
stop: SourceSite | { oneShot: string };
/**
* What keeps a second run from working beside this one: the `lock`
* its registry definition declares (`lockedPass`), or a marker in the
* named function.
*/
exclusive: "lockedPass" | { marker: string; at: SourceSite };
why: string;
};
const short = (why: string): QueueRuntime => ({ runtime: "short", why });
const cohortSync = (provider: string): QueueRuntime =>
short(
`${provider} sync: a recent window per connection (incremental since the last sync); a webhook job is one connection.`,
);
const oauthStateCleanup = short("One DELETE of expired OAuth state rows.");
const forwarder = short(
"Forwards each job to integration-backfill-admission; the import itself runs there.",
);
export const QUEUE_RUNTIME: Readonly<Record<string, QueueRuntime>> = {
// ── Integration sync ───────────────────────────────────────────────
"integration-backfill-admission": {
runtime: "long",
expireInSeconds: INTEGRATION_BACKFILL_EXPIRE_SECONDS,
expiryVia: ["integrationBackfillAdmissionSendOptions"],
stop: {
file: "lib/jobs/integration-backfill-drain.ts",
fn: "drainIntegrationBackfillAdmission",
},
exclusive: {
marker: "withIntegrationBackfillLock",
at: {
file: "lib/jobs/integration-backfill-drain.ts",
fn: "drainIntegrationBackfillAdmission",
},
},
why: "Full-history provider imports: thousands of pages on a dense account.",
},
"withings-fallback-sync": cohortSync("Withings"),
"withings-activity-sync": cohortSync("Withings activity"),
"withings-sleep-sync": cohortSync("Withings sleep"),
"withings-ecg-sync": cohortSync("Withings ECG"),
"withings-oauth-state-cleanup": oauthStateCleanup,
"whoop-recovery-sync": cohortSync("WHOOP recovery"),
"whoop-sleep-sync": cohortSync("WHOOP sleep"),
"whoop-workout-sync": cohortSync("WHOOP workout"),
"whoop-cycle-sync": cohortSync("WHOOP cycle"),
"whoop-backfill": forwarder,
"whoop-oauth-state-cleanup": oauthStateCleanup,
"oidc-native-handoff-cleanup": short("One DELETE of expired handoff rows."),
"fitbit-sync": cohortSync("Fitbit"),
"fitbit-backfill": forwarder,
"fitbit-sleep-repair": forwarder,
"fitbit-oauth-state-cleanup": oauthStateCleanup,
"google-health-sync": cohortSync("Google Health"),
"google-health-backfill": forwarder,
"google-health-sleep-repair": forwarder,
"google-health-oauth-state-cleanup": oauthStateCleanup,
"sleep-timeline-backfill": forwarder,
"lab-biomarker-backfill": forwarder,
"nightscout-sync": cohortSync("Nightscout"),
"polar-sync": cohortSync("Polar"),
"oura-sync": cohortSync("Oura"),
"strava-sync": cohortSync("Strava"),
"strava-backfill": forwarder,
"oura-backfill": forwarder,
"garmin-sync": cohortSync("Garmin"),
"garmin-backfill": forwarder,
// ── Status and insights ────────────────────────────────────────────
"insights-general-status": {
runtime: "long",
expireInSeconds: NIGHTLY_INSIGHT_PASS_EXPIRE_SECONDS,
expiryVia: ["nightlyInsightPassOptions"],
stop: {
file: "lib/jobs/reminder/insights-handlers.ts",
fn: "handleGeneralStatusGenerate",
},
exclusive: "lockedPass",
why: "Nightly status batch: one provider call per candidate account, serially, over the whole instance.",
},
"insight-pregenerate": {
runtime: "long",
expireInSeconds: INSIGHT_PREGENERATE_EXPIRE_SECONDS,
expiryVia: ["INSIGHT_PREGENERATE_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/reminder/insights-handlers.ts",
fn: "handleInsightPregenerateJob",
},
exclusive: "lockedPass",
why: "Up to 200 accounts, a comprehensive generation each (up to five provider calls in a row, each bounded by the account's timeout of at most ten minutes) plus the status warm.",
},
"morning-digest-refresh": {
runtime: "bounded",
modelSeconds: COMPREHENSIVE_WARM_CEILING_MS / 1000,
expireInSeconds: MORNING_DIGEST_REFRESH_EXPIRE_SECONDS,
expiryVia: ["MORNING_DIGEST_REFRESH_EXPIRE_SECONDS"],
why: "One account, one forced comprehensive generation: up to five calls in a row at the account's timeout, behind the warm's own bound.",
},
"insight-status-generate": {
runtime: "bounded",
modelSeconds: COMPLETION_CEILING_MS / 1000,
expireInSeconds: INSIGHT_STATUS_GENERATE_EXPIRE_SECONDS,
expiryVia: ["INSIGHT_STATUS_GENERATE_EXPIRE_SECONDS"],
why: "One account, one note: one status run, the call and its one reasoning repeat at the account's timeout.",
},
"data-arrival": short("One arrival's reactions."),
"reaction-line-generate": short("One provider call for one reaction line."),
"workout-insight-generate": {
runtime: "bounded",
modelSeconds: COMPLETION_CEILING_MS / 1000,
expireInSeconds: WORKOUT_INSIGHT_GENERATE_EXPIRE_SECONDS,
expiryVia: ["WORKOUT_INSIGHT_GENERATE_EXPIRE_SECONDS"],
why: "One workout's line: one status run at the account's timeout.",
},
"recovery-score-compute": short(
"Arithmetic over a recent window, capped at 500 accounts; no provider call.",
),
"stress-score-compute": short(
"Arithmetic over a recent window, capped at 500 accounts; no provider call.",
),
"strain-score-compute": short(
"Arithmetic over a recent window, capped at 500 accounts; no provider call.",
),
"period-narrative-warm": {
runtime: "long",
expireInSeconds: PERIOD_NARRATIVE_EXPIRE_SECONDS,
expiryVia: ["PERIOD_NARRATIVE_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/reminder/status-handlers.ts",
fn: "handlePeriodNarrative",
},
exclusive: "lockedPass",
why: "On a boundary night up to 200 accounts with a provider call per period each; a single-account warm is short.",
},
"coach-memory-refresh": {
runtime: "bounded",
modelSeconds: (COACH_MEMORY_MODEL_RUNS * COMPLETION_CEILING_MS) / 1000,
expireInSeconds: COACH_MEMORY_REFRESH_EXPIRE_SECONDS,
expiryVia: ["COACH_MEMORY_REFRESH_EXPIRE_SECONDS"],
why: "One conversation's summary, facts and plan proposals: three status runs in a row at the account's timeout.",
},
"coach-nudge": short(
"Light deterministic checks per account; the provider part is capped at 25 calls and 90 seconds a tick.",
),
"coach-reminder-sweep": short("Batches of 200 to 500 rows, no provider."),
"coach-plan-review": short("A batch of 100 plans, folded in SQL."),
"medication-low-stock": short("A light inventory check per account."),
"daily-briefing": short("A light cohort scan every fifteen minutes."),
// ── Rollups ────────────────────────────────────────────────────────
"rollup-recompute": short(
"One type at one granularity over one bucket or a run of adjacent buckets, inside the five-year fold window.",
),
"rollup-full-backfill": {
runtime: "long",
expireInSeconds: ROLLUP_FULL_BACKFILL_EXPIRE_SECONDS,
expiryVia: ["ROLLUP_FULL_BACKFILL_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/reminder/rollup-handlers.ts",
fn: "handleRollupFullBackfill",
},
exclusive: "lockedPass",
why: "One account's five-year fold, a calendar year at a time with every statement under its own five-minute limit; the run stops at its budget between windows and hands the remaining years to a follow-up.",
},
"mood-rollup-recompute": short("One bucket."),
"mood-rollup-full-backfill": short(
"One account's mood entries, a few a day.",
),
"step-consolidation": short(
"One account's legacy step rows, one transaction per day.",
),
"step-consolidation-repair": short(
"One account's tombstoned step rows inside the retention window.",
),
"supplement-nutrient-recompute": short(
"One account's taken doses of medications with a composition: a few thousand rows for years of a daily supplement.",
),
"cumulative-pr-rederive": short(
"One account's record detection; measured at 20 seconds for 1.25 million rows.",
),
"mean-consolidation": {
runtime: "budgeted",
budget: {
file: "lib/jobs/reminder/rollup-handlers.ts",
fn: "handleMeanConsolidation",
},
why: "One account's whole history, a day at a time; stops at three quarters of the default expiry and resumes.",
},
"dense-intraday-retention": {
runtime: "budgeted",
budget: {
file: "lib/jobs/reminder/rollup-handlers.ts",
fn: "handleDenseIntradayRetention",
},
why: "A dense account's history, a day at a time; stops at three quarters of the default expiry and resumes.",
},
"dense-intraday-hourly-rebuild": {
runtime: "budgeted",
budget: {
file: "lib/jobs/reminder/rollup-handlers.ts",
fn: "handleDenseIntradayHourlyRebuild",
},
why: "A dense account's hourly rows, a day at a time; stops at three quarters of the default expiry and resumes.",
},
"drain-per-sample-cumulative": {
runtime: "budgeted",
budget: {
file: "lib/jobs/reminder/rollup-handlers.ts",
fn: "drainCumulativeHandler",
},
why: "Every account's per-sample drains; stops at three quarters of the default expiry and hands the rest to a continuation job.",
},
// ── Reminders ──────────────────────────────────────────────────────
"medication-reminder-check": short("The due slots of the current minute."),
"mood-reminder-check": short("Accounts whose local reminder hour is now."),
"cycle-reminder-check": short("Accounts whose local reminder hour is now."),
"measurement-reminder-check": short(
"Accounts whose local reminder hour is now.",
),
"reminder-satisfy": short("One account's open reminders."),
// ── Maintenance ────────────────────────────────────────────────────
"data-backup": {
runtime: "long",
expireInSeconds: DATA_BACKUP_SEND_OPTIONS.expireInSeconds,
expiryVia: ["DATA_BACKUP_SEND_OPTIONS"],
stop: {
file: "lib/jobs/reminder/backup-handlers.ts",
fn: "handleDataBackup",
},
exclusive: "lockedPass",
why: "Serialises every account's whole record.",
},
"database-backup": {
runtime: "long",
expireInSeconds: DATABASE_BACKUP_EXPIRE_SECONDS,
expiryVia: ["DATABASE_BACKUP_SEND_OPTIONS"],
stop: {
file: "lib/jobs/reminder/backup-handlers.ts",
fn: "handleDatabaseBackup",
},
exclusive: "lockedPass",
why: "Runs pg_dump over the whole database and uploads the dump off-host.",
},
"data-backup-offhost": {
runtime: "long",
expireInSeconds: OFFHOST_BACKUP_EXPIRE_SECONDS,
expiryVia: ["OFFHOST_BACKUP_SEND_OPTIONS"],
stop: {
file: "lib/jobs/reminder/backup-handlers.ts",
fn: "handleOffhostBackup",
},
exclusive: "lockedPass",
why: "Uploads every account's record off-host.",
},
"data-restore-drill": {
runtime: "long",
expireInSeconds: RESTORE_DRILL_EXPIRE_SECONDS,
expiryVia: ["RESTORE_DRILL_SEND_OPTIONS"],
stop: { file: "lib/jobs/restore-drill.ts", fn: "handleRestoreDrill" },
exclusive: "lockedPass",
why: "Fetches and stream-parses every account's newest off-host object.",
},
"offhost-backup-purge": short("At most 200 delete requests per run."),
"account-deletion-purge": short(
"At most 50 account erasures per run, plus one DELETE of expired pre-wipe copies.",
),
"backup-restore": {
runtime: "long",
expireInSeconds: BACKUP_RESTORE_EXPIRE_SECONDS,
expiryVia: ["BACKUP_RESTORE_SEND_OPTIONS", "BACKUP_RESTORE_EXPIRE_SECONDS"],
stop: { file: "lib/jobs/backup-restore.ts", fn: "handleBackupRestore" },
exclusive: {
marker: "restore_claimed",
at: { file: "lib/jobs/backup-restore.ts", fn: "runBackupRestoreJob" },
},
why: "Restores a whole account in one transaction.",
},
"host-metric-sample": short("One host sample."),
"feedback-aggregator": short("One aggregate over the feedback table."),
"geo-backfill": short("At most 500 audit rows per pass."),
"geolite2-fetch": short("One database download."),
"tls-pin-monitor": short("One TLS handshake."),
"recovery-readiness": short(
"A few indexed reads, one row per account from two backup ledgers, and at most one notice per signal.",
),
"system-job-alert": short(
"The newest fifty terminal runs of each system queue over pg-boss's completion index, and at most one notice per queue.",
),
"integration-watchdog-hourly": short(
"A few indexed reads per account with a connection and no provider call; a 14-day history count only for a silent source.",
),
"integration-watchdog-daily": short(
"The hourly pass plus one 14-day history count per standing silence flag.",
),
"mood-reminder-cleanup": short("One retention DELETE."),
"push-attempt-cleanup": short("One retention DELETE."),
"arrival-reaction-cleanup": short("One retention DELETE."),
"rate-limit-cleanup": short("One retention DELETE."),
"idempotency-cleanup": short("One retention DELETE."),
"step-up-elevation-cleanup": short("One retention DELETE."),
"coach-message-cleanup": short("One retention DELETE."),
"workout-insight-claim-cleanup": short("One retention DELETE."),
"mcp-token-cleanup": short("One retention DELETE."),
"audit-log-cleanup": short("At most 40 batches of 5 000 rows per leg."),
"measurement-tombstone-cleanup": short(
"At most 40 batches of 5 000 rows per leg.",
),
"document-tombstone-purge": short("One deleteMany."),
"soft-delete-purge": short(
"At most 40 batches of 5 000 rows per table, over a few small tables.",
),
"auth-ledger-cleanup": short("At most 40 batches of 5 000 rows per table."),
"document-summary-reaper": short("One updateMany."),
"cycle-prediction-refresh": short(
"Arithmetic per eligible account, no provider call.",
),
"mood-prognosis-refresh": short(
"Arithmetic per eligible account, no provider call.",
),
"achievement-unlock-sweep": short(
"A bounded achievement read per account, no provider call.",
),
"pr-detection": {
runtime: "long",
expireInSeconds: PR_DETECTION_EXPIRE_SECONDS,
expiryVia: ["PR_DETECTION_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/reminder/ops-handlers.ts",
fn: "handlePrDetection",
},
exclusive: "lockedPass",
why: "The fallback cron scans every account's all-time history every thirty minutes; an ingest job is one account.",
},
"medication-inventory-expire": short("One updateMany."),
"intake-auto-skip": short("One updateMany."),
"intake-auto-take": short(
"At most seven days of slots per opted-in medication, a few rows each.",
),
"apple-health-import-v2": {
runtime: "long",
expireInSeconds: APPLE_HEALTH_IMPORT_SEND_OPTIONS.expireInSeconds,
expiryVia: ["APPLE_HEALTH_IMPORT_SEND_OPTIONS"],
stop: {
oneShot:
"The run consumes and unlinks its staged upload, so it can neither stop half-way nor be retried; the send sets retryLimit 0.",
},
exclusive: {
marker: "retryLimit: 0",
at: {
file: "lib/jobs/apple-health-import-worker.ts",
fn: "APPLE_HEALTH_IMPORT_SEND_OPTIONS",
},
},
why: "Parses an export that can be several gigabytes.",
},
"apple-health-import": short(
"The legacy queue: moves each job onto apple-health-import-v2.",
),
"apple-health-import-reconcile": short("One updateMany."),
"health-connect-import": {
runtime: "long",
expireInSeconds: HEALTH_CONNECT_IMPORT_SEND_OPTIONS.expireInSeconds,
expiryVia: ["HEALTH_CONNECT_IMPORT_SEND_OPTIONS"],
stop: {
oneShot:
"The run consumes and unlinks its staged upload, so it can neither stop half-way nor be retried; the send sets retryLimit 0.",
},
exclusive: {
marker: "retryLimit: 0",
at: {
file: "lib/jobs/health-connect-import-worker.ts",
fn: "HEALTH_CONNECT_IMPORT_SEND_OPTIONS",
},
},
why: "Reads a Health Connect export database that can hold years of minute-level samples.",
},
"compaction-tombstone-purge": short(
"At most 40 batches of 5 000 rows per run; the predicate is idempotent, so the next run resumes.",
),
"measurement-fold-repair": {
runtime: "budgeted",
budget: {
file: "lib/jobs/measurement-fold-repair.ts",
fn: "handleMeasurementFoldRepair",
},
why: "One account's folded means, a day at a time; stops at three quarters of the default expiry and sends a follow-up that resumes at the next day.",
},
"lab-document-date-repair": short(
"Reads the document lab values still filed at their confirmation moment, a handful per account, and moves each with one update.",
),
"wearable-cycle-repair": short(
"Reads the wearable period days still without a cycle, a few hundred per account at most, and opens or attributes each with a short transaction.",
),
"measurement-maintenance": {
runtime: "long",
expireInSeconds: MEASUREMENT_MAINTENANCE_SEND_OPTIONS.expireInSeconds,
expiryVia: ["MEASUREMENT_MAINTENANCE_SEND_OPTIONS"],
stop: {
oneShot:
"VACUUM and REINDEX CONCURRENTLY cannot be resumed mid-statement; the send and the nightly tick set retryLimit 0, and the next night or the operator runs it again.",
},
exclusive: {
marker: "retryLimit: 0",
at: {
file: "lib/jobs/measurement-maintenance.ts",
fn: "MEASUREMENT_MAINTENANCE_SEND_OPTIONS",
},
},
why: "The operator's run rebuilds every index of the largest table, one at a time; the nightly check is one VACUUM at most.",
},
"pulse-day-mean": {
runtime: "long",
expireInSeconds: PULSE_DAY_MEAN_SEND_OPTIONS.expireInSeconds,
expiryVia: ["PULSE_DAY_MEAN_SEND_OPTIONS"],
stop: {
oneShot:
"A dry run or rebuild that stops part way is started again by the operator; the send sets retryLimit 0.",
},
exclusive: {
marker: "retryLimit: 0",
at: {
file: "lib/jobs/pulse-day-mean.ts",
fn: "PULSE_DAY_MEAN_SEND_OPTIONS",
},
},
why: "Walks every account's pulse history a window at a time, twice over for a dry run.",
},
"medication-intake-import": {
runtime: "long",
expireInSeconds: MEDICATION_INTAKE_IMPORT_SEND_OPTIONS.expireInSeconds,
expiryVia: ["MEDICATION_INTAKE_IMPORT_SEND_OPTIONS"],
stop: {
file: "lib/jobs/medication-intake-import.ts",
fn: "handleMedicationIntakeImport",
},
exclusive: {
marker: "FOR UPDATE",
at: {
file: "lib/jobs/medication-intake-import.ts",
fn: "processNextChunk",
},
},
why: "Imports a dose-history file chunk by chunk; its length follows the file.",
},
"intake-slot-dedup": short("One account's duplicate dose slots."),
"note-encryption-backfill": short(
"Pages of 200 rows of one account's plaintext notes, light per row.",
),
"med-notes-encryption-backfill": short(
"Pages of 200 rows of one account's plaintext notes, light per row.",
),
"free-text-encryption-backfill": short(
"Pages of 200 rows of one account's plaintext fields, light per row.",
),
"encryption-key-rotate": {
runtime: "long",
expireInSeconds: ENCRYPTION_KEY_ROTATE_EXPIRE_SECONDS,
expiryVia: ["ENCRYPTION_KEY_ROTATE_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/encryption-key-rotate.ts",
fn: "handleEncryptionKeyRotate",
},
exclusive: "lockedPass",
why: "Re-encrypts every encrypted column on the instance.",
},
"document-content-index-backfill": {
runtime: "long",
expireInSeconds: CONTENT_INDEX_BACKFILL_EXPIRE_SECONDS,
expiryVia: ["CONTENT_INDEX_BACKFILL_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/reminder/document-handlers.ts",
fn: "handleContentIndexBackfill",
},
exclusive: "lockedPass",
why: "Up to 200 documents of one account, a provider transcription each.",
},
"document-index": {
runtime: "long",
expireInSeconds: DOCUMENT_INDEX_EXPIRE_SECONDS,
expiryVia: ["DOCUMENT_INDEX_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/reminder/document-handlers.ts",
fn: "handleDocumentIndex",
},
exclusive: "lockedPass",
why: "One document: the transcription, then a lab report's staging reads, as many as fit before the job's deadline at the person's timeout.",
},
"document-ai-run": {
runtime: "long",
expireInSeconds: DOCUMENT_AI_RUN_EXPIRE_SECONDS,
expiryVia: ["DOCUMENT_AI_RUN_EXPIRE_SECONDS"],
stop: {
file: "lib/jobs/document-ai-run.ts",
fn: "handleDocumentAiRunJobs",
},
exclusive: "lockedPass",
why: "One person's document or lab scan, up to three model calls at their AI response time (up to ten minutes each).",
},
"document-ai-run-reaper": short(
"Up to 500 conditional updates and one deleteMany.",
),
"document-thumbnail": short("One document."),
"document-summary": {
runtime: "bounded",
modelSeconds: COMPLETION_CEILING_MS / 1000,
expireInSeconds: DOCUMENT_SUMMARY_EXPIRE_SECONDS,
expiryVia: ["DOCUMENT_SUMMARY_EXPIRE_SECONDS"],
why: "One document's summary: one call and its reasoning repeat at the person's timeout.",
},
"document-summary-catchup": short("Enqueues at most 200 documents."),
"document-thumbnail-backfill": short("Enqueues at most 1 000 documents."),
"environment-fetch": short(
"A fan-out of sends, or one account's bounded archive range.",
),
"dawarich-sync": short(
"A fan-out of sends, or one account's range: one timeline request per 30 days (at most 13), one visits request and at most two residency requests.",
),
"environment-aq-history": short(
"A fan-out of sends, or one account's history run: at most eight ranges of up to 90 days, two requests each, then a follow-up.",
),
};
@@ -8,7 +8,7 @@
* so could every other job that legitimately needs longer: the nightly status
* passes, the pre-generation, the record scan, the key rotation, the backups.
*
* `src/lib/jobs/queue-runtime.ts` declares every queue `short`, `budgeted` or
* `helpers/queue-runtime.ts` declares every queue `short`, `budgeted` or
* `long`. This guard holds the tree to it:
*
* - every queue the worker registry declares (`jobs/registry/`) is in the
@@ -41,7 +41,7 @@ import {
DEFAULT_JOB_EXPIRE_SECONDS,
QUEUE_RUNTIME,
type QueueRuntime,
} from "@/lib/jobs/queue-runtime";
} from "./helpers/queue-runtime";
import { SCHEDULED_AND_SENT_QUEUES } from "@/lib/jobs/reminder/registrar-shared";
import { HEAVY_QUEUES } from "@/lib/jobs/heavy-lane";
import type { JobDefinition } from "@/lib/jobs/registry/define-job";
@@ -22,8 +22,7 @@
* that file does, or is listed below by file and function with the reason
* its rows cannot reach a prompt. A new reader fails here until it does one
* of those. The data routes are not in scope: a module decides what a model
* is given, not what the owner can read (`CLAUDE.md`, "An AI capability
* gates model work").
* is given, not what the owner can read.
*
* The check is per read, not per file. It used to ask whether a file that
* reads the table mentions the gate anywhere, so one ungated read in a file
-114
View File
@@ -1,114 +0,0 @@
/**
* The moodLog bridge stays removed.
*
* It was retired once before, in pieces: the Settings card went in June, the
* cron, webhook, credentials, ledger entry and roughly twenty i18n keys stayed
* behind, and for a month the code ran hourly against an upstream that had
* stopped answering while nothing on any screen said so. Half-removed was
* worse than either finished state.
*
* This test pins the finished state. It is a structural guard, not a
* behavioural one: it fails the moment a moodLog surface reappears, so a
* reintroduction has to be a decision someone writes down rather than a merge
* that slips through.
*
* What it deliberately does NOT forbid: the `MOODLOG` mood-entry source value
* and its label. Rows the bridge imported are the user's own history, they
* keep their provenance, and every read path must go on resolving it.
*/
import { readFileSync, existsSync } from "node:fs";
import path from "node:path";
import { allJobDefinitions } from "@/lib/jobs/registry/index";
import { describe, expect, it } from "vitest";
import { INTEGRATION_CADENCE } from "@/lib/integrations/sync-verdict";
import { INTEGRATION_DISPLAY_NAMES } from "@/components/settings/integrations/integration-fallback-row";
const ROOT = path.resolve(__dirname, "../..");
const LOCALES = [
"de",
"en",
"es",
"fr",
"it",
"pl",
"ko",
"nl",
"pt-BR",
] as const;
/** Every path the retired bridge occupied. */
const REMOVED_PATHS = [
"src/lib/moodlog",
"src/lib/moodlog-secret.ts",
"src/lib/jobs/reminder/moodlog-sync.ts",
"src/app/api/integrations/moodlog",
"src/app/api/settings/moodlog",
"src/lib/validations/moodlog.ts",
];
/** Columns migration 0271 dropped. */
const REMOVED_SCHEMA_FIELDS = [
"moodLogUrlEncrypted",
"moodLogApiKeyEncrypted",
"moodLogEnabled",
"moodLogLastSyncedAt",
"moodLogWebhookSecret",
"moodLogGlobal",
];
describe("moodLog integration stays removed", () => {
it("has no moodLog module, route or validation file", () => {
for (const rel of REMOVED_PATHS) {
expect(existsSync(path.join(ROOT, rel)), `${rel} is back`).toBe(false);
}
});
it("declares no moodLog column on the Prisma schema", () => {
const schema = readFileSync(
path.join(ROOT, "prisma/schema.prisma"),
"utf8",
);
for (const field of REMOVED_SCHEMA_FIELDS) {
expect(schema, `${field} is back on the schema`).not.toContain(field);
}
});
it("registers no moodlog queue, cron or handler binding", () => {
const queues = allJobDefinitions().map((job) => job.queue);
expect(queues.length).toBeGreaterThan(100);
expect(queues.filter((queue) => /mood-?log/i.test(queue))).toEqual([]);
});
it("carries no moodlog integration key on the status envelope", () => {
expect(Object.keys(INTEGRATION_CADENCE)).not.toContain("moodlog");
expect(Object.keys(INTEGRATION_DISPLAY_NAMES)).not.toContain("moodlog");
});
it("keeps no orphaned moodLog message key in any locale", () => {
for (const locale of LOCALES) {
const bundle = JSON.parse(
readFileSync(path.join(ROOT, `messages/${locale}.json`), "utf8"),
) as {
settings: Record<string, unknown>;
admin: Record<string, unknown>;
};
const orphans = [
...Object.keys(bundle.settings),
...Object.keys(bundle.admin),
].filter((key) => key.startsWith("moodLog"));
expect(orphans, `${locale} still carries moodLog keys`).toEqual([]);
}
});
it("still resolves the MOODLOG provenance of imported mood rows", () => {
// The other half of the contract: removing the bridge must not erase the
// history it wrote. The source badge label has to survive the removal.
const en = JSON.parse(
readFileSync(path.join(ROOT, "messages/en.json"), "utf8"),
) as { mood: Record<string, string> };
expect(en.mood.sourceMoodlog).toBeTruthy();
});
});
+1 -1
View File
@@ -43,7 +43,7 @@ const SRC = join(process.cwd(), "src");
* Every non-test `.ts` / `.tsx` under `src/app/`, which is the whole of the
* request-handling tree: API routes, RSC pages, layouts, route handlers.
* The generated Prisma client is excluded by construction (it is not under
* `app/`) and never read — see CLAUDE.md.
* `app/`) and never read.
*/
function appFiles(): string[] {
return walkSourceFiles(SRC, { floor: 3000 })
@@ -50,6 +50,7 @@ const HISTORICAL_SETTINGS_PATHS: readonly string[] = [
"/settings/api",
"/settings/mcp",
"/settings/gesundheitsakte",
"/settings/health-record",
"/settings/sharing",
"/settings/export",
"/settings/advanced",
@@ -72,6 +73,7 @@ const HISTORICAL_SETTINGS_PATHS: readonly string[] = [
"/settings/layout/illness",
"/settings/layout/documents",
"/settings/layout/vorsorge",
"/settings/layout/checkups",
];
interface Redirect {
@@ -151,6 +153,22 @@ describe("historical Settings addresses", () => {
expect(unlisted).toEqual([]);
});
it("sends the old German addresses to their English ones", async () => {
const redirects = await settingsRedirects();
expect(resolve("/settings/gesundheitsakte", redirects)).toBe(
"/settings/health-record",
);
expect(resolve("/settings/sharing", redirects)).toBe(
"/settings/health-record",
);
expect(resolve("/settings/layout/vorsorge", redirects)).toBe(
"/settings/layout/checkups",
);
expect(resolve("/settings/vorsorge", redirects)).toBe(
"/settings/layout/checkups",
);
});
it("keeps the v1.44 moves addressable", async () => {
const redirects = await settingsRedirects();
expect(resolve("/settings/layout/mood", redirects)).toBe(
+1 -1
View File
@@ -161,7 +161,7 @@ const BARE_REQUIRE_AUTH_FLOOR = 200;
* omits the three routes under `src/app/.well-known/` — three request handlers
* that a glob-based sweep reports as if they did not exist. Leg (a) pins one of
* them by name so this cannot quietly regress. Names only; nothing under
* `generated/` is ever read (CLAUDE.md).
* `generated/` is ever read.
*/
function allPaths(): string[] {
return readdirSync(SRC, { recursive: true })
-187
View File
@@ -1,187 +0,0 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
const ROOT = join(__dirname, "../..");
const LOCALES = [
"en",
"de",
"es",
"fr",
"it",
"pl",
"ko",
"nl",
"pt-BR",
] as const;
const REQUIRED_KEYS = [
// Security: adding a passkey now requires an existing sign-in factor.
"settings.passkeyReauth.title",
"settings.passkeyReauth.description",
"settings.passkeyReauth.methodLabel",
"settings.passkeyReauth.methods.password",
"settings.passkeyReauth.methods.totp",
"settings.passkeyReauth.methods.passkey",
"settings.passkeyReauth.methods.webauthn",
"settings.passkeyReauth.currentPassword",
"settings.passkeyReauth.authenticatorCode",
"settings.passkeyReauth.authenticatorPlaceholder",
"settings.passkeyReauth.verifyAndAdd",
// Integrations/imports: operator policy and Apple ECG terminal outcome.
"settings.nightscoutPrivateOperatorTitle",
"settings.nightscoutPrivateOperatorDescription",
"settings.sections.export.import.appleHealth.ecgResult",
// Existing terminal contracts reused by the final v1.34.1 call sites.
"insights.assessmentPreparing",
"insights.noAnalysisYet",
"common.loadFailed",
"common.networkError",
"settings.googleHealthSyncResult",
"settings.googleHealthSyncFailed",
// `settings.googleHealthBackfillInProgress` left this list in v1.42.4: the
// history-loading line became a sentence variant of the shared integration
// card (`settings.integrationCard.reason.dataArrivingHistory`).
"settings.syncOutcome.empty",
"settings.syncOutcome.partial",
"settings.syncOutcome.failed",
// Retained score, records, and navigation contracts.
// `insights.healthScore.method` was listed obsolete in v1.34.1 because its
// only reference was `METRIC_PROVENANCE.HEALTH_SCORE.methodKey`, which the
// card then passed as `method={null}` — a dangling reference, not a dead
// one. The score card now renders that method paragraph in its disclosure
// footer, so the key is a live contract again.
"insights.healthScore.method",
"insights.healthScore.bandSetter",
"insights.healthScore.versionAndNoise",
"insights.healthScore.methodVersion",
"insights.healthScore.source",
"records.allergies.add",
"records.allergies.addFirst",
"records.family.add",
"records.family.addFirst",
"admin.shell.sectionsNav",
"settings.shell.sectionsNav",
] as const;
const OBSOLETE_KEYS = [
"insights.healthScore.algorithmChanged",
"insights.healthScore.dismissAlgorithmChanged",
"insights.healthScore.composition",
"documents.detail.summary.regenerate",
"records.profileFacts.correct",
// v1.43 — the profile-facts card became the life-circumstances card, whose
// sections save on their own.
"records.profileFacts.save",
"settings.nightscoutPrivateHost",
"settings.nightscoutPrivateHostHelp",
] as const;
const NEW_CALL_SITES = {
"src/components/settings/security-section/passkey-list-section.tsx": [
"settings.passkeyReauth.title",
"settings.passkeyReauth.description",
"settings.passkeyReauth.methodLabel",
"settings.passkeyReauth.methods.password",
"settings.passkeyReauth.methods.totp",
"settings.passkeyReauth.methods.passkey",
"settings.passkeyReauth.methods.webauthn",
"settings.passkeyReauth.currentPassword",
"settings.passkeyReauth.authenticatorCode",
"settings.passkeyReauth.authenticatorPlaceholder",
"settings.passkeyReauth.verifyAndAdd",
],
"src/components/settings/integrations/nightscout-card.tsx": [
"settings.nightscoutPrivateOperatorTitle",
"settings.nightscoutPrivateOperatorDescription",
],
"src/components/settings/import-panel/apple-health-import-card.tsx": [
"settings.sections.export.import.appleHealth.ecgResult",
],
} as const;
type Catalog = Record<string, unknown>;
function readCatalog(locale: (typeof LOCALES)[number]): Catalog {
return JSON.parse(
readFileSync(join(ROOT, "messages", `${locale}.json`), "utf8"),
) as Catalog;
}
function resolveLeaf(catalog: Catalog, dottedKey: string): string | undefined {
let value: unknown = catalog;
for (const segment of dottedKey.split(".")) {
if (typeof value !== "object" || value === null || !(segment in value)) {
return undefined;
}
value = (value as Record<string, unknown>)[segment];
}
return typeof value === "string" ? value : undefined;
}
function placeholders(message: string): string[] {
return [
...new Set(
[...message.matchAll(/\{([A-Za-z_][A-Za-z0-9_]*)\b/g)].map(
(match) => match[1],
),
),
].sort();
}
describe("v1.34.1 locale reconciliation", () => {
it("wires every newly introduced user-facing state through a literal t() call", () => {
for (const [relativePath, keys] of Object.entries(NEW_CALL_SITES)) {
const source = readFileSync(join(ROOT, relativePath), "utf8");
for (const key of keys) {
expect(source, `${relativePath} must translate ${key}`).toMatch(
new RegExp(`\\bt\\(\\s*["']${key.replaceAll(".", "\\.")}["']`),
);
}
}
});
it("provides every final contract in all six locales with ICU parity", () => {
const catalogs = Object.fromEntries(
LOCALES.map((locale) => [locale, readCatalog(locale)]),
) as Record<(typeof LOCALES)[number], Catalog>;
for (const key of REQUIRED_KEYS) {
const english = resolveLeaf(catalogs.en, key);
expect(english, `messages/en.json is missing ${key}`).toBeTruthy();
for (const locale of LOCALES) {
const translated = resolveLeaf(catalogs[locale], key);
expect(
translated,
`messages/${locale}.json is missing ${key}`,
).toBeTruthy();
expect(
placeholders(translated ?? ""),
`messages/${locale}.json changed ICU placeholders for ${key}`,
).toEqual(placeholders(english ?? ""));
}
}
});
it("removes only the v1.34.1 copy proven obsolete after final call-site inventory", () => {
for (const locale of LOCALES) {
const catalog = readCatalog(locale);
for (const key of OBSOLETE_KEYS) {
expect(
resolveLeaf(catalog, key),
`messages/${locale}.json still contains obsolete ${key}`,
).toBeUndefined();
}
}
const productionSource = Object.keys(NEW_CALL_SITES)
.map((relativePath) => readFileSync(join(ROOT, relativePath), "utf8"))
.join("\n");
for (const key of OBSOLETE_KEYS) {
expect(productionSource).not.toContain(`t("${key}")`);
expect(productionSource).not.toContain(`t('${key}')`);
}
});
});