import assert from 'node:assert/strict'; // A gap invalidates the run. It is never subtracted from the two-hour gate // or excused by extending a guest/host deadline. Wall time also catches sleep // on platforms whose monotonic clock stops while suspended. export class HostContinuity { constructor({maximumGapMilliseconds = 30000, monotonic = () => performance.now(), wall = () => Date.now()} = {}) { assert.ok(Number.isFinite(maximumGapMilliseconds) && maximumGapMilliseconds > 0); Object.assign(this, {maximumGapMilliseconds, monotonic, wall, samples: 0, largestMonotonicGap: 0, largestWallGap: 0, failure: null}); this.sample(); } sample() { const current = {monotonic: this.monotonic(), wall: this.wall()}; if (this.previous) { const monotonicGap = current.monotonic - this.previous.monotonic, wallGap = current.wall - this.previous.wall; this.largestMonotonicGap = Math.max(this.largestMonotonicGap, monotonicGap); this.largestWallGap = Math.max(this.largestWallGap, wallGap); if (!this.failure && (!Number.isFinite(monotonicGap) || !Number.isFinite(wallGap) || monotonicGap < 0 || wallGap < 0 || monotonicGap > this.maximumGapMilliseconds || wallGap > this.maximumGapMilliseconds)) { this.failure = {previous: this.previous, current, monotonicGap, wallGap}; } } this.previous = current; this.samples++; return this.snapshot(); } assertHealthy() { this.sample(); if (this.failure) { const error = new Error('HOST_EXECUTION_INTERRUPTED: sampling continuity lost; this run cannot be accepted'); error.code = 'HOST_EXECUTION_INTERRUPTED'; throw error; } } snapshot() { return {status: this.failure ? 'HOST_EXECUTION_INTERRUPTED' : 'HOST_EXECUTION_CONTINUITY_PASSED', guestAccepted: false, productAccepted: false, maximumGapMilliseconds: this.maximumGapMilliseconds, samples: this.samples, largestMonotonicGap: this.largestMonotonicGap, largestWallGap: this.largestWallGap, failure: this.failure}; } }