@camstack/addon-post-analysis 1.2.278 → 1.2.280

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.
@@ -2,7 +2,7 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
- const require_dist = require("../dist-BUtk8EU2.js");
5
+ const require_dist = require("../dist-VeiAavYR.js");
6
6
  let node_fs = require("node:fs");
7
7
  node_fs = require_dist.__toESM(node_fs, 1);
8
8
  let node_path = require("node:path");
@@ -5620,8 +5620,8 @@ async function raceTimeout(call, timeoutMs) {
5620
5620
  * detail the encoder can see.
5621
5621
  */
5622
5622
  async function downscaleJpeg(bytes, maxPx) {
5623
- const { default: sharp$17 } = await import("sharp");
5624
- const out = await sharp$17(Buffer.from(bytes)).resize({
5623
+ const { default: sharp$18 } = await import("sharp");
5624
+ const out = await sharp$18(Buffer.from(bytes)).resize({
5625
5625
  width: maxPx,
5626
5626
  height: maxPx,
5627
5627
  fit: "inside",
@@ -9547,15 +9547,20 @@ function readSensorEventType(value) {
9547
9547
  const eventType = last["eventType"];
9548
9548
  return typeof eventType === "string" && eventType.length > 0 ? eventType : void 0;
9549
9549
  }
9550
+ /** A LINKED SET subject (ADR 0632) — see {@link NcRuleSubject.linkedSensorId}. */
9551
+ function isLinkedSetSubject(subject) {
9552
+ return subject.linkedSensorId !== void 0;
9553
+ }
9550
9554
  /**
9551
9555
  * Build the subject for a `device-event` evaluation (a persisted SensorEvent —
9552
- * one row per linked camera; `deviceId` is the CAMERA).
9556
+ * one row per linked camera; `deviceId` is the CAMERA), or, with `linked`, the
9557
+ * ONE sensor-level evaluation of a linked set.
9553
9558
  *
9554
9559
  * BOTH ids ride along. The camera is what the notification shows; the sensor is
9555
9560
  * what the operator named in the rule. Carrying only the camera is what made a
9556
9561
  * sensor-scoped rule unmatched — see {@link NcRuleSubject.sourceDeviceId}.
9557
9562
  */
9558
- function subjectFromSensorEvent(ev, markerTrackId) {
9563
+ function subjectFromSensorEvent(ev, markerTrackId, linked) {
9559
9564
  const eventType = readSensorEventType(ev.value);
9560
9565
  const sensorEdge = sensorEdgeOf(ev.kind, ev.value);
9561
9566
  return {
@@ -9570,7 +9575,14 @@ function subjectFromSensorEvent(ev, markerTrackId) {
9570
9575
  source: "sensor",
9571
9576
  sensorKind: ev.kind,
9572
9577
  ...eventType !== void 0 ? { eventType } : {},
9573
- ...sensorEdge !== void 0 ? { sensorEdge } : {}
9578
+ ...sensorEdge !== void 0 ? { sensorEdge } : {},
9579
+ ...linked !== void 0 ? {
9580
+ linkedSensorId: ev.sourceDeviceId,
9581
+ linkedCameraIds: [...linked.linkedCameraIds],
9582
+ rowCameraIds: [...linked.rowCameraIds],
9583
+ mutedRowCameraIds: [...linked.mutedRowCameraIds]
9584
+ } : {},
9585
+ ...linked?.linkedStills !== void 0 ? { linkedStills: linked.linkedStills } : {}
9574
9586
  };
9575
9587
  }
9576
9588
  /**
@@ -9892,6 +9904,21 @@ function zonesVisitedBy(subject) {
9892
9904
  if (subject.crossing !== void 0) visited.add(subject.crossing.zoneId);
9893
9905
  return visited;
9894
9906
  }
9907
+ /**
9908
+ * Could this `device-event` rule fire on a sensor change of `sensorKind`?
9909
+ * The SAME two refusals {@link evaluateRule} makes before anything else a
9910
+ * sensor subject is judged on — an `occupancy` condition (such a rule targets
9911
+ * only occupancy edges, which ride the same delivery) and a `sensorKinds` list
9912
+ * that excludes the kind — for a caller that must decide from the rules alone,
9913
+ * before the subject exists (the linked-camera capture gate). Coarse in one
9914
+ * direction only: `true` may still fail later; `false` never would have fired.
9915
+ */
9916
+ function deviceEventRuleMayFireOnKind(rule, sensorKind) {
9917
+ const c = rule.conditions;
9918
+ if (c.occupancy !== void 0) return false;
9919
+ if (c.sensorKinds === void 0 || c.sensorKinds.length === 0) return true;
9920
+ return toLowerSet(c.sensorKinds).has(sensorKind.trim().toLowerCase());
9921
+ }
9895
9922
  function toLowerSet(values) {
9896
9923
  return new Set(values.map((v) => v.trim().toLowerCase()));
9897
9924
  }
@@ -10292,13 +10319,17 @@ function systemEventCooldownScope(systemEvent) {
10292
10319
  * the operator actually cares about and the one they pick in the Devices
10293
10320
  * tab. Before this, that rule matched nothing, ever, silently.
10294
10321
  *
10295
- * Consequence worth knowing: a sensor linked to N cameras persists N rows, so
10296
- * a SENSOR-scoped rule is evaluated N times for one door opening. The rule's
10297
- * own throttle is what collapses that — `scope: 'rule'` gives one
10298
- * notification, `scope: 'device'` gives one per camera, which is the right
10299
- * choice when each carries its own picture.
10322
+ * A sensor linked to MORE than one camera is evaluated once, at the sensor
10323
+ * level (ADR 0632), with `deviceId` = the primary camera. That evaluation
10324
+ * matches the SENSOR and the cameras that took a timeline row for it
10325
+ * (`rowCameraIds`) — exactly the rules the per-camera rows would have matched
10326
+ * (D630 §6). The primary is only the camera the notification leads with: one
10327
+ * that links the sensor without opting it in keeps its rules silent, and an
10328
+ * opted-in camera that is not the primary still fires its own. The other
10329
+ * linked cameras ride `linkedCameraIds` for the MEDIA only.
10300
10330
  */
10301
10331
  function matchesDeviceScope(scope, subject) {
10332
+ if (subject.linkedSensorId !== void 0) return scope.includes(subject.linkedSensorId) || (subject.rowCameraIds ?? []).some((cameraId) => scope.includes(cameraId));
10302
10333
  if (scope.includes(subject.deviceId)) return true;
10303
10334
  return subject.sourceDeviceId !== void 0 && scope.includes(subject.sourceDeviceId);
10304
10335
  }
@@ -10521,23 +10552,34 @@ function incomingFromTrack(track, info) {
10521
10552
  };
10522
10553
  }
10523
10554
  /**
10524
- * Sensor-event persist (one row per linked camera).
10555
+ * Sensor-event persist (one row per linked camera), or — with `linked` — the
10556
+ * ONE sensor-level evaluation of a sensor linked to several cameras (ADR 0632),
10557
+ * whose `event.deviceId` is the primary camera.
10525
10558
  *
10526
10559
  * `markerTrackId` is the synthetic marker track the same state change
10527
10560
  * projected onto this camera — the notification's media owner, and the only
10528
10561
  * frame a device event has. Absent when no marker landed.
10562
+ *
10563
+ * A sensor-level evaluation is a per-EVENT line, so it is tagged with the
10564
+ * SENSOR; the primary camera rides in the meta. `mutedCameraIds` are the
10565
+ * linked cameras the centre left out (D62) — for the line's counts only.
10529
10566
  */
10530
- function incomingFromSensorEvent(event, markerTrackId) {
10567
+ function incomingFromSensorEvent(event, markerTrackId, linked, mutedCameraIds = []) {
10531
10568
  return {
10532
- subject: subjectFromSensorEvent(event, markerTrackId),
10569
+ subject: subjectFromSensorEvent(event, markerTrackId, linked),
10533
10570
  kind: "device-event",
10534
10571
  origin: "sensor",
10535
10572
  log: () => ({
10536
- tags: { deviceId: event.deviceId },
10573
+ tags: { deviceId: linked !== void 0 ? event.sourceDeviceId : event.deviceId },
10537
10574
  meta: {
10538
10575
  sensorEventId: event.id,
10539
10576
  kind: event.kind,
10540
- ...markerTrackId !== void 0 ? { trackId: markerTrackId } : {}
10577
+ ...markerTrackId !== void 0 ? { trackId: markerTrackId } : {},
10578
+ ...linked !== void 0 ? {
10579
+ ...event.deviceId !== event.sourceDeviceId ? { primaryCameraId: event.deviceId } : {},
10580
+ linkedCameras: linked.linkedCameraIds.length + mutedCameraIds.length,
10581
+ mutedCameras: mutedCameraIds.length
10582
+ } : {}
10541
10583
  }
10542
10584
  })
10543
10585
  };
@@ -14774,8 +14816,8 @@ async function deriveSyntheticMedia(jpeg, bbox, timestamp) {
14774
14816
  ];
14775
14817
  if (bbox === void 0) return files;
14776
14818
  try {
14777
- const { default: sharp$16 } = await import("sharp");
14778
- const meta = await sharp$16(Buffer.from(jpeg)).metadata();
14819
+ const { default: sharp$17 } = await import("sharp");
14820
+ const meta = await sharp$17(Buffer.from(jpeg)).metadata();
14779
14821
  const W = meta.width ?? 0;
14780
14822
  const H = meta.height ?? 0;
14781
14823
  if (W === 0 || H === 0) return files;
@@ -14783,7 +14825,7 @@ async function deriveSyntheticMedia(jpeg, bbox, timestamp) {
14783
14825
  const top = Math.max(0, Math.min(H - 1, Math.floor(bbox.y * H)));
14784
14826
  const width = Math.max(1, Math.min(W - left, Math.ceil(bbox.w * W)));
14785
14827
  const height = Math.max(1, Math.min(H - top, Math.ceil(bbox.h * H)));
14786
- const cropBuf = await sharp$16(Buffer.from(jpeg)).extract({
14828
+ const cropBuf = await sharp$17(Buffer.from(jpeg)).extract({
14787
14829
  left,
14788
14830
  top,
14789
14831
  width,
@@ -14805,7 +14847,7 @@ async function deriveSyntheticMedia(jpeg, bbox, timestamp) {
14805
14847
  });
14806
14848
  const stroke = Math.max(2, Math.round(Math.min(W, H) / 240));
14807
14849
  const overlay = Buffer.from(`<svg width="${W}" height="${H}"><rect x="${left}" y="${top}" width="${width}" height="${height}" fill="none" stroke="#22d3ee" stroke-width="${stroke}"/></svg>`);
14808
- const boxedBuf = await sharp$16(Buffer.from(jpeg)).composite([{
14850
+ const boxedBuf = await sharp$17(Buffer.from(jpeg)).composite([{
14809
14851
  input: overlay,
14810
14852
  top: 0,
14811
14853
  left: 0
@@ -17004,7 +17046,8 @@ var NcDispatcher = class {
17004
17046
  const analyse = this.deps.ruleAi;
17005
17047
  const policy = entry.payload.ai;
17006
17048
  if (analyse === void 0 || policy === void 0) return null;
17007
- const frames = policy.shape === "detection-track" ? await this.trackNarrationFrames(entry) : shippedFrames(built.notification);
17049
+ const tiles = policy.shape === "detection-track" ? [] : await this.linkedAnalysisFrames(entry);
17050
+ const frames = policy.shape === "detection-track" ? await this.trackNarrationFrames(entry) : tiles.length > 0 ? tiles : shippedFrames(built.notification);
17008
17051
  if (frames.length === 0) {
17009
17052
  this.deps.logger.debug("notification AI skipped — no picture to describe", {
17010
17053
  tags: { deviceId: entry.deviceId },
@@ -17045,6 +17088,43 @@ var NcDispatcher = class {
17045
17088
  return null;
17046
17089
  }
17047
17090
  }
17091
+ /** A linked set's raw per-camera tiles (`subject.analysisTiles`), in
17092
+ * camera order — one frame per camera whose picture landed. Best-effort: an
17093
+ * owner that answers nothing or throws is left out (a blank frame is never
17094
+ * handed to a model), and no owners at all is `[]`. */
17095
+ async linkedAnalysisFrames(entry) {
17096
+ const tiles = entry.payload.subject.analysisTiles ?? [];
17097
+ const frames = [];
17098
+ for (const { ownerId, cameraId } of tiles) {
17099
+ const file = await this.linkedStillFile(entry, ownerId, cameraId);
17100
+ const bytes = file === void 0 ? null : decodeStillBytes(file.base64);
17101
+ if (bytes !== null) frames.push({
17102
+ bytes,
17103
+ mime: "image/jpeg"
17104
+ });
17105
+ }
17106
+ return frames;
17107
+ }
17108
+ /** One linked-camera shelf owner's still — `keyFrameSmall`, else whatever it
17109
+ * holds. `undefined` when it holds nothing or the read throws (said at DEBUG
17110
+ * on `cameraId`, the camera the picture is of: the caller decides whether
17111
+ * the absence is worth a line of its own). */
17112
+ async linkedStillFile(entry, ownerId, cameraId) {
17113
+ try {
17114
+ const files = await this.deps.getMediaForOwner("track", ownerId);
17115
+ return files.find((f) => f.kind === "keyFrameSmall") ?? files[0];
17116
+ } catch (err) {
17117
+ this.deps.logger.debug("linked camera picture read failed", {
17118
+ tags: { deviceId: cameraId },
17119
+ meta: {
17120
+ recordId: entry.recordId,
17121
+ ownerId,
17122
+ error: String(err)
17123
+ }
17124
+ });
17125
+ return;
17126
+ }
17127
+ }
17048
17128
  /** The whole-scene frames spanning a CLOSED track, oldest first. Best-effort
17049
17129
  * in every direction: no track id, a throwing read or an empty store all
17050
17130
  * leave the pass with nothing, which skips it. */
@@ -17053,11 +17133,8 @@ var NcDispatcher = class {
17053
17133
  if (trackId === void 0) return [];
17054
17134
  try {
17055
17135
  return pickTrackNarrationFrames(await this.deps.getMediaForOwner("track", trackId), 3).flatMap((file) => {
17056
- const raw = Buffer.from(file.base64, "base64");
17057
- if (raw.byteLength === 0) return [];
17058
- const bytes = new Uint8Array(raw.byteLength);
17059
- bytes.set(raw);
17060
- return [{
17136
+ const bytes = decodeStillBytes(file.base64);
17137
+ return bytes === null ? [] : [{
17061
17138
  bytes,
17062
17139
  mime: "image/jpeg",
17063
17140
  atMs: file.timestamp
@@ -17505,7 +17582,7 @@ var NcDispatcher = class {
17505
17582
  const deviceId = entry.payload.subject.deviceId;
17506
17583
  const common = {
17507
17584
  deviceId: deviceId > 0 ? deviceId : null,
17508
- deviceIds: deviceId > 0 ? [deviceId] : [],
17585
+ deviceIds: entry.payload.subject.linkedCameraIds !== void 0 ? [...entry.payload.subject.linkedCameraIds] : deviceId > 0 ? [deviceId] : [],
17509
17586
  capturedAt: entry.payload.subject.timestamp,
17510
17587
  ruleId: entry.ruleId,
17511
17588
  ruleName: entry.payload.ruleName
@@ -17553,6 +17630,7 @@ var NcDispatcher = class {
17553
17630
  const footagePending = this.renderFootage(entry);
17554
17631
  const still = firstLook !== null || entry.payload.media === "none" ? firstLook : await this.waitForStill(entry, stillOverride);
17555
17632
  const footage = await footagePending;
17633
+ const extras = await this.linkedExtraStills(entry);
17556
17634
  if (still !== null) {
17557
17635
  const zoneIds = zoneIdsWanted;
17558
17636
  if (zoneIds !== void 0 && zoneIds.length > 0) {
@@ -17570,7 +17648,17 @@ var NcDispatcher = class {
17570
17648
  name: "group.jpg"
17571
17649
  } : still);
17572
17650
  }
17573
- } else if (entry.payload.media !== "none") this.deps.logger.info("no still could be resolved — this notification ships text-only", {
17651
+ } else if (entry.payload.media !== "none" && extras.length > 0) this.deps.logger.info("no still of the primary camera could be resolved — the other linked cameras' stills ship without it", {
17652
+ tags: { deviceId: entry.payload.subject.deviceId },
17653
+ meta: {
17654
+ recordKind: entry.recordKind,
17655
+ recordId: entry.recordId,
17656
+ policy: entry.payload.media,
17657
+ ...entry.payload.subject.trackId !== void 0 ? { owner: `track:${entry.payload.subject.trackId}` } : {},
17658
+ otherCameras: extras.length
17659
+ }
17660
+ });
17661
+ else if (entry.payload.media !== "none") this.deps.logger.info("no still could be resolved — this notification ships text-only", {
17574
17662
  tags: { deviceId: entry.payload.subject.deviceId },
17575
17663
  meta: {
17576
17664
  recordKind: entry.recordKind,
@@ -17581,6 +17669,43 @@ var NcDispatcher = class {
17581
17669
  }
17582
17670
  });
17583
17671
  out.push(...footage.attachments);
17672
+ out.push(...extras);
17673
+ return out;
17674
+ }
17675
+ /**
17676
+ * `each` (ADR 0632): the OTHER linked cameras' stills, in camera order —
17677
+ * AFTER the primary still and the primary's footage, so a target with little
17678
+ * room keeps both and the other cameras fill only what is left (the degrade
17679
+ * engine drops by position). A camera whose picture never landed is skipped
17680
+ * and named ON THAT CAMERA: a blank attachment would read as a broken camera.
17681
+ * The camera is the one the row CARRIES with each still (the one the shelf
17682
+ * photographed) — never inferred from a position in `linkedCameraIds`, which
17683
+ * a mute between capture and evaluation shifts. Named `camera-<id>.jpg`.
17684
+ */
17685
+ async linkedExtraStills(entry) {
17686
+ const subject = entry.payload.subject;
17687
+ const out = [];
17688
+ for (const { ownerId, cameraId } of subject.extraStills ?? []) {
17689
+ const file = await this.linkedStillFile(entry, ownerId, cameraId);
17690
+ const bytes = file === void 0 ? null : decodeStillBytes(file.base64);
17691
+ if (bytes === null) {
17692
+ this.deps.logger.info("linked camera picture missing at send — skipped", {
17693
+ tags: { deviceId: cameraId },
17694
+ meta: {
17695
+ recordId: entry.recordId,
17696
+ ruleId: entry.ruleId,
17697
+ ownerId
17698
+ }
17699
+ });
17700
+ continue;
17701
+ }
17702
+ out.push({
17703
+ mediaType: "image",
17704
+ bytes,
17705
+ mime: "image/jpeg",
17706
+ name: `camera-${String(cameraId)}.jpg`
17707
+ });
17708
+ }
17584
17709
  return out;
17585
17710
  }
17586
17711
  /**
@@ -17857,8 +17982,8 @@ var NcDispatcher = class {
17857
17982
  try {
17858
17983
  const points = (await this.deps.getZonePolygons?.(deviceId, zoneIds) ?? []).flat();
17859
17984
  if (points.length === 0) return null;
17860
- const { default: sharp$15 } = await import("sharp");
17861
- const img = sharp$15(Buffer.from(jpeg));
17985
+ const { default: sharp$16 } = await import("sharp");
17986
+ const img = sharp$16(Buffer.from(jpeg));
17862
17987
  const meta = await img.metadata();
17863
17988
  const W = meta.width ?? 0;
17864
17989
  const H = meta.height ?? 0;
@@ -18059,10 +18184,8 @@ var NcDispatcher = class {
18059
18184
  const shortlist = await this.narrowToTriggerZone(entry, inBand, freshness);
18060
18185
  if (shortlist.length === 0) continue;
18061
18186
  for (const file of shortlist) {
18062
- const raw = Buffer.from(file.base64, "base64");
18063
- if (raw.byteLength === 0) continue;
18064
- const bytes = new Uint8Array(raw.byteLength);
18065
- bytes.set(raw);
18187
+ const bytes = decodeStillBytes(file.base64);
18188
+ if (bytes === null) continue;
18066
18189
  return {
18067
18190
  mediaType: "image",
18068
18191
  bytes,
@@ -18295,6 +18418,18 @@ function copyBytes(bytes) {
18295
18418
  out.set(bytes);
18296
18419
  return out;
18297
18420
  }
18421
+ /**
18422
+ * A stored file's base64 as bytes backed by their OWN `ArrayBuffer`, or `null`
18423
+ * when it decodes to nothing (a blank picture is never a picture).
18424
+ *
18425
+ * The copy is the point: a pooled `Buffer` view throws `Trying to deserialize
18426
+ * unknown typed array` on the far side of a transport, and the attachment and
18427
+ * frame types both demand `Uint8Array<ArrayBuffer>`.
18428
+ */
18429
+ function decodeStillBytes(base64) {
18430
+ const raw = Buffer.from(base64, "base64");
18431
+ return raw.byteLength === 0 ? null : copyBytes(raw);
18432
+ }
18298
18433
  /** Does this rule ever cut footage from the broker's clip ring? */
18299
18434
  function wantsFootage(rule) {
18300
18435
  return rule.media.gif === true || rule.media.clip === true;
@@ -20131,6 +20266,916 @@ var DeviceLivenessHoldoff = class {
20131
20266
  }
20132
20267
  };
20133
20268
  //#endregion
20269
+ //#region src/notification-center/linked-camera-media.ts
20270
+ /** ADR 0632: absent = mosaic, applied HERE and never as a Zod default. */
20271
+ function linkedCameraMode(media) {
20272
+ return media.linkedCameras ?? "mosaic";
20273
+ }
20274
+ /** Which shelf owners one RULE's row names. The model always gets the raw tiles
20275
+ * (like the digest, D154) — a composite is a worse input than its parts. */
20276
+ function linkedMediaOwners(stills, mode) {
20277
+ const tiles = stills.cameraOwnerIds.flatMap((ownerId, i) => {
20278
+ const cameraId = stills.cameraIds[i];
20279
+ return cameraId === void 0 ? [] : [{
20280
+ ownerId,
20281
+ cameraId
20282
+ }];
20283
+ });
20284
+ const [primary] = stills.cameraOwnerIds;
20285
+ if (mode === "each" && primary !== void 0) return {
20286
+ trackId: primary,
20287
+ extraStills: tiles.slice(1),
20288
+ analysisTiles: tiles
20289
+ };
20290
+ return {
20291
+ trackId: stills.mosaicOwnerId,
20292
+ extraStills: [],
20293
+ analysisTiles: tiles
20294
+ };
20295
+ }
20296
+ /** JPEG quality for the downscaled full frame — matches the crop path. */
20297
+ var FULL_FRAME_QUALITY = 80;
20298
+ /**
20299
+ * Downscale an already-encoded JPEG full frame to FIT WITHIN
20300
+ * {@link FULL_FRAME_MAX_WIDTH}×{@link FULL_FRAME_MAX_HEIGHT}, preserving aspect
20301
+ * ratio (`fit: 'inside'`) and never enlarging a source already smaller than the
20302
+ * box. Re-encodes as JPEG. Used before persisting a synthetic sensor/control
20303
+ * track's whole-scene snapshot so a raw native-resolution frame (a 4K bedroom
20304
+ * at night) is never stored or served — the privacy fix moved to CAPTURE time.
20305
+ */
20306
+ async function downscaleFullFrameJpeg(jpeg, maxWidth = 640, maxHeight = 360) {
20307
+ return (0, sharp.default)(Buffer.from(jpeg)).resize(maxWidth, maxHeight, {
20308
+ fit: "inside",
20309
+ withoutEnlargement: true
20310
+ }).jpeg({ quality: FULL_FRAME_QUALITY }).toBuffer();
20311
+ }
20312
+ //#endregion
20313
+ //#region src/notification-center/still-shelf.ts
20314
+ /**
20315
+ * The still shelf — the PHOTOGRAPH a notification carries when nothing it can
20316
+ * name owns a frame.
20317
+ *
20318
+ * ## Why a trigger needs one at all
20319
+ *
20320
+ * The attachment ladder resolves media by OWNER, and most triggers have one: an
20321
+ * object or package event owns its crops, a closed track owns its best shot, a
20322
+ * doorbell press owns the marker track the same press projected
20323
+ * (`sensor-marker-projector.ts`), an occupancy edge names one of the objects it
20324
+ * counted (`chooseOccupancyMediaOwner`). Two triggers own nothing, and for the
20325
+ * same reason in both cases — the subject is an ABSENCE:
20326
+ *
20327
+ * - an **audio** match: nothing was boxed, nothing was tracked, and —
20328
+ * deliberately — nothing is persisted at all. A confirmed window is a claim
20329
+ * about sound that has already stopped, and `event-intake.ts` states why
20330
+ * replaying it later would be wrong.
20331
+ * - an **occupancy** edge whose scope is EMPTY — "posto libero". The vehicle
20332
+ * whose departure IS the news has left, so `chooseOccupancyMediaOwner` names
20333
+ * nobody and the ladder logs `no still could be resolved … owners=[]`.
20334
+ *
20335
+ * So the only honest picture is a PHOTOGRAPH of the camera taken at the moment
20336
+ * of the trigger. Not of the sound, not of the object that left — of what the
20337
+ * camera can see now that it happened. For a freed parking space that is
20338
+ * exactly the answer the operator wants: the space, empty.
20339
+ *
20340
+ * **One shelf, not two.** The mechanism is identical down to the reuse window,
20341
+ * and the only thing that differs between the two triggers is the GATE deciding
20342
+ * that a photograph is owed at all — which belongs at the trigger site, where
20343
+ * the rules are, and not here. A twin module would be a second derivation of
20344
+ * one thing. The trigger rides along as {@link NcStillTrigger} only so the logs
20345
+ * can say which absence they are about.
20346
+ *
20347
+ * ## Three properties, and each one is a decision
20348
+ *
20349
+ * **It is not a record.** The bytes live here, in RAM, under an owner id and a
20350
+ * TTL that covers the outbox's whole retry horizon — and nowhere else. The
20351
+ * alternative was the doorbell's: materialise a synthetic marker track through
20352
+ * `SyntheticTrackMaterializer` and let the notification name it. That would put
20353
+ * a durable Track on the camera's timeline for every confirmed window and every
20354
+ * emptied zone, feeding the digest's `listTracks`, retention, and the audio-
20355
+ * marker feature's own operator ceilings (`audio-marker-projector.ts` exists
20356
+ * precisely to bound how many audio markers a camera may emit). A notification
20357
+ * must not manufacture timeline history as a side effect of wanting a picture.
20358
+ *
20359
+ * **The capture STARTS immediately and is never awaited.** The subject is
20360
+ * transient — a scream is over before a snapshot round-trip completes, and a
20361
+ * freed space is about to be taken by the next car — so the fetch is kicked off
20362
+ * at the trigger, before the rule evaluation runs, and the owner id is minted
20363
+ * synchronously so the outbox row can name it. The bytes land while the row
20364
+ * waits in the queue, and the dispatcher's existing bounded still-wait (or the
20365
+ * pause its own footage render already costs) picks them up. A camera that
20366
+ * never answers costs the picture and never the notification.
20367
+ *
20368
+ * **Two triggers seconds apart share ONE capture.** A barking dog confirms
20369
+ * repeatedly and a label-mode rule has no re-arm timer at all (D157) — the
20370
+ * rule's cooldown is its only brake, and the cooldown is applied AFTER this.
20371
+ * Without a reuse window this would photograph a camera at whatever rate the
20372
+ * sound happens to occur. Each trigger still gets its OWN owner id, so two
20373
+ * outbox rows are never mistaken for one subject; they merely point at the same
20374
+ * frame, which is the truth — the scene did not change in ten seconds. The
20375
+ * window is per CAMERA and trigger-agnostic for the same reason: a sound and an
20376
+ * emptied zone ten seconds apart are two claims about one scene.
20377
+ *
20378
+ * Nothing here is silent: a capture that lands and a camera that refuses each
20379
+ * emit one line carrying `tags: { deviceId }`, because "why did 617 get a photo
20380
+ * and 615 not" is the only form that question is ever asked in.
20381
+ */
20382
+ /**
20383
+ * The owner-id namespace. It is what routes a lookup here instead of to the
20384
+ * media store, and it is the reason the dispatcher needs no audio or occupancy
20385
+ * branch — `getMediaForOwner` answers for all of them under one signature.
20386
+ */
20387
+ var NC_STILL_SHELF_PREFIX = "nc-still:";
20388
+ /** True for an owner id this shelf minted. */
20389
+ function isStillShelfId(id) {
20390
+ return id.startsWith(NC_STILL_SHELF_PREFIX);
20391
+ }
20392
+ /**
20393
+ * How long the bytes are held.
20394
+ *
20395
+ * The outbox retries 8 times with a 5 s → 300 s backoff, which tops out around
20396
+ * ten minutes; fifteen covers that with room for a slow drain. Past it the row
20397
+ * ships text-only, which is the correct degradation for a photograph of a scene
20398
+ * that is a quarter of an hour stale anyway.
20399
+ */
20400
+ var NC_STILL_SHELF_TTL_MS = 15 * 6e4;
20401
+ /** A hanging snapshot cap must not pin a capture slot forever. */
20402
+ var SNAPSHOT_TIMEOUT_MS = 8e3;
20403
+ /**
20404
+ * Hard bound on held captures. Reached only if every camera on the hub triggers
20405
+ * one inside a single TTL; the oldest is dropped first, which costs a
20406
+ * fifteen-minute-old picture nobody is waiting for.
20407
+ */
20408
+ var MAX_CAPTURES = 64;
20409
+ var NcStillShelf = class {
20410
+ deps;
20411
+ /** captureId → the photograph. */
20412
+ captures = /* @__PURE__ */ new Map();
20413
+ /** ownerId → captureId. Several owners may name one capture (the reuse window). */
20414
+ owners = /* @__PURE__ */ new Map();
20415
+ /** deviceId → its newest capture, for the reuse window. */
20416
+ newest = /* @__PURE__ */ new Map();
20417
+ constructor(deps) {
20418
+ this.deps = deps;
20419
+ }
20420
+ /**
20421
+ * Photograph `deviceId` for a trigger at `atMs`, and return the owner id the
20422
+ * subject should name. SYNCHRONOUS by contract: the caller is on the trigger
20423
+ * path and the outbox row is built from what this returns.
20424
+ */
20425
+ capture(deviceId, atMs, trigger) {
20426
+ const now = this.deps.now();
20427
+ this.prune(now);
20428
+ const ownerId = `${NC_STILL_SHELF_PREFIX}${(0, node_crypto.randomUUID)()}`;
20429
+ const recent = this.newest.get(deviceId);
20430
+ if (recent !== void 0 && now - recent.at < 1e4 && this.captures.has(recent.captureId)) {
20431
+ this.owners.set(ownerId, recent.captureId);
20432
+ return ownerId;
20433
+ }
20434
+ const captureId = (0, node_crypto.randomUUID)();
20435
+ this.captures.set(captureId, {
20436
+ deviceId,
20437
+ trigger,
20438
+ startedAt: now,
20439
+ expiresAt: now + NC_STILL_SHELF_TTL_MS,
20440
+ files: []
20441
+ });
20442
+ this.newest.set(deviceId, {
20443
+ captureId,
20444
+ at: now
20445
+ });
20446
+ this.owners.set(ownerId, captureId);
20447
+ this.fetch(captureId, deviceId, atMs, trigger);
20448
+ return ownerId;
20449
+ }
20450
+ /**
20451
+ * The media an owner id holds, or `undefined` when this shelf never minted
20452
+ * it. An EMPTY array is a different answer: the capture exists and has not
20453
+ * landed (or never will), which is exactly the case the dispatcher's bounded
20454
+ * wait and its `no still could be resolved` line are for.
20455
+ */
20456
+ get(ownerId) {
20457
+ const captureId = this.owners.get(ownerId);
20458
+ if (captureId === void 0) return void 0;
20459
+ return this.captures.get(captureId)?.files ?? [];
20460
+ }
20461
+ /** Drop expired captures and the owners that named them. */
20462
+ prune(now) {
20463
+ for (const [captureId, held] of this.captures) {
20464
+ if (held.expiresAt > now) continue;
20465
+ this.captures.delete(captureId);
20466
+ if (this.newest.get(held.deviceId)?.captureId === captureId) this.newest.delete(held.deviceId);
20467
+ }
20468
+ while (this.captures.size > MAX_CAPTURES) {
20469
+ const oldest = this.captures.keys().next();
20470
+ if (oldest.done === true) break;
20471
+ const held = this.captures.get(oldest.value);
20472
+ this.captures.delete(oldest.value);
20473
+ if (held !== void 0 && this.newest.get(held.deviceId)?.captureId === oldest.value) this.newest.delete(held.deviceId);
20474
+ }
20475
+ for (const [ownerId, captureId] of this.owners) if (!this.captures.has(captureId)) this.owners.delete(ownerId);
20476
+ }
20477
+ /** Drop everything (shutdown). */
20478
+ clear() {
20479
+ this.captures.clear();
20480
+ this.owners.clear();
20481
+ this.newest.clear();
20482
+ }
20483
+ async fetch(captureId, deviceId, atMs, trigger) {
20484
+ try {
20485
+ const shot = await withTimeout$4(this.deps.getSnapshot(deviceId), SNAPSHOT_TIMEOUT_MS);
20486
+ if (shot === null || shot.base64.length === 0) {
20487
+ this.reportMiss(deviceId, trigger, "the camera returned no snapshot");
20488
+ return;
20489
+ }
20490
+ const raw = Buffer.from(shot.base64, "base64");
20491
+ let data = raw;
20492
+ try {
20493
+ data = await downscaleFullFrameJpeg(raw, 960, 540);
20494
+ } catch {}
20495
+ const held = this.captures.get(captureId);
20496
+ if (held === void 0) return;
20497
+ this.captures.set(captureId, {
20498
+ ...held,
20499
+ files: stillShelfMedia(data, atMs)
20500
+ });
20501
+ this.deps.logger.info(`${trigger} still captured`, {
20502
+ tags: { deviceId },
20503
+ meta: {
20504
+ trigger,
20505
+ bytes: data.byteLength,
20506
+ tookMs: this.deps.now() - held.startedAt
20507
+ }
20508
+ });
20509
+ } catch (err) {
20510
+ this.reportMiss(deviceId, trigger, err instanceof Error ? err.message : String(err));
20511
+ }
20512
+ }
20513
+ /**
20514
+ * A branch that drops work says so. This one costs the operator the picture
20515
+ * on a notification they DID receive, so it is a warn and it carries the
20516
+ * camera — the only key the question is ever asked with.
20517
+ */
20518
+ reportMiss(deviceId, trigger, reason) {
20519
+ this.deps.logger.warn(`the camera did not answer the ${trigger} still — this notification ships text-only`, {
20520
+ tags: { deviceId },
20521
+ meta: {
20522
+ trigger,
20523
+ reason
20524
+ }
20525
+ });
20526
+ }
20527
+ };
20528
+ /**
20529
+ * The photograph, in the three kinds the CLEAN-SCENE ladders ask for.
20530
+ *
20531
+ * `keyFrameSmall` leads because it is the first rung of both `attach: 'best'`
20532
+ * and `attach: 'keyFrame'` on a track owner; `keyFrame` and `fullFrame` answer
20533
+ * `frame: 'full'` and `frame: 'boxed'`'s honest degrade. There is deliberately
20534
+ * no `crop` / `thumbnail`: nothing was boxed, so `frame: 'cropped'` resolves
20535
+ * NOTHING and the notification ships text-only with the ordinary line saying
20536
+ * so. Inventing a centre crop would answer a different question from the one
20537
+ * the operator asked.
20538
+ */
20539
+ function stillShelfMedia(data, timestamp) {
20540
+ const base64 = data.toString("base64");
20541
+ const file = (kind) => ({
20542
+ mediaId: nextUnstoredMediaId(),
20543
+ kind,
20544
+ base64,
20545
+ sizeBytes: data.byteLength,
20546
+ timestamp
20547
+ });
20548
+ return [
20549
+ file("keyFrameSmall"),
20550
+ file("keyFrame"),
20551
+ file("fullFrame")
20552
+ ];
20553
+ }
20554
+ /** Reject if `promise` does not settle within `ms`. */
20555
+ function withTimeout$4(promise, ms) {
20556
+ return new Promise((resolve, reject) => {
20557
+ const timer = setTimeout(() => {
20558
+ reject(/* @__PURE__ */ new Error(`snapshot cap timed out after ${String(ms)}ms`));
20559
+ }, ms);
20560
+ promise.then((value) => {
20561
+ clearTimeout(timer);
20562
+ resolve(value);
20563
+ }, (err) => {
20564
+ clearTimeout(timer);
20565
+ reject(err instanceof Error ? err : new Error(String(err)));
20566
+ });
20567
+ });
20568
+ }
20569
+ /** The canvas behind a tile whose aspect does not fill its cell. */
20570
+ var MOSAIC_BACKGROUND = {
20571
+ r: 17,
20572
+ g: 17,
20573
+ b: 17
20574
+ };
20575
+ /** Tile aspect — cameras are 16:9 and a square cell would letterbox every one. */
20576
+ var TILE_ASPECT = 9 / 16;
20577
+ /** Height of the per-tile label strip, as a fraction of the tile height. */
20578
+ var LABEL_BAND_FRACTION = .14;
20579
+ var LABEL_MIN_PX = 11;
20580
+ /** Height of the mosaic's own title band, as a fraction of a tile's height. */
20581
+ var TITLE_BAND_FRACTION = .22;
20582
+ var TITLE_MIN_PX = 16;
20583
+ /**
20584
+ * Average glyph width as a fraction of the font size, for bold sans-serif.
20585
+ *
20586
+ * An ESTIMATE, and it has to be: librsvg lays the text out long after this
20587
+ * string is written, so there are no metrics to measure against. The same
20588
+ * number and the same reasoning as `preview-frame.ts#fitTitle` — deliberately
20589
+ * GENEROUS, because a label that shrank slightly more than it had to is
20590
+ * invisible and one that overflowed runs into the tile beside it. The first
20591
+ * live mosaic did exactly that: `Videocamera cortile · 07:49 · animal` was cut
20592
+ * to `…· anima` at the tile edge, mid-word.
20593
+ */
20594
+ var GLYPH_ADVANCE = .56;
20595
+ /** Fraction of the band a label may occupy, leaving the padding either side. */
20596
+ var LABEL_USABLE_FRACTION = .94;
20597
+ /** `<`, `>`, `&`, `'`, `"` in a camera name or an operator caption would each
20598
+ * turn the overlay into a document librsvg refuses. */
20599
+ function escapeXml$1(s) {
20600
+ return s.replace(/[<>&'"]/g, (ch) => {
20601
+ switch (ch) {
20602
+ case "<": return "&lt;";
20603
+ case ">": return "&gt;";
20604
+ case "&": return "&amp;";
20605
+ case "'": return "&apos;";
20606
+ default: return "&quot;";
20607
+ }
20608
+ });
20609
+ }
20610
+ /**
20611
+ * The single decision about drawn text — and the home of the DEFAULT.
20612
+ *
20613
+ * `undefined` means `none`, not `all`: a rule stored before this option existed
20614
+ * has no `captions` key, and the operator's request is that such a rule deliver
20615
+ * pictures. The schema materialises the same default on read
20616
+ * (`NcSummaryRuleInputSchema`), so this arm only fires for a caller that never
20617
+ * had a rule — the test bridge and the spec. Both agreeing is the point.
20618
+ */
20619
+ function mosaicTextPlan(captions) {
20620
+ if (captions === "all") return {
20621
+ tileLabels: true,
20622
+ titleBand: true
20623
+ };
20624
+ if (captions === "tiles") return {
20625
+ tileLabels: true,
20626
+ titleBand: false
20627
+ };
20628
+ return {
20629
+ tileLabels: false,
20630
+ titleBand: false
20631
+ };
20632
+ }
20633
+ /** Grid shape for `n` tiles: as square as possible, rows never exceeding cols
20634
+ * by more than one — a 3×3 for nine, a 3×2 for five, never a 1×9 strip.
20635
+ *
20636
+ * `rows` is the load-bearing half — it is how many rows {@link mosaicRowCounts}
20637
+ * distributes into. `cols` describes the WIDEST row, and is no longer a cell
20638
+ * count: see {@link mosaicRowCounts} for why a `cols × rows` grid was the bug. */
20639
+ function mosaicGrid(n) {
20640
+ const count = Math.max(1, Math.floor(n));
20641
+ const cols = Math.ceil(Math.sqrt(count));
20642
+ return {
20643
+ cols,
20644
+ rows: Math.ceil(count / cols)
20645
+ };
20646
+ }
20647
+ /**
20648
+ * How many tiles each ROW carries, top to bottom — and the reason the mosaic
20649
+ * can no longer have a hole in it.
20650
+ *
20651
+ * The layout used to be a `cols × rows` GRID, and a grid holds more cells than
20652
+ * tiles for every count that is not a perfect fit: 3 into a 2×2, 5 into a 3×2,
20653
+ * 7 and 8 into a 3×3. The composite only ever wrote the tiles, so the spare
20654
+ * cells stayed the canvas — `MOSAIC_BACKGROUND`, rgb 17 — and the operator's
20655
+ * three-tile digest was a quarter black. Measured on the shipped renderer:
20656
+ * 24.8% of a three-tile mosaic was background. His words: *"se ci sono 3
20657
+ * elementi non dovrebbe renderizzare buchi neri"*.
20658
+ *
20659
+ * Counting ROWS instead removes the failure by construction rather than by
20660
+ * patching it. Every row spans the full width and divides it among the tiles it
20661
+ * actually has, so a row is full whatever the remainder and there is no such
20662
+ * thing as a spare cell. The shapes fall out of it, and they are the ones asked
20663
+ * for: 1 ⇒ full frame, 2 ⇒ side by side, 3 ⇒ one big over two small, 4 ⇒ 2×2.
20664
+ *
20665
+ * **The fewer-tiled row comes FIRST.** Tiles arrive in the selection's order,
20666
+ * so row 0 is the head of the ranking; putting the remainder at the top would
20667
+ * make the WORST tile the big one.
20668
+ *
20669
+ * Every cell keeps {@link TILE_ASPECT}, so rows differ in height — which is
20670
+ * also what stops the letterbox: a full-width hero tile is 16:9 exactly, not a
20671
+ * 16:9 picture centred in a double-height cell with bars over and under it.
20672
+ */
20673
+ function mosaicRowCounts(n) {
20674
+ const count = Math.max(1, Math.floor(n));
20675
+ const { rows } = mosaicGrid(count);
20676
+ const base = Math.floor(count / rows);
20677
+ const remainder = count % rows;
20678
+ const counts = [];
20679
+ for (let row = 0; row < rows; row += 1) counts.push(row < rows - remainder ? base : base + 1);
20680
+ return counts;
20681
+ }
20682
+ /**
20683
+ * Where every tile lands. Pure — no bytes, no sharp, no clock.
20684
+ *
20685
+ * Exported because the rectangles are DATA the artefact should carry: a viewer
20686
+ * that wants a tappable mosaic reads these rather than re-deriving a layout
20687
+ * that could drift from the one actually rendered.
20688
+ *
20689
+ * The rectangles COVER the picture area exactly — that is the property the
20690
+ * spec asserts, and it is the one the old grid broke.
20691
+ */
20692
+ function mosaicLayout(input) {
20693
+ const rowCounts = mosaicRowCounts(input.tileCount);
20694
+ const width = Math.max(1, Math.floor(input.maxWidth ?? 1920));
20695
+ const firstRowCount = rowCounts[0] ?? 1;
20696
+ const tileWidth = Math.floor(width / firstRowCount);
20697
+ const tileHeight = Math.round(tileWidth * TILE_ASPECT);
20698
+ const titleHeight = input.withTitle === true ? Math.round(tileHeight * TITLE_BAND_FRACTION) : 0;
20699
+ const tiles = [];
20700
+ let y = titleHeight;
20701
+ let index = 0;
20702
+ for (const count of rowCounts) {
20703
+ const nominalWidth = Math.floor(width / count);
20704
+ const rowHeight = Math.round(nominalWidth * TILE_ASPECT);
20705
+ let x = 0;
20706
+ for (let inRow = 0; inRow < count; inRow += 1) {
20707
+ const w = inRow === count - 1 ? width - x : nominalWidth;
20708
+ tiles.push({
20709
+ index,
20710
+ x,
20711
+ y,
20712
+ w,
20713
+ h: rowHeight
20714
+ });
20715
+ x += w;
20716
+ index += 1;
20717
+ }
20718
+ y += rowHeight;
20719
+ }
20720
+ return {
20721
+ width,
20722
+ height: y,
20723
+ cols: Math.max(...rowCounts),
20724
+ rows: rowCounts.length,
20725
+ rowCounts,
20726
+ tileWidth,
20727
+ tileHeight,
20728
+ titleHeight,
20729
+ tiles
20730
+ };
20731
+ }
20732
+ /**
20733
+ * Shrink, then ELIDE, until the line fits `usablePx`.
20734
+ *
20735
+ * Shrinking is tried first because a slightly smaller label still says
20736
+ * everything; only past `minPx` is the tail cut, and then with an ellipsis so
20737
+ * the reader can SEE that something was cut. The failure this replaces was
20738
+ * silent: SVG simply clips at the viewport, so an overlong label lost its last
20739
+ * word mid-glyph and looked like a rendering bug rather than a truncation.
20740
+ *
20741
+ * Pure and exported so the arithmetic is testable without rendering a pixel.
20742
+ */
20743
+ function fitLine(text, usablePx, basePx, minPx) {
20744
+ const flat = text.trim().replace(/\s+/g, " ");
20745
+ const fits = (s, fontPx) => s.length * fontPx * GLYPH_ADVANCE <= usablePx;
20746
+ let fontPx = Math.max(minPx, Math.round(basePx));
20747
+ while (fontPx > minPx && !fits(flat, fontPx)) fontPx = Math.max(minPx, fontPx - 1);
20748
+ if (fits(flat, fontPx)) return {
20749
+ text: flat,
20750
+ fontPx
20751
+ };
20752
+ const budget = Math.max(1, Math.floor(usablePx / (fontPx * GLYPH_ADVANCE)));
20753
+ return {
20754
+ text: `${flat.slice(0, Math.max(1, budget - 1)).trimEnd()}…`,
20755
+ fontPx
20756
+ };
20757
+ }
20758
+ /** The label strip drawn across the bottom of one tile. */
20759
+ function tileLabelSvg(width, height, label) {
20760
+ const bandHeight = Math.max(18, Math.round(height * LABEL_BAND_FRACTION));
20761
+ const basePx = Math.round(bandHeight * .62);
20762
+ const padding = Math.round(basePx * .6);
20763
+ const fitted = fitLine(label, width * LABEL_USABLE_FRACTION - padding, basePx, LABEL_MIN_PX);
20764
+ const baseline = height - Math.round((bandHeight - fitted.fontPx) / 2) - Math.round(fitted.fontPx * .18);
20765
+ return Buffer.from(`<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
20766
+ <rect x="0" y="${height - bandHeight}" width="${width}" height="${bandHeight}" fill="black" fill-opacity="0.55"/>
20767
+ <text x="${padding}" y="${baseline}" font-size="${fitted.fontPx}" font-family="sans-serif" font-weight="bold" fill="white">${escapeXml$1(fitted.text)}</text>
20768
+ </svg>`);
20769
+ }
20770
+ /** The mosaic's own title band. */
20771
+ function titleSvg(width, height, caption) {
20772
+ const fitted = fitLine(caption, width * LABEL_USABLE_FRACTION, Math.round(height * .5), TITLE_MIN_PX);
20773
+ const baseline = Math.round(height / 2 + fitted.fontPx * .36);
20774
+ return Buffer.from(`<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
20775
+ <rect x="0" y="0" width="${width}" height="${height}" fill="#111111"/>
20776
+ <text x="${Math.round(width / 2)}" y="${baseline}" font-size="${fitted.fontPx}" font-family="sans-serif" font-weight="bold" text-anchor="middle" fill="white">${escapeXml$1(fitted.text)}</text>
20777
+ </svg>`);
20778
+ }
20779
+ /**
20780
+ * Compose the mosaic.
20781
+ *
20782
+ * Every tile is fitted with `contain` onto the cell background rather than
20783
+ * cropped: a `cover` fit would silently cut the subject out of a portrait crop,
20784
+ * and a tile that does not show what it is about is worse than a letterboxed
20785
+ * one.
20786
+ *
20787
+ * A tile sharp cannot read is DROPPED and counted, never composited as a blank
20788
+ * cell — a black square in a digest reads as "the camera saw nothing", which is
20789
+ * the opposite of what happened. The layout is computed from the SURVIVORS, and
20790
+ * because {@link mosaicRowCounts} counts rows rather than grid cells there is no
20791
+ * remainder to leave empty either.
20792
+ *
20793
+ * @throws when every tile was dropped, and when sharp cannot produce the final
20794
+ * canvas at all; the caller treats both as "no mosaic" and still
20795
+ * delivers the counts.
20796
+ */
20797
+ async function renderMosaic(request, logger) {
20798
+ const plan = mosaicTextPlan(request.captions);
20799
+ const usable = [];
20800
+ for (const tile of request.tiles) try {
20801
+ await (0, sharp.default)(tile.jpeg).metadata();
20802
+ usable.push(tile);
20803
+ } catch (err) {
20804
+ logger.warn(`${request.purpose} mosaic: a tile could not be decoded and was dropped`, {
20805
+ tags: { deviceId: tile.deviceId },
20806
+ meta: {
20807
+ ...request.purpose === "summary" ? { trackId: tile.sourceId } : { sourceId: tile.sourceId },
20808
+ error: String(err)
20809
+ }
20810
+ });
20811
+ }
20812
+ const droppedTiles = request.tiles.length - usable.length;
20813
+ if (usable.length === 0) throw new Error(`${request.purpose} mosaic: no tile could be decoded (${request.tiles.length} offered)`);
20814
+ const caption = plan.titleBand ? request.caption?.trim() ?? "" : "";
20815
+ const layout = mosaicLayout({
20816
+ tileCount: usable.length,
20817
+ ...request.maxWidth !== void 0 ? { maxWidth: request.maxWidth } : {},
20818
+ withTitle: caption.length > 0
20819
+ });
20820
+ const composites = await Promise.all(usable.map(async (tile, index) => {
20821
+ const rect = layout.tiles[index];
20822
+ if (rect === void 0) throw new Error(`${request.purpose} mosaic: layout lost a tile`);
20823
+ const label = plan.tileLabels ? tile.label?.trim() ?? "" : "";
20824
+ const fitted = (0, sharp.default)(tile.jpeg).resize({
20825
+ width: rect.w,
20826
+ height: rect.h,
20827
+ fit: "contain",
20828
+ background: MOSAIC_BACKGROUND
20829
+ });
20830
+ return {
20831
+ input: await (label.length === 0 ? fitted : fitted.composite([{
20832
+ input: tileLabelSvg(rect.w, rect.h, label),
20833
+ top: 0,
20834
+ left: 0
20835
+ }])).jpeg({ quality: 82 }).toBuffer(),
20836
+ top: rect.y,
20837
+ left: rect.x
20838
+ };
20839
+ }));
20840
+ if (caption.length > 0 && layout.titleHeight > 0) composites.unshift({
20841
+ input: titleSvg(layout.width, layout.titleHeight, caption),
20842
+ top: 0,
20843
+ left: 0
20844
+ });
20845
+ return {
20846
+ jpeg: await (0, sharp.default)({ create: {
20847
+ width: layout.width,
20848
+ height: layout.height,
20849
+ channels: 3,
20850
+ background: MOSAIC_BACKGROUND
20851
+ } }).composite(composites).jpeg({ quality: 82 }).toBuffer(),
20852
+ layout,
20853
+ droppedTiles
20854
+ };
20855
+ }
20856
+ //#endregion
20857
+ //#region src/notification-center/linked-stills.ts
20858
+ /**
20859
+ * The linked-camera shelf — the photographs a SENSOR notification carries of
20860
+ * every camera that links the sensor (ADR 0632).
20861
+ *
20862
+ * Same three properties as the still shelf (`still-shelf.ts`), for the same
20863
+ * reasons: not a record (RAM, TTL, no timeline track), the capture starts at the
20864
+ * trigger and is never awaited (owner ids minted synchronously), and nothing is
20865
+ * silent (one line per camera with its outcome, one per event on the sensor).
20866
+ * A separate module because the unit is a SET: exclusion, freshness and the
20867
+ * one composition are decisions about the set, and none of them belongs in a
20868
+ * shelf that photographs one camera for an absence.
20869
+ *
20870
+ * Two reads can only ever ADD a camera back, never take one away on their own
20871
+ * failure (D49): a wrapper-state read (run in parallel with the capture) that
20872
+ * misses or throws keeps the tile, and a freshness read that misses or throws
20873
+ * keeps every tile. Only a read that ANSWERED
20874
+ * `sleeping` / `disabled` / … or a capture time older than
20875
+ * {@link SENSOR_LINKED_MAX_FRAME_AGE_MS} removes a tile — and says so, on that
20876
+ * camera.
20877
+ */
20878
+ var NC_LINKED_MOSAIC_PREFIX = "nc-mosaic:";
20879
+ var NC_LINKED_CAMERA_PREFIX = "nc-linked:";
20880
+ function isLinkedStillId(id) {
20881
+ return id.startsWith("nc-mosaic:") || id.startsWith("nc-linked:");
20882
+ }
20883
+ /** Per camera — the marker's own bound (`SENSOR_MARKER_SNAPSHOT_TIMEOUT_MS`). */
20884
+ var SENSOR_LINKED_CAPTURE_TIMEOUT_MS = 2500;
20885
+ /** The capture-free wrapper-state read, per camera. It runs IN PARALLEL with
20886
+ * the capture and under the capture's own bound, so it costs no extra time and
20887
+ * a slow-but-honest answer is still heard: a blocking reason EXCLUDES the tile
20888
+ * even when the capture returned bytes (they are a state card, not a
20889
+ * photograph). A read that misses the bound or fails is UNKNOWN and keeps the
20890
+ * tile (D49). */
20891
+ var SENSOR_LINKED_STATE_READ_TIMEOUT_MS = SENSOR_LINKED_CAPTURE_TIMEOUT_MS;
20892
+ Math.max(SENSOR_LINKED_STATE_READ_TIMEOUT_MS, SENSOR_LINKED_CAPTURE_TIMEOUT_MS) + 400;
20893
+ /** Hard bound on sets held at once, on top of the TTL. */
20894
+ var MAX_SETS = 32;
20895
+ function isLandedTile(r) {
20896
+ return r.outcome === "landed" && r.jpeg !== void 0;
20897
+ }
20898
+ var LinkedReadTimeout = class extends Error {
20899
+ constructor(what, ms) {
20900
+ super(`${what} timed out after ${String(ms)}ms`);
20901
+ this.name = "LinkedReadTimeout";
20902
+ }
20903
+ };
20904
+ var NcLinkedStillShelf = class {
20905
+ deps;
20906
+ sets = /* @__PURE__ */ new Map();
20907
+ owners = /* @__PURE__ */ new Map();
20908
+ constructor(deps) {
20909
+ this.deps = deps;
20910
+ }
20911
+ /** SYNCHRONOUS: the evaluation that follows names these owners. */
20912
+ captureSet(sensorId, cameraIds, atMs) {
20913
+ const now = this.deps.now();
20914
+ this.prune(now);
20915
+ const setId = (0, node_crypto.randomUUID)();
20916
+ const stills = {
20917
+ sensorId,
20918
+ cameraIds: [...cameraIds],
20919
+ mosaicOwnerId: `${NC_LINKED_MOSAIC_PREFIX}${(0, node_crypto.randomUUID)()}`,
20920
+ cameraOwnerIds: cameraIds.map(() => `${NC_LINKED_CAMERA_PREFIX}${(0, node_crypto.randomUUID)()}`)
20921
+ };
20922
+ this.sets.set(setId, {
20923
+ stills,
20924
+ expiresAt: now + NC_STILL_SHELF_TTL_MS,
20925
+ atMs,
20926
+ tiles: /* @__PURE__ */ new Map(),
20927
+ mosaic: []
20928
+ });
20929
+ this.owners.set(stills.mosaicOwnerId, {
20930
+ setId,
20931
+ camera: "mosaic"
20932
+ });
20933
+ stills.cameraOwnerIds.forEach((ownerId, i) => {
20934
+ const cameraId = cameraIds[i];
20935
+ if (cameraId !== void 0) this.owners.set(ownerId, {
20936
+ setId,
20937
+ camera: cameraId
20938
+ });
20939
+ });
20940
+ this.run(setId, stills, atMs, now).catch((err) => {
20941
+ this.deps.logger.warn("sensor notification pictures failed — it ships text-only", {
20942
+ tags: { deviceId: sensorId },
20943
+ meta: { error: String(err) }
20944
+ });
20945
+ });
20946
+ return stills;
20947
+ }
20948
+ /** `undefined` = not an owner this shelf minted (or pruned); `[]` = nothing (yet). */
20949
+ get(ownerId) {
20950
+ const ref = this.owners.get(ownerId);
20951
+ if (ref === void 0) return void 0;
20952
+ const held = this.sets.get(ref.setId);
20953
+ if (held === void 0) return [];
20954
+ if (ref.camera === "mosaic") return held.mosaic;
20955
+ return held.tiles.get(ref.camera) ?? [];
20956
+ }
20957
+ prune(now) {
20958
+ for (const [setId, held] of this.sets) if (held.expiresAt <= now) this.sets.delete(setId);
20959
+ while (this.sets.size > MAX_SETS) {
20960
+ const oldest = this.sets.keys().next();
20961
+ if (oldest.done === true) break;
20962
+ this.sets.delete(oldest.value);
20963
+ }
20964
+ for (const [ownerId, ref] of this.owners) if (!this.sets.has(ref.setId)) this.owners.delete(ownerId);
20965
+ }
20966
+ clear() {
20967
+ this.sets.clear();
20968
+ this.owners.clear();
20969
+ }
20970
+ async run(setId, stills, atMs, startedAt) {
20971
+ const results = await Promise.all(stills.cameraIds.map((id) => this.captureOne(id, startedAt)));
20972
+ const judged = await this.judgeFreshness(stills.sensorId, results, atMs);
20973
+ for (const r of judged) this.logTile(stills.sensorId, r);
20974
+ const landed = judged.filter(isLandedTile);
20975
+ const composed = await this.compose(stills.sensorId, landed, atMs);
20976
+ const undrawable = landed.length - composed.drawn;
20977
+ this.deps.logger.info(composed.mosaic.length === 0 ? "sensor notification has no linked picture — it ships text-only" : "sensor notification pictures ready", {
20978
+ tags: { deviceId: stills.sensorId },
20979
+ meta: {
20980
+ cameras: stills.cameraIds.length,
20981
+ landed: composed.drawn,
20982
+ ...undrawable > 0 ? { undrawable } : {},
20983
+ dropped: Object.fromEntries(judged.filter((r) => r.outcome !== "landed").map((r) => [String(r.cameraId), r.outcome])),
20984
+ tookMs: this.deps.now() - startedAt
20985
+ }
20986
+ });
20987
+ const held = this.sets.get(setId);
20988
+ if (held === void 0) return;
20989
+ this.sets.set(setId, {
20990
+ ...held,
20991
+ tiles: new Map(composed.servable.map((r) => [r.cameraId, stillShelfMedia(r.jpeg, atMs)])),
20992
+ mosaic: composed.mosaic
20993
+ });
20994
+ }
20995
+ async captureOne(cameraId, startedAt) {
20996
+ const took = () => this.deps.now() - startedAt;
20997
+ if (this.deps.isOnline(cameraId) === false) return {
20998
+ cameraId,
20999
+ outcome: "excluded",
21000
+ reason: "offline",
21001
+ tookMs: took()
21002
+ };
21003
+ const [verdict, capture] = await Promise.all([this.wrapperVerdict(cameraId), this.captureStill(cameraId)]);
21004
+ if (verdict.reason !== null) return {
21005
+ cameraId,
21006
+ outcome: "excluded",
21007
+ reason: verdict.reason,
21008
+ tookMs: took()
21009
+ };
21010
+ return {
21011
+ cameraId,
21012
+ ...capture,
21013
+ ...verdict.unknown !== null ? { stateUnknown: verdict.unknown } : {},
21014
+ tookMs: took()
21015
+ };
21016
+ }
21017
+ async captureStill(cameraId) {
21018
+ try {
21019
+ const shot = await withTimeout$3(this.deps.getSnapshot(cameraId), SENSOR_LINKED_CAPTURE_TIMEOUT_MS, "snapshot cap");
21020
+ if (shot === null || shot.base64.length === 0) return { outcome: "empty" };
21021
+ const jpeg = await this.decodableStill(Buffer.from(shot.base64, "base64"));
21022
+ if (jpeg === null) return {
21023
+ outcome: "error",
21024
+ reason: "undecodable"
21025
+ };
21026
+ return {
21027
+ outcome: "landed",
21028
+ jpeg
21029
+ };
21030
+ } catch (err) {
21031
+ return {
21032
+ outcome: err instanceof LinkedReadTimeout ? "timeout" : "error",
21033
+ reason: String(err)
21034
+ };
21035
+ }
21036
+ }
21037
+ /**
21038
+ * The downscaled still, or null when the bytes are not a picture. A resize
21039
+ * that fails on bytes sharp can still READ keeps them raw (a worse picture,
21040
+ * never a missing one); bytes it cannot read never ship — a decode failure is
21041
+ * a fact about the bytes, not a failed read.
21042
+ */
21043
+ async decodableStill(raw) {
21044
+ try {
21045
+ return await downscaleFullFrameJpeg(raw, 960, 540);
21046
+ } catch {
21047
+ try {
21048
+ await (0, sharp.default)(raw).metadata();
21049
+ return raw;
21050
+ } catch {
21051
+ return null;
21052
+ }
21053
+ }
21054
+ }
21055
+ /** A failed, slow or empty read is UNKNOWN and never excludes (D49); the
21056
+ * camera's own outcome line then carries `stateUnknown` with the cause. */
21057
+ async wrapperVerdict(cameraId) {
21058
+ const read = this.deps.getSnapshotState;
21059
+ if (read === void 0) return {
21060
+ reason: null,
21061
+ unknown: null
21062
+ };
21063
+ try {
21064
+ const state = await withTimeout$3(read(cameraId), SENSOR_LINKED_STATE_READ_TIMEOUT_MS, "snapshot state read");
21065
+ return state === void 0 ? {
21066
+ reason: null,
21067
+ unknown: "empty"
21068
+ } : {
21069
+ reason: state.reason,
21070
+ unknown: null
21071
+ };
21072
+ } catch (err) {
21073
+ return {
21074
+ reason: null,
21075
+ unknown: err instanceof LinkedReadTimeout ? "timeout" : "error"
21076
+ };
21077
+ }
21078
+ }
21079
+ async judgeFreshness(sensorId, results, atMs) {
21080
+ const read = this.deps.getFrameCapturedAt;
21081
+ const landedIds = results.filter((r) => r.outcome === "landed").map((r) => r.cameraId);
21082
+ if (read === void 0 || landedIds.length === 0) return results;
21083
+ let capturedAt;
21084
+ try {
21085
+ capturedAt = await withTimeout$3(read(landedIds), 400, "frame freshness read");
21086
+ } catch (err) {
21087
+ this.deps.logger.warn("linked pictures freshness unverified — keeping every tile", {
21088
+ tags: { deviceId: sensorId },
21089
+ meta: { error: String(err) }
21090
+ });
21091
+ return results;
21092
+ }
21093
+ return results.map((r) => {
21094
+ if (r.outcome !== "landed") return r;
21095
+ const at = capturedAt.get(r.cameraId);
21096
+ if (at === void 0 || at === null) return r;
21097
+ if (at >= atMs - 1e4) return r;
21098
+ return {
21099
+ cameraId: r.cameraId,
21100
+ outcome: "stale",
21101
+ reason: `frame ${String(atMs - at)} ms older than the event`,
21102
+ tookMs: r.tookMs
21103
+ };
21104
+ });
21105
+ }
21106
+ async compose(sensorId, landed, atMs) {
21107
+ const first = landed[0];
21108
+ if (first === void 0) return {
21109
+ mosaic: [],
21110
+ servable: [],
21111
+ drawn: 0
21112
+ };
21113
+ if (landed.length === 1) return {
21114
+ mosaic: stillShelfMedia(first.jpeg, atMs),
21115
+ servable: landed,
21116
+ drawn: 1
21117
+ };
21118
+ try {
21119
+ const { jpeg, droppedTiles } = await renderMosaic({
21120
+ purpose: "sensor",
21121
+ tiles: landed.map((r) => ({
21122
+ jpeg: r.jpeg,
21123
+ deviceId: r.cameraId,
21124
+ sourceId: String(r.cameraId)
21125
+ }))
21126
+ }, this.deps.logger);
21127
+ return {
21128
+ mosaic: stillShelfMedia(jpeg, atMs),
21129
+ servable: landed,
21130
+ drawn: landed.length - droppedTiles
21131
+ };
21132
+ } catch (err) {
21133
+ this.deps.logger.warn("sensor mosaic could not be composed — shipping the first camera", {
21134
+ tags: { deviceId: sensorId },
21135
+ meta: {
21136
+ error: String(err),
21137
+ offered: landed.length,
21138
+ shipped: first.cameraId
21139
+ }
21140
+ });
21141
+ return {
21142
+ mosaic: stillShelfMedia(first.jpeg, atMs),
21143
+ servable: landed,
21144
+ drawn: 1
21145
+ };
21146
+ }
21147
+ }
21148
+ logTile(sensorId, r) {
21149
+ const extras = {
21150
+ tags: { deviceId: r.cameraId },
21151
+ meta: {
21152
+ sensorId,
21153
+ outcome: r.outcome,
21154
+ tookMs: r.tookMs,
21155
+ ...r.reason !== void 0 ? { reason: r.reason } : {},
21156
+ ...r.stateUnknown !== void 0 ? { stateUnknown: r.stateUnknown } : {}
21157
+ }
21158
+ };
21159
+ if (r.outcome === "excluded") this.deps.logger.info("linked camera excluded from the sensor notification", extras);
21160
+ else if (r.outcome === "landed" && r.stateUnknown !== void 0) this.deps.logger.info("linked camera photographed for the sensor notification — state unknown, tile kept", extras);
21161
+ else if (r.outcome === "landed") this.deps.logger.debug("linked camera photographed for the sensor notification", extras);
21162
+ else this.deps.logger.warn("linked camera gave no usable picture for the sensor notification", extras);
21163
+ }
21164
+ };
21165
+ /** Reject with {@link LinkedReadTimeout} if `promise` does not settle within `ms`. */
21166
+ function withTimeout$3(promise, ms, what) {
21167
+ return new Promise((resolve, reject) => {
21168
+ const timer = setTimeout(() => reject(new LinkedReadTimeout(what, ms)), ms);
21169
+ promise.then((value) => {
21170
+ clearTimeout(timer);
21171
+ resolve(value);
21172
+ }, (err) => {
21173
+ clearTimeout(timer);
21174
+ reject(err instanceof Error ? err : new Error(String(err)));
21175
+ });
21176
+ });
21177
+ }
21178
+ //#endregion
20134
21179
  //#region src/notification-center/liveness-ledger.ts
20135
21180
  /**
20136
21181
  * @durable class=ledger owner=notification-center
@@ -22970,279 +24015,6 @@ var NcSnoozeStore = class {
22970
24015
  return parsed.success ? parsed.data : null;
22971
24016
  }
22972
24017
  };
22973
- /** JPEG quality for the downscaled full frame — matches the crop path. */
22974
- var FULL_FRAME_QUALITY = 80;
22975
- /**
22976
- * Downscale an already-encoded JPEG full frame to FIT WITHIN
22977
- * {@link FULL_FRAME_MAX_WIDTH}×{@link FULL_FRAME_MAX_HEIGHT}, preserving aspect
22978
- * ratio (`fit: 'inside'`) and never enlarging a source already smaller than the
22979
- * box. Re-encodes as JPEG. Used before persisting a synthetic sensor/control
22980
- * track's whole-scene snapshot so a raw native-resolution frame (a 4K bedroom
22981
- * at night) is never stored or served — the privacy fix moved to CAPTURE time.
22982
- */
22983
- async function downscaleFullFrameJpeg(jpeg, maxWidth = 640, maxHeight = 360) {
22984
- return (0, sharp.default)(Buffer.from(jpeg)).resize(maxWidth, maxHeight, {
22985
- fit: "inside",
22986
- withoutEnlargement: true
22987
- }).jpeg({ quality: FULL_FRAME_QUALITY }).toBuffer();
22988
- }
22989
- //#endregion
22990
- //#region src/notification-center/still-shelf.ts
22991
- /**
22992
- * The still shelf — the PHOTOGRAPH a notification carries when nothing it can
22993
- * name owns a frame.
22994
- *
22995
- * ## Why a trigger needs one at all
22996
- *
22997
- * The attachment ladder resolves media by OWNER, and most triggers have one: an
22998
- * object or package event owns its crops, a closed track owns its best shot, a
22999
- * doorbell press owns the marker track the same press projected
23000
- * (`sensor-marker-projector.ts`), an occupancy edge names one of the objects it
23001
- * counted (`chooseOccupancyMediaOwner`). Two triggers own nothing, and for the
23002
- * same reason in both cases — the subject is an ABSENCE:
23003
- *
23004
- * - an **audio** match: nothing was boxed, nothing was tracked, and —
23005
- * deliberately — nothing is persisted at all. A confirmed window is a claim
23006
- * about sound that has already stopped, and `event-intake.ts` states why
23007
- * replaying it later would be wrong.
23008
- * - an **occupancy** edge whose scope is EMPTY — "posto libero". The vehicle
23009
- * whose departure IS the news has left, so `chooseOccupancyMediaOwner` names
23010
- * nobody and the ladder logs `no still could be resolved … owners=[]`.
23011
- *
23012
- * So the only honest picture is a PHOTOGRAPH of the camera taken at the moment
23013
- * of the trigger. Not of the sound, not of the object that left — of what the
23014
- * camera can see now that it happened. For a freed parking space that is
23015
- * exactly the answer the operator wants: the space, empty.
23016
- *
23017
- * **One shelf, not two.** The mechanism is identical down to the reuse window,
23018
- * and the only thing that differs between the two triggers is the GATE deciding
23019
- * that a photograph is owed at all — which belongs at the trigger site, where
23020
- * the rules are, and not here. A twin module would be a second derivation of
23021
- * one thing. The trigger rides along as {@link NcStillTrigger} only so the logs
23022
- * can say which absence they are about.
23023
- *
23024
- * ## Three properties, and each one is a decision
23025
- *
23026
- * **It is not a record.** The bytes live here, in RAM, under an owner id and a
23027
- * TTL that covers the outbox's whole retry horizon — and nowhere else. The
23028
- * alternative was the doorbell's: materialise a synthetic marker track through
23029
- * `SyntheticTrackMaterializer` and let the notification name it. That would put
23030
- * a durable Track on the camera's timeline for every confirmed window and every
23031
- * emptied zone, feeding the digest's `listTracks`, retention, and the audio-
23032
- * marker feature's own operator ceilings (`audio-marker-projector.ts` exists
23033
- * precisely to bound how many audio markers a camera may emit). A notification
23034
- * must not manufacture timeline history as a side effect of wanting a picture.
23035
- *
23036
- * **The capture STARTS immediately and is never awaited.** The subject is
23037
- * transient — a scream is over before a snapshot round-trip completes, and a
23038
- * freed space is about to be taken by the next car — so the fetch is kicked off
23039
- * at the trigger, before the rule evaluation runs, and the owner id is minted
23040
- * synchronously so the outbox row can name it. The bytes land while the row
23041
- * waits in the queue, and the dispatcher's existing bounded still-wait (or the
23042
- * pause its own footage render already costs) picks them up. A camera that
23043
- * never answers costs the picture and never the notification.
23044
- *
23045
- * **Two triggers seconds apart share ONE capture.** A barking dog confirms
23046
- * repeatedly and a label-mode rule has no re-arm timer at all (D157) — the
23047
- * rule's cooldown is its only brake, and the cooldown is applied AFTER this.
23048
- * Without a reuse window this would photograph a camera at whatever rate the
23049
- * sound happens to occur. Each trigger still gets its OWN owner id, so two
23050
- * outbox rows are never mistaken for one subject; they merely point at the same
23051
- * frame, which is the truth — the scene did not change in ten seconds. The
23052
- * window is per CAMERA and trigger-agnostic for the same reason: a sound and an
23053
- * emptied zone ten seconds apart are two claims about one scene.
23054
- *
23055
- * Nothing here is silent: a capture that lands and a camera that refuses each
23056
- * emit one line carrying `tags: { deviceId }`, because "why did 617 get a photo
23057
- * and 615 not" is the only form that question is ever asked in.
23058
- */
23059
- /**
23060
- * The owner-id namespace. It is what routes a lookup here instead of to the
23061
- * media store, and it is the reason the dispatcher needs no audio or occupancy
23062
- * branch — `getMediaForOwner` answers for all of them under one signature.
23063
- */
23064
- var NC_STILL_SHELF_PREFIX = "nc-still:";
23065
- /** True for an owner id this shelf minted. */
23066
- function isStillShelfId(id) {
23067
- return id.startsWith(NC_STILL_SHELF_PREFIX);
23068
- }
23069
- /**
23070
- * How long the bytes are held.
23071
- *
23072
- * The outbox retries 8 times with a 5 s → 300 s backoff, which tops out around
23073
- * ten minutes; fifteen covers that with room for a slow drain. Past it the row
23074
- * ships text-only, which is the correct degradation for a photograph of a scene
23075
- * that is a quarter of an hour stale anyway.
23076
- */
23077
- var NC_STILL_SHELF_TTL_MS = 15 * 6e4;
23078
- /** A hanging snapshot cap must not pin a capture slot forever. */
23079
- var SNAPSHOT_TIMEOUT_MS = 8e3;
23080
- /**
23081
- * Hard bound on held captures. Reached only if every camera on the hub triggers
23082
- * one inside a single TTL; the oldest is dropped first, which costs a
23083
- * fifteen-minute-old picture nobody is waiting for.
23084
- */
23085
- var MAX_CAPTURES = 64;
23086
- var NcStillShelf = class {
23087
- deps;
23088
- /** captureId → the photograph. */
23089
- captures = /* @__PURE__ */ new Map();
23090
- /** ownerId → captureId. Several owners may name one capture (the reuse window). */
23091
- owners = /* @__PURE__ */ new Map();
23092
- /** deviceId → its newest capture, for the reuse window. */
23093
- newest = /* @__PURE__ */ new Map();
23094
- constructor(deps) {
23095
- this.deps = deps;
23096
- }
23097
- /**
23098
- * Photograph `deviceId` for a trigger at `atMs`, and return the owner id the
23099
- * subject should name. SYNCHRONOUS by contract: the caller is on the trigger
23100
- * path and the outbox row is built from what this returns.
23101
- */
23102
- capture(deviceId, atMs, trigger) {
23103
- const now = this.deps.now();
23104
- this.prune(now);
23105
- const ownerId = `${NC_STILL_SHELF_PREFIX}${(0, node_crypto.randomUUID)()}`;
23106
- const recent = this.newest.get(deviceId);
23107
- if (recent !== void 0 && now - recent.at < 1e4 && this.captures.has(recent.captureId)) {
23108
- this.owners.set(ownerId, recent.captureId);
23109
- return ownerId;
23110
- }
23111
- const captureId = (0, node_crypto.randomUUID)();
23112
- this.captures.set(captureId, {
23113
- deviceId,
23114
- trigger,
23115
- startedAt: now,
23116
- expiresAt: now + NC_STILL_SHELF_TTL_MS,
23117
- files: []
23118
- });
23119
- this.newest.set(deviceId, {
23120
- captureId,
23121
- at: now
23122
- });
23123
- this.owners.set(ownerId, captureId);
23124
- this.fetch(captureId, deviceId, atMs, trigger);
23125
- return ownerId;
23126
- }
23127
- /**
23128
- * The media an owner id holds, or `undefined` when this shelf never minted
23129
- * it. An EMPTY array is a different answer: the capture exists and has not
23130
- * landed (or never will), which is exactly the case the dispatcher's bounded
23131
- * wait and its `no still could be resolved` line are for.
23132
- */
23133
- get(ownerId) {
23134
- const captureId = this.owners.get(ownerId);
23135
- if (captureId === void 0) return void 0;
23136
- return this.captures.get(captureId)?.files ?? [];
23137
- }
23138
- /** Drop expired captures and the owners that named them. */
23139
- prune(now) {
23140
- for (const [captureId, held] of this.captures) {
23141
- if (held.expiresAt > now) continue;
23142
- this.captures.delete(captureId);
23143
- if (this.newest.get(held.deviceId)?.captureId === captureId) this.newest.delete(held.deviceId);
23144
- }
23145
- while (this.captures.size > MAX_CAPTURES) {
23146
- const oldest = this.captures.keys().next();
23147
- if (oldest.done === true) break;
23148
- const held = this.captures.get(oldest.value);
23149
- this.captures.delete(oldest.value);
23150
- if (held !== void 0 && this.newest.get(held.deviceId)?.captureId === oldest.value) this.newest.delete(held.deviceId);
23151
- }
23152
- for (const [ownerId, captureId] of this.owners) if (!this.captures.has(captureId)) this.owners.delete(ownerId);
23153
- }
23154
- /** Drop everything (shutdown). */
23155
- clear() {
23156
- this.captures.clear();
23157
- this.owners.clear();
23158
- this.newest.clear();
23159
- }
23160
- async fetch(captureId, deviceId, atMs, trigger) {
23161
- try {
23162
- const shot = await withTimeout$3(this.deps.getSnapshot(deviceId), SNAPSHOT_TIMEOUT_MS);
23163
- if (shot === null || shot.base64.length === 0) {
23164
- this.reportMiss(deviceId, trigger, "the camera returned no snapshot");
23165
- return;
23166
- }
23167
- const raw = Buffer.from(shot.base64, "base64");
23168
- let data = raw;
23169
- try {
23170
- data = await downscaleFullFrameJpeg(raw, 960, 540);
23171
- } catch {}
23172
- const held = this.captures.get(captureId);
23173
- if (held === void 0) return;
23174
- this.captures.set(captureId, {
23175
- ...held,
23176
- files: stillShelfMedia(data, atMs)
23177
- });
23178
- this.deps.logger.info(`${trigger} still captured`, {
23179
- tags: { deviceId },
23180
- meta: {
23181
- trigger,
23182
- bytes: data.byteLength,
23183
- tookMs: this.deps.now() - held.startedAt
23184
- }
23185
- });
23186
- } catch (err) {
23187
- this.reportMiss(deviceId, trigger, err instanceof Error ? err.message : String(err));
23188
- }
23189
- }
23190
- /**
23191
- * A branch that drops work says so. This one costs the operator the picture
23192
- * on a notification they DID receive, so it is a warn and it carries the
23193
- * camera — the only key the question is ever asked with.
23194
- */
23195
- reportMiss(deviceId, trigger, reason) {
23196
- this.deps.logger.warn(`the camera did not answer the ${trigger} still — this notification ships text-only`, {
23197
- tags: { deviceId },
23198
- meta: {
23199
- trigger,
23200
- reason
23201
- }
23202
- });
23203
- }
23204
- };
23205
- /**
23206
- * The photograph, in the three kinds the CLEAN-SCENE ladders ask for.
23207
- *
23208
- * `keyFrameSmall` leads because it is the first rung of both `attach: 'best'`
23209
- * and `attach: 'keyFrame'` on a track owner; `keyFrame` and `fullFrame` answer
23210
- * `frame: 'full'` and `frame: 'boxed'`'s honest degrade. There is deliberately
23211
- * no `crop` / `thumbnail`: nothing was boxed, so `frame: 'cropped'` resolves
23212
- * NOTHING and the notification ships text-only with the ordinary line saying
23213
- * so. Inventing a centre crop would answer a different question from the one
23214
- * the operator asked.
23215
- */
23216
- function stillShelfMedia(data, timestamp) {
23217
- const base64 = data.toString("base64");
23218
- const file = (kind) => ({
23219
- mediaId: nextUnstoredMediaId(),
23220
- kind,
23221
- base64,
23222
- sizeBytes: data.byteLength,
23223
- timestamp
23224
- });
23225
- return [
23226
- file("keyFrameSmall"),
23227
- file("keyFrame"),
23228
- file("fullFrame")
23229
- ];
23230
- }
23231
- /** Reject if `promise` does not settle within `ms`. */
23232
- function withTimeout$3(promise, ms) {
23233
- return new Promise((resolve, reject) => {
23234
- const timer = setTimeout(() => {
23235
- reject(/* @__PURE__ */ new Error(`snapshot cap timed out after ${String(ms)}ms`));
23236
- }, ms);
23237
- promise.then((value) => {
23238
- clearTimeout(timer);
23239
- resolve(value);
23240
- }, (err) => {
23241
- clearTimeout(timer);
23242
- reject(err instanceof Error ? err : new Error(String(err)));
23243
- });
23244
- });
23245
- }
23246
24018
  //#endregion
23247
24019
  //#region src/notification-center/summary/summary-ai.ts
23248
24020
  /**
@@ -23734,293 +24506,6 @@ function findNextWindowOpen(input) {
23734
24506
  endMs: null
23735
24507
  };
23736
24508
  }
23737
- /** The canvas behind a tile whose aspect does not fill its cell. */
23738
- var MOSAIC_BACKGROUND = {
23739
- r: 17,
23740
- g: 17,
23741
- b: 17
23742
- };
23743
- /** Tile aspect — cameras are 16:9 and a square cell would letterbox every one. */
23744
- var TILE_ASPECT = 9 / 16;
23745
- /** Height of the per-tile label strip, as a fraction of the tile height. */
23746
- var LABEL_BAND_FRACTION = .14;
23747
- var LABEL_MIN_PX = 11;
23748
- /** Height of the mosaic's own title band, as a fraction of a tile's height. */
23749
- var TITLE_BAND_FRACTION = .22;
23750
- var TITLE_MIN_PX = 16;
23751
- /**
23752
- * Average glyph width as a fraction of the font size, for bold sans-serif.
23753
- *
23754
- * An ESTIMATE, and it has to be: librsvg lays the text out long after this
23755
- * string is written, so there are no metrics to measure against. The same
23756
- * number and the same reasoning as `preview-frame.ts#fitTitle` — deliberately
23757
- * GENEROUS, because a label that shrank slightly more than it had to is
23758
- * invisible and one that overflowed runs into the tile beside it. The first
23759
- * live mosaic did exactly that: `Videocamera cortile · 07:49 · animal` was cut
23760
- * to `…· anima` at the tile edge, mid-word.
23761
- */
23762
- var GLYPH_ADVANCE = .56;
23763
- /** Fraction of the band a label may occupy, leaving the padding either side. */
23764
- var LABEL_USABLE_FRACTION = .94;
23765
- /** `<`, `>`, `&`, `'`, `"` in a camera name or an operator caption would each
23766
- * turn the overlay into a document librsvg refuses. */
23767
- function escapeXml$1(s) {
23768
- return s.replace(/[<>&'"]/g, (ch) => {
23769
- switch (ch) {
23770
- case "<": return "&lt;";
23771
- case ">": return "&gt;";
23772
- case "&": return "&amp;";
23773
- case "'": return "&apos;";
23774
- default: return "&quot;";
23775
- }
23776
- });
23777
- }
23778
- /**
23779
- * The single decision about drawn text — and the home of the DEFAULT.
23780
- *
23781
- * `undefined` means `none`, not `all`: a rule stored before this option existed
23782
- * has no `captions` key, and the operator's request is that such a rule deliver
23783
- * pictures. The schema materialises the same default on read
23784
- * (`NcSummaryRuleInputSchema`), so this arm only fires for a caller that never
23785
- * had a rule — the test bridge and the spec. Both agreeing is the point.
23786
- */
23787
- function mosaicTextPlan(captions) {
23788
- if (captions === "all") return {
23789
- tileLabels: true,
23790
- titleBand: true
23791
- };
23792
- if (captions === "tiles") return {
23793
- tileLabels: true,
23794
- titleBand: false
23795
- };
23796
- return {
23797
- tileLabels: false,
23798
- titleBand: false
23799
- };
23800
- }
23801
- /** Grid shape for `n` tiles: as square as possible, rows never exceeding cols
23802
- * by more than one — a 3×3 for nine, a 3×2 for five, never a 1×9 strip.
23803
- *
23804
- * `rows` is the load-bearing half — it is how many rows {@link mosaicRowCounts}
23805
- * distributes into. `cols` describes the WIDEST row, and is no longer a cell
23806
- * count: see {@link mosaicRowCounts} for why a `cols × rows` grid was the bug. */
23807
- function mosaicGrid(n) {
23808
- const count = Math.max(1, Math.floor(n));
23809
- const cols = Math.ceil(Math.sqrt(count));
23810
- return {
23811
- cols,
23812
- rows: Math.ceil(count / cols)
23813
- };
23814
- }
23815
- /**
23816
- * How many tiles each ROW carries, top to bottom — and the reason the mosaic
23817
- * can no longer have a hole in it.
23818
- *
23819
- * The layout used to be a `cols × rows` GRID, and a grid holds more cells than
23820
- * tiles for every count that is not a perfect fit: 3 into a 2×2, 5 into a 3×2,
23821
- * 7 and 8 into a 3×3. The composite only ever wrote the tiles, so the spare
23822
- * cells stayed the canvas — `MOSAIC_BACKGROUND`, rgb 17 — and the operator's
23823
- * three-tile digest was a quarter black. Measured on the shipped renderer:
23824
- * 24.8% of a three-tile mosaic was background. His words: *"se ci sono 3
23825
- * elementi non dovrebbe renderizzare buchi neri"*.
23826
- *
23827
- * Counting ROWS instead removes the failure by construction rather than by
23828
- * patching it. Every row spans the full width and divides it among the tiles it
23829
- * actually has, so a row is full whatever the remainder and there is no such
23830
- * thing as a spare cell. The shapes fall out of it, and they are the ones asked
23831
- * for: 1 ⇒ full frame, 2 ⇒ side by side, 3 ⇒ one big over two small, 4 ⇒ 2×2.
23832
- *
23833
- * **The fewer-tiled row comes FIRST.** Tiles arrive in the selection's order,
23834
- * so row 0 is the head of the ranking; putting the remainder at the top would
23835
- * make the WORST tile the big one.
23836
- *
23837
- * Every cell keeps {@link TILE_ASPECT}, so rows differ in height — which is
23838
- * also what stops the letterbox: a full-width hero tile is 16:9 exactly, not a
23839
- * 16:9 picture centred in a double-height cell with bars over and under it.
23840
- */
23841
- function mosaicRowCounts(n) {
23842
- const count = Math.max(1, Math.floor(n));
23843
- const { rows } = mosaicGrid(count);
23844
- const base = Math.floor(count / rows);
23845
- const remainder = count % rows;
23846
- const counts = [];
23847
- for (let row = 0; row < rows; row += 1) counts.push(row < rows - remainder ? base : base + 1);
23848
- return counts;
23849
- }
23850
- /**
23851
- * Where every tile lands. Pure — no bytes, no sharp, no clock.
23852
- *
23853
- * Exported because the rectangles are DATA the artefact should carry: a viewer
23854
- * that wants a tappable mosaic reads these rather than re-deriving a layout
23855
- * that could drift from the one actually rendered.
23856
- *
23857
- * The rectangles COVER the picture area exactly — that is the property the
23858
- * spec asserts, and it is the one the old grid broke.
23859
- */
23860
- function mosaicLayout(input) {
23861
- const rowCounts = mosaicRowCounts(input.tileCount);
23862
- const width = Math.max(1, Math.floor(input.maxWidth ?? 1920));
23863
- const firstRowCount = rowCounts[0] ?? 1;
23864
- const tileWidth = Math.floor(width / firstRowCount);
23865
- const tileHeight = Math.round(tileWidth * TILE_ASPECT);
23866
- const titleHeight = input.withTitle === true ? Math.round(tileHeight * TITLE_BAND_FRACTION) : 0;
23867
- const tiles = [];
23868
- let y = titleHeight;
23869
- let index = 0;
23870
- for (const count of rowCounts) {
23871
- const nominalWidth = Math.floor(width / count);
23872
- const rowHeight = Math.round(nominalWidth * TILE_ASPECT);
23873
- let x = 0;
23874
- for (let inRow = 0; inRow < count; inRow += 1) {
23875
- const w = inRow === count - 1 ? width - x : nominalWidth;
23876
- tiles.push({
23877
- index,
23878
- x,
23879
- y,
23880
- w,
23881
- h: rowHeight
23882
- });
23883
- x += w;
23884
- index += 1;
23885
- }
23886
- y += rowHeight;
23887
- }
23888
- return {
23889
- width,
23890
- height: y,
23891
- cols: Math.max(...rowCounts),
23892
- rows: rowCounts.length,
23893
- rowCounts,
23894
- tileWidth,
23895
- tileHeight,
23896
- titleHeight,
23897
- tiles
23898
- };
23899
- }
23900
- /**
23901
- * Shrink, then ELIDE, until the line fits `usablePx`.
23902
- *
23903
- * Shrinking is tried first because a slightly smaller label still says
23904
- * everything; only past `minPx` is the tail cut, and then with an ellipsis so
23905
- * the reader can SEE that something was cut. The failure this replaces was
23906
- * silent: SVG simply clips at the viewport, so an overlong label lost its last
23907
- * word mid-glyph and looked like a rendering bug rather than a truncation.
23908
- *
23909
- * Pure and exported so the arithmetic is testable without rendering a pixel.
23910
- */
23911
- function fitLine(text, usablePx, basePx, minPx) {
23912
- const flat = text.trim().replace(/\s+/g, " ");
23913
- const fits = (s, fontPx) => s.length * fontPx * GLYPH_ADVANCE <= usablePx;
23914
- let fontPx = Math.max(minPx, Math.round(basePx));
23915
- while (fontPx > minPx && !fits(flat, fontPx)) fontPx = Math.max(minPx, fontPx - 1);
23916
- if (fits(flat, fontPx)) return {
23917
- text: flat,
23918
- fontPx
23919
- };
23920
- const budget = Math.max(1, Math.floor(usablePx / (fontPx * GLYPH_ADVANCE)));
23921
- return {
23922
- text: `${flat.slice(0, Math.max(1, budget - 1)).trimEnd()}…`,
23923
- fontPx
23924
- };
23925
- }
23926
- /** The label strip drawn across the bottom of one tile. */
23927
- function tileLabelSvg(width, height, label) {
23928
- const bandHeight = Math.max(18, Math.round(height * LABEL_BAND_FRACTION));
23929
- const basePx = Math.round(bandHeight * .62);
23930
- const padding = Math.round(basePx * .6);
23931
- const fitted = fitLine(label, width * LABEL_USABLE_FRACTION - padding, basePx, LABEL_MIN_PX);
23932
- const baseline = height - Math.round((bandHeight - fitted.fontPx) / 2) - Math.round(fitted.fontPx * .18);
23933
- return Buffer.from(`<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
23934
- <rect x="0" y="${height - bandHeight}" width="${width}" height="${bandHeight}" fill="black" fill-opacity="0.55"/>
23935
- <text x="${padding}" y="${baseline}" font-size="${fitted.fontPx}" font-family="sans-serif" font-weight="bold" fill="white">${escapeXml$1(fitted.text)}</text>
23936
- </svg>`);
23937
- }
23938
- /** The mosaic's own title band. */
23939
- function titleSvg(width, height, caption) {
23940
- const fitted = fitLine(caption, width * LABEL_USABLE_FRACTION, Math.round(height * .5), TITLE_MIN_PX);
23941
- const baseline = Math.round(height / 2 + fitted.fontPx * .36);
23942
- return Buffer.from(`<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
23943
- <rect x="0" y="0" width="${width}" height="${height}" fill="#111111"/>
23944
- <text x="${Math.round(width / 2)}" y="${baseline}" font-size="${fitted.fontPx}" font-family="sans-serif" font-weight="bold" text-anchor="middle" fill="white">${escapeXml$1(fitted.text)}</text>
23945
- </svg>`);
23946
- }
23947
- /**
23948
- * Compose the mosaic.
23949
- *
23950
- * Every tile is fitted with `contain` onto the cell background rather than
23951
- * cropped: a `cover` fit would silently cut the subject out of a portrait crop,
23952
- * and a tile that does not show what it is about is worse than a letterboxed
23953
- * one.
23954
- *
23955
- * A tile sharp cannot read is DROPPED and counted, never composited as a blank
23956
- * cell — a black square in a digest reads as "the camera saw nothing", which is
23957
- * the opposite of what happened. The layout is computed from the SURVIVORS, and
23958
- * because {@link mosaicRowCounts} counts rows rather than grid cells there is no
23959
- * remainder to leave empty either.
23960
- *
23961
- * @throws when every tile was dropped, and when sharp cannot produce the final
23962
- * canvas at all; the caller treats both as "no mosaic" and still
23963
- * delivers the counts.
23964
- */
23965
- async function renderMosaic(request, logger) {
23966
- const plan = mosaicTextPlan(request.captions);
23967
- const usable = [];
23968
- for (const tile of request.tiles) try {
23969
- await (0, sharp.default)(tile.jpeg).metadata();
23970
- usable.push(tile);
23971
- } catch (err) {
23972
- logger.warn("summary mosaic: a tile could not be decoded and was dropped", {
23973
- tags: { deviceId: tile.deviceId },
23974
- meta: {
23975
- trackId: tile.trackId,
23976
- error: String(err)
23977
- }
23978
- });
23979
- }
23980
- const droppedTiles = request.tiles.length - usable.length;
23981
- if (usable.length === 0) throw new Error(`summary mosaic: no tile could be decoded (${request.tiles.length} offered)`);
23982
- const caption = plan.titleBand ? request.caption?.trim() ?? "" : "";
23983
- const layout = mosaicLayout({
23984
- tileCount: usable.length,
23985
- ...request.maxWidth !== void 0 ? { maxWidth: request.maxWidth } : {},
23986
- withTitle: caption.length > 0
23987
- });
23988
- const composites = await Promise.all(usable.map(async (tile, index) => {
23989
- const rect = layout.tiles[index];
23990
- if (rect === void 0) throw new Error("summary mosaic: layout lost a tile");
23991
- const label = plan.tileLabels ? tile.label?.trim() ?? "" : "";
23992
- const fitted = (0, sharp.default)(tile.jpeg).resize({
23993
- width: rect.w,
23994
- height: rect.h,
23995
- fit: "contain",
23996
- background: MOSAIC_BACKGROUND
23997
- });
23998
- return {
23999
- input: await (label.length === 0 ? fitted : fitted.composite([{
24000
- input: tileLabelSvg(rect.w, rect.h, label),
24001
- top: 0,
24002
- left: 0
24003
- }])).jpeg({ quality: 82 }).toBuffer(),
24004
- top: rect.y,
24005
- left: rect.x
24006
- };
24007
- }));
24008
- if (caption.length > 0 && layout.titleHeight > 0) composites.unshift({
24009
- input: titleSvg(layout.width, layout.titleHeight, caption),
24010
- top: 0,
24011
- left: 0
24012
- });
24013
- return {
24014
- jpeg: await (0, sharp.default)({ create: {
24015
- width: layout.width,
24016
- height: layout.height,
24017
- channels: 3,
24018
- background: MOSAIC_BACKGROUND
24019
- } }).composite(composites).jpeg({ quality: 82 }).toBuffer(),
24020
- layout,
24021
- droppedTiles
24022
- };
24023
- }
24024
24509
  //#endregion
24025
24510
  //#region src/notification-center/summary/summary-ai-subject-view.ts
24026
24511
  /**
@@ -25344,11 +25829,12 @@ var NcSummaryProducer = class {
25344
25829
  try {
25345
25830
  const plan = mosaicTextPlan(rule.captions);
25346
25831
  rendered = await renderMosaic({
25832
+ purpose: "summary",
25347
25833
  tiles: tiles.map(({ candidate, jpeg }) => ({
25348
25834
  jpeg,
25349
25835
  ...plan.tileLabels ? { label: `${names.get(candidate.deviceId) ?? candidate.deviceId} · ${clockOf$1(candidate.firstSeen)} · ${candidate.className}` } : {},
25350
25836
  deviceId: candidate.deviceId,
25351
- trackId: candidate.trackId
25837
+ sourceId: candidate.trackId
25352
25838
  })),
25353
25839
  captions: rule.captions,
25354
25840
  ...plan.titleBand ? { caption: summaryCaptionText({
@@ -27711,6 +28197,12 @@ var NotificationCenter = class NotificationCenter {
27711
28197
  */
27712
28198
  stills;
27713
28199
  /**
28200
+ * The photographs a SENSOR notification carries of every camera linking the
28201
+ * sensor (`linked-stills.ts`, ADR 0632). Null when this wiring has no
28202
+ * snapshot cap — such a notification then ships text-only.
28203
+ */
28204
+ linkedStills;
28205
+ /**
27714
28206
  * Rate limit for the "matched NO rule" report — see `reportNoMatch`. Keyed by
27715
28207
  * {@link noMatchReportKey} (device + subject kind + class set), NOT by device:
27716
28208
  * a person's verdict must never consume the window a cat's verdict needed on
@@ -27721,6 +28213,10 @@ var NotificationCenter = class NotificationCenter {
27721
28213
  /** Same rate-limit pair, same key, for the per-camera mute drop — see `reportMutedDrop`. */
27722
28214
  lastMutedReportAt = /* @__PURE__ */ new Map();
27723
28215
  mutedSuppressed = /* @__PURE__ */ new Map();
28216
+ /** Same pair, keyed by CAMERA, for a muted camera left out of a linked set —
28217
+ * see `reportLinkedCameraMuted`. */
28218
+ lastLinkedMutedReportAt = /* @__PURE__ */ new Map();
28219
+ linkedMutedSuppressed = /* @__PURE__ */ new Map();
27724
28220
  /**
27725
28221
  * RAM-only same-edge dedup for the families the durable ledger does NOT
27726
28222
  * govern — stream health and the operator's disable switch. Both are already
@@ -28371,6 +28867,14 @@ var NotificationCenter = class NotificationCenter {
28371
28867
  logger: this.logger.child("still-shelf"),
28372
28868
  now: this.now
28373
28869
  }) : null;
28870
+ this.linkedStills = getSnapshot !== void 0 ? new NcLinkedStillShelf({
28871
+ getSnapshot,
28872
+ ...deps.getSnapshotState !== void 0 ? { getSnapshotState: deps.getSnapshotState } : {},
28873
+ ...deps.getFrameCapturedAt !== void 0 ? { getFrameCapturedAt: deps.getFrameCapturedAt } : {},
28874
+ isOnline: (id) => this.deviceDirectory.get(id)?.online,
28875
+ logger: this.logger.child("linked-stills"),
28876
+ now: this.now
28877
+ }) : null;
28374
28878
  this.rules = new NcRuleStore({
28375
28879
  store: deps.store,
28376
28880
  logger: this.logger.child("rules"),
@@ -28488,6 +28992,8 @@ var NotificationCenter = class NotificationCenter {
28488
28992
  if (held !== void 0) return held.files;
28489
28993
  const shelved = isStillShelfId(ownerId) ? this.stills?.get(ownerId) : void 0;
28490
28994
  if (shelved !== void 0) return shelved;
28995
+ const linked = isLinkedStillId(ownerId) ? this.linkedStills?.get(ownerId) : void 0;
28996
+ if (linked !== void 0) return linked;
28491
28997
  return deps.dispatcher.getMediaForOwner(ownerKind, ownerId);
28492
28998
  },
28493
28999
  ...deps.now !== void 0 ? { now: deps.now } : {},
@@ -28886,6 +29392,7 @@ var NotificationCenter = class NotificationCenter {
28886
29392
  this.timelapseScheduler?.stop();
28887
29393
  this.summaryProducer?.stop();
28888
29394
  this.stills?.clear();
29395
+ this.linkedStills?.clear();
28889
29396
  this.addonUpdates.dispose();
28890
29397
  this.livenessHoldoff.dispose();
28891
29398
  this.evaluationActive = false;
@@ -29214,6 +29721,110 @@ var NotificationCenter = class NotificationCenter {
29214
29721
  this.consumeEvent(incomingFromUnownedSensorEvent(event, linkedCameraIds));
29215
29722
  }
29216
29723
  /**
29724
+ * Start photographing every camera that links `sensorId`, and return the
29725
+ * owners the sensor-level evaluation names — or `undefined` when there is no
29726
+ * set (≤1 linked camera: today's marker is the picture), nothing to show
29727
+ * (every linked camera muted), the event will be dropped as muted (the
29728
+ * SENSOR is muted, or there were row cameras and every one is muted — see
29729
+ * the evaluation's mute gate), or no enabled device-event rule that could
29730
+ * fire on this sensor KIND wants a picture (the gate is the RULE's media
29731
+ * policy, scope and kind conditions, read from the in-memory mirror — D49,
29732
+ * as `audioStillOwner`; an occupancy rule, which rides the same delivery,
29733
+ * never fires on a sensor). Coarse on purpose, in one direction only: a
29734
+ * capture for a rule whose other conditions then fail is one wasted
29735
+ * snapshot, a missing capture is a notification without its picture. The
29736
+ * kind check is what keeps a chatty multi-linked motion sensor from
29737
+ * composing a mosaic on every edge for a doorbell rule.
29738
+ *
29739
+ * A MUTED camera (D62) is never dialled: its tile is left out, said on that
29740
+ * camera (once per window), and the primary is the first linked camera that
29741
+ * is not muted — the same derivation {@link onSensorEvent} makes.
29742
+ *
29743
+ * `cameraIds` is every linking camera, UNFILTERED; `rowCameraIds` the ones
29744
+ * that take a timeline row for the change — with the sensor, the device
29745
+ * scope the evaluation will match on (`matchesDeviceScope`).
29746
+ */
29747
+ beginLinkedStills(request) {
29748
+ const { sensorId, sensorKind, cameraIds, atMs, rowCameraIds } = request;
29749
+ const shelf = this.linkedStills;
29750
+ if (shelf === null || !this.evaluationActive || cameraIds.length < 2) return void 0;
29751
+ if (this.deviceMutes.isMuted(sensorId)) return void 0;
29752
+ const rowShown = this.unmutedCameras(rowCameraIds);
29753
+ if (rowCameraIds.length > 0 && rowShown.length === 0) return void 0;
29754
+ const shown = this.unmutedCameras(cameraIds);
29755
+ const involved = [sensorId, ...rowShown];
29756
+ if (!this.rules.listEnabled("device-event").some((rule) => {
29757
+ if (rule.media.attach === "none") return false;
29758
+ if (!deviceEventRuleMayFireOnKind(rule, sensorKind)) return false;
29759
+ const devices = rule.conditions.devices;
29760
+ return devices === void 0 || devices.length === 0 || devices.some((id) => involved.includes(id));
29761
+ })) return void 0;
29762
+ for (const cameraId of cameraIds) if (!shown.includes(cameraId)) this.reportLinkedCameraMuted(cameraId, sensorId);
29763
+ return shown.length > 0 ? shelf.captureSet(sensorId, shown, atMs) : void 0;
29764
+ }
29765
+ /**
29766
+ * A muted camera left out of a linked set — one INFO line per camera per
29767
+ * window, the suppressed count folded into the next one. A chatty contact
29768
+ * linked to a muted camera must not write a line on every change.
29769
+ */
29770
+ reportLinkedCameraMuted(cameraId, sensorId) {
29771
+ const now = this.now();
29772
+ const last = this.lastLinkedMutedReportAt.get(cameraId);
29773
+ const suppressed = this.linkedMutedSuppressed.get(cameraId) ?? 0;
29774
+ if (last !== void 0 && now - last < NO_MATCH_REPORT_INTERVAL_MS) {
29775
+ this.linkedMutedSuppressed.set(cameraId, suppressed + 1);
29776
+ return;
29777
+ }
29778
+ this.lastLinkedMutedReportAt.set(cameraId, now);
29779
+ this.linkedMutedSuppressed.set(cameraId, 0);
29780
+ this.logger.info("linked camera muted — left out of the sensor notification", {
29781
+ tags: { deviceId: cameraId },
29782
+ meta: {
29783
+ sensorId,
29784
+ reason: "muted",
29785
+ ...suppressed > 0 ? { alsoLeftOutSinceLastReport: suppressed } : {}
29786
+ }
29787
+ });
29788
+ }
29789
+ /**
29790
+ * ONE evaluation for one sensor state change (ADR 0632) — replaces the
29791
+ * per-camera fan-out when the sensor is linked to more than one camera.
29792
+ *
29793
+ * The linked cameras widen the MEDIA only — which cameras' stills ship —
29794
+ * never which rules fire. Matching is on the SENSOR and the cameras that
29795
+ * took a timeline row (`rowCameraIds`, not muted) — D630 §6, whatever the
29796
+ * number of linked cameras. The primary is only the camera the notification
29797
+ * leads with.
29798
+ *
29799
+ * The primary is re-derived here as the first linked camera that is NOT
29800
+ * muted (D62): a camera's mute drops only its own tile, and its marker is
29801
+ * then not the picture. Every linked camera muted ⇒ the sensor is its own
29802
+ * device and the notification is text-only. The MUTE of the event itself is
29803
+ * judged on the sensor ({@link NcRuleSubject.linkedSensorId}). A
29804
+ * `rule-device` cooldown is keyed by the primary. Same lossy boundary as
29805
+ * {@link onSensorEventPersisted}.
29806
+ */
29807
+ onSensorEvent(input) {
29808
+ this.observeOpeningEvent(input.event);
29809
+ const shown = this.unmutedCameras(input.linkedCameraIds);
29810
+ const muted = input.linkedCameraIds.filter((id) => !shown.includes(id));
29811
+ const primary = shown[0] ?? input.event.sourceDeviceId;
29812
+ const marker = primary === input.event.deviceId ? input.markerTrackId : void 0;
29813
+ this.consumeEvent(incomingFromSensorEvent({
29814
+ ...input.event,
29815
+ deviceId: primary
29816
+ }, marker, {
29817
+ linkedCameraIds: shown,
29818
+ rowCameraIds: this.unmutedCameras(input.rowCameraIds),
29819
+ mutedRowCameraIds: input.rowCameraIds.filter((id) => this.deviceMutes.isMuted(id)),
29820
+ ...input.linkedStills !== void 0 ? { linkedStills: input.linkedStills } : {}
29821
+ }, muted));
29822
+ }
29823
+ /** The linked cameras a sensor notification may show — not muted (D62), in order. */
29824
+ unmutedCameras(cameraIds) {
29825
+ return cameraIds.filter((id) => !this.deviceMutes.isMuted(id));
29826
+ }
29827
+ /**
29217
29828
  * The opening reading a sensor row carries — a contact, a cover or a lock,
29218
29829
  * read with D630's table (`alarmOpeningFromSensorEvent`) — handed to the
29219
29830
  * panel. A row that is not an opening, or whose word is unknown, hands over
@@ -30340,8 +30951,9 @@ var NotificationCenter = class NotificationCenter {
30340
30951
  outcomes,
30341
30952
  ...extra
30342
30953
  });
30343
- if (this.deviceMutes.isMuted(subject.deviceId) && controls.bypassMute !== true) {
30344
- this.reportMutedDrop(subject, kind, this.now());
30954
+ const muteDeviceId = this.mutedAuthority(subject);
30955
+ if (muteDeviceId !== void 0 && controls.bypassMute !== true) {
30956
+ this.reportMutedDrop(subject, muteDeviceId, kind, this.now());
30345
30957
  return report({ droppedBy: "muted" });
30346
30958
  }
30347
30959
  const delivery = deliveryForKind(kind);
@@ -30512,7 +31124,7 @@ var NotificationCenter = class NotificationCenter {
30512
31124
  buttons: unresolvable.join(", ")
30513
31125
  }
30514
31126
  });
30515
- if (!noOwnerReported && kind === "device-event" && subject.trackId === void 0 && rule.media.attach !== "none") {
31127
+ if (!noOwnerReported && kind === "device-event" && subject.trackId === void 0 && subject.linkedStills === void 0 && rule.media.attach !== "none") {
30516
31128
  noOwnerReported = true;
30517
31129
  const linked = subject.linkedCameraIds;
30518
31130
  const meta = {
@@ -30521,7 +31133,19 @@ var NotificationCenter = class NotificationCenter {
30521
31133
  ruleId: rule.id,
30522
31134
  rule: rule.name
30523
31135
  };
30524
- if (linked !== void 0) this.logger.debug(linked.length === 0 ? "device event from a sensor linked to no camera — this notification ships text-only" : `device event from a sensor linked to ${linked.length} camera(s), none opted into tracked events — this notification ships text-only`, {
31136
+ if (linked !== void 0 && linked.length === 0 && isLinkedSetSubject(subject)) this.logger.info("every linked camera is muted — this sensor notification ships text-only", {
31137
+ tags: { deviceId: subject.linkedSensorId ?? subject.deviceId },
31138
+ meta
31139
+ });
31140
+ else if (linked !== void 0 && isLinkedSetSubject(subject)) this.logger.warn("sensor event has no linked-camera pictures and no marker — this notification ships text-only", {
31141
+ tags: { deviceId: subject.sourceDeviceId ?? subject.deviceId },
31142
+ meta: {
31143
+ ...meta,
31144
+ linkedCameraIds: [...linked],
31145
+ snapshotWired: this.linkedStills !== null
31146
+ }
31147
+ });
31148
+ else if (linked !== void 0) this.logger.debug(linked.length === 0 ? "device event from a sensor linked to no camera — this notification ships text-only" : `device event from a sensor linked to ${linked.length} camera(s), none opted into tracked events — this notification ships text-only`, {
30525
31149
  tags: { deviceId: subject.deviceId },
30526
31150
  meta: {
30527
31151
  ...meta,
@@ -30778,14 +31402,26 @@ var NotificationCenter = class NotificationCenter {
30778
31402
  });
30779
31403
  }
30780
31404
  /**
31405
+ * The muted device that drops this subject, or `undefined` when none does.
31406
+ * A per-camera subject: its camera. A linked set: the sensor; else, when
31407
+ * the change took rows and every row camera is muted, the sensor too — the
31408
+ * line names the muted row cameras.
31409
+ */
31410
+ mutedAuthority(subject) {
31411
+ const sensorId = subject.linkedSensorId;
31412
+ if (sensorId === void 0) return this.deviceMutes.isMuted(subject.deviceId) ? subject.deviceId : void 0;
31413
+ if (this.deviceMutes.isMuted(sensorId)) return sensorId;
31414
+ return (subject.rowCameraIds ?? []).length === 0 && (subject.mutedRowCameraIds ?? []).length > 0 ? sensorId : void 0;
31415
+ }
31416
+ /**
30781
31417
  * One INFO line when a MUTED camera's event is dropped, bounded to one per
30782
31418
  * camera per window with the suppressed count folded into the next report —
30783
31419
  * identical shape to `reportNoMatch`, because the question an operator asks
30784
31420
  * is identical: "why did this camera not notify me?".
30785
31421
  */
30786
- reportMutedDrop(subject, kind, now) {
31422
+ reportMutedDrop(subject, mutedDeviceId, kind, now) {
30787
31423
  const bucket = noMatchReportKey({
30788
- deviceId: subject.deviceId,
31424
+ deviceId: mutedDeviceId,
30789
31425
  kind,
30790
31426
  classNames: subject.classNames
30791
31427
  });
@@ -30797,10 +31433,12 @@ var NotificationCenter = class NotificationCenter {
30797
31433
  }
30798
31434
  this.lastMutedReportAt.set(bucket, now);
30799
31435
  this.mutedSuppressed.set(bucket, 0);
30800
- this.logger.info("notifications muted for this camera — event dropped before rule evaluation", {
30801
- tags: { deviceId: subject.deviceId },
31436
+ const rowsMuted = subject.linkedSensorId !== void 0 && !this.deviceMutes.isMuted(subject.linkedSensorId);
31437
+ this.logger.info(subject.linkedSensorId === void 0 ? "notifications muted for this camera — event dropped before rule evaluation" : rowsMuted ? "every camera that took its row is muted — sensor event dropped before rule evaluation" : "notifications muted for this sensor — event dropped before rule evaluation", {
31438
+ tags: { deviceId: mutedDeviceId },
30802
31439
  meta: {
30803
31440
  kind,
31441
+ ...rowsMuted ? { mutedRowCameraIds: [...subject.mutedRowCameraIds ?? []] } : {},
30804
31442
  classes: subject.classNames,
30805
31443
  eventId: subject.recordId,
30806
31444
  ...subject.trackId !== void 0 ? { trackId: subject.trackId } : {},
@@ -30851,6 +31489,7 @@ var NotificationCenter = class NotificationCenter {
30851
31489
  const confirm = frozenConfirmPolicy(rule, isSystemEvent);
30852
31490
  const cropZoneIds = rule.conditions.zones !== void 0 ? rule.conditions.zones.ids : rule.conditions.occupancy?.zoneId !== void 0 ? [rule.conditions.occupancy.zoneId] : void 0;
30853
31491
  const allTargets = [...rule.targets, ...userTargets.filter((t) => !direct.has(t.targetId))];
31492
+ const linkedOwners = !noMedia && subject.linkedStills !== void 0 ? linkedMediaOwners(subject.linkedStills, linkedCameraMode(mediaRule.media)) : void 0;
30854
31493
  return (upgrade !== void 0 ? allTargets.filter((t) => upgrade.targetIds.includes(t.targetId)) : allTargets).filter((target) => !rule.disabledTargetIds.includes(target.targetId)).map((target) => {
30855
31494
  const base = {
30856
31495
  ruleName: rule.name,
@@ -30881,7 +31520,12 @@ var NotificationCenter = class NotificationCenter {
30881
31520
  ...target.params !== void 0 ? { params: target.params } : {},
30882
31521
  subject: {
30883
31522
  deviceId: subject.deviceId,
30884
- ...alarmSource?.trackId !== void 0 ? { trackId: alarmSource.trackId } : subject.trackId !== void 0 ? { trackId: subject.trackId } : {},
31523
+ ...alarmSource?.trackId !== void 0 ? { trackId: alarmSource.trackId } : linkedOwners !== void 0 ? {
31524
+ trackId: linkedOwners.trackId,
31525
+ ...linkedOwners.extraStills.length > 0 ? { extraStills: linkedOwners.extraStills.map((x) => ({ ...x })) } : {},
31526
+ analysisTiles: linkedOwners.analysisTiles.map((x) => ({ ...x }))
31527
+ } : subject.trackId !== void 0 ? { trackId: subject.trackId } : {},
31528
+ ...subject.linkedCameraIds !== void 0 && subject.linkedCameraIds.length > 1 && isLinkedSetSubject(subject) ? { linkedCameraIds: [...subject.linkedCameraIds] } : {},
30885
31529
  ...alarmSource?.eventId !== void 0 ? { eventId: alarmSource.eventId } : hasEventMedia ? { eventId: subject.recordId } : {},
30886
31530
  className: subject.classNames[0] ?? subject.sensorKind ?? "event",
30887
31531
  ...subject.label !== void 0 ? { label: subject.label } : {},
@@ -72260,6 +72904,20 @@ function hasWrappedDetection(entries) {
72260
72904
  return entries.some((e) => e.capName === "detection-pipeline" && e.kind === "wrapped");
72261
72905
  }
72262
72906
  //#endregion
72907
+ //#region src/pipeline-analytics/runtime/linked-snapshot-reads.ts
72908
+ function buildLinkedSnapshotReads(snapshot) {
72909
+ return {
72910
+ getSnapshotState: async (deviceId) => {
72911
+ return { reason: (await snapshot.getDebugState.query({ deviceId })).state.reason };
72912
+ },
72913
+ getFrameCapturedAt: async (deviceIds) => {
72914
+ if (deviceIds.length === 0) return /* @__PURE__ */ new Map();
72915
+ const rows = await snapshot.getSnapshotOverview.query({ deviceIds: [...deviceIds] });
72916
+ return new Map(rows.map((r) => [r.deviceId, r.lastCapturedAt]));
72917
+ }
72918
+ };
72919
+ }
72920
+ //#endregion
72263
72921
  //#region src/pipeline-analytics/runtime/native-crop-dedupe.ts
72264
72922
  var NativeCropDedupe = class {
72265
72923
  config;
@@ -73868,6 +74526,59 @@ async function resolveSensorEventCameras(cache, data) {
73868
74526
  };
73869
74527
  }
73870
74528
  /**
74529
+ * The cameras a NOTIFICATION about this sensor shows — the emitting device
74530
+ * itself when it is a camera that may self-emit this cap, then every camera
74531
+ * that links it, opt-in or not (ADR 0632). The order is the mosaic's tile order
74532
+ * and names the PRIMARY camera (the first). Deliberately a sibling of
74533
+ * resolveSensorEventCameras rather than a flag on it: that one decides which
74534
+ * timeline rows exist and must keep honouring the opt-in.
74535
+ *
74536
+ * `[]` is NOT knowledge. It answers both "no camera links this sensor" and
74537
+ * "the camera index has not answered yet" (cold start, no camera list read —
74538
+ * this function does not consult `answered()`). A caller must read `[]` (and a
74539
+ * single camera) as "no mosaic this time, fall back to the plain path", never
74540
+ * as a durable "linked to nothing" that drops or deletes work (D49).
74541
+ */
74542
+ async function resolveLinkedMediaCameras(cache, data) {
74543
+ const linked = await cache.allCamerasFor(data.deviceId);
74544
+ return [...await cache.isCamera(data.deviceId) && selfCameraMayEmit(data.capName) ? [data.deviceId] : [], ...linked.filter((id) => id !== data.deviceId)];
74545
+ }
74546
+ var NO_SENSOR_NOTIFICATION_CAMERAS = {
74547
+ mediaCameraIds: [],
74548
+ rowCameraIds: []
74549
+ };
74550
+ /**
74551
+ * Which cameras a notification about this change shows, known BEFORE the
74552
+ * ingest runs, so the capture can start at the trigger.
74553
+ *
74554
+ * Only a change the ingest EVALUATES has any: a mapped cap that takes rows
74555
+ * (`dropReason` null) or an unowned sensor (`no-camera`, D630 §6). A camera's
74556
+ * own `motion` no camera opted in (`camera-native-cap`) and a cold index
74557
+ * (`camera-index-unknown`) are drops today, and a camera merely LINKING the
74558
+ * device must not turn a drop into a notification. Asks the SAME resolution
74559
+ * the ingest asks (`resolveSensorEventCameras`), off the same cache.
74560
+ */
74561
+ async function resolveSensorNotificationCameras(cache, data) {
74562
+ if (require_dist.EVENT_KIND_BY_CAP[data.capName] === void 0) return NO_SENSOR_NOTIFICATION_CAMERAS;
74563
+ const rows = await resolveSensorEventCameras(cache, data);
74564
+ if (rows.dropReason !== null && rows.dropReason !== "no-camera") return NO_SENSOR_NOTIFICATION_CAMERAS;
74565
+ return {
74566
+ mediaCameraIds: await resolveLinkedMediaCameras(cache, data),
74567
+ rowCameraIds: rows.cameraIds
74568
+ };
74569
+ }
74570
+ /**
74571
+ * A sensor slice as a row's `value`: the object it is, or `null` for anything
74572
+ * else (absent, a primitive, an array) — one narrowing for every sensor event
74573
+ * built from a `DeviceStateChanged`.
74574
+ */
74575
+ function sensorSliceRecord(slice) {
74576
+ return isSliceRecord(slice) ? slice : null;
74577
+ }
74578
+ function isSliceRecord(slice) {
74579
+ return typeof slice === "object" && slice !== null && !Array.isArray(slice);
74580
+ }
74581
+ /**
73871
74582
  * One `DeviceStateChanged` → N history rows, one per camera the event belongs
73872
74583
  * to: the emitting device's LINKED cameras, plus the emitting device ITSELF
73873
74584
  * when it is a camera carrying the sensor cap (a doorbell wrapper bound on
@@ -73883,8 +74594,7 @@ async function ingestSensorStateChange(deps, data, timestamp) {
73883
74594
  const descriptor = require_dist.EVENT_KIND_BY_CAP[data.capName];
73884
74595
  if (descriptor === void 0) return 0;
73885
74596
  const { cameraIds, dropReason, linkedCameraIds } = await resolveSensorEventCameras(deps.cache, data);
73886
- const slice = data.slice;
73887
- const value = slice !== null && slice !== void 0 && typeof slice === "object" && !Array.isArray(slice) ? slice : null;
74597
+ const value = sensorSliceRecord(data.slice);
73888
74598
  const makeId = deps.makeId ?? (() => `pa-sensor-${(0, node_crypto.randomUUID)()}`);
73889
74599
  if (dropReason === "no-camera" && deps.onUnowned !== void 0) {
73890
74600
  const ev = {
@@ -74863,8 +75573,14 @@ var MotionEventSnapshotCapturer = class {
74863
75573
  /**
74864
75574
  * Project one `DeviceStateChanged` of a mapped sensor/control cap into a
74865
75575
  * synthetic track per camera the event belongs to. Returns the number of
74866
- * markers that landed. Best-effort (telemetry, D8) — a materializer that
74867
- * throws propagates to the caller, which logs it.
75576
+ * markers that landed. Best-effort (telemetry, D8).
75577
+ *
75578
+ * Every camera is materialized CONCURRENTLY — the notification about this
75579
+ * event waits for the markers, so N cameras cost one snapshot bound, not N —
75580
+ * and reported afterwards in camera order. A materializer that throws for one
75581
+ * camera no longer propagates to the caller (where it was logged against the
75582
+ * SENSOR): it is reported as `not-materialized` on ITS camera, carrying the
75583
+ * rejection's message in `error`, and the other cameras still land.
74868
75584
  */
74869
75585
  async function projectSensorMarkers(deps, data, timestamp) {
74870
75586
  const descriptor = require_dist.EVENT_KIND_BY_CAP[data.capName];
@@ -74890,26 +75606,30 @@ async function projectSensorMarkers(deps, data, timestamp) {
74890
75606
  return 0;
74891
75607
  }
74892
75608
  const producingDeviceName = await deps.producingDeviceName(data.deviceId);
75609
+ const settled = await Promise.allSettled(cameraIds.map((cameraId) => deps.markers.materialize({
75610
+ cameraId,
75611
+ sourceDeviceId: data.deviceId,
75612
+ source: "sensor",
75613
+ kind: descriptor.kind,
75614
+ timestamp,
75615
+ snapshotTimeoutMs: deps.snapshotTimeoutMs ?? 2500,
75616
+ ...producingDeviceName !== void 0 ? { producingDeviceName } : {}
75617
+ })));
74893
75618
  let landed = 0;
74894
- for (const cameraId of cameraIds) {
74895
- const track = await deps.markers.materialize({
74896
- cameraId,
74897
- sourceDeviceId: data.deviceId,
74898
- source: "sensor",
74899
- kind: descriptor.kind,
74900
- timestamp,
74901
- snapshotTimeoutMs: deps.snapshotTimeoutMs ?? 2500,
74902
- ...producingDeviceName !== void 0 ? { producingDeviceName } : {}
74903
- });
75619
+ settled.forEach((outcome, i) => {
75620
+ const cameraId = cameraIds[i];
75621
+ if (cameraId === void 0) return;
75622
+ const track = outcome.status === "fulfilled" ? outcome.value : null;
74904
75623
  if (track === null) {
74905
75624
  deps.onSkipped({
74906
75625
  cameraId,
74907
75626
  sourceDeviceId: data.deviceId,
74908
75627
  capName: data.capName,
74909
75628
  kind: descriptor.kind,
74910
- reason: "not-materialized"
75629
+ reason: "not-materialized",
75630
+ ...outcome.status === "rejected" ? { error: require_dist.errMsg(outcome.reason) } : {}
74911
75631
  });
74912
- continue;
75632
+ return;
74913
75633
  }
74914
75634
  landed++;
74915
75635
  deps.onProjected({
@@ -74921,7 +75641,7 @@ async function projectSensorMarkers(deps, data, timestamp) {
74921
75641
  selfCamera: cameraId === data.deviceId,
74922
75642
  hasMedia: track.snapshots.length > 0
74923
75643
  });
74924
- }
75644
+ });
74925
75645
  return landed;
74926
75646
  }
74927
75647
  //#endregion
@@ -80070,6 +80790,14 @@ var RETRAIN_EXPORT_MAX = 2e4;
80070
80790
  * surface to turn the refinement pipeline on/off for a camera.
80071
80791
  */
80072
80792
  var TTL_SWEEP_INTERVAL_MS = 5e3;
80793
+ /**
80794
+ * How long shutdown waits for the sensor handlers already running. Just above
80795
+ * the marker's bounded snapshot fetch (`SENSOR_MARKER_SNAPSHOT_TIMEOUT_MS`,
80796
+ * 2.5 s), the one long await a handler makes, and BELOW the kernel's SIGKILL
80797
+ * fallback (process-service.ts: 3 s after SIGTERM on the stop-all path, 5 s on
80798
+ * the others) — a longer drain would be killed mid-way and log nothing.
80799
+ */
80800
+ var SENSOR_HANDLER_DRAIN_MS = 2700;
80073
80801
  /** Throttle for the group-shot gate's window line (D470). */
80074
80802
  var GROUP_SHOT_METRIC_INTERVAL_MS = 3e4;
80075
80803
  /**
@@ -81140,6 +81868,14 @@ var PipelineAnalyticsAddon = class PipelineAnalyticsAddon extends require_dist.B
81140
81868
  getNativeKeyFrameRgb = null;
81141
81869
  shuttingDown = false;
81142
81870
  /**
81871
+ * Sensor handlers the bus dispatched under `void` that have not finished.
81872
+ * `onShutdown` DRAINS them before it tears anything down: a handler awaits a
81873
+ * snapshot for its marker before its last context read, and one left running
81874
+ * across the teardown threw "ctx accessed before initialize()" as an
81875
+ * unhandled rejection with no device on it.
81876
+ */
81877
+ sensorHandlersInFlight = /* @__PURE__ */ new Set();
81878
+ /**
81143
81879
  * Per-device delivery-lag windows, folded at `handleInferenceResult` entry.
81144
81880
  * The instrument that tells a late DELIVERY (starved) apart from a slow
81145
81881
  * `processFrame` (waiting) — see `frame-lag-observer.ts`. Costs one map read
@@ -81686,7 +82422,7 @@ var PipelineAnalyticsAddon = class PipelineAnalyticsAddon extends require_dist.B
81686
82422
  onMotionAnalysis: (deviceId, data, timestampMs) => this.handleMotionAnalysis(deviceId, data, timestampMs),
81687
82423
  onOnboardMotion: (deviceId, data, timestampMs) => this.handleOnboardMotion(deviceId, data, timestampMs),
81688
82424
  onBatterySample: (deviceId, percentage, at) => this.lts?.note("battery", deviceId, percentage, at),
81689
- onSensorStateChanged: (data, timestampMs) => this.handleSensorStateChanged(data, timestampMs),
82425
+ onSensorStateChanged: (data, timestampMs) => this.dispatchSensorStateChanged(data, timestampMs),
81690
82426
  onBindingsChanged: (data) => this.handleBindingsChangedEvent(data),
81691
82427
  onDeviceUnregistered: (deviceId) => this.handleDeviceUnregisteredEvent(deviceId),
81692
82428
  onClusterTopology: (nodes) => this.nodeLiveness.applySnapshot(nodes, Date.now()),
@@ -82376,10 +83112,13 @@ var PipelineAnalyticsAddon = class PipelineAnalyticsAddon extends require_dist.B
82376
83112
  snapshot: { getSnapshot: (i) => api.snapshot.getSnapshot.query(i) },
82377
83113
  media: mediaStore,
82378
83114
  tracks: trackStore,
82379
- onError: (scope, err) => logger.warn("synthetic track error", { meta: {
82380
- scope,
82381
- error: require_dist.errMsg(err)
82382
- } })
83115
+ onError: (scope, err, deviceId) => logger.warn("synthetic track error", {
83116
+ ...deviceId !== void 0 ? { tags: { deviceId } } : {},
83117
+ meta: {
83118
+ scope,
83119
+ error: require_dist.errMsg(err)
83120
+ }
83121
+ })
82383
83122
  });
82384
83123
  this.syntheticTracks = syntheticTracks;
82385
83124
  this.motionEventSnapshots = new MotionEventSnapshotCapturer({
@@ -82686,6 +83425,7 @@ var PipelineAnalyticsAddon = class PipelineAnalyticsAddon extends require_dist.B
82686
83425
  },
82687
83426
  isDeviceDeleted: async (deviceId) => await api.deviceManager.getDevice.query({ deviceId }) === null,
82688
83427
  getSnapshot: (deviceId) => api.snapshot.getSnapshot.query({ deviceId }),
83428
+ ...buildLinkedSnapshotReads(api.snapshot),
82689
83429
  identityIdsByName: async () => {
82690
83430
  const byName = /* @__PURE__ */ new Map();
82691
83431
  const identities = await stores.identityStore.listIdentities();
@@ -84221,7 +84961,7 @@ var PipelineAnalyticsAddon = class PipelineAnalyticsAddon extends require_dist.B
84221
84961
  this.alarmPanelConvergence = null;
84222
84962
  for (const unsub of this.subscriptionUnsubs) unsub();
84223
84963
  this.subscriptionUnsubs = [];
84224
- await this.motionEpisodes?.closeAll("addon-shutdown");
84964
+ await Promise.all([this.drainSensorHandlers(), this.motionEpisodes?.closeAll("addon-shutdown")]);
84225
84965
  await this.embeddingDispatcher?.stop();
84226
84966
  this.embeddingDispatcher = null;
84227
84967
  await this.notificationCenter?.stop();
@@ -88531,11 +89271,118 @@ var PipelineAnalyticsAddon = class PipelineAnalyticsAddon extends require_dist.B
88531
89271
  return this.queryFacade.getSensorEvents(input);
88532
89272
  }
88533
89273
  /**
89274
+ * Start the linked set's capture (ADR 0632) with the UNFILTERED camera list:
89275
+ * the centre applies the mute itself and says so per camera.
89276
+ */
89277
+ startLinkedStills(data, timestamp, cameras) {
89278
+ const sensorKind = require_dist.EVENT_KIND_BY_CAP[data.capName]?.kind;
89279
+ if (sensorKind === void 0) return void 0;
89280
+ try {
89281
+ return this.notificationCenter?.beginLinkedStills({
89282
+ sensorId: data.deviceId,
89283
+ sensorKind,
89284
+ cameraIds: cameras.mediaCameraIds,
89285
+ rowCameraIds: cameras.rowCameraIds,
89286
+ atMs: timestamp
89287
+ });
89288
+ } catch (err) {
89289
+ this.ctx.logger.warn("linked-camera capture could not start — the notification ships without it", {
89290
+ tags: { deviceId: data.deviceId },
89291
+ meta: {
89292
+ capName: data.capName,
89293
+ cameraIds: [...cameras.mediaCameraIds],
89294
+ error: require_dist.errMsg(err)
89295
+ }
89296
+ });
89297
+ return;
89298
+ }
89299
+ }
89300
+ /**
89301
+ * The ONE sensor-level evaluation of a linked set (ADR 0632). Its record is
89302
+ * the primary camera's row when that camera has one, else another camera's
89303
+ * row, else a camera-attributed event that is NOT a timeline row (no linking
89304
+ * camera opted the sensor in). The cameras that took a row travel as
89305
+ * `rowCameraIds`: with the sensor, what a camera-scoped rule matches on
89306
+ * (D630 §6).
89307
+ */
89308
+ handOffLinkedSensorEvent(input) {
89309
+ const { data, timestamp, persisted } = input;
89310
+ const primary = input.mediaCameraIds[0];
89311
+ if (primary === void 0) return;
89312
+ const event = persisted.find((ev) => ev.deviceId === primary) ?? persisted[0] ?? {
89313
+ id: `pa-sensor-${(0, node_crypto.randomUUID)()}`,
89314
+ deviceId: primary,
89315
+ sourceDeviceId: data.deviceId,
89316
+ kind: require_dist.EVENT_KIND_BY_CAP[data.capName]?.kind ?? data.capName,
89317
+ value: sensorSliceRecord(data.slice),
89318
+ timestamp
89319
+ };
89320
+ const markerTrackId = input.markerByCamera.get(primary)?.trackId;
89321
+ try {
89322
+ this.notificationCenter?.onSensorEvent({
89323
+ event: {
89324
+ ...event,
89325
+ deviceId: primary
89326
+ },
89327
+ linkedCameraIds: input.mediaCameraIds,
89328
+ rowCameraIds: persisted.map((ev) => ev.deviceId),
89329
+ ...markerTrackId !== void 0 ? { markerTrackId } : {},
89330
+ ...input.linkedStills !== void 0 ? { linkedStills: input.linkedStills } : {}
89331
+ });
89332
+ } catch (err) {
89333
+ this.ctx.logger.warn("sensor event hand-off to the notification centre failed", {
89334
+ tags: { deviceId: data.deviceId },
89335
+ meta: {
89336
+ kind: event.kind,
89337
+ linkedCameraIds: [...input.mediaCameraIds],
89338
+ error: require_dist.errMsg(err)
89339
+ }
89340
+ });
89341
+ }
89342
+ }
89343
+ /**
89344
+ * The bus's door into {@link handleSensorStateChanged}: tracked, so shutdown
89345
+ * can drain it, and caught, so a throw is a tagged line instead of an
89346
+ * unhandled rejection. Refused once shutdown began.
89347
+ */
89348
+ dispatchSensorStateChanged(data, timestampMs) {
89349
+ if (this.shuttingDown) return Promise.resolve();
89350
+ const run = this.handleSensorStateChanged(data, timestampMs).catch((err) => {
89351
+ this.ctxIfReady?.logger.warn("sensor state change handler failed", {
89352
+ tags: { deviceId: data.deviceId },
89353
+ meta: {
89354
+ capName: data.capName,
89355
+ error: require_dist.errMsg(err)
89356
+ }
89357
+ });
89358
+ });
89359
+ this.sensorHandlersInFlight.add(run);
89360
+ run.finally(() => this.sensorHandlersInFlight.delete(run));
89361
+ return run;
89362
+ }
89363
+ /** Wait for the in-flight sensor handlers, bounded — see {@link sensorHandlersInFlight}. */
89364
+ async drainSensorHandlers() {
89365
+ const inFlight = [...this.sensorHandlersInFlight];
89366
+ if (inFlight.length === 0) return;
89367
+ let timer;
89368
+ const bound = new Promise((resolve) => {
89369
+ timer = setTimeout(() => resolve("bound"), SENSOR_HANDLER_DRAIN_MS);
89370
+ });
89371
+ const outcome = await Promise.race([Promise.all(inFlight).then(() => "drained"), bound]);
89372
+ clearTimeout(timer);
89373
+ if (outcome === "bound") this.ctx.logger.warn("shutdown: sensor handlers still running past the drain bound", { meta: {
89374
+ inFlight: this.sensorHandlersInFlight.size,
89375
+ boundMs: SENSOR_HANDLER_DRAIN_MS
89376
+ } });
89377
+ }
89378
+ /**
88534
89379
  * Sensor-event ingest handler — `DeviceStateChanged` of a device exposing a
88535
89380
  * mapped sensor cap. Resolves the camera set through the TTL cache (the
88536
89381
  * device's LINKED cameras, plus the device itself when it is a camera
88537
89382
  * carrying the cap) and inserts ONE row per camera. Best-effort
88538
- * (telemetry-lossy).
89383
+ * (telemetry-lossy). The NOTIFICATION is not per row when more than one
89384
+ * camera links the sensor (ADR 0632): the linked cameras are photographed at
89385
+ * the trigger and the change is evaluated ONCE, at the sensor level.
88539
89386
  *
88540
89387
  * D8/D11 boundary, stated plainly: the ride here is the LOSSY
88541
89388
  * `DeviceStateChanged` bus, and there is no reconcile that replays a missed
@@ -88556,6 +89403,18 @@ var PipelineAnalyticsAddon = class PipelineAnalyticsAddon extends require_dist.B
88556
89403
  const cache = this.linkedCamerasCache;
88557
89404
  if (store === null || cache === null) return;
88558
89405
  if (!this.sensorSliceCarriedATransition(data)) return;
89406
+ const cameras = await resolveSensorNotificationCameras(cache, data).catch((err) => {
89407
+ this.ctx.logger.debug("linked-camera resolution failed — evaluated per row", {
89408
+ tags: { deviceId: data.deviceId },
89409
+ meta: {
89410
+ capName: data.capName,
89411
+ error: require_dist.errMsg(err)
89412
+ }
89413
+ });
89414
+ return NO_SENSOR_NOTIFICATION_CAMERAS;
89415
+ });
89416
+ const linkedSet = cameras.mediaCameraIds.length > 1;
89417
+ const linkedStills = linkedSet ? this.startLinkedStills(data, timestamp, cameras) : void 0;
88559
89418
  const persisted = [];
88560
89419
  const unowned = [];
88561
89420
  try {
@@ -88600,18 +89459,33 @@ var PipelineAnalyticsAddon = class PipelineAnalyticsAddon extends require_dist.B
88600
89459
  }
88601
89460
  });
88602
89461
  },
88603
- onSkipped: (r) => this.ctx.logger.debug("synthetic sensor-track NOT projected", {
88604
- tags: { deviceId: r.cameraId ?? r.sourceDeviceId },
88605
- meta: {
88606
- capName: r.capName,
88607
- kind: r.kind,
88608
- reason: r.reason,
88609
- sourceDeviceId: r.sourceDeviceId
89462
+ onSkipped: (r) => {
89463
+ if (r.error !== void 0) {
89464
+ this.ctx.logger.warn("synthetic sensor-track materialize rejected", {
89465
+ tags: { deviceId: r.cameraId ?? r.sourceDeviceId },
89466
+ meta: {
89467
+ capName: r.capName,
89468
+ kind: r.kind,
89469
+ reason: r.reason,
89470
+ sourceDeviceId: r.sourceDeviceId,
89471
+ error: r.error
89472
+ }
89473
+ });
89474
+ return;
88610
89475
  }
88611
- })
89476
+ this.ctx.logger.debug("synthetic sensor-track NOT projected", {
89477
+ tags: { deviceId: r.cameraId ?? r.sourceDeviceId },
89478
+ meta: {
89479
+ capName: r.capName,
89480
+ kind: r.kind,
89481
+ reason: r.reason,
89482
+ sourceDeviceId: r.sourceDeviceId
89483
+ }
89484
+ });
89485
+ }
88612
89486
  }, data, timestamp);
88613
89487
  } catch (err) {
88614
- this.ctx.logger.warn("synthetic sensor-track materialize failed", {
89488
+ this.ctx.logger.warn("synthetic sensor-track camera resolution / producing-device name read failed", {
88615
89489
  tags: { deviceId: data.deviceId },
88616
89490
  meta: {
88617
89491
  capName: data.capName,
@@ -88619,6 +89493,17 @@ var PipelineAnalyticsAddon = class PipelineAnalyticsAddon extends require_dist.B
88619
89493
  }
88620
89494
  });
88621
89495
  }
89496
+ if (linkedSet) {
89497
+ this.handOffLinkedSensorEvent({
89498
+ data,
89499
+ timestamp,
89500
+ mediaCameraIds: cameras.mediaCameraIds,
89501
+ persisted,
89502
+ markerByCamera,
89503
+ ...linkedStills !== void 0 ? { linkedStills } : {}
89504
+ });
89505
+ return;
89506
+ }
88622
89507
  for (const ev of persisted) try {
88623
89508
  this.notificationCenter?.onSensorEventPersisted(ev, markerByCamera.get(ev.deviceId)?.trackId);
88624
89509
  } catch (err) {