@camstack/server 1.2.803 → 1.2.805

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 (113) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/agent/main.js +1 -1
  3. package/dist/api/core/addon-settings.router.js +2 -2
  4. package/dist/api/trpc/device-config-secret-redaction.js +3 -5
  5. package/dist/api/trpc/generated-cap-routers.js +10 -24
  6. package/dist/api/trpc/localized-schema-paths.js +0 -2
  7. package/dist/core/addon/addon-registry.service.js +4 -4
  8. package/dist/core/addon/addon-settings-provider.js +2 -49
  9. package/package.json +34 -15
  10. package/system/dist/addon-runner.js +2 -9
  11. package/system/dist/addon-runner.mjs +2 -9
  12. package/system/dist/{agent-https-DtYiXPGm.js → agent-https-CuChFRA2.js} +1 -1
  13. package/system/dist/{agent-https-BRfJO9ZR.mjs → agent-https-DS4b0ucn.mjs} +1 -1
  14. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  15. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  16. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  17. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  18. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  19. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  20. package/system/dist/builtins/autotrack/index.js +1 -1
  21. package/system/dist/builtins/autotrack/index.mjs +1 -1
  22. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  23. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  24. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  25. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  26. package/system/dist/builtins/camera-grid/index.js +1 -1
  27. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  28. package/system/dist/builtins/composer/composed-device.d.ts +5 -0
  29. package/system/dist/builtins/composer/composer.addon.js +39 -4
  30. package/system/dist/builtins/composer/composer.addon.mjs +39 -4
  31. package/system/dist/builtins/composer/composer.d.ts +13 -0
  32. package/system/dist/builtins/console-logging/index.js +1 -1
  33. package/system/dist/builtins/console-logging/index.mjs +1 -1
  34. package/system/dist/builtins/core-blocks/core-blocks.addon.js +4 -5
  35. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +4 -5
  36. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  37. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  38. package/system/dist/builtins/device-manager/device-alias-actions.d.ts +45 -0
  39. package/system/dist/builtins/device-manager/device-manager.addon.js +958 -768
  40. package/system/dist/builtins/device-manager/device-manager.addon.mjs +958 -768
  41. package/system/dist/builtins/device-manager/device-meta-types.d.ts +3 -0
  42. package/system/dist/builtins/device-manager/device-row-store.d.ts +8 -0
  43. package/system/dist/builtins/device-manager/device-template/mirror-resolver.d.ts +19 -0
  44. package/system/dist/builtins/device-manager/device-template/nunjucks-internals.d.ts +53 -0
  45. package/system/dist/builtins/device-manager/device-template/template-filters.d.ts +28 -0
  46. package/system/dist/builtins/device-manager/device-template/template-grammar.d.ts +43 -0
  47. package/system/dist/builtins/device-manager/device-template/template-protocol.d.ts +33 -0
  48. package/system/dist/builtins/device-manager/device-template/template-renderer.d.ts +54 -0
  49. package/system/dist/builtins/device-manager/device-template/template-worker.d.ts +1 -0
  50. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  51. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  52. package/system/dist/builtins/keychain/index.js +4 -4
  53. package/system/dist/builtins/keychain/index.mjs +4 -4
  54. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  55. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  56. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  57. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  58. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  59. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  60. package/system/dist/builtins/loki-logging/index.js +1 -1
  61. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  62. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  63. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  64. package/system/dist/builtins/platform-probe/index.js +1 -1
  65. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  66. package/system/dist/builtins/record-entries/index.js +1 -1
  67. package/system/dist/builtins/record-entries/index.mjs +1 -1
  68. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  69. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  70. package/system/dist/builtins/snapshot/index.js +2 -2
  71. package/system/dist/builtins/snapshot/index.mjs +2 -2
  72. package/system/dist/builtins/snapshot/snapshot.addon.d.ts +1 -1
  73. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  74. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  75. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  76. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  77. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  78. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  79. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  80. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  81. package/system/dist/builtins/system-config/bootstrap-form-actions.d.ts +4 -4
  82. package/system/dist/builtins/system-config/system-config.addon.js +7 -7
  83. package/system/dist/builtins/system-config/system-config.addon.mjs +7 -7
  84. package/system/dist/builtins/winston-logging/index.js +1 -1
  85. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  86. package/system/dist/{capture-engine-BQ08XTnZ.js → capture-engine-Byc5Fkp0.js} +1 -1
  87. package/system/dist/{capture-engine-BFgeAHa9.mjs → capture-engine-CnVIcnyN.mjs} +1 -1
  88. package/system/dist/{composition-sources-DkOfzgpS.mjs → composition-sources-BhM6G9QT.mjs} +1 -1
  89. package/system/dist/{composition-sources-DNHNUvTr.js → composition-sources-BxK6ttP9.js} +1 -1
  90. package/system/dist/{constants-D5CG3Gvc.js → constants--xo6Q-KA.js} +1 -1
  91. package/system/dist/{constants-GCrIKhD_.mjs → constants-Bf1PEHRU.mjs} +1 -1
  92. package/system/dist/{device-ca-Dk2sx_18.mjs → device-ca-Do0-HV_h.mjs} +1 -1
  93. package/system/dist/{device-ca-DgZeLVC1.js → device-ca-Uq5KGFSq.js} +1 -1
  94. package/system/dist/device-template-worker.js +7289 -0
  95. package/system/dist/device-template-worker.mjs +7287 -0
  96. package/system/dist/{dist-D5nGm8Sd.js → dist-2SHQaxaS.js} +631 -618
  97. package/system/dist/{dist-ze-qVU7x.mjs → dist-CogtCQxu.mjs} +608 -619
  98. package/system/dist/file-host-worker.js +1 -1
  99. package/system/dist/file-host-worker.mjs +1 -1
  100. package/system/dist/{hub-mdns-ciao-D4g9qsNL.js → hub-mdns-ciao-DqPrLiYH.js} +2 -2
  101. package/system/dist/{hub-mdns-ciao-DD2QP3w5.mjs → hub-mdns-ciao-aFHCKrif.mjs} +2 -2
  102. package/system/dist/index.js +28 -48
  103. package/system/dist/index.mjs +28 -48
  104. package/system/dist/kernel/moleculer/addon-service-factory.d.ts +2 -3
  105. package/system/dist/kernel/transport/child-cap-protocol.d.ts +2 -2
  106. package/system/dist/kernel/transport/parent-unowned-call.d.ts +1 -1
  107. package/system/dist/{legacy-integration-rows-door-MRr8Ncb_.js → legacy-integration-rows-door-Bz8rivxI.js} +1 -1
  108. package/system/dist/{legacy-integration-rows-door-BvEFQrAa.mjs → legacy-integration-rows-door-CiuxDLoc.mjs} +1 -1
  109. package/system/dist/{restore-archive-aG7OlQNo.js → restore-archive-D-3wmHDq.js} +1 -1
  110. package/system/dist/{restore-archive-DBc5sNQS.mjs → restore-archive-PlBC2NwT.mjs} +1 -1
  111. package/system/dist/{wal-maintenance-C-ddHy-q.js → wal-maintenance-BTR55y--.js} +0 -0
  112. package/system/dist/{wal-maintenance-vQHsOLGg.mjs → wal-maintenance-jrhYTCn2.mjs} +0 -0
  113. package/system/package.json +1 -1
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-D5nGm8Sd.js");
6
+ const require_dist = require("../../dist-2SHQaxaS.js");
7
7
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
8
8
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
9
9
  const require_prefix_walk = require("../../prefix-walk-Dv6MLZlM.js");
@@ -432,6 +432,7 @@ function toDeviceInfo(addonId, device, metadata = null, metaRow = null) {
432
432
  config: configValues,
433
433
  ...liveSecretConfigPaths(device),
434
434
  metadata,
435
+ ...metaRow?.alias !== void 0 ? { alias: metaRow.alias } : {},
435
436
  ...metaRow?.integrationId !== void 0 ? { integrationId: metaRow.integrationId } : {},
436
437
  ...metaRow?.linkDeviceId !== void 0 ? { linkDeviceId: metaRow.linkDeviceId } : {},
437
438
  ...metaRow?.primaryChildEntityId !== void 0 ? { primaryChildEntityId: metaRow.primaryChildEntityId } : {},
@@ -5214,458 +5215,149 @@ async function listDeviceSettingsScopes(door) {
5214
5215
  }
5215
5216
  }
5216
5217
  //#endregion
5217
- //#region src/builtins/device-manager/migration-refused.ts
5218
+ //#region src/builtins/device-manager/device-alias-actions.ts
5218
5219
  /**
5219
- * A migration step that REFUSED with nothing moved.
5220
- *
5221
- * `migrateDevice` distinguishes two kinds of failure after the disable phase,
5222
- * and they must never be confused (D663 task 5b ruling I-1):
5223
- *
5224
- * - **refused, nothing moved** — a precheck of `swapIds` (a row missing, the
5225
- * temp id taken), the mirror drain that runs before the rows move, or a
5226
- * claim found in the mirror after that drain (it landed while the migration
5227
- * was starting). Both cameras are switched back to exactly what they were,
5228
- * because nothing about either device changed.
5229
- * - **failed while moving** — any other throw from `swapIds` (rows partially
5230
- * moved), or from `swapHardwareState` (rows swapped, state not). The two
5231
- * devices may wear each other's identity; switching them back on would run
5232
- * pipelines against crossed identities, so they stay off and the operator is
5233
- * told to intervene.
5220
+ * The template alias of a device (D1021): its generation at first registration,
5221
+ * the `setAlias` mutation, and the one-shot boot backfill for rows that predate
5222
+ * the column.
5234
5223
  *
5235
- * Only a step that KNOWS it wrote nothing may throw this. An unknown error is
5236
- * read as "may have moved" — the safe reading.
5224
+ * The grammar and the slug live in `@camstack/types` (`device-alias.ts`); this
5225
+ * file owns the persistence and the cluster-wide uniqueness, always under the
5226
+ * meta write lock so two registrations cannot both claim `stufa`.
5237
5227
  */
5238
- var MigrationRefusedError = class extends Error {
5239
- constructor(message, options) {
5240
- super(message, options);
5241
- this.name = "MigrationRefusedError";
5242
- }
5243
- };
5244
- /** A refusal that names a switch the camera does not offer, rather than one it
5245
- * could not be asked about. The cap documents rejecting the former; anything
5246
- * else is treated as the camera being out of reach, which is the safe reading:
5247
- * it keeps the switch in `sourceStillLive` instead of quietly clearing it. */
5248
- function classify(err) {
5249
- const detail = err instanceof Error ? err.message : String(err);
5250
- return {
5251
- outcome: /does not offer|not available|unsupported/i.test(detail) ? "not-offered" : "unreachable",
5252
- detail
5253
- };
5254
- }
5228
+ var DEVICE_ALIAS_BACKFILL_MARKER_KEY = "_deviceAliasBackfillVersion";
5255
5229
  /**
5256
- * One switch write under the bound. The race, not the write, is what fails on
5257
- * timeout — the underlying promise is marked handled so a late rejection from
5258
- * a camera that eventually answers "no" cannot surface as an unhandled
5259
- * rejection after the migration already reported `unreachable`.
5230
+ * Addon-store key holding `{ [alias]: deviceId }` of REMOVED devices. A removed
5231
+ * device's alias stays reserved so a template that still names it never silently
5232
+ * starts reading a different device; only an explicit `setAlias` reclaims it.
5260
5233
  */
