@camstack/addon-pipeline 1.2.146 → 1.2.148

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.
Files changed (37) hide show
  1. package/dist/audio-analyzer/index.js +2 -2
  2. package/dist/audio-analyzer/index.mjs +2 -2
  3. package/dist/detection-pipeline/index.js +8 -6
  4. package/dist/detection-pipeline/index.mjs +7 -5
  5. package/dist/{dist-DML3mpn9.js → dist-DLy_uz82.js} +121 -13
  6. package/dist/{dist-cZopp8Xm.mjs → dist-DjplinYP.mjs} +121 -13
  7. package/dist/{lazy-sharp-BzXIjfN8.js → lazy-sharp-BI4LsfMM.js} +1 -1
  8. package/dist/{local-frame-registry-Ctv_TzmF.mjs → local-frame-registry-77FL9ua_.mjs} +1 -1
  9. package/dist/{local-frame-registry-DO8-LuSo.js → local-frame-registry-Dr_U_xCG.js} +1 -1
  10. package/dist/motion-wasm/index.js +2 -2
  11. package/dist/motion-wasm/index.mjs +1 -1
  12. package/dist/{node-OvVqe9eh.js → node-BHFLhfkh.js} +1 -1
  13. package/dist/{node-Br6p9KvD.mjs → node-D7uxWSXD.mjs} +1 -1
  14. package/dist/pipeline-runner/index.js +5 -5
  15. package/dist/pipeline-runner/index.mjs +4 -4
  16. package/dist/{process-memory-DX25Z60Q.mjs → process-memory-B2tApNua.mjs} +1 -1
  17. package/dist/{process-memory-NWKrKfmi.js → process-memory-M8WiR3qj.js} +1 -1
  18. package/dist/recorder/index.js +619 -381
  19. package/dist/recorder/index.mjs +619 -381
  20. package/dist/{segment-demux-js-DGmFQ1Zj.mjs → segment-demux-js-3niBZUpJ.mjs} +1 -1
  21. package/dist/{segment-demux-js-CerfMroc.js → segment-demux-js-Cc_If7C_.js} +1 -1
  22. package/dist/session-decode/decode-worker-child.js +2 -2
  23. package/dist/session-decode/decode-worker-child.mjs +1 -1
  24. package/dist/stream-broker/_stub.js +2 -2
  25. package/dist/stream-broker/{_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-DQNgiTjz.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-QfvsYvjB.mjs} +3 -3
  26. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-DXrU11Bz.mjs +26 -0
  27. package/dist/stream-broker/{_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-bjYJYwAq.mjs → _virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-CgIcw5Wl.mjs} +1 -1
  28. package/dist/stream-broker/demux-worker-child.js +1 -1
  29. package/dist/stream-broker/demux-worker-child.mjs +1 -1
  30. package/dist/stream-broker/{hostInit-NShcJE25.mjs → hostInit-Dd2CEvDK.mjs} +3 -3
  31. package/dist/stream-broker/index.js +3 -3
  32. package/dist/stream-broker/index.mjs +3 -3
  33. package/dist/stream-broker/remoteEntry.js +1 -1
  34. package/dist/{worker-protocol-CUCQ1IPR.mjs → worker-protocol-Cvln9GmS.mjs} +1 -1
  35. package/dist/{worker-protocol-Dt3zWCQY.js → worker-protocol-basMNc_q.js} +1 -1
  36. package/package.json +1 -1
  37. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-D4-thZGg.mjs +0 -26
@@ -1,5 +1,5 @@
1
- import { $ as isFirstLevelMacroClass, $t as record, B as defineCustomActions, Bt as nodePin, E as RecordingConfigSchema, It as hydrateSchema, J as evaluateSensorEdge, Kt as array, L as customAction, N as batteryCapability, Nt as DeviceFeature, Pt as DeviceType, Qt as object, T as RECORDING_EXPORT_MAX_READ_BYTES, U as deriveRecordingMode, Ut as selectAssignedProfileSlots, V as deriveBatteryPresence, Zt as number, bt as storageEvictableCapability, d as DEFAULT_EVENTS_BAND_BUFFER_SEC, en as string, et as loadContributionCapability, g as ExportRecordSchema, i as BatteryStatusSchema, jt as BaseAddon, mt as recordingExportCapability, nn as EventCategory, pt as recordingCapability, qt as boolean, vt as resolveRecordingProfiles, wt as errMsg, x as OpsLogEntrySchema } from "../dist-cZopp8Xm.mjs";
2
- import { i as NO_COST_CLAIM, t as ChildCostRegistry } from "../node-Br6p9KvD.mjs";
1
+ import { $ as isFirstLevelMacroClass, $t as record, B as defineCustomActions, Bt as nodePin, E as RecordingConfigSchema, It as hydrateSchema, J as evaluateSensorEdge, Kt as array, L as customAction, N as batteryCapability, Nt as DeviceFeature, Pt as DeviceType, Qt as object, T as RECORDING_EXPORT_MAX_READ_BYTES, U as deriveRecordingMode, Ut as selectAssignedProfileSlots, V as deriveBatteryPresence, Zt as number, bt as storageEvictableCapability, d as DEFAULT_EVENTS_BAND_BUFFER_SEC, en as string, et as loadContributionCapability, g as ExportRecordSchema, i as BatteryStatusSchema, jt as BaseAddon, mt as recordingExportCapability, nn as EventCategory, pt as recordingCapability, qt as boolean, vt as resolveRecordingProfiles, wt as errMsg, x as OpsLogEntrySchema } from "../dist-DjplinYP.mjs";
2
+ import { i as NO_COST_CLAIM, t as ChildCostRegistry } from "../node-D7uxWSXD.mjs";
3
3
  import { t as resolveHubHostname } from "../hub-hostname-cCknRYKj.mjs";
4
4
  import { r as withRecordingIntent } from "../restream-intent-B4BXZra7.mjs";
5
5
  import { n as startEventLoopStallMonitor } from "../event-loop-stall-monitor-DXLNBMkY.mjs";
@@ -49,321 +49,6 @@ function subscribeEventCapture(deps) {
49
49
  });
50
50
  }
51
51
  //#endregion
