@camstack/server 1.2.804 → 1.2.806

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