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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .github/actions/load-infisical-secrets/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,19 @@ runs:
exit 1
fi

mask_value() {
local mask_line
while IFS= read -r mask_line || [ -n "$mask_line" ]; do
mask_line="${mask_line//'%'/'%25'}"
mask_line="${mask_line//$'\r'/'%0D'}"
mask_line="${mask_line//$'\n'/'%0A'}"
printf '::add-mask::%s\n' "$mask_line"
done <<< "$1"
}

while IFS= read -r key; do
if ! value="$(infisical secrets get "$key" --env="$INFISICAL_ENV" --projectId="$project_id" --token="$infisical_access_token" --plain --silent 2>&1)"; then
mask_value "$value"
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
echo "::error::Failed to fetch Infisical secret: $key (env=$INFISICAL_ENV, project=$project_id)"
echo "$value"
exit 1
Expand All @@ -116,6 +127,8 @@ runs:
exit 1
fi

mask_value "$value"

if printf '%s' "$value" | grep -q $'\n'; then
marker="INFISICAL_${key}_$(uuidgen)"
{
Expand Down
3 changes: 3 additions & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,9 @@
"acwr",
"drhr",
"ewma",
"Tukey",
"tukey",
"interquartile",
"trimp",
"trimps",
"tdee",
Expand Down
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ the exact section.
| [schema.md](schema.md) | Database layout, raw-data-only rules, and view/dedup behavior. |
| [altitude-provenance.md](altitude-provenance.md) | Provider-by-provider altitude source confidence and modeling implications. |
| [record-local-time.md](record-local-time.md) | Trusted per-record local clock context, provenance, and bounded historical activity backfill. |
| [body-metrics-decision-context.md](body-metrics-decision-context.md) | Server-authored Trend Weight methodology, measurement provenance, and personalized variation context. |
| [schema.dbml](schema.dbml) / [schema.puml](schema.puml) | Generated schema diagrams for quick visual orientation. |
| [adding-a-provider.md](adding-a-provider.md) | Step-by-step provider implementation guide. |
| [exercise-metadata.md](exercise-metadata.md) | Strength exercise metadata source, override format, and upstream refresh workflow. |
Expand Down
38 changes: 38 additions & 0 deletions docs/body-metrics-decision-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Body metrics decision context

The Body page and mobile Recovery tab show the server-authored context needed to
interpret Trend Weight and recent scale readings. The context is derived from
the existing ClickHouse body-measurement view; it does not create a second
source of body data.

## Measurement provenance

The latest positive body measurement selected for the user’s local calendar day
is shown with its provider, optional device/source name, weight, and recorded
clock time in the configured user timezone. The display encourages comparable
measurements: [NHS England recommends recording weight at the same time of day
and using the same scales](https://www.england.nhs.uk/long-read/how-to-record-your-weight/).

## Trend Weight contract

Trend Weight uses the existing server-side EWMA with alpha `0.1`:

- each selected daily scale reading moves the trend 10% toward that reading;
- missing days between readings are linearly interpolated;
- non-positive weights are excluded from the trend input;
- readings are not removed as outliers.

The exact contract is returned with the body analytics response so web and
mobile render the same explanation.

## Personalized typical measurement variation

The server computes scale-to-Trend-Weight residuals for the latest 30 selected
daily readings. It reports an informational residual band after at least eight
readings using Tukey inner fences (`Q1 - 1.5 × IQR` and `Q3 + 1.5 × IQR`). The
band is not a clinical threshold, and outlying readings remain included in the
underlying data. This follows the standard boxplot inner-fence definition
described by [NIST’s outlier guidance](https://www.itl.nist.gov/div898/handbook/prc/section1/prc16.htm).

When fewer than eight residual observations are available, the response explicitly
returns an insufficient-data state instead of inventing a range.
49 changes: 49 additions & 0 deletions docs/production-incident-baseline.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,55 @@ Run `pnpm test:unit`, the heart-rate integration test, and full `pnpm lint` on
the exact PR head in CI or after an explicitly scoped Docker cleanup, following
the resource guidance in [`docs/testing.md`](testing.md#docker-disk-recovery).

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
## 2026-08-02: Mobile Preview OTA workflow exposed an unmasked Infisical credential

### Symptoms

During the diagnosis associated with PR #2303, a successful `Mobile Preview
OTA` workflow loaded an Infisical-provided OTA credential in its `Publish
Mobile Preview OTA` job without registering a GitHub Actions mask first.

### User Impact

The affected Expo credential must be considered exposed and replaced. The
incident affected CI credential confidentiality; no application availability
or user health-data integrity impact has been identified.

### Evidence

The affected key is `EXPO_TOKEN`. The Actions evidence collected during the
PR #2303 diagnosis includes successful `Publish Mobile Preview OTA` jobs
`90889411701` and `90710536078`.
Both invoked `.github/actions/load-infisical-secrets` and contained no
`::add-mask::` registration before the action made fetched values available to
later workflow steps. No secret value is recorded in this incident document.

### Root Cause

The shared Infisical composite action wrote fetched values to `GITHUB_ENV`
without first registering them as masked workflow-command values. GitHub
requires sensitive values to be registered with `add-mask` before use in
workflow commands or logs: <https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-commands#masking-a-value-in-a-log>.

### Fix or Mitigation

The composite action now masks each fetched value (line by line for the
existing multiline path) before writing it to `GITHUB_ENV`, while preserving
the existing explicit failures for fetch and empty-value errors. A focused
Vitest contract check prevents a future write from preceding the mask.

### Validation

The composite action was reviewed to verify that each fetched value is escaped
and masked before the `GITHUB_ENV` write on both success and failure paths.

### Remaining Risk

`EXPO_TOKEN` is present in the `dev`, `prod`, and `staging` Infisical
environments. Replacement and Expo-side revocation remain required; Expo's
current procedure is to delete the exposed access token from its Access Tokens
dashboard: <https://docs.expo.dev/accounts/programmatic-access/#revoke-access-tokens>.

## 2026-08-01: Review-stack detail smoke test encoded tRPC input incorrectly

### Symptoms
Expand Down
1 change: 1 addition & 0 deletions packages/format/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"./activity-data-state": "./src/activity-data-state.ts",
"./baseline-context": "./src/baseline-context.ts",
"./data-quality": "./src/data-quality.ts",
"./body-decision-context": "./src/body-decision-context.ts",
"./format": "./src/format.ts",
"./healthspan-context": "./src/healthspan-context.ts",
"./medication-dose-events": "./src/medication-dose-events.ts",
Expand Down
147 changes: 147 additions & 0 deletions packages/format/src/body-decision-context.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { describe, expect, it } from "vitest";
import {
BODY_SOURCE_GUIDANCE,
BODY_TREND_WEIGHT_DECISION_COPY,
formatBodyDecisionProvenance,
formatBodyDecisionVariation,
formatSignedBodyResidual,
} from "./body-decision-context.ts";

const formatWeight = (value: number) => `${value.toFixed(1)} kg`;

describe("body decision context formatting", () => {
it("returns no provenance when there is no latest measurement", () => {
expect(
formatBodyDecisionProvenance(null, {
formatWeight,
providerLabel: (providerId) => providerId,
}),
).toBeNull();
});

it("uses the same provenance copy for the measurement source and local time", () => {
expect(
formatBodyDecisionProvenance(
{
recordedAtLocal: "2026-07-25 08:00:00",
weightKg: 80,
providerId: "withings",
sourceName: "Body+",
},
{
formatWeight,
providerLabel: (providerId) => (providerId === "withings" ? "Withings" : providerId),
},
),
).toBe(
"Latest scale reading: 80.0 kg · Provider: Withings · Source: Body+ · Recorded: 2026-07-25 08:00:00",
);
});

it("omits provenance copy when the source name is absent", () => {
expect(
formatBodyDecisionProvenance(
{
recordedAtLocal: "2026-07-25 08:00:00",
weightKg: 80,
providerId: "withings",
sourceName: null,
},
{
formatWeight,
providerLabel: () => "Withings",
},
),
).toBe("Latest scale reading: 80.0 kg · Provider: Withings · Recorded: 2026-07-25 08:00:00");
});

it("formats positive, negative, and zero residuals with absolute magnitudes", () => {
expect(formatSignedBodyResidual(0.4, formatWeight)).toBe("+0.4 kg");
expect(formatSignedBodyResidual(-0.4, formatWeight)).toBe("-0.4 kg");
expect(formatSignedBodyResidual(0, formatWeight)).toBe("0.0 kg");
});

it("describes available variation as an informational residual band", () => {
expect(
formatBodyDecisionVariation(
{
status: "available",
observations: 12,
minimumObservations: 8,
maximumObservations: 30,
lowerResidualKg: -0.4,
upperResidualKg: 0.6,
},
(value) => formatSignedBodyResidual(value, formatWeight),
),
).toBe(
"Personalized typical measurement variation is -0.4 kg to +0.6 kg around Trend Weight, based on 12 of the latest 30 actual scale readings. This is informational, not a clinical threshold; outliers remain included.",
);
});

it("states when variation needs more readings", () => {
expect(
formatBodyDecisionVariation(
{
status: "insufficient_data",
observations: 7,
minimumObservations: 8,
maximumObservations: 30,
lowerResidualKg: null,
upperResidualKg: null,
},
(value) => formatSignedBodyResidual(value, formatWeight),
),
).toBe(
"Personalized typical measurement variation is unavailable until at least 8 actual scale readings are available.",
);
});

it("treats either missing residual bound as unavailable", () => {
const formatResidual = (value: number) => formatSignedBodyResidual(value, formatWeight);
const baseVariation = {
status: "available" as const,
observations: 12,
minimumObservations: 8,
maximumObservations: 30,
};

expect(
formatBodyDecisionVariation(
{ ...baseVariation, lowerResidualKg: null, upperResidualKg: 0.6 },
formatResidual,
),
).toContain("unavailable until at least 8 actual scale readings are available");
expect(
formatBodyDecisionVariation(
{ ...baseVariation, lowerResidualKg: -0.4, upperResidualKg: null },
formatResidual,
),
).toContain("unavailable until at least 8 actual scale readings are available");
});

it("treats a non-available status as unavailable even when bounds are present", () => {
expect(
formatBodyDecisionVariation(
{
status: "insufficient_data",
observations: 8,
minimumObservations: 8,
maximumObservations: 30,
lowerResidualKg: -0.4,
upperResidualKg: 0.6,
},
(value) => formatSignedBodyResidual(value, formatWeight),
),
).toBe(
"Personalized typical measurement variation is unavailable until at least 8 actual scale readings are available.",
);
});

it("keeps the Trend Weight method and source guidance as shared copy", () => {
expect(BODY_TREND_WEIGHT_DECISION_COPY).toContain("Missing days are linearly interpolated");
expect(BODY_SOURCE_GUIDANCE).toBe(
"For comparable readings, use the same scale at a consistent time of day.",
);
});
});
74 changes: 74 additions & 0 deletions packages/format/src/body-decision-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
export const BODY_TREND_WEIGHT_DECISION_COPY =
"Trend Weight moves 10% toward each selected daily scale reading. Missing days are linearly interpolated; non-positive values are excluded and outliers remain included.";

export const BODY_SOURCE_GUIDANCE =
"For comparable readings, use the same scale at a consistent time of day.";

export const BODY_DECISION_CONTEXT_UNAVAILABLE =
"Measurement decision context is temporarily unavailable. Refresh to try again.";

interface BodyDecisionLatestMeasurement {
recordedAtLocal: string;
weightKg: number;
providerId: string;
sourceName: string | null;
}

interface BodyDecisionVariation {
status: "available" | "insufficient_data";
observations: number;
minimumObservations: number;
maximumObservations: number;
lowerResidualKg: number | null;
upperResidualKg: number | null;
}

export interface BodyDecisionContextView {
latestMeasurement: BodyDecisionLatestMeasurement | null;
variation: BodyDecisionVariation;
}

export function formatBodyDecisionProvenance(
measurement: BodyDecisionLatestMeasurement | null,
options: {
formatWeight: (weightKg: number) => string;
providerLabel: (providerId: string) => string;
},
): string | null {
if (measurement == null) return null;

const source = measurement.sourceName != null ? `Source: ${measurement.sourceName}` : null;
return [
`Latest scale reading: ${options.formatWeight(measurement.weightKg)}`,
`Provider: ${options.providerLabel(measurement.providerId)}`,
source,
`Recorded: ${measurement.recordedAtLocal}`,
]
.filter((part): part is string => part != null)
.join(" · ");
}

export function formatSignedBodyResidual(
residualKg: number,
formatWeight: (absoluteWeightKg: number) => string,
): string {
const magnitude = formatWeight(Math.abs(residualKg));
if (residualKg > 0) return `+${magnitude}`;
if (residualKg < 0) return `-${magnitude}`;
return magnitude;
}

export function formatBodyDecisionVariation(
variation: BodyDecisionVariation,
formatResidual: (residualKg: number) => string,
): string {
if (
variation.status !== "available" ||
variation.lowerResidualKg == null ||
variation.upperResidualKg == null
) {
return `Personalized typical measurement variation is unavailable until at least ${variation.minimumObservations} actual scale readings are available.`;
}

return `Personalized typical measurement variation is ${formatResidual(variation.lowerResidualKg)} to ${formatResidual(variation.upperResidualKg)} around Trend Weight, based on ${variation.observations} of the latest ${variation.maximumObservations} actual scale readings. This is informational, not a clinical threshold; outliers remain included.`;
}
Loading
Loading