An exhaustive adversarial stress-test pass (6 parallel domain adversaries + in-kernel engine probing + a real-browser adversary) tried to BREAK every feature. 24 genuine breaks were found and fixed at root cause, each with a regression test; the dominant class (15/24) was a NaN/Infinity slipping past a typeof/isNaN-only guard at a trust boundary and poisoning a derived value. - Water Watch: blank value stored as fabricated 0; a single NaN reading permanently killed a channel baseline (and survived replay). Reject non-finite at the form, the gate, and the replay matcher. - Fair Share: a floor consuming the pool emitted an Infinity clearing price; Infinity need/supply/trend -> NaN. Finiteness guards + residual-only CEEI sub-market. - Housing: NaN/Infinity score/capacity signed a NaN fairness-debt that poisoned all future cycles. Validate finiteness at the input boundary. - Tunnel Safety: A* returned suboptimal routes when coord scale != weight scale (inadmissible heuristic). Scale the heuristic to be provably consistent; verified vs brute-force Dijkstra. - Assembly QV: duplicate P2P-synced credit rows double-counted a resident. Collapse per (proposal,resident) before tallying. - Fair Draw: empty participants committed a draw it could never resolve (stuck). Refuse empty draws. - Light Clock: negative/huge/NaN lux -> NaN circadian output; non-finite hours -> unbounded RK4 loop (hang/OOM). Finite light-drive + step bound. - Farms: NaN baseTemp/crop fields -> NaN GDD/yield (NaN-leak into Fair Share's signed ledger); overflow temps -> Infinity GDD. Finiteness + overflow-safe mean. - The Climb: Infinity capacities -> self-contradictory schedule; non-integer readyPeriod -> silent 0-delivered. Finiteness + integer guards. - Upload/manifest: an extra unknown field leaked into the stored manifest and onto the share wire; duplicate permissions and 200k names accepted. Reject unknown keys and return a reconstructed manifest; dedupe + length caps. Combined gate green: 689 tests pass (+21 regression over 668 baseline), tsc build exit 0, oxlint exit 0. No test skipped or weakened.
342 lines
12 KiB
TypeScript
342 lines
12 KiB
TypeScript
/**
|
|
* Light Clock: Hannay19 circadian phase model engine (plan todo 44).
|
|
*
|
|
* Standalone, pure-function port of the published Hannay19 macroscopic
|
|
* circadian model:
|
|
*
|
|
* Hannay, K.M., Booth, V., & Forger, D.B. (2019). "Macroscopic Models for
|
|
* Human Circadian Rhythms." Journal of Biological Rhythms, 34(6), 658-671.
|
|
* DOI: 10.1177/0748730419878298
|
|
*
|
|
* Equations, default parameters, and the default initial condition are
|
|
* ported verbatim from `fixtures/hannay19-model-spec.md`, which was itself
|
|
* pulled directly from the real, Hannay-coauthored `circadian` package
|
|
* (PyPI: circadian; GitHub: Arcascope/circadian, circadian/models.py,
|
|
* class Hannay19). No equation here was re-derived.
|
|
*
|
|
* MUST NOT be imported by, or import, any resource-allocation module
|
|
* (Fair Share's `fairshare.ts` / `ceeiSpike.ts` or anything downstream of
|
|
* them) - this engine is explicitly standalone per the adversarial review's
|
|
* fabrication-risk cut (plan todo 44). See `lightclockAllocatorIsolation.test.ts`
|
|
* for the enforced static-analysis check.
|
|
*/
|
|
|
|
/** The 15 fixed model parameters (see fixtures/hannay19-model-spec.md). */
|
|
export interface Hannay19Params {
|
|
tau: number;
|
|
K: number;
|
|
gamma: number;
|
|
Beta1: number;
|
|
A1: number;
|
|
A2: number;
|
|
BetaL1: number;
|
|
BetaL2: number;
|
|
sigma: number;
|
|
G: number;
|
|
alpha0: number;
|
|
delta: number;
|
|
p: number;
|
|
I0: number;
|
|
cbtToDlmo: number;
|
|
}
|
|
|
|
/** Default parameters, ported verbatim from the model spec. */
|
|
export const DEFAULT_PARAMS: Hannay19Params = {
|
|
tau: 23.84,
|
|
K: 0.06358,
|
|
gamma: 0.024,
|
|
Beta1: -0.09318,
|
|
A1: 0.3855,
|
|
A2: 0.1977,
|
|
BetaL1: -0.0026,
|
|
BetaL2: -0.957756,
|
|
sigma: 0.0400692,
|
|
G: 33.75,
|
|
alpha0: 0.05,
|
|
delta: 0.0075,
|
|
p: 1.5,
|
|
I0: 9325.0,
|
|
cbtToDlmo: 7.0,
|
|
};
|
|
|
|
/** The 3-variable model state: amplitude R, phase Psi, light-adaptation n. */
|
|
export interface Hannay19State {
|
|
R: number;
|
|
Psi: number;
|
|
n: number;
|
|
}
|
|
|
|
/** Default initial condition (midnight, 16L/8D schedule), ported verbatim. */
|
|
export const DEFAULT_INITIAL_STATE: Hannay19State = {
|
|
R: 0.82041911,
|
|
Psi: 1.71383697,
|
|
n: 0.52318122,
|
|
};
|
|
|
|
/**
|
|
* Light-drive term `alpha`: a saturating (Hill-type) function of light
|
|
* intensity `light` (lux). `alpha = alpha_0 * light^p / (light^p + I0)`.
|
|
*/
|
|
export function lightDrive(light: number, params: Hannay19Params = DEFAULT_PARAMS): number {
|
|
// Light intensity (lux) is physically non-negative and finite. Guard the
|
|
// saturating Hill function against inputs outside that domain so it can
|
|
// never silently emit NaN into the ODE integrator (which would poison the
|
|
// whole phase trajectory). A negative or NaN lux carries no usable drive
|
|
// (-> 0); an infinite/overflowing lux saturates the Hill function at its
|
|
// alpha0 limit rather than evaluating Infinity/Infinity -> NaN.
|
|
if (Number.isNaN(light) || light <= 0) return 0;
|
|
const lightP = Math.pow(light, params.p);
|
|
if (!Number.isFinite(lightP)) return params.alpha0;
|
|
return (params.alpha0 * lightP) / (lightP + params.I0);
|
|
}
|
|
|
|
function addScaled(state: Hannay19State, deriv: Hannay19State, factor: number): Hannay19State {
|
|
return {
|
|
R: state.R + deriv.R * factor,
|
|
Psi: state.Psi + deriv.Psi * factor,
|
|
n: state.n + deriv.n * factor,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The RHS of the Hannay19 ODE at `state` under light intensity `light`
|
|
* (lux), ported verbatim from fixtures/hannay19-model-spec.md.
|
|
*/
|
|
export function hannay19Derivative(
|
|
state: Hannay19State,
|
|
light: number,
|
|
params: Hannay19Params = DEFAULT_PARAMS,
|
|
): Hannay19State {
|
|
const { R, Psi, n } = state;
|
|
const alpha = lightDrive(light, params);
|
|
const Bhat = params.G * (1 - n) * alpha;
|
|
|
|
const a1TermAmp = params.A1 * 0.5 * Bhat * (1 - R ** 4) * Math.cos(Psi + params.BetaL1);
|
|
const a2TermAmp =
|
|
params.A2 * 0.5 * Bhat * R * (1 - R ** 8) * Math.cos(2 * Psi + params.BetaL2);
|
|
const lightAmp = a1TermAmp + a2TermAmp;
|
|
|
|
const a1TermPhase = params.A1 * Bhat * 0.5 * (R ** 3 + 1 / R) * Math.sin(Psi + params.BetaL1);
|
|
const a2TermPhase = params.A2 * Bhat * 0.5 * (1 + R ** 8) * Math.sin(2 * Psi + params.BetaL2);
|
|
const lightPhase = params.sigma * Bhat - a1TermPhase - a2TermPhase;
|
|
|
|
const dR = -params.gamma * R + (params.K * Math.cos(params.Beta1) * R * (1 - R ** 4)) / 2 + lightAmp;
|
|
const dPsi = (2 * Math.PI) / params.tau + (params.K / 2) * Math.sin(params.Beta1) * (1 + R ** 4) + lightPhase;
|
|
const dn = 60 * (alpha * (1 - n) - params.delta * n);
|
|
|
|
return { R: dR, Psi: dPsi, n: dn };
|
|
}
|
|
|
|
/**
|
|
* One explicit RK4 integration step of size `dtHours`, holding `light`
|
|
* constant across the step (the spec's prescribed integration scheme).
|
|
*/
|
|
export function rk4Step(
|
|
state: Hannay19State,
|
|
light: number,
|
|
dtHours: number,
|
|
params: Hannay19Params = DEFAULT_PARAMS,
|
|
): Hannay19State {
|
|
const k1 = hannay19Derivative(state, light, params);
|
|
const k2 = hannay19Derivative(addScaled(state, k1, dtHours / 2), light, params);
|
|
const k3 = hannay19Derivative(addScaled(state, k2, dtHours / 2), light, params);
|
|
const k4 = hannay19Derivative(addScaled(state, k3, dtHours), light, params);
|
|
|
|
return {
|
|
R: state.R + (dtHours / 6) * (k1.R + 2 * k2.R + 2 * k3.R + k4.R),
|
|
Psi: state.Psi + (dtHours / 6) * (k1.Psi + 2 * k2.Psi + 2 * k3.Psi + k4.Psi),
|
|
n: state.n + (dtHours / 6) * (k1.n + 2 * k2.n + 2 * k3.n + k4.n),
|
|
};
|
|
}
|
|
|
|
/** Circadian clock reading: Psi wrapped to (-pi, pi]. */
|
|
export function clockPhase(state: Hannay19State): number {
|
|
return Math.atan2(Math.sin(state.Psi), Math.cos(state.Psi));
|
|
}
|
|
|
|
/** One light/activity exposure sample: light intensity (lux) starting at `hours`. */
|
|
export interface ExposureSample {
|
|
hours: number;
|
|
light: number;
|
|
}
|
|
|
|
export interface SimulationOptions {
|
|
initialState?: Hannay19State;
|
|
params?: Hannay19Params;
|
|
/** Integration step size in hours (zero-order-held light between samples). Default 1/60 (1 minute). */
|
|
stepHours?: number;
|
|
}
|
|
|
|
export interface SimulationPoint {
|
|
hours: number;
|
|
R: number;
|
|
Psi: number;
|
|
n: number;
|
|
phase: number;
|
|
}
|
|
|
|
export interface SimulationResult {
|
|
trace: SimulationPoint[];
|
|
final: Hannay19State;
|
|
finalPhase: number;
|
|
}
|
|
|
|
/**
|
|
* Pure function: integrates the Hannay19 ODE across a light/activity
|
|
* exposure time series `exposure` (sorted ascending by `hours`, light
|
|
* zero-order-held between samples) and returns the resulting phase
|
|
* trajectory and final phase estimate.
|
|
*/
|
|
/**
|
|
* Upper bound on fixed-step RK4 iterations `simulateHannay19` will run, so a
|
|
* non-finite or pathologically large exposure window can never make it loop
|
|
* unboundedly / exhaust memory. 1,000,000 one-minute steps is ~694 days -
|
|
* far beyond any real circadian observation log, yet a hard termination
|
|
* guarantee for malformed input.
|
|
*/
|
|
export const MAX_SIMULATION_STEPS = 1_000_000;
|
|
|
|
export function simulateHannay19(
|
|
exposure: ExposureSample[],
|
|
options: SimulationOptions = {},
|
|
): SimulationResult {
|
|
if (exposure.length === 0) {
|
|
throw new Error("simulateHannay19 requires a non-empty exposure time series");
|
|
}
|
|
const sorted = [...exposure].sort((a, b) => a.hours - b.hours);
|
|
const params = options.params ?? DEFAULT_PARAMS;
|
|
const stepHours = options.stepHours ?? 1 / 60;
|
|
let state = options.initialState ?? DEFAULT_INITIAL_STATE;
|
|
|
|
const startHours = sorted[0].hours;
|
|
const endHours = sorted[sorted.length - 1].hours;
|
|
|
|
if (!Number.isFinite(startHours) || !Number.isFinite(endHours)) {
|
|
throw new Error("simulateHannay19 requires finite sample hours");
|
|
}
|
|
if (!(stepHours > 0) || !Number.isFinite(stepHours)) {
|
|
throw new Error("simulateHannay19 requires a positive, finite stepHours");
|
|
}
|
|
if ((endHours - startHours) / stepHours > MAX_SIMULATION_STEPS) {
|
|
throw new Error(
|
|
`simulateHannay19: exposure window too large to integrate at this resolution ` +
|
|
`(exceeds ${MAX_SIMULATION_STEPS} steps) - use a shorter window or a coarser stepHours`,
|
|
);
|
|
}
|
|
const trace: SimulationPoint[] = [
|
|
{ hours: startHours, R: state.R, Psi: state.Psi, n: state.n, phase: clockPhase(state) },
|
|
];
|
|
|
|
let sampleIndex = 0;
|
|
for (let t = startHours; t < endHours - 1e-9; t += stepHours) {
|
|
while (
|
|
sampleIndex + 1 < sorted.length &&
|
|
sorted[sampleIndex + 1].hours <= t + 1e-9
|
|
) {
|
|
sampleIndex += 1;
|
|
}
|
|
const dt = Math.min(stepHours, endHours - t);
|
|
state = rk4Step(state, sorted[sampleIndex].light, dt, params);
|
|
trace.push({
|
|
hours: t + dt,
|
|
R: state.R,
|
|
Psi: state.Psi,
|
|
n: state.n,
|
|
phase: clockPhase(state),
|
|
});
|
|
}
|
|
|
|
return { trace, final: state, finalPhase: clockPhase(state) };
|
|
}
|
|
|
|
/**
|
|
* Estimated DLMO (dim-light-melatonin-onset) times in hours-from-trace-start,
|
|
* found at each trace crossing of the CBTmin marker (unwrapped Psi crossing
|
|
* an odd multiple of pi, increasing direction), minus `cbtToDlmo` hours.
|
|
*/
|
|
export function estimateDlmoHours(
|
|
trace: SimulationPoint[],
|
|
params: Hannay19Params = DEFAULT_PARAMS,
|
|
): number[] {
|
|
const crossings: number[] = [];
|
|
for (let i = 1; i < trace.length; i += 1) {
|
|
const prev = trace[i - 1].Psi;
|
|
const curr = trace[i].Psi;
|
|
const prevMod = prev / Math.PI;
|
|
const currMod = curr / Math.PI;
|
|
const prevK = Math.floor((prevMod - 1) / 2);
|
|
const currK = Math.floor((currMod - 1) / 2);
|
|
if (currK > prevK) {
|
|
// Linear interpolation for the crossing time of Psi = (2*crossedK + 1) * pi.
|
|
const target = (2 * (prevK + 1) + 1) * Math.PI;
|
|
const frac = (target - prev) / (curr - prev);
|
|
const crossingHours = trace[i - 1].hours + frac * (trace[i].hours - trace[i - 1].hours);
|
|
crossings.push(crossingHours - params.cbtToDlmo);
|
|
}
|
|
}
|
|
return crossings;
|
|
}
|
|
|
|
/** One hours-from-trace-start interval during which the recommendation applies. */
|
|
export interface LightTimingWindow {
|
|
startHours: number;
|
|
endHours: number;
|
|
}
|
|
|
|
/**
|
|
* Half-width (hours) of the recommended bright-light-seeking window after
|
|
* CBTmin, and of the light-avoidance window before it.
|
|
*/
|
|
export const LIGHT_TIMING_WINDOW_HOURS = 2;
|
|
|
|
/**
|
|
* Concrete light-timing advice derived from `estimateDlmoHours`, or the
|
|
* explicit `"insufficient-data"` state when the trace contains no DLMO
|
|
* crossing to derive advice from (never a fabricated recommendation).
|
|
*/
|
|
export type LightTimingRecommendation =
|
|
| { state: "insufficient-data" }
|
|
| {
|
|
state: "ok";
|
|
/** Projected hours-from-trace-start of the next DLMO (dim-light-melatonin-onset) event. */
|
|
nextDlmoHour: number;
|
|
/** Window after the projected CBTmin (DLMO + `cbtToDlmo` hours) during which bright-light exposure advances/reinforces entrainment. */
|
|
seekLightWindow: LightTimingWindow;
|
|
/** Window before the projected CBTmin during which bright light would delay the clock and should be avoided. */
|
|
avoidLightWindow: LightTimingWindow;
|
|
};
|
|
|
|
/**
|
|
* Pure function: turns `estimateDlmoHours`'s crossing-detection output into
|
|
* actionable light-timing advice. CBTmin is approximated as the most
|
|
* recently observed DLMO plus `params.cbtToDlmo` hours (the same offset
|
|
* `estimateDlmoHours` subtracts to go from CBTmin to DLMO, per the cited
|
|
* Hannay19 spec); the next DLMO is projected one circadian period
|
|
* (`params.tau` hours) past the last observed one. Per the standard
|
|
* phase-response-curve structure this model's CBTmin anchors: bright light
|
|
* shortly after CBTmin produces a phase advance (seek it), shortly before
|
|
* CBTmin produces a phase delay (avoid it).
|
|
*
|
|
* Returns the explicit `{ state: "insufficient-data" }` marker - never a
|
|
* fabricated window - when the trace is too short to contain even one
|
|
* DLMO crossing.
|
|
*/
|
|
export function recommendLightTiming(
|
|
trace: SimulationPoint[],
|
|
params: Hannay19Params = DEFAULT_PARAMS,
|
|
): LightTimingRecommendation {
|
|
const dlmoHours = estimateDlmoHours(trace, params);
|
|
if (dlmoHours.length === 0) {
|
|
return { state: "insufficient-data" };
|
|
}
|
|
const lastObservedDlmoHour = dlmoHours[dlmoHours.length - 1];
|
|
const nextDlmoHour = lastObservedDlmoHour + params.tau;
|
|
const cbtMinHour = nextDlmoHour + params.cbtToDlmo;
|
|
return {
|
|
state: "ok",
|
|
nextDlmoHour,
|
|
seekLightWindow: { startHours: cbtMinHour, endHours: cbtMinHour + LIGHT_TIMING_WINDOW_HOURS },
|
|
avoidLightWindow: { startHours: cbtMinHour - LIGHT_TIMING_WINDOW_HOURS, endHours: cbtMinHour },
|
|
};
|
|
}
|