@camstack/server 1.2.804 → 1.2.806

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