5261
- async function setSwitchBounded(deps, deviceId, switchId, enabled) {
5262
- const budget = deps.switchTimeoutMs ?? 15e3;
5263
- await withinBudget(deps.setSwitch(deviceId, switchId, enabled), budget, `switch write did not answer within ${budget}ms — reported unreachable; if it lands late, a duplicate write of the same value is a no-op`);
5234
+ var RESERVED_ALIASES_KEY = "_reservedAliases";
5235
+ function isReservedAliases(value) {
5236
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
5237
+ return Object.values(value).every((v) => typeof v === "number");
5264
5238
  }
5265
- /** A bounded call: the race fails at `budget`, the late loser is marked handled. */
5266
- async function withinBudget(call, budget, timeoutMessage) {
5267
- call.catch(() => {});
5268
- let timer;
5269
- try {
5270
- return await Promise.race([call, new Promise((_resolve, reject) => {
5271
- timer = setTimeout(() => {
5272
- reject(new Error(timeoutMessage));
5273
- }, budget);
5274
- })]);
5275
- } finally {
5276
- if (timer !== void 0) clearTimeout(timer);
5277
- }
5239
+ async function readReservedAliases(pctx) {
5240
+ const raw = (await pctx.settings.readAddonStore())[RESERVED_ALIASES_KEY];
5241
+ return isReservedAliases(raw) ? raw : {};
5278
5242
  }
5279
- /** The prior switch states, or `null` when they could not be read (reported). */
5280
- async function readPriorSwitches(deps, deviceId) {
5281
- const budget = deps.switchTimeoutMs ?? 15e3;
5282
- try {
5283
- return await withinBudget(deps.readSwitches(deviceId), budget, `switch-state read did not answer within ${budget}ms`);
5284
- } catch (err) {
5285
- deps.logDevice("warn", deviceId, "migration: prior switch states unreadable", {
5286
- error: err instanceof Error ? err.message : String(err),
5287
- consequence: "a refusal before the swap would switch this camera fully back on"
5288
- });
5289
- return null;
5290
- }
5243
+ /** Reserve (or, with `deviceId: null`, release) one alias. Merges per key. */
5244
+ async function writeReservation(pctx, alias, deviceId) {
5245
+ await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
5246
+ const next = { ...await readReservedAliases(pctx) };
5247
+ if (deviceId === null) delete next[alias];
5248
+ else next[alias] = deviceId;
5249
+ await pctx.settings.writeAddonStore({ [RESERVED_ALIASES_KEY]: next });
5250
+ });
5251
+ }
5252
+ /** Keep the alias of a device that is being removed. Caller holds the meta write lock. */
5253
+ async function reserveAliasOfRemovedDevice(pctx, alias, deviceId) {
5254
+ await writeReservation(pctx, alias, deviceId);
5291
5255
  }
5292
5256
  /**
5293
- * Put one camera's switches back to what they were before the disable phase.
5294
- * A switch that was off stays off (it still is); one that was on is written
5295
- * on; unknown priors fall back to on — a refusal must not leave a camera dark.
5257
+ * The first free alias for `name`, against the persisted fleet. Caller holds the
5258
+ * meta write lock. `selfId` is the device the alias is for: finding itself is not
5259
+ * a collision.
5296
5260
  */
5297
- async function restoreSwitches(deps, deviceId, prior) {
5298
- const out = [];
5299
- for (const switchId of require_dist.CAMERA_SWITCH_ORDER) {
5300
- if (prior !== null && !prior.has(switchId)) continue;
5301
- if (prior !== null && prior.get(switchId) === false) {
5302
- out.push({
5303
- deviceId,
5304
- switchId,
5305
- outcome: "off"
5306
- });
5307
- continue;
5308
- }
5309
- try {
5310
- await setSwitchBounded(deps, deviceId, switchId, true);
5311
- out.push({
5312
- deviceId,
5313
- switchId,
5314
- outcome: "on"
5315
- });
5316
- } catch (err) {
5317
- out.push({
5318
- deviceId,
5319
- switchId,
5320
- ...classify(err)
5321
- });
5322
- }
5261
+ async function freeAliasFor(rows, name, selfId, reserved) {
5262
+ const refused = /* @__PURE__ */ new Set();
5263
+ for (;;) {
5264
+ const candidate = require_dist.generateDeviceAlias(name, (alias) => refused.has(alias) || alias in reserved);
5265
+ const owner = await rows.findByAlias(candidate);
5266
+ if (owner === null || owner.meta.id === selfId) return candidate;
5267
+ refused.add(candidate);
5323
5268
  }
5324
- return out;
5325
5269
  }
5326
- /** A refusal before any row moved: both cameras back as they were, then rethrow. */
5327
- async function rollBackRefusal(deps, ids, prior, err) {
5328
- for (const deviceId of [ids.sourceId, ids.targetId]) {
5329
- const restored = await restoreSwitches(deps, deviceId, prior.get(deviceId) ?? null);
5330
- deps.logDevice("warn", deviceId, "migration refused before any row moved — switches restored to their prior state", {
5331
- ...ids,
5332
- error: err.message,
5333
- priorKnown: (prior.get(deviceId) ?? null) !== null,
5334
- restored,
5335
- stillOff: restored.filter((r) => r.outcome !== "on").map((r) => r.switchId)
5270
+ async function setAlias(pctx, input) {
5271
+ const { deviceId, alias } = input;
5272
+ const outcome = await pctx.metaStore.withMetaWriteLock(async () => {
5273
+ const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
5274
+ if (!persisted) throw new Error(`[device-manager] setAlias: unknown device id=${deviceId}`);
5275
+ const grammar = require_dist.checkDeviceAlias(alias, () => false);
5276
+ if (!grammar.ok) return grammar;
5277
+ const owner = await pctx.metaStore.rows.findByAlias(alias);
5278
+ if (owner !== null && owner.meta.id !== deviceId) return {
5279
+ ok: false,
5280
+ reason: "taken",
5281
+ takenBy: owner.meta.id
5282
+ };
5283
+ if (persisted.meta.alias !== alias) await pctx.metaStore.rows.patch(deviceId, { alias });
5284
+ if (alias in await readReservedAliases(pctx)) await writeReservation(pctx, alias, null);
5285
+ return grammar;
5286
+ });
5287
+ if (!outcome.ok) {
5288
+ pctx.host.ctx.logger.info("setAlias refused", {
5289
+ tags: { deviceId },
5290
+ meta: {
5291
+ alias,
5292
+ reason: outcome.reason
5293
+ }
5336
5294
  });
5295
+ return outcome;
5337
5296
  }
5338
- throw err;
5297
+ pctx.host.ctx.eventBus.emit({
5298
+ id: (0, node_crypto.randomUUID)(),
5299
+ timestamp: /* @__PURE__ */ new Date(),
5300
+ source: {
5301
+ type: "device",
5302
+ id: deviceId
5303
+ },
5304
+ category: require_dist.EventCategory.DeviceMetaChanged,
5305
+ data: {
5306
+ deviceId,
5307
+ field: "alias",
5308
+ value: outcome.alias
5309
+ }
5310
+ });
5311
+ return outcome;
5339
5312
  }
5340
5313
  /**
5341
- * A failure once rows may have moved. The two devices may wear each other's
5342
- * identity, so nothing is switched back on: both stay off and each device gets
5343
- * an ERROR line saying what moved and that an operator must intervene (D391).
5314
+ * Who gets which alias. Rows are taken in id order, so the same fleet always
5315
+ * yields the same names; an alias a row already carries is kept and reserved.
5344
5316
  */
5345
- function alarmPartialMigration(deps, ids, phase, err) {
5346
- const moved = phase === "swapIds" ? "device rows may be PARTIALLY swapped — look for a device at an unfamiliar id" : "device rows swapped; driver config / runtime state swap incomplete — the two devices may wear each other's identity";
5347
- for (const deviceId of [ids.sourceId, ids.targetId]) deps.logDevice("error", deviceId, "migration FAILED after rows began to move — both cameras left switched off; operator must intervene", {
5348
- ...ids,
5349
- phase,
5350
- moved,
5351
- error: err instanceof Error ? err.message : String(err),
5352
- remedy: "inspect both devices (rows, driver config, runtime state) and repair by hand before switching them back on"
5353
- });
5354
- }
5355
- async function applyAll(deps, deviceId, enabled) {
5317
+ function planAliasBackfill(rows, reserved = {}) {
5318
+ const taken = new Set(Object.keys(reserved));
5319
+ for (const row of rows) if (row.alias !== void 0) taken.add(row.alias);
5356
5320
  const out = [];
5357
- for (const switchId of require_dist.CAMERA_SWITCH_ORDER) try {
5358
- await setSwitchBounded(deps, deviceId, switchId, enabled);
5359
- out.push({
5360
- deviceId,
5361
- switchId,
5362
- outcome: enabled ? "on" : "off"
5363
- });
5364
- } catch (err) {
5365
- const { outcome, detail } = classify(err);
5321
+ for (const row of rows.toSorted((a, b) => a.id - b.id)) {
5322
+ if (row.alias !== void 0) continue;
5323
+ const alias = require_dist.generateDeviceAlias(row.name, (candidate) => taken.has(candidate));
5324
+ taken.add(alias);
5366
5325
  out.push({
5367
- deviceId,
5368
- switchId,
5369
- outcome,
5370
- detail
5371
- });
5372
- deps.log("camera switch refused", {
5373
- deviceId,
5374
- switchId,
5375
- enabled,
5376
- outcome,
5377
- detail
5326
+ id: row.id,
5327
+ alias
5378
5328
  });
5379
5329
  }
5380
5330
  return out;
5381
5331
  }
5382
5332
  /**
5383
- * Put both cameras to sleep, exchange their identities, wake the target.
5384
- *
5385
- * Throws only if the swap itself fails — a switch that could not be written is
5386
- * reported, not raised, because refusing to migrate a camera whose old hardware
5387
- * is unreachable would refuse the exact case this exists for.
5333
+ * One-shot, under a version marker in the addon store (same posture as the
5334
+ * location and linked-devices backfills it sits beside): every device that has
5335
+ * no alias gets the slug of its current name, deduped. Registration also stamps
5336
+ * an alias-less row, so a device the boot missed heals the first time it registers.
5388
5337
  */
5389
- async function migrateDevice$1(deps, input) {
5390
- const { sourceId, targetId } = input;
5391
- if (sourceId === targetId) throw new Error(`[device-manager] migrateDevice: ${sourceId} is both source and target`);
5392
- await deps.assertNoFieldClaims(sourceId, targetId);
5393
- const ids = {
5394
- sourceId,
5395
- targetId
5396
- };
5397
- const prior = new Map([[sourceId, await readPriorSwitches(deps, sourceId)], [targetId, await readPriorSwitches(deps, targetId)]]);
5398
- const down = [...await applyAll(deps, sourceId, false), ...await applyAll(deps, targetId, false)];
5399
- const sourceStillLive = down.filter((r) => r.deviceId === sourceId && r.outcome === "unreachable").map((r) => r.switchId);
5400
- try {
5401
- await deps.swapIds(sourceId, targetId);
5402
- } catch (err) {
5403
- if (err instanceof MigrationRefusedError) return rollBackRefusal(deps, ids, prior, err);
5404
- alarmPartialMigration(deps, ids, "swapIds", err);
5405
- throw err;
5406
- }
5407
- try {
5408
- await deps.swapHardwareState(sourceId, targetId);
5409
- } catch (err) {
5410
- alarmPartialMigration(deps, ids, "swapHardwareState", err);
5411
- throw err;
5412
- }
5413
- for (const deviceId of [sourceId, targetId]) try {
5414
- await deps.forgetStreamState(deviceId);
5415
- } catch (err) {
5416
- deps.log("migration: broker hardware state NOT forgotten — stale stream state survives", {
5417
- deviceId,
5418
- error: err instanceof Error ? err.message : String(err),
5419
- remedy: "delete the device's derived streams and reassign its stream profiles, or update the stream-broker addon and re-run streamBroker.forgetDeviceHardware"
5420
- });
5421
- }
5422
- const up = await applyAll(deps, sourceId, true);
5423
- deps.log("camera migrated", {
5424
- sourceId,
5425
- targetId,
5426
- sourceStillLive,
5427
- refusals: [...down, ...up].filter((r) => r.outcome === "unreachable").length
5338
+ async function runDeviceAliasBackfillAtBoot(pctx) {
5339
+ const logger = pctx.host.ctx.logger;
5340
+ const markerRaw = (await pctx.settings.readAddonStore())[DEVICE_ALIAS_BACKFILL_MARKER_KEY];
5341
+ if ((typeof markerRaw === "number" ? markerRaw : 0) >= 1) return;
5342
+ const stamped = await pctx.metaStore.withMetaWriteLock(async () => {
5343
+ const all = await pctx.metaStore.rows.listAll();
5344
+ const reserved = await readReservedAliases(pctx);
5345
+ const plan = planAliasBackfill(all.filter((row) => row.registered).map((row) => ({
5346
+ id: row.meta.id,
5347
+ name: row.meta.name,
5348
+ ...row.meta.alias !== void 0 ? { alias: row.meta.alias } : {}
5349
+ })), reserved);
5350
+ for (const assignment of plan) {
5351
+ await pctx.metaStore.rows.patch(assignment.id, { alias: assignment.alias });
5352
+ logger.debug("device alias backfilled (D1021)", {
5353
+ tags: { deviceId: assignment.id },
5354
+ meta: { alias: assignment.alias }
5355
+ });
5356
+ }
5357
+ return plan.length;
5428
5358
  });
5429
- return {
5430
- sourceId,
5431
- targetId,
5432
- switches: [...down, ...up],
5433
- sourceStillLive,
5434
- swapped: true
5435
- };
5436
- }
5437
- //#endregion
5438
- //#region src/builtins/device-manager/migrate-reload.ts
5439
- async function reloadMigratedDevices(pctx, targets) {
5440
- const ctx = pctx.host.ctx;
5441
- for (const target of targets) {
5442
- pctx.metaStore.idToAddonId.set(target.deviceId, target.addonId);
5443
- pctx.host.remoteNativeCaps.delete(target.deviceId);
5444
- pctx.host.capabilityRegistry?.unregisterAllNativeForDevice(target.deviceId);
5445
- }
5446
- const fallbackAddons = /* @__PURE__ */ new Map();
5447
- await Promise.all(targets.map(async (target) => {
5448
- try {
5449
- const reloaded = await (await pctx.host.requireDeviceProvider(target.addonId)).reloadDevice({ stableId: target.stableId });
5450
- ctx.logger.info("migration: device reloaded in place — no other device disturbed", {
5451
- tags: { deviceId: target.deviceId },
5452
- meta: {
5453
- addonId: target.addonId,
5454
- stableId: target.stableId,
5455
- reloadedAs: reloaded.deviceId
5456
- }
5457
- });
5458
- } catch (err) {
5459
- ctx.logger.error("migration: in-place reload FAILED — falling back to a provider restart", {
5460
- tags: { deviceId: target.deviceId },
5461
- meta: {
5462
- addonId: target.addonId,
5463
- stableId: target.stableId,
5464
- error: err instanceof Error ? err.message : String(err)
5465
- }
5466
- });
5467
- fallbackAddons.set(target.addonId, target.deviceId);
5468
- }
5469
- }));
5470
- if (fallbackAddons.size === 0) return;
5471
- await Promise.all([...fallbackAddons.entries()].map(async ([addonId, migratedDeviceId]) => {
5472
- const owned = [...pctx.metaStore.idToAddonId.entries()].filter(([, a]) => a === addonId).length;
5473
- ctx.logger.info("migration: restarting a whole provider to flush the id maps", {
5474
- tags: { deviceId: migratedDeviceId },
5475
- meta: {
5476
- addonId,
5477
- devicesTakenDown: owned
5478
- }
5479
- });
5480
- await ctx.api.addons.restartAddon.mutate({ addonId });
5481
- }));
5482
- }
5483
- //#endregion
5484
- //#region src/builtins/device-manager/migrate-hardware-state.ts
5485
- /**
5486
- * The per-device state half of a migration (`deviceManager.migrateDevice`).
5487
- *
5488
- * ## The rule
5489
- *
5490
- * **Role-scoped state follows the NUMBER. Hardware-scoped state follows the
5491
- * DEVICE.** `swapIds` moves the device ROWS — `addonId` and `stableId` follow
5492
- * the hardware — but the per-device CONFIG blob and the runtime-state blob are
5493
- * keyed by the number in a separate store, and until 2026-09-01 they simply
5494
- * stayed put. Measured on the live hub after replacing a Hikvision (id 618)
5495
- * with a Reolink: device 108 — Reolink hardware — was dialled at
5496
- * `192.168.10.245:80` with `deviceCache.model="DS-2DE2A404IW-DE3/W"`, the
5497
- * Hikvision's address, credentials and cached model, and never came online.
5498
- * Device 4362 wore the Reolink's config on Hikvision hardware. The two devices
5499
- * were wearing each other's identity.
5500
- *
5501
- * The proof the config belongs to the hardware, not the number: writing the
5502
- * Hikvision blob onto the Reolink was REJECTED by the Reolink driver's own
5503
- * zod schema (`motionSensitivity: 60` vs max 50). A config that fails the
5504
- * other provider's schema is a config for different hardware.
5505
- *
5506
- * ## What swaps, what stays
5507
- *
5508
- * - The DRIVER config keys (host, port, credentials, `deviceCache`, every
5509
- * schema field) SWAP — they describe the box.
5510
- * - The device-manager-owned linked-devices keys (mode, ids, tracked-event
5511
- * opt-in — {@link ROLE_SCOPED_CONFIG_KEYS}) STAY with the number — a sensor
5512
- * is linked to "the driveway camera", not to a serial number.
5513
- * - `_profileMap` is DROPPED from both. It is the legacy spelling of the
5514
- * stream-profile assignment (the live authority is the stream broker's own
5515
- * map — see `StreamsTab.tsx`, which stopped writing it), and either copy
5516
- * names stream ids of the wrong hardware after a swap.
5517
- * - The runtime-state blobs (`__device-state:<id>` — battery snapshot, sleep
5518
- * flag, feature probe) SWAP wholesale: every slice mirrors the box — never
5519
- * while either carries `$owned` (D663): the migration is refused first
5520
- * ({@link assertNoFieldClaims}). A claim names the NUMBER, the block that
5521
- * owns it names a STABLE ID, and the swap moves the stable id to the other
5522
- * number; whatever it did with `$owned`, one of the two keys would end up
5523
- * on the wrong device.
5524
- *
5525
- * ## Crash points are loud, same as `swapIds`
5526
- *
5527
- * There is no transaction: each blob is cleared and rewritten. A crash between
5528
- * clear and write leaves a device with NO config — a provider that fails to
5529
- * construct and says so — never two devices wearing each other's, which is the
5530
- * state that reads as plausible and costs a day.
5531
- */
5532
- /** Legacy stream-profile assignment key (cf. `device-queries.ts`). */
5533
- var PROFILE_MAP_CONFIG_KEY = "_profileMap";
5534
- /** Config keys that belong to the camera's ROLE and stay with the number. */
5535
- var ROLE_SCOPED_CONFIG_KEYS = LINKED_DEVICES_RESERVED_KEYS;
5536
- /**
5537
- * The refusal of a migration over a device under customization. `blocked`
5538
- * carries the same facts as the message, per device, so the caller can log
5539
- * one line per device tagged with its id.
5540
- */
5541
- var FieldClaimsBlockMigrationError = class extends Error {
5542
- sourceId;
5543
- targetId;
5544
- blocked;
5545
- constructor(sourceId, targetId, blocked) {
5546
- super(`migration ${sourceId} → ${targetId} refused: ${describeBlocked(blocked)} — delete the customization before migrating (the composer releases its claims; then retry)`);
5547
- this.sourceId = sourceId;
5548
- this.targetId = targetId;
5549
- this.blocked = blocked;
5550
- this.name = "FieldClaimsBlockMigrationError";
5551
- }
5552
- };
5553
- /**
5554
- * A claim that landed while the migration was already running (D663 final
5555
- * review I-1). It passed the claim methods' migration gate just before the
5556
- * migration began, and its write-through had not reached the row when
5557
- * {@link assertNoFieldClaims} read it. Found after the drain, before any row
5558
- * moved — so it is a {@link MigrationRefusedError}: both cameras' switches are
5559
- * restored, and the claim stays on the number it names.
5560
- */
5561
- var ClaimLandedDuringMigrationError = class extends MigrationRefusedError {
5562
- sourceId;
5563
- targetId;
5564
- blocked;
5565
- constructor(sourceId, targetId, blocked) {
5566
- super(`migration ${sourceId} → ${targetId} refused: ${describeBlocked(blocked)}, landed while the migration was starting — nothing moved; delete the customization, then retry`);
5567
- this.sourceId = sourceId;
5568
- this.targetId = targetId;
5569
- this.blocked = blocked;
5570
- this.name = "ClaimLandedDuringMigrationError";
5571
- }
5572
- };
5573
- function describeBlocked(blocked) {
5574
- return blocked.map(({ deviceId, claims }) => {
5575
- return `device ${deviceId} has fields claimed by a customization (${claims.map((c) => `${c.cap} [${c.fields.join(", ")}]: ${c.owner}`).join(", ")})`;
5576
- }).join("; ");
5577
- }
5578
- function blockingClaims(owned) {
5579
- return [...owned].map(([cap, o]) => ({
5580
- cap,
5581
- owner: o.owner,
5582
- fields: [...o.fields]
5583
- }));
5584
- }
5585
- /**
5586
- * The second look, from MEMORY, once the mirror's writer is held and drained
5587
- * (I-1). A claim is in the mirror from the moment it is accepted, before its
5588
- * write-through lands, and the hold refuses any claim that reaches the mirror
5589
- * after it — so an empty answer here means no claim can land on either row
5590
- * until the swap is done.
5591
- */
5592
- function assertNoClaimLandedDuringMigration(ownedCapsOf, sourceId, targetId) {
5593
- const blocked = [];
5594
- for (const deviceId of [sourceId, targetId]) {
5595
- const owned = ownedCapsOf(deviceId);
5596
- if (owned.size > 0) blocked.push({
5597
- deviceId,
5598
- claims: blockingClaims(owned)
5599
- });
5600
- }
5601
- if (blocked.length > 0) throw new ClaimLandedDuringMigrationError(sourceId, targetId, blocked);
5602
- }
5603
- /**
5604
- * A claim names a NUMBER (`$owned` sits in `__device-state:<id>`); the block
5605
- * that owns it names a STABLE ID; `swapIds` moves the stable id to the other
5606
- * number. No swap of `$owned` keeps both keys right, so a device under
5607
- * customization is not migratable (D663). Read from the ROW — claims are
5608
- * written through, so the row is where one exists. A row that cannot be read
5609
- * THROWS: an unknown answer must refuse, never read as "no claim" (D49).
5610
- */
5611
- async function assertNoFieldClaims(settings, sourceId, targetId) {
5612
- const blocked = [];
5613
- for (const deviceId of [sourceId, targetId]) {
5614
- const { owned } = splitRuntimeBlob(await settings.readDeviceRuntimeState(deviceId));
5615
- if (owned.size > 0) blocked.push({
5616
- deviceId,
5617
- claims: blockingClaims(owned)
5618
- });
5619
- }
5620
- if (blocked.length > 0) throw new FieldClaimsBlockMigrationError(sourceId, targetId, blocked);
5621
- }
5622
- function splitConfig(config) {
5623
- const hardware = {};
5624
- const role = {};
5625
- for (const [key, value] of Object.entries(config)) {
5626
- if (key === PROFILE_MAP_CONFIG_KEY) continue;
5627
- if (ROLE_SCOPED_CONFIG_KEYS.has(key)) role[key] = value;
5628
- else hardware[key] = value;
5629
- }
5630
- return {
5631
- hardware,
5632
- role
5633
- };
5634
- }
5635
- /**
5636
- * Swap the hardware-scoped halves of two devices' persisted state. Runs right
5637
- * after `swapIds`, under the same meta write lock. THROWS on failure: a
5638
- * migration whose rows swapped but whose configs did not is exactly the
5639
- * incident this module exists to prevent, and it must never be reported as a
5640
- * success.
5641
- */
5642
- async function swapHardwareState(settings, sourceId, targetId) {
5643
- const sourceConfig = await settings.readDeviceStore(sourceId);
5644
- const targetConfig = await settings.readDeviceStore(targetId);
5645
- const source = splitConfig(sourceConfig);
5646
- const target = splitConfig(targetConfig);
5647
- await settings.clearDeviceStore(sourceId);
5648
- await settings.writeDeviceStore(sourceId, {
5649
- ...target.hardware,
5650
- ...source.role
5651
- });
5652
- await settings.clearDeviceStore(targetId);
5653
- await settings.writeDeviceStore(targetId, {
5654
- ...source.hardware,
5655
- ...target.role
5656
- });
5657
- const sourceRuntimeState = await settings.readDeviceRuntimeState(sourceId);
5658
- const targetRuntimeState = await settings.readDeviceRuntimeState(targetId);
5659
- await settings.writeDeviceRuntimeState(sourceId, targetRuntimeState);
5660
- await settings.writeDeviceRuntimeState(targetId, sourceRuntimeState);
5661
- return {
5662
- runtimeStateNowAtSource: targetRuntimeState,
5663
- runtimeStateNowAtTarget: sourceRuntimeState,
5664
- hardwareKeysToSource: Object.keys(target.hardware).toSorted(),
5665
- hardwareKeysToTarget: Object.keys(source.hardware).toSorted(),
5666
- roleKeysKeptAtSource: Object.keys(source.role).toSorted(),
5667
- roleKeysKeptAtTarget: Object.keys(target.role).toSorted()
5668
- };
5359
+ await pctx.settings.writeAddonStore({ [DEVICE_ALIAS_BACKFILL_MARKER_KEY]: 1 });
5360
+ logger.info("device aliases backfilled (D1021)", { meta: { devicesStamped: stamped } });
5669
5361
  }
5670
5362
  //#endregion
5671
5363
  //#region src/builtins/device-manager/device-config-secrets.ts
@@ -5731,224 +5423,15 @@ async function loadDeviceConfigWithSecrets(ctx, input) {
5731
5423
  return value;
5732
5424
  }
5733
5425
  //#endregion
5734
- //#region src/builtins/device-manager/location-alignment.ts
5426
+ //#region src/builtins/device-manager/device-removal-hooks.ts
5735
5427
  /**
5736
- * Location alignment — closes the RETROACTIVITY hole D252/D329 left open, and
5737
- * makes the broken state LOUD wherever it survives.
5738
- *
5739
- * The cascade (`setLocation` → every descendant's own `location` column,
5740
- * device-meta-actions.ts) runs only when `setLocation` is CALLED. Both records
5741
- * said so out loud ("Nothing retroactive") and the fleet paid for it: measured
5742
- * on the live hub 2026-09-04, 40 containers whose location predated the
5743
- * cascade carried 373 children at `location: null` — every one of those
5744
- * containers invisible to auto-mode linking-by-location (the container itself
5745
- * is deliberately never a link; its children never matched), and not one log
5746
- * line said so. Camera 101 showed one siren where four appliances belonged.
5747
- *
5748
- * Two mechanisms close it, both WRITE-time — read-time inheritance stays
5749
- * rejected (D252's context: a live-resolved location is invisible everywhere
5750
- * except the one call site that resolves it):
5751
- *
5752
- * 1. **A one-shot boot backfill** (`runLocationBackfillAtBoot`). For every
5753
- * device whose `location` is null and whose parent chain reaches a located
5754
- * CONTAINER ancestor (container-only — see `planNullLocationFills` for
5755
- * why a camera's subtree is deliberately left alone), the NEAREST located
5756
- * ancestor's location is written onto the
5757
- * row — once per install, marker-guarded. It fills NULL ONLY: an automated
5758
- * pass carries no operator intent, so it must never overwrite an explicit
5759
- * different location the way an operator's `setLocation` deliberately
5760
- * does. Runs under `withMetaWriteLock` and re-verifies each row is still
5761
- * null before patching, so it cannot fight a concurrent edit. The marker
5762
- * is only advanced when every planned write LANDED — a partial repair
5763
- * retries next boot (bounded: once per boot), never silently half-done.
5764
- *
5765
- * 2. **Registration-time inheritance** (`resolveInheritedLocation`, consumed
5766
- * by `registerDevice` in device-meta-actions.ts). A child adopted AFTER
5767
- * its parent's location was set is the same hole reopened — the cascade
5768
- * only fires on `setLocation`, and nobody re-saves a container because HA
5769
- * grew an entity. So a newly-registered (or re-parented) row whose own
5770
- * location is null inherits the nearest located CONTAINER ancestor's
5771
- * location the instant it registers, and pulls it down onto its own
5772
- * null-location descendants (out-of-order adoption registers children
5773
- * before parents).
5428
+ * device-manager's side of `device-removal-hook` (D865): tell every implementer
5429
+ * a device was deleted, and answer the admin question "which stored data belongs
5430
+ * to devices that no longer exist?".
5774
5431
  *
5775
- * And one detection: every boot, read-only, the fleet is checked for the
5776
- * broken state and each misaligned ancestor is WARNED about, device-tagged —
5777
- * the state can re-enter (a partially-failed cascade, a hand-edited ledger)
5778
- * and a branch that drops work must say so.
5779
- */
5780
- /** Addon-store key of the one-shot marker. A number: the highest backfill
5781
- * version that COMPLETED (every planned write landed). */
5782
- var LOCATION_BACKFILL_MARKER_KEY = "locationBackfillVersion";
5783
- /** Walk the parent chain of `startParentId` over an in-memory fleet snapshot
5784
- * and return the nearest ancestor carrying a non-null location. Cycle-guarded:
5785
- * a chain that revisits a node answers null rather than spinning. */
5786
- function nearestLocatedAncestor(byId, startParentId) {
5787
- const visited = /* @__PURE__ */ new Set();
5788
- let cursor = startParentId;
5789
- while (cursor !== null && !visited.has(cursor)) {
5790
- visited.add(cursor);
5791
- const ancestor = byId.get(cursor);
5792
- if (!ancestor) return null;
5793
- if (ancestor.location !== null) return ancestor;
5794
- cursor = ancestor.parentDeviceId;
5795
- }
5796
- return null;
5797
- }
5798
- /**
5799
- * Pure planning core of the backfill: every row whose own `location` is null
5800
- * and whose parent chain reaches a located CONTAINER ancestor gets that
5801
- * ancestor's location. Nearest located ancestor wins — and DECIDES: a located
5802
- * non-container between the row and a located container blocks the fill.
5803
- *
5804
- * The container-only predicate is an operator decision (2026-09-05), the
5805
- * automated mirror of the structural-children rule: a non-container parent's
5806
- * subtree (a camera and its siren/floodlight) is already fully reachable
5807
- * through `resolveLinkedDeviceIds`' children-of-self rule, so a location buys
5808
- * its own camera nothing — and COSTS cross-camera noise, verified against the
5809
- * real fleet shape with the real resolver: a camera child that gains the room
5810
- * matches every OTHER camera in that room individually (`ids.add`; only a
5811
- * Container parent routes through `expand`), so camera B lists camera A's
5812
- * siren as a companion. A container's descendants, by contrast, are reachable
5813
- * by location ONLY through their own columns — the container itself is never
5814
- * a link — which is the whole reason the cascade writes them (D252). Note the
5815
- * asymmetry with the OPERATOR's cascade, which has no type predicate (D329):
5816
- * an operator re-saving a camera accepts that trade explicitly; an automated
5817
- * pass must not manufacture it.
5818
- */
5819
- function planNullLocationFills(rows) {
5820
- const byId = new Map(rows.map((r) => [r.id, r]));
5821
- const plan = [];
5822
- for (const row of rows) {
5823
- if (row.location !== null) continue;
5824
- if (row.parentDeviceId === null) continue;
5825
- const hit = nearestLocatedAncestor(byId, row.parentDeviceId);
5826
- if (hit === null) continue;
5827
- if (hit.type !== require_dist.DeviceType.Container) continue;
5828
- if (hit.location === null) continue;
5829
- plan.push({
5830
- id: row.id,
5831
- location: hit.location,
5832
- ancestorId: hit.id
5833
- });
5834
- }
5835
- return plan;
5836
- }
5837
- /**
5838
- * Async ancestor walk for `registerDevice`: the nearest located CONTAINER
5839
- * ancestor's location, read row by row (registration has no fleet snapshot in
5840
- * hand and must not pay for one). Same container-only predicate as
5841
- * {@link planNullLocationFills}, and for the same reason — a child adopted
5842
- * under a located CAMERA is already linked structurally to that camera, and a
5843
- * location on its own column would make it a companion of every other camera
5844
- * in the room. The nearest located ancestor decides: a located non-container
5845
- * on the way up answers null. Cycle-guarded like the pure walk; a missing row
5846
- * — a parent registered out of order — answers null, and the parent's own
5847
- * later registration pulls the location down instead (see `registerDevice`).
5848
- */
5849
- async function resolveInheritedLocation(rows, parentDeviceId) {
5850
- const visited = /* @__PURE__ */ new Set();
5851
- let cursor = parentDeviceId;
5852
- while (cursor !== null && !visited.has(cursor)) {
5853
- visited.add(cursor);
5854
- const ancestor = await rows.get(cursor);
5855
- if (ancestor === null) return null;
5856
- if (ancestor.meta.location !== null) return ancestor.meta.type === require_dist.DeviceType.Container ? ancestor.meta.location : null;
5857
- cursor = ancestor.meta.parentDeviceId;
5858
- }
5859
- return null;
5860
- }
5861
- /** `fills` grouped by the ancestor whose location they inherit — the unit the
5862
- * logs speak in, because the ancestor is the device an operator would act on. */
5863
- function groupByAncestor(fills) {
5864
- const grouped = /* @__PURE__ */ new Map();
5865
- for (const fill of fills) {
5866
- const bucket = grouped.get(fill.ancestorId);
5867
- if (bucket) bucket.push(fill);
5868
- else grouped.set(fill.ancestorId, [fill]);
5869
- }
5870
- return grouped;
5871
- }
5872
- /**
5873
- * Boot entrypoint: the one-shot repair (marker-guarded) plus the every-boot
5874
- * detection. `bootRows` is the fleet listing the addon's warm-boot pass
5875
- * already paid for — reused for the detection so a clean boot costs no extra
5876
- * fleet read; ignored by the repair, which takes its own listing UNDER the
5877
- * meta write lock (the snapshot must not predate the lock).
5878
- */
5879
- async function runLocationBackfillAtBoot(pctx, bootRows) {
5880
- const logger = pctx.host.ctx.logger;
5881
- const markerRaw = (await pctx.settings.readAddonStore())[LOCATION_BACKFILL_MARKER_KEY];
5882
- const completedVersion = typeof markerRaw === "number" ? markerRaw : 0;
5883
- let repaired = false;
5884
- if (completedVersion < 1) {
5885
- const patched = [];
5886
- const failed = [];
5887
- await pctx.metaStore.withMetaWriteLock(async () => {
5888
- const plan = planNullLocationFills((await pctx.metaStore.rows.listAll()).map((r) => r.meta));
5889
- for (const fill of plan) try {
5890
- const current = await pctx.metaStore.rows.get(fill.id);
5891
- if (current === null || current.meta.location !== null) continue;
5892
- await pctx.metaStore.rows.patch(fill.id, { location: fill.location });
5893
- patched.push(fill);
5894
- } catch (err) {
5895
- failed.push({
5896
- id: fill.id,
5897
- error: err
5898
- });
5899
- }
5900
- });
5901
- repaired = true;
5902
- for (const [ancestorId, fills] of groupByAncestor(patched)) {
5903
- pctx.host.ctx.eventBus.emit({
5904
- id: (0, node_crypto.randomUUID)(),
5905
- timestamp: /* @__PURE__ */ new Date(),
5906
- source: {
5907
- type: "device",
5908
- id: ancestorId
5909
- },
5910
- category: require_dist.EventCategory.DeviceMetaChanged,
5911
- data: {
5912
- deviceId: ancestorId,
5913
- field: "location",
5914
- value: fills[0]?.location ?? null
5915
- }
5916
- });
5917
- logger.info("location backfill: aligned location-less descendants to their ancestor", {
5918
- tags: { deviceId: ancestorId },
5919
- meta: {
5920
- location: fills[0]?.location,
5921
- updatedIds: fills.map((f) => f.id)
5922
- }
5923
- });
5924
- }
5925
- if (failed.length > 0) logger.error("location backfill partially failed — retrying on the next boot", { meta: {
5926
- failedIds: failed.map((f) => f.id),
5927
- errors: failed.map((f) => f.error instanceof Error ? f.error.message : String(f.error))
5928
- } });
5929
- else await pctx.metaStore.withAddonStoreWriteLock(async () => {
5930
- await pctx.settings.writeAddonStore({ [LOCATION_BACKFILL_MARKER_KEY]: 1 });
5931
- });
5932
- }
5933
- const residual = planNullLocationFills((!repaired && bootRows !== void 0 ? bootRows : await pctx.metaStore.rows.listAll()).map((r) => r.meta));
5934
- for (const [ancestorId, fills] of groupByAncestor(residual)) logger.warn("location cascade misaligned — location-less descendants under a located ancestor never reach the same-location suggestions of the picker; re-save the ancestor location to realign", {
5935
- tags: { deviceId: ancestorId },
5936
- meta: {
5937
- location: fills[0]?.location,
5938
- misalignedDescendantIds: fills.map((f) => f.id)
5939
- }
5940
- });
5941
- }
5942
- //#endregion
5943
- //#region src/builtins/device-manager/device-removal-hooks.ts
5944
- /**
5945
- * device-manager's side of `device-removal-hook` (D865): tell every implementer
5946
- * a device was deleted, and answer the admin question "which stored data belongs
5947
- * to devices that no longer exist?".
5948
- *
5949
- * Two entry points, one rule: **an implementer is told to delete only on a
5950
- * recorded delete (a tombstone), or on an explicit operator confirm.** Nothing
5951
- * here infers a deletion from a device being absent from a single read.
5432
+ * Two entry points, one rule: **an implementer is told to delete only on a
5433
+ * recorded delete (a tombstone), or on an explicit operator confirm.** Nothing
5434
+ * here infers a deletion from a device being absent from a single read.
5952
5435
  */
5953
5436
  /** The capability name implementers register under. */
5954
5437
  var DEVICE_REMOVAL_HOOK_CAP = "device-removal-hook";
@@ -6017,146 +5500,809 @@ async function checkFleetTwice(reads) {
6017
5500
  };
6018
5501
  for (const id of read.ids) known.add(id);
6019
5502
  }
6020
- return {
6021
- ok: true,
6022
- known
6023
- };
5503
+ return {
5504
+ ok: true,
5505
+ known
5506
+ };
5507
+ }
5508
+ /** Stores holding data for devices that are not in `known`, grouped per device. */
5509
+ function orphanDevices(held, known) {
5510
+ const byDevice = /* @__PURE__ */ new Map();
5511
+ const holders = /* @__PURE__ */ new Set();
5512
+ let overlap = 0;
5513
+ for (const [, entry] of held) if (!holders.has(entry.deviceId)) {
5514
+ holders.add(entry.deviceId);
5515
+ if (known.has(entry.deviceId)) overlap += 1;
5516
+ }
5517
+ for (const [addonId, entry] of held) {
5518
+ if (known.has(entry.deviceId) || entry.count === 0) continue;
5519
+ const stores = byDevice.get(entry.deviceId) ?? {};
5520
+ stores[`${addonId}:${entry.store}`] = (stores[`${addonId}:${entry.store}`] ?? 0) + entry.count;
5521
+ byDevice.set(entry.deviceId, stores);
5522
+ }
5523
+ const idSpaceMismatch = holders.size >= 5 && overlap === 0;
5524
+ return {
5525
+ devices: [...byDevice.entries()].toSorted(([a], [b]) => a - b).map(([deviceId, stores]) => ({
5526
+ deviceId,
5527
+ stores
5528
+ })),
5529
+ idSpaceMismatch
5530
+ };
5531
+ }
5532
+ /** The admin "Clean data of deleted devices" action: dry run unless `confirm`. */
5533
+ async function cleanupDeletedDevicesData(deps, input) {
5534
+ const skipped = (reason, unreachable = []) => {
5535
+ deps.logger.warn("cleanup of deleted devices data skipped — nothing listed or deleted", { meta: { reason } });
5536
+ return {
5537
+ status: "skipped",
5538
+ reason,
5539
+ devices: [],
5540
+ unreachable: [...unreachable]
5541
+ };
5542
+ };
5543
+ const api = deps.api;
5544
+ if (api === void 0) return skipped("no api on this context");
5545
+ const fleet = await checkFleetTwice(deps.reads);
5546
+ if (!fleet.ok) return skipped(fleet.reason);
5547
+ let addonIds;
5548
+ try {
5549
+ addonIds = await hookProviders(api);
5550
+ } catch (err) {
5551
+ return skipped(`implementers could not be listed: ${require_dist.errMsg(err)}`);
5552
+ }
5553
+ const unreachable = /* @__PURE__ */ new Set();
5554
+ const held = [];
5555
+ for (const addonId of addonIds) try {
5556
+ for (const entry of await api.deviceRemovalHook.listDeviceData.query({ addonId })) held.push([addonId, entry]);
5557
+ } catch (err) {
5558
+ unreachable.add(addonId);
5559
+ deps.logger.warn("cleanup of deleted devices data: an implementer did not answer", { meta: {
5560
+ addonId,
5561
+ error: require_dist.errMsg(err)
5562
+ } });
5563
+ }
5564
+ if (deps.settings !== void 0) try {
5565
+ for (const scope of await deps.settings.list()) held.push(["settings", {
5566
+ store: scope.addonId,
5567
+ deviceId: scope.deviceId,
5568
+ count: 1
5569
+ }]);
5570
+ } catch (err) {
5571
+ return skipped(`device settings could not be listed: ${require_dist.errMsg(err)}`, [...unreachable]);
5572
+ }
5573
+ const { devices, idSpaceMismatch } = orphanDevices(held, fleet.known);
5574
+ if (idSpaceMismatch) return skipped("none of the device ids holding data is a known device — the id space looks wrong, refusing", [...unreachable]);
5575
+ if (!input.confirm) {
5576
+ deps.logger.info("cleanup of deleted devices data: dry run", { meta: {
5577
+ devices: devices.length,
5578
+ unreachable: [...unreachable]
5579
+ } });
5580
+ return {
5581
+ status: "dry-run",
5582
+ reason: null,
5583
+ devices: [...devices],
5584
+ unreachable: [...unreachable]
5585
+ };
5586
+ }
5587
+ const now = (deps.now ?? (() => Date.now()))();
5588
+ const cleaned = [];
5589
+ for (const device of devices) {
5590
+ const deleted = {};
5591
+ for (const addonId of addonIds) try {
5592
+ const result = await api.deviceRemovalHook.onDeviceRemoved.mutate({
5593
+ addonId,
5594
+ deviceId: device.deviceId,
5595
+ deletedAt: now,
5596
+ providerAddonId: "unknown"
5597
+ });
5598
+ for (const [store, count] of Object.entries(result.counts)) deleted[`${addonId}:${store}`] = count;
5599
+ } catch (err) {
5600
+ deps.logger.warn("cleanup of deleted devices data: an implementer failed", {
5601
+ tags: { deviceId: device.deviceId },
5602
+ meta: {
5603
+ addonId,
5604
+ error: require_dist.errMsg(err)
5605
+ }
5606
+ });
5607
+ }
5608
+ if (deps.settings !== void 0 && Object.keys(device.stores).some((k) => k.startsWith("settings:"))) try {
5609
+ deleted["settings"] = await deps.settings.clear(device.deviceId);
5610
+ } catch (err) {
5611
+ deps.logger.warn("cleanup of deleted devices data: settings not cleared", {
5612
+ tags: { deviceId: device.deviceId },
5613
+ meta: { error: require_dist.errMsg(err) }
5614
+ });
5615
+ }
5616
+ deps.logger.info("cleaned data of a device deleted before tombstones", {
5617
+ tags: { deviceId: device.deviceId },
5618
+ meta: { counts: deleted }
5619
+ });
5620
+ cleaned.push({
5621
+ deviceId: device.deviceId,
5622
+ stores: deleted
5623
+ });
5624
+ }
5625
+ return {
5626
+ status: "cleaned",
5627
+ reason: null,
5628
+ devices: cleaned,
5629
+ unreachable: [...unreachable]
5630
+ };
5631
+ }
5632
+ /** Scope access over the settings store; undefined when the store is unavailable. */
5633
+ function settingsScopes(store) {
5634
+ if (store === void 0) return void 0;
5635
+ const door = {
5636
+ query: (input) => store.query.query(input),
5637
+ deleteWhere: (input) => store.deleteWhere.mutate(input)
5638
+ };
5639
+ return {
5640
+ list: () => listDeviceSettingsScopes(door),
5641
+ clear: (deviceId) => clearDeviceSettings(door, deviceId)
5642
+ };
5643
+ }
5644
+ //#endregion
5645
+ //#region src/builtins/device-manager/location-alignment.ts
5646
+ /**
5647
+ * Location alignment — closes the RETROACTIVITY hole D252/D329 left open, and
5648
+ * makes the broken state LOUD wherever it survives.
5649
+ *
5650
+ * The cascade (`setLocation` → every descendant's own `location` column,
5651
+ * device-meta-actions.ts) runs only when `setLocation` is CALLED. Both records
5652
+ * said so out loud ("Nothing retroactive") and the fleet paid for it: measured
5653
+ * on the live hub 2026-09-04, 40 containers whose location predated the
5654
+ * cascade carried 373 children at `location: null` — every one of those
5655
+ * containers invisible to auto-mode linking-by-location (the container itself
5656
+ * is deliberately never a link; its children never matched), and not one log
5657
+ * line said so. Camera 101 showed one siren where four appliances belonged.
5658
+ *
5659
+ * Two mechanisms close it, both WRITE-time — read-time inheritance stays
5660
+ * rejected (D252's context: a live-resolved location is invisible everywhere
5661
+ * except the one call site that resolves it):
5662
+ *
5663
+ * 1. **A one-shot boot backfill** (`runLocationBackfillAtBoot`). For every
5664
+ * device whose `location` is null and whose parent chain reaches a located
5665
+ * CONTAINER ancestor (container-only — see `planNullLocationFills` for
5666
+ * why a camera's subtree is deliberately left alone), the NEAREST located
5667
+ * ancestor's location is written onto the
5668
+ * row — once per install, marker-guarded. It fills NULL ONLY: an automated
5669
+ * pass carries no operator intent, so it must never overwrite an explicit
5670
+ * different location the way an operator's `setLocation` deliberately
5671
+ * does. Runs under `withMetaWriteLock` and re-verifies each row is still
5672
+ * null before patching, so it cannot fight a concurrent edit. The marker
5673
+ * is only advanced when every planned write LANDED — a partial repair
5674
+ * retries next boot (bounded: once per boot), never silently half-done.
5675
+ *
5676
+ * 2. **Registration-time inheritance** (`resolveInheritedLocation`, consumed
5677
+ * by `registerDevice` in device-meta-actions.ts). A child adopted AFTER
5678
+ * its parent's location was set is the same hole reopened — the cascade
5679
+ * only fires on `setLocation`, and nobody re-saves a container because HA
5680
+ * grew an entity. So a newly-registered (or re-parented) row whose own
5681
+ * location is null inherits the nearest located CONTAINER ancestor's
5682
+ * location the instant it registers, and pulls it down onto its own
5683
+ * null-location descendants (out-of-order adoption registers children
5684
+ * before parents).
5685
+ *
5686
+ * And one detection: every boot, read-only, the fleet is checked for the
5687
+ * broken state and each misaligned ancestor is WARNED about, device-tagged —
5688
+ * the state can re-enter (a partially-failed cascade, a hand-edited ledger)
5689
+ * and a branch that drops work must say so.
5690
+ */
5691
+ /** Addon-store key of the one-shot marker. A number: the highest backfill
5692
+ * version that COMPLETED (every planned write landed). */
5693
+ var LOCATION_BACKFILL_MARKER_KEY = "locationBackfillVersion";
5694
+ /** Walk the parent chain of `startParentId` over an in-memory fleet snapshot
5695
+ * and return the nearest ancestor carrying a non-null location. Cycle-guarded:
5696
+ * a chain that revisits a node answers null rather than spinning. */
5697
+ function nearestLocatedAncestor(byId, startParentId) {
5698
+ const visited = /* @__PURE__ */ new Set();
5699
+ let cursor = startParentId;
5700
+ while (cursor !== null && !visited.has(cursor)) {
5701
+ visited.add(cursor);
5702
+ const ancestor = byId.get(cursor);
5703
+ if (!ancestor) return null;
5704
+ if (ancestor.location !== null) return ancestor;
5705
+ cursor = ancestor.parentDeviceId;
5706
+ }
5707
+ return null;
5708
+ }
5709
+ /**
5710
+ * Pure planning core of the backfill: every row whose own `location` is null
5711
+ * and whose parent chain reaches a located CONTAINER ancestor gets that
5712
+ * ancestor's location. Nearest located ancestor wins — and DECIDES: a located
5713
+ * non-container between the row and a located container blocks the fill.
5714
+ *
5715
+ * The container-only predicate is an operator decision (2026-09-05), the
5716
+ * automated mirror of the structural-children rule: a non-container parent's
5717
+ * subtree (a camera and its siren/floodlight) is already fully reachable
5718
+ * through `resolveLinkedDeviceIds`' children-of-self rule, so a location buys
5719
+ * its own camera nothing — and COSTS cross-camera noise, verified against the
5720
+ * real fleet shape with the real resolver: a camera child that gains the room
5721
+ * matches every OTHER camera in that room individually (`ids.add`; only a
5722
+ * Container parent routes through `expand`), so camera B lists camera A's
5723
+ * siren as a companion. A container's descendants, by contrast, are reachable
5724
+ * by location ONLY through their own columns — the container itself is never
5725
+ * a link — which is the whole reason the cascade writes them (D252). Note the
5726
+ * asymmetry with the OPERATOR's cascade, which has no type predicate (D329):
5727
+ * an operator re-saving a camera accepts that trade explicitly; an automated
5728
+ * pass must not manufacture it.
5729
+ */
5730
+ function planNullLocationFills(rows) {
5731
+ const byId = new Map(rows.map((r) => [r.id, r]));
5732
+ const plan = [];
5733
+ for (const row of rows) {
5734
+ if (row.location !== null) continue;
5735
+ if (row.parentDeviceId === null) continue;
5736
+ const hit = nearestLocatedAncestor(byId, row.parentDeviceId);
5737
+ if (hit === null) continue;
5738
+ if (hit.type !== require_dist.DeviceType.Container) continue;
5739
+ if (hit.location === null) continue;
5740
+ plan.push({
5741
+ id: row.id,
5742
+ location: hit.location,
5743
+ ancestorId: hit.id
5744
+ });
5745
+ }
5746
+ return plan;
5747
+ }
5748
+ /**
5749
+ * Async ancestor walk for `registerDevice`: the nearest located CONTAINER
5750
+ * ancestor's location, read row by row (registration has no fleet snapshot in
5751
+ * hand and must not pay for one). Same container-only predicate as
5752
+ * {@link planNullLocationFills}, and for the same reason — a child adopted
5753
+ * under a located CAMERA is already linked structurally to that camera, and a
5754
+ * location on its own column would make it a companion of every other camera
5755
+ * in the room. The nearest located ancestor decides: a located non-container
5756
+ * on the way up answers null. Cycle-guarded like the pure walk; a missing row
5757
+ * — a parent registered out of order — answers null, and the parent's own
5758
+ * later registration pulls the location down instead (see `registerDevice`).
5759
+ */
5760
+ async function resolveInheritedLocation(rows, parentDeviceId) {
5761
+ const visited = /* @__PURE__ */ new Set();
5762
+ let cursor = parentDeviceId;
5763
+ while (cursor !== null && !visited.has(cursor)) {
5764
+ visited.add(cursor);
5765
+ const ancestor = await rows.get(cursor);
5766
+ if (ancestor === null) return null;
5767
+ if (ancestor.meta.location !== null) return ancestor.meta.type === require_dist.DeviceType.Container ? ancestor.meta.location : null;
5768
+ cursor = ancestor.meta.parentDeviceId;
5769
+ }
5770
+ return null;
5771
+ }
5772
+ /** `fills` grouped by the ancestor whose location they inherit — the unit the
5773
+ * logs speak in, because the ancestor is the device an operator would act on. */
5774
+ function groupByAncestor(fills) {
5775
+ const grouped = /* @__PURE__ */ new Map();
5776
+ for (const fill of fills) {
5777
+ const bucket = grouped.get(fill.ancestorId);
5778
+ if (bucket) bucket.push(fill);
5779
+ else grouped.set(fill.ancestorId, [fill]);
5780
+ }
5781
+ return grouped;
5782
+ }
5783
+ /**
5784
+ * Boot entrypoint: the one-shot repair (marker-guarded) plus the every-boot
5785
+ * detection. `bootRows` is the fleet listing the addon's warm-boot pass
5786
+ * already paid for — reused for the detection so a clean boot costs no extra
5787
+ * fleet read; ignored by the repair, which takes its own listing UNDER the
5788
+ * meta write lock (the snapshot must not predate the lock).
5789
+ */
5790
+ async function runLocationBackfillAtBoot(pctx, bootRows) {
5791
+ const logger = pctx.host.ctx.logger;
5792
+ const markerRaw = (await pctx.settings.readAddonStore())[LOCATION_BACKFILL_MARKER_KEY];
5793
+ const completedVersion = typeof markerRaw === "number" ? markerRaw : 0;
5794
+ let repaired = false;
5795
+ if (completedVersion < 1) {
5796
+ const patched = [];
5797
+ const failed = [];
5798
+ await pctx.metaStore.withMetaWriteLock(async () => {
5799
+ const plan = planNullLocationFills((await pctx.metaStore.rows.listAll()).map((r) => r.meta));
5800
+ for (const fill of plan) try {
5801
+ const current = await pctx.metaStore.rows.get(fill.id);
5802
+ if (current === null || current.meta.location !== null) continue;
5803
+ await pctx.metaStore.rows.patch(fill.id, { location: fill.location });
5804
+ patched.push(fill);
5805
+ } catch (err) {
5806
+ failed.push({
5807
+ id: fill.id,
5808
+ error: err
5809
+ });
5810
+ }
5811
+ });
5812
+ repaired = true;
5813
+ for (const [ancestorId, fills] of groupByAncestor(patched)) {
5814
+ pctx.host.ctx.eventBus.emit({
5815
+ id: (0, node_crypto.randomUUID)(),
5816
+ timestamp: /* @__PURE__ */ new Date(),
5817
+ source: {
5818
+ type: "device",
5819
+ id: ancestorId
5820
+ },
5821
+ category: require_dist.EventCategory.DeviceMetaChanged,
5822
+ data: {
5823
+ deviceId: ancestorId,
5824
+ field: "location",
5825
+ value: fills[0]?.location ?? null
5826
+ }
5827
+ });
5828
+ logger.info("location backfill: aligned location-less descendants to their ancestor", {
5829
+ tags: { deviceId: ancestorId },
5830
+ meta: {
5831
+ location: fills[0]?.location,
5832
+ updatedIds: fills.map((f) => f.id)
5833
+ }
5834
+ });
5835
+ }
5836
+ if (failed.length > 0) logger.error("location backfill partially failed — retrying on the next boot", { meta: {
5837
+ failedIds: failed.map((f) => f.id),
5838
+ errors: failed.map((f) => f.error instanceof Error ? f.error.message : String(f.error))
5839
+ } });
5840
+ else await pctx.metaStore.withAddonStoreWriteLock(async () => {
5841
+ await pctx.settings.writeAddonStore({ [LOCATION_BACKFILL_MARKER_KEY]: 1 });
5842
+ });
5843
+ }
5844
+ const residual = planNullLocationFills((!repaired && bootRows !== void 0 ? bootRows : await pctx.metaStore.rows.listAll()).map((r) => r.meta));
5845
+ for (const [ancestorId, fills] of groupByAncestor(residual)) logger.warn("location cascade misaligned — location-less descendants under a located ancestor never reach the same-location suggestions of the picker; re-save the ancestor location to realign", {
5846
+ tags: { deviceId: ancestorId },
5847
+ meta: {
5848
+ location: fills[0]?.location,
5849
+ misalignedDescendantIds: fills.map((f) => f.id)
5850
+ }
5851
+ });
5852
+ }
5853
+ //#endregion
5854
+ //#region src/builtins/device-manager/migration-refused.ts
5855
+ /**
5856
+ * A migration step that REFUSED with nothing moved.
5857
+ *
5858
+ * `migrateDevice` distinguishes two kinds of failure after the disable phase,
5859
+ * and they must never be confused (D663 task 5b ruling I-1):
5860
+ *
5861
+ * - **refused, nothing moved** — a precheck of `swapIds` (a row missing, the
5862
+ * temp id taken), the mirror drain that runs before the rows move, or a
5863
+ * claim found in the mirror after that drain (it landed while the migration
5864
+ * was starting). Both cameras are switched back to exactly what they were,
5865
+ * because nothing about either device changed.
5866
+ * - **failed while moving** — any other throw from `swapIds` (rows partially
5867
+ * moved), or from `swapHardwareState` (rows swapped, state not). The two
5868
+ * devices may wear each other's identity; switching them back on would run
5869
+ * pipelines against crossed identities, so they stay off and the operator is
5870
+ * told to intervene.
5871
+ *
5872
+ * Only a step that KNOWS it wrote nothing may throw this. An unknown error is
5873
+ * read as "may have moved" — the safe reading.
5874
+ */
5875
+ var MigrationRefusedError = class extends Error {
5876
+ constructor(message, options) {
5877
+ super(message, options);
5878
+ this.name = "MigrationRefusedError";
5879
+ }
5880
+ };
5881
+ /** A refusal that names a switch the camera does not offer, rather than one it
5882
+ * could not be asked about. The cap documents rejecting the former; anything
5883
+ * else is treated as the camera being out of reach, which is the safe reading:
5884
+ * it keeps the switch in `sourceStillLive` instead of quietly clearing it. */
5885
+ function classify(err) {
5886
+ const detail = err instanceof Error ? err.message : String(err);
5887
+ return {
5888
+ outcome: /does not offer|not available|unsupported/i.test(detail) ? "not-offered" : "unreachable",
5889
+ detail
5890
+ };
5891
+ }
5892
+ /**
5893
+ * One switch write under the bound. The race, not the write, is what fails on
5894
+ * timeout — the underlying promise is marked handled so a late rejection from
5895
+ * a camera that eventually answers "no" cannot surface as an unhandled
5896
+ * rejection after the migration already reported `unreachable`.
5897
+ */
5898
+ async function setSwitchBounded(deps, deviceId, switchId, enabled) {
5899
+ const budget = deps.switchTimeoutMs ?? 15e3;
5900
+ await withinBudget(deps.setSwitch(deviceId, switchId, enabled), budget, `switch write did not answer within ${budget}ms — reported unreachable; if it lands late, a duplicate write of the same value is a no-op`);
5901
+ }
5902
+ /** A bounded call: the race fails at `budget`, the late loser is marked handled. */
5903
+ async function withinBudget(call, budget, timeoutMessage) {
5904
+ call.catch(() => {});
5905
+ let timer;
5906
+ try {
5907
+ return await Promise.race([call, new Promise((_resolve, reject) => {
5908
+ timer = setTimeout(() => {
5909
+ reject(new Error(timeoutMessage));
5910
+ }, budget);
5911
+ })]);
5912
+ } finally {
5913
+ if (timer !== void 0) clearTimeout(timer);
5914
+ }
5915
+ }
5916
+ /** The prior switch states, or `null` when they could not be read (reported). */
5917
+ async function readPriorSwitches(deps, deviceId) {
5918
+ const budget = deps.switchTimeoutMs ?? 15e3;
5919
+ try {
5920
+ return await withinBudget(deps.readSwitches(deviceId), budget, `switch-state read did not answer within ${budget}ms`);
5921
+ } catch (err) {
5922
+ deps.logDevice("warn", deviceId, "migration: prior switch states unreadable", {
5923
+ error: err instanceof Error ? err.message : String(err),
5924
+ consequence: "a refusal before the swap would switch this camera fully back on"
5925
+ });
5926
+ return null;
5927
+ }
5928
+ }
5929
+ /**
5930
+ * Put one camera's switches back to what they were before the disable phase.
5931
+ * A switch that was off stays off (it still is); one that was on is written
5932
+ * on; unknown priors fall back to on — a refusal must not leave a camera dark.
5933
+ */
5934
+ async function restoreSwitches(deps, deviceId, prior) {
5935
+ const out = [];
5936
+ for (const switchId of require_dist.CAMERA_SWITCH_ORDER) {
5937
+ if (prior !== null && !prior.has(switchId)) continue;
5938
+ if (prior !== null && prior.get(switchId) === false) {
5939
+ out.push({
5940
+ deviceId,
5941
+ switchId,
5942
+ outcome: "off"
5943
+ });
5944
+ continue;
5945
+ }
5946
+ try {
5947
+ await setSwitchBounded(deps, deviceId, switchId, true);
5948
+ out.push({
5949
+ deviceId,
5950
+ switchId,
5951
+ outcome: "on"
5952
+ });
5953
+ } catch (err) {
5954
+ out.push({
5955
+ deviceId,
5956
+ switchId,
5957
+ ...classify(err)
5958
+ });
5959
+ }
5960
+ }
5961
+ return out;
5962
+ }
5963
+ /** A refusal before any row moved: both cameras back as they were, then rethrow. */
5964
+ async function rollBackRefusal(deps, ids, prior, err) {
5965
+ for (const deviceId of [ids.sourceId, ids.targetId]) {
5966
+ const restored = await restoreSwitches(deps, deviceId, prior.get(deviceId) ?? null);
5967
+ deps.logDevice("warn", deviceId, "migration refused before any row moved — switches restored to their prior state", {
5968
+ ...ids,
5969
+ error: err.message,
5970
+ priorKnown: (prior.get(deviceId) ?? null) !== null,
5971
+ restored,
5972
+ stillOff: restored.filter((r) => r.outcome !== "on").map((r) => r.switchId)
5973
+ });
5974
+ }
5975
+ throw err;
5976
+ }
5977
+ /**
5978
+ * A failure once rows may have moved. The two devices may wear each other's
5979
+ * identity, so nothing is switched back on: both stay off and each device gets
5980
+ * an ERROR line saying what moved and that an operator must intervene (D391).
5981
+ */
5982
+ function alarmPartialMigration(deps, ids, phase, err) {
5983
+ const moved = phase === "swapIds" ? "device rows may be PARTIALLY swapped — look for a device at an unfamiliar id" : "device rows swapped; driver config / runtime state swap incomplete — the two devices may wear each other's identity";
5984
+ for (const deviceId of [ids.sourceId, ids.targetId]) deps.logDevice("error", deviceId, "migration FAILED after rows began to move — both cameras left switched off; operator must intervene", {
5985
+ ...ids,
5986
+ phase,
5987
+ moved,
5988
+ error: err instanceof Error ? err.message : String(err),
5989
+ remedy: "inspect both devices (rows, driver config, runtime state) and repair by hand before switching them back on"
5990
+ });
5991
+ }
5992
+ async function applyAll(deps, deviceId, enabled) {
5993
+ const out = [];
5994
+ for (const switchId of require_dist.CAMERA_SWITCH_ORDER) try {
5995
+ await setSwitchBounded(deps, deviceId, switchId, enabled);
5996
+ out.push({
5997
+ deviceId,
5998
+ switchId,
5999
+ outcome: enabled ? "on" : "off"
6000
+ });
6001
+ } catch (err) {
6002
+ const { outcome, detail } = classify(err);
6003
+ out.push({
6004
+ deviceId,
6005
+ switchId,
6006
+ outcome,
6007
+ detail
6008
+ });
6009
+ deps.log("camera switch refused", {
6010
+ deviceId,
6011
+ switchId,
6012
+ enabled,
6013
+ outcome,
6014
+ detail
6015
+ });
6016
+ }
6017
+ return out;
6018
+ }
6019
+ /**
6020
+ * Put both cameras to sleep, exchange their identities, wake the target.
6021
+ *
6022
+ * Throws only if the swap itself fails — a switch that could not be written is
6023
+ * reported, not raised, because refusing to migrate a camera whose old hardware
6024
+ * is unreachable would refuse the exact case this exists for.
6025
+ */
6026
+ async function migrateDevice$1(deps, input) {
6027
+ const { sourceId, targetId } = input;
6028
+ if (sourceId === targetId) throw new Error(`[device-manager] migrateDevice: ${sourceId} is both source and target`);
6029
+ await deps.assertNoFieldClaims(sourceId, targetId);
6030
+ const ids = {
6031
+ sourceId,
6032
+ targetId
6033
+ };
6034
+ const prior = new Map([[sourceId, await readPriorSwitches(deps, sourceId)], [targetId, await readPriorSwitches(deps, targetId)]]);
6035
+ const down = [...await applyAll(deps, sourceId, false), ...await applyAll(deps, targetId, false)];
6036
+ const sourceStillLive = down.filter((r) => r.deviceId === sourceId && r.outcome === "unreachable").map((r) => r.switchId);
6037
+ try {
6038
+ await deps.swapIds(sourceId, targetId);
6039
+ } catch (err) {
6040
+ if (err instanceof MigrationRefusedError) return rollBackRefusal(deps, ids, prior, err);
6041
+ alarmPartialMigration(deps, ids, "swapIds", err);
6042
+ throw err;
6043
+ }
6044
+ try {
6045
+ await deps.swapHardwareState(sourceId, targetId);
6046
+ } catch (err) {
6047
+ alarmPartialMigration(deps, ids, "swapHardwareState", err);
6048
+ throw err;
6049
+ }
6050
+ for (const deviceId of [sourceId, targetId]) try {
6051
+ await deps.forgetStreamState(deviceId);
6052
+ } catch (err) {
6053
+ deps.log("migration: broker hardware state NOT forgotten — stale stream state survives", {
6054
+ deviceId,
6055
+ error: err instanceof Error ? err.message : String(err),
6056
+ remedy: "delete the device's derived streams and reassign its stream profiles, or update the stream-broker addon and re-run streamBroker.forgetDeviceHardware"
6057
+ });
6058
+ }
6059
+ const up = await applyAll(deps, sourceId, true);
6060
+ deps.log("camera migrated", {
6061
+ sourceId,
6062
+ targetId,
6063
+ sourceStillLive,
6064
+ refusals: [...down, ...up].filter((r) => r.outcome === "unreachable").length
6065
+ });
6066
+ return {
6067
+ sourceId,
6068
+ targetId,
6069
+ switches: [...down, ...up],
6070
+ sourceStillLive,
6071
+ swapped: true
6072
+ };
6073
+ }
6074
+ //#endregion
6075
+ //#region src/builtins/device-manager/migrate-hardware-state.ts
6076
+ /**
6077
+ * The per-device state half of a migration (`deviceManager.migrateDevice`).
6078
+ *
6079
+ * ## The rule
6080
+ *
6081
+ * **Role-scoped state follows the NUMBER. Hardware-scoped state follows the
6082
+ * DEVICE.** `swapIds` moves the device ROWS — `addonId` and `stableId` follow
6083
+ * the hardware — but the per-device CONFIG blob and the runtime-state blob are
6084
+ * keyed by the number in a separate store, and until 2026-09-01 they simply
6085
+ * stayed put. Measured on the live hub after replacing a Hikvision (id 618)
6086
+ * with a Reolink: device 108 — Reolink hardware — was dialled at
6087
+ * `192.168.10.245:80` with `deviceCache.model="DS-2DE2A404IW-DE3/W"`, the
6088
+ * Hikvision's address, credentials and cached model, and never came online.
6089
+ * Device 4362 wore the Reolink's config on Hikvision hardware. The two devices
6090
+ * were wearing each other's identity.
6091
+ *
6092
+ * The proof the config belongs to the hardware, not the number: writing the
6093
+ * Hikvision blob onto the Reolink was REJECTED by the Reolink driver's own
6094
+ * zod schema (`motionSensitivity: 60` vs max 50). A config that fails the
6095
+ * other provider's schema is a config for different hardware.
6096
+ *
6097
+ * ## What swaps, what stays
6098
+ *
6099
+ * - The DRIVER config keys (host, port, credentials, `deviceCache`, every
6100
+ * schema field) SWAP — they describe the box.
6101
+ * - The device-manager-owned linked-devices keys (mode, ids, tracked-event
6102
+ * opt-in — {@link ROLE_SCOPED_CONFIG_KEYS}) STAY with the number — a sensor
6103
+ * is linked to "the driveway camera", not to a serial number.
6104
+ * - `_profileMap` is DROPPED from both. It is the legacy spelling of the
6105
+ * stream-profile assignment (the live authority is the stream broker's own
6106
+ * map — see `StreamsTab.tsx`, which stopped writing it), and either copy
6107
+ * names stream ids of the wrong hardware after a swap.
6108
+ * - The runtime-state blobs (`__device-state:<id>` — battery snapshot, sleep
6109
+ * flag, feature probe) SWAP wholesale: every slice mirrors the box — never
6110
+ * while either carries `$owned` (D663): the migration is refused first
6111
+ * ({@link assertNoFieldClaims}). A claim names the NUMBER, the block that
6112
+ * owns it names a STABLE ID, and the swap moves the stable id to the other
6113
+ * number; whatever it did with `$owned`, one of the two keys would end up
6114
+ * on the wrong device.
6115
+ *
6116
+ * ## Crash points are loud, same as `swapIds`
6117
+ *
6118
+ * There is no transaction: each blob is cleared and rewritten. A crash between
6119
+ * clear and write leaves a device with NO config — a provider that fails to
6120
+ * construct and says so — never two devices wearing each other's, which is the
6121
+ * state that reads as plausible and costs a day.
6122
+ */
6123
+ /** Legacy stream-profile assignment key (cf. `device-queries.ts`). */
6124
+ var PROFILE_MAP_CONFIG_KEY = "_profileMap";
6125
+ /** Config keys that belong to the camera's ROLE and stay with the number. */
6126
+ var ROLE_SCOPED_CONFIG_KEYS = LINKED_DEVICES_RESERVED_KEYS;
6127
+ /**
6128
+ * The refusal of a migration over a device under customization. `blocked`
6129
+ * carries the same facts as the message, per device, so the caller can log
6130
+ * one line per device tagged with its id.
6131
+ */
6132
+ var FieldClaimsBlockMigrationError = class extends Error {
6133
+ sourceId;
6134
+ targetId;
6135
+ blocked;
6136
+ constructor(sourceId, targetId, blocked) {
6137
+ super(`migration ${sourceId} → ${targetId} refused: ${describeBlocked(blocked)} — delete the customization before migrating (the composer releases its claims; then retry)`);
6138
+ this.sourceId = sourceId;
6139
+ this.targetId = targetId;
6140
+ this.blocked = blocked;
6141
+ this.name = "FieldClaimsBlockMigrationError";
6142
+ }
6143
+ };
6144
+ /**
6145
+ * A claim that landed while the migration was already running (D663 final
6146
+ * review I-1). It passed the claim methods' migration gate just before the
6147
+ * migration began, and its write-through had not reached the row when
6148
+ * {@link assertNoFieldClaims} read it. Found after the drain, before any row
6149
+ * moved — so it is a {@link MigrationRefusedError}: both cameras' switches are
6150
+ * restored, and the claim stays on the number it names.
6151
+ */
6152
+ var ClaimLandedDuringMigrationError = class extends MigrationRefusedError {
6153
+ sourceId;
6154
+ targetId;
6155
+ blocked;
6156
+ constructor(sourceId, targetId, blocked) {
6157
+ super(`migration ${sourceId} → ${targetId} refused: ${describeBlocked(blocked)}, landed while the migration was starting — nothing moved; delete the customization, then retry`);
6158
+ this.sourceId = sourceId;
6159
+ this.targetId = targetId;
6160
+ this.blocked = blocked;
6161
+ this.name = "ClaimLandedDuringMigrationError";
6162
+ }
6163
+ };
6164
+ function describeBlocked(blocked) {
6165
+ return blocked.map(({ deviceId, claims }) => {
6166
+ return `device ${deviceId} has fields claimed by a customization (${claims.map((c) => `${c.cap} [${c.fields.join(", ")}]: ${c.owner}`).join(", ")})`;
6167
+ }).join("; ");
6168
+ }
6169
+ function blockingClaims(owned) {
6170
+ return [...owned].map(([cap, o]) => ({
6171
+ cap,
6172
+ owner: o.owner,
6173
+ fields: [...o.fields]
6174
+ }));
6175
+ }
6176
+ /**
6177
+ * The second look, from MEMORY, once the mirror's writer is held and drained
6178
+ * (I-1). A claim is in the mirror from the moment it is accepted, before its
6179
+ * write-through lands, and the hold refuses any claim that reaches the mirror
6180
+ * after it — so an empty answer here means no claim can land on either row
6181
+ * until the swap is done.
6182
+ */
6183
+ function assertNoClaimLandedDuringMigration(ownedCapsOf, sourceId, targetId) {
6184
+ const blocked = [];
6185
+ for (const deviceId of [sourceId, targetId]) {
6186
+ const owned = ownedCapsOf(deviceId);
6187
+ if (owned.size > 0) blocked.push({
6188
+ deviceId,
6189
+ claims: blockingClaims(owned)
6190
+ });
6191
+ }
6192
+ if (blocked.length > 0) throw new ClaimLandedDuringMigrationError(sourceId, targetId, blocked);
6024
6193
  }
6025
- /** Stores holding data for devices that are not in `known`, grouped per device. */
6026
- function orphanDevices(held, known) {
6027
- const byDevice = /* @__PURE__ */ new Map();
6028
- const holders = /* @__PURE__ */ new Set();
6029
- let overlap = 0;
6030
- for (const [, entry] of held) if (!holders.has(entry.deviceId)) {
6031
- holders.add(entry.deviceId);
6032
- if (known.has(entry.deviceId)) overlap += 1;
6194
+ /**
6195
+ * A claim names a NUMBER (`$owned` sits in `__device-state:<id>`); the block
6196
+ * that owns it names a STABLE ID; `swapIds` moves the stable id to the other
6197
+ * number. No swap of `$owned` keeps both keys right, so a device under
6198
+ * customization is not migratable (D663). Read from the ROW — claims are
6199
+ * written through, so the row is where one exists. A row that cannot be read
6200
+ * THROWS: an unknown answer must refuse, never read as "no claim" (D49).
6201
+ */
6202
+ async function assertNoFieldClaims(settings, sourceId, targetId) {
6203
+ const blocked = [];
6204
+ for (const deviceId of [sourceId, targetId]) {
6205
+ const { owned } = splitRuntimeBlob(await settings.readDeviceRuntimeState(deviceId));
6206
+ if (owned.size > 0) blocked.push({
6207
+ deviceId,
6208
+ claims: blockingClaims(owned)
6209
+ });
6033
6210
  }
6034
- for (const [addonId, entry] of held) {
6035
- if (known.has(entry.deviceId) || entry.count === 0) continue;
6036
- const stores = byDevice.get(entry.deviceId) ?? {};
6037
- stores[`${addonId}:${entry.store}`] = (stores[`${addonId}:${entry.store}`] ?? 0) + entry.count;
6038
- byDevice.set(entry.deviceId, stores);
6211
+ if (blocked.length > 0) throw new FieldClaimsBlockMigrationError(sourceId, targetId, blocked);
6212
+ }
6213
+ function splitConfig(config) {
6214
+ const hardware = {};
6215
+ const role = {};
6216
+ for (const [key, value] of Object.entries(config)) {
6217
+ if (key === PROFILE_MAP_CONFIG_KEY) continue;
6218
+ if (ROLE_SCOPED_CONFIG_KEYS.has(key)) role[key] = value;
6219
+ else hardware[key] = value;
6039
6220
  }
6040
- const idSpaceMismatch = holders.size >= 5 && overlap === 0;
6041
6221
  return {
6042
- devices: [...byDevice.entries()].toSorted(([a], [b]) => a - b).map(([deviceId, stores]) => ({
6043
- deviceId,
6044
- stores
6045
- })),
6046
- idSpaceMismatch
6222
+ hardware,
6223
+ role
6047
6224
  };
6048
6225
  }
6049
- /** The admin "Clean data of deleted devices" action: dry run unless `confirm`. */
6050
- async function cleanupDeletedDevicesData(deps, input) {
6051
- const skipped = (reason, unreachable = []) => {
6052
- deps.logger.warn("cleanup of deleted devices data skipped — nothing listed or deleted", { meta: { reason } });
6053
- return {
6054
- status: "skipped",
6055
- reason,
6056
- devices: [],
6057
- unreachable: [...unreachable]
6058
- };
6226
+ /**
6227
+ * Swap the hardware-scoped halves of two devices' persisted state. Runs right
6228
+ * after `swapIds`, under the same meta write lock. THROWS on failure: a
6229
+ * migration whose rows swapped but whose configs did not is exactly the
6230
+ * incident this module exists to prevent, and it must never be reported as a
6231
+ * success.
6232
+ */
6233
+ async function swapHardwareState(settings, sourceId, targetId) {
6234
+ const sourceConfig = await settings.readDeviceStore(sourceId);
6235
+ const targetConfig = await settings.readDeviceStore(targetId);
6236
+ const source = splitConfig(sourceConfig);
6237
+ const target = splitConfig(targetConfig);
6238
+ await settings.clearDeviceStore(sourceId);
6239
+ await settings.writeDeviceStore(sourceId, {
6240
+ ...target.hardware,
6241
+ ...source.role
6242
+ });
6243
+ await settings.clearDeviceStore(targetId);
6244
+ await settings.writeDeviceStore(targetId, {
6245
+ ...source.hardware,
6246
+ ...target.role
6247
+ });
6248
+ const sourceRuntimeState = await settings.readDeviceRuntimeState(sourceId);
6249
+ const targetRuntimeState = await settings.readDeviceRuntimeState(targetId);
6250
+ await settings.writeDeviceRuntimeState(sourceId, targetRuntimeState);
6251
+ await settings.writeDeviceRuntimeState(targetId, sourceRuntimeState);
6252
+ return {
6253
+ runtimeStateNowAtSource: targetRuntimeState,
6254
+ runtimeStateNowAtTarget: sourceRuntimeState,
6255
+ hardwareKeysToSource: Object.keys(target.hardware).toSorted(),
6256
+ hardwareKeysToTarget: Object.keys(source.hardware).toSorted(),
6257
+ roleKeysKeptAtSource: Object.keys(source.role).toSorted(),
6258
+ roleKeysKeptAtTarget: Object.keys(target.role).toSorted()
6059
6259
  };
6060
- const api = deps.api;
6061
- if (api === void 0) return skipped("no api on this context");
6062
- const fleet = await checkFleetTwice(deps.reads);
6063
- if (!fleet.ok) return skipped(fleet.reason);
6064
- let addonIds;
6065
- try {
6066
- addonIds = await hookProviders(api);
6067
- } catch (err) {
6068
- return skipped(`implementers could not be listed: ${require_dist.errMsg(err)}`);
6069
- }
6070
- const unreachable = /* @__PURE__ */ new Set();
6071
- const held = [];
6072
- for (const addonId of addonIds) try {
6073
- for (const entry of await api.deviceRemovalHook.listDeviceData.query({ addonId })) held.push([addonId, entry]);
6074
- } catch (err) {
6075
- unreachable.add(addonId);
6076
- deps.logger.warn("cleanup of deleted devices data: an implementer did not answer", { meta: {
6077
- addonId,
6078
- error: require_dist.errMsg(err)
6079
- } });
6080
- }
6081
- if (deps.settings !== void 0) try {
6082
- for (const scope of await deps.settings.list()) held.push(["settings", {
6083
- store: scope.addonId,
6084
- deviceId: scope.deviceId,
6085
- count: 1
6086
- }]);
6087
- } catch (err) {
6088
- return skipped(`device settings could not be listed: ${require_dist.errMsg(err)}`, [...unreachable]);
6089
- }
6090
- const { devices, idSpaceMismatch } = orphanDevices(held, fleet.known);
6091
- if (idSpaceMismatch) return skipped("none of the device ids holding data is a known device — the id space looks wrong, refusing", [...unreachable]);
6092
- if (!input.confirm) {
6093
- deps.logger.info("cleanup of deleted devices data: dry run", { meta: {
6094
- devices: devices.length,
6095
- unreachable: [...unreachable]
6096
- } });
6097
- return {
6098
- status: "dry-run",
6099
- reason: null,
6100
- devices: [...devices],
6101
- unreachable: [...unreachable]
6102
- };
6260
+ }
6261
+ //#endregion
6262
+ //#region src/builtins/device-manager/migrate-reload.ts
6263
+ async function reloadMigratedDevices(pctx, targets) {
6264
+ const ctx = pctx.host.ctx;
6265
+ for (const target of targets) {
6266
+ pctx.metaStore.idToAddonId.set(target.deviceId, target.addonId);
6267
+ pctx.host.remoteNativeCaps.delete(target.deviceId);
6268
+ pctx.host.capabilityRegistry?.unregisterAllNativeForDevice(target.deviceId);
6103
6269
  }
6104
- const now = (deps.now ?? (() => Date.now()))();
6105
- const cleaned = [];
6106
- for (const device of devices) {
6107
- const deleted = {};
6108
- for (const addonId of addonIds) try {
6109
- const result = await api.deviceRemovalHook.onDeviceRemoved.mutate({
6110
- addonId,
6111
- deviceId: device.deviceId,
6112
- deletedAt: now,
6113
- providerAddonId: "unknown"
6114
- });
6115
- for (const [store, count] of Object.entries(result.counts)) deleted[`${addonId}:${store}`] = count;
6116
- } catch (err) {
6117
- deps.logger.warn("cleanup of deleted devices data: an implementer failed", {
6118
- tags: { deviceId: device.deviceId },
6270
+ const fallbackAddons = /* @__PURE__ */ new Map();
6271
+ await Promise.all(targets.map(async (target) => {
6272
+ try {
6273
+ const reloaded = await (await pctx.host.requireDeviceProvider(target.addonId)).reloadDevice({ stableId: target.stableId });
6274
+ ctx.logger.info("migration: device reloaded in place — no other device disturbed", {
6275
+ tags: { deviceId: target.deviceId },
6119
6276
  meta: {
6120
- addonId,
6121
- error: require_dist.errMsg(err)
6277
+ addonId: target.addonId,
6278
+ stableId: target.stableId,
6279
+ reloadedAs: reloaded.deviceId
6122
6280
  }
6123
6281
  });
6124
- }
6125
- if (deps.settings !== void 0 && Object.keys(device.stores).some((k) => k.startsWith("settings:"))) try {
6126
- deleted["settings"] = await deps.settings.clear(device.deviceId);
6127
6282
  } catch (err) {
6128
- deps.logger.warn("cleanup of deleted devices data: settings not cleared", {
6129
- tags: { deviceId: device.deviceId },
6130
- meta: { error: require_dist.errMsg(err) }
6283
+ ctx.logger.error("migration: in-place reload FAILED — falling back to a provider restart", {
6284
+ tags: { deviceId: target.deviceId },
6285
+ meta: {
6286
+ addonId: target.addonId,
6287
+ stableId: target.stableId,
6288
+ error: err instanceof Error ? err.message : String(err)
6289
+ }
6131
6290
  });
6291
+ fallbackAddons.set(target.addonId, target.deviceId);
6132
6292
  }
6133
- deps.logger.info("cleaned data of a device deleted before tombstones", {
6134
- tags: { deviceId: device.deviceId },
6135
- meta: { counts: deleted }
6136
- });
6137
- cleaned.push({
6138
- deviceId: device.deviceId,
6139
- stores: deleted
6293
+ }));
6294
+ if (fallbackAddons.size === 0) return;
6295
+ await Promise.all([...fallbackAddons.entries()].map(async ([addonId, migratedDeviceId]) => {
6296
+ const owned = [...pctx.metaStore.idToAddonId.entries()].filter(([, a]) => a === addonId).length;
6297
+ ctx.logger.info("migration: restarting a whole provider to flush the id maps", {
6298
+ tags: { deviceId: migratedDeviceId },
6299
+ meta: {
6300
+ addonId,
6301
+ devicesTakenDown: owned
6302
+ }
6140
6303
  });
6141
- }
6142
- return {
6143
- status: "cleaned",
6144
- reason: null,
6145
- devices: cleaned,
6146
- unreachable: [...unreachable]
6147
- };
6148
- }
6149
- /** Scope access over the settings store; undefined when the store is unavailable. */
6150
- function settingsScopes(store) {
6151
- if (store === void 0) return void 0;
6152
- const door = {
6153
- query: (input) => store.query.query(input),
6154
- deleteWhere: (input) => store.deleteWhere.mutate(input)
6155
- };
6156
- return {
6157
- list: () => listDeviceSettingsScopes(door),
6158
- clear: (deviceId) => clearDeviceSettings(door, deviceId)
6159
- };
6304
+ await ctx.api.addons.restartAddon.mutate({ addonId });
6305
+ }));
6160
6306
  }
6161
6307
  //#endregion
6162
6308
  //#region src/builtins/device-manager/device-meta-actions.ts
@@ -6455,6 +6601,7 @@ async function registerDevice(pctx, input) {
6455
6601
  features: featuresArr,
6456
6602
  exportFingerprint: fingerprint
6457
6603
  });
6604
+ if (existingMeta?.alias === void 0) await pctx.metaStore.rows.patch(id, { alias: await freeAliasFor(pctx.metaStore.rows, resolvedName, id, await readReservedAliases(pctx)) });
6458
6605
  const descendantsFilled = [];
6459
6606
  const descendantsFailed = [];
6460
6607
  if (inherited !== null) for (const descendant of await collectDescendants(pctx.metaStore, id)) {
@@ -6645,6 +6792,7 @@ async function removeDevice(pctx, input) {
6645
6792
  const { addonId, stableId, meta: persistedMeta } = persisted;
6646
6793
  const deviceName = persistedMeta.name;
6647
6794
  await pctx.metaStore.withMetaWriteLock(async () => {
6795
+ if (persistedMeta.alias !== void 0) await reserveAliasOfRemovedDevice(pctx, persistedMeta.alias, deviceId);
6648
6796
  await pctx.metaStore.rows.remove(deviceId);
6649
6797
  pctx.removalFence.record({
6650
6798
  deviceId,
@@ -8567,6 +8715,10 @@ var DEVICE_ROWS_COLUMNS = [
8567
8715
  type: "TEXT",
8568
8716
  notNull: true
8569
8717
  },
8718
+ {
8719
+ name: "alias",
8720
+ type: "TEXT"
8721
+ },
8570
8722
  {
8571
8723
  name: "userNamed",
8572
8724
  type: "BOOLEAN"
@@ -8670,6 +8822,10 @@ var DEVICE_ROWS_INDEXES = [
8670
8822
  {
8671
8823
  name: "idx_dm_devices_integration",
8672
8824
  columns: ["integrationId"]
8825
+ },
8826
+ {
8827
+ name: "idx_dm_devices_alias",
8828
+ columns: ["alias"]
8673
8829
  }
8674
8830
  ];
8675
8831
  /** Adapt `ctx.api.settingsStore` (tRPC namespace) to {@link DeviceRowBackend}. */
@@ -8734,6 +8890,7 @@ function decodeDeviceRow(data) {
8734
8890
  const linkDeviceId = readNumber(data["linkDeviceId"]);
8735
8891
  const primaryChildEntityId = readString(data["primaryChildEntityId"]);
8736
8892
  const role = readString(data["role"]);
8893
+ const alias = readString(data["alias"]);
8737
8894
  const rawChildLayout = data["childLayout"];
8738
8895
  const rawDisplay = data["display"];
8739
8896
  const rawMetadata = data["metadata"];
@@ -8747,6 +8904,7 @@ function decodeDeviceRow(data) {
8747
8904
  location: location ?? null,
8748
8905
  disabled: readBoolean(data["disabled"]) ?? false,
8749
8906
  parentDeviceId: parentDeviceId ?? null,
8907
+ ...alias !== void 0 ? { alias } : {},
8750
8908
  ...userNamed !== void 0 ? { userNamed } : {},
8751
8909
  ...features !== void 0 ? { features } : {},
8752
8910
  ...exportFingerprint !== void 0 ? { exportFingerprint } : {},
@@ -8786,6 +8944,7 @@ function encodeDeviceRow(meta, extra = {}) {
8786
8944
  stableId: meta.stableId,
8787
8945
  type: meta.type,
8788
8946
  name: meta.name,
8947
+ alias: meta.alias ?? null,
8789
8948
  userNamed: meta.userNamed ?? null,
8790
8949
  location: meta.location,
8791
8950
  disabled: meta.disabled,
@@ -8981,6 +9140,31 @@ var DeviceRowStore = class {
8981
9140
  });
8982
9141
  return first;
8983
9142
  }
9143
+ /**
9144
+ * The device that owns a template alias, or `null`. Aliases are unique, so a
9145
+ * second row for one alias would be a corruption: the LOWEST id is answered and
9146
+ * the duplicate is said on the record.
9147
+ */
9148
+ async findByAlias(alias) {
9149
+ const rows = await this.list({
9150
+ where: { alias },
9151
+ orderBy: {
9152
+ field: "deviceId",
9153
+ direction: "asc"
9154
+ },
9155
+ limit: 2
9156
+ });
9157
+ const first = rows[0];
9158
+ if (first === void 0) return null;
9159
+ if (rows.length > 1) this.logger.warn("duplicate device rows for one alias — using the lowest id", {
9160
+ tags: { deviceId: first.meta.id },
9161
+ meta: {
9162
+ alias,
9163
+ ids: rows.map((r) => r.meta.id)
9164
+ }
9165
+ });
9166
+ return first;
9167
+ }
8984
9168
  /** Every device owned by one addon, ordered by numeric id. */
8985
9169
  async listByAddon(addonId) {
8986
9170
  return this.list({
@@ -11354,6 +11538,11 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
11354
11538
  } catch (err) {
11355
11539
  this.ctx.logger.warn("location backfill failed — fleet boots without it", { meta: { error: require_dist.errMsg(err) } });
11356
11540
  }
11541
+ try {
11542
+ await runDeviceAliasBackfillAtBoot(pctx);
11543
+ } catch (err) {
11544
+ this.ctx.logger.warn("device alias backfill failed — rows without an alias wait for their next registration", { meta: { error: require_dist.errMsg(err) } });
11545
+ }
11357
11546
  try {
11358
11547
  await runLinkedDevicesManualBackfillAtBoot(pctx);
11359
11548
  } catch (err) {
@@ -11382,6 +11571,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
11382
11571
  loadConfig: (input) => loadConfig(pctx, input),
11383
11572
  loadMeta: (input) => loadMeta(pctx, input),
11384
11573
  setName: (input) => setName(pctx, input),
11574
+ setAlias: (input) => setAlias(pctx, input),
11385
11575
  setLocation: (input) => setLocation(pctx, input),
11386
11576
  setType: (input) => setType(pctx, input),
11387
11577
  setIntegrationId: (input) => setIntegrationId(pctx, input),