@camstack/server 1.2.803 → 1.2.805

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