52
- //#region src/recorder/object-trigger.ts
53
- /**
54
- * Il gate fra `pipeline-analytics.detection-event` e "apri una finestra di
55
- * registrazione".
56
- *
57
- * Fratello di `recorder/event-capture.ts` e per lo stesso motivo: la qualifica
58
- * ha dei rami, e un ramo che scarta lavoro senza dirlo è indistinguibile da una
59
- * funzione mai cablata. Ogni verdetto negativo NOMINA il motivo, e il chiamante
60
- * lo logga.
61
- *
62
- * Puro: nessun bus, nessun orologio, nessuna config. La scelta di QUALI classi
63
- * ascoltare è della banda (`bandTriggerSources`); qui si decide solo se
64
- * l'evento è una detection utilizzabile e di che macro classe è.
65
- *
66
- * ## Perché la forma è DISCRIMINATA su `kind` (2026-08-29)
67
- *
68
- * Fino al 2026-08-29 questo file dichiarava UNA sola forma piatta — quella
69
- * dell'evento `object` — e la pretendeva da OGNI payload del topic. Ma
70
- * `EventCategory.PipelineAnalyticsDetectionEvent` è un topic condiviso da tre
71
- * emettitori in `addon-post-analysis/src/pipeline-analytics/index.ts`: object
72
- * (`className`, `source`, `confidence`, `zones`), motion e audio — e motion e
73
- * audio non portano `className`, perché non ne hanno una. Il risultato misurato:
74
- * `malformed` su **394 righe campionate su 394**, a 3.3–3.9 eventi/s, per
75
- * settimane. `malformed` significa "l'emettitore è andato in deriva" ed era
76
- * invece il traffico normale del topic; l'unico secchio che poteva segnalare
77
- * una vera rottura di protocollo era saturo al 100% di eventi sani, quindi
78
- * inservibile — ed è stato letto come "il trigger object non ha mai funzionato".
79
- *
80
- * Quindi: si valida prima la BUSTA comune (`deviceId`, `kind`, `timestamp`),
81
- * poi si discrimina su `kind`, e solo il ramo `object` pretende i campi
82
- * dell'object. Un `object` senza `className` resta un difetto e ha il suo nome
83
- * (`malformed-object`), distinto da una busta illeggibile.
84
- */
85
- /** Il `kind` dell'unico ramo del topic che può aprire una finestra. */
86
- var OBJECT_EVENT_KIND = "object";
87
- /** La sorgente implicita delle righe legacy senza `source` (`DetectionSourceSchema`). */
88
- var DEFAULT_DETECTION_SOURCE = "pipeline";
89
- /** Type guard, non cast: `event.data` è `unknown` finché non passa di qui. */
90
- function isDetectionEventEnvelope(value) {
91
- if (typeof value !== "object" || value === null) return false;
92
- if (!("deviceId" in value) || typeof value.deviceId !== "number") return false;
93
- if (!Number.isFinite(value.deviceId)) return false;
94
- if (!("kind" in value) || typeof value.kind !== "string") return false;
95
- if (!("timestamp" in value) || typeof value.timestamp !== "number") return false;
96
- if (!Number.isFinite(value.timestamp) || value.timestamp <= 0) return false;
97
- return true;
98
- }
99
- /** I campi che SOLO il ramo object porta. Chiamata dopo la busta. */
100
- function isObjectDetectionEventData(value) {
101
- if (!("className" in value) || typeof value.className !== "string") return false;
102
- if ("source" in value && value.source !== void 0 && typeof value.source !== "string") return false;
103
- return true;
104
- }
105
- function qualifyObjectTrigger(data) {
106
- if (!isDetectionEventEnvelope(data)) return {
107
- qualified: false,
108
- reason: "malformed"
109
- };
110
- const deviceId = data.deviceId;
111
- if (data.kind !== OBJECT_EVENT_KIND) return {
112
- qualified: false,
113
- reason: "not-object",
114
- deviceId
115
- };
116
- if (!isObjectDetectionEventData(data)) return {
117
- qualified: false,
118
- reason: "malformed-object",
119
- deviceId
120
- };
121
- if ((data.source ?? DEFAULT_DETECTION_SOURCE) !== DEFAULT_DETECTION_SOURCE) return {
122
- qualified: false,
123
- reason: "not-pipeline",
124
- deviceId
125
- };
126
- const className = data.className.trim().toLowerCase();
127
- if (!isFirstLevelMacroClass(className)) return {
128
- qualified: false,
129
- reason: "not-a-macro",
130
- deviceId
131
- };
132
- return {
133
- qualified: true,
134
- deviceId,
135
- macroClass: className,
136
- atMs: data.timestamp
137
- };
138
- }
139
- //#endregion
140
- //#region src/recorder/object-trigger-health.ts
141
- /** Ampiezza della finestra di aggregazione. Un minuto: abbastanza corto perché
142
- * la riga arrivi entro il primo minuto di un deploy rotto, abbastanza lungo
143
- * perché a 4 eventi/s il campione sia significativo. */
144
- var OBJECT_TRIGGER_HEALTH_WINDOW_MS = 6e4;
145
- function emptyTally() {
146
- return {
147
- objectEvents: 0,
148
- qualified: 0,
149
- otherKinds: 0,
150
- byReason: /* @__PURE__ */ new Map()
151
- };
152
- }
153
- function dominantReason(byReason) {
154
- let reason = null;
155
- let best = 0;
156
- const counts = {};
157
- for (const [r, n] of byReason) {
158
- counts[r] = n;
159
- if (n > best) {
160
- best = n;
161
- reason = r;
162
- }
163
- }
164
- return {
165
- reason,
166
- counts
167
- };
168
- }
169
- var ObjectTriggerHealth = class {
170
- windowMs;
171
- minSample;
172
- buckets = /* @__PURE__ */ new Map();
173
- windowStartMs = null;
174
- constructor(windowMs = OBJECT_TRIGGER_HEALTH_WINDOW_MS, minSample = 5) {
175
- this.windowMs = windowMs;
176
- this.minSample = minSample;
177
- }
178
- /**
179
- * Registra un verdetto e, se la finestra si è chiusa con questo evento,
180
- * restituisce i report da stampare (e riapre la finestra). Nessun timer:
181
- * il feed viaggia a ~4/s, quindi la chiusura arriva sempre in tempo, e una
182
- * finestra che non si chiude è una finestra in cui non è successo nulla.
183
- */
184
- record(verdict, nowMs) {
185
- const reports = this.windowStartMs !== null && nowMs - this.windowStartMs >= this.windowMs ? this.drain(nowMs) : [];
186
- this.windowStartMs ??= nowMs;
187
- this.count(verdict);
188
- return reports;
189
- }
190
- count(verdict) {
191
- if (verdict.qualified) {
192
- const t = this.bucket(verdict.deviceId);
193
- t.objectEvents += 1;
194
- t.qualified += 1;
195
- return;
196
- }
197
- if (verdict.reason === "not-object") {
198
- this.bucket(verdict.deviceId).otherKinds += 1;
199
- return;
200
- }
201
- const key = verdict.reason === "malformed" ? null : verdict.deviceId;
202
- const t = this.bucket(key);
203
- t.objectEvents += 1;
204
- t.byReason.set(verdict.reason, (t.byReason.get(verdict.reason) ?? 0) + 1);
205
- }
206
- bucket(key) {
207
- const existing = this.buckets.get(key);
208
- if (existing !== void 0) return existing;
209
- const fresh = emptyTally();
210
- this.buckets.set(key, fresh);
211
- return fresh;
212
- }
213
- /** Chiude la finestra e restituisce un report per secchio non vuoto. */
214
- drain(nowMs) {
215
- const windowMs = this.windowStartMs === null ? 0 : nowMs - this.windowStartMs;
216
- const out = [];
217
- for (const [deviceId, t] of this.buckets) {
218
- if (t.objectEvents === 0 && t.otherKinds === 0) continue;
219
- const rejected = t.objectEvents - t.qualified;
220
- const { reason, counts } = dominantReason(t.byReason);
221
- out.push({
222
- deviceId,
223
- windowMs,
224
- objectEvents: t.objectEvents,
225
- qualified: t.qualified,
226
- rejectedPct: t.objectEvents === 0 ? 0 : Math.round(rejected / t.objectEvents * 100),
227
- otherKinds: t.otherKinds,
228
- topReason: reason,
229
- byReason: counts,
230
- totalRejection: t.objectEvents >= this.minSample && t.qualified === 0
231
- });
232
- }
233
- this.buckets.clear();
234
- this.windowStartMs = nowMs;
235
- return out;
236
- }
237
- };
238
- //#endregion
239
- //#region src/recorder/sensor-trigger.ts
240
- /**
241
- * Da `DeviceStateChanged` a "quali camere devono registrare".
242
- *
243
- * Due responsabilità, entrambe in RAM e nessuna durevole:
244
- * - la MEMORIA del fronte, per `(deviceId, capName)`, che rende `false→true`
245
- * distinguibile da una ri-emissione. Il predicato è `evaluateSensorEdge`
246
- * (`@camstack/types`) — la stessa tabella `SOURCE_CAP_ACTIVE_FIELD` del
247
- * virtual-doorbell, non una copia;
248
- * - l'INDICE INVERSO sorgente→camere, uno stato rispecchiato aggiornato FUORI
249
- * dal percorso dell'evento (D49): `setBindings` è chiamato al boot dalle
250
- * config già lette e a ogni `onConfigChanged`, che è un'RPC. Una lettura
251
- * fallibile sul percorso del trigger potrebbe rispondere "nessuno ascolta"
252
- * e perdere l'episodio, che è il fallimento contro cui D49 è scritta.
253
- *
254
- * L'ordine dei controlli è deliberato: `DeviceStateChanged` viaggia a ritmo di
255
- * bus su tutta la flotta (batteria, la `motion` nativa di ogni camera, la
256
- * connettività). L'indice inverso è una `Map.get` senza allocazioni e va per
257
- * primo; il fronte — che legge due tabelle e la slice — viene dopo. È la stessa
258
- * scelta che post-analysis scrive per la sua sottoscrizione: *"the
259
- * EVENT_KIND_BY_CAP gate runs FIRST so non-sensor cap churn exits before any
260
- * async work"*.
261
- *
262
- * Puro rispetto al mondo: nessun bus, nessun logger, nessun orologio proprio.
263
- * Il chiamante logga il verdetto — un ramo che non accende nulla lo DICE.
264
- */
265
- /**
266
- * Type GUARD, not a cast: `event.data` is `unknown`, and a version-skewed
267
- * emitter must leave this router untouched rather than route a `deviceId` of
268
- * `undefined`. Same discipline as `parseTopologySnapshotNodes`.
269
- *
270
- * A missing or non-object `slice` is REFUSED rather than defaulted to `{}`:
271
- * `evaluateSensorEdge` would read `non-boolean-value` from an empty object and
272
- * that would look like a sensor reporting nonsense, when what actually
273
- * happened is that there was nothing to read.
274
- */
275
- function parseSensorStateChanged(data) {
276
- if (typeof data !== "object" || data === null) return null;
277
- if (!("deviceId" in data) || typeof data.deviceId !== "number") return null;
278
- if (!("capName" in data) || typeof data.capName !== "string") return null;
279
- if (!("slice" in data) || typeof data.slice !== "object" || data.slice === null) return null;
280
- const slice = { ...data.slice };
281
- return {
282
- deviceId: data.deviceId,
283
- capName: data.capName,
284
- slice
285
- };
286
- }
287
- /**
288
- * sourceDeviceId → cameras whose config names it.
289
- *
290
- * From EVERY band, not only the one active now: the index only changes on a
291
- * config write, while the active band changes with the clock, and an index
292
- * that followed the clock would lose the first trigger after every band edge.
293
- * Filtering by band is already the gate's job — `bandTriggerSources` reads the
294
- * band active at the instant of evaluation.
295
- *
296
- * A disabled camera is skipped: it records nothing whatever a sensor does, and
297
- * it re-enters through `onConfigChanged`, which rebuilds this.
298
- */
299
- function buildSensorTriggerBindings(configs) {
300
- const index = /* @__PURE__ */ new Map();
301
- for (const [cameraId, config] of configs) {
302
- if (config.enabled !== true) continue;
303
- for (const band of config.bands ?? []) for (const sourceDeviceId of band.triggers?.sensorDeviceIds ?? []) {
304
- const cameras = index.get(sourceDeviceId) ?? /* @__PURE__ */ new Set();
305
- cameras.add(cameraId);
306
- index.set(sourceDeviceId, cameras);
307
- }
308
- }
309
- return index;
310
- }
311
- var SensorTriggerRouter = class {
312
- /** sourceDeviceId → camere la cui config lo nomina. */
313
- bindings = /* @__PURE__ */ new Map();
314
- /** Ultimo booleano osservato, per `${deviceId}:${capName}`. */
315
- lastValues = /* @__PURE__ */ new Map();
316
- now;
317
- startedAtMs;
318
- freshnessMs;
319
- constructor(options) {
320
- this.now = options.now;
321
- this.startedAtMs = options.startedAtMs;
322
- this.freshnessMs = options.firstSightingFreshnessMs ?? 3e4;
323
- }
324
- /**
325
- * Sostituisce l'indice inverso. NON tocca `lastValues`: un sensore tolto e
326
- * rimesso in una banda deve ritrovare il suo livello precedente, altrimenti
327
- * la prima slice dopo il rientro sarebbe una "prima osservazione" e un
328
- * contatto rimasto aperto tutto il tempo diventerebbe un fronte alto.
329
- */
330
- setBindings(bindings) {
331
- this.bindings = bindings;
332
- }
333
- /** Quali sorgenti l'indice contiene ora — per la riga di log al boot. */
334
- listenedSourceIds() {
335
- return [...this.bindings.keys()];
336
- }
337
- onStateSlice(deviceId, capName, slice) {
338
- const cameras = this.bindings.get(deviceId);
339
- if (cameras === void 0 || cameras.size === 0) return {
340
- fired: [],
341
- skipped: "not-listened"
342
- };
343
- const key = `${deviceId}:${capName}`;
344
- const verdict = evaluateSensorEdge({
345
- capName,
346
- slice,
347
- prior: this.lastValues.get(key),
348
- startedAtMs: this.startedAtMs,
349
- nowMs: this.now(),
350
- firstSightingFreshnessMs: this.freshnessMs
351
- });
352
- if (verdict.edge === "none") {
353
- if (verdict.value !== null) this.lastValues.set(key, verdict.value);
354
- return {
355
- fired: [],
356
- skipped: verdict.reason
357
- };
358
- }
359
- this.lastValues.set(key, true);
360
- return {
361
- fired: [...cameras],
362
- skipped: null
363
- };
364
- }
365
- };
366
- //#endregion
367
52
  //#region src/recorder/init-info.ts
