@sekyro/web 0.1.0-rc.2 → 0.1.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/index.ts","../../src/core/media.ts","../../src/core/keyframe.ts","../../src/core/messages.ts","../../src/core/clip-recorder.ts","../../src/core/capture-constraints.ts","../../src/core/v3/detector-blaze.ts","../../src/core/v3/detector-native.ts","../../src/core/v3/detector.ts","../../src/core/v3/frame-quality.ts","../../src/core/v3/face-gate-v3.ts","../../src/core/v3/device-profile.ts","../../src/core/v3/detect-scheduler.ts","../../src/core/v3/detect-worker.ts","../../src/core/v3/capture-session-v3.ts"],"sourcesContent":["// @sekyro/web/core — framework-free capture modules ported byte-identically\n// from v1 (kyc-ibtikar/lib/faceCaptureV2). Calibration-pinned: the FAS-CLIP liveness model\n// was calibrated on clips produced by exactly this pipeline. See test/port-parity.test.ts.\nexport * from \"./media\";\nexport * from \"./keyframe\";\nexport * from \"./messages\";\nexport * from \"./clip-recorder\";\nexport * from \"./types\";\n// Shared, engine-agnostic capture helpers (camera constraint tier + mobile\n// heuristic + gate-geometry factors) — the v1 CaptureSession/FaceGate engine\n// was removed; v3 is the only capture path.\nexport * from \"./capture-constraints\";\n// Capture program Phase 1 — the PARALLEL v3 engine (additive exports only;\n// every module above stays byte-identical / calibration-pinned). The worker\n// entry is deliberately NOT re-exported here: hosts import the\n// `./core/v3/detect-worker` subpath so its worker-scope auto-install never\n// rides along a main-thread bundle import.\nexport * from \"./v3/detector\";\nexport * from \"./v3/face-gate-v3\";\nexport * from \"./v3/frame-quality\";\nexport * from \"./v3/device-profile\";\nexport * from \"./v3/detect-scheduler\";\nexport * from \"./v3/capture-session-v3\";\n// Doc Capture v2 (program Phase 3 — doc catalog, DocGateV1, MRZ band, frame\n// analysis, feedback aggregator, CaptureSessionDoc) is DELIBERATELY NOT part\n// of the public `core` surface: it is consumed by Sekyro's own hosted page\n// only and ships via the `@sekyro/web/internal` entry (src/internal/index.ts)\n// with no semver guarantees.\n","// PORTED byte-identical from kyc-ibtikar/lib/faceCaptureV2/media.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Do NOT edit without a calibration re-validation.\n\n// Pure, framework-free helpers for FaceCaptureV2. No React, minimal DOM.\n\n/** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.\n * WebM/VP9→VP8 only as the Firefox/older-Chromium fallback. */\nexport const MIME_CANDIDATES = [\n \"video/mp4;codecs=avc1.42E01E,mp4a.40.2\",\n \"video/mp4;codecs=avc1.42E01E\",\n \"video/mp4\",\n \"video/webm;codecs=vp9,opus\",\n \"video/webm;codecs=vp9\",\n \"video/webm;codecs=vp8,opus\",\n \"video/webm;codecs=vp8\",\n \"video/webm\",\n] as const;\n\nexport type CameraErrorKind =\n | \"permission\"\n | \"notfound\"\n | \"inuse\"\n | \"overconstrained\"\n | \"insecure\"\n | \"unsupported\"\n | \"generic\";\n\n/** First supported candidate, or \"\" to let the browser pick its own default. */\nexport function pickMimeType(): string {\n const MR = (globalThis as unknown as { MediaRecorder?: { isTypeSupported?: (t: string) => boolean } })\n .MediaRecorder;\n if (!MR || typeof MR.isTypeSupported !== \"function\") return \"\";\n return MIME_CANDIDATES.find((t) => MR.isTypeSupported!(t)) ?? \"\";\n}\n\n/** Default clip container when pickMimeType() === \"\" — NEVER .bin/octet-stream (REVIEW FIX 5).\n * Prefer the first webm in the ladder the browser most likely defaults to. */\nexport const DEFAULT_CLIP_MIME = \"video/webm\";\n\n/** Branch on err.name (never the message). TypeError ⇒ navigator.mediaDevices was undefined\n * (insecure/unsupported context) — surfaced as \"insecure\". */\nexport function mapGetUserMediaError(err: unknown): CameraErrorKind {\n if (err instanceof TypeError) return \"insecure\";\n const name = (err as { name?: string })?.name ?? \"\";\n switch (name) {\n case \"NotAllowedError\":\n case \"PermissionDeniedError\":\n return \"permission\";\n case \"NotFoundError\":\n case \"DevicesNotFoundError\":\n return \"notfound\";\n case \"NotReadableError\":\n case \"TrackStartError\":\n return \"inuse\";\n case \"OverconstrainedError\":\n case \"ConstraintNotSatisfiedError\":\n return \"overconstrained\";\n default:\n return \"generic\";\n }\n}\n\nexport function cameraPreflight(): \"INSECURE_CONTEXT\" | \"UNSUPPORTED\" | \"OK\" {\n const w = globalThis as unknown as { window?: { isSecureContext?: boolean }; navigator?: Navigator };\n if (typeof w.window !== \"undefined\" && w.window.isSecureContext === false)\n return \"INSECURE_CONTEXT\";\n const md = (w.navigator as Navigator | undefined)?.mediaDevices as\n | { getUserMedia?: unknown }\n | undefined;\n if (!md || typeof md.getUserMedia !== \"function\") return \"UNSUPPORTED\";\n return \"OK\";\n}\n\n/** iOS Safari (and any browser) may lack MediaRecorder entirely — detect BEFORE prompting\n * for the camera so we can fall back to the v1 single-photo path (REVIEW FIX 1). */\nexport function isMediaRecorderSupported(): boolean {\n const MR = (globalThis as unknown as { MediaRecorder?: { isTypeSupported?: unknown } }).MediaRecorder;\n return typeof MR !== \"undefined\" && typeof (MR as { isTypeSupported?: unknown }).isTypeSupported === \"function\";\n}\n\nexport const MAX_CLIP_BYTES = 8 * 1024 * 1024; // 8 MB hard cap (shared with the /api/liveness/v2 contract)\nexport function isClipTooLarge(blob: Blob): boolean {\n return blob.size > MAX_CLIP_BYTES;\n}\n\nexport function extForMime(mime: string): string {\n const m = (mime || \"\").toLowerCase();\n if (m.startsWith(\"image/jpeg\")) return \"jpg\";\n if (m.startsWith(\"video/mp4\")) return \"mp4\";\n if (m.startsWith(\"video/webm\")) return \"webm\";\n // Never .bin — default to the clip container we actually record (REVIEW FIX 5).\n return \"webm\";\n}\n\n/** Build the exact multipart body /api/liveness/v2 expects: fields `token`, files `clip` + `keyframe`.\n * Caller must NOT set Content-Type — the browser adds the boundary. */\nexport function buildLivenessV2FormData(args: {\n token: string;\n clip: Blob;\n keyframe: Blob;\n ts?: number;\n}): FormData {\n const { token, clip, keyframe } = args;\n const ts = args.ts ?? Date.now();\n const clipType = clip.type || DEFAULT_CLIP_MIME;\n const kfType = keyframe.type || \"image/jpeg\";\n const fd = new FormData();\n fd.append(\"token\", token);\n fd.append(\"clip\", new File([clip], `liveness-${ts}.${extForMime(clipType)}`, { type: clipType }));\n fd.append(\"keyframe\", new File([keyframe], `keyframe-${ts}.${extForMime(kfType)}`, { type: kfType }));\n return fd;\n}\n","// PORTED byte-identical from kyc-ibtikar/lib/faceCaptureV2/keyframe.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Do NOT edit without a calibration re-validation.\n\n// Grab ONE mirrored frontal keyframe from the live <video> into a JPEG Blob (a file part,\n// not a dataURL). Mirror matches the selfie preview (front camera), same as FaceCapture v1.\nexport function captureMirroredKeyframe(\n video: HTMLVideoElement,\n canvas: HTMLCanvasElement,\n quality = 0.92,\n): Promise<Blob> {\n return new Promise((resolve, reject) => {\n const w = video.videoWidth;\n const h = video.videoHeight;\n if (!w || !h) {\n reject(new Error(\"video-not-ready\"));\n return;\n }\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) {\n reject(new Error(\"no-2d-context\"));\n return;\n }\n canvas.width = w;\n canvas.height = h;\n ctx.scale(-1, 1);\n ctx.drawImage(video, -w, 0);\n canvas.toBlob(\n (blob) => (blob ? resolve(blob) : reject(new Error(\"empty-keyframe\"))),\n \"image/jpeg\",\n quality,\n );\n });\n}\n","// PORTED byte-identical from kyc-ibtikar/lib/faceCaptureV2/messages.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Do NOT edit without a calibration re-validation.\n\nimport type { CameraErrorKind } from \"./media\";\n\n/** i18n key + inline French fallback (repo convention: t(key, frenchFallback)). */\nexport const errorCopy: Record<CameraErrorKind, { key: string; fr: string }> = {\n permission: {\n key: \"fcv2.err.permission\",\n fr: \"Autorisez la caméra dans les réglages du navigateur (icône caméra dans la barre d’adresse), puis réessayez.\",\n },\n notfound: {\n key: \"fcv2.err.notfound\",\n fr: \"Aucune caméra détectée. Branchez ou activez une caméra, puis réessayez.\",\n },\n inuse: {\n key: \"fcv2.err.inuse\",\n fr: \"La caméra est utilisée par une autre application. Fermez-la puis réessayez.\",\n },\n overconstrained: {\n key: \"fcv2.err.overconstrained\",\n fr: \"La caméra ne prend pas en charge les réglages demandés. Nouvel essai en cours…\",\n },\n insecure: {\n key: \"fcv2.err.insecure\",\n fr: \"La caméra nécessite une connexion sécurisée (HTTPS). Ouvrez la page en HTTPS.\",\n },\n unsupported: {\n key: \"fcv2.err.unsupported\",\n fr: \"Votre navigateur ne prend pas en charge l’enregistrement vidéo. Utilisez un navigateur récent.\",\n },\n generic: {\n key: \"fcv2.err.generic\",\n fr: \"Caméra indisponible. Réessayez ou contactez le support.\",\n },\n};\n\nexport const uiCopy = {\n recording: { key: \"fcv2.recording\", fr: \"Enregistrement en cours…\" },\n uploading: { key: \"fcv2.uploading\", fr: \"Envoi en cours…\" },\n clipTooLarge: {\n key: \"fcv2.err.cliptoolarge\",\n fr: \"La vidéo est trop volumineuse. Réessayez dans un endroit mieux éclairé.\",\n },\n retry: { key: \"fcv2.retry\", fr: \"Réessayer\" },\n listen: { key: \"fcv2.listen\", fr: \"Écouter\" },\n} as const;\n","// De-hooked port of kyc-ibtikar/lib/faceCaptureV2/useClipRecorder.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Framework-free class: useRef → private fields,\n// useCallback(start) → record(), stopAndCleanup + the unmount useEffect → stop().\n// Behavior is the v1 hook's, VERBATIM (iOS workarounds included). Source line references\n// (kyc-ibtikar/lib/faceCaptureV2/useClipRecorder.ts):\n// - constants CLIP_MS / TIMESLICE_MS / STOP_GRACE_MS / VIDEO_BPS ............ L10-13\n// - ClipError(kind, msg?) .................................................. L15-21\n// - guarded double MediaRecorder construction (REVIEW FIX 1) ............... L47-63\n// - single-settle guard + timer clearing ................................... L66-71\n// - finalize: Blob(type = recorder.mimeType || picked || DEFAULT_CLIP_MIME)\n// + post-hoc size-cap check .............................................. L73-82\n// - incremental 8MB cap enforcement on dataavailable (REVIEW FIX 7) ........ L84-100\n// - onstop → finalize, onerror → generic, guarded start(TIMESLICE_MS) ...... L101-109\n// - hard stop at CLIP_MS + iOS stop-grace finalize (REVIEW FIX 3) .......... L111-124\n// - teardown: clear timers, stop recorder, stop ALL tracks (REVIEW FIX 8) .. L128-145\n// V2 additions on top of the verbatim behavior (both zero-impact on clip bytes, both\n// required because a class instance outlives one recording where v1's hook state was\n// remounted fresh): a re-entrancy guard in record(), and clearing stale timers when a\n// new recording starts. See the record() JSDoc.\n// Do NOT edit without a calibration re-validation.\nimport {\n pickMimeType,\n isClipTooLarge,\n MAX_CLIP_BYTES,\n DEFAULT_CLIP_MIME,\n type CameraErrorKind,\n} from \"./media\";\n\nexport const CLIP_MS = 2500; // 2.5s, within the 2.0–3.0s target window\nexport const TIMESLICE_MS = 1000; // periodic dataavailable — iOS reliability workaround\nexport const STOP_GRACE_MS = 1500; // iOS: if onstop never fires, finalize from chunks\n// 2.5 Mbps pairs with the 720p capture tier (capture-session.ts): 1.5 Mbps at\n// 720p over-compresses exactly the texture the FAS-CLIP head needs. ~0.8MB per\n// 2.5s clip — well under the 8MB client cap / 15MB server caps.\nexport const VIDEO_BPS = 2_500_000;\n\nexport type ClipErrorKind = CameraErrorKind | \"cliptoolarge\";\n\nexport class ClipError extends Error {\n kind: ClipErrorKind;\n constructor(kind: ClipErrorKind, msg?: string) {\n super(msg ?? kind);\n this.kind = kind;\n }\n}\n\nexport interface ClipResult {\n blob: Blob;\n /** Container mime the clip was finalized with (recorder.mimeType || picked || DEFAULT_CLIP_MIME). */\n mimeType: string;\n}\n\nexport class ClipRecorder {\n private recorder: MediaRecorder | null = null;\n private stream: MediaStream | null = null; // own field so teardown can stop tracks (REVIEW FIX 8)\n private chunks: Blob[] = [];\n private bytes = 0;\n private hardStopTimer: ReturnType<typeof setTimeout> | null = null;\n private graceTimer: ReturnType<typeof setTimeout> | null = null;\n private settled = false;\n\n private clearTimers(): void {\n if (this.hardStopTimer) clearTimeout(this.hardStopTimer);\n if (this.graceTimer) clearTimeout(this.graceTimer);\n this.hardStopTimer = null;\n this.graceTimer = null;\n }\n\n /** Records CLIP_MS of the stream. Resolves with the clip blob + its container mime;\n * rejects with ClipError. Behavior contract is the v1 hook's `start`, verbatim\n * (iOS workarounds included).\n *\n * ONE RECORDING AT A TIME: chunk/byte/timer state is shared per instance, so a\n * second record() while one is in flight rejects ClipError(\"generic\") instead of\n * corrupting the in-flight clip. (v2 guard — v1's hook was gated by its owning\n * component; a class API invites reuse. Zero impact on clip bytes.)\n *\n * `onStopped` (optional) fires ONCE the moment the CLIP_MS recording window\n * elapses (the hard-stop), BEFORE finalize — which on iOS can lag up to\n * STOP_GRACE_MS while onstop flushes the last chunk. It lets the host freeze\n * the display on the already-captured keyframe the instant recording ends,\n * instead of waiting for the blob. PURE NOTIFICATION — it does not touch\n * timers, chunks, or the finalize path, so it is calibration-neutral (no\n * effect on clip bytes). Never fires on a rejected capture (error /\n * cliptoolarge settle before the hard-stop and clear the timer). */\n record(stream: MediaStream, onStopped?: () => void): Promise<ClipResult> {\n if (this.recorder && !this.settled) {\n return Promise.reject(\n new ClipError(\n \"generic\",\n \"record() called while a recording is in flight — ClipRecorder handles one recording at a time\",\n ),\n );\n }\n this.recorder = null; // so a failed construction below never blocks a retry\n // De-hooking correction (zero impact on clip bytes): v1 got fresh refs per hook\n // mount, so a previous recording's post-settle grace timer (the hard-stop callback\n // arms it AFTER settle cleared timers — v1-verbatim) could never leak into a new\n // one. On a reused instance it would fire mid-flight, settle the fresh state, and\n // clear the new hard-stop timer — so drop stale timers before starting.\n this.clearTimers();\n this.chunks = [];\n this.bytes = 0;\n this.settled = false;\n this.stream = stream;\n const picked = pickMimeType();\n\n return new Promise<ClipResult>((resolve, reject) => {\n // Guarded construction — iOS Safari may lack MediaRecorder entirely (REVIEW FIX 1).\n let recorder: MediaRecorder;\n try {\n recorder = new MediaRecorder(\n stream,\n picked\n ? { mimeType: picked, videoBitsPerSecond: VIDEO_BPS }\n : { videoBitsPerSecond: VIDEO_BPS },\n );\n } catch {\n try {\n recorder = new MediaRecorder(stream); // last resort: browser defaults\n } catch {\n reject(new ClipError(\"unsupported\"));\n return;\n }\n }\n this.recorder = recorder;\n\n const settle = (fn: () => void) => {\n if (this.settled) return;\n this.settled = true;\n this.clearTimers();\n fn();\n };\n\n const finalize = () =>\n settle(() => {\n const type = recorder.mimeType || picked || DEFAULT_CLIP_MIME;\n const blob = new Blob(this.chunks, { type });\n if (isClipTooLarge(blob)) {\n reject(new ClipError(\"cliptoolarge\"));\n return;\n }\n resolve({ blob, mimeType: type });\n });\n\n recorder.ondataavailable = (e: BlobEvent) => {\n if (e.data && e.data.size) {\n this.chunks.push(e.data);\n this.bytes += e.data.size;\n // Enforce the 8MB cap INCREMENTALLY — stop + reject as soon as exceeded (REVIEW FIX 7).\n if (this.bytes > MAX_CLIP_BYTES) {\n settle(() => {\n try {\n if (recorder.state !== \"inactive\") recorder.stop();\n } catch {\n /* noop */\n }\n reject(new ClipError(\"cliptoolarge\"));\n });\n }\n }\n };\n recorder.onstop = finalize;\n recorder.onerror = () => settle(() => reject(new ClipError(\"generic\")));\n\n try {\n recorder.start(TIMESLICE_MS);\n } catch {\n settle(() => reject(new ClipError(\"generic\")));\n return;\n }\n\n // Hard stop at CLIP_MS; gate on state, not on frame count.\n this.hardStopTimer = setTimeout(() => {\n // Recording window elapsed — the clip is DONE. Notify BEFORE finalize\n // (which may lag on iOS) so the host can freeze on the keyframe now.\n // Guarded by `settled`: an error/cliptoolarge before the hard-stop has\n // already cleared this timer, so this only runs for a real stop.\n if (!this.settled) onStopped?.();\n if (recorder.state !== \"inactive\") {\n try {\n recorder.stop();\n } catch {\n finalize();\n }\n // iOS safety-net: onstop may never fire — finalize from chunks (REVIEW FIX 3).\n this.graceTimer = setTimeout(finalize, STOP_GRACE_MS);\n } else {\n finalize();\n }\n }, CLIP_MS);\n });\n }\n\n /** Idempotent teardown: stop recorder + ALL tracks (v1 `stopAndCleanup` + the unmount\n * effect). Optional `stream` override mirrors v1's `stopAndCleanup(stream?)`.\n *\n * MID-RECORDING SEMANTICS (verbatim v1): calling stop() while a record() is in\n * flight may LATER resolve the pending promise with a TRUNCATED clip (recorder.stop()\n * fires onstop → finalize from whatever chunks arrived so far), or — because this\n * method clears the hard-stop/grace timers — never settle it at all if onstop never\n * fires (the iOS grace path has been torn down). Callers MUST NOT treat a resolution\n * arriving after stop() as a full CLIP_MS clip, and must not await a record()\n * promise past stop() without their own timeout. (Task 4's CaptureSession owns\n * sequencing on top of this contract.) */\n stop(stream?: MediaStream | null): void {\n this.clearTimers();\n const rec = this.recorder;\n if (rec && rec.state !== \"inactive\") {\n try {\n rec.stop();\n } catch {\n /* noop */\n }\n }\n this.recorder = null;\n const s = stream ?? this.stream;\n s?.getTracks().forEach((t) => t.stop());\n this.stream = null;\n }\n}\n","// Shared capture helpers — used by BOTH the (now sole) v3 engine and the\n// hosted gate-debug overlay. Extracted from the former v1 capture-session.ts\n// when the v1 engine was removed: the camera constraint tier + the mobile\n// heuristic are engine-agnostic, and the gate-geometry factors feed the\n// hosted debug overlay's tolerance rings. Zero React, calibration-pinned.\n\n/** getUserMedia constraint tier — 720p-class on every device since 2026-07-06.\n * The v2 FAS-CLIP liveness head loses its texture cues below ~720p: the SAME\n * genuine clip scores heads 0.0001 at 720x1280 vs 0.355 at the old 480x360\n * mobile tier, which pushed real users into review (first observed live on\n * staging 2026-07-06; falsified on corpus clips the same day). Dimensions are\n * sensor-relative (landscape); mobile browsers deliver portrait via rotation\n * metadata, which the liveness service's decoder applies (cv2\n * ORIENTATION_AUTO). `isMobile` is kept for call-site compat and future\n * divergence — both tiers are 720p today. Bitrate pairs with VIDEO_BPS in\n * clip-recorder.ts (2.5 Mbps). */\nexport function buildCaptureConstraints(\n isMobile: boolean,\n facingMode: \"user\" | \"environment\",\n): MediaStreamConstraints {\n void isMobile;\n return {\n video: {\n width: { ideal: 1280, max: 1280 },\n height: { ideal: 720, max: 720 },\n facingMode: facingMode,\n frameRate: { ideal: 24, max: 30 },\n },\n audio: false,\n };\n}\n\n/** v1 mobile heuristic (FaceCaptureV2.tsx L216-224). */\nexport function detectIsMobile(): boolean {\n if (typeof window === \"undefined\" || typeof navigator === \"undefined\") return false;\n return (\n window.innerWidth <= 768 ||\n /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(\n String(navigator.userAgent ?? \"\"),\n )\n );\n}\n\n// ── gate geometry factors ─────────────────────────────────────────────────────\n// The calibration-pinned gate math the hosted `?debug=gate` overlay derives its\n// tolerance rings from (lib/gate-geometry-constants.ts). Kept exported here after\n// the v1 FaceGate was removed so the overlay never restates them as literals.\n\n/** Gate radius as a fraction of the guidance circle (v1 L501: circleSize × 0.45). */\nexport const CIRCLE_RADIUS_FACTOR = 0.45;\n/** `inCircle` tolerance as a fraction of the gate radius (v1 L508: r × 0.9). */\nexport const IN_CIRCLE_FACTOR = 0.9;\n/** `centered` tolerance as a fraction of the gate radius (v1 L509: r × 0.4). */\nexport const CENTERED_FACTOR = 0.4;\n","// BlazeFace short-range tier (Task 7) — MediaPipe tasks-vision FaceDetector,\n// the modern default: strong on large/close faces, ~15–40ms on low-end\n// WASM+SIMD. tasks-vision is imported LAZILY (only when this tier is\n// selected) and every asset is SELF-HOSTED under the v3 asset base (hosted\n// CSP is connect-src 'self' — no CDN): the wasm fileset via\n// FilesetResolver.forVisionTasks(base) and the model at\n// `${base}/blaze_face_short_range.tflite` (synced by\n// identity-hosted/scripts/sync-models-v3.mjs, sha256-manifested).\n//\n// DELEGATE = 'CPU' (2026-07-09, capture-v3 hardening — the load-bearing fix):\n// tasks-vision defaults `baseOptions.delegate` to the WebGL/GPU delegate,\n// which HANGS on iOS Safari — every field capture blew the 10s init deadline\n// (`blaze:blaze_init_timeout`) and silently fell to the deprecated face-api\n// floor at ~2.4fps. BlazeFace short-range is tiny (~229 KB) and fast on the\n// WASM+SIMD CPU delegate, so we pin CPU UNCONDITIONALLY: reliability across\n// iOS Safari + Chrome beats the marginal desktop-GPU speedup (and the GPU\n// path is exactly the bug). A GPU-first-with-CPU-fallback dance would only\n// re-introduce the hang risk inside the init budget for no real win.\nimport { type Detector, type FaceObservation, intrinsicSize, toStreamPixels } from \"./detector\";\n\n/** createFromOptions must resolve within this window or the ladder falls\n * through with `blaze_init_timeout` (overridable via CreateDetectorOptions).\n * Raised 5s→10s: on iOS Safari the COLD wasm SIMD compile of tasks-vision can\n * exceed 5s on the FIRST (unwarmed) capture. Since the face-api floor was\n * dropped (2026-07-09), blowing this deadline is now a HARD capture failure\n * (error{kind:'models'} — retryable), not a silent degrade, so the CPU\n * delegate above (which makes init actually complete on iOS) is what keeps\n * this deadline reachable. The hosted warm path\n * (identity-hosted/lib/warm-models.ts) pre-warms this tier in idle time so\n * capture usually reuses a hot instance; this larger deadline only covers the\n * un-warmed fallback (Data-Saver, deep-link straight to liveness). */\nexport const BLAZE_INIT_TIMEOUT_MS = 10_000;\n\ninterface TasksVisionDetection {\n boundingBox?: { originX: number; originY: number; width: number; height: number };\n categories: Array<{ score: number }>;\n /** NORMALIZED to the input image (0..1) — tasks-vision docs; index 0 =\n * right eye, 1 = left eye (SUBJECT perspective). We re-order by image-x\n * (the FaceObservation convention), so the doc order is informative only. */\n keypoints?: Array<{ x: number; y: number }>;\n}\n\ninterface TasksVisionFaceDetector {\n detect(source: unknown): { detections: TasksVisionDetection[] };\n close(): void;\n}\n\nexport class BlazeDetector implements Detector {\n readonly tier = \"blaze\" as const;\n readonly fallbackReason?: string;\n private readonly inner: TasksVisionFaceDetector;\n\n private constructor(inner: TasksVisionFaceDetector, fallbackReason?: string) {\n this.inner = inner;\n if (fallbackReason !== undefined) this.fallbackReason = fallbackReason;\n }\n\n static async create(assetBaseUrl: string, fallbackReason?: string): Promise<BlazeDetector> {\n const vision = await import(\"@mediapipe/tasks-vision\");\n const fileset = await vision.FilesetResolver.forVisionTasks(assetBaseUrl);\n const inner = (await vision.FaceDetector.createFromOptions(fileset, {\n baseOptions: {\n modelAssetPath: `${assetBaseUrl}/blaze_face_short_range.tflite`,\n // CPU delegate — the iOS-Safari-safe path (see header). NEVER 'GPU'.\n delegate: \"CPU\",\n },\n runningMode: \"IMAGE\",\n })) as unknown as TasksVisionFaceDetector;\n return new BlazeDetector(inner, fallbackReason);\n }\n\n async detect(\n source: CanvasImageSource,\n sourceWidth: number,\n sourceHeight: number,\n ): Promise<FaceObservation | null> {\n let detections: TasksVisionDetection[];\n try {\n detections = this.inner.detect(source).detections;\n } catch {\n return null; // never rejects mid-loop\n }\n const best = pickMostConfident(detections);\n if (best?.boundingBox === undefined) return null;\n const size = intrinsicSize(source);\n const eyes = extractEyes(best.keypoints, size);\n const observation: FaceObservation = {\n box: {\n x: best.boundingBox.originX,\n y: best.boundingBox.originY,\n width: best.boundingBox.width,\n height: best.boundingBox.height,\n },\n ...(eyes !== undefined ? { eyes } : {}),\n score: best.categories[0]?.score ?? 0,\n };\n return toStreamPixels(observation, source, sourceWidth, sourceHeight);\n }\n\n destroy(): void {\n try {\n this.inner.close();\n } catch {\n // wasm teardown failures are inert\n }\n }\n}\n\nfunction pickMostConfident(detections: TasksVisionDetection[]): TasksVisionDetection | undefined {\n let best: TasksVisionDetection | undefined;\n let bestScore = -1;\n for (const detection of detections) {\n const score = detection.categories[0]?.score ?? 0;\n if (score > bestScore) {\n best = detection;\n bestScore = score;\n }\n }\n return best;\n}\n\n/** Keypoints 0/1 (the eye pair) — normalized → SOURCE px, ordered by image-x. */\nfunction extractEyes(\n keypoints: Array<{ x: number; y: number }> | undefined,\n size: { width: number; height: number },\n): FaceObservation[\"eyes\"] | undefined {\n const a = keypoints?.[0];\n const b = keypoints?.[1];\n if (a === undefined || b === undefined) return undefined;\n const toSource = (p: { x: number; y: number }) => ({ x: p.x * size.width, y: p.y * size.height });\n const [pa, pb] = [toSource(a), toSource(b)];\n return pa.x <= pb.x ? { left: pa, right: pb } : { left: pb, right: pa };\n}\n","// Native FaceDetector tier (Task 6) — the Shape Detection API: free,\n// hardware-backed where implemented (Chrome/Android, some WebViews). Probed\n// with a 1-frame smoke detect because several browsers EXPOSE the constructor\n// but throw `Face detection service unavailable` at runtime.\nimport { type Detector, type FaceObservation, toStreamPixels } from \"./detector\";\n\ninterface NativeLandmark {\n type: string;\n locations: Array<{ x: number; y: number }>;\n}\n\ninterface NativeDetectedFace {\n boundingBox: { x: number; y: number; width: number; height: number };\n landmarks?: NativeLandmark[];\n}\n\nexport interface NativeFaceDetectorLike {\n detect(source: CanvasImageSource): Promise<NativeDetectedFace[]>;\n}\n\ntype NativeGlobal = typeof globalThis & {\n FaceDetector?: new (options: { fastMode: boolean; maxDetectedFaces: number }) => NativeFaceDetectorLike;\n};\n\nfunction smokeSource(): CanvasImageSource {\n if (typeof OffscreenCanvas === \"function\") return new OffscreenCanvas(2, 2);\n const canvas = document.createElement(\"canvas\");\n canvas.width = 2;\n canvas.height = 2;\n return canvas;\n}\n\n/** Constructor + 1-frame smoke detect (must not throw; result irrelevant). */\nexport async function probeNativeDetector(): Promise<\n { ok: true; instance: NativeFaceDetectorLike } | { ok: false; reason: string }\n> {\n const ctor = (globalThis as NativeGlobal).FaceDetector;\n if (typeof ctor !== \"function\") return { ok: false, reason: \"unsupported\" };\n try {\n const instance = new ctor({ fastMode: true, maxDetectedFaces: 1 });\n await instance.detect(smokeSource());\n return { ok: true, instance };\n } catch (err) {\n return { ok: false, reason: `smoke_failed:${err instanceof Error ? err.message : String(err)}` };\n }\n}\n\nexport class NativeDetector implements Detector {\n readonly tier = \"native\" as const;\n readonly fallbackReason?: string;\n private readonly inner: NativeFaceDetectorLike;\n\n constructor(inner: NativeFaceDetectorLike, fallbackReason?: string) {\n this.inner = inner;\n if (fallbackReason !== undefined) this.fallbackReason = fallbackReason;\n }\n\n async detect(\n source: CanvasImageSource,\n sourceWidth: number,\n sourceHeight: number,\n ): Promise<FaceObservation | null> {\n let faces: NativeDetectedFace[];\n try {\n faces = await this.inner.detect(source);\n } catch {\n return null; // never rejects mid-loop\n }\n const face = faces[0];\n if (face === undefined) return null;\n const eyes = extractEyes(face.landmarks);\n const observation: FaceObservation = {\n box: {\n x: face.boundingBox.x,\n y: face.boundingBox.y,\n width: face.boundingBox.width,\n height: face.boundingBox.height,\n },\n ...(eyes !== undefined ? { eyes } : {}),\n // The Shape Detection API exposes no confidence — the smoke-tested\n // native tier treats any detection as confident.\n score: 1,\n };\n return toStreamPixels(observation, source, sourceWidth, sourceHeight);\n }\n\n destroy(): void {\n // The native detector holds no resources the page must release.\n }\n}\n\n/** Two `eye` landmarks → {left, right} by image-x (see FaceObservation). */\nfunction extractEyes(\n landmarks: NativeLandmark[] | undefined,\n): FaceObservation[\"eyes\"] | undefined {\n if (landmarks === undefined) return undefined;\n const eyePoints = landmarks\n .filter((landmark) => landmark.type === \"eye\")\n .map((landmark) => landmark.locations[0])\n .filter((point): point is { x: number; y: number } => point !== undefined);\n const [a, b] = eyePoints;\n if (a === undefined || b === undefined) return undefined;\n return a.x <= b.x ? { left: a, right: b } : { left: b, right: a };\n}\n","// v3 Detector abstraction (capture program Task 6) — one detection seam with\n// capability-probed tiers. NEW parallel module: nothing in the v1 core\n// imports from v3/*, and the calibration-pinned v1 gate math is untouched.\n//\n// Ladder (DEFAULT_TIER_ORDER): `native` (the browser's FaceDetector — free,\n// hardware-backed where it exists) → `blaze` (MediaPipe BlazeFace short-range,\n// Task 7). The legacy `faceapi` floor was DROPPED (2026-07-09, capture-v3\n// hardening): field telemetry showed BlazeFace never initialized (the GPU\n// delegate hung on iOS → `blaze_init_timeout`) so EVERY capture silently ran\n// the deprecated ~2.4fps face-api floor. With the CPU-delegate blaze fix,\n// face-api is dead weight — and a floor that masks a blaze regression is worse\n// than none, so the ladder is now native→blaze with NO fallback.\n//\n// Contract change: createDetector still never throws while a tier can be\n// built, but with no floor it REJECTS (DetectorLadderError) once the ladder is\n// exhausted — a CLEAN, non-hanging failure carrying the per-tier reasons.\n// CaptureSessionV3.run() maps that rejection to error{kind:'models'}\n// (retryable; the hosted UI renders a retry). A skipped tier still records a\n// `fallbackReason` (exposed on the returned Detector) so a native→blaze\n// fall-through stays observable in telemetry.\nimport { BLAZE_INIT_TIMEOUT_MS, BlazeDetector } from \"./detector-blaze\";\nimport { NativeDetector, probeNativeDetector } from \"./detector-native\";\n\nexport interface FaceObservation {\n /** Stream-pixel box. */\n box: { x: number; y: number; width: number; height: number };\n /** Stream-pixel eye centers when the tier provides them (native:\n * landmarks?, blaze: keypoints). Convention: `left` = smaller x in IMAGE\n * coordinates — gate math only uses the midpoint and |roll|, so the\n * person-left/image-left distinction never matters. */\n eyes?: { left: { x: number; y: number }; right: { x: number; y: number } };\n score: number;\n}\n\nexport interface Detector {\n readonly tier: \"native\" | \"blaze\";\n /** Why higher tiers were skipped (telemetry) — absent when the first\n * preference won. */\n readonly fallbackReason?: string;\n /** Detect on a (possibly downscaled) snapshot; `sourceWidth/Height` are the\n * STREAM dimensions the observation must be normalized to. Returns the\n * single most-confident face or null; NEVER rejects. */\n detect(\n source: CanvasImageSource,\n sourceWidth: number,\n sourceHeight: number,\n ): Promise<FaceObservation | null>;\n destroy(): void;\n}\n\nexport interface CreateDetectorOptions {\n /** v3 self-hosted assets base (tasks-vision wasm + blaze tflite) — hosted\n * serves `/models-v3`, a sha256-manifested directory. */\n v3AssetBaseUrl?: string;\n preferred?: Detector[\"tier\"][];\n /** Test/tuning override for the blaze init deadline. */\n blazeInitTimeoutMs?: number;\n}\n\nexport const DEFAULT_V3_ASSET_BASE_URL = \"/models-v3\";\n\nexport const DEFAULT_TIER_ORDER: Detector[\"tier\"][] = [\"native\", \"blaze\"];\n\n/** Thrown by createDetector when the ENTIRE tier ladder is exhausted. Since the\n * face-api floor was dropped (2026-07-09) there is no last resort, so blaze\n * failing on an already-native-less platform leaves NO detector. Carries the\n * joined per-tier reasons ('native:unsupported; blaze:blaze_init_timeout') as\n * `fallbackReason` for telemetry. Callers MUST map this to a retryable models\n * error — never a hang (CaptureSessionV3.run → error{kind:'models'}). */\nexport class DetectorLadderError extends Error {\n readonly fallbackReason: string;\n constructor(fallbackReason: string) {\n super(`no detector tier available (${fallbackReason})`);\n this.name = \"DetectorLadderError\";\n this.fallbackReason = fallbackReason;\n }\n}\n\n/** Intrinsic pixel size of a snapshot source (video → videoWidth, image →\n * naturalWidth, canvas/bitmap → width). Property-sniffed so worker-side\n * sources (OffscreenCanvas, ImageBitmap) work without instanceof. */\nexport function intrinsicSize(source: CanvasImageSource): { width: number; height: number } {\n const candidate = source as {\n videoWidth?: number;\n videoHeight?: number;\n naturalWidth?: number;\n naturalHeight?: number;\n width?: number | { baseVal?: { value?: number } };\n height?: number | { baseVal?: { value?: number } };\n };\n if (typeof candidate.videoWidth === \"number\" && candidate.videoWidth > 0) {\n return { width: candidate.videoWidth, height: candidate.videoHeight ?? 0 };\n }\n if (typeof candidate.naturalWidth === \"number\" && candidate.naturalWidth > 0) {\n return { width: candidate.naturalWidth, height: candidate.naturalHeight ?? 0 };\n }\n const width = typeof candidate.width === \"number\" ? candidate.width : 0;\n const height = typeof candidate.height === \"number\" ? candidate.height : 0;\n return { width, height };\n}\n\n/** Scale a source-space observation to stream px. Exported for adapters. */\nexport function toStreamPixels(\n observation: FaceObservation,\n source: CanvasImageSource,\n streamWidth: number,\n streamHeight: number,\n): FaceObservation {\n const size = intrinsicSize(source);\n const scaleX = size.width > 0 ? streamWidth / size.width : 1;\n const scaleY = size.height > 0 ? streamHeight / size.height : 1;\n const scalePoint = (p: { x: number; y: number }) => ({ x: p.x * scaleX, y: p.y * scaleY });\n return {\n box: {\n x: observation.box.x * scaleX,\n y: observation.box.y * scaleY,\n width: observation.box.width * scaleX,\n height: observation.box.height * scaleY,\n },\n ...(observation.eyes !== undefined\n ? { eyes: { left: scalePoint(observation.eyes.left), right: scalePoint(observation.eyes.right) } }\n : {}),\n score: observation.score,\n };\n}\n\nfunction describeError(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nexport async function createDetector(options: CreateDetectorOptions): Promise<Detector> {\n const order = options.preferred ?? DEFAULT_TIER_ORDER;\n const reasons: string[] = [];\n for (const tier of order) {\n if (tier === \"native\") {\n const probed = await probeNativeDetector();\n if (probed.ok) {\n return new NativeDetector(probed.instance, reasonOf(reasons));\n }\n reasons.push(`native:${probed.reason}`);\n continue;\n }\n // tier === \"blaze\": smoke test = createFromOptions resolving within the\n // deadline (wasm fetch/compile can hang on hostile networks — never stall\n // the ladder).\n try {\n return await withTimeout(\n BlazeDetector.create(\n options.v3AssetBaseUrl ?? DEFAULT_V3_ASSET_BASE_URL,\n reasonOf(reasons),\n ),\n options.blazeInitTimeoutMs ?? BLAZE_INIT_TIMEOUT_MS,\n );\n } catch (err) {\n reasons.push(\n err instanceof InitTimeoutError\n ? \"blaze:blaze_init_timeout\"\n : `blaze:${describeError(err)}`,\n );\n }\n }\n // Ladder exhausted — the face-api floor is gone, so there is NO fallback.\n // REJECT cleanly with the recorded reasons; CaptureSessionV3.run() maps this\n // to a retryable error{kind:'models'} (a bounded failure the hosted UI\n // retries) rather than hanging. NEVER return a null-yielding detector here.\n throw new DetectorLadderError(reasonOf(reasons) ?? \"no_tier_available\");\n}\n\nfunction reasonOf(reasons: string[]): string | undefined {\n return reasons.length > 0 ? reasons.join(\"; \") : undefined;\n}\n\nclass InitTimeoutError extends Error {}\n\nfunction withTimeout<T extends { destroy(): void }>(\n promise: Promise<T>,\n deadlineMs: number,\n): Promise<T> {\n return new Promise<T>((resolvePromise, rejectPromise) => {\n const timer = setTimeout(() => {\n rejectPromise(new InitTimeoutError(`init exceeded ${deadlineMs}ms`));\n // A late resolution after the deadline is an orphan (wasm/GPU\n // delegate) — release it instead of leaking until navigation.\n promise.then(\n (value) => value.destroy(),\n () => undefined,\n );\n }, deadlineMs);\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolvePromise(value);\n },\n (err) => {\n clearTimeout(timer);\n rejectPromise(err);\n },\n );\n });\n}\n","// frame-quality (Task 8) — pure, deterministic image measures on a small\n// (≤96px) face crop. No canvas access here: callers hand in ImageData; that\n// keeps these functions golden-testable and worker-portable.\n\n/** Laplacian-variance normalization reference — crops whose edge variance\n * reaches this value (or beyond) count as fully sharp. */\nexport const SHARP_REF = 180;\n\n/** Mean-luma comfort band: inside → exposure 1; outside → linear falloff.\n * Dark bound raised 70→100 (operator ruling 2026-07-07): face crops in the\n * 70–100 range passed the gate but kept drawing dark-face review verdicts —\n * gating them here converts that into pre-capture more_light coaching. */\nexport const EXPOSURE_BAND: readonly [number, number] = [100, 190];\n\n/** Luma distance that zeroes the exposure factor (≈ one stop past the band). */\nconst EXPOSURE_FALLOFF = 64;\n\n/** Rec.601 luma. */\nfunction lumaAt(data: Uint8ClampedArray, index: number): number {\n return (\n 0.299 * (data[index] ?? 0) + 0.587 * (data[index + 1] ?? 0) + 0.114 * (data[index + 2] ?? 0)\n );\n}\n\nexport function meanLuma(image: ImageData): number {\n const { data, width, height } = image;\n const pixels = width * height;\n if (pixels === 0) return 0;\n let sum = 0;\n for (let i = 0; i < pixels; i += 1) sum += lumaAt(data, i * 4);\n return sum / pixels;\n}\n\n/**\n * Sharpness = variance of the 3×3 Laplacian (∇² kernel [0,1,0;1,−4,1;0,1,0])\n * over the interior pixels, normalized 0..1 against SHARP_REF. Flat crop → 0;\n * hard edges → 1 (clamped).\n */\nexport function sharpness(image: ImageData): number {\n const { data, width, height } = image;\n if (width < 3 || height < 3) return 0;\n const gray = new Float32Array(width * height);\n for (let i = 0; i < gray.length; i += 1) gray[i] = lumaAt(data, i * 4);\n let sum = 0;\n let sumSquares = 0;\n let count = 0;\n for (let y = 1; y < height - 1; y += 1) {\n for (let x = 1; x < width - 1; x += 1) {\n const i = y * width + x;\n const response =\n (gray[i - width] ?? 0) +\n (gray[i - 1] ?? 0) +\n (gray[i + 1] ?? 0) +\n (gray[i + width] ?? 0) -\n 4 * (gray[i] ?? 0);\n sum += response;\n sumSquares += response * response;\n count += 1;\n }\n }\n if (count === 0) return 0;\n const mean = sum / count;\n const variance = sumSquares / count - mean * mean;\n // VARIANCE against the reference (the plan's formula). Field lesson\n // (Salem's iPhone, 2026-07-07): sqrt(variance)/REF put every real face\n // crop at ~0.03-0.1 — permanently under the steady_camera threshold and\n // crushing q to zero, so the gate could never fire. Real crops have\n // Laplacian variance well above 180; a genuinely soft/blurred crop does not.\n return Math.min(1, Math.max(0, variance) / SHARP_REF);\n}\n\n/** Exposure factor: 1 inside the band; linear falloff to 0 over\n * EXPOSURE_FALLOFF luma outside it. */\nexport function exposure(image: ImageData): number {\n const mean = meanLuma(image);\n const [low, high] = EXPOSURE_BAND;\n const distance = mean < low ? low - mean : mean > high ? mean - high : 0;\n return Math.max(0, 1 - distance / EXPOSURE_FALLOFF);\n}\n","// FaceGateV3 (Task 8) — the v3 gate: scale-invariant, landmark-aware,\n// continuous-quality, gentle-drain. PARALLEL to the calibration-pinned v1\n// FaceGate (face-gate.ts) — nothing here feeds or alters v1's math.\n//\n// Design deltas vs v1 (the two field complaints this kills):\n// - the gate point is the EYE MIDPOINT when the tier provides eyes (humans\n// center their EYES, detectors center their BBOX — v1's bbox-center gate\n// read a centered face as \"high\"); box-only tiers get a documented\n// 0.12×height upward shift instead;\n// - progress is a CONTINUOUS integrator (rise 0.9/s on good quality, fall\n// 0.25/s on bad) instead of v1's ±counters — a wobble dips the progress\n// slightly instead of resetting the attempt.\n//\n// q AGGREGATION = MIN over factors (operator ruling 2026-07-12, replacing\n// the original 7-factor PRODUCT). Field finding: with a product, seven\n// factors each at a decent 0.85 gave q≈0.32 — progress DRAINED while every\n// factor sat above its guidance threshold, so the chrome said \"hold still\"\n// and the only discoverable escape was leaning unnaturally close (size,\n// centering falloff (∝IOD) and crop sharpness all improve together with\n// proximity). min() makes q the same quantity guidance reasons about — the\n// worst factor — so \"no complaint\" ⇔ \"progress rises\" by construction, one\n// genuinely bad factor still blocks (non-compensatory), and many mediocre\n// factors (the low-end-device reality: noisy sensor, dim room, wide FOV)\n// are no longer multiplied into failure.\n//\n// 100% deterministic: the clock is a tick INPUT (timestampMs); nothing here\n// reads Date.now or performance.now.\nimport type { FaceObservation } from \"./detector\";\nimport { EXPOSURE_BAND } from \"./frame-quality\";\n\nexport interface V3GateThresholds {\n /** q at/above which progress rises; below it progress falls. */\n Q_GOOD: number;\n /** Integrator slopes, per second. */\n RISE_PER_S: number;\n FALL_PER_S: number;\n /** Centering falloff radius = this × IOD (scale-invariant). The plan's\n * formula is 0.45 × IOD × 3 — the 0.45 echoes v1's CIRCLE_RADIUS_FACTOR\n * heritage — folded here to 1.35 × IOD. */\n CENTER_FALLOFF_IOD_MULTIPLE: number;\n /** Box-only tiers: gate point = bbox center shifted UP by this × height\n * (the documented bbox-vs-eyes offset heuristic). */\n BOX_EYE_OFFSET_FACTOR: number;\n /** Box-only IOD proxy = this × box width. */\n IOD_BOX_PROXY_FACTOR: number;\n /** IOD / frame short side: ideal band + hard limits. */\n SIZE_IDEAL_MIN: number;\n SIZE_IDEAL_MAX: number;\n SIZE_HARD_MIN: number;\n SIZE_HARD_MAX: number;\n /** Eye-line roll (deg) that zeroes the pose factor. */\n ROLL_MAX_DEG: number;\n /** Center velocity that zeroes the motion factor, in IOD-per-second. */\n MOTION_VELOCITY_IOD_PER_S: number;\n /** Velocity-EMA time constant (seconds) — the EMA weight is derived per\n * tick as 1−exp(−dt/τ), so the smoothing HORIZON is cadence-invariant:\n * a LOW device detecting at 5 Hz gets the same effective smoothing as a\n * HIGH device at 10 Hz (a fixed per-sample alpha under-smoothed exactly\n * the jittery low-cadence ticks that needed it most). */\n MOTION_TAU_S: number;\n /** Velocities at/below this (IOD/s) count as stillness — absorbs detector\n * box jitter (largest on LOW's 128px input) before it reaches the EMA. */\n MOTION_DEADBAND_IOD_PER_S: number;\n /** ready = p ≥ 1 AND mean q over this window ≥ READY_MEAN_Q. The mean is\n * TRIMMED: with ≥3 samples in the window the single worst is dropped, so\n * one flaky tick (5 Hz LOW cadence = only 2–3 samples per window) cannot\n * veto an otherwise-ready user. */\n READY_WINDOW_MS: number;\n READY_MEAN_Q: number;\n /** Per-factor guidance trigger levels (lowest failing factor speaks). */\n GUIDE_SIZE: number;\n GUIDE_CENTERING: number;\n GUIDE_POSE: number;\n GUIDE_EXPOSURE: number;\n GUIDE_SHARPNESS: number;\n GUIDE_MOTION: number;\n}\n\n/** Defaults — retuned 2026-07-12 (operator ruling superseding the 2026-07\n * freeze; the capture Task-15 refit set must be split at this boundary):\n * Q_GOOD 0.55→0.6 so it aligns with the 0.6 guidance thresholds under\n * min-q (\"no complaint\" ⇔ \"progress rises\"); SIZE_IDEAL_MIN 0.16→0.12 —\n * wide-FOV front cameras (common low-end) put an arm's-length face below\n * 0.16, silently forcing lean-in; the 720p clip floor keeps a 0.12-IOD\n * face fully resolvable server-side. */\nexport const V3_GATE_DEFAULTS: Readonly<V3GateThresholds> = Object.freeze({\n Q_GOOD: 0.6,\n RISE_PER_S: 0.9,\n FALL_PER_S: 0.25,\n CENTER_FALLOFF_IOD_MULTIPLE: 1.35,\n BOX_EYE_OFFSET_FACTOR: 0.12,\n IOD_BOX_PROXY_FACTOR: 0.42,\n SIZE_IDEAL_MIN: 0.12,\n SIZE_IDEAL_MAX: 0.3,\n SIZE_HARD_MIN: 0.08,\n SIZE_HARD_MAX: 0.45,\n ROLL_MAX_DEG: 25,\n MOTION_VELOCITY_IOD_PER_S: 0.5,\n MOTION_TAU_S: 0.4,\n MOTION_DEADBAND_IOD_PER_S: 0.1,\n READY_WINDOW_MS: 500,\n // 0.7→0.75 with the trimmed window: trimming forgives exactly ONE flaky\n // tick; the raised mean keeps a SECOND bad tick (a real sustained wobble)\n // from diluting through at 10 Hz cadences.\n READY_MEAN_Q: 0.75,\n GUIDE_SIZE: 0.6,\n GUIDE_CENTERING: 0.6,\n GUIDE_POSE: 0.6,\n GUIDE_EXPOSURE: 0.6,\n GUIDE_SHARPNESS: 0.35,\n GUIDE_MOTION: 0.5,\n});\n\nexport interface V3GateQuality {\n /** From frame-quality.sharpness on the face crop. */\n sharpness: number;\n /** From frame-quality.exposure on the face crop. */\n exposure: number;\n /** Mean crop luma — picks more_light vs too_bright guidance. */\n meanLuma: number;\n}\n\nexport interface V3GateTickInput {\n timestampMs: number;\n observation: FaceObservation | null;\n quality: V3GateQuality;\n frameWidth: number;\n frameHeight: number;\n}\n\nexport type V3GateFactor =\n | \"presence\"\n | \"centering\"\n | \"size\"\n | \"pose\"\n | \"sharpness\"\n | \"exposure\"\n | \"motion\";\n\n/** Per-tick output — the telemetry + chrome contract. */\nexport interface V3GateTick {\n at: number;\n /** Instantaneous quality 0..1 (MIN over the factors — the worst factor). */\n q: number;\n /** Integrated progress 0..1. */\n p: number;\n factors: Record<V3GateFactor, number>;\n /** fcv3.* message key for the lowest failing factor (host translates). */\n guidanceKey: string;\n /** Fire signal: p ≥ 1 AND the READY_WINDOW mean q ≥ READY_MEAN_Q. */\n ready: boolean;\n}\n\nconst clamp01 = (value: number) => Math.min(1, Math.max(0, value));\n\nexport class FaceGateV3 {\n private readonly t: V3GateThresholds;\n private p = 0;\n private lastTickAt: number | null = null;\n private lastCenter: { x: number; y: number; at: number } | null = null;\n private velocityEma = 0;\n private qWindow: Array<{ at: number; q: number }> = [];\n\n constructor(overrides: Partial<V3GateThresholds> = {}) {\n this.t = { ...V3_GATE_DEFAULTS, ...overrides };\n }\n\n reset(): void {\n this.p = 0;\n this.lastTickAt = null;\n this.lastCenter = null;\n this.velocityEma = 0;\n this.qWindow = [];\n this.lastSizeDirection = \"ideal\";\n }\n\n tick(input: V3GateTickInput): V3GateTick {\n const { observation, quality, timestampMs } = input;\n const dtSeconds =\n this.lastTickAt === null\n ? 0\n : Math.max(0, (timestampMs - this.lastTickAt) / 1000);\n this.lastTickAt = timestampMs;\n\n const factors: Record<V3GateFactor, number> = {\n presence: 0,\n centering: 0,\n size: 0,\n pose: 0,\n sharpness: clamp01(quality.sharpness),\n exposure: clamp01(quality.exposure),\n motion: 1,\n };\n\n if (observation !== null) {\n factors.presence = 1;\n const geometry = this.geometryOf(observation, input);\n factors.centering = geometry.centering;\n factors.size = geometry.size;\n factors.pose = geometry.pose;\n factors.motion = this.motionOf(\n geometry.center,\n geometry.iod,\n timestampMs,\n );\n } else {\n // No face: the motion history must not survive to the next sighting\n // (a re-acquired face \"jumping\" from its old position is not motion,\n // and a stale pre-loss velocity EMA must not penalize re-acquisition).\n this.lastCenter = null;\n this.velocityEma = 0;\n }\n\n // Worst factor IS the quality (see header) — presence 0 zeroes it exactly\n // as the old product did; the compensatory many-mediocre penalty is gone.\n const q = Math.min(\n factors.presence,\n factors.centering,\n factors.size,\n factors.pose,\n factors.sharpness,\n factors.exposure,\n factors.motion,\n );\n\n // Integrator: gentle drain — bad ticks pull p down at FALL×(1−q), never\n // reset it (the v1 counter-reset feel this replaces).\n this.p = clamp01(\n this.p +\n (q >= this.t.Q_GOOD\n ? this.t.RISE_PER_S * q\n : -this.t.FALL_PER_S * (1 - q)) *\n dtSeconds,\n );\n\n // Sustained-quality window (prevents luck-firing through a wobble).\n // TRIMMED mean: with ≥3 samples the single worst is dropped — at LOW's\n // 5 Hz cadence a window holds 2–3 ticks, and one jittery detection must\n // not veto a user who is otherwise steadily ready.\n this.qWindow.push({ at: timestampMs, q });\n this.qWindow = this.qWindow.filter(\n (entry) => entry.at >= timestampMs - this.t.READY_WINDOW_MS,\n );\n let windowSamples = this.qWindow.map((entry) => entry.q);\n if (windowSamples.length >= 3) {\n const worst = Math.min(...windowSamples);\n const worstIndex = windowSamples.indexOf(worst);\n windowSamples = windowSamples.filter((_, index) => index !== worstIndex);\n }\n const windowMean =\n windowSamples.reduce((sum, value) => sum + value, 0) /\n Math.max(1, windowSamples.length);\n const ready = this.p >= 1 && windowMean >= this.t.READY_MEAN_Q;\n\n return {\n at: timestampMs,\n q,\n p: this.p,\n factors,\n guidanceKey: this.guidanceOf(factors, quality, q),\n ready,\n };\n }\n\n private geometryOf(\n observation: FaceObservation,\n input: V3GateTickInput,\n ): {\n center: { x: number; y: number };\n iod: number;\n centering: number;\n size: number;\n pose: number;\n } {\n const { box, eyes } = observation;\n const frameCenter = { x: input.frameWidth / 2, y: input.frameHeight / 2 };\n const shortSide = Math.min(input.frameWidth, input.frameHeight);\n\n // Gate point: eye midpoint, or the bbox center shifted UP so box-only\n // tiers behave like eye tiers (BOX_EYE_OFFSET heuristic).\n const center =\n eyes !== undefined\n ? {\n x: (eyes.left.x + eyes.right.x) / 2,\n y: (eyes.left.y + eyes.right.y) / 2,\n }\n : {\n x: box.x + box.width / 2,\n y:\n box.y +\n box.height / 2 -\n this.t.BOX_EYE_OFFSET_FACTOR * box.height,\n };\n const iod =\n eyes !== undefined\n ? Math.hypot(eyes.right.x - eyes.left.x, eyes.right.y - eyes.left.y)\n : this.t.IOD_BOX_PROXY_FACTOR * box.width;\n\n // Smooth, SCALE-INVARIANT centering falloff: distance measured in IODs.\n const distance = Math.hypot(\n center.x - frameCenter.x,\n center.y - frameCenter.y,\n );\n const centering =\n iod <= 0\n ? 0\n : 1 - clamp01(distance / (this.t.CENTER_FALLOFF_IOD_MULTIPLE * iod));\n\n // Size factor from IOD relative to the frame short side.\n const ratio = shortSide > 0 ? iod / shortSide : 0;\n this.lastSizeDirection =\n ratio < this.t.SIZE_IDEAL_MIN\n ? \"far\"\n : ratio > this.t.SIZE_IDEAL_MAX\n ? \"close\"\n : \"ideal\";\n let size: number;\n if (ratio < this.t.SIZE_HARD_MIN || ratio > this.t.SIZE_HARD_MAX) {\n size = 0;\n } else if (ratio < this.t.SIZE_IDEAL_MIN) {\n size =\n (ratio - this.t.SIZE_HARD_MIN) /\n (this.t.SIZE_IDEAL_MIN - this.t.SIZE_HARD_MIN);\n } else if (ratio > this.t.SIZE_IDEAL_MAX) {\n size =\n (this.t.SIZE_HARD_MAX - ratio) /\n (this.t.SIZE_HARD_MAX - this.t.SIZE_IDEAL_MAX);\n } else {\n size = 1;\n }\n\n // Pose from the eye-line roll; box-only tiers stay neutral (no signal).\n let pose = 1;\n if (eyes !== undefined) {\n const rollDeg =\n (Math.abs(\n Math.atan2(eyes.right.y - eyes.left.y, eyes.right.x - eyes.left.x),\n ) *\n 180) /\n Math.PI;\n pose = 1 - clamp01(rollDeg / this.t.ROLL_MAX_DEG);\n }\n\n return { center, iod, centering, size, pose };\n }\n\n private motionOf(\n center: { x: number; y: number },\n iod: number,\n at: number,\n ): number {\n const previous = this.lastCenter;\n this.lastCenter = { ...center, at };\n if (previous === null || iod <= 0) return 1;\n const dtSeconds = (at - previous.at) / 1000;\n if (dtSeconds <= 0) return 1;\n let velocityIodPerS =\n Math.hypot(center.x - previous.x, center.y - previous.y) /\n iod /\n dtSeconds;\n // Deadband: sub-jitter velocities are stillness. Detector boxes quantize\n // hardest on LOW's 128px input, where a ±1px wobble at 5 Hz reads as\n // ~0.25 IOD/s — half the zeroing velocity — despite a rock-steady user.\n if (velocityIodPerS <= this.t.MOTION_DEADBAND_IOD_PER_S)\n velocityIodPerS = 0;\n // Time-constant EMA: alpha derived from dt so the smoothing horizon is\n // the same at 5 Hz and 10 Hz (see MOTION_TAU_S).\n const alpha = 1 - Math.exp(-dtSeconds / this.t.MOTION_TAU_S);\n this.velocityEma = alpha * velocityIodPerS + (1 - alpha) * this.velocityEma;\n return 1 - clamp01(this.velocityEma / this.t.MOTION_VELOCITY_IOD_PER_S);\n }\n\n /** Lowest failing factor speaks — fixed priority (diagnostic, incl. light):\n * presence → size → centering → pose → exposure → sharpness → hold.\n *\n * HONESTY FALLBACK (operator ruling 2026-07-12): when every factor clears\n * its guide threshold but q (= min factor) is still below Q_GOOD — i.e.\n * progress is DRAINING — \"hold still\" would be a lie (\"Perfect\" while\n * nothing advances; the field symptom was users discovering by accident\n * that only leaning in fires the gate). In that state the WORST factor\n * speaks even though it passed its guide level, so the user always hears\n * the change that actually unblocks recording. */\n private guidanceOf(\n factors: Record<V3GateFactor, number>,\n quality: V3GateQuality,\n q: number,\n ): string {\n if (factors.presence <= 0) return \"fcv3.no_face\";\n if (factors.size < this.t.GUIDE_SIZE) return this.sizeGuidance();\n if (factors.centering < this.t.GUIDE_CENTERING) return \"fcv3.center_face\";\n if (factors.pose < this.t.GUIDE_POSE) return \"fcv3.straighten\";\n if (factors.exposure < this.t.GUIDE_EXPOSURE)\n return this.exposureGuidance(quality);\n if (factors.sharpness < this.t.GUIDE_SHARPNESS) return \"fcv3.steady_camera\";\n if (factors.motion < this.t.GUIDE_MOTION) return \"fcv3.hold_still\";\n if (q < this.t.Q_GOOD) {\n // All guides pass but progress drains — coach the worst factor anyway.\n const coachable: Array<[V3GateFactor, string]> = [\n [\"size\", this.sizeGuidance()],\n [\"centering\", \"fcv3.center_face\"],\n [\"pose\", \"fcv3.straighten\"],\n [\"exposure\", this.exposureGuidance(quality)],\n [\"sharpness\", \"fcv3.steady_camera\"],\n [\"motion\", \"fcv3.hold_still\"],\n ];\n let worst = coachable[0] as [V3GateFactor, string];\n for (const entry of coachable) {\n if (factors[entry[0]] < factors[worst[0]]) worst = entry;\n }\n return worst[1];\n }\n return \"fcv3.hold_still\";\n }\n\n /** Direction from the size band set THIS tick (never inverted at the hard\n * limits: past SIZE_HARD_MAX the direction is 'close' → move_back). */\n private sizeGuidance(): string {\n return this.lastSizeDirection === \"far\"\n ? \"fcv3.come_closer\"\n : \"fcv3.move_back\";\n }\n\n /** Band midpoint — direction only (tracks EXPOSURE_BAND automatically). */\n private exposureGuidance(quality: V3GateQuality): string {\n const bandMid = (EXPOSURE_BAND[0] + EXPOSURE_BAND[1]) / 2;\n return quality.meanLuma < bandMid ? \"fcv3.more_light\" : \"fcv3.too_bright\";\n }\n\n /** Which side of the ideal band the last size measurement fell on. */\n private lastSizeDirection: \"far\" | \"close\" | \"ideal\" = \"ideal\";\n}\n","// Device profiles (Task 9) — LOW/MID/HIGH from a boot probe, refined by the\n// first measured detect times. Profiles adapt DETECTION cost only (cadence,\n// downscale input width, animation richness): clip constraints are NOT here —\n// the 720p/2.5Mbps floor is global (locked decision 1) and lives in the v1\n// constraint builder both engines share.\n\nexport type DeviceClass = \"LOW\" | \"MID\" | \"HIGH\";\n\nexport interface DeviceProfile {\n /** Detection cadence — the scheduler's pace. */\n cadenceHz: number;\n /** Downscaled snapshot width handed to the detector. */\n inputWidth: number;\n /** Chrome hint: 'reduced' tones down ticks/breathe on LOW even without\n * prefers-reduced-motion. */\n animations: \"full\" | \"reduced\";\n}\n\nexport const DEVICE_PROFILES: Readonly<Record<DeviceClass, Readonly<DeviceProfile>>> =\n Object.freeze({\n LOW: Object.freeze({ cadenceHz: 5, inputWidth: 128, animations: \"reduced\" as const }),\n MID: Object.freeze({ cadenceHz: 8, inputWidth: 160, animations: \"full\" as const }),\n HIGH: Object.freeze({ cadenceHz: 10, inputWidth: 192, animations: \"full\" as const }),\n });\n\nexport interface DeviceProbe {\n cores: number;\n /** null where the UA hides it — iOS Safari NEVER exposes deviceMemory\n * (field lesson: a 2GB default classified every iPhone LOW). Unknown is\n * treated as NEUTRAL (4GB): never demotes to LOW on its own, never\n * promotes to HIGH; the dynamic profiler corrects truly slow devices. */\n memGB: number | null;\n /** WebAssembly SIMD available (informs wasm-tier expectations/telemetry). */\n simd: boolean;\n}\n\n/** Canonical WASM SIMD feature-test module (validates only where SIMD is\n * supported) — the standard wasm-feature-detect bytes. */\nconst SIMD_TEST_BYTES = new Uint8Array([\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253,\n 15, 253, 98, 11,\n]);\n\nexport function probeDevice(): DeviceProbe {\n const nav = typeof navigator === \"undefined\" ? undefined : navigator;\n let simd = false;\n try {\n simd = typeof WebAssembly !== \"undefined\" && WebAssembly.validate(SIMD_TEST_BYTES);\n } catch {\n simd = false;\n }\n return {\n cores: nav?.hardwareConcurrency ?? 2,\n memGB: (nav as { deviceMemory?: number } | undefined)?.deviceMemory ?? null,\n simd,\n };\n}\n\n/** Static class: LOW (<4 cores or <3GB), HIGH (≥8 cores AND ≥6GB), else MID.\n * Unknown memory counts as a neutral 4GB (see DeviceProbe.memGB). */\nexport function classifyDevice(probe: DeviceProbe): DeviceClass {\n const memGB = probe.memGB ?? 4;\n if (probe.cores < 4 || memGB < 3) return \"LOW\";\n if (probe.cores >= 8 && memGB >= 6) return \"HIGH\";\n return \"MID\";\n}\n\nconst ORDER: DeviceClass[] = [\"LOW\", \"MID\", \"HIGH\"];\n\n/** Dynamic refinement: after the FIRST 10 measured detect ticks, a mean over\n * 70ms demotes straight to LOW; under 25ms promotes ONE class — at most one\n * adjustment ever (no oscillation). */\nexport class DeviceProfiler {\n private current: DeviceClass;\n private readonly samples: number[] = [];\n private adjusted = false;\n\n constructor(initial: DeviceClass) {\n this.current = initial;\n }\n\n get deviceClass(): DeviceClass {\n return this.current;\n }\n\n get profile(): DeviceProfile {\n return DEVICE_PROFILES[this.current];\n }\n\n record(detectMs: number): DeviceClass {\n if (this.adjusted || this.samples.length >= 10) return this.current;\n this.samples.push(detectMs);\n if (this.samples.length < 10) return this.current;\n this.adjusted = true;\n const mean = this.samples.reduce((sum, value) => sum + value, 0) / this.samples.length;\n if (mean > 70) {\n this.current = \"LOW\";\n } else if (mean < 25) {\n const index = ORDER.indexOf(this.current);\n this.current = ORDER[Math.min(ORDER.length - 1, index + 1)] ?? this.current;\n }\n return this.current;\n }\n}\n","// Detect scheduler (Task 9) — paces the detection pass at the profile's\n// cadence, preferring requestVideoFrameCallback (runs only when a REAL camera\n// frame arrived) with a plain interval fallback. A tick whose predecessor is\n// still in flight is SKIPPED — never queued (no backlog on a slow device) —\n// and counted as a degrade for telemetry.\n\nexport interface DetectSchedulerOptions {\n /** Ticks per second (profile cadenceHz). */\n cadenceHz: number;\n /** One detection pass — the scheduler awaits it and measures wall time. */\n run: () => Promise<void>;\n /** When provided AND it exposes requestVideoFrameCallback, ticks ride real\n * camera frames (throttled to the cadence) instead of a timer. */\n video?: HTMLVideoElement;\n /** Injectable clock (tests) — defaults to performance.now. */\n now?: () => number;\n}\n\ninterface VideoFrameCallbackTarget {\n requestVideoFrameCallback?: (callback: () => void) => number;\n cancelVideoFrameCallback?: (id: number) => void;\n}\n\n/** Rolling window for meanDetectMs. */\nconst STATS_WINDOW = 20;\n\nexport class DetectScheduler {\n private readonly options: DetectSchedulerOptions;\n private readonly periodMs: number;\n private timer: ReturnType<typeof setInterval> | null = null;\n private frameCallbackId: number | null = null;\n private running = false;\n private busy = false;\n private lastRunAt = Number.NEGATIVE_INFINITY;\n private degradeCount = 0;\n private readonly durations: number[] = [];\n\n constructor(options: DetectSchedulerOptions) {\n this.options = options;\n this.periodMs = 1000 / options.cadenceHz;\n }\n\n start(): void {\n if (this.running) return;\n this.running = true;\n const video = this.options.video as VideoFrameCallbackTarget | undefined;\n if (typeof video?.requestVideoFrameCallback === \"function\") {\n const loop = () => {\n if (!this.running) return;\n this.frameCallbackId = video.requestVideoFrameCallback?.(() => {\n this.frameCallbackId = null;\n // Throttle: camera frames arrive faster than the cadence.\n if (this.now() - this.lastRunAt >= this.periodMs) this.tick();\n loop();\n }) as number;\n };\n loop();\n return;\n }\n this.timer = setInterval(() => this.tick(), this.periodMs);\n }\n\n stop(): void {\n this.running = false;\n if (this.timer !== null) {\n clearInterval(this.timer);\n this.timer = null;\n }\n if (this.frameCallbackId !== null) {\n (this.options.video as VideoFrameCallbackTarget | undefined)?.cancelVideoFrameCallback?.(\n this.frameCallbackId,\n );\n this.frameCallbackId = null;\n }\n }\n\n stats(): { degradeCount: number; meanDetectMs: number } {\n const meanDetectMs =\n this.durations.length === 0\n ? 0\n : this.durations.reduce((sum, value) => sum + value, 0) / this.durations.length;\n return { degradeCount: this.degradeCount, meanDetectMs };\n }\n\n private now(): number {\n return this.options.now?.() ?? performance.now();\n }\n\n private tick(): void {\n if (!this.running) return;\n if (this.busy) {\n // Skip-when-busy: no queue growth on slow devices; telemetry counts it.\n this.degradeCount += 1;\n return;\n }\n this.busy = true;\n this.lastRunAt = this.now();\n const startedAt = this.now();\n this.options\n .run()\n .catch(() => undefined) // a failed pass must never kill the loop\n .finally(() => {\n this.busy = false;\n this.durations.push(this.now() - startedAt);\n if (this.durations.length > STATS_WINDOW) this.durations.shift();\n });\n }\n}\n","// Worker offload (Task 9) — detection off the main thread when the platform\n// allows (OffscreenCanvas + createImageBitmap + Worker). BOTH protocol sides\n// live in this file so the tiny versioned protocol (v:1) can never drift:\n// - installWorkerDetectorHost: runs INSIDE the worker (auto-installed when\n// this module loads in a DedicatedWorkerGlobalScope; tsup builds it as\n// its own entry so hosts can `new Worker(new URL(...))` the dist file);\n// - WorkerDetectorProxy: main-thread Detector implementation that posts\n// ImageBitmap frames as transferables and resolves results by id.\nimport {\n type CreateDetectorOptions,\n createDetector as defaultCreateDetector,\n type Detector,\n type FaceObservation,\n} from \"./detector\";\n\nexport const WORKER_PROTOCOL_VERSION = 1;\n\ninterface InitMessage {\n v: typeof WORKER_PROTOCOL_VERSION;\n type: \"init\";\n options: CreateDetectorOptions;\n}\ninterface DetectMessage {\n v: typeof WORKER_PROTOCOL_VERSION;\n type: \"detect\";\n id: number;\n bitmap: ImageBitmap;\n streamWidth: number;\n streamHeight: number;\n}\ninterface ReadyMessage {\n v: typeof WORKER_PROTOCOL_VERSION;\n type: \"ready\";\n tier: Detector[\"tier\"];\n fallbackReason?: string;\n}\ninterface ResultMessage {\n v: typeof WORKER_PROTOCOL_VERSION;\n type: \"result\";\n id: number;\n observation: FaceObservation | null;\n}\n\ntype ToWorker = InitMessage | DetectMessage;\ntype ToMain = ReadyMessage | ResultMessage;\n\n/** The slice of Worker/scope surface the protocol needs — test-stubbable. */\nexport interface WorkerScopeLike {\n onmessage: ((event: { data: unknown }) => void) | null;\n postMessage(data: unknown): void;\n}\nexport interface WorkerLike {\n postMessage(data: unknown, transfer?: Transferable[]): void;\n addEventListener(type: \"message\", listener: (event: { data: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (event: { data: unknown }) => void): void;\n terminate(): void;\n}\n\n/** Feature gate: bitmap capture + transfer + workers must all exist. */\nexport function workerOffloadSupported(): boolean {\n return (\n typeof OffscreenCanvas === \"function\" &&\n typeof createImageBitmap === \"function\" &&\n typeof Worker === \"function\"\n );\n}\n\n/** Worker-side message host. `deps.createDetector` is a test seam. */\nexport function installWorkerDetectorHost(\n scope: WorkerScopeLike,\n deps: { createDetector?: (options: CreateDetectorOptions) => Promise<Detector> } = {},\n): void {\n const create = deps.createDetector ?? defaultCreateDetector;\n let detector: Detector | null = null;\n scope.onmessage = (event) => {\n const message = event.data as ToWorker;\n if (message.v !== WORKER_PROTOCOL_VERSION) {\n // Ignore unknown versions — but never strand a transferred bitmap.\n (message as { bitmap?: { close?: () => void } }).bitmap?.close?.();\n return;\n }\n if (message.type === \"init\") {\n void create(message.options).then((created) => {\n detector = created;\n const ready: ReadyMessage = {\n v: WORKER_PROTOCOL_VERSION,\n type: \"ready\",\n tier: created.tier,\n ...(created.fallbackReason !== undefined\n ? { fallbackReason: created.fallbackReason }\n : {}),\n };\n scope.postMessage(ready);\n });\n return;\n }\n if (message.type === \"detect\") {\n const respond = (observation: FaceObservation | null) => {\n const result: ResultMessage = {\n v: WORKER_PROTOCOL_VERSION,\n type: \"result\",\n id: message.id,\n observation,\n };\n scope.postMessage(result);\n (message.bitmap as { close?: () => void }).close?.();\n };\n if (detector === null) {\n respond(null);\n return;\n }\n void detector\n .detect(message.bitmap, message.streamWidth, message.streamHeight)\n .then(respond, () => respond(null));\n }\n };\n}\n\n// Auto-install when this module IS the worker entry (DedicatedWorkerGlobalScope\n// has importScripts; window does not). Inert in main-thread bundles/tests.\ndeclare const self: (WorkerScopeLike & { importScripts?: unknown }) | undefined;\nif (typeof self !== \"undefined\" && typeof self.importScripts === \"function\") {\n installWorkerDetectorHost(self);\n}\n\n/** Main-side Detector over the worker protocol. Same interface as the\n * in-thread detectors — Task 10's engine cannot tell the difference. */\nexport class WorkerDetectorProxy implements Detector {\n readonly tier: Detector[\"tier\"];\n readonly fallbackReason?: string;\n private readonly worker: WorkerLike;\n private readonly pending = new Map<number, (observation: FaceObservation | null) => void>();\n private nextId = 1;\n\n private constructor(worker: WorkerLike, ready: ReadyMessage) {\n this.worker = worker;\n this.tier = ready.tier;\n if (ready.fallbackReason !== undefined) this.fallbackReason = ready.fallbackReason;\n worker.addEventListener(\"message\", (event) => {\n const message = event.data as ToMain;\n if (message.v !== WORKER_PROTOCOL_VERSION || message.type !== \"result\") return;\n const resolve = this.pending.get(message.id);\n this.pending.delete(message.id);\n resolve?.(message.observation);\n });\n }\n\n static create(\n worker: WorkerLike,\n options: CreateDetectorOptions,\n readyTimeoutMs = 10_000,\n ): Promise<WorkerDetectorProxy> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n worker.removeEventListener(\"message\", onReady);\n worker.terminate();\n reject(new Error(`worker detector not ready within ${readyTimeoutMs}ms`));\n }, readyTimeoutMs);\n const onReady = (event: { data: unknown }) => {\n const message = event.data as ToMain;\n if (message.v !== WORKER_PROTOCOL_VERSION || message.type !== \"ready\") return;\n clearTimeout(timer);\n worker.removeEventListener(\"message\", onReady);\n resolve(new WorkerDetectorProxy(worker, message));\n };\n worker.addEventListener(\"message\", onReady);\n const init: InitMessage = { v: WORKER_PROTOCOL_VERSION, type: \"init\", options };\n worker.postMessage(init);\n });\n }\n\n async detect(\n source: CanvasImageSource,\n sourceWidth: number,\n sourceHeight: number,\n ): Promise<FaceObservation | null> {\n // Only ImageBitmap is Transferable — convert other sources (video,\n // canvas) via createImageBitmap (the feature gate guarantees it). A\n // failed conversion yields null, never a DataCloneError.\n let bitmap: ImageBitmap;\n try {\n if (typeof ImageBitmap !== \"undefined\" && source instanceof ImageBitmap) {\n bitmap = source;\n } else if (typeof createImageBitmap === \"function\") {\n bitmap = await createImageBitmap(source as ImageBitmapSource);\n } else {\n // No conversion surface (stubbed environments) — trust the caller.\n bitmap = source as ImageBitmap;\n }\n } catch {\n return null;\n }\n const id = this.nextId;\n this.nextId += 1;\n return new Promise((resolve) => {\n this.pending.set(id, resolve);\n const message: DetectMessage = {\n v: WORKER_PROTOCOL_VERSION,\n type: \"detect\",\n id,\n bitmap,\n streamWidth: sourceWidth,\n streamHeight: sourceHeight,\n };\n this.worker.postMessage(message, [bitmap]);\n });\n }\n\n destroy(): void {\n // Settle in-flight detects (an awaiting scheduler run must not hang\n // busy=true forever) before tearing the worker down.\n for (const resolve of this.pending.values()) resolve(null);\n this.pending.clear();\n this.worker.terminate();\n }\n}\n","// CaptureSessionV3 (Task 10) — the v3 engine behind the v1 event surface\n// (`statechange | guidance | checks | artifacts | error`), plus ONE v3-only\n// chrome event (`frozen`, fired at recording-stop so the host can freeze the\n// display on the keyframe before the clip finalizes), so hosts bind it with\n// minimal changes. PARALLEL module: it REUSES v1's building blocks AS\n// IMPORTS — ClipRecorder (the 720p/2.5Mbps clip floor lives in ONE place),\n// captureMirroredKeyframe, buildCaptureConstraints, the camera error taxonomy\n// — and touches no v1 file.\n//\n// v3 deltas: detector LADDER (native → blaze; the face-api floor was dropped\n// 2026-07-09) on an adaptive scheduler with device profiles; FaceGateV3\n// (eye-midpoint, continuous\n// integrator); keyframe BEST-OF-N (sharpest of up to 4 candidates in the\n// first 600ms of the capture window); `checks` carries a v3 payload\n// discriminated on `engine: 'v3'` (no v1 counters).\n//\n// Supersession: retry()/switchCamera()/destroy() bump the attempt token —\n// in-flight async continuations from an old attempt observe the bump and\n// stop (the v1 pattern, ported; see capture-session.ts header).\nimport { buildCaptureConstraints, detectIsMobile } from \"../capture-constraints\";\nimport { ClipRecorder, type ClipResult } from \"../clip-recorder\";\nimport { captureMirroredKeyframe } from \"../keyframe\";\nimport { cameraPreflight, isClipTooLarge, mapGetUserMediaError } from \"../media\";\nimport type { CaptureArtifacts, CaptureErrorKind, CaptureState } from \"../types\";\nimport {\n createDetector as createLadderDetector,\n type Detector,\n DetectorLadderError,\n intrinsicSize,\n} from \"./detector\";\nimport { WorkerDetectorProxy, type WorkerLike, workerOffloadSupported } from \"./detect-worker\";\nimport {\n classifyDevice,\n type DeviceClass,\n DeviceProfiler,\n probeDevice,\n} from \"./device-profile\";\nimport { DetectScheduler } from \"./detect-scheduler\";\nimport {\n FaceGateV3,\n type V3GateFactor,\n type V3GateQuality,\n type V3GateThresholds,\n} from \"./face-gate-v3\";\nimport { exposure, meanLuma, sharpness } from \"./frame-quality\";\n\n/** Best-of-N keyframe window: up to 4 candidates over the first 600ms. */\nexport const KEYFRAME_CANDIDATES = 4;\nexport const KEYFRAME_WINDOW_MS = 600;\n\nexport interface V3ChecksPayload {\n engine: \"v3\";\n /** Gate integrator 0..1 — the ring drives off this directly. */\n progress: number;\n /** Instantaneous quality 0..1. */\n q: number;\n factors: Record<V3GateFactor, number>;\n /** Attempt ordinal (bumps on retry/switchCamera). */\n attempt: number;\n}\n\nexport interface CaptureSessionV3Events {\n statechange: { state: CaptureState };\n checks: V3ChecksPayload;\n /** fcv3.* message KEY — hosts translate; never prose. Deduped. */\n guidance: { key: string };\n artifacts: CaptureArtifacts;\n error: { kind: CaptureErrorKind; retryable: boolean };\n /** v3-only, CHROME-only (no data flows here): fires the instant the clip\n * recording window ends — BEFORE the blob finalizes (iOS onstop can lag up\n * to STOP_GRACE_MS). Carries the already-captured keyframe's JPEG data URL so\n * the host can freeze the display on the still immediately instead of leaving\n * the live feed running while the clip flushes. Clip mode only (photo mode\n * goes straight to `artifacts`). A host that ignores it is unaffected. */\n frozen: { previewDataUrl: string };\n}\n\nexport type V3TelemetryEvent =\n | { type: \"detector\"; tier: Detector[\"tier\"]; fallbackReason?: string }\n | { type: \"profile\"; staticClass: DeviceClass; activeClass: DeviceClass; simd: boolean }\n | { type: \"fired\"; timeToGateMs: number; degradeCount: number; meanDetectMs: number }\n | { type: \"error\"; kind: CaptureErrorKind; fallbackReason?: string };\n\ninterface KeyframeCandidate {\n blob: Blob;\n previewDataUrl: string;\n sharpness: number;\n}\n\n/** Challenge-clip artifact for the Phase 3 escalation path. */\nexport interface EscalationClipArtifact {\n clip: Blob;\n clipMimeType: string;\n}\n\n/** INERT Phase 3 seam (docs/superpowers/specs/2026-07-07-active-liveness-\n * escalation-spec.md): when the server settles a liveness verdict in the\n * REVIEW band it may mint ONE gesture challenge; the host then asks the\n * engine for a challenge clip through this hook. Typed and documented NOW so\n * capture-v3+ starts from a design — NEVER invoked anywhere in the current\n * flow (pinned by a test). */\nexport interface EscalationHook {\n onBorderline(challenge: \"blink\" | \"turn\"): Promise<EscalationClipArtifact>;\n}\n\nexport interface CaptureSessionV3Options {\n /** Host-owned <video playsInline muted> — same iOS contract as v1. */\n video: HTMLVideoElement;\n /** v3 assets base (tasks-vision wasm + tflite); default /models-v3. */\n v3AssetBaseUrl?: string;\n mode?: \"clip\" | \"photo\";\n /** FaceGateV3 threshold overrides (Phase 2 tuning). */\n thresholds?: Partial<V3GateThresholds>;\n telemetry?: (event: V3TelemetryEvent) => void;\n facingMode?: \"user\" | \"environment\";\n /** Static class override (tests / host pinning); default = boot probe. */\n deviceClass?: DeviceClass;\n // ── seams (production defaults in parens) ─────────────────────────────────\n /** (detector ladder) */\n createDetector?: () => Promise<Detector>;\n /** (fresh ClipRecorder per attempt) */\n createRecorder?: () => Pick<ClipRecorder, \"record\" | \"stop\">;\n /** (navigator.mediaDevices.getUserMedia) */\n getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;\n /** (mirrored canvas keyframe + downscaled Laplacian sharpness) */\n captureKeyframe?: (video: HTMLVideoElement) => Promise<KeyframeCandidate>;\n /** (downscaled face-crop sharpness/exposure via canvas) */\n measureQuality?: (\n video: HTMLVideoElement,\n box: { x: number; y: number; width: number; height: number },\n ) => V3GateQuality;\n /** (reused canvas at profile.inputWidth; falls back to the raw video where\n * canvas is unavailable) */\n makeSnapshot?: (video: HTMLVideoElement, targetWidth: number) => CanvasImageSource;\n /** Worker offload opt-in (Task 9): when provided AND the platform supports\n * it (OffscreenCanvas + createImageBitmap + Worker), detection runs\n * worker-side through WorkerDetectorProxy. Hosts own Worker construction\n * (bundler-specific `new Worker(new URL(...))`). */\n createWorker?: () => WorkerLike;\n /** INERT (Phase 3 escalation seam — see EscalationHook). Accepted and\n * retained, never called in Phases 1–2. */\n escalation?: EscalationHook;\n /** (performance.now) */\n now?: () => number;\n}\n\ntype Handler<K extends keyof CaptureSessionV3Events> = (\n payload: CaptureSessionV3Events[K],\n) => void;\n\nconst NEUTRAL_QUALITY: V3GateQuality = { sharpness: 1, exposure: 1, meanLuma: 128 };\n\nexport class CaptureSessionV3 {\n private readonly options: CaptureSessionV3Options;\n private readonly handlers = new Map<string, Set<(payload: never) => void>>();\n private stateValue: CaptureState = \"idle\";\n private attempt = 0;\n private facing: \"user\" | \"environment\";\n private stream: MediaStream | null = null;\n private detector: Detector | null = null;\n private scheduler: DetectScheduler | null = null;\n private gate: FaceGateV3 | null = null;\n private profiler: DeviceProfiler | null = null;\n private lastGuidanceKey: string | null = null;\n private positioningStartedAt = 0;\n private fired = false;\n private carriedDegrade = 0;\n private carriedMeans: number[] = [];\n\n constructor(options: CaptureSessionV3Options) {\n this.options = options;\n this.facing = options.facingMode ?? \"user\";\n }\n\n get state(): CaptureState {\n return this.stateValue;\n }\n\n on<K extends keyof CaptureSessionV3Events>(event: K, handler: Handler<K>): () => void {\n let set = this.handlers.get(event);\n if (!set) {\n set = new Set();\n this.handlers.set(event, set);\n }\n set.add(handler as (payload: never) => void);\n return () => set?.delete(handler as (payload: never) => void);\n }\n\n private emit<K extends keyof CaptureSessionV3Events>(\n event: K,\n payload: CaptureSessionV3Events[K],\n ): void {\n for (const handler of [...(this.handlers.get(event) ?? [])]) {\n (handler as Handler<K>)(payload);\n }\n }\n\n async start(): Promise<void> {\n this.attempt += 1;\n await this.run(this.attempt);\n }\n\n /** Full reset + camera restart — the documented recovery path (v1 parity). */\n retry(): void {\n this.teardownAttempt();\n void this.start();\n }\n\n switchCamera(): void {\n this.facing = this.facing === \"user\" ? \"environment\" : \"user\";\n this.teardownAttempt();\n void this.start();\n }\n\n destroy(): void {\n this.attempt += 1; // supersede in-flight continuations\n this.teardownAttempt();\n this.detector?.destroy();\n this.detector = null;\n this.options.video.srcObject = null;\n }\n\n // ── attempt lifecycle ──────────────────────────────────────────────────────\n\n private async run(attempt: number): Promise<void> {\n const { options } = this;\n this.fired = false;\n this.lastGuidanceKey = null;\n this.carriedDegrade = 0;\n this.carriedMeans = [];\n this.setState(\"preflight\");\n const preflight = cameraPreflight();\n if (preflight !== \"OK\") {\n this.fail(preflight === \"INSECURE_CONTEXT\" ? \"insecure\" : \"unsupported\");\n return;\n }\n\n this.setState(\"acquiring\");\n const getUserMedia =\n options.getUserMedia ??\n ((constraints: MediaStreamConstraints) => navigator.mediaDevices.getUserMedia(constraints));\n let stream: MediaStream;\n try {\n // The 720p/2.5Mbps floor: v1's constraint builder, imported — never forked.\n stream = await getUserMedia(buildCaptureConstraints(detectIsMobile(), this.facing));\n } catch (err) {\n if (attempt !== this.attempt) return;\n this.fail(mapGetUserMediaError(err));\n return;\n }\n if (attempt !== this.attempt) {\n for (const track of stream.getTracks()) track.stop();\n return;\n }\n this.stream = stream;\n options.video.srcObject = stream;\n await options.video.play().catch(() => undefined);\n // play() awaited — a retry/destroy may have superseded this attempt while\n // it was suspended; continuing would overwrite the LIVE attempt's\n // profiler/gate/scheduler with stale ones (review S2-2).\n if (attempt !== this.attempt) return;\n\n if (this.detector === null) {\n const ladderOptions = {\n ...(options.v3AssetBaseUrl !== undefined\n ? { v3AssetBaseUrl: options.v3AssetBaseUrl }\n : {}),\n };\n const create =\n options.createDetector ??\n (options.createWorker !== undefined && workerOffloadSupported()\n ? async () => {\n // Worker offload (Task 9): the ladder runs WORKER-side; a\n // failed/hung init falls back to the in-thread ladder.\n try {\n return await WorkerDetectorProxy.create(\n (options.createWorker as () => WorkerLike)(),\n ladderOptions,\n );\n } catch {\n return createLadderDetector(ladderOptions);\n }\n }\n : () => createLadderDetector(ladderOptions));\n let created: Detector;\n try {\n created = await create();\n } catch (err) {\n // With the face-api floor gone, the ladder REJECTS once exhausted\n // (DetectorLadderError) — and any throwing seam is likewise a models\n // failure. Surface a retryable error{kind:'models'} (never a hang),\n // carrying the per-tier reasons for telemetry so a blaze init failure\n // stays observable in the field.\n if (attempt === this.attempt) {\n this.fail(\n \"models\",\n err instanceof DetectorLadderError ? err.fallbackReason : describeError(err),\n );\n }\n return;\n }\n // Resolve into a LOCAL first: assigning a detector into a superseded\n // (or destroyed) session would leak it — destroy() already nulled the\n // field, and a racing attempt may have created its own (review S2-3).\n if (attempt !== this.attempt) {\n created.destroy();\n return;\n }\n this.detector = created;\n this.options.telemetry?.({\n type: \"detector\",\n tier: created.tier,\n ...(created.fallbackReason !== undefined\n ? { fallbackReason: created.fallbackReason }\n : {}),\n });\n }\n\n const probe = probeDevice();\n const staticClass = options.deviceClass ?? classifyDevice(probe);\n this.profiler = new DeviceProfiler(staticClass);\n this.options.telemetry?.({\n type: \"profile\",\n staticClass,\n activeClass: this.profiler.deviceClass,\n simd: probe.simd,\n });\n\n this.gate = new FaceGateV3(options.thresholds ?? {});\n this.setState(\"positioning\");\n this.positioningStartedAt = this.now();\n this.startScheduler(attempt);\n }\n\n /** Chrome hint (Task 11): 'reduced' on LOW even without the media query. */\n get animations(): \"full\" | \"reduced\" {\n return this.profiler?.profile.animations ?? \"full\";\n }\n\n private startScheduler(attempt: number): void {\n const profiler = this.profiler;\n if (profiler === null) return;\n if (this.scheduler !== null) {\n // A dynamic profile change replaces the scheduler — carry its stats so\n // the `fired` telemetry keeps the PRE-adjustment struggle visible.\n const stats = this.scheduler.stats();\n this.carriedDegrade += stats.degradeCount;\n if (stats.meanDetectMs > 0) this.carriedMeans.push(stats.meanDetectMs);\n this.scheduler.stop();\n }\n const scheduler = new DetectScheduler({\n cadenceHz: profiler.profile.cadenceHz,\n video: this.options.video,\n ...(this.options.now !== undefined ? { now: this.options.now } : {}),\n run: () => this.detectTick(attempt),\n });\n this.scheduler = scheduler;\n scheduler.start();\n }\n\n private async detectTick(attempt: number): Promise<void> {\n const { detector, gate, profiler } = this;\n const video = this.options.video;\n if (attempt !== this.attempt || detector === null || gate === null || profiler === null)\n return;\n if (this.fired || video.videoWidth === 0) return;\n\n const before = profiler.deviceClass;\n const t0 = this.now();\n // Profile-adaptive DOWNSCALE: the detector sees an inputWidth-wide\n // snapshot, never the full 720p frame (the profile system's perf win);\n // stream-px normalization scales the observation back up.\n const source =\n this.options.makeSnapshot?.(video, profiler.profile.inputWidth) ??\n this.defaultSnapshot(video, profiler.profile.inputWidth);\n let observation: Awaited<ReturnType<Detector[\"detect\"]>> = null;\n try {\n observation = await detector.detect(source, video.videoWidth, video.videoHeight);\n } catch {\n observation = null; // detectors never reject by contract; belt-and-braces\n }\n if (attempt !== this.attempt || this.fired) return;\n profiler.record(this.now() - t0);\n if (profiler.deviceClass !== before) this.startScheduler(attempt); // cadence follows the class\n\n const quality =\n observation === null\n ? NEUTRAL_QUALITY\n : (this.options.measureQuality?.(video, observation.box) ??\n this.defaultQuality(video, observation.box));\n\n const tick = gate.tick({\n timestampMs: this.now(),\n observation,\n quality,\n frameWidth: video.videoWidth,\n frameHeight: video.videoHeight,\n });\n this.emit(\"checks\", {\n engine: \"v3\",\n progress: tick.p,\n q: tick.q,\n factors: tick.factors,\n attempt,\n });\n if (tick.guidanceKey !== this.lastGuidanceKey) {\n this.lastGuidanceKey = tick.guidanceKey;\n this.emit(\"guidance\", { key: tick.guidanceKey });\n }\n if (tick.ready && this.stateValue === \"positioning\") {\n this.fired = true;\n void this.fire(attempt);\n }\n }\n\n private async fire(attempt: number): Promise<void> {\n const { options } = this;\n const scheduler = this.scheduler;\n scheduler?.stop();\n const stats = scheduler?.stats() ?? { degradeCount: 0, meanDetectMs: 0 };\n const means = [...this.carriedMeans, ...(stats.meanDetectMs > 0 ? [stats.meanDetectMs] : [])];\n options.telemetry?.({\n type: \"fired\",\n timeToGateMs: this.now() - this.positioningStartedAt,\n degradeCount: this.carriedDegrade + stats.degradeCount,\n meanDetectMs:\n means.length === 0 ? 0 : means.reduce((sum, value) => sum + value, 0) / means.length,\n });\n\n const mode = options.mode ?? \"clip\";\n const bestOf = this.collectKeyframes(attempt);\n if (mode === \"photo\") {\n const best = await bestOf;\n if (attempt !== this.attempt) return;\n if (best === null) {\n this.fail(\"generic\");\n return;\n }\n this.finishCapture({ keyframe: best.blob, previewDataUrl: best.previewDataUrl });\n return;\n }\n\n this.setState(\"recording\");\n const recorder = options.createRecorder?.() ?? new ClipRecorder();\n const stream = this.stream;\n if (stream === null) {\n this.fail(\"generic\");\n return;\n }\n // The keyframe (the face_match selfie) resolves within the first 600ms —\n // well before the 2.5s clip ends. Latch it so the recording-STOP callback\n // below can emit `frozen` immediately, letting the host freeze the display\n // on the still without waiting for the clip blob to finalize (iOS lag).\n let frozenBest: KeyframeCandidate | null = null;\n void bestOf.then(\n (candidate) => {\n frozenBest = candidate;\n },\n () => {},\n );\n const onRecordingStopped = (): void => {\n if (attempt !== this.attempt) return; // superseded (retry/switch/destroy)\n if (frozenBest !== null) {\n this.emit(\"frozen\", { previewDataUrl: frozenBest.previewDataUrl });\n }\n };\n let clip: ClipResult;\n let best: KeyframeCandidate | null;\n try {\n [clip, best] = await Promise.all([recorder.record(stream, onRecordingStopped), bestOf]);\n } catch (err) {\n if (attempt !== this.attempt) return;\n const kind = (err as { kind?: CaptureErrorKind }).kind;\n this.fail(kind === \"cliptoolarge\" ? \"cliptoolarge\" : \"recorder\");\n return;\n }\n if (attempt !== this.attempt) return;\n if (isClipTooLarge(clip.blob)) {\n this.fail(\"cliptoolarge\");\n return;\n }\n if (best === null) {\n this.fail(\"generic\");\n return;\n }\n this.finishCapture({\n clip: clip.blob,\n clipMimeType: clip.mimeType,\n keyframe: best.blob,\n previewDataUrl: best.previewDataUrl,\n });\n }\n\n /** Up to KEYFRAME_CANDIDATES mirrored frames over KEYFRAME_WINDOW_MS —\n * sharpest wins (reuses frame-quality.sharpness via the capture seam). */\n private async collectKeyframes(attempt: number): Promise<KeyframeCandidate | null> {\n const capture = this.options.captureKeyframe ?? ((video) => this.defaultKeyframe(video));\n const stepMs = KEYFRAME_WINDOW_MS / (KEYFRAME_CANDIDATES - 1);\n let best: KeyframeCandidate | null = null;\n for (let i = 0; i < KEYFRAME_CANDIDATES; i += 1) {\n if (attempt !== this.attempt) return best;\n try {\n const candidate = await capture(this.options.video);\n if (best === null || candidate.sharpness > best.sharpness) best = candidate;\n } catch {\n // a failed candidate never sinks the capture — keep the best so far\n }\n if (i < KEYFRAME_CANDIDATES - 1) await delay(stepMs);\n }\n return best;\n }\n\n private finishCapture(artifacts: CaptureArtifacts): void {\n this.stopTracks(); // privacy posture: camera off the moment we have artifacts\n this.setState(\"captured\");\n this.emit(\"artifacts\", artifacts);\n }\n\n // ── defaults for the canvas-bound seams ────────────────────────────────────\n\n private async defaultKeyframe(video: HTMLVideoElement): Promise<KeyframeCandidate> {\n const canvas = document.createElement(\"canvas\");\n const blob = await captureMirroredKeyframe(video, canvas);\n const previewDataUrl = canvas.toDataURL(\"image/jpeg\", 0.92);\n return { blob, previewDataUrl, sharpness: this.centerSharpness(video) };\n }\n\n /** Reused downscale canvas — falls back to the raw video where canvas 2D\n * is unavailable (jsdom) so tests and exotic hosts keep detecting. */\n private snapshotCanvas: HTMLCanvasElement | null = null;\n private defaultSnapshot(video: HTMLVideoElement, targetWidth: number): CanvasImageSource {\n try {\n const canvas = this.snapshotCanvas ?? document.createElement(\"canvas\");\n const scale = targetWidth / Math.max(1, video.videoWidth);\n const width = Math.max(1, Math.round(video.videoWidth * scale));\n const height = Math.max(1, Math.round(video.videoHeight * scale));\n const ctx = canvas.getContext(\"2d\");\n if (ctx === null) return video;\n if (canvas.width !== width) canvas.width = width;\n if (canvas.height !== height) canvas.height = height;\n ctx.drawImage(video, 0, 0, width, height);\n this.snapshotCanvas = canvas;\n return canvas;\n } catch {\n return video;\n }\n }\n\n private defaultQuality(\n video: HTMLVideoElement,\n box: { x: number; y: number; width: number; height: number },\n ): V3GateQuality {\n const crop = cropImageData(video, box, 96);\n if (crop === null) return NEUTRAL_QUALITY;\n return { sharpness: sharpness(crop), exposure: exposure(crop), meanLuma: meanLuma(crop) };\n }\n\n private centerSharpness(video: HTMLVideoElement): number {\n const size = intrinsicSize(video);\n const crop = cropImageData(\n video,\n { x: size.width * 0.25, y: size.height * 0.25, width: size.width * 0.5, height: size.height * 0.5 },\n 96,\n );\n return crop === null ? 0 : sharpness(crop);\n }\n\n // ── teardown ──────────────────────────────────────────────────────────────\n\n private teardownAttempt(): void {\n // No token bump here: retry()/switchCamera() call start() synchronously\n // right after, and START's own bump supersedes; destroy() bumps itself.\n this.scheduler?.stop();\n this.scheduler = null;\n this.gate = null;\n this.stopTracks();\n }\n\n private stopTracks(): void {\n if (this.stream === null) return;\n for (const track of this.stream.getTracks()) track.stop();\n this.stream = null;\n }\n\n private fail(kind: CaptureErrorKind, fallbackReason?: string): void {\n this.scheduler?.stop();\n this.stopTracks();\n this.setState(\"error\");\n this.options.telemetry?.({\n type: \"error\",\n kind,\n ...(fallbackReason !== undefined ? { fallbackReason } : {}),\n });\n // v1 canRetry semantics (capture-session.ts L424).\n this.emit(\"error\", { kind, retryable: kind !== \"insecure\" && kind !== \"unsupported\" });\n }\n\n private setState(state: CaptureState): void {\n this.stateValue = state;\n this.emit(\"statechange\", { state });\n }\n\n private now(): number {\n return this.options.now?.() ?? performance.now();\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction describeError(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Downscaled face-crop ImageData for the quality measures; null where canvas\n * is unavailable (jsdom) — callers fall back to neutral quality. */\nfunction cropImageData(\n video: HTMLVideoElement,\n box: { x: number; y: number; width: number; height: number },\n targetWidth: number,\n): ImageData | null {\n try {\n const canvas = document.createElement(\"canvas\");\n const scale = targetWidth / Math.max(1, box.width);\n canvas.width = Math.max(1, Math.round(box.width * scale));\n canvas.height = Math.max(1, Math.round(box.height * scale));\n const ctx = canvas.getContext(\"2d\");\n if (ctx === null) return null;\n ctx.drawImage(\n video,\n box.x,\n box.y,\n box.width,\n box.height,\n 0,\n 0,\n canvas.width,\n canvas.height,\n );\n return ctx.getImageData(0, 0, canvas.width, canvas.height);\n } catch {\n return null;\n }\n}\n"],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":["extractEyes","describeError","best"]}
1
+ {"version":3,"sources":["../../src/core/index.ts","../../src/core/media.ts","../../src/core/keyframe.ts","../../src/core/messages.ts","../../src/core/clip-recorder.ts","../../src/core/capture-constraints.ts","../../src/core/v3/detector-blaze.ts","../../src/core/v3/detector-native.ts","../../src/core/v3/detector.ts","../../src/core/v3/frame-quality.ts","../../src/core/v3/face-gate-v3.ts","../../src/core/v3/device-profile.ts","../../src/core/v3/detect-scheduler.ts","../../src/core/v3/detect-worker.ts","../../src/core/v3/capture-session-v3.ts"],"sourcesContent":["// @sekyro/web/core — framework-free capture modules ported byte-identically\n// from v1 (kyc-ibtikar/lib/faceCaptureV2). Calibration-pinned: the FAS-CLIP liveness model\n// was calibrated on clips produced by exactly this pipeline. See test/port-parity.test.ts.\nexport * from \"./media\";\nexport * from \"./keyframe\";\nexport * from \"./messages\";\nexport * from \"./clip-recorder\";\nexport * from \"./types\";\n// Shared, engine-agnostic capture helpers (camera constraint tier + mobile\n// heuristic + gate-geometry factors) — the v1 CaptureSession/FaceGate engine\n// was removed; v3 is the only capture path.\nexport * from \"./capture-constraints\";\n// Capture program Phase 1 — the PARALLEL v3 engine (additive exports only;\n// every module above stays byte-identical / calibration-pinned). The worker\n// entry is deliberately NOT re-exported here: hosts import the\n// `./core/v3/detect-worker` subpath so its worker-scope auto-install never\n// rides along a main-thread bundle import.\nexport * from \"./v3/detector\";\nexport * from \"./v3/face-gate-v3\";\nexport * from \"./v3/frame-quality\";\nexport * from \"./v3/device-profile\";\nexport * from \"./v3/detect-scheduler\";\nexport * from \"./v3/capture-session-v3\";\n// Doc Capture v2 (program Phase 3 — doc catalog, DocGateV1, MRZ band, frame\n// analysis, feedback aggregator, CaptureSessionDoc) is DELIBERATELY NOT part\n// of the public `core` surface: it is consumed by Sekyro's own hosted page\n// only and ships via the `@sekyro/web/internal` entry (src/internal/index.ts)\n// with no semver guarantees.\n","// PORTED byte-identical from kyc-ibtikar/lib/faceCaptureV2/media.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Do NOT edit without a calibration re-validation.\n\n// Pure, framework-free helpers for FaceCaptureV2. No React, minimal DOM.\n\n/** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.\n * WebM/VP9→VP8 only as the Firefox/older-Chromium fallback. */\nexport const MIME_CANDIDATES = [\n \"video/mp4;codecs=avc1.42E01E,mp4a.40.2\",\n \"video/mp4;codecs=avc1.42E01E\",\n \"video/mp4\",\n \"video/webm;codecs=vp9,opus\",\n \"video/webm;codecs=vp9\",\n \"video/webm;codecs=vp8,opus\",\n \"video/webm;codecs=vp8\",\n \"video/webm\",\n] as const;\n\nexport type CameraErrorKind =\n | \"permission\"\n | \"notfound\"\n | \"inuse\"\n | \"overconstrained\"\n | \"insecure\"\n | \"unsupported\"\n | \"generic\";\n\n/** First supported candidate, or \"\" to let the browser pick its own default. */\nexport function pickMimeType(): string {\n const MR = (globalThis as unknown as { MediaRecorder?: { isTypeSupported?: (t: string) => boolean } })\n .MediaRecorder;\n if (!MR || typeof MR.isTypeSupported !== \"function\") return \"\";\n return MIME_CANDIDATES.find((t) => MR.isTypeSupported!(t)) ?? \"\";\n}\n\n/** Default clip container when pickMimeType() === \"\" — NEVER .bin/octet-stream (REVIEW FIX 5).\n * Prefer the first webm in the ladder the browser most likely defaults to. */\nexport const DEFAULT_CLIP_MIME = \"video/webm\";\n\n/** Branch on err.name (never the message). TypeError ⇒ navigator.mediaDevices was undefined\n * (insecure/unsupported context) — surfaced as \"insecure\". */\nexport function mapGetUserMediaError(err: unknown): CameraErrorKind {\n if (err instanceof TypeError) return \"insecure\";\n const name = (err as { name?: string })?.name ?? \"\";\n switch (name) {\n case \"NotAllowedError\":\n case \"PermissionDeniedError\":\n return \"permission\";\n case \"NotFoundError\":\n case \"DevicesNotFoundError\":\n return \"notfound\";\n case \"NotReadableError\":\n case \"TrackStartError\":\n return \"inuse\";\n case \"OverconstrainedError\":\n case \"ConstraintNotSatisfiedError\":\n return \"overconstrained\";\n default:\n return \"generic\";\n }\n}\n\nexport function cameraPreflight(): \"INSECURE_CONTEXT\" | \"UNSUPPORTED\" | \"OK\" {\n const w = globalThis as unknown as { window?: { isSecureContext?: boolean }; navigator?: Navigator };\n if (typeof w.window !== \"undefined\" && w.window.isSecureContext === false)\n return \"INSECURE_CONTEXT\";\n const md = (w.navigator as Navigator | undefined)?.mediaDevices as\n | { getUserMedia?: unknown }\n | undefined;\n if (!md || typeof md.getUserMedia !== \"function\") return \"UNSUPPORTED\";\n return \"OK\";\n}\n\n/** iOS Safari (and any browser) may lack MediaRecorder entirely — detect BEFORE prompting\n * for the camera so we can fall back to the v1 single-photo path (REVIEW FIX 1). */\nexport function isMediaRecorderSupported(): boolean {\n const MR = (globalThis as unknown as { MediaRecorder?: { isTypeSupported?: unknown } }).MediaRecorder;\n return typeof MR !== \"undefined\" && typeof (MR as { isTypeSupported?: unknown }).isTypeSupported === \"function\";\n}\n\nexport const MAX_CLIP_BYTES = 8 * 1024 * 1024; // 8 MB hard cap (shared with the /api/liveness/v2 contract)\nexport function isClipTooLarge(blob: Blob): boolean {\n return blob.size > MAX_CLIP_BYTES;\n}\n\nexport function extForMime(mime: string): string {\n const m = (mime || \"\").toLowerCase();\n if (m.startsWith(\"image/jpeg\")) return \"jpg\";\n if (m.startsWith(\"video/mp4\")) return \"mp4\";\n if (m.startsWith(\"video/webm\")) return \"webm\";\n // Never .bin — default to the clip container we actually record (REVIEW FIX 5).\n return \"webm\";\n}\n\n/** Build the exact multipart body /api/liveness/v2 expects: fields `token`, files `clip` + `keyframe`.\n * Caller must NOT set Content-Type — the browser adds the boundary. */\nexport function buildLivenessV2FormData(args: {\n token: string;\n clip: Blob;\n keyframe: Blob;\n ts?: number;\n}): FormData {\n const { token, clip, keyframe } = args;\n const ts = args.ts ?? Date.now();\n const clipType = clip.type || DEFAULT_CLIP_MIME;\n const kfType = keyframe.type || \"image/jpeg\";\n const fd = new FormData();\n fd.append(\"token\", token);\n fd.append(\"clip\", new File([clip], `liveness-${ts}.${extForMime(clipType)}`, { type: clipType }));\n fd.append(\"keyframe\", new File([keyframe], `keyframe-${ts}.${extForMime(kfType)}`, { type: kfType }));\n return fd;\n}\n","// PORTED byte-identical from kyc-ibtikar/lib/faceCaptureV2/keyframe.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Do NOT edit without a calibration re-validation.\n\n// Grab ONE mirrored frontal keyframe from the live <video> into a JPEG Blob (a file part,\n// not a dataURL). Mirror matches the selfie preview (front camera), same as FaceCapture v1.\nexport function captureMirroredKeyframe(\n video: HTMLVideoElement,\n canvas: HTMLCanvasElement,\n quality = 0.92,\n): Promise<Blob> {\n return new Promise((resolve, reject) => {\n const w = video.videoWidth;\n const h = video.videoHeight;\n if (!w || !h) {\n reject(new Error(\"video-not-ready\"));\n return;\n }\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) {\n reject(new Error(\"no-2d-context\"));\n return;\n }\n canvas.width = w;\n canvas.height = h;\n ctx.scale(-1, 1);\n ctx.drawImage(video, -w, 0);\n canvas.toBlob(\n (blob) => (blob ? resolve(blob) : reject(new Error(\"empty-keyframe\"))),\n \"image/jpeg\",\n quality,\n );\n });\n}\n","// PORTED byte-identical from kyc-ibtikar/lib/faceCaptureV2/messages.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Do NOT edit without a calibration re-validation.\n\nimport type { CameraErrorKind } from \"./media\";\n\n/** i18n key + inline French fallback (repo convention: t(key, frenchFallback)). */\nexport const errorCopy: Record<CameraErrorKind, { key: string; fr: string }> = {\n permission: {\n key: \"fcv2.err.permission\",\n fr: \"Autorisez la caméra dans les réglages du navigateur (icône caméra dans la barre d’adresse), puis réessayez.\",\n },\n notfound: {\n key: \"fcv2.err.notfound\",\n fr: \"Aucune caméra détectée. Branchez ou activez une caméra, puis réessayez.\",\n },\n inuse: {\n key: \"fcv2.err.inuse\",\n fr: \"La caméra est utilisée par une autre application. Fermez-la puis réessayez.\",\n },\n overconstrained: {\n key: \"fcv2.err.overconstrained\",\n fr: \"La caméra ne prend pas en charge les réglages demandés. Nouvel essai en cours…\",\n },\n insecure: {\n key: \"fcv2.err.insecure\",\n fr: \"La caméra nécessite une connexion sécurisée (HTTPS). Ouvrez la page en HTTPS.\",\n },\n unsupported: {\n key: \"fcv2.err.unsupported\",\n fr: \"Votre navigateur ne prend pas en charge l’enregistrement vidéo. Utilisez un navigateur récent.\",\n },\n generic: {\n key: \"fcv2.err.generic\",\n fr: \"Caméra indisponible. Réessayez ou contactez le support.\",\n },\n};\n\nexport const uiCopy = {\n recording: { key: \"fcv2.recording\", fr: \"Enregistrement en cours…\" },\n uploading: { key: \"fcv2.uploading\", fr: \"Envoi en cours…\" },\n clipTooLarge: {\n key: \"fcv2.err.cliptoolarge\",\n fr: \"La vidéo est trop volumineuse. Réessayez dans un endroit mieux éclairé.\",\n },\n retry: { key: \"fcv2.retry\", fr: \"Réessayer\" },\n listen: { key: \"fcv2.listen\", fr: \"Écouter\" },\n} as const;\n","// De-hooked port of kyc-ibtikar/lib/faceCaptureV2/useClipRecorder.ts (calibration-pinned\n// capture contract — spec §6 / risk 1). Framework-free class: useRef → private fields,\n// useCallback(start) → record(), stopAndCleanup + the unmount useEffect → stop().\n// Behavior is the v1 hook's, VERBATIM (iOS workarounds included). Source line references\n// (kyc-ibtikar/lib/faceCaptureV2/useClipRecorder.ts):\n// - constants CLIP_MS / TIMESLICE_MS / STOP_GRACE_MS / VIDEO_BPS ............ L10-13\n// - ClipError(kind, msg?) .................................................. L15-21\n// - guarded double MediaRecorder construction (REVIEW FIX 1) ............... L47-63\n// - single-settle guard + timer clearing ................................... L66-71\n// - finalize: Blob(type = recorder.mimeType || picked || DEFAULT_CLIP_MIME)\n// + post-hoc size-cap check .............................................. L73-82\n// - incremental 8MB cap enforcement on dataavailable (REVIEW FIX 7) ........ L84-100\n// - onstop → finalize, onerror → generic, guarded start(TIMESLICE_MS) ...... L101-109\n// - hard stop at CLIP_MS + iOS stop-grace finalize (REVIEW FIX 3) .......... L111-124\n// - teardown: clear timers, stop recorder, stop ALL tracks (REVIEW FIX 8) .. L128-145\n// V2 additions on top of the verbatim behavior (both zero-impact on clip bytes, both\n// required because a class instance outlives one recording where v1's hook state was\n// remounted fresh): a re-entrancy guard in record(), and clearing stale timers when a\n// new recording starts. See the record() JSDoc.\n// Do NOT edit without a calibration re-validation.\nimport {\n pickMimeType,\n isClipTooLarge,\n MAX_CLIP_BYTES,\n DEFAULT_CLIP_MIME,\n type CameraErrorKind,\n} from \"./media\";\n\nexport const CLIP_MS = 2500; // 2.5s, within the 2.0–3.0s target window\nexport const TIMESLICE_MS = 1000; // periodic dataavailable — iOS reliability workaround\nexport const STOP_GRACE_MS = 1500; // iOS: if onstop never fires, finalize from chunks\n// 2.5 Mbps pairs with the 720p capture tier (capture-session.ts): 1.5 Mbps at\n// 720p over-compresses exactly the texture the FAS-CLIP head needs. ~0.8MB per\n// 2.5s clip — well under the 8MB client cap / 15MB server caps.\nexport const VIDEO_BPS = 2_500_000;\n\nexport type ClipErrorKind = CameraErrorKind | \"cliptoolarge\";\n\nexport class ClipError extends Error {\n kind: ClipErrorKind;\n constructor(kind: ClipErrorKind, msg?: string) {\n super(msg ?? kind);\n this.kind = kind;\n }\n}\n\nexport interface ClipResult {\n blob: Blob;\n /** Container mime the clip was finalized with (recorder.mimeType || picked || DEFAULT_CLIP_MIME). */\n mimeType: string;\n}\n\nexport class ClipRecorder {\n private recorder: MediaRecorder | null = null;\n private stream: MediaStream | null = null; // own field so teardown can stop tracks (REVIEW FIX 8)\n private chunks: Blob[] = [];\n private bytes = 0;\n private hardStopTimer: ReturnType<typeof setTimeout> | null = null;\n private graceTimer: ReturnType<typeof setTimeout> | null = null;\n private settled = false;\n\n private clearTimers(): void {\n if (this.hardStopTimer) clearTimeout(this.hardStopTimer);\n if (this.graceTimer) clearTimeout(this.graceTimer);\n this.hardStopTimer = null;\n this.graceTimer = null;\n }\n\n /** Records CLIP_MS of the stream. Resolves with the clip blob + its container mime;\n * rejects with ClipError. Behavior contract is the v1 hook's `start`, verbatim\n * (iOS workarounds included).\n *\n * ONE RECORDING AT A TIME: chunk/byte/timer state is shared per instance, so a\n * second record() while one is in flight rejects ClipError(\"generic\") instead of\n * corrupting the in-flight clip. (v2 guard — v1's hook was gated by its owning\n * component; a class API invites reuse. Zero impact on clip bytes.)\n *\n * `onStopped` (optional) fires ONCE the moment the CLIP_MS recording window\n * elapses (the hard-stop), BEFORE finalize — which on iOS can lag up to\n * STOP_GRACE_MS while onstop flushes the last chunk. It lets the host freeze\n * the display on the already-captured keyframe the instant recording ends,\n * instead of waiting for the blob. PURE NOTIFICATION — it does not touch\n * timers, chunks, or the finalize path, so it is calibration-neutral (no\n * effect on clip bytes). Never fires on a rejected capture (error /\n * cliptoolarge settle before the hard-stop and clear the timer). */\n record(stream: MediaStream, onStopped?: () => void): Promise<ClipResult> {\n if (this.recorder && !this.settled) {\n return Promise.reject(\n new ClipError(\n \"generic\",\n \"record() called while a recording is in flight — ClipRecorder handles one recording at a time\",\n ),\n );\n }\n this.recorder = null; // so a failed construction below never blocks a retry\n // De-hooking correction (zero impact on clip bytes): v1 got fresh refs per hook\n // mount, so a previous recording's post-settle grace timer (the hard-stop callback\n // arms it AFTER settle cleared timers — v1-verbatim) could never leak into a new\n // one. On a reused instance it would fire mid-flight, settle the fresh state, and\n // clear the new hard-stop timer — so drop stale timers before starting.\n this.clearTimers();\n this.chunks = [];\n this.bytes = 0;\n this.settled = false;\n this.stream = stream;\n const picked = pickMimeType();\n\n return new Promise<ClipResult>((resolve, reject) => {\n // Guarded construction — iOS Safari may lack MediaRecorder entirely (REVIEW FIX 1).\n let recorder: MediaRecorder;\n try {\n recorder = new MediaRecorder(\n stream,\n picked\n ? { mimeType: picked, videoBitsPerSecond: VIDEO_BPS }\n : { videoBitsPerSecond: VIDEO_BPS },\n );\n } catch {\n try {\n recorder = new MediaRecorder(stream); // last resort: browser defaults\n } catch {\n reject(new ClipError(\"unsupported\"));\n return;\n }\n }\n this.recorder = recorder;\n\n const settle = (fn: () => void) => {\n if (this.settled) return;\n this.settled = true;\n this.clearTimers();\n fn();\n };\n\n const finalize = () =>\n settle(() => {\n const type = recorder.mimeType || picked || DEFAULT_CLIP_MIME;\n const blob = new Blob(this.chunks, { type });\n if (isClipTooLarge(blob)) {\n reject(new ClipError(\"cliptoolarge\"));\n return;\n }\n resolve({ blob, mimeType: type });\n });\n\n recorder.ondataavailable = (e: BlobEvent) => {\n if (e.data && e.data.size) {\n this.chunks.push(e.data);\n this.bytes += e.data.size;\n // Enforce the 8MB cap INCREMENTALLY — stop + reject as soon as exceeded (REVIEW FIX 7).\n if (this.bytes > MAX_CLIP_BYTES) {\n settle(() => {\n try {\n if (recorder.state !== \"inactive\") recorder.stop();\n } catch {\n /* noop */\n }\n reject(new ClipError(\"cliptoolarge\"));\n });\n }\n }\n };\n recorder.onstop = finalize;\n recorder.onerror = () => settle(() => reject(new ClipError(\"generic\")));\n\n try {\n recorder.start(TIMESLICE_MS);\n } catch {\n settle(() => reject(new ClipError(\"generic\")));\n return;\n }\n\n // Hard stop at CLIP_MS; gate on state, not on frame count.\n this.hardStopTimer = setTimeout(() => {\n // Recording window elapsed — the clip is DONE. Notify BEFORE finalize\n // (which may lag on iOS) so the host can freeze on the keyframe now.\n // Guarded by `settled`: an error/cliptoolarge before the hard-stop has\n // already cleared this timer, so this only runs for a real stop.\n if (!this.settled) onStopped?.();\n if (recorder.state !== \"inactive\") {\n try {\n recorder.stop();\n } catch {\n finalize();\n }\n // iOS safety-net: onstop may never fire — finalize from chunks (REVIEW FIX 3).\n this.graceTimer = setTimeout(finalize, STOP_GRACE_MS);\n } else {\n finalize();\n }\n }, CLIP_MS);\n });\n }\n\n /** Idempotent teardown: stop recorder + ALL tracks (v1 `stopAndCleanup` + the unmount\n * effect). Optional `stream` override mirrors v1's `stopAndCleanup(stream?)`.\n *\n * MID-RECORDING SEMANTICS (verbatim v1): calling stop() while a record() is in\n * flight may LATER resolve the pending promise with a TRUNCATED clip (recorder.stop()\n * fires onstop → finalize from whatever chunks arrived so far), or — because this\n * method clears the hard-stop/grace timers — never settle it at all if onstop never\n * fires (the iOS grace path has been torn down). Callers MUST NOT treat a resolution\n * arriving after stop() as a full CLIP_MS clip, and must not await a record()\n * promise past stop() without their own timeout. (Task 4's CaptureSession owns\n * sequencing on top of this contract.) */\n stop(stream?: MediaStream | null): void {\n this.clearTimers();\n const rec = this.recorder;\n if (rec && rec.state !== \"inactive\") {\n try {\n rec.stop();\n } catch {\n /* noop */\n }\n }\n this.recorder = null;\n const s = stream ?? this.stream;\n s?.getTracks().forEach((t) => t.stop());\n this.stream = null;\n }\n}\n","// Shared capture helpers — used by BOTH the (now sole) v3 engine and the\n// hosted gate-debug overlay. Extracted from the former v1 capture-session.ts\n// when the v1 engine was removed: the camera constraint tier + the mobile\n// heuristic are engine-agnostic, and the gate-geometry factors feed the\n// hosted debug overlay's tolerance rings. Zero React, calibration-pinned.\n\n/** getUserMedia constraint tier — 720p-class on every device since 2026-07-06.\n * The v2 FAS-CLIP liveness head loses its texture cues below ~720p: the SAME\n * genuine clip scores heads 0.0001 at 720x1280 vs 0.355 at the old 480x360\n * mobile tier, which pushed real users into review (first observed live on\n * staging 2026-07-06; falsified on corpus clips the same day). Dimensions are\n * sensor-relative (landscape); mobile browsers deliver portrait via rotation\n * metadata, which the liveness service's decoder applies (cv2\n * ORIENTATION_AUTO). `isMobile` is kept for call-site compat and future\n * divergence — both tiers are 720p today. Bitrate pairs with VIDEO_BPS in\n * clip-recorder.ts (2.5 Mbps). */\nexport function buildCaptureConstraints(\n isMobile: boolean,\n facingMode: \"user\" | \"environment\",\n): MediaStreamConstraints {\n void isMobile;\n return {\n video: {\n width: { ideal: 1280, max: 1280 },\n height: { ideal: 720, max: 720 },\n facingMode: facingMode,\n frameRate: { ideal: 24, max: 30 },\n },\n audio: false,\n };\n}\n\n/** v1 mobile heuristic (FaceCaptureV2.tsx L216-224). */\nexport function detectIsMobile(): boolean {\n if (typeof window === \"undefined\" || typeof navigator === \"undefined\") return false;\n return (\n window.innerWidth <= 768 ||\n /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(\n String(navigator.userAgent ?? \"\"),\n )\n );\n}\n\n// ── gate geometry factors ─────────────────────────────────────────────────────\n// The calibration-pinned gate math the hosted `?debug=gate` overlay derives its\n// tolerance rings from (lib/gate-geometry-constants.ts). Kept exported here after\n// the v1 FaceGate was removed so the overlay never restates them as literals.\n\n/** Gate radius as a fraction of the guidance circle (v1 L501: circleSize × 0.45). */\nexport const CIRCLE_RADIUS_FACTOR = 0.45;\n/** `inCircle` tolerance as a fraction of the gate radius (v1 L508: r × 0.9). */\nexport const IN_CIRCLE_FACTOR = 0.9;\n/** `centered` tolerance as a fraction of the gate radius (v1 L509: r × 0.4). */\nexport const CENTERED_FACTOR = 0.4;\n","// BlazeFace short-range tier (Task 7) — MediaPipe tasks-vision FaceDetector,\n// the modern default: strong on large/close faces, ~15–40ms on low-end\n// WASM+SIMD. tasks-vision is imported LAZILY (only when this tier is\n// selected) and every asset is SELF-HOSTED under the v3 asset base (hosted\n// CSP is connect-src 'self' — no CDN): the wasm fileset via\n// FilesetResolver.forVisionTasks(base) and the model at\n// `${base}/blaze_face_short_range.tflite` (synced by\n// identity-hosted/scripts/sync-models-v3.mjs, sha256-manifested).\n//\n// DELEGATE = 'CPU' (2026-07-09, capture-v3 hardening — the load-bearing fix):\n// tasks-vision defaults `baseOptions.delegate` to the WebGL/GPU delegate,\n// which HANGS on iOS Safari — every field capture blew the 10s init deadline\n// (`blaze:blaze_init_timeout`) and silently fell to the deprecated face-api\n// floor at ~2.4fps. BlazeFace short-range is tiny (~229 KB) and fast on the\n// WASM+SIMD CPU delegate, so we pin CPU UNCONDITIONALLY: reliability across\n// iOS Safari + Chrome beats the marginal desktop-GPU speedup (and the GPU\n// path is exactly the bug). A GPU-first-with-CPU-fallback dance would only\n// re-introduce the hang risk inside the init budget for no real win.\nimport { type Detector, type FaceObservation, intrinsicSize, toStreamPixels } from \"./detector\";\n\n/** createFromOptions must resolve within this window or the ladder falls\n * through with `blaze_init_timeout` (overridable via CreateDetectorOptions).\n * Raised 5s→10s: on iOS Safari the COLD wasm SIMD compile of tasks-vision can\n * exceed 5s on the FIRST (unwarmed) capture. Since the face-api floor was\n * dropped (2026-07-09), blowing this deadline is now a HARD capture failure\n * (error{kind:'models'} — retryable), not a silent degrade, so the CPU\n * delegate above (which makes init actually complete on iOS) is what keeps\n * this deadline reachable. The hosted warm path\n * (identity-hosted/lib/warm-models.ts) pre-warms this tier in idle time so\n * capture usually reuses a hot instance; this larger deadline only covers the\n * un-warmed fallback (Data-Saver, deep-link straight to liveness). */\nexport const BLAZE_INIT_TIMEOUT_MS = 10_000;\n\ninterface TasksVisionDetection {\n boundingBox?: { originX: number; originY: number; width: number; height: number };\n categories: Array<{ score: number }>;\n /** NORMALIZED to the input image (0..1) — tasks-vision docs; index 0 =\n * right eye, 1 = left eye (SUBJECT perspective). We re-order by image-x\n * (the FaceObservation convention), so the doc order is informative only. */\n keypoints?: Array<{ x: number; y: number }>;\n}\n\ninterface TasksVisionFaceDetector {\n detect(source: unknown): { detections: TasksVisionDetection[] };\n close(): void;\n}\n\nexport class BlazeDetector implements Detector {\n readonly tier = \"blaze\" as const;\n readonly fallbackReason?: string;\n private readonly inner: TasksVisionFaceDetector;\n\n private constructor(inner: TasksVisionFaceDetector, fallbackReason?: string) {\n this.inner = inner;\n if (fallbackReason !== undefined) this.fallbackReason = fallbackReason;\n }\n\n static async create(assetBaseUrl: string, fallbackReason?: string): Promise<BlazeDetector> {\n const vision = await import(\"@mediapipe/tasks-vision\");\n const fileset = await vision.FilesetResolver.forVisionTasks(assetBaseUrl);\n const inner = (await vision.FaceDetector.createFromOptions(fileset, {\n baseOptions: {\n modelAssetPath: `${assetBaseUrl}/blaze_face_short_range.tflite`,\n // CPU delegate — the iOS-Safari-safe path (see header). NEVER 'GPU'.\n delegate: \"CPU\",\n },\n runningMode: \"IMAGE\",\n })) as unknown as TasksVisionFaceDetector;\n return new BlazeDetector(inner, fallbackReason);\n }\n\n async detect(\n source: CanvasImageSource,\n sourceWidth: number,\n sourceHeight: number,\n ): Promise<FaceObservation | null> {\n let detections: TasksVisionDetection[];\n try {\n detections = this.inner.detect(source).detections;\n } catch {\n return null; // never rejects mid-loop\n }\n const best = pickMostConfident(detections);\n if (best?.boundingBox === undefined) return null;\n const size = intrinsicSize(source);\n const eyes = extractEyes(best.keypoints, size);\n const observation: FaceObservation = {\n box: {\n x: best.boundingBox.originX,\n y: best.boundingBox.originY,\n width: best.boundingBox.width,\n height: best.boundingBox.height,\n },\n ...(eyes !== undefined ? { eyes } : {}),\n score: best.categories[0]?.score ?? 0,\n };\n return toStreamPixels(observation, source, sourceWidth, sourceHeight);\n }\n\n destroy(): void {\n try {\n this.inner.close();\n } catch {\n // wasm teardown failures are inert\n }\n }\n}\n\nfunction pickMostConfident(detections: TasksVisionDetection[]): TasksVisionDetection | undefined {\n let best: TasksVisionDetection | undefined;\n let bestScore = -1;\n for (const detection of detections) {\n const score = detection.categories[0]?.score ?? 0;\n if (score > bestScore) {\n best = detection;\n bestScore = score;\n }\n }\n return best;\n}\n\n/** Keypoints 0/1 (the eye pair) — normalized → SOURCE px, ordered by image-x. */\nfunction extractEyes(\n keypoints: Array<{ x: number; y: number }> | undefined,\n size: { width: number; height: number },\n): FaceObservation[\"eyes\"] | undefined {\n const a = keypoints?.[0];\n const b = keypoints?.[1];\n if (a === undefined || b === undefined) return undefined;\n const toSource = (p: { x: number; y: number }) => ({ x: p.x * size.width, y: p.y * size.height });\n const [pa, pb] = [toSource(a), toSource(b)];\n return pa.x <= pb.x ? { left: pa, right: pb } : { left: pb, right: pa };\n}\n","// Native FaceDetector tier (Task 6) — the Shape Detection API: free,\n// hardware-backed where implemented (Chrome/Android, some WebViews). Probed\n// with a 1-frame smoke detect because several browsers EXPOSE the constructor\n// but throw `Face detection service unavailable` at runtime.\nimport { type Detector, type FaceObservation, toStreamPixels } from \"./detector\";\n\ninterface NativeLandmark {\n type: string;\n locations: Array<{ x: number; y: number }>;\n}\n\ninterface NativeDetectedFace {\n boundingBox: { x: number; y: number; width: number; height: number };\n landmarks?: NativeLandmark[];\n}\n\nexport interface NativeFaceDetectorLike {\n detect(source: CanvasImageSource): Promise<NativeDetectedFace[]>;\n}\n\ntype NativeGlobal = typeof globalThis & {\n FaceDetector?: new (options: { fastMode: boolean; maxDetectedFaces: number }) => NativeFaceDetectorLike;\n};\n\nfunction smokeSource(): CanvasImageSource {\n if (typeof OffscreenCanvas === \"function\") return new OffscreenCanvas(2, 2);\n const canvas = document.createElement(\"canvas\");\n canvas.width = 2;\n canvas.height = 2;\n return canvas;\n}\n\n/** Constructor + 1-frame smoke detect (must not throw; result irrelevant). */\nexport async function probeNativeDetector(): Promise<\n { ok: true; instance: NativeFaceDetectorLike } | { ok: false; reason: string }\n> {\n const ctor = (globalThis as NativeGlobal).FaceDetector;\n if (typeof ctor !== \"function\") return { ok: false, reason: \"unsupported\" };\n try {\n const instance = new ctor({ fastMode: true, maxDetectedFaces: 1 });\n await instance.detect(smokeSource());\n return { ok: true, instance };\n } catch (err) {\n return { ok: false, reason: `smoke_failed:${err instanceof Error ? err.message : String(err)}` };\n }\n}\n\nexport class NativeDetector implements Detector {\n readonly tier = \"native\" as const;\n readonly fallbackReason?: string;\n private readonly inner: NativeFaceDetectorLike;\n\n constructor(inner: NativeFaceDetectorLike, fallbackReason?: string) {\n this.inner = inner;\n if (fallbackReason !== undefined) this.fallbackReason = fallbackReason;\n }\n\n async detect(\n source: CanvasImageSource,\n sourceWidth: number,\n sourceHeight: number,\n ): Promise<FaceObservation | null> {\n let faces: NativeDetectedFace[];\n try {\n faces = await this.inner.detect(source);\n } catch {\n return null; // never rejects mid-loop\n }\n const face = faces[0];\n if (face === undefined) return null;\n const eyes = extractEyes(face.landmarks);\n const observation: FaceObservation = {\n box: {\n x: face.boundingBox.x,\n y: face.boundingBox.y,\n width: face.boundingBox.width,\n height: face.boundingBox.height,\n },\n ...(eyes !== undefined ? { eyes } : {}),\n // The Shape Detection API exposes no confidence — the smoke-tested\n // native tier treats any detection as confident.\n score: 1,\n };\n return toStreamPixels(observation, source, sourceWidth, sourceHeight);\n }\n\n destroy(): void {\n // The native detector holds no resources the page must release.\n }\n}\n\n/** Two `eye` landmarks → {left, right} by image-x (see FaceObservation). */\nfunction extractEyes(\n landmarks: NativeLandmark[] | undefined,\n): FaceObservation[\"eyes\"] | undefined {\n if (landmarks === undefined) return undefined;\n const eyePoints = landmarks\n .filter((landmark) => landmark.type === \"eye\")\n .map((landmark) => landmark.locations[0])\n .filter((point): point is { x: number; y: number } => point !== undefined);\n const [a, b] = eyePoints;\n if (a === undefined || b === undefined) return undefined;\n return a.x <= b.x ? { left: a, right: b } : { left: b, right: a };\n}\n","// v3 Detector abstraction (capture program Task 6) — one detection seam with\n// capability-probed tiers. NEW parallel module: nothing in the v1 core\n// imports from v3/*, and the calibration-pinned v1 gate math is untouched.\n//\n// Ladder (DEFAULT_TIER_ORDER): `native` (the browser's FaceDetector — free,\n// hardware-backed where it exists) → `blaze` (MediaPipe BlazeFace short-range,\n// Task 7). The legacy `faceapi` floor was DROPPED (2026-07-09, capture-v3\n// hardening): field telemetry showed BlazeFace never initialized (the GPU\n// delegate hung on iOS → `blaze_init_timeout`) so EVERY capture silently ran\n// the deprecated ~2.4fps face-api floor. With the CPU-delegate blaze fix,\n// face-api is dead weight — and a floor that masks a blaze regression is worse\n// than none, so the ladder is now native→blaze with NO fallback.\n//\n// Contract change: createDetector still never throws while a tier can be\n// built, but with no floor it REJECTS (DetectorLadderError) once the ladder is\n// exhausted — a CLEAN, non-hanging failure carrying the per-tier reasons.\n// CaptureSessionV3.run() maps that rejection to error{kind:'models'}\n// (retryable; the hosted UI renders a retry). A skipped tier still records a\n// `fallbackReason` (exposed on the returned Detector) so a native→blaze\n// fall-through stays observable in telemetry.\nimport { BLAZE_INIT_TIMEOUT_MS, BlazeDetector } from \"./detector-blaze\";\nimport { NativeDetector, probeNativeDetector } from \"./detector-native\";\n\nexport interface FaceObservation {\n /** Stream-pixel box. */\n box: { x: number; y: number; width: number; height: number };\n /** Stream-pixel eye centers when the tier provides them (native:\n * landmarks?, blaze: keypoints). Convention: `left` = smaller x in IMAGE\n * coordinates — gate math only uses the midpoint and |roll|, so the\n * person-left/image-left distinction never matters. */\n eyes?: { left: { x: number; y: number }; right: { x: number; y: number } };\n score: number;\n}\n\nexport interface Detector {\n readonly tier: \"native\" | \"blaze\";\n /** Why higher tiers were skipped (telemetry) — absent when the first\n * preference won. */\n readonly fallbackReason?: string;\n /** Detect on a (possibly downscaled) snapshot; `sourceWidth/Height` are the\n * STREAM dimensions the observation must be normalized to. Returns the\n * single most-confident face or null; NEVER rejects. */\n detect(\n source: CanvasImageSource,\n sourceWidth: number,\n sourceHeight: number,\n ): Promise<FaceObservation | null>;\n destroy(): void;\n}\n\nexport interface CreateDetectorOptions {\n /** v3 self-hosted assets base (tasks-vision wasm + blaze tflite) — hosted\n * serves `/models-v3`, a sha256-manifested directory. */\n v3AssetBaseUrl?: string;\n preferred?: Detector[\"tier\"][];\n /** Test/tuning override for the blaze init deadline. */\n blazeInitTimeoutMs?: number;\n}\n\nexport const DEFAULT_V3_ASSET_BASE_URL = \"/models-v3\";\n\nexport const DEFAULT_TIER_ORDER: Detector[\"tier\"][] = [\"native\", \"blaze\"];\n\n/** Thrown by createDetector when the ENTIRE tier ladder is exhausted. Since the\n * face-api floor was dropped (2026-07-09) there is no last resort, so blaze\n * failing on an already-native-less platform leaves NO detector. Carries the\n * joined per-tier reasons ('native:unsupported; blaze:blaze_init_timeout') as\n * `fallbackReason` for telemetry. Callers MUST map this to a retryable models\n * error — never a hang (CaptureSessionV3.run → error{kind:'models'}). */\nexport class DetectorLadderError extends Error {\n readonly fallbackReason: string;\n constructor(fallbackReason: string) {\n super(`no detector tier available (${fallbackReason})`);\n this.name = \"DetectorLadderError\";\n this.fallbackReason = fallbackReason;\n }\n}\n\n/** Intrinsic pixel size of a snapshot source (video → videoWidth, image →\n * naturalWidth, canvas/bitmap → width). Property-sniffed so worker-side\n * sources (OffscreenCanvas, ImageBitmap) work without instanceof. */\nexport function intrinsicSize(source: CanvasImageSource): { width: number; height: number } {\n const candidate = source as {\n videoWidth?: number;\n videoHeight?: number;\n naturalWidth?: number;\n naturalHeight?: number;\n width?: number | { baseVal?: { value?: number } };\n height?: number | { baseVal?: { value?: number } };\n };\n if (typeof candidate.videoWidth === \"number\" && candidate.videoWidth > 0) {\n return { width: candidate.videoWidth, height: candidate.videoHeight ?? 0 };\n }\n if (typeof candidate.naturalWidth === \"number\" && candidate.naturalWidth > 0) {\n return { width: candidate.naturalWidth, height: candidate.naturalHeight ?? 0 };\n }\n const width = typeof candidate.width === \"number\" ? candidate.width : 0;\n const height = typeof candidate.height === \"number\" ? candidate.height : 0;\n return { width, height };\n}\n\n/** Scale a source-space observation to stream px. Exported for adapters. */\nexport function toStreamPixels(\n observation: FaceObservation,\n source: CanvasImageSource,\n streamWidth: number,\n streamHeight: number,\n): FaceObservation {\n const size = intrinsicSize(source);\n const scaleX = size.width > 0 ? streamWidth / size.width : 1;\n const scaleY = size.height > 0 ? streamHeight / size.height : 1;\n const scalePoint = (p: { x: number; y: number }) => ({ x: p.x * scaleX, y: p.y * scaleY });\n return {\n box: {\n x: observation.box.x * scaleX,\n y: observation.box.y * scaleY,\n width: observation.box.width * scaleX,\n height: observation.box.height * scaleY,\n },\n ...(observation.eyes !== undefined\n ? { eyes: { left: scalePoint(observation.eyes.left), right: scalePoint(observation.eyes.right) } }\n : {}),\n score: observation.score,\n };\n}\n\nfunction describeError(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nexport async function createDetector(options: CreateDetectorOptions): Promise<Detector> {\n const order = options.preferred ?? DEFAULT_TIER_ORDER;\n const reasons: string[] = [];\n for (const tier of order) {\n if (tier === \"native\") {\n const probed = await probeNativeDetector();\n if (probed.ok) {\n return new NativeDetector(probed.instance, reasonOf(reasons));\n }\n reasons.push(`native:${probed.reason}`);\n continue;\n }\n // tier === \"blaze\": smoke test = createFromOptions resolving within the\n // deadline (wasm fetch/compile can hang on hostile networks — never stall\n // the ladder).\n try {\n return await withTimeout(\n BlazeDetector.create(\n options.v3AssetBaseUrl ?? DEFAULT_V3_ASSET_BASE_URL,\n reasonOf(reasons),\n ),\n options.blazeInitTimeoutMs ?? BLAZE_INIT_TIMEOUT_MS,\n );\n } catch (err) {\n reasons.push(\n err instanceof InitTimeoutError\n ? \"blaze:blaze_init_timeout\"\n : `blaze:${describeError(err)}`,\n );\n }\n }\n // Ladder exhausted — the face-api floor is gone, so there is NO fallback.\n // REJECT cleanly with the recorded reasons; CaptureSessionV3.run() maps this\n // to a retryable error{kind:'models'} (a bounded failure the hosted UI\n // retries) rather than hanging. NEVER return a null-yielding detector here.\n throw new DetectorLadderError(reasonOf(reasons) ?? \"no_tier_available\");\n}\n\nfunction reasonOf(reasons: string[]): string | undefined {\n return reasons.length > 0 ? reasons.join(\"; \") : undefined;\n}\n\nclass InitTimeoutError extends Error {}\n\nfunction withTimeout<T extends { destroy(): void }>(\n promise: Promise<T>,\n deadlineMs: number,\n): Promise<T> {\n return new Promise<T>((resolvePromise, rejectPromise) => {\n const timer = setTimeout(() => {\n rejectPromise(new InitTimeoutError(`init exceeded ${deadlineMs}ms`));\n // A late resolution after the deadline is an orphan (wasm/GPU\n // delegate) — release it instead of leaking until navigation.\n promise.then(\n (value) => value.destroy(),\n () => undefined,\n );\n }, deadlineMs);\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolvePromise(value);\n },\n (err) => {\n clearTimeout(timer);\n rejectPromise(err);\n },\n );\n });\n}\n","// frame-quality (Task 8) — pure, deterministic image measures on a small\n// (≤96px) face crop. No canvas access here: callers hand in ImageData; that\n// keeps these functions golden-testable and worker-portable.\n\n/** Laplacian-variance normalization reference — crops whose edge variance\n * reaches this value (or beyond) count as fully sharp. */\nexport const SHARP_REF = 180;\n\n/** Mean-luma comfort band: inside → exposure 1; outside → linear falloff.\n * Dark bound raised 70→100 (operator ruling 2026-07-07): face crops in the\n * 70–100 range passed the gate but kept drawing dark-face review verdicts —\n * gating them here converts that into pre-capture more_light coaching. */\nexport const EXPOSURE_BAND: readonly [number, number] = [100, 190];\n\n/** Luma distance that zeroes the exposure factor (≈ one stop past the band). */\nconst EXPOSURE_FALLOFF = 64;\n\n/** Rec.601 luma. */\nfunction lumaAt(data: Uint8ClampedArray, index: number): number {\n return (\n 0.299 * (data[index] ?? 0) + 0.587 * (data[index + 1] ?? 0) + 0.114 * (data[index + 2] ?? 0)\n );\n}\n\nexport function meanLuma(image: ImageData): number {\n const { data, width, height } = image;\n const pixels = width * height;\n if (pixels === 0) return 0;\n let sum = 0;\n for (let i = 0; i < pixels; i += 1) sum += lumaAt(data, i * 4);\n return sum / pixels;\n}\n\n/**\n * Sharpness = variance of the 3×3 Laplacian (∇² kernel [0,1,0;1,−4,1;0,1,0])\n * over the interior pixels, normalized 0..1 against SHARP_REF. Flat crop → 0;\n * hard edges → 1 (clamped).\n */\nexport function sharpness(image: ImageData): number {\n const { data, width, height } = image;\n if (width < 3 || height < 3) return 0;\n const gray = new Float32Array(width * height);\n for (let i = 0; i < gray.length; i += 1) gray[i] = lumaAt(data, i * 4);\n let sum = 0;\n let sumSquares = 0;\n let count = 0;\n for (let y = 1; y < height - 1; y += 1) {\n for (let x = 1; x < width - 1; x += 1) {\n const i = y * width + x;\n const response =\n (gray[i - width] ?? 0) +\n (gray[i - 1] ?? 0) +\n (gray[i + 1] ?? 0) +\n (gray[i + width] ?? 0) -\n 4 * (gray[i] ?? 0);\n sum += response;\n sumSquares += response * response;\n count += 1;\n }\n }\n if (count === 0) return 0;\n const mean = sum / count;\n const variance = sumSquares / count - mean * mean;\n // VARIANCE against the reference (the plan's formula). Field lesson\n // (Salem's iPhone, 2026-07-07): sqrt(variance)/REF put every real face\n // crop at ~0.03-0.1 — permanently under the steady_camera threshold and\n // crushing q to zero, so the gate could never fire. Real crops have\n // Laplacian variance well above 180; a genuinely soft/blurred crop does not.\n return Math.min(1, Math.max(0, variance) / SHARP_REF);\n}\n\n/** Exposure factor: 1 inside the band; linear falloff to 0 over\n * EXPOSURE_FALLOFF luma outside it. */\nexport function exposure(image: ImageData): number {\n const mean = meanLuma(image);\n const [low, high] = EXPOSURE_BAND;\n const distance = mean < low ? low - mean : mean > high ? mean - high : 0;\n return Math.max(0, 1 - distance / EXPOSURE_FALLOFF);\n}\n","// FaceGateV3 (Task 8) — the v3 gate: scale-invariant, landmark-aware,\n// continuous-quality, gentle-drain. PARALLEL to the calibration-pinned v1\n// FaceGate (face-gate.ts) — nothing here feeds or alters v1's math.\n//\n// Design deltas vs v1 (the two field complaints this kills):\n// - the gate point is the EYE MIDPOINT when the tier provides eyes (humans\n// center their EYES, detectors center their BBOX — v1's bbox-center gate\n// read a centered face as \"high\"); box-only tiers get a documented\n// 0.12×height upward shift instead;\n// - progress is a CONTINUOUS integrator (rise 0.9/s on good quality, fall\n// 0.25/s on bad) instead of v1's ±counters — a wobble dips the progress\n// slightly instead of resetting the attempt.\n//\n// q AGGREGATION = MIN over factors (operator ruling 2026-07-12, replacing\n// the original 7-factor PRODUCT). Field finding: with a product, seven\n// factors each at a decent 0.85 gave q≈0.32 — progress DRAINED while every\n// factor sat above its guidance threshold, so the chrome said \"hold still\"\n// and the only discoverable escape was leaning unnaturally close (size,\n// centering falloff (∝IOD) and crop sharpness all improve together with\n// proximity). min() makes q the same quantity guidance reasons about — the\n// worst factor — so \"no complaint\" ⇔ \"progress rises\" by construction, one\n// genuinely bad factor still blocks (non-compensatory), and many mediocre\n// factors (the low-end-device reality: noisy sensor, dim room, wide FOV)\n// are no longer multiplied into failure.\n//\n// 100% deterministic: the clock is a tick INPUT (timestampMs); nothing here\n// reads Date.now or performance.now.\nimport type { FaceObservation } from \"./detector\";\nimport { EXPOSURE_BAND } from \"./frame-quality\";\n\nexport interface V3GateThresholds {\n /** q at/above which progress rises; below it progress falls. */\n Q_GOOD: number;\n /** Integrator slopes, per second. */\n RISE_PER_S: number;\n FALL_PER_S: number;\n /** Centering falloff radius = this × IOD (scale-invariant). The plan's\n * formula is 0.45 × IOD × 3 — the 0.45 echoes v1's CIRCLE_RADIUS_FACTOR\n * heritage — folded here to 1.35 × IOD. */\n CENTER_FALLOFF_IOD_MULTIPLE: number;\n /** Box-only tiers: gate point = bbox center shifted UP by this × height\n * (the documented bbox-vs-eyes offset heuristic). */\n BOX_EYE_OFFSET_FACTOR: number;\n /** Box-only IOD proxy = this × box width. */\n IOD_BOX_PROXY_FACTOR: number;\n /** IOD / frame short side: ideal band + hard limits. */\n SIZE_IDEAL_MIN: number;\n SIZE_IDEAL_MAX: number;\n SIZE_HARD_MIN: number;\n SIZE_HARD_MAX: number;\n /** Eye-line roll (deg) that zeroes the pose factor. */\n ROLL_MAX_DEG: number;\n /** Center velocity that zeroes the motion factor, in IOD-per-second. */\n MOTION_VELOCITY_IOD_PER_S: number;\n /** Velocity-EMA time constant (seconds) — the EMA weight is derived per\n * tick as 1−exp(−dt/τ), so the smoothing HORIZON is cadence-invariant:\n * a LOW device detecting at 5 Hz gets the same effective smoothing as a\n * HIGH device at 10 Hz (a fixed per-sample alpha under-smoothed exactly\n * the jittery low-cadence ticks that needed it most). */\n MOTION_TAU_S: number;\n /** Velocities at/below this (IOD/s) count as stillness — absorbs detector\n * box jitter (largest on LOW's 128px input) before it reaches the EMA. */\n MOTION_DEADBAND_IOD_PER_S: number;\n /** ready = p ≥ 1 AND no bad tick (q < Q_GOOD) left in this window after\n * TRIMMING: with ≥3 samples the single worst is dropped, so one flaky tick\n * (5 Hz LOW cadence = only 2–3 samples per window) cannot veto an\n * otherwise-ready user, while a SECOND bad tick (a real sustained wobble)\n * still blocks. The readiness bar is Q_GOOD itself — the level the\n * integrator rises on — so any input that fills the ring also fires it. */\n READY_WINDOW_MS: number;\n /** Per-factor guidance trigger levels (lowest failing factor speaks). */\n GUIDE_SIZE: number;\n GUIDE_CENTERING: number;\n GUIDE_POSE: number;\n GUIDE_EXPOSURE: number;\n GUIDE_SHARPNESS: number;\n GUIDE_MOTION: number;\n}\n\n/** Defaults — retuned 2026-07-12 (operator ruling superseding the 2026-07\n * freeze; the capture Task-15 refit set must be split at this boundary):\n * Q_GOOD 0.55→0.6 so it aligns with the 0.6 guidance thresholds under\n * min-q (\"no complaint\" ⇔ \"progress rises\"); SIZE_IDEAL_MIN 0.16→0.12 —\n * wide-FOV front cameras (common low-end) put an arm's-length face below\n * 0.16, silently forcing lean-in; the 720p clip floor keeps a 0.12-IOD\n * face fully resolvable server-side. */\nexport const V3_GATE_DEFAULTS: Readonly<V3GateThresholds> = Object.freeze({\n Q_GOOD: 0.6,\n RISE_PER_S: 0.9,\n FALL_PER_S: 0.25,\n CENTER_FALLOFF_IOD_MULTIPLE: 1.35,\n BOX_EYE_OFFSET_FACTOR: 0.12,\n IOD_BOX_PROXY_FACTOR: 0.42,\n SIZE_IDEAL_MIN: 0.12,\n SIZE_IDEAL_MAX: 0.3,\n SIZE_HARD_MIN: 0.08,\n SIZE_HARD_MAX: 0.45,\n ROLL_MAX_DEG: 25,\n MOTION_VELOCITY_IOD_PER_S: 0.5,\n MOTION_TAU_S: 0.4,\n MOTION_DEADBAND_IOD_PER_S: 0.1,\n READY_WINDOW_MS: 500,\n // (READY_MEAN_Q, the former 0.75 window MEAN, is gone — 2026-10-17 field\n // bug: a steady q anywhere in [Q_GOOD, 0.75) saturated p at 1, passed every\n // guide (\"hold still\") and could never reach the mean, so the ring sat full\n // and green with nothing recording. Readiness now checks the window against\n // Q_GOOD, which keeps the one-flaky-tick forgiveness and the second-bad-tick\n // block without a dead band above the rise threshold.)\n GUIDE_SIZE: 0.6,\n GUIDE_CENTERING: 0.6,\n GUIDE_POSE: 0.6,\n GUIDE_EXPOSURE: 0.6,\n GUIDE_SHARPNESS: 0.35,\n GUIDE_MOTION: 0.5,\n});\n\nexport interface V3GateQuality {\n /** From frame-quality.sharpness on the face crop. */\n sharpness: number;\n /** From frame-quality.exposure on the face crop. */\n exposure: number;\n /** Mean crop luma — picks more_light vs too_bright guidance. */\n meanLuma: number;\n}\n\nexport interface V3GateTickInput {\n timestampMs: number;\n observation: FaceObservation | null;\n quality: V3GateQuality;\n frameWidth: number;\n frameHeight: number;\n}\n\nexport type V3GateFactor =\n | \"presence\"\n | \"centering\"\n | \"size\"\n | \"pose\"\n | \"sharpness\"\n | \"exposure\"\n | \"motion\";\n\n/** Per-tick output — the telemetry + chrome contract. */\nexport interface V3GateTick {\n at: number;\n /** Instantaneous quality 0..1 (MIN over the factors — the worst factor). */\n q: number;\n /** Integrated progress 0..1. */\n p: number;\n factors: Record<V3GateFactor, number>;\n /** fcv3.* message key for the lowest failing factor (host translates). */\n guidanceKey: string;\n /** Fire signal: p ≥ 1 AND no second bad tick (q < Q_GOOD) in READY_WINDOW_MS. */\n ready: boolean;\n}\n\nconst clamp01 = (value: number) => Math.min(1, Math.max(0, value));\n\nexport class FaceGateV3 {\n private readonly t: V3GateThresholds;\n private p = 0;\n private lastTickAt: number | null = null;\n private lastCenter: { x: number; y: number; at: number } | null = null;\n private velocityEma = 0;\n private qWindow: Array<{ at: number; q: number }> = [];\n\n constructor(overrides: Partial<V3GateThresholds> = {}) {\n this.t = { ...V3_GATE_DEFAULTS, ...overrides };\n }\n\n reset(): void {\n this.p = 0;\n this.lastTickAt = null;\n this.lastCenter = null;\n this.velocityEma = 0;\n this.qWindow = [];\n this.lastSizeDirection = \"ideal\";\n }\n\n tick(input: V3GateTickInput): V3GateTick {\n const { observation, quality, timestampMs } = input;\n const dtSeconds =\n this.lastTickAt === null\n ? 0\n : Math.max(0, (timestampMs - this.lastTickAt) / 1000);\n this.lastTickAt = timestampMs;\n\n const factors: Record<V3GateFactor, number> = {\n presence: 0,\n centering: 0,\n size: 0,\n pose: 0,\n sharpness: clamp01(quality.sharpness),\n exposure: clamp01(quality.exposure),\n motion: 1,\n };\n\n if (observation !== null) {\n factors.presence = 1;\n const geometry = this.geometryOf(observation, input);\n factors.centering = geometry.centering;\n factors.size = geometry.size;\n factors.pose = geometry.pose;\n factors.motion = this.motionOf(\n geometry.center,\n geometry.iod,\n timestampMs,\n );\n } else {\n // No face: the motion history must not survive to the next sighting\n // (a re-acquired face \"jumping\" from its old position is not motion,\n // and a stale pre-loss velocity EMA must not penalize re-acquisition).\n this.lastCenter = null;\n this.velocityEma = 0;\n }\n\n // Worst factor IS the quality (see header) — presence 0 zeroes it exactly\n // as the old product did; the compensatory many-mediocre penalty is gone.\n const q = Math.min(\n factors.presence,\n factors.centering,\n factors.size,\n factors.pose,\n factors.sharpness,\n factors.exposure,\n factors.motion,\n );\n\n // Integrator: gentle drain — bad ticks pull p down at FALL×(1−q), never\n // reset it (the v1 counter-reset feel this replaces).\n this.p = clamp01(\n this.p +\n (q >= this.t.Q_GOOD\n ? this.t.RISE_PER_S * q\n : -this.t.FALL_PER_S * (1 - q)) *\n dtSeconds,\n );\n\n // Sustained-quality window (prevents luck-firing through a wobble).\n // TRIMMED: with ≥3 samples the single worst is dropped — at LOW's 5 Hz\n // cadence a window holds 2–3 ticks, and one jittery detection must not\n // veto a user who is otherwise steadily ready. Every remaining sample must\n // be a GOOD tick (q ≥ Q_GOOD, the integrator's own rise level): a second\n // bad tick blocks, and — by construction — any steady input that fills\n // the ring is ready the moment the window is clean (no dead band where\n // p = 1, guidance says hold_still and nothing fires; 2026-10-17).\n this.qWindow.push({ at: timestampMs, q });\n this.qWindow = this.qWindow.filter(\n (entry) => entry.at >= timestampMs - this.t.READY_WINDOW_MS,\n );\n let windowSamples = this.qWindow.map((entry) => entry.q);\n if (windowSamples.length >= 3) {\n const worst = Math.min(...windowSamples);\n const worstIndex = windowSamples.indexOf(worst);\n windowSamples = windowSamples.filter((_, index) => index !== worstIndex);\n }\n const ready =\n this.p >= 1 && windowSamples.every((sample) => sample >= this.t.Q_GOOD);\n\n return {\n at: timestampMs,\n q,\n p: this.p,\n factors,\n guidanceKey: this.guidanceOf(factors, quality, q),\n ready,\n };\n }\n\n private geometryOf(\n observation: FaceObservation,\n input: V3GateTickInput,\n ): {\n center: { x: number; y: number };\n iod: number;\n centering: number;\n size: number;\n pose: number;\n } {\n const { box, eyes } = observation;\n const frameCenter = { x: input.frameWidth / 2, y: input.frameHeight / 2 };\n const shortSide = Math.min(input.frameWidth, input.frameHeight);\n\n // Gate point: eye midpoint, or the bbox center shifted UP so box-only\n // tiers behave like eye tiers (BOX_EYE_OFFSET heuristic).\n const center =\n eyes !== undefined\n ? {\n x: (eyes.left.x + eyes.right.x) / 2,\n y: (eyes.left.y + eyes.right.y) / 2,\n }\n : {\n x: box.x + box.width / 2,\n y:\n box.y +\n box.height / 2 -\n this.t.BOX_EYE_OFFSET_FACTOR * box.height,\n };\n const iod =\n eyes !== undefined\n ? Math.hypot(eyes.right.x - eyes.left.x, eyes.right.y - eyes.left.y)\n : this.t.IOD_BOX_PROXY_FACTOR * box.width;\n\n // Smooth, SCALE-INVARIANT centering falloff: distance measured in IODs.\n const distance = Math.hypot(\n center.x - frameCenter.x,\n center.y - frameCenter.y,\n );\n const centering =\n iod <= 0\n ? 0\n : 1 - clamp01(distance / (this.t.CENTER_FALLOFF_IOD_MULTIPLE * iod));\n\n // Size factor from IOD relative to the frame short side.\n const ratio = shortSide > 0 ? iod / shortSide : 0;\n this.lastSizeDirection =\n ratio < this.t.SIZE_IDEAL_MIN\n ? \"far\"\n : ratio > this.t.SIZE_IDEAL_MAX\n ? \"close\"\n : \"ideal\";\n let size: number;\n if (ratio < this.t.SIZE_HARD_MIN || ratio > this.t.SIZE_HARD_MAX) {\n size = 0;\n } else if (ratio < this.t.SIZE_IDEAL_MIN) {\n size =\n (ratio - this.t.SIZE_HARD_MIN) /\n (this.t.SIZE_IDEAL_MIN - this.t.SIZE_HARD_MIN);\n } else if (ratio > this.t.SIZE_IDEAL_MAX) {\n size =\n (this.t.SIZE_HARD_MAX - ratio) /\n (this.t.SIZE_HARD_MAX - this.t.SIZE_IDEAL_MAX);\n } else {\n size = 1;\n }\n\n // Pose from the eye-line roll; box-only tiers stay neutral (no signal).\n let pose = 1;\n if (eyes !== undefined) {\n const rollDeg =\n (Math.abs(\n Math.atan2(eyes.right.y - eyes.left.y, eyes.right.x - eyes.left.x),\n ) *\n 180) /\n Math.PI;\n pose = 1 - clamp01(rollDeg / this.t.ROLL_MAX_DEG);\n }\n\n return { center, iod, centering, size, pose };\n }\n\n private motionOf(\n center: { x: number; y: number },\n iod: number,\n at: number,\n ): number {\n const previous = this.lastCenter;\n this.lastCenter = { ...center, at };\n if (previous === null || iod <= 0) return 1;\n const dtSeconds = (at - previous.at) / 1000;\n if (dtSeconds <= 0) return 1;\n let velocityIodPerS =\n Math.hypot(center.x - previous.x, center.y - previous.y) /\n iod /\n dtSeconds;\n // Deadband: sub-jitter velocities are stillness. Detector boxes quantize\n // hardest on LOW's 128px input, where a ±1px wobble at 5 Hz reads as\n // ~0.25 IOD/s — half the zeroing velocity — despite a rock-steady user.\n if (velocityIodPerS <= this.t.MOTION_DEADBAND_IOD_PER_S)\n velocityIodPerS = 0;\n // Time-constant EMA: alpha derived from dt so the smoothing horizon is\n // the same at 5 Hz and 10 Hz (see MOTION_TAU_S).\n const alpha = 1 - Math.exp(-dtSeconds / this.t.MOTION_TAU_S);\n this.velocityEma = alpha * velocityIodPerS + (1 - alpha) * this.velocityEma;\n return 1 - clamp01(this.velocityEma / this.t.MOTION_VELOCITY_IOD_PER_S);\n }\n\n /** Lowest failing factor speaks — fixed priority (diagnostic, incl. light):\n * presence → size → centering → pose → exposure → sharpness → hold.\n *\n * HONESTY FALLBACK (operator ruling 2026-07-12): when every factor clears\n * its guide threshold but q (= min factor) is still below Q_GOOD — i.e.\n * progress is DRAINING — \"hold still\" would be a lie (\"Perfect\" while\n * nothing advances; the field symptom was users discovering by accident\n * that only leaning in fires the gate). In that state the WORST factor\n * speaks even though it passed its guide level, so the user always hears\n * the change that actually unblocks recording. */\n private guidanceOf(\n factors: Record<V3GateFactor, number>,\n quality: V3GateQuality,\n q: number,\n ): string {\n if (factors.presence <= 0) return \"fcv3.no_face\";\n if (factors.size < this.t.GUIDE_SIZE) return this.sizeGuidance();\n if (factors.centering < this.t.GUIDE_CENTERING) return \"fcv3.center_face\";\n if (factors.pose < this.t.GUIDE_POSE) return \"fcv3.straighten\";\n if (factors.exposure < this.t.GUIDE_EXPOSURE)\n return this.exposureGuidance(quality);\n if (factors.sharpness < this.t.GUIDE_SHARPNESS) return \"fcv3.steady_camera\";\n if (factors.motion < this.t.GUIDE_MOTION) return \"fcv3.hold_still\";\n if (q < this.t.Q_GOOD) {\n // All guides pass but progress drains — coach the worst factor anyway.\n const coachable: Array<[V3GateFactor, string]> = [\n [\"size\", this.sizeGuidance()],\n [\"centering\", \"fcv3.center_face\"],\n [\"pose\", \"fcv3.straighten\"],\n [\"exposure\", this.exposureGuidance(quality)],\n [\"sharpness\", \"fcv3.steady_camera\"],\n [\"motion\", \"fcv3.hold_still\"],\n ];\n let worst = coachable[0] as [V3GateFactor, string];\n for (const entry of coachable) {\n if (factors[entry[0]] < factors[worst[0]]) worst = entry;\n }\n return worst[1];\n }\n return \"fcv3.hold_still\";\n }\n\n /** Direction from the size band set THIS tick (never inverted at the hard\n * limits: past SIZE_HARD_MAX the direction is 'close' → move_back). */\n private sizeGuidance(): string {\n return this.lastSizeDirection === \"far\"\n ? \"fcv3.come_closer\"\n : \"fcv3.move_back\";\n }\n\n /** Band midpoint — direction only (tracks EXPOSURE_BAND automatically). */\n private exposureGuidance(quality: V3GateQuality): string {\n const bandMid = (EXPOSURE_BAND[0] + EXPOSURE_BAND[1]) / 2;\n return quality.meanLuma < bandMid ? \"fcv3.more_light\" : \"fcv3.too_bright\";\n }\n\n /** Which side of the ideal band the last size measurement fell on. */\n private lastSizeDirection: \"far\" | \"close\" | \"ideal\" = \"ideal\";\n}\n","// Device profiles (Task 9) — LOW/MID/HIGH from a boot probe, refined by the\n// first measured detect times. Profiles adapt DETECTION cost only (cadence,\n// downscale input width, animation richness): clip constraints are NOT here —\n// the 720p/2.5Mbps floor is global (locked decision 1) and lives in the v1\n// constraint builder both engines share.\n\nexport type DeviceClass = \"LOW\" | \"MID\" | \"HIGH\";\n\nexport interface DeviceProfile {\n /** Detection cadence — the scheduler's pace. */\n cadenceHz: number;\n /** Downscaled snapshot width handed to the detector. */\n inputWidth: number;\n /** Chrome hint: 'reduced' tones down ticks/breathe on LOW even without\n * prefers-reduced-motion. */\n animations: \"full\" | \"reduced\";\n}\n\nexport const DEVICE_PROFILES: Readonly<Record<DeviceClass, Readonly<DeviceProfile>>> =\n Object.freeze({\n LOW: Object.freeze({ cadenceHz: 5, inputWidth: 128, animations: \"reduced\" as const }),\n MID: Object.freeze({ cadenceHz: 8, inputWidth: 160, animations: \"full\" as const }),\n HIGH: Object.freeze({ cadenceHz: 10, inputWidth: 192, animations: \"full\" as const }),\n });\n\nexport interface DeviceProbe {\n cores: number;\n /** null where the UA hides it — iOS Safari NEVER exposes deviceMemory\n * (field lesson: a 2GB default classified every iPhone LOW). Unknown is\n * treated as NEUTRAL (4GB): never demotes to LOW on its own, never\n * promotes to HIGH; the dynamic profiler corrects truly slow devices. */\n memGB: number | null;\n /** WebAssembly SIMD available (informs wasm-tier expectations/telemetry). */\n simd: boolean;\n}\n\n/** Canonical WASM SIMD feature-test module (validates only where SIMD is\n * supported) — the standard wasm-feature-detect bytes. */\nconst SIMD_TEST_BYTES = new Uint8Array([\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253,\n 15, 253, 98, 11,\n]);\n\nexport function probeDevice(): DeviceProbe {\n const nav = typeof navigator === \"undefined\" ? undefined : navigator;\n let simd = false;\n try {\n simd = typeof WebAssembly !== \"undefined\" && WebAssembly.validate(SIMD_TEST_BYTES);\n } catch {\n simd = false;\n }\n return {\n cores: nav?.hardwareConcurrency ?? 2,\n memGB: (nav as { deviceMemory?: number } | undefined)?.deviceMemory ?? null,\n simd,\n };\n}\n\n/** Static class: LOW (<4 cores or <3GB), HIGH (≥8 cores AND ≥6GB), else MID.\n * Unknown memory counts as a neutral 4GB (see DeviceProbe.memGB). */\nexport function classifyDevice(probe: DeviceProbe): DeviceClass {\n const memGB = probe.memGB ?? 4;\n if (probe.cores < 4 || memGB < 3) return \"LOW\";\n if (probe.cores >= 8 && memGB >= 6) return \"HIGH\";\n return \"MID\";\n}\n\nconst ORDER: DeviceClass[] = [\"LOW\", \"MID\", \"HIGH\"];\n\n/** Dynamic refinement: after the FIRST 10 measured detect ticks, a mean over\n * 70ms demotes straight to LOW; under 25ms promotes ONE class — at most one\n * adjustment ever (no oscillation). */\nexport class DeviceProfiler {\n private current: DeviceClass;\n private readonly samples: number[] = [];\n private adjusted = false;\n\n constructor(initial: DeviceClass) {\n this.current = initial;\n }\n\n get deviceClass(): DeviceClass {\n return this.current;\n }\n\n get profile(): DeviceProfile {\n return DEVICE_PROFILES[this.current];\n }\n\n record(detectMs: number): DeviceClass {\n if (this.adjusted || this.samples.length >= 10) return this.current;\n this.samples.push(detectMs);\n if (this.samples.length < 10) return this.current;\n this.adjusted = true;\n const mean = this.samples.reduce((sum, value) => sum + value, 0) / this.samples.length;\n if (mean > 70) {\n this.current = \"LOW\";\n } else if (mean < 25) {\n const index = ORDER.indexOf(this.current);\n this.current = ORDER[Math.min(ORDER.length - 1, index + 1)] ?? this.current;\n }\n return this.current;\n }\n}\n","// Detect scheduler (Task 9) — paces the detection pass at the profile's\n// cadence, preferring requestVideoFrameCallback (runs only when a REAL camera\n// frame arrived) with a plain interval fallback. A tick whose predecessor is\n// still in flight is SKIPPED — never queued (no backlog on a slow device) —\n// and counted as a degrade for telemetry.\n\nexport interface DetectSchedulerOptions {\n /** Ticks per second (profile cadenceHz). */\n cadenceHz: number;\n /** One detection pass — the scheduler awaits it and measures wall time. */\n run: () => Promise<void>;\n /** When provided AND it exposes requestVideoFrameCallback, ticks ride real\n * camera frames (throttled to the cadence) instead of a timer. */\n video?: HTMLVideoElement;\n /** Injectable clock (tests) — defaults to performance.now. */\n now?: () => number;\n}\n\ninterface VideoFrameCallbackTarget {\n requestVideoFrameCallback?: (callback: () => void) => number;\n cancelVideoFrameCallback?: (id: number) => void;\n}\n\n/** Rolling window for meanDetectMs. */\nconst STATS_WINDOW = 20;\n\nexport class DetectScheduler {\n private readonly options: DetectSchedulerOptions;\n private readonly periodMs: number;\n private timer: ReturnType<typeof setInterval> | null = null;\n private frameCallbackId: number | null = null;\n private running = false;\n private busy = false;\n private lastRunAt = Number.NEGATIVE_INFINITY;\n private degradeCount = 0;\n private readonly durations: number[] = [];\n\n constructor(options: DetectSchedulerOptions) {\n this.options = options;\n this.periodMs = 1000 / options.cadenceHz;\n }\n\n start(): void {\n if (this.running) return;\n this.running = true;\n const video = this.options.video as VideoFrameCallbackTarget | undefined;\n if (typeof video?.requestVideoFrameCallback === \"function\") {\n const loop = () => {\n if (!this.running) return;\n this.frameCallbackId = video.requestVideoFrameCallback?.(() => {\n this.frameCallbackId = null;\n // Throttle: camera frames arrive faster than the cadence.\n if (this.now() - this.lastRunAt >= this.periodMs) this.tick();\n loop();\n }) as number;\n };\n loop();\n return;\n }\n this.timer = setInterval(() => this.tick(), this.periodMs);\n }\n\n stop(): void {\n this.running = false;\n if (this.timer !== null) {\n clearInterval(this.timer);\n this.timer = null;\n }\n if (this.frameCallbackId !== null) {\n (this.options.video as VideoFrameCallbackTarget | undefined)?.cancelVideoFrameCallback?.(\n this.frameCallbackId,\n );\n this.frameCallbackId = null;\n }\n }\n\n stats(): { degradeCount: number; meanDetectMs: number } {\n const meanDetectMs =\n this.durations.length === 0\n ? 0\n : this.durations.reduce((sum, value) => sum + value, 0) / this.durations.length;\n return { degradeCount: this.degradeCount, meanDetectMs };\n }\n\n private now(): number {\n return this.options.now?.() ?? performance.now();\n }\n\n private tick(): void {\n if (!this.running) return;\n if (this.busy) {\n // Skip-when-busy: no queue growth on slow devices; telemetry counts it.\n this.degradeCount += 1;\n return;\n }\n this.busy = true;\n this.lastRunAt = this.now();\n const startedAt = this.now();\n this.options\n .run()\n .catch(() => undefined) // a failed pass must never kill the loop\n .finally(() => {\n this.busy = false;\n this.durations.push(this.now() - startedAt);\n if (this.durations.length > STATS_WINDOW) this.durations.shift();\n });\n }\n}\n","// Worker offload (Task 9) — detection off the main thread when the platform\n// allows (OffscreenCanvas + createImageBitmap + Worker). BOTH protocol sides\n// live in this file so the tiny versioned protocol (v:1) can never drift:\n// - installWorkerDetectorHost: runs INSIDE the worker (auto-installed when\n// this module loads in a DedicatedWorkerGlobalScope; tsup builds it as\n// its own entry so hosts can `new Worker(new URL(...))` the dist file);\n// - WorkerDetectorProxy: main-thread Detector implementation that posts\n// ImageBitmap frames as transferables and resolves results by id.\nimport {\n type CreateDetectorOptions,\n createDetector as defaultCreateDetector,\n type Detector,\n type FaceObservation,\n} from \"./detector\";\n\nexport const WORKER_PROTOCOL_VERSION = 1;\n\ninterface InitMessage {\n v: typeof WORKER_PROTOCOL_VERSION;\n type: \"init\";\n options: CreateDetectorOptions;\n}\ninterface DetectMessage {\n v: typeof WORKER_PROTOCOL_VERSION;\n type: \"detect\";\n id: number;\n bitmap: ImageBitmap;\n streamWidth: number;\n streamHeight: number;\n}\ninterface ReadyMessage {\n v: typeof WORKER_PROTOCOL_VERSION;\n type: \"ready\";\n tier: Detector[\"tier\"];\n fallbackReason?: string;\n}\ninterface ResultMessage {\n v: typeof WORKER_PROTOCOL_VERSION;\n type: \"result\";\n id: number;\n observation: FaceObservation | null;\n}\n\ntype ToWorker = InitMessage | DetectMessage;\ntype ToMain = ReadyMessage | ResultMessage;\n\n/** The slice of Worker/scope surface the protocol needs — test-stubbable. */\nexport interface WorkerScopeLike {\n onmessage: ((event: { data: unknown }) => void) | null;\n postMessage(data: unknown): void;\n}\nexport interface WorkerLike {\n postMessage(data: unknown, transfer?: Transferable[]): void;\n addEventListener(type: \"message\", listener: (event: { data: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (event: { data: unknown }) => void): void;\n terminate(): void;\n}\n\n/** Feature gate: bitmap capture + transfer + workers must all exist. */\nexport function workerOffloadSupported(): boolean {\n return (\n typeof OffscreenCanvas === \"function\" &&\n typeof createImageBitmap === \"function\" &&\n typeof Worker === \"function\"\n );\n}\n\n/** Worker-side message host. `deps.createDetector` is a test seam. */\nexport function installWorkerDetectorHost(\n scope: WorkerScopeLike,\n deps: { createDetector?: (options: CreateDetectorOptions) => Promise<Detector> } = {},\n): void {\n const create = deps.createDetector ?? defaultCreateDetector;\n let detector: Detector | null = null;\n scope.onmessage = (event) => {\n const message = event.data as ToWorker;\n if (message.v !== WORKER_PROTOCOL_VERSION) {\n // Ignore unknown versions — but never strand a transferred bitmap.\n (message as { bitmap?: { close?: () => void } }).bitmap?.close?.();\n return;\n }\n if (message.type === \"init\") {\n void create(message.options).then((created) => {\n detector = created;\n const ready: ReadyMessage = {\n v: WORKER_PROTOCOL_VERSION,\n type: \"ready\",\n tier: created.tier,\n ...(created.fallbackReason !== undefined\n ? { fallbackReason: created.fallbackReason }\n : {}),\n };\n scope.postMessage(ready);\n });\n return;\n }\n if (message.type === \"detect\") {\n const respond = (observation: FaceObservation | null) => {\n const result: ResultMessage = {\n v: WORKER_PROTOCOL_VERSION,\n type: \"result\",\n id: message.id,\n observation,\n };\n scope.postMessage(result);\n (message.bitmap as { close?: () => void }).close?.();\n };\n if (detector === null) {\n respond(null);\n return;\n }\n void detector\n .detect(message.bitmap, message.streamWidth, message.streamHeight)\n .then(respond, () => respond(null));\n }\n };\n}\n\n// Auto-install when this module IS the worker entry (DedicatedWorkerGlobalScope\n// has importScripts; window does not). Inert in main-thread bundles/tests.\ndeclare const self: (WorkerScopeLike & { importScripts?: unknown }) | undefined;\nif (typeof self !== \"undefined\" && typeof self.importScripts === \"function\") {\n installWorkerDetectorHost(self);\n}\n\n/** Main-side Detector over the worker protocol. Same interface as the\n * in-thread detectors — Task 10's engine cannot tell the difference. */\nexport class WorkerDetectorProxy implements Detector {\n readonly tier: Detector[\"tier\"];\n readonly fallbackReason?: string;\n private readonly worker: WorkerLike;\n private readonly pending = new Map<number, (observation: FaceObservation | null) => void>();\n private nextId = 1;\n\n private constructor(worker: WorkerLike, ready: ReadyMessage) {\n this.worker = worker;\n this.tier = ready.tier;\n if (ready.fallbackReason !== undefined) this.fallbackReason = ready.fallbackReason;\n worker.addEventListener(\"message\", (event) => {\n const message = event.data as ToMain;\n if (message.v !== WORKER_PROTOCOL_VERSION || message.type !== \"result\") return;\n const resolve = this.pending.get(message.id);\n this.pending.delete(message.id);\n resolve?.(message.observation);\n });\n }\n\n static create(\n worker: WorkerLike,\n options: CreateDetectorOptions,\n readyTimeoutMs = 10_000,\n ): Promise<WorkerDetectorProxy> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n worker.removeEventListener(\"message\", onReady);\n worker.terminate();\n reject(new Error(`worker detector not ready within ${readyTimeoutMs}ms`));\n }, readyTimeoutMs);\n const onReady = (event: { data: unknown }) => {\n const message = event.data as ToMain;\n if (message.v !== WORKER_PROTOCOL_VERSION || message.type !== \"ready\") return;\n clearTimeout(timer);\n worker.removeEventListener(\"message\", onReady);\n resolve(new WorkerDetectorProxy(worker, message));\n };\n worker.addEventListener(\"message\", onReady);\n const init: InitMessage = { v: WORKER_PROTOCOL_VERSION, type: \"init\", options };\n worker.postMessage(init);\n });\n }\n\n async detect(\n source: CanvasImageSource,\n sourceWidth: number,\n sourceHeight: number,\n ): Promise<FaceObservation | null> {\n // Only ImageBitmap is Transferable — convert other sources (video,\n // canvas) via createImageBitmap (the feature gate guarantees it). A\n // failed conversion yields null, never a DataCloneError.\n let bitmap: ImageBitmap;\n try {\n if (typeof ImageBitmap !== \"undefined\" && source instanceof ImageBitmap) {\n bitmap = source;\n } else if (typeof createImageBitmap === \"function\") {\n bitmap = await createImageBitmap(source as ImageBitmapSource);\n } else {\n // No conversion surface (stubbed environments) — trust the caller.\n bitmap = source as ImageBitmap;\n }\n } catch {\n return null;\n }\n const id = this.nextId;\n this.nextId += 1;\n return new Promise((resolve) => {\n this.pending.set(id, resolve);\n const message: DetectMessage = {\n v: WORKER_PROTOCOL_VERSION,\n type: \"detect\",\n id,\n bitmap,\n streamWidth: sourceWidth,\n streamHeight: sourceHeight,\n };\n this.worker.postMessage(message, [bitmap]);\n });\n }\n\n destroy(): void {\n // Settle in-flight detects (an awaiting scheduler run must not hang\n // busy=true forever) before tearing the worker down.\n for (const resolve of this.pending.values()) resolve(null);\n this.pending.clear();\n this.worker.terminate();\n }\n}\n","// CaptureSessionV3 (Task 10) — the v3 engine behind the v1 event surface\n// (`statechange | guidance | checks | artifacts | error`), plus ONE v3-only\n// chrome event (`frozen`, fired at recording-stop so the host can freeze the\n// display on the keyframe before the clip finalizes), so hosts bind it with\n// minimal changes. PARALLEL module: it REUSES v1's building blocks AS\n// IMPORTS — ClipRecorder (the 720p/2.5Mbps clip floor lives in ONE place),\n// captureMirroredKeyframe, buildCaptureConstraints, the camera error taxonomy\n// — and touches no v1 file.\n//\n// v3 deltas: detector LADDER (native → blaze; the face-api floor was dropped\n// 2026-07-09) on an adaptive scheduler with device profiles; FaceGateV3\n// (eye-midpoint, continuous\n// integrator); keyframe BEST-OF-N (sharpest of up to 4 candidates in the\n// first 600ms of the capture window); `checks` carries a v3 payload\n// discriminated on `engine: 'v3'` (no v1 counters).\n//\n// Supersession: retry()/switchCamera()/destroy() bump the attempt token —\n// in-flight async continuations from an old attempt observe the bump and\n// stop (the v1 pattern, ported; see capture-session.ts header).\nimport { buildCaptureConstraints, detectIsMobile } from \"../capture-constraints\";\nimport { ClipRecorder, type ClipResult } from \"../clip-recorder\";\nimport { captureMirroredKeyframe } from \"../keyframe\";\nimport { cameraPreflight, isClipTooLarge, mapGetUserMediaError } from \"../media\";\nimport type { CaptureArtifacts, CaptureErrorKind, CaptureState } from \"../types\";\nimport {\n createDetector as createLadderDetector,\n type Detector,\n DetectorLadderError,\n intrinsicSize,\n} from \"./detector\";\nimport { WorkerDetectorProxy, type WorkerLike, workerOffloadSupported } from \"./detect-worker\";\nimport {\n classifyDevice,\n type DeviceClass,\n DeviceProfiler,\n probeDevice,\n} from \"./device-profile\";\nimport { DetectScheduler } from \"./detect-scheduler\";\nimport {\n FaceGateV3,\n type V3GateFactor,\n type V3GateQuality,\n type V3GateThresholds,\n} from \"./face-gate-v3\";\nimport { exposure, meanLuma, sharpness } from \"./frame-quality\";\n\n/** Best-of-N keyframe window: up to 4 candidates over the first 600ms. */\nexport const KEYFRAME_CANDIDATES = 4;\nexport const KEYFRAME_WINDOW_MS = 600;\n\nexport interface V3ChecksPayload {\n engine: \"v3\";\n /** Gate integrator 0..1 — the ring drives off this directly. */\n progress: number;\n /** Instantaneous quality 0..1. */\n q: number;\n factors: Record<V3GateFactor, number>;\n /** Attempt ordinal (bumps on retry/switchCamera). */\n attempt: number;\n}\n\nexport interface CaptureSessionV3Events {\n statechange: { state: CaptureState };\n checks: V3ChecksPayload;\n /** fcv3.* message KEY — hosts translate; never prose. Deduped. */\n guidance: { key: string };\n artifacts: CaptureArtifacts;\n error: { kind: CaptureErrorKind; retryable: boolean };\n /** v3-only, CHROME-only (no data flows here): fires the instant the clip\n * recording window ends — BEFORE the blob finalizes (iOS onstop can lag up\n * to STOP_GRACE_MS). Carries the already-captured keyframe's JPEG data URL so\n * the host can freeze the display on the still immediately instead of leaving\n * the live feed running while the clip flushes. Clip mode only (photo mode\n * goes straight to `artifacts`). A host that ignores it is unaffected. */\n frozen: { previewDataUrl: string };\n}\n\nexport type V3TelemetryEvent =\n | { type: \"detector\"; tier: Detector[\"tier\"]; fallbackReason?: string }\n | { type: \"profile\"; staticClass: DeviceClass; activeClass: DeviceClass; simd: boolean }\n | { type: \"fired\"; timeToGateMs: number; degradeCount: number; meanDetectMs: number }\n | { type: \"error\"; kind: CaptureErrorKind; fallbackReason?: string };\n\ninterface KeyframeCandidate {\n blob: Blob;\n previewDataUrl: string;\n sharpness: number;\n}\n\n/** Challenge-clip artifact for the Phase 3 escalation path. */\nexport interface EscalationClipArtifact {\n clip: Blob;\n clipMimeType: string;\n}\n\n/** INERT Phase 3 seam (docs/superpowers/specs/2026-07-07-active-liveness-\n * escalation-spec.md): when the server settles a liveness verdict in the\n * REVIEW band it may mint ONE gesture challenge; the host then asks the\n * engine for a challenge clip through this hook. Typed and documented NOW so\n * capture-v3+ starts from a design — NEVER invoked anywhere in the current\n * flow (pinned by a test). */\nexport interface EscalationHook {\n onBorderline(challenge: \"blink\" | \"turn\"): Promise<EscalationClipArtifact>;\n}\n\nexport interface CaptureSessionV3Options {\n /** Host-owned <video playsInline muted> — same iOS contract as v1. */\n video: HTMLVideoElement;\n /** v3 assets base (tasks-vision wasm + tflite); default /models-v3. */\n v3AssetBaseUrl?: string;\n mode?: \"clip\" | \"photo\";\n /** FaceGateV3 threshold overrides (Phase 2 tuning). */\n thresholds?: Partial<V3GateThresholds>;\n telemetry?: (event: V3TelemetryEvent) => void;\n facingMode?: \"user\" | \"environment\";\n /** Static class override (tests / host pinning); default = boot probe. */\n deviceClass?: DeviceClass;\n // ── seams (production defaults in parens) ─────────────────────────────────\n /** (detector ladder) */\n createDetector?: () => Promise<Detector>;\n /** (fresh ClipRecorder per attempt) */\n createRecorder?: () => Pick<ClipRecorder, \"record\" | \"stop\">;\n /** (navigator.mediaDevices.getUserMedia) */\n getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;\n /** (mirrored canvas keyframe + downscaled Laplacian sharpness) */\n captureKeyframe?: (video: HTMLVideoElement) => Promise<KeyframeCandidate>;\n /** (downscaled face-crop sharpness/exposure via canvas) */\n measureQuality?: (\n video: HTMLVideoElement,\n box: { x: number; y: number; width: number; height: number },\n ) => V3GateQuality;\n /** (reused canvas at profile.inputWidth; falls back to the raw video where\n * canvas is unavailable) */\n makeSnapshot?: (video: HTMLVideoElement, targetWidth: number) => CanvasImageSource;\n /** Worker offload opt-in (Task 9): when provided AND the platform supports\n * it (OffscreenCanvas + createImageBitmap + Worker), detection runs\n * worker-side through WorkerDetectorProxy. Hosts own Worker construction\n * (bundler-specific `new Worker(new URL(...))`). */\n createWorker?: () => WorkerLike;\n /** INERT (Phase 3 escalation seam — see EscalationHook). Accepted and\n * retained, never called in Phases 1–2. */\n escalation?: EscalationHook;\n /** (performance.now) */\n now?: () => number;\n}\n\ntype Handler<K extends keyof CaptureSessionV3Events> = (\n payload: CaptureSessionV3Events[K],\n) => void;\n\nconst NEUTRAL_QUALITY: V3GateQuality = { sharpness: 1, exposure: 1, meanLuma: 128 };\n\nexport class CaptureSessionV3 {\n private readonly options: CaptureSessionV3Options;\n private readonly handlers = new Map<string, Set<(payload: never) => void>>();\n private stateValue: CaptureState = \"idle\";\n private attempt = 0;\n private facing: \"user\" | \"environment\";\n private stream: MediaStream | null = null;\n private detector: Detector | null = null;\n private scheduler: DetectScheduler | null = null;\n private gate: FaceGateV3 | null = null;\n private profiler: DeviceProfiler | null = null;\n private lastGuidanceKey: string | null = null;\n private positioningStartedAt = 0;\n private fired = false;\n private carriedDegrade = 0;\n private carriedMeans: number[] = [];\n\n constructor(options: CaptureSessionV3Options) {\n this.options = options;\n this.facing = options.facingMode ?? \"user\";\n }\n\n get state(): CaptureState {\n return this.stateValue;\n }\n\n on<K extends keyof CaptureSessionV3Events>(event: K, handler: Handler<K>): () => void {\n let set = this.handlers.get(event);\n if (!set) {\n set = new Set();\n this.handlers.set(event, set);\n }\n set.add(handler as (payload: never) => void);\n return () => set?.delete(handler as (payload: never) => void);\n }\n\n private emit<K extends keyof CaptureSessionV3Events>(\n event: K,\n payload: CaptureSessionV3Events[K],\n ): void {\n for (const handler of [...(this.handlers.get(event) ?? [])]) {\n (handler as Handler<K>)(payload);\n }\n }\n\n async start(): Promise<void> {\n this.attempt += 1;\n await this.run(this.attempt);\n }\n\n /** Full reset + camera restart — the documented recovery path (v1 parity). */\n retry(): void {\n this.teardownAttempt();\n void this.start();\n }\n\n switchCamera(): void {\n this.facing = this.facing === \"user\" ? \"environment\" : \"user\";\n this.teardownAttempt();\n void this.start();\n }\n\n destroy(): void {\n this.attempt += 1; // supersede in-flight continuations\n this.teardownAttempt();\n this.detector?.destroy();\n this.detector = null;\n this.options.video.srcObject = null;\n }\n\n // ── attempt lifecycle ──────────────────────────────────────────────────────\n\n private async run(attempt: number): Promise<void> {\n const { options } = this;\n this.fired = false;\n this.lastGuidanceKey = null;\n this.carriedDegrade = 0;\n this.carriedMeans = [];\n this.setState(\"preflight\");\n const preflight = cameraPreflight();\n if (preflight !== \"OK\") {\n this.fail(preflight === \"INSECURE_CONTEXT\" ? \"insecure\" : \"unsupported\");\n return;\n }\n\n this.setState(\"acquiring\");\n const getUserMedia =\n options.getUserMedia ??\n ((constraints: MediaStreamConstraints) => navigator.mediaDevices.getUserMedia(constraints));\n let stream: MediaStream;\n try {\n // The 720p/2.5Mbps floor: v1's constraint builder, imported — never forked.\n stream = await getUserMedia(buildCaptureConstraints(detectIsMobile(), this.facing));\n } catch (err) {\n if (attempt !== this.attempt) return;\n this.fail(mapGetUserMediaError(err));\n return;\n }\n if (attempt !== this.attempt) {\n for (const track of stream.getTracks()) track.stop();\n return;\n }\n this.stream = stream;\n options.video.srcObject = stream;\n await options.video.play().catch(() => undefined);\n // play() awaited — a retry/destroy may have superseded this attempt while\n // it was suspended; continuing would overwrite the LIVE attempt's\n // profiler/gate/scheduler with stale ones (review S2-2).\n if (attempt !== this.attempt) return;\n\n if (this.detector === null) {\n const ladderOptions = {\n ...(options.v3AssetBaseUrl !== undefined\n ? { v3AssetBaseUrl: options.v3AssetBaseUrl }\n : {}),\n };\n const create =\n options.createDetector ??\n (options.createWorker !== undefined && workerOffloadSupported()\n ? async () => {\n // Worker offload (Task 9): the ladder runs WORKER-side; a\n // failed/hung init falls back to the in-thread ladder.\n try {\n return await WorkerDetectorProxy.create(\n (options.createWorker as () => WorkerLike)(),\n ladderOptions,\n );\n } catch {\n return createLadderDetector(ladderOptions);\n }\n }\n : () => createLadderDetector(ladderOptions));\n let created: Detector;\n try {\n created = await create();\n } catch (err) {\n // With the face-api floor gone, the ladder REJECTS once exhausted\n // (DetectorLadderError) — and any throwing seam is likewise a models\n // failure. Surface a retryable error{kind:'models'} (never a hang),\n // carrying the per-tier reasons for telemetry so a blaze init failure\n // stays observable in the field.\n if (attempt === this.attempt) {\n this.fail(\n \"models\",\n err instanceof DetectorLadderError ? err.fallbackReason : describeError(err),\n );\n }\n return;\n }\n // Resolve into a LOCAL first: assigning a detector into a superseded\n // (or destroyed) session would leak it — destroy() already nulled the\n // field, and a racing attempt may have created its own (review S2-3).\n if (attempt !== this.attempt) {\n created.destroy();\n return;\n }\n this.detector = created;\n this.options.telemetry?.({\n type: \"detector\",\n tier: created.tier,\n ...(created.fallbackReason !== undefined\n ? { fallbackReason: created.fallbackReason }\n : {}),\n });\n }\n\n const probe = probeDevice();\n const staticClass = options.deviceClass ?? classifyDevice(probe);\n this.profiler = new DeviceProfiler(staticClass);\n this.options.telemetry?.({\n type: \"profile\",\n staticClass,\n activeClass: this.profiler.deviceClass,\n simd: probe.simd,\n });\n\n this.gate = new FaceGateV3(options.thresholds ?? {});\n this.setState(\"positioning\");\n this.positioningStartedAt = this.now();\n this.startScheduler(attempt);\n }\n\n /** Chrome hint (Task 11): 'reduced' on LOW even without the media query. */\n get animations(): \"full\" | \"reduced\" {\n return this.profiler?.profile.animations ?? \"full\";\n }\n\n private startScheduler(attempt: number): void {\n const profiler = this.profiler;\n if (profiler === null) return;\n if (this.scheduler !== null) {\n // A dynamic profile change replaces the scheduler — carry its stats so\n // the `fired` telemetry keeps the PRE-adjustment struggle visible.\n const stats = this.scheduler.stats();\n this.carriedDegrade += stats.degradeCount;\n if (stats.meanDetectMs > 0) this.carriedMeans.push(stats.meanDetectMs);\n this.scheduler.stop();\n }\n const scheduler = new DetectScheduler({\n cadenceHz: profiler.profile.cadenceHz,\n video: this.options.video,\n ...(this.options.now !== undefined ? { now: this.options.now } : {}),\n run: () => this.detectTick(attempt),\n });\n this.scheduler = scheduler;\n scheduler.start();\n }\n\n private async detectTick(attempt: number): Promise<void> {\n const { detector, gate, profiler } = this;\n const video = this.options.video;\n if (attempt !== this.attempt || detector === null || gate === null || profiler === null)\n return;\n if (this.fired || video.videoWidth === 0) return;\n\n const before = profiler.deviceClass;\n const t0 = this.now();\n // Profile-adaptive DOWNSCALE: the detector sees an inputWidth-wide\n // snapshot, never the full 720p frame (the profile system's perf win);\n // stream-px normalization scales the observation back up.\n const source =\n this.options.makeSnapshot?.(video, profiler.profile.inputWidth) ??\n this.defaultSnapshot(video, profiler.profile.inputWidth);\n let observation: Awaited<ReturnType<Detector[\"detect\"]>> = null;\n try {\n observation = await detector.detect(source, video.videoWidth, video.videoHeight);\n } catch {\n observation = null; // detectors never reject by contract; belt-and-braces\n }\n if (attempt !== this.attempt || this.fired) return;\n profiler.record(this.now() - t0);\n if (profiler.deviceClass !== before) this.startScheduler(attempt); // cadence follows the class\n\n const quality =\n observation === null\n ? NEUTRAL_QUALITY\n : (this.options.measureQuality?.(video, observation.box) ??\n this.defaultQuality(video, observation.box));\n\n const tick = gate.tick({\n timestampMs: this.now(),\n observation,\n quality,\n frameWidth: video.videoWidth,\n frameHeight: video.videoHeight,\n });\n this.emit(\"checks\", {\n engine: \"v3\",\n progress: tick.p,\n q: tick.q,\n factors: tick.factors,\n attempt,\n });\n if (tick.guidanceKey !== this.lastGuidanceKey) {\n this.lastGuidanceKey = tick.guidanceKey;\n this.emit(\"guidance\", { key: tick.guidanceKey });\n }\n if (tick.ready && this.stateValue === \"positioning\") {\n this.fired = true;\n void this.fire(attempt);\n }\n }\n\n private async fire(attempt: number): Promise<void> {\n const { options } = this;\n const scheduler = this.scheduler;\n scheduler?.stop();\n const stats = scheduler?.stats() ?? { degradeCount: 0, meanDetectMs: 0 };\n const means = [...this.carriedMeans, ...(stats.meanDetectMs > 0 ? [stats.meanDetectMs] : [])];\n options.telemetry?.({\n type: \"fired\",\n timeToGateMs: this.now() - this.positioningStartedAt,\n degradeCount: this.carriedDegrade + stats.degradeCount,\n meanDetectMs:\n means.length === 0 ? 0 : means.reduce((sum, value) => sum + value, 0) / means.length,\n });\n\n const mode = options.mode ?? \"clip\";\n const bestOf = this.collectKeyframes(attempt);\n if (mode === \"photo\") {\n const best = await bestOf;\n if (attempt !== this.attempt) return;\n if (best === null) {\n this.fail(\"generic\");\n return;\n }\n this.finishCapture({ keyframe: best.blob, previewDataUrl: best.previewDataUrl });\n return;\n }\n\n this.setState(\"recording\");\n const recorder = options.createRecorder?.() ?? new ClipRecorder();\n const stream = this.stream;\n if (stream === null) {\n this.fail(\"generic\");\n return;\n }\n // The keyframe (the face_match selfie) resolves within the first 600ms —\n // well before the 2.5s clip ends. Latch it so the recording-STOP callback\n // below can emit `frozen` immediately, letting the host freeze the display\n // on the still without waiting for the clip blob to finalize (iOS lag).\n let frozenBest: KeyframeCandidate | null = null;\n void bestOf.then(\n (candidate) => {\n frozenBest = candidate;\n },\n () => {},\n );\n const onRecordingStopped = (): void => {\n if (attempt !== this.attempt) return; // superseded (retry/switch/destroy)\n if (frozenBest !== null) {\n this.emit(\"frozen\", { previewDataUrl: frozenBest.previewDataUrl });\n }\n };\n let clip: ClipResult;\n let best: KeyframeCandidate | null;\n try {\n [clip, best] = await Promise.all([recorder.record(stream, onRecordingStopped), bestOf]);\n } catch (err) {\n if (attempt !== this.attempt) return;\n const kind = (err as { kind?: CaptureErrorKind }).kind;\n this.fail(kind === \"cliptoolarge\" ? \"cliptoolarge\" : \"recorder\");\n return;\n }\n if (attempt !== this.attempt) return;\n if (isClipTooLarge(clip.blob)) {\n this.fail(\"cliptoolarge\");\n return;\n }\n if (best === null) {\n this.fail(\"generic\");\n return;\n }\n this.finishCapture({\n clip: clip.blob,\n clipMimeType: clip.mimeType,\n keyframe: best.blob,\n previewDataUrl: best.previewDataUrl,\n });\n }\n\n /** Up to KEYFRAME_CANDIDATES mirrored frames over KEYFRAME_WINDOW_MS —\n * sharpest wins (reuses frame-quality.sharpness via the capture seam). */\n private async collectKeyframes(attempt: number): Promise<KeyframeCandidate | null> {\n const capture = this.options.captureKeyframe ?? ((video) => this.defaultKeyframe(video));\n const stepMs = KEYFRAME_WINDOW_MS / (KEYFRAME_CANDIDATES - 1);\n let best: KeyframeCandidate | null = null;\n for (let i = 0; i < KEYFRAME_CANDIDATES; i += 1) {\n if (attempt !== this.attempt) return best;\n try {\n const candidate = await capture(this.options.video);\n if (best === null || candidate.sharpness > best.sharpness) best = candidate;\n } catch {\n // a failed candidate never sinks the capture — keep the best so far\n }\n if (i < KEYFRAME_CANDIDATES - 1) await delay(stepMs);\n }\n return best;\n }\n\n private finishCapture(artifacts: CaptureArtifacts): void {\n this.stopTracks(); // privacy posture: camera off the moment we have artifacts\n this.setState(\"captured\");\n this.emit(\"artifacts\", artifacts);\n }\n\n // ── defaults for the canvas-bound seams ────────────────────────────────────\n\n private async defaultKeyframe(video: HTMLVideoElement): Promise<KeyframeCandidate> {\n const canvas = document.createElement(\"canvas\");\n const blob = await captureMirroredKeyframe(video, canvas);\n const previewDataUrl = canvas.toDataURL(\"image/jpeg\", 0.92);\n return { blob, previewDataUrl, sharpness: this.centerSharpness(video) };\n }\n\n /** Reused downscale canvas — falls back to the raw video where canvas 2D\n * is unavailable (jsdom) so tests and exotic hosts keep detecting. */\n private snapshotCanvas: HTMLCanvasElement | null = null;\n private defaultSnapshot(video: HTMLVideoElement, targetWidth: number): CanvasImageSource {\n try {\n const canvas = this.snapshotCanvas ?? document.createElement(\"canvas\");\n const scale = targetWidth / Math.max(1, video.videoWidth);\n const width = Math.max(1, Math.round(video.videoWidth * scale));\n const height = Math.max(1, Math.round(video.videoHeight * scale));\n const ctx = canvas.getContext(\"2d\");\n if (ctx === null) return video;\n if (canvas.width !== width) canvas.width = width;\n if (canvas.height !== height) canvas.height = height;\n ctx.drawImage(video, 0, 0, width, height);\n this.snapshotCanvas = canvas;\n return canvas;\n } catch {\n return video;\n }\n }\n\n private defaultQuality(\n video: HTMLVideoElement,\n box: { x: number; y: number; width: number; height: number },\n ): V3GateQuality {\n const crop = cropImageData(video, box, 96);\n if (crop === null) return NEUTRAL_QUALITY;\n return { sharpness: sharpness(crop), exposure: exposure(crop), meanLuma: meanLuma(crop) };\n }\n\n private centerSharpness(video: HTMLVideoElement): number {\n const size = intrinsicSize(video);\n const crop = cropImageData(\n video,\n { x: size.width * 0.25, y: size.height * 0.25, width: size.width * 0.5, height: size.height * 0.5 },\n 96,\n );\n return crop === null ? 0 : sharpness(crop);\n }\n\n // ── teardown ──────────────────────────────────────────────────────────────\n\n private teardownAttempt(): void {\n // No token bump here: retry()/switchCamera() call start() synchronously\n // right after, and START's own bump supersedes; destroy() bumps itself.\n this.scheduler?.stop();\n this.scheduler = null;\n this.gate = null;\n this.stopTracks();\n }\n\n private stopTracks(): void {\n if (this.stream === null) return;\n for (const track of this.stream.getTracks()) track.stop();\n this.stream = null;\n }\n\n private fail(kind: CaptureErrorKind, fallbackReason?: string): void {\n this.scheduler?.stop();\n this.stopTracks();\n this.setState(\"error\");\n this.options.telemetry?.({\n type: \"error\",\n kind,\n ...(fallbackReason !== undefined ? { fallbackReason } : {}),\n });\n // v1 canRetry semantics (capture-session.ts L424).\n this.emit(\"error\", { kind, retryable: kind !== \"insecure\" && kind !== \"unsupported\" });\n }\n\n private setState(state: CaptureState): void {\n this.stateValue = state;\n this.emit(\"statechange\", { state });\n }\n\n private now(): number {\n return this.options.now?.() ?? performance.now();\n }\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction describeError(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Downscaled face-crop ImageData for the quality measures; null where canvas\n * is unavailable (jsdom) — callers fall back to neutral quality. */\nfunction cropImageData(\n video: HTMLVideoElement,\n box: { x: number; y: number; width: number; height: number },\n targetWidth: number,\n): ImageData | null {\n try {\n const canvas = document.createElement(\"canvas\");\n const scale = targetWidth / Math.max(1, box.width);\n canvas.width = Math.max(1, Math.round(box.width * scale));\n canvas.height = Math.max(1, Math.round(box.height * scale));\n const ctx = canvas.getContext(\"2d\");\n if (ctx === null) return null;\n ctx.drawImage(\n video,\n box.x,\n box.y,\n box.width,\n box.height,\n 0,\n 0,\n canvas.width,\n canvas.height,\n );\n return ctx.getImageData(0, 0, canvas.width, canvas.height);\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAYO,SAAS,eAAuB;AACrC,QAAM,KAAM,WACT;AACH,MAAI,CAAC,MAAM,OAAO,GAAG,oBAAoB,WAAY,QAAO;AAC5D,SAAO,gBAAgB,KAAK,CAAC,MAAM,GAAG,gBAAiB,CAAC,CAAC,KAAK;AAChE;AAIO,IAAM,oBAAoB;AAI1B,SAAS,qBAAqB,KAA+B;AAClE,MAAI,eAAe,UAAW,QAAO;AACrC,QAAM,OAAQ,KAA2B,QAAQ;AACjD,UAAQ,MAAM;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAEO,SAAS,kBAA6D;AAC3E,QAAM,IAAI;AACV,MAAI,OAAO,EAAE,WAAW,eAAe,EAAE,OAAO,oBAAoB;AAClE,WAAO;AACT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