368
53
  /** Walk sibling boxes in [from, to), yielding [type, start, end]. */
369
54
  function* boxes$1(buf, view, from, to) {
@@ -819,13 +504,200 @@ var MfraTableStore = class {
819
504
  get size() {
820
505
  return this.tables.size;
821
506
  }
822
- /** Insertion order is time order, so the expired prefix is contiguous. */
823
- prune() {
824
- const cutoff = this.now() - MFRA_RETAIN_MS;
825
- for (const [key, entry] of this.tables) {
826
- if (entry.startMs >= cutoff) break;
827
- this.tables.delete(key);
507
+ /** Insertion order is time order, so the expired prefix is contiguous. */
508
+ prune() {
509
+ const cutoff = this.now() - MFRA_RETAIN_MS;
510
+ for (const [key, entry] of this.tables) {
511
+ if (entry.startMs >= cutoff) break;
512
+ this.tables.delete(key);
513
+ }
514
+ }
515
+ };
516
+ //#endregion
517
+ //#region src/recorder/object-trigger.ts
518
+ /**
519
+ * Il gate fra `pipeline-analytics.detection-event` e "apri una finestra di
520
+ * registrazione".
521
+ *
522
+ * Fratello di `recorder/event-capture.ts` e per lo stesso motivo: la qualifica
523
+ * ha dei rami, e un ramo che scarta lavoro senza dirlo è indistinguibile da una
524
+ * funzione mai cablata. Ogni verdetto negativo NOMINA il motivo, e il chiamante
525
+ * lo logga.
526
+ *
527
+ * Puro: nessun bus, nessun orologio, nessuna config. La scelta di QUALI classi
528
+ * ascoltare è della banda (`bandTriggerSources`); qui si decide solo se
529
+ * l'evento è una detection utilizzabile e di che macro classe è.
530
+ *
531
+ * ## Perché la forma è DISCRIMINATA su `kind` (2026-08-29)
532
+ *
533
+ * Fino al 2026-08-29 questo file dichiarava UNA sola forma piatta — quella
534
+ * dell'evento `object` — e la pretendeva da OGNI payload del topic. Ma
535
+ * `EventCategory.PipelineAnalyticsDetectionEvent` è un topic condiviso da tre
536
+ * emettitori in `addon-post-analysis/src/pipeline-analytics/index.ts`: object
537
+ * (`className`, `source`, `confidence`, `zones`), motion e audio — e motion e
538
+ * audio non portano `className`, perché non ne hanno una. Il risultato misurato:
539
+ * `malformed` su **394 righe campionate su 394**, a 3.3–3.9 eventi/s, per
540
+ * settimane. `malformed` significa "l'emettitore è andato in deriva" ed era
541
+ * invece il traffico normale del topic; l'unico secchio che poteva segnalare
542
+ * una vera rottura di protocollo era saturo al 100% di eventi sani, quindi
543
+ * inservibile — ed è stato letto come "il trigger object non ha mai funzionato".
544
+ *
545
+ * Quindi: si valida prima la BUSTA comune (`deviceId`, `kind`, `timestamp`),
546
+ * poi si discrimina su `kind`, e solo il ramo `object` pretende i campi
547
+ * dell'object. Un `object` senza `className` resta un difetto e ha il suo nome
548
+ * (`malformed-object`), distinto da una busta illeggibile.
549
+ */
550
+ /** Il `kind` dell'unico ramo del topic che può aprire una finestra. */
551
+ var OBJECT_EVENT_KIND = "object";
552
+ /** La sorgente implicita delle righe legacy senza `source` (`DetectionSourceSchema`). */
553
+ var DEFAULT_DETECTION_SOURCE = "pipeline";
554
+ /** Type guard, non cast: `event.data` è `unknown` finché non passa di qui. */
555
+ function isDetectionEventEnvelope(value) {
556
+ if (typeof value !== "object" || value === null) return false;
557
+ if (!("deviceId" in value) || typeof value.deviceId !== "number") return false;
558
+ if (!Number.isFinite(value.deviceId)) return false;
559
+ if (!("kind" in value) || typeof value.kind !== "string") return false;
560
+ if (!("timestamp" in value) || typeof value.timestamp !== "number") return false;
561
+ if (!Number.isFinite(value.timestamp) || value.timestamp <= 0) return false;
562
+ return true;
563
+ }
564
+ /** I campi che SOLO il ramo object porta. Chiamata dopo la busta. */
565
+ function isObjectDetectionEventData(value) {
566
+ if (!("className" in value) || typeof value.className !== "string") return false;
567
+ if ("source" in value && value.source !== void 0 && typeof value.source !== "string") return false;
568
+ return true;
569
+ }
570
+ function qualifyObjectTrigger(data) {
571
+ if (!isDetectionEventEnvelope(data)) return {
572
+ qualified: false,
573
+ reason: "malformed"
574
+ };
575
+ const deviceId = data.deviceId;
576
+ if (data.kind !== OBJECT_EVENT_KIND) return {
577
+ qualified: false,
578
+ reason: "not-object",
579
+ deviceId
580
+ };
581
+ if (!isObjectDetectionEventData(data)) return {
582
+ qualified: false,
583
+ reason: "malformed-object",
584
+ deviceId
585
+ };
586
+ if ((data.source ?? DEFAULT_DETECTION_SOURCE) !== DEFAULT_DETECTION_SOURCE) return {
587
+ qualified: false,
588
+ reason: "not-pipeline",
589
+ deviceId
590
+ };
591
+ const className = data.className.trim().toLowerCase();
592
+ if (!isFirstLevelMacroClass(className)) return {
593
+ qualified: false,
594
+ reason: "not-a-macro",
595
+ deviceId
596
+ };
597
+ return {
598
+ qualified: true,
599
+ deviceId,
600
+ macroClass: className,
601
+ atMs: data.timestamp
602
+ };
603
+ }
604
+ //#endregion
605
+ //#region src/recorder/object-trigger-health.ts
606
+ /** Ampiezza della finestra di aggregazione. Un minuto: abbastanza corto perché
607
+ * la riga arrivi entro il primo minuto di un deploy rotto, abbastanza lungo
608
+ * perché a 4 eventi/s il campione sia significativo. */
609
+ var OBJECT_TRIGGER_HEALTH_WINDOW_MS = 6e4;
610
+ function emptyTally() {
611
+ return {
612
+ objectEvents: 0,
613
+ qualified: 0,
614
+ otherKinds: 0,
615
+ byReason: /* @__PURE__ */ new Map()
616
+ };
617
+ }
618
+ function dominantReason(byReason) {
619
+ let reason = null;
620
+ let best = 0;
621
+ const counts = {};
622
+ for (const [r, n] of byReason) {
623
+ counts[r] = n;
624
+ if (n > best) {
625
+ best = n;
626
+ reason = r;
627
+ }
628
+ }
629
+ return {
630
+ reason,
631
+ counts
632
+ };
633
+ }
634
+ var ObjectTriggerHealth = class {
635
+ windowMs;
636
+ minSample;
637
+ buckets = /* @__PURE__ */ new Map();
638
+ windowStartMs = null;
639
+ constructor(windowMs = OBJECT_TRIGGER_HEALTH_WINDOW_MS, minSample = 5) {
640
+ this.windowMs = windowMs;
641
+ this.minSample = minSample;
642
+ }
643
+ /**
644
+ * Registra un verdetto e, se la finestra si è chiusa con questo evento,
645
+ * restituisce i report da stampare (e riapre la finestra). Nessun timer:
646
+ * il feed viaggia a ~4/s, quindi la chiusura arriva sempre in tempo, e una
647
+ * finestra che non si chiude è una finestra in cui non è successo nulla.
648
+ */
649
+ record(verdict, nowMs) {
650
+ const reports = this.windowStartMs !== null && nowMs - this.windowStartMs >= this.windowMs ? this.drain(nowMs) : [];
651
+ this.windowStartMs ??= nowMs;
652
+ this.count(verdict);
653
+ return reports;
654
+ }
655
+ count(verdict) {
656
+ if (verdict.qualified) {
657
+ const t = this.bucket(verdict.deviceId);
658
+ t.objectEvents += 1;
659
+ t.qualified += 1;
660
+ return;
661
+ }
662
+ if (verdict.reason === "not-object") {
663
+ this.bucket(verdict.deviceId).otherKinds += 1;
664
+ return;
665
+ }
666
+ const key = verdict.reason === "malformed" ? null : verdict.deviceId;
667
+ const t = this.bucket(key);
668
+ t.objectEvents += 1;
669
+ t.byReason.set(verdict.reason, (t.byReason.get(verdict.reason) ?? 0) + 1);
670
+ }
671
+ bucket(key) {
672
+ const existing = this.buckets.get(key);
673
+ if (existing !== void 0) return existing;
674
+ const fresh = emptyTally();
675
+ this.buckets.set(key, fresh);
676
+ return fresh;
677
+ }
678
+ /** Chiude la finestra e restituisce un report per secchio non vuoto. */
679
+ drain(nowMs) {
680
+ const windowMs = this.windowStartMs === null ? 0 : nowMs - this.windowStartMs;
681
+ const out = [];
682
+ for (const [deviceId, t] of this.buckets) {
683
+ if (t.objectEvents === 0 && t.otherKinds === 0) continue;
684
+ const rejected = t.objectEvents - t.qualified;
685
+ const { reason, counts } = dominantReason(t.byReason);
686
+ out.push({
687
+ deviceId,
688
+ windowMs,
689
+ objectEvents: t.objectEvents,
690
+ qualified: t.qualified,
691
+ rejectedPct: t.objectEvents === 0 ? 0 : Math.round(rejected / t.objectEvents * 100),
692
+ otherKinds: t.otherKinds,
693
+ topReason: reason,
694
+ byReason: counts,
695
+ totalRejection: t.objectEvents >= this.minSample && t.qualified === 0
696
+ });
828
697
  }
698
+ this.buckets.clear();
699
+ this.windowStartMs = nowMs;
700
+ return out;
829
701
  }
830
702
  };
831
703
  var PendingGate = class {
@@ -949,14 +821,14 @@ function parseSegmentPath(relPath) {
949
821
  //#region src/recorder/recording-index.ts
950
822
  /** Hour bucket, the granularity the path convention (`.../YYYY/MM/DD/HH/`)
951
823
  * already gives us — so "have I walked this?" costs one Set lookup. */
952
- var HOUR_MS$5 = 36e5;
824
+ var HOUR_MS$6 = 36e5;
953
825
  /** A device walked end-to-end. Cheaper and clearer than inserting every hour of
954
826
  * the retention window into the set. */
955
827
  var ALL_HOURS = Symbol("all-hours");
956
828
  /** The hour buckets a half-open span touches. */
957
829
  function* hourBuckets(fromMs, toMs) {
958
- const first = Math.floor(fromMs / HOUR_MS$5) * HOUR_MS$5;
959
- for (let h = first; h < toMs; h += HOUR_MS$5) yield h;
830
+ const first = Math.floor(fromMs / HOUR_MS$6) * HOUR_MS$6;
831
+ for (let h = first; h < toMs; h += HOUR_MS$6) yield h;
960
832
  }
961
833
  /**
962
834
  * Index of the first element whose `startMs` is GREATER than `startMs` (upper
@@ -1246,7 +1118,7 @@ var RecordingIndex = class {
1246
1118
  changed = true;
1247
1119
  }
1248
1120
  if (changed) this.invalidateSorted(deviceId);
1249
- this.markHydrated(deviceId, hourStartMs, hourStartMs + HOUR_MS$5);
1121
+ this.markHydrated(deviceId, hourStartMs, hourStartMs + HOUR_MS$6);
1250
1122
  }
1251
1123
  /**
1252
1124
  * Insert/replace one finalized segment (idempotent by path).
@@ -1492,22 +1364,41 @@ var RecordingIndex = class {
1492
1364
  for (const m of this.byDevice.values()) for (const s of m.values()) if (s.locationId === locationId) out.push(s);
1493
1365
  return out.toSorted((a, b) => a.startMs - b.startMs);
1494
1366
  }
1495
- /** Binary-search a start-sorted slice for the segment containing epochMs. */
1367
+ /**
1368
+ * Binary-search a start-sorted slice for the segment containing `epochMs`,
1369
+ * then walk backwards under {@link maxDurMs} while an earlier row could still
1370
+ * cover it.
1371
+ *
1372
+ * ## Why the last row starting at-or-before the instant is not the answer
1373
+ *
1374
+ * It is the answer whenever it covers — and that case is unchanged, so the
1375
+ * row this returns is the row it always returned. But the view is sorted by
1376
+ * `startMs` and coverage is `startMs + durMs`, which is NOT sorted: a SHORT
1377
+ * segment starting inside a longer overlapping one (a restart re-recording an
1378
+ * hour) lands last and does not cover, while the long one enclosing it does.
1379
+ * Stopping there reported a gap over footage that is on disk — a hole in the
1380
+ * operator's timeline, and a `locateSegment` / `nearestCoveredEdge` answer
1381
+ * that snapped past playable video.
1382
+ *
1383
+ * The walk is bounded exactly as {@link segmentsOverlapping} and
1384
+ * {@link coveredEdgeBefore} bound theirs: once a candidate's ceiling
1385
+ * `startMs + maxDurMs` no longer reaches past `epochMs`, no earlier row's can
1386
+ * either — earlier rows start no later. The ceiling is checked AFTER the row
1387
+ * itself, so a stale-narrow ceiling could only lengthen the walk, never skip
1388
+ * a coverer.
1389
+ *
1390
+ * Boundary convention preserved verbatim: the window is `[startMs, startMs +
1391
+ * durMs)`. `epochMs === startMs` is covered; `epochMs === startMs + durMs` is
1392
+ * not. Among several covering rows the LATEST-starting one wins, which is
1393
+ * what the plain binary search returned.
1394
+ */
1496
1395
  segmentAtIn(segs, epochMs) {
1497
- if (segs.length === 0) return null;
1498
- let lo = 0;
1499
- let hi = segs.length - 1;
1500
- let cand = -1;
1501
- while (lo <= hi) {
1502
- const mid = lo + hi >> 1;
1503
- if (segs[mid].startMs <= epochMs) {
1504
- cand = mid;
1505
- lo = mid + 1;
1506
- } else hi = mid - 1;
1396
+ for (let i = upperBoundByStart(segs, epochMs) - 1; i >= 0; i--) {
1397
+ const s = segs[i];
1398
+ if (epochMs < s.startMs + s.durMs) return s;
1399
+ if (s.startMs + this.maxDurMs <= epochMs) break;
1507
1400
  }
1508
- if (cand < 0) return null;
1509
- const seg = segs[cand];
1510
- return epochMs < seg.startMs + seg.durMs ? seg : null;
1401
+ return null;
1511
1402
  }
1512
1403
  /** The segment whose [startMs, startMs+durMs) window contains `epochMs`, or null if `epochMs` falls in a gap / there is no footage. */
1513
1404
  segmentAt(deviceId, profile, epochMs) {
@@ -1642,12 +1533,17 @@ function resolveEvictionDomain(locations, locationId, realpath = realpathSync) {
1642
1533
  * of disk decommissioning: mark the old location read-only (Phase 2), then
1643
1534
  * relocate its footage here, then delete the location.
1644
1535
  *
1645
- * Mechanics, per file: throttled copy size-verify delete source index
1646
- * re-point. The copy is `copy-if-absent` (an equal-size destination is
1647
- * adopted, not re-copied), so cancel/crash/re-run RESUMES instead of
1648
- * restarting. Throttling is file-level pacing (segments are ~1–8 MB /
1649
- * ~4 s, so per-file granularity bounds the rate tightly enough) the drain
1650
- * is a background chore that must never starve live writers.
1536
+ * Mechanics, per HOUR (D291): throttled copy + size-verify of every file in the
1537
+ * hour → re-point the DURABLE hour row delete the sources → re-point the RAM
1538
+ * index. The hour is the batch because the durable index is hour-granular, and
1539
+ * the sources outlive the durable write on purpose: between the copy and the
1540
+ * delete both locations hold the hour, so no crash can leave the index naming a
1541
+ * location without the bytes. The copy is `copy-if-absent` (an equal-size
1542
+ * destination is adopted, not re-copied), so cancel/crash/re-run RESUMES
1543
+ * instead of restarting, and a cancel inside an hour leaves that hour WHOLLY
1544
+ * readable at the source. Throttling is file-level pacing (segments are
1545
+ * ~1–8 MB / ~4 s, so per-file granularity bounds the rate tightly enough) —
1546
+ * the drain is a background chore that must never starve live writers.
1651
1547
  *
1652
1548
  * Runs INSIDE the recorder process — container uid, same-uid files, no host
1653
1549
  * chown trap (see docs/history 2026-07-29).
@@ -1666,8 +1562,16 @@ function resolveEvictionDomain(locations, locationId, realpath = realpathSync) {
1666
1562
  * strand the queue behind it.
1667
1563
  */
1668
1564
  var DEFAULT_THROTTLE_MBPS = 40;
1565
+ /** The durable index's bucket, and therefore this mover's batch. */
1566
+ var HOUR_MS$5 = 36e5;
1669
1567
  /** Progress callback cadence (files) — cheap enough to fire often. */
1670
1568
  var PROGRESS_EVERY_FILES = 25;
1569
+ /** Free space a destination must keep when it declares no `config.minFreePercent`
1570
+ * — the same default `roots.ts` documents for placement. */
1571
+ var DEFAULT_MIN_FREE_PERCENT$1 = 10;
1572
+ /** Prefix every destination-full error carries, so the coordinator can report
1573
+ * "drain stalled: destination full" instead of a raw ENOSPC string. */
1574
+ var DESTINATION_FULL_PREFIX = "destination full";
1671
1575
  function snapshot(j) {
1672
1576
  return {
1673
1577
  jobId: j.jobId,
@@ -1684,25 +1588,27 @@ function snapshot(j) {
1684
1588
  error: j.error
1685
1589
  };
1686
1590
  }
1687
- /** One file's move: copy-if-absent → verify size → delete source. Returns the
1688
- * bytes that MOVED (0 when the destination was already complete). */
1689
- async function moveFile(src, dst, srcBytes) {
1690
- let copied = 0;
1591
+ /**
1592
+ * One file's COPY: copy-if-absent verify size. The source is left in place.
1593
+ *
1594
+ * Split out of {@link moveFile} because the durable index re-point has to
1595
+ * happen while BOTH locations still hold the bytes — see
1596
+ * `SegmentHourLedger.repointSegments`. Returns the bytes that were copied
1597
+ * (0 when the destination already held a complete copy).
1598
+ */
1599
+ async function copyVerified(src, dst, srcBytes) {
1691
1600
  let dstBytes = null;
1692
1601
  try {
1693
1602
  dstBytes = (await promises.stat(dst)).size;
1694
1603
  } catch {
1695
1604
  dstBytes = null;
1696
1605
  }
1697
- if (dstBytes !== srcBytes) {
1698
- await promises.mkdir(path.dirname(dst), { recursive: true });
1699
- await promises.copyFile(src, dst);
1700
- const after = await promises.stat(dst);
1701
- if (after.size !== srcBytes) throw new Error(`relocate verify failed: ${dst} is ${after.size}B, expected ${srcBytes}B`);
1702
- copied = srcBytes;
1703
- }
1704
- await promises.rm(src, { force: true });
1705
- return copied;
1606
+ if (dstBytes === srcBytes) return 0;
1607
+ await promises.mkdir(path.dirname(dst), { recursive: true });
1608
+ await promises.copyFile(src, dst);
1609
+ const after = await promises.stat(dst);
1610
+ if (after.size !== srcBytes) throw new Error(`relocate verify failed: ${dst} is ${after.size}B, expected ${srcBytes}B`);
1611
+ return srcBytes;
1706
1612
  }
1707
1613
  var RelocateEngine = class {
1708
1614
  deps;
@@ -1825,15 +1731,15 @@ var RelocateEngine = class {
1825
1731
  const bytesPerMs = job.throttleMbps * 1024 * 1024 / 1e3;
1826
1732
  try {
1827
1733
  const samePhysicalRoot = await rootsPhysicallySame(from.root, to.root);
1734
+ const upFront = await this.headroomRefusal(job, to, samePhysicalRoot);
1735
+ if (upFront !== null) throw new Error(upFront);
1828
1736
  const segRows = job.entities.includes("segments") === false ? [] : this.deps.index.segmentsOnLocation(from.id).filter((r) => job.deviceId === null || r.deviceId === job.deviceId).filter((r) => job.profiles.length === 0 || job.profiles.includes(r.profile)).filter((r) => profileBelongsToClass(r.profile, job.footageClass)).filter((r) => job.sinceMs === null || r.startMs >= job.sinceMs).sort((a, b) => a.startMs - b.startMs);
1829
1737
  job.filesTotal = segRows.length;
1830
- for (const row of segRows) {
1738
+ for (const [, hourRows] of groupByHour(segRows)) {
1831
1739
  if (job.cancelRequested) break;
1832
- await this.moveSegment(row, from, to, samePhysicalRoot);
1833
- job.filesMoved++;
1834
- job.bytesMoved += row.bytes;
1835
- if (job.filesMoved % PROGRESS_EVERY_FILES === 0) this.deps.onProgress?.(snapshot(job));
1836
- await sleep(row.bytes / bytesPerMs);
1740
+ const refusal = await this.headroomRefusal(job, to, samePhysicalRoot);
1741
+ if (refusal !== null) throw new Error(refusal);
1742
+ await this.moveHour(job, hourRows, from, to, samePhysicalRoot, sleep, bytesPerMs);
1837
1743
  }
1838
1744
  async function rootsPhysicallySame(from, to) {
1839
1745
  if (physicalRootKey(from) === physicalRootKey(to)) return true;
@@ -1860,15 +1766,76 @@ var RelocateEngine = class {
1860
1766
  this.deps.onFinished?.(snapshot(job));
1861
1767
  }
1862
1768
  }
1863
- /** Move one segment file and re-point its index row to the target location
1864
- * (same location-relative path the layout is identical on every root).
1865
- * A source that is already gone (evicted, never flushed, ENOSPC) is dropped
1866
- * from the index and skipped — one ghost file must not abort a drain. */
1867
- async moveSegment(row, from, to, samePhysicalRoot) {
1868
- if (!samePhysicalRoot) try {
1869
- await moveFile(path.join(from.root, row.path), path.join(to.root, row.path), row.bytes);
1870
- } catch (err) {
1871
- if (isEnoent(err)) {
1769
+ /**
1770
+ * Why this drain must not put another hour on `to`, or `null` to proceed.
1771
+ *
1772
+ * Three deliberate non-refusals:
1773
+ *
1774
+ * - **Same physical root.** The move is a re-stamp, not a copy: it consumes
1775
+ * one hour of transient duplication and gives it straight back. Refusing
1776
+ * there would block the one relocation that RELIEVES a full disk.
1777
+ * - **Unknown free space.** `null` is "the question was not answered", not
1778
+ * "there is no room". Refusing on unknown would strand every drain on a
1779
+ * filesystem `statfs` cannot describe, and the fallback — ENOSPC — is
1780
+ * already safe: D291 copies and verifies before any durable re-point, so
1781
+ * a full destination loses nothing. It is logged, because a check that
1782
+ * silently never fires is worse than no check.
1783
+ * - **`maxUsedGb`.** That is a cap on what recordings may OCCUPY, arbitrated
1784
+ * by the eviction sweep against the archive ledger — not free space on a
1785
+ * volume, and not a question a mover can answer with one syscall.
1786
+ */
1787
+ async headroomRefusal(job, to, samePhysicalRoot) {
1788
+ if (samePhysicalRoot) return null;
1789
+ const free = await (this.deps.freePercentOf ?? volumeFreePercent)(to.root);
1790
+ if (free === null) {
1791
+ this.deps.logger.warn("relocate: destination free space is UNREADABLE — draining anyway, a full disk will surface as ENOSPC", {
1792
+ ...job.deviceId !== null ? { tags: { deviceId: job.deviceId } } : {},
1793
+ meta: {
1794
+ jobId: job.jobId,
1795
+ toLocationId: to.id,
1796
+ root: to.root
1797
+ }
1798
+ });
1799
+ return null;
1800
+ }
1801
+ const floor = to.minFreePercent ?? DEFAULT_MIN_FREE_PERCENT$1;
1802
+ if (free >= floor) return null;
1803
+ this.deps.logger.warn("relocate: destination is at its free-space floor — drain stops here", {
1804
+ ...job.deviceId !== null ? { tags: { deviceId: job.deviceId } } : {},
1805
+ meta: {
1806
+ jobId: job.jobId,
1807
+ toLocationId: to.id,
1808
+ freePercent: Math.round(free * 100) / 100,
1809
+ minFreePercent: floor,
1810
+ filesMoved: job.filesMoved
1811
+ }
1812
+ });
1813
+ return `${DESTINATION_FULL_PREFIX}: ${to.id} has ${(Math.round(free * 100) / 100).toString()}% free, below its ${floor.toString()}% floor — everything not yet moved is still readable at ${job.fromLocationId}`;
1814
+ }
1815
+ /**
1816
+ * Move ONE hour of one (device, profile): copy+verify every file, re-point
1817
+ * the durable hour row, delete the sources, re-point the RAM index.
1818
+ *
1819
+ * The order is the whole point. Between the copy and the delete both
1820
+ * locations hold every byte, so the ledger re-point in the middle can only
1821
+ * ever name a location that HAS the file — which is what makes a crash
1822
+ * recoverable instead of a black window. A ledger that refuses (a failed
1823
+ * point read: D49/D287) stops this hour dead with nothing deleted; the
1824
+ * copies at the target are adopted by the next run.
1825
+ */
1826
+ async moveHour(job, rows, from, to, samePhysicalRoot, sleep, bytesPerMs) {
1827
+ const movable = [];
1828
+ let copiedBytes = 0;
1829
+ if (samePhysicalRoot) movable.push(...rows);
1830
+ else for (const row of rows) {
1831
+ if (job.cancelRequested) return;
1832
+ const src = path.join(from.root, row.path);
1833
+ const dst = path.join(to.root, row.path);
1834
+ try {
1835
+ copiedBytes += await copyVerified(src, dst, row.bytes);
1836
+ movable.push(row);
1837
+ } catch (err) {
1838
+ if (!isEnoent(err)) throw err;
1872
1839
  this.deps.index.removeSegments([row.path]);
1873
1840
  this.deps.logger.warn("relocate skipped missing source", {
1874
1841
  tags: { deviceId: row.deviceId },
@@ -1877,17 +1844,70 @@ var RelocateEngine = class {
1877
1844
  locationId: from.id
1878
1845
  }
1879
1846
  });
1880
- return;
1881
1847
  }
1882
- throw err;
1848
+ await sleep(row.bytes / bytesPerMs);
1883
1849
  }
1884
- this.deps.index.removeSegments([row.path]);
1885
- this.deps.index.addSegment({
1886
- ...row,
1887
- locationId: to.id
1850
+ if (movable.length === 0) return;
1851
+ if (job.cancelRequested) return;
1852
+ const ledger = this.deps.ledger?.() ?? null;
1853
+ if (ledger === null) this.deps.logger.warn("relocate: NO durable hour ledger on this node — the re-point is RAM-only and will not survive a restart", {
1854
+ tags: { deviceId: movable[0].deviceId },
1855
+ meta: {
1856
+ jobId: job.jobId,
1857
+ toLocationId: to.id
1858
+ }
1888
1859
  });
1860
+ else if (!await ledger.repointSegments(movable, to.id)) {
1861
+ this.deps.logger.warn("relocate: hour NOT moved — the durable ledger refused the re-point, so the source bytes are kept", {
1862
+ tags: { deviceId: movable[0].deviceId },
1863
+ meta: {
1864
+ jobId: job.jobId,
1865
+ files: movable.length,
1866
+ toLocationId: to.id
1867
+ }
1868
+ });
1869
+ return;
1870
+ }
1871
+ if (!samePhysicalRoot) for (const row of movable) await promises.rm(path.join(from.root, row.path), { force: true });
1872
+ for (const row of movable) {
1873
+ this.deps.index.removeSegments([row.path]);
1874
+ this.deps.index.addSegment({
1875
+ ...row,
1876
+ locationId: to.id
1877
+ });
1878
+ }
1879
+ job.filesMoved += movable.length;
1880
+ job.bytesMoved += copiedBytes;
1881
+ if (job.filesMoved % PROGRESS_EVERY_FILES < movable.length) this.deps.onProgress?.(snapshot(job));
1889
1882
  }
1890
1883
  };
1884
+ /**
1885
+ * The job's rows bucketed by the hour row that describes them — `(device,
1886
+ * profile, hour)`, the durable ledger's own key minus its location half.
1887
+ * Insertion order preserves the caller's start-ascending sort, so a drain
1888
+ * still empties the oldest footage first.
1889
+ */
1890
+ function groupByHour(rows) {
1891
+ const out = /* @__PURE__ */ new Map();
1892
+ for (const row of rows) {
1893
+ const key = `${row.deviceId}|${row.profile}|${Math.floor(row.startMs / HOUR_MS$5)}`;
1894
+ const found = out.get(key);
1895
+ if (found) found.push(row);
1896
+ else out.set(key, [row]);
1897
+ }
1898
+ return out;
1899
+ }
1900
+ /** Free space on the volume behind `root`, as a percentage of total blocks.
1901
+ * `null` when the volume cannot be described — never a number that guesses. */
1902
+ async function volumeFreePercent(root) {
1903
+ try {
1904
+ const st = await promises.statfs(root);
1905
+ if (st.blocks <= 0) return null;
1906
+ return st.bavail / st.blocks * 100;
1907
+ } catch {
1908
+ return null;
1909
+ }
1910
+ }
1891
1911
  function isEnoent(err) {
1892
1912
  return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
1893
1913
  }
@@ -2210,6 +2230,134 @@ var macrotask$3 = () => new Promise((resolve) => {
2210
2230
  setImmediate(resolve);
2211
2231
  });
2212
2232
  //#endregion
2233
+ //#region src/recorder/sensor-trigger.ts
2234
+ /**
2235
+ * Da `DeviceStateChanged` a "quali camere devono registrare".
2236
+ *
2237
+ * Due responsabilità, entrambe in RAM e nessuna durevole:
2238
+ * - la MEMORIA del fronte, per `(deviceId, capName)`, che rende `false→true`
2239
+ * distinguibile da una ri-emissione. Il predicato è `evaluateSensorEdge`
2240
+ * (`@camstack/types`) — la stessa tabella `SOURCE_CAP_ACTIVE_FIELD` del
2241
+ * virtual-doorbell, non una copia;
2242
+ * - l'INDICE INVERSO sorgente→camere, uno stato rispecchiato aggiornato FUORI
2243
+ * dal percorso dell'evento (D49): `setBindings` è chiamato al boot dalle
2244
+ * config già lette e a ogni `onConfigChanged`, che è un'RPC. Una lettura
2245
+ * fallibile sul percorso del trigger potrebbe rispondere "nessuno ascolta"
2246
+ * e perdere l'episodio, che è il fallimento contro cui D49 è scritta.
2247
+ *
2248
+ * L'ordine dei controlli è deliberato: `DeviceStateChanged` viaggia a ritmo di
2249
+ * bus su tutta la flotta (batteria, la `motion` nativa di ogni camera, la
2250
+ * connettività). L'indice inverso è una `Map.get` senza allocazioni e va per
2251
+ * primo; il fronte — che legge due tabelle e la slice — viene dopo. È la stessa
2252
+ * scelta che post-analysis scrive per la sua sottoscrizione: *"the
2253
+ * EVENT_KIND_BY_CAP gate runs FIRST so non-sensor cap churn exits before any
2254
+ * async work"*.
2255
+ *
2256
+ * Puro rispetto al mondo: nessun bus, nessun logger, nessun orologio proprio.
2257
+ * Il chiamante logga il verdetto — un ramo che non accende nulla lo DICE.
2258
+ */
2259
+ /**
2260
+ * Type GUARD, not a cast: `event.data` is `unknown`, and a version-skewed
2261
+ * emitter must leave this router untouched rather than route a `deviceId` of
2262
+ * `undefined`. Same discipline as `parseTopologySnapshotNodes`.
2263
+ *
2264
+ * A missing or non-object `slice` is REFUSED rather than defaulted to `{}`:
2265
+ * `evaluateSensorEdge` would read `non-boolean-value` from an empty object and
2266
+ * that would look like a sensor reporting nonsense, when what actually
2267
+ * happened is that there was nothing to read.
2268
+ */
2269
+ function parseSensorStateChanged(data) {
2270
+ if (typeof data !== "object" || data === null) return null;
2271
+ if (!("deviceId" in data) || typeof data.deviceId !== "number") return null;
2272
+ if (!("capName" in data) || typeof data.capName !== "string") return null;
2273
+ if (!("slice" in data) || typeof data.slice !== "object" || data.slice === null) return null;
2274
+ const slice = { ...data.slice };
2275
+ return {
2276
+ deviceId: data.deviceId,
2277
+ capName: data.capName,
2278
+ slice
2279
+ };
2280
+ }
2281
+ /**
2282
+ * sourceDeviceId → cameras whose config names it.
2283
+ *
2284
+ * From EVERY band, not only the one active now: the index only changes on a
2285
+ * config write, while the active band changes with the clock, and an index
2286
+ * that followed the clock would lose the first trigger after every band edge.
2287
+ * Filtering by band is already the gate's job — `bandTriggerSources` reads the
2288
+ * band active at the instant of evaluation.
2289
+ *
2290
+ * A disabled camera is skipped: it records nothing whatever a sensor does, and
2291
+ * it re-enters through `onConfigChanged`, which rebuilds this.
2292
+ */
2293
+ function buildSensorTriggerBindings(configs) {
2294
+ const index = /* @__PURE__ */ new Map();
2295
+ for (const [cameraId, config] of configs) {
2296
+ if (config.enabled !== true) continue;
2297
+ for (const band of config.bands ?? []) for (const sourceDeviceId of band.triggers?.sensorDeviceIds ?? []) {
2298
+ const cameras = index.get(sourceDeviceId) ?? /* @__PURE__ */ new Set();
2299
+ cameras.add(cameraId);
2300
+ index.set(sourceDeviceId, cameras);
2301
+ }
2302
+ }
2303
+ return index;
2304
+ }
2305
+ var SensorTriggerRouter = class {
2306
+ /** sourceDeviceId → camere la cui config lo nomina. */
2307
+ bindings = /* @__PURE__ */ new Map();
2308
+ /** Ultimo booleano osservato, per `${deviceId}:${capName}`. */
2309
+ lastValues = /* @__PURE__ */ new Map();
2310
+ now;
2311
+ startedAtMs;
2312
+ freshnessMs;
2313
+ constructor(options) {
2314
+ this.now = options.now;
2315
+ this.startedAtMs = options.startedAtMs;
2316
+ this.freshnessMs = options.firstSightingFreshnessMs ?? 3e4;
2317
+ }
2318
+ /**
2319
+ * Sostituisce l'indice inverso. NON tocca `lastValues`: un sensore tolto e
2320
+ * rimesso in una banda deve ritrovare il suo livello precedente, altrimenti
2321
+ * la prima slice dopo il rientro sarebbe una "prima osservazione" e un
2322
+ * contatto rimasto aperto tutto il tempo diventerebbe un fronte alto.
2323
+ */
2324
+ setBindings(bindings) {
2325
+ this.bindings = bindings;
2326
+ }
2327
+ /** Quali sorgenti l'indice contiene ora — per la riga di log al boot. */
2328
+ listenedSourceIds() {
2329
+ return [...this.bindings.keys()];
2330
+ }
2331
+ onStateSlice(deviceId, capName, slice) {
2332
+ const cameras = this.bindings.get(deviceId);
2333
+ if (cameras === void 0 || cameras.size === 0) return {
2334
+ fired: [],
2335
+ skipped: "not-listened"
2336
+ };
2337
+ const key = `${deviceId}:${capName}`;
2338
+ const verdict = evaluateSensorEdge({
2339
+ capName,
2340
+ slice,
2341
+ prior: this.lastValues.get(key),
2342
+ startedAtMs: this.startedAtMs,
2343
+ nowMs: this.now(),
2344
+ firstSightingFreshnessMs: this.freshnessMs
2345
+ });
2346
+ if (verdict.edge === "none") {
2347
+ if (verdict.value !== null) this.lastValues.set(key, verdict.value);
2348
+ return {
2349
+ fired: [],
2350
+ skipped: verdict.reason
2351
+ };
2352
+ }
2353
+ this.lastValues.set(key, true);
2354
+ return {
2355
+ fired: [...cameras],
2356
+ skipped: null
2357
+ };
2358
+ }
2359
+ };
2360
+ //#endregion
2213
2361
  //#region src/recorder/still/still-source.ts
2214
2362
  /**
2215
2363
  * Resolve the low segment covering `epochMs` and the seek offset from that
@@ -12464,11 +12612,17 @@ var SegmentHourLedger = class {
12464
12612
  offset
12465
12613
  }
12466
12614
  });
12615
+ let met = false;
12467
12616
  for (const record of records) {
12468
12617
  chosen.push(record.id);
12469
12618
  const bytes = record.data["bytes"];
12470
12619
  covered += typeof bytes === "number" ? bytes : 0;
12620
+ if (covered >= targetBytes) {
12621
+ met = true;
12622
+ break;
12623
+ }
12471
12624
  }
12625
+ if (met) break;
12472
12626
  offset += records.length;
12473
12627
  if (records.length < 32) {
12474
12628
  exhausted = true;
@@ -12643,6 +12797,89 @@ var SegmentHourLedger = class {
12643
12797
  }
12644
12798
  }
12645
12799
  /**
12800
+ * Move `rows` from the hour rows they are listed in today to the SAME hours
12801
+ * at `toLocationId` — the DURABLE half of a relocation.
12802
+ *
12803
+ * Without this the mover re-points only `RecordingIndex`, which is RAM. Since
12804
+ * D287 a closed hour is hydrated from the ledger FIRST and the disk is not
12805
+ * consulted at all when the ledger covered the window, so a relocated hour
12806
+ * comes back at its OLD location on the next boot — paths under a root that
12807
+ * no longer holds the file. Playback does not stat (that syscall per segment
12808
+ * was removed deliberately), so the result is a silent black window; and once
12809
+ * the drained location is deleted, `collectRangeSegments` drops the rows
12810
+ * outright and the footage is invisible. That is the shape of the 2 131
12811
+ * `recordings:high` ghost segments already on this hub.
12812
+ *
12813
+ * **The ordering is the invariant, not an implementation detail.** The
12814
+ * destination row is written BEFORE the source row is shrunk, and the caller
12815
+ * has not yet deleted the source bytes — so the only state a crash can leave
12816
+ * is "listed at BOTH locations, both of which hold the file", which resolves
12817
+ * correctly whichever row hydrate happens to apply last. The reverse order
12818
+ * has a window in which the path is in NO row, and a ledger-known hour marks
12819
+ * the index `hydrated`: nothing would ever walk that hour again, and the
12820
+ * segment would sit on disk permanently unreachable.
12821
+ *
12822
+ * Returns `false` when NOTHING was repointed and the caller must delete
12823
+ * nothing. An hour whose detail could not be read decides nothing (D49) —
12824
+ * the same refusal {@link dropSegments} makes for eviction.
12825
+ */
12826
+ async repointSegments(rows, toLocationId) {
12827
+ const byHour = /* @__PURE__ */ new Map();
12828
+ for (const row of rows) {
12829
+ if (row.locationId === toLocationId) continue;
12830
+ const { key } = hourOf(row);
12831
+ const entry = byHour.get(key);
12832
+ if (entry === void 0) byHour.set(key, {
12833
+ row,
12834
+ paths: new Set([row.path])
12835
+ });
12836
+ else entry.paths.add(row.path);
12837
+ }
12838
+ for (const [sourceKey, { row, paths }] of byHour) {
12839
+ const held = await this.resident(sourceKey, row.deviceId);
12840
+ if (held === null) {
12841
+ this.logger.warn("recorder: hour detail unavailable — this relocation is REFUSED and nothing is deleted; the segments stay where they are", {
12842
+ tags: { deviceId: row.deviceId },
12843
+ meta: {
12844
+ key: sourceKey,
12845
+ toLocationId,
12846
+ paths: paths.size
12847
+ }
12848
+ });
12849
+ return false;
12850
+ }
12851
+ const targetKey = segmentHourKey(row.deviceId, row.profile, toLocationId, held.hourStartMs);
12852
+ const target = this.ledger.has(targetKey) ? await this.resident(targetKey, row.deviceId) : void 0;
12853
+ if (target === null) {
12854
+ this.logger.warn("recorder: TARGET hour detail unavailable — this relocation is REFUSED; appending to a summary would rewrite the hour as these paths alone", {
12855
+ tags: { deviceId: row.deviceId },
12856
+ meta: {
12857
+ key: targetKey,
12858
+ fromLocationId: row.locationId,
12859
+ paths: paths.size
12860
+ }
12861
+ });
12862
+ return false;
12863
+ }
12864
+ const merged = uniquePaths([...target?.paths ?? [], ...paths]);
12865
+ await this.ledger.put(segmentHourRow({
12866
+ key: targetKey,
12867
+ deviceId: row.deviceId,
12868
+ profile: row.profile,
12869
+ locationId: toLocationId,
12870
+ hourStartMs: held.hourStartMs,
12871
+ paths: merged
12872
+ }));
12873
+ const next = held.paths.filter((p) => !paths.has(p));
12874
+ if (next.length === 0) await this.ledger.forget(sourceKey);
12875
+ else await this.ledger.put(segmentHourRow({
12876
+ ...held,
12877
+ paths: next
12878
+ }));
12879
+ }
12880
+ return true;
12881
+ }
12882
+ /**
12646
12883
  * After a disk walk of `deviceIds`, make the ledger match the index — with
12647
12884
  * two D148 exceptions:
12648
12885
  *
@@ -13734,6 +13971,7 @@ var RecorderV2Addon = class extends BaseAddon {
13734
13971
  const relocateEngine = new RelocateEngine({
13735
13972
  index: this.index,
13736
13973
  locations: () => this.resolvedLocations,
13974
+ ledger: () => this.segmentHours,
13737
13975
  logger: this.ctx.logger.child("relocate"),
13738
13976
  now: () => Date.now(),
13739
13977
  newId: () => randomUUID(),