@camstack/server 1.2.943 → 1.2.944

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 (157) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/closure-pins.json +350 -0
  3. package/dist/api/core/auth-sessions.procedures.js +18 -0
  4. package/dist/api/core/auth.router.js +19 -6
  5. package/dist/api/server-upload.js +17 -1
  6. package/dist/api/trpc/generated-cap-routers.js +83 -0
  7. package/dist/auth/native-return.js +9 -3
  8. package/dist/auth/sso-routes.js +5 -1
  9. package/dist/core/addon/instance-lifecycle.js +4 -1
  10. package/dist/core/auth/handoff-code.service.js +35 -1
  11. package/dist/server-root/index.js +313 -70
  12. package/package.json +21 -11
  13. package/system/dist/{action-index-B1fgpQBt.mjs → action-index-DpYmsOKh.mjs} +1 -1
  14. package/system/dist/{action-index-B_cLRwXJ.js → action-index-Dz9rd1qa.js} +1 -1
  15. package/system/dist/{addon-settings.cap-CZ4MC7ha.mjs → addon-settings.cap-CHpmuaQG.mjs} +1 -1
  16. package/system/dist/{addon-settings.cap-DrLdMFIe.js → addon-settings.cap-nZVHPo3X.js} +1 -1
  17. package/system/dist/{alert-episode-Be--PngO.mjs → alert-episode-D-1VUUkZ.mjs} +1 -1
  18. package/system/dist/{alert-episode-Bqktmt-i.js → alert-episode-DaQ3prSe.js} +1 -1
  19. package/system/dist/{base-addon-CRsXtYFG.js → base-addon-BG7p06Hb.js} +136 -15
  20. package/system/dist/{base-addon-BcS6r1cT.mjs → base-addon-BcVoYZbC.mjs} +136 -15
  21. package/system/dist/{base-device-DAdWzDOl.js → base-device-DeSNiwZ4.js} +4 -4
  22. package/system/dist/{base-device-DJXF5eDN.mjs → base-device-w_MD0Bf4.mjs} +4 -4
  23. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  24. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  25. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  26. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  27. package/system/dist/builtins/alerts/alerts.addon.js +3 -3
  28. package/system/dist/builtins/alerts/alerts.addon.mjs +3 -3
  29. package/system/dist/builtins/autotrack/index.js +1 -1
  30. package/system/dist/builtins/autotrack/index.mjs +1 -1
  31. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +1 -1
  32. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +1 -1
  33. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  34. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  35. package/system/dist/builtins/camera-grid/index.js +3 -3
  36. package/system/dist/builtins/camera-grid/index.mjs +3 -3
  37. package/system/dist/builtins/composer/composer.addon.js +7 -7
  38. package/system/dist/builtins/composer/composer.addon.mjs +7 -7
  39. package/system/dist/builtins/console-logging/index.js +1 -1
  40. package/system/dist/builtins/console-logging/index.mjs +1 -1
  41. package/system/dist/builtins/core-blocks/actions-store.d.ts +2 -0
  42. package/system/dist/builtins/core-blocks/block-supervisor.d.ts +16 -4
  43. package/system/dist/builtins/core-blocks/core-block-store.d.ts +2 -0
  44. package/system/dist/builtins/core-blocks/core-blocks.addon.js +1018 -323
  45. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +986 -291
  46. package/system/dist/builtins/core-blocks/migrations/index.d.ts +5 -2
  47. package/system/dist/builtins/core-blocks/migrations/tag-ids.d.ts +42 -0
  48. package/system/dist/builtins/core-blocks/migrations/tags-as-records.d.ts +47 -0
  49. package/system/dist/builtins/core-blocks/record-kinds.d.ts +12 -1
  50. package/system/dist/builtins/core-blocks/runs-api.d.ts +3 -1
  51. package/system/dist/builtins/core-blocks/runs-ledger.d.ts +3 -1
  52. package/system/dist/builtins/core-blocks/scheduler/scheduler-store.d.ts +2 -0
  53. package/system/dist/builtins/core-blocks/tags-service.d.ts +52 -27
  54. package/system/dist/builtins/core-blocks/tags-wiring.d.ts +2 -0
  55. package/system/dist/builtins/core-notifier/core-notifier.addon.js +76 -67
  56. package/system/dist/builtins/core-notifier/core-notifier.addon.mjs +76 -67
  57. package/system/dist/builtins/device-history/device-history.addon.js +4 -4
  58. package/system/dist/builtins/device-history/device-history.addon.mjs +4 -4
  59. package/system/dist/builtins/device-manager/device-manager.addon.js +1602 -760
  60. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1588 -746
  61. package/system/dist/builtins/device-manager/device-meta-actions.d.ts +13 -136
  62. package/system/dist/builtins/device-manager/device-meta-types.d.ts +5 -1
  63. package/system/dist/builtins/device-manager/device-provider-context.d.ts +9 -0
  64. package/system/dist/builtins/device-manager/device-row-store.d.ts +21 -4
  65. package/system/dist/builtins/device-manager/device-search.d.ts +6 -0
  66. package/system/dist/builtins/device-manager/location-alignment.d.ts +9 -2
  67. package/system/dist/builtins/device-manager/migrate-device.d.ts +7 -2
  68. package/system/dist/builtins/device-manager/migrate-hardware-state.d.ts +132 -1
  69. package/system/dist/builtins/device-manager/migrations/device-tag-ids.d.ts +25 -0
  70. package/system/dist/builtins/device-manager/migrations/index.d.ts +16 -0
  71. package/system/dist/builtins/device-manager/migrations/orphan-children.d.ts +33 -0
  72. package/system/dist/builtins/device-manager/migrations/ports.d.ts +17 -0
  73. package/system/dist/builtins/device-manager/migrations/rooms-as-records.d.ts +52 -0
  74. package/system/dist/builtins/device-manager/record-kinds.d.ts +3 -1
  75. package/system/dist/builtins/device-manager/removal-cleanup.d.ts +7 -0
  76. package/system/dist/builtins/device-manager/room-actions.d.ts +27 -0
  77. package/system/dist/builtins/device-manager/room-store.d.ts +19 -0
  78. package/system/dist/builtins/device-manager/tag-names.d.ts +32 -0
  79. package/system/dist/builtins/device-manager/wireable-enum-catalog.d.ts +18 -0
  80. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  81. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  82. package/system/dist/builtins/keychain/index.js +2 -2
  83. package/system/dist/builtins/keychain/index.mjs +2 -2
  84. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  85. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  86. package/system/dist/builtins/local-auth/local-auth.addon.js +1 -1
  87. package/system/dist/builtins/local-auth/local-auth.addon.mjs +1 -1
  88. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  89. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  90. package/system/dist/builtins/loki-logging/index.js +2 -2
  91. package/system/dist/builtins/loki-logging/index.mjs +2 -2
  92. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  93. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  94. package/system/dist/builtins/platform-probe/index.js +1 -1
  95. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  96. package/system/dist/builtins/record-entries/index.js +1 -1
  97. package/system/dist/builtins/record-entries/index.mjs +1 -1
  98. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  99. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  100. package/system/dist/builtins/snapshot/index.js +1 -1
  101. package/system/dist/builtins/snapshot/index.mjs +1 -1
  102. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  103. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  104. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  105. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  106. package/system/dist/builtins/sqlite-storage/migrations/migration-engine.d.ts +3 -1
  107. package/system/dist/builtins/sqlite-storage/migrations/migrations-provider.d.ts +1 -0
  108. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +15 -10
  109. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +15 -10
  110. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  111. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  112. package/system/dist/builtins/system-config/system-config.addon.js +1 -1
  113. package/system/dist/builtins/system-config/system-config.addon.mjs +1 -1
  114. package/system/dist/builtins/winston-logging/index.js +2 -2
  115. package/system/dist/builtins/winston-logging/index.mjs +2 -2
  116. package/system/dist/{command-catalog-C29hVOOg.js → command-catalog-CI0tu1Nt.js} +1 -1
  117. package/system/dist/{command-catalog-xAeqxbZk.mjs → command-catalog-zwlIA3T5.mjs} +1 -1
  118. package/system/dist/{composition-sources-C327LGFn.mjs → composition-sources-CXxXfh1z.mjs} +1 -1
  119. package/system/dist/{composition-sources-Do5qM6EB.js → composition-sources-DNgSItK-.js} +1 -1
  120. package/system/dist/{core-blocks.cap-CdTGUKtr.js → core-blocks.cap-BHEok4VO.js} +125 -373
  121. package/system/dist/{core-blocks.cap-DLkEfV5b.mjs → core-blocks.cap-CPgZRcpj.mjs} +109 -327
  122. package/system/dist/{device-manager.cap-DJs8izI6.js → device-manager.cap-B9qVf7ag.js} +163 -22
  123. package/system/dist/{device-manager.cap-eYrj1Ezp.mjs → device-manager.cap-CV4KGp3e.mjs} +134 -17
  124. package/system/dist/{error.cap-CU1FB6uE.mjs → error.cap-B8l7L8e4.mjs} +7 -1
  125. package/system/dist/{error.cap-BuKbL3Ac.js → error.cap-BqlvgBJd.js} +7 -1
  126. package/system/dist/file-host-worker.js +1 -1
  127. package/system/dist/file-host-worker.mjs +1 -1
  128. package/system/dist/index.js +7 -7
  129. package/system/dist/index.mjs +6 -6
  130. package/system/dist/{legacy-integration-rows-door-CdqYAj-o.js → legacy-integration-rows-door-BK8eoGlF.js} +1 -1
  131. package/system/dist/{legacy-integration-rows-door-LSgpClpX.mjs → legacy-integration-rows-door-CwzC5XNk.mjs} +1 -1
  132. package/system/dist/{migration-DGAc6ywR.mjs → migration-BvbfW9g-.mjs} +6 -0
  133. package/system/dist/{migration-BOQlFZCN.js → migration-CHPdAdNh.js} +6 -0
  134. package/system/dist/{prefix-walk-BFnw8NBu.js → named-entity-store-DFwLij9c.js} +244 -90
  135. package/system/dist/{prefix-walk-Mtij0NNT.mjs → named-entity-store-DOnyyFFf.mjs} +195 -89
  136. package/system/dist/{notification-rules.cap-BUIuYPlQ.mjs → notification-rules.cap-ClvK6QT1.mjs} +10 -5
  137. package/system/dist/{notification-rules.cap-BJKUjizS.js → notification-rules.cap-uSLoe2pA.js} +10 -5
  138. package/system/dist/{notification-targets-DMW7xgR2.js → notification-targets-ChqpBbtR.js} +2 -2
  139. package/system/dist/{notification-targets-4bGYH5J7.mjs → notification-targets-DUA6-F2t.mjs} +2 -2
  140. package/system/dist/{device-row-store-CTocYKqC.mjs → record-kinds-BD2xv4Pd.mjs} +222 -93
  141. package/system/dist/{device-row-store-C0P2H18h.js → record-kinds-BV8Gcpsx.js} +246 -93
  142. package/system/dist/records/named-entity-store.d.ts +60 -0
  143. package/system/dist/{rename-composition-block-Cdh-dRmY.mjs → rename-composition-block-C3QQ9UUE.mjs} +134 -33
  144. package/system/dist/{rename-composition-block-D9Uc1AF7.js → rename-composition-block-Cx3X8QSm.js} +134 -33
  145. package/system/dist/{retention-source.cap-C6Hy0hlM.js → retention-source.cap-A-TMhU5O.js} +1 -1
  146. package/system/dist/{retention-source.cap-550kkyp5.mjs → retention-source.cap-Ct07pM30.mjs} +1 -1
  147. package/system/dist/{storage-admin.cap-Ci4QbL6P.mjs → storage-admin.cap-C54s9_B9.mjs} +8 -2
  148. package/system/dist/{storage-admin.cap-DqW1ol4j.js → storage-admin.cap-DSPHi7ut.js} +8 -2
  149. package/system/dist/{stream-catalog.cap-CjEQFknc.js → stream-catalog.cap-7WPsugOy.js} +1 -1
  150. package/system/dist/{stream-catalog.cap-DVniDdRD.mjs → stream-catalog.cap-CzwRDaqT.mjs} +1 -1
  151. package/system/dist/{tag-BxLazvVb.js → tag-BLraBqvp.js} +12 -0
  152. package/system/dist/{tag-uZBAq6ox.mjs → tag-DU8pm9Bi.mjs} +7 -1
  153. package/system/dist/time-window-B6UhCArd.js +679 -0
  154. package/system/dist/time-window-BnUBULgu.mjs +578 -0
  155. package/system/dist/{wal-maintenance-BgYiAy5b.js → wal-maintenance-CkPfVApC.js} +0 -0
  156. package/system/dist/{wal-maintenance-Bey5ChBb.mjs → wal-maintenance-u84_1sVl.mjs} +0 -0
  157. package/system/package.json +1 -1
@@ -3,30 +3,31 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_stream_catalog_cap = require("../../stream-catalog.cap-CjEQFknc.js");
7
- const require_base_addon = require("../../base-addon-CRsXtYFG.js");
6
+ const require_stream_catalog_cap = require("../../stream-catalog.cap-7WPsugOy.js");
7
+ const require_base_addon = require("../../base-addon-BG7p06Hb.js");
8
8
  const require_scoped_settings = require("../../scoped-settings-CylSSq_8.js");
9
- const require_rename_composition_block = require("../../rename-composition-block-D9Uc1AF7.js");
9
+ const require_rename_composition_block = require("../../rename-composition-block-Cx3X8QSm.js");
10
10
  const require_camstack_error = require("../../camstack-error-DJ-TUAi1.js");
11
11
  const require_capability_definition = require("../../capability-definition-BEVd01Xj.js");
12
12
  const require_zod_secret = require("../../zod-secret-DS7mj1bk.js");
13
- const require_device_manager_cap = require("../../device-manager.cap-DJs8izI6.js");
13
+ const require_device_manager_cap = require("../../device-manager.cap-B9qVf7ag.js");
14
14
  const require_device_identifiers = require("../../device-identifiers-BQg9EQi1.js");
15
- const require_tag = require("../../tag-BxLazvVb.js");
15
+ const require_record_kinds = require("../../record-kinds-BV8Gcpsx.js");
16
+ const require_migration = require("../../migration-CHPdAdNh.js");
17
+ const require_tag = require("../../tag-BLraBqvp.js");
16
18
  const require_device_type = require("../../device-type-Cnc0NiSX.js");
17
19
  const require_device_kind = require("../../device-kind-FMhJg8uC.js");
18
- const require_action_index = require("../../action-index-B_cLRwXJ.js");
19
- const require_addon_settings_cap = require("../../addon-settings.cap-DrLdMFIe.js");
20
- const require_core_blocks_cap = require("../../core-blocks.cap-CdTGUKtr.js");
20
+ const require_core_blocks_cap = require("../../core-blocks.cap-BHEok4VO.js");
21
+ const require_action_index = require("../../action-index-Dz9rd1qa.js");
22
+ const require_addon_settings_cap = require("../../addon-settings.cap-nZVHPo3X.js");
21
23
  require("../../compile-SpeAhaZ6.js");
22
24
  const require_source_info = require("../../source-info-DtWf4k2j.js");
23
- const require_prefix_walk = require("../../prefix-walk-BFnw8NBu.js");
24
- const require_command_catalog = require("../../command-catalog-C29hVOOg.js");
25
+ const require_named_entity_store = require("../../named-entity-store-DFwLij9c.js");
26
+ const require_command_catalog = require("../../command-catalog-CI0tu1Nt.js");
25
27
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
26
28
  const require_log_redactor = require("../../log-redactor-BhIEMaG9.js");
27
29
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
28
30
  const require_retired_settings_keys = require("../../retired-settings-keys-C8nOOr5H.js");
29
- const require_device_row_store = require("../../device-row-store-C0P2H18h.js");
30
31
  const require_template_protocol = require("../../template-protocol-D5ogm1rj.js");
31
32
  const require_dns_wire = require("../../dns-wire-B1BvF9Ao.js");
32
33
  let zod = require("zod");
@@ -2947,6 +2948,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
2947
2948
  access: "create",
2948
2949
  role: "admin"
2949
2950
  },
2951
+ "deviceManager.deleteRoom": {
2952
+ capName: "device-manager",
2953
+ capScope: "system",
2954
+ addonId: null,
2955
+ access: "delete",
2956
+ role: "admin"
2957
+ },
2950
2958
  "deviceManager.disable": {
2951
2959
  capName: "device-manager",
2952
2960
  capScope: "system",
@@ -3003,6 +3011,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3003
3011
  access: "create",
3004
3012
  role: "admin"
3005
3013
  },
3014
+ "deviceManager.ensureRoom": {
3015
+ capName: "device-manager",
3016
+ capScope: "system",
3017
+ addonId: null,
3018
+ access: "create",
3019
+ role: "admin"
3020
+ },
3006
3021
  "deviceManager.getAllBindings": {
3007
3022
  capName: "device-manager",
3008
3023
  capScope: "system",
@@ -3227,6 +3242,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3227
3242
  access: "view",
3228
3243
  role: "admin"
3229
3244
  },
3245
+ "deviceManager.listRooms": {
3246
+ capName: "device-manager",
3247
+ capScope: "system",
3248
+ addonId: null,
3249
+ access: "view",
3250
+ role: "viewer"
3251
+ },
3230
3252
  "deviceManager.listSiteZones": {
3231
3253
  capName: "device-manager",
3232
3254
  capScope: "system",
@@ -3367,6 +3389,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3367
3389
  access: "view",
3368
3390
  role: "admin"
3369
3391
  },
3392
+ "deviceManager.repairMigrationSecrets": {
3393
+ capName: "device-manager",
3394
+ capScope: "system",
3395
+ addonId: null,
3396
+ access: "create",
3397
+ role: "admin"
3398
+ },
3370
3399
  "deviceManager.reportDiscoveryObservations": {
3371
3400
  capName: "device-manager",
3372
3401
  capScope: "system",
@@ -3598,6 +3627,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
3598
3627
  access: "create",
3599
3628
  role: "admin"
3600
3629
  },
3630
+ "deviceManager.updateRoom": {
3631
+ capName: "device-manager",
3632
+ capScope: "system",
3633
+ addonId: null,
3634
+ access: "create",
3635
+ role: "admin"
3636
+ },
3601
3637
  "deviceOps.getConfigEntries": {
3602
3638
  capName: "device-ops",
3603
3639
  capScope: "device",
@@ -10444,6 +10480,20 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
10444
10480
  access: "create",
10445
10481
  role: "admin"
10446
10482
  },
10483
+ "tags.deleteTag": {
10484
+ capName: "tags",
10485
+ capScope: "system",
10486
+ addonId: null,
10487
+ access: "delete",
10488
+ role: "admin"
10489
+ },
10490
+ "tags.ensureTag": {
10491
+ capName: "tags",
10492
+ capScope: "system",
10493
+ addonId: null,
10494
+ access: "create",
10495
+ role: "admin"
10496
+ },
10447
10497
  "tags.list": {
10448
10498
  capName: "tags",
10449
10499
  capScope: "system",
@@ -10451,6 +10501,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
10451
10501
  access: "view",
10452
10502
  role: "admin"
10453
10503
  },
10504
+ "tags.listTags": {
10505
+ capName: "tags",
10506
+ capScope: "system",
10507
+ addonId: null,
10508
+ access: "view",
10509
+ role: "admin"
10510
+ },
10454
10511
  "tags.remove": {
10455
10512
  capName: "tags",
10456
10513
  capScope: "system",
@@ -10472,6 +10529,13 @@ var METHOD_ACCESS_MAP = /* @__PURE__ */ Object.freeze({
10472
10529
  access: "create",
10473
10530
  role: "admin"
10474
10531
  },
10532
+ "tags.updateTag": {
10533
+ capName: "tags",
10534
+ capScope: "system",
10535
+ addonId: null,
10536
+ access: "create",
10537
+ role: "admin"
10538
+ },
10475
10539
  "tamper.getStatus": {
10476
10540
  capName: "tamper",
10477
10541
  capScope: "device",
@@ -12519,104 +12583,629 @@ function resolveCommandHold(cap, method, args, current, option, shown = current)
12519
12583
  };
12520
12584
  }
12521
12585
  //#endregion
12522
- //#region src/builtins/device-manager/adoption-job-engine.ts
12523
- /** How many finished jobs are kept per (addonId, integrationId). */
12524
- var JOB_HISTORY = 20;
12525
- function snapshot(j) {
12526
- let adopted = 0;
12527
- let alreadyAdopted = 0;
12528
- let failed = 0;
12529
- let processed = 0;
12530
- let accessoriesCreated = 0;
12531
- for (const r of j.results) {
12532
- if (r.outcome === "cancelled") continue;
12533
- processed += 1;
12534
- accessoriesCreated += r.accessoryCount;
12535
- if (r.outcome === "adopted") adopted += 1;
12536
- else if (r.outcome === "already-adopted") alreadyAdopted += 1;
12537
- else if (r.outcome === "failed") failed += 1;
12586
+ //#region src/builtins/device-manager/migrations/device-tag-ids.ts
12587
+ /**
12588
+ * A device row gets the ids of its tags (D1089, the device-manager step of the tags
12589
+ * migration): `tagIds` is added beside the kept `tags` names, aligned by index, with each id
12590
+ * derived from the folded name (`tagIdFromKey`) so every owner of that name mints the same
12591
+ * one. The names stay for one release; the `tags` records are written later by the
12592
+ * core-blocks tags-as-records procedure, which `dependsOn` this step.
12593
+ *
12594
+ * ONE plan, one transaction. A row that already has `tagIds` is left alone (a rerun is
12595
+ * empty); a row whose names repeat one tag in two spellings is rewritten with both columns
12596
+ * de-duplicated, so the index alignment holds.
12597
+ */
12598
+ var DEVICE_TAG_IDS_ID = "device-manager/2026-11-23-device-tag-ids";
12599
+ async function planDeviceTagIds(ports) {
12600
+ const rows = await ports.readDeviceTags();
12601
+ const edits = [];
12602
+ for (const row of rows) {
12603
+ if (row.hasTagIds) continue;
12604
+ const names = require_tag.normalizeTags(row.tags);
12605
+ if (names.length === 0) continue;
12606
+ const sameNames = names.length === row.tags.length;
12607
+ edits.push({
12608
+ op: "putRow",
12609
+ table: require_record_kinds.DEVICE_ROWS_COLLECTION,
12610
+ key: { deviceId: row.deviceId },
12611
+ row: {
12612
+ tagIds: names.map((name) => require_named_entity_store.tagIdFromKey(require_tag.tagKey(name))),
12613
+ ...sameNames ? {} : { tags: names }
12614
+ },
12615
+ preconditionColumns: ["tagIds"],
12616
+ precondition: require_migration.preconditionOf({ tagIds: null })
12617
+ });
12618
+ }
12619
+ return { edits };
12620
+ }
12621
+ //#endregion
12622
+ //#region src/builtins/device-manager/migrations/orphan-children.ts
12623
+ /** The rows that name a parent no row answers to. */
12624
+ function orphansOf(rows) {
12625
+ const ids = new Set(rows.map((r) => r.id));
12626
+ return rows.filter((r) => r.parentDeviceId !== null && !ids.has(r.parentDeviceId));
12627
+ }
12628
+ /**
12629
+ * Destructive on one read is never enough (D49): a row is removed only when TWO
12630
+ * reads agree it is an orphan, and nothing is removed from a read that may have
12631
+ * been cut short at the row limit. The candidate ids are recorded in the summary
12632
+ * and the log BEFORE any removal.
12633
+ */
12634
+ async function removeOrphanChildren(ports) {
12635
+ const first = await ports.listRows();
12636
+ if (first.length >= ports.rowLimit) throw new Error(`device-manager: ${first.length} rows read, the limit is ${ports.rowLimit} — the read may be truncated, nothing removed`);
12637
+ const candidates = orphansOf(first);
12638
+ if (candidates.length === 0) return {
12639
+ outcome: "already-done",
12640
+ summary: {
12641
+ candidates: [],
12642
+ removed: []
12643
+ }
12644
+ };
12645
+ const second = await ports.listRows();
12646
+ const stillOrphans = new Set(orphansOf(second).map((r) => r.id));
12647
+ const confirmed = candidates.filter((r) => stillOrphans.has(r.id));
12648
+ const candidateIds = candidates.map((r) => r.id);
12649
+ ports.summary({
12650
+ rows: first.length,
12651
+ candidateCount: candidateIds.length,
12652
+ candidates: candidateIds,
12653
+ confirmedCount: confirmed.length,
12654
+ confirmed: confirmed.map((r) => r.id)
12655
+ });
12656
+ const removed = [];
12657
+ for (const orphan of confirmed) {
12658
+ if (orphan.parentDeviceId === null) continue;
12659
+ ports.info("device-manager: removing an orphan child, its parent no longer exists", orphan.id, orphan.parentDeviceId);
12660
+ await ports.removeDevice(orphan.id);
12661
+ removed.push(orphan.id);
12538
12662
  }
12539
12663
  return {
12540
- jobId: j.jobId,
12541
- addonId: j.addonId,
12542
- integrationId: j.integrationId,
12543
- state: j.state,
12544
- total: j.total,
12545
- processed,
12546
- adopted,
12547
- alreadyAdopted,
12548
- failed,
12549
- accessoriesCreated,
12550
- currentChildNativeId: j.currentChildNativeId,
12551
- results: j.results.map((r) => ({
12552
- childNativeId: r.childNativeId,
12553
- outcome: r.outcome,
12554
- parentDeviceId: r.parentDeviceId,
12555
- accessoryCount: r.accessoryCount,
12556
- error: r.error
12557
- })),
12558
- startedAt: j.startedAt,
12559
- finishedAt: j.finishedAt,
12560
- error: j.error
12664
+ outcome: "done",
12665
+ summary: {
12666
+ candidates: candidateIds,
12667
+ removed
12668
+ }
12561
12669
  };
12562
12670
  }
12563
- var AdoptionJobEngine = class {
12564
- deps;
12565
- jobs = /* @__PURE__ */ new Map();
12566
- seq = 0;
12567
- constructor(deps) {
12568
- this.deps = deps;
12569
- }
12570
- now() {
12571
- return this.deps.now?.() ?? Date.now();
12671
+ //#endregion
12672
+ //#region src/builtins/device-manager/device-meta-types.ts
12673
+ /**
12674
+ * Decode the raw `ctx.settings.readAddonStore()` record into {@link AddonStore}.
12675
+ *
12676
+ * A field of the wrong shape reads as ABSENT rather than being trusted through
12677
+ * a cast: the store is JSON on disk and a hand-edit or a partial restore must
12678
+ * cost the caller its default, never a downstream `TypeError`.
12679
+ */
12680
+ function decodeAddonStore(raw) {
12681
+ const nextDeviceId = raw["nextDeviceId"];
12682
+ const locations = raw["locations"];
12683
+ const roleDisplayDefaults = raw["roleDisplayDefaults"];
12684
+ const locationIcons = decodeLocationIcons(raw["locationIcons"]);
12685
+ const locationDescriptions = decodeLocationDescriptions(raw["locationDescriptions"]);
12686
+ const siteZones = decodeSiteZones(raw["siteZones"]);
12687
+ const locationZones = decodeStringMap(raw["locationZones"]);
12688
+ return {
12689
+ ...typeof nextDeviceId === "number" && Number.isFinite(nextDeviceId) ? { nextDeviceId } : {},
12690
+ ...Array.isArray(locations) ? { locations: locations.filter((l) => typeof l === "string") } : {},
12691
+ ...isRoleDisplayDefaults(roleDisplayDefaults) ? { roleDisplayDefaults } : {},
12692
+ ...locationIcons !== null ? { locationIcons } : {},
12693
+ ...locationDescriptions !== null ? { locationDescriptions } : {},
12694
+ ...siteZones !== null ? { siteZones } : {},
12695
+ ...locationZones !== null ? { locationZones } : {}
12696
+ };
12697
+ }
12698
+ /**
12699
+ * Decode the `locationIcons` map, dropping every entry whose value is not a
12700
+ * member of the closed vocabulary.
12701
+ *
12702
+ * Dropping, not passing through: the icon's whole point is that both surfaces
12703
+ * can draw it, and an id from a hand-edit or a newer hub is exactly the value
12704
+ * that draws nothing. Absent reads as "no icon chosen", which every renderer
12705
+ * already degrades to the fallback pin. Returns `null` when the key itself is
12706
+ * absent or of the wrong shape, so the field stays OMITTED rather than being
12707
+ * written back as an empty object.
12708
+ */
12709
+ function decodeLocationIcons(raw) {
12710
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12711
+ const out = {};
12712
+ for (const [key, value] of Object.entries(raw)) {
12713
+ const icon = require_tag.canonicalIconKey(value);
12714
+ if (icon === void 0) continue;
12715
+ out[key] = icon;
12572
12716
  }
12573
- newId() {
12574
- if (this.deps.newId) return this.deps.newId();
12575
- this.seq += 1;
12576
- return `adopt-${Date.now().toString(36)}-${this.seq}`;
12717
+ return out;
12718
+ }
12719
+ /**
12720
+ * Decode the `locationDescriptions` map, dropping every entry that is not a
12721
+ * non-blank string.
12722
+ *
12723
+ * Same posture as the icons: a blank description and a missing one are the
12724
+ * same instruction to every reader, and storing the first would send an empty
12725
+ * line to a vision model. Over-long text is TRUNCATED rather than dropped —
12726
+ * losing the whole description because a hand-edit ran long is a worse answer
12727
+ * than losing its tail.
12728
+ */
12729
+ function decodeLocationDescriptions(raw) {
12730
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12731
+ const out = {};
12732
+ for (const [key, value] of Object.entries(raw)) {
12733
+ if (typeof value !== "string") continue;
12734
+ const text = value.trim();
12735
+ if (text.length === 0) continue;
12736
+ out[key] = text.slice(0, 400);
12577
12737
  }
12578
- /**
12579
- * Accept the batch and return immediately. The provider is resolved BEFORE
12580
- * returning so an unroutable `addonId` is refused at the call the operator
12581
- * made, not buried in a job they have to go looking for.
12582
- */
12583
- async start(input) {
12584
- const provider = await this.deps.resolveProvider(input.addonId);
12585
- const job = {
12586
- jobId: this.newId(),
12587
- addonId: input.addonId,
12588
- integrationId: input.integrationId,
12589
- state: "running",
12590
- total: input.childNativeIds.length,
12591
- currentChildNativeId: null,
12592
- results: [],
12593
- startedAt: this.now(),
12594
- finishedAt: null,
12595
- error: null,
12596
- cancelRequested: false,
12597
- done: Promise.resolve()
12738
+ return out;
12739
+ }
12740
+ /**
12741
+ * Decode the zone registry, dropping any entry without a usable label.
12742
+ *
12743
+ * A zone whose label did not survive a hand-edit cannot be shown or renamed —
12744
+ * it would be a row the operator can see the effects of and never name. An
12745
+ * icon outside the vocabulary is dropped on its own, leaving the zone: losing
12746
+ * a glyph is a smaller loss than losing the grouping.
12747
+ */
12748
+ function decodeSiteZones(raw) {
12749
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12750
+ const out = {};
12751
+ for (const [key, value] of Object.entries(raw)) {
12752
+ if (value === null || typeof value !== "object" || Array.isArray(value)) continue;
12753
+ const rec = value;
12754
+ const label = typeof rec["label"] === "string" ? rec["label"].trim() : "";
12755
+ if (label.length === 0) continue;
12756
+ const icon = require_tag.canonicalIconKey(rec["icon"]);
12757
+ out[key] = icon === void 0 ? { label } : {
12758
+ label,
12759
+ icon
12598
12760
  };
12599
- this.jobs.set(job.jobId, job);
12600
- this.prune(input.addonId, input.integrationId);
12601
- this.deps.logger.info("adoption job started", {
12602
- tags: { addonId: input.addonId },
12603
- meta: {
12604
- jobId: job.jobId,
12605
- integrationId: input.integrationId,
12606
- total: job.total
12607
- }
12608
- });
12609
- job.done = this.run(job, provider, input);
12610
- return { jobId: job.jobId };
12611
12761
  }
12612
- get(jobId) {
12613
- const j = this.jobs.get(jobId);
12614
- return j ? snapshot(j) : null;
12615
- }
12616
- list(filter) {
12617
- return [...this.jobs.values()].filter((j) => (filter.addonId === void 0 || j.addonId === filter.addonId) && (filter.integrationId === void 0 || j.integrationId === filter.integrationId)).sort((a, b) => b.startedAt - a.startedAt || b.jobId.localeCompare(a.jobId)).map(snapshot);
12762
+ return out;
12763
+ }
12764
+ /** Decode a plain `string → string` map, dropping anything else. */
12765
+ function decodeStringMap(raw) {
12766
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
12767
+ const out = {};
12768
+ for (const [key, value] of Object.entries(raw)) {
12769
+ if (typeof value !== "string" || value.trim().length === 0) continue;
12770
+ out[key] = value;
12618
12771
  }
12619
- /** Cooperative cancel — the in-flight candidate finishes, the rest do not start. */
12772
+ return out;
12773
+ }
12774
+ function isRoleDisplayDefaults(value) {
12775
+ return value !== null && typeof value === "object" && !Array.isArray(value);
12776
+ }
12777
+ //#endregion
12778
+ //#region src/builtins/device-manager/migrations/rooms-as-records.ts
12779
+ /**
12780
+ * Rooms and site zones become records with an id (D1089, step 1 of the migration).
12781
+ *
12782
+ * Before: a room was a LABEL. The registry (`locations`), its icon and description maps
12783
+ * and the two zone maps (`siteZones`, `locationZones`) lived as keys of the addon store,
12784
+ * and a device carried the label in its `location` column.
12785
+ *
12786
+ * After: one `rooms` record per label and one `zones` record per site zone, with an id
12787
+ * derived from the folded name (`roomIdFromKey` / `zoneIdFromKey`, so a rerun and a
12788
+ * restored older snapshot reach the same ids); a device carries `locationId`; the maps and
12789
+ * the `location` column are gone.
12790
+ *
12791
+ * ONE plan, so ONE transaction with the ledger row: the records, the device rows and the
12792
+ * deleted keys land together or not at all. A rerun finds no legacy key and no device with
12793
+ * a `location`, and the plan is empty. A record that already exists is never rewritten (a
12794
+ * seed never overwrites): a room an operator edited after a partial restore keeps its edit.
12795
+ *
12796
+ * The display spelling is the registry's, else the one most devices use (the first
12797
+ * alphabetically on a tie), else the folded key a map entry carries.
12798
+ */
12799
+ var DEVICE_MANAGER_ID = "device-manager";
12800
+ var ROOMS_AS_RECORDS_ID = "device-manager/2026-11-23-rooms-as-records";
12801
+ /** The canonical settings table: one row per key, id `<addonId>.<key>`. */
12802
+ var ADDON_SETTINGS_TABLE = "addon-settings";
12803
+ /** The addon-store keys this migration retires. */
12804
+ var LEGACY_ROOM_KEYS = [
12805
+ "locations",
12806
+ "locationIcons",
12807
+ "locationDescriptions",
12808
+ "siteZones",
12809
+ "locationZones"
12810
+ ];
12811
+ var isPlainMap = (raw) => raw !== null && typeof raw === "object" && !Array.isArray(raw);
12812
+ /** The entries the decode drops or shortens, raw, before the keys are deleted. */
12813
+ function droppedLegacyEntries(stored) {
12814
+ const out = [];
12815
+ const icons = stored["locationIcons"];
12816
+ if (isPlainMap(icons)) {
12817
+ for (const [key, value] of Object.entries(icons)) if (require_tag.canonicalIconKey(value) === void 0) out.push({
12818
+ map: "locationIcons",
12819
+ key,
12820
+ reason: "icon not in the catalogue",
12821
+ value
12822
+ });
12823
+ }
12824
+ const descriptions = stored["locationDescriptions"];
12825
+ if (isPlainMap(descriptions)) {
12826
+ for (const [key, value] of Object.entries(descriptions)) if (typeof value !== "string" || value.trim().length === 0) out.push({
12827
+ map: "locationDescriptions",
12828
+ key,
12829
+ reason: "blank description",
12830
+ value
12831
+ });
12832
+ else if (value.trim().length > 400) out.push({
12833
+ map: "locationDescriptions",
12834
+ key,
12835
+ reason: "description truncated",
12836
+ value
12837
+ });
12838
+ }
12839
+ const zones = stored["siteZones"];
12840
+ if (isPlainMap(zones)) {
12841
+ for (const [key, value] of Object.entries(zones)) if ((isPlainMap(value) && typeof value["label"] === "string" ? value["label"].trim() : "").length === 0) out.push({
12842
+ map: "siteZones",
12843
+ key,
12844
+ reason: "zone without a label",
12845
+ value
12846
+ });
12847
+ else if (isPlainMap(value) && value["icon"] !== void 0 && require_tag.canonicalIconKey(value["icon"]) === void 0) out.push({
12848
+ map: "siteZones",
12849
+ key,
12850
+ reason: "zone icon not in the catalogue",
12851
+ value
12852
+ });
12853
+ }
12854
+ const membership = stored["locationZones"];
12855
+ if (isPlainMap(membership)) {
12856
+ for (const [key, value] of Object.entries(membership)) if (typeof value !== "string" || value.trim().length === 0) out.push({
12857
+ map: "locationZones",
12858
+ key,
12859
+ reason: "blank zone",
12860
+ value
12861
+ });
12862
+ else if (!isPlainMap(zones) || zones[value] === void 0) out.push({
12863
+ map: "locationZones",
12864
+ key,
12865
+ reason: "zone not in the registry",
12866
+ value
12867
+ });
12868
+ }
12869
+ return out;
12870
+ }
12871
+ /** A map keyed by the FOLDED room key: a legacy key that was never folded still matches. */
12872
+ function foldedBy(map) {
12873
+ const out = /* @__PURE__ */ new Map();
12874
+ for (const [key, value] of Object.entries(map ?? {})) {
12875
+ const folded = require_addon_settings_cap.locationIconKey(key);
12876
+ if (folded.length > 0 && !out.has(folded)) out.set(folded, value);
12877
+ }
12878
+ return out;
12879
+ }
12880
+ var settingsRowId = (key) => `${DEVICE_MANAGER_ID}.${key}`;
12881
+ function clip(name) {
12882
+ return name.trim().slice(0, 80);
12883
+ }
12884
+ /** The spelling to show for each folded room key: registry first, else the most used on devices. */
12885
+ function spellings(registry, devices) {
12886
+ const out = /* @__PURE__ */ new Map();
12887
+ for (const label of registry) {
12888
+ const key = require_addon_settings_cap.locationIconKey(label);
12889
+ if (key.length > 0 && !out.has(key)) out.set(key, clip(label));
12890
+ }
12891
+ const used = /* @__PURE__ */ new Map();
12892
+ for (const { location } of devices) {
12893
+ if (location === null) continue;
12894
+ const key = require_addon_settings_cap.locationIconKey(location);
12895
+ if (key.length === 0) continue;
12896
+ const counts = used.get(key) ?? /* @__PURE__ */ new Map();
12897
+ counts.set(location.trim(), (counts.get(location.trim()) ?? 0) + 1);
12898
+ used.set(key, counts);
12899
+ }
12900
+ for (const [key, counts] of used) {
12901
+ if (out.has(key)) continue;
12902
+ const best = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0];
12903
+ if (best !== void 0) out.set(key, clip(best[0]));
12904
+ }
12905
+ return out;
12906
+ }
12907
+ async function planRoomsAsRecords(ports) {
12908
+ const stored = await ports.readStored(LEGACY_ROOM_KEYS);
12909
+ const store = decodeAddonStore(stored);
12910
+ const devices = await ports.readDeviceLocations();
12911
+ const existingRooms = await ports.readRoomIds();
12912
+ const existingZones = await ports.readZoneIds();
12913
+ const names = spellings(store.locations ?? [], devices);
12914
+ for (const key of [
12915
+ ...Object.keys(store.locationIcons ?? {}),
12916
+ ...Object.keys(store.locationDescriptions ?? {}),
12917
+ ...Object.keys(store.locationZones ?? {})
12918
+ ]) {
12919
+ const folded = require_addon_settings_cap.locationIconKey(key);
12920
+ if (folded.length > 0 && !names.has(folded)) names.set(folded, clip(key));
12921
+ }
12922
+ const zones = store.siteZones ?? {};
12923
+ const membership = foldedBy(store.locationZones);
12924
+ const iconsByRoom = foldedBy(store.locationIcons);
12925
+ const descriptionsByRoom = foldedBy(store.locationDescriptions);
12926
+ const dropped = droppedLegacyEntries(stored);
12927
+ if (dropped.length > 0) {
12928
+ const counts = {};
12929
+ for (const entry of dropped) counts[entry.map] = (counts[entry.map] ?? 0) + 1;
12930
+ ports.report?.("rooms migration: legacy entries not carried over", {
12931
+ counts,
12932
+ dropped
12933
+ });
12934
+ }
12935
+ const edits = [];
12936
+ for (const [zoneKey, zone] of Object.entries(zones)) {
12937
+ const id = require_named_entity_store.zoneIdFromKey(zoneKey);
12938
+ if (existingZones.has(id)) continue;
12939
+ const body = {
12940
+ name: clip(zone.label),
12941
+ ...zone.icon === void 0 ? {} : { icon: zone.icon }
12942
+ };
12943
+ edits.push(require_record_kinds.recordUpsertEdit({
12944
+ owner: DEVICE_MANAGER_ID,
12945
+ kind: require_record_kinds.deviceManagerRecordKinds.zones,
12946
+ id,
12947
+ data: body,
12948
+ read: null
12949
+ }));
12950
+ }
12951
+ for (const [key, name] of names) {
12952
+ const id = require_named_entity_store.roomIdFromKey(key);
12953
+ if (existingRooms.has(id)) continue;
12954
+ const icon = iconsByRoom.get(key);
12955
+ const description = descriptionsByRoom.get(key);
12956
+ const zoneKey = membership.get(key);
12957
+ const zoneId = zoneKey !== void 0 && zones[zoneKey] !== void 0 ? require_named_entity_store.zoneIdFromKey(zoneKey) : void 0;
12958
+ const body = {
12959
+ name,
12960
+ ...icon === void 0 ? {} : { icon },
12961
+ ...description === void 0 ? {} : { description },
12962
+ ...zoneId === void 0 ? {} : { zoneId }
12963
+ };
12964
+ edits.push(require_record_kinds.recordUpsertEdit({
12965
+ owner: DEVICE_MANAGER_ID,
12966
+ kind: require_record_kinds.deviceManagerRecordKinds.rooms,
12967
+ id,
12968
+ data: body,
12969
+ read: null
12970
+ }));
12971
+ }
12972
+ for (const device of devices) {
12973
+ if (device.location === null) continue;
12974
+ const folded = require_addon_settings_cap.locationIconKey(device.location);
12975
+ const locationId = device.locationId ?? (folded.length === 0 ? null : require_named_entity_store.roomIdFromKey(folded));
12976
+ edits.push({
12977
+ op: "putRow",
12978
+ table: require_record_kinds.DEVICE_ROWS_COLLECTION,
12979
+ key: { deviceId: device.deviceId },
12980
+ row: {
12981
+ locationId,
12982
+ location: null
12983
+ },
12984
+ preconditionColumns: ["location", "locationId"],
12985
+ precondition: require_migration.preconditionOf({
12986
+ location: device.location,
12987
+ locationId: device.locationId
12988
+ })
12989
+ });
12990
+ }
12991
+ const present = LEGACY_ROOM_KEYS.filter((key) => key in stored);
12992
+ if (present.length > 0) edits.push({
12993
+ op: "deleteKeys",
12994
+ scope: ADDON_SETTINGS_TABLE,
12995
+ keys: present.map(settingsRowId),
12996
+ precondition: require_migration.preconditionOf(Object.fromEntries(present.map((key) => [settingsRowId(key), {
12997
+ addonId: DEVICE_MANAGER_ID,
12998
+ key,
12999
+ value: stored[key]
13000
+ }])))
13001
+ });
13002
+ return { edits };
13003
+ }
13004
+ //#endregion
13005
+ //#region src/builtins/device-manager/migrations/index.ts
13006
+ var REMOVE_ORPHAN_CHILDREN_ID = "device-manager/2026-11-23-remove-orphan-children";
13007
+ /** Rooms, zones and tag ids: run BEFORE the first read resolves a name (D1089). */
13008
+ var ROOMS_AND_TAGS_MIGRATIONS = [{
13009
+ meta: {
13010
+ id: ROOMS_AS_RECORDS_ID,
13011
+ owner: DEVICE_MANAGER_ID,
13012
+ level: "addon-state",
13013
+ seq: 1,
13014
+ dependsOn: [],
13015
+ store: "settings",
13016
+ scope: "cluster",
13017
+ onFailure: "tolerate",
13018
+ bodyKind: "plan",
13019
+ description: "Rooms and site zones become records with an id: one record per label, a locationId on each device, and the label maps and the location column deleted, in one transaction",
13020
+ fixtureMark: "a device column and a room icon the migration does not know"
13021
+ },
13022
+ plan: (ports) => planRoomsAsRecords(ports)
13023
+ }, {
13024
+ meta: {
13025
+ id: DEVICE_TAG_IDS_ID,
13026
+ owner: DEVICE_MANAGER_ID,
13027
+ level: "addon-state",
13028
+ seq: 2,
13029
+ dependsOn: [],
13030
+ store: "settings",
13031
+ scope: "cluster",
13032
+ onFailure: "tolerate",
13033
+ bodyKind: "plan",
13034
+ description: "Add the ids of its tags to each device row beside the kept names, derived from the folded name",
13035
+ fixtureMark: "a device column the migration does not know"
13036
+ },
13037
+ plan: (ports) => planDeviceTagIds(ports)
13038
+ }];
13039
+ /** Accessory rows left behind by a removal that did not cascade: run once the fleet is up (D987). */
13040
+ var ORPHAN_CHILDREN_MIGRATIONS = [{
13041
+ meta: {
13042
+ id: REMOVE_ORPHAN_CHILDREN_ID,
13043
+ owner: DEVICE_MANAGER_ID,
13044
+ level: "addon-state",
13045
+ seq: 3,
13046
+ dependsOn: [],
13047
+ store: "settings",
13048
+ scope: "cluster",
13049
+ onFailure: "tolerate",
13050
+ bodyKind: "procedure",
13051
+ description: "Remove every device row whose parentDeviceId names no row, through the tombstoned removal, each one logged",
13052
+ fixtureMark: "a child of a live parent and a top-level row, both kept"
13053
+ },
13054
+ procedure: removeOrphanChildren
13055
+ }];
13056
+ [...ROOMS_AND_TAGS_MIGRATIONS, ...ORPHAN_CHILDREN_MIGRATIONS];
13057
+ //#endregion
13058
+ //#region src/builtins/device-manager/migrations/ports.ts
13059
+ var import_read_all_rows = require_read_all_rows$1.require_read_all_rows();
13060
+ var stringOrNull = (value) => typeof value === "string" ? value : null;
13061
+ function stringArray(value) {
13062
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
13063
+ }
13064
+ function deviceManagerMigrationPorts(source) {
13065
+ return {
13066
+ readStored: async (keys) => {
13067
+ const found = {};
13068
+ for (const key of keys) {
13069
+ const answer = await source.readStoredKey(key);
13070
+ if (answer.kind === "unreadable") throw new Error(`${DEVICE_MANAGER_ID}: the setting ${key} cannot be read (${answer.reason})`);
13071
+ if (answer.kind === "present") found[key] = answer.value;
13072
+ }
13073
+ return found;
13074
+ },
13075
+ readDeviceLocations: async () => {
13076
+ return (await source.rows.readRawColumns([
13077
+ "deviceId",
13078
+ "location",
13079
+ "locationId"
13080
+ ])).flatMap((row) => {
13081
+ const deviceId = row["deviceId"];
13082
+ if (typeof deviceId !== "number") return [];
13083
+ return [{
13084
+ deviceId,
13085
+ location: stringOrNull(row["location"]),
13086
+ locationId: stringOrNull(row["locationId"])
13087
+ }];
13088
+ });
13089
+ },
13090
+ readDeviceTags: async () => {
13091
+ return (await source.rows.readRawColumns([
13092
+ "deviceId",
13093
+ "tags",
13094
+ "tagIds"
13095
+ ])).flatMap((row) => {
13096
+ const deviceId = row["deviceId"];
13097
+ if (typeof deviceId !== "number") return [];
13098
+ return [{
13099
+ deviceId,
13100
+ tags: stringArray(row["tags"]),
13101
+ hasTagIds: row["tagIds"] !== null && row["tagIds"] !== void 0
13102
+ }];
13103
+ });
13104
+ },
13105
+ readRoomIds: async () => new Set((await (0, import_read_all_rows.readAllRows)(source.rooms)).map((row) => row.id)),
13106
+ readZoneIds: async () => new Set((await (0, import_read_all_rows.readAllRows)(source.zones)).map((row) => row.id)),
13107
+ ...source.report === void 0 ? {} : { report: source.report }
13108
+ };
13109
+ }
13110
+ //#endregion
13111
+ //#region src/builtins/device-manager/adoption-job-engine.ts
13112
+ /** How many finished jobs are kept per (addonId, integrationId). */
13113
+ var JOB_HISTORY = 20;
13114
+ function snapshot(j) {
13115
+ let adopted = 0;
13116
+ let alreadyAdopted = 0;
13117
+ let failed = 0;
13118
+ let processed = 0;
13119
+ let accessoriesCreated = 0;
13120
+ for (const r of j.results) {
13121
+ if (r.outcome === "cancelled") continue;
13122
+ processed += 1;
13123
+ accessoriesCreated += r.accessoryCount;
13124
+ if (r.outcome === "adopted") adopted += 1;
13125
+ else if (r.outcome === "already-adopted") alreadyAdopted += 1;
13126
+ else if (r.outcome === "failed") failed += 1;
13127
+ }
13128
+ return {
13129
+ jobId: j.jobId,
13130
+ addonId: j.addonId,
13131
+ integrationId: j.integrationId,
13132
+ state: j.state,
13133
+ total: j.total,
13134
+ processed,
13135
+ adopted,
13136
+ alreadyAdopted,
13137
+ failed,
13138
+ accessoriesCreated,
13139
+ currentChildNativeId: j.currentChildNativeId,
13140
+ results: j.results.map((r) => ({
13141
+ childNativeId: r.childNativeId,
13142
+ outcome: r.outcome,
13143
+ parentDeviceId: r.parentDeviceId,
13144
+ accessoryCount: r.accessoryCount,
13145
+ error: r.error
13146
+ })),
13147
+ startedAt: j.startedAt,
13148
+ finishedAt: j.finishedAt,
13149
+ error: j.error
13150
+ };
13151
+ }
13152
+ var AdoptionJobEngine = class {
13153
+ deps;
13154
+ jobs = /* @__PURE__ */ new Map();
13155
+ seq = 0;
13156
+ constructor(deps) {
13157
+ this.deps = deps;
13158
+ }
13159
+ now() {
13160
+ return this.deps.now?.() ?? Date.now();
13161
+ }
13162
+ newId() {
13163
+ if (this.deps.newId) return this.deps.newId();
13164
+ this.seq += 1;
13165
+ return `adopt-${Date.now().toString(36)}-${this.seq}`;
13166
+ }
13167
+ /**
13168
+ * Accept the batch and return immediately. The provider is resolved BEFORE
13169
+ * returning so an unroutable `addonId` is refused at the call the operator
13170
+ * made, not buried in a job they have to go looking for.
13171
+ */
13172
+ async start(input) {
13173
+ const provider = await this.deps.resolveProvider(input.addonId);
13174
+ const job = {
13175
+ jobId: this.newId(),
13176
+ addonId: input.addonId,
13177
+ integrationId: input.integrationId,
13178
+ state: "running",
13179
+ total: input.childNativeIds.length,
13180
+ currentChildNativeId: null,
13181
+ results: [],
13182
+ startedAt: this.now(),
13183
+ finishedAt: null,
13184
+ error: null,
13185
+ cancelRequested: false,
13186
+ done: Promise.resolve()
13187
+ };
13188
+ this.jobs.set(job.jobId, job);
13189
+ this.prune(input.addonId, input.integrationId);
13190
+ this.deps.logger.info("adoption job started", {
13191
+ tags: { addonId: input.addonId },
13192
+ meta: {
13193
+ jobId: job.jobId,
13194
+ integrationId: input.integrationId,
13195
+ total: job.total
13196
+ }
13197
+ });
13198
+ job.done = this.run(job, provider, input);
13199
+ return { jobId: job.jobId };
13200
+ }
13201
+ get(jobId) {
13202
+ const j = this.jobs.get(jobId);
13203
+ return j ? snapshot(j) : null;
13204
+ }
13205
+ list(filter) {
13206
+ return [...this.jobs.values()].filter((j) => (filter.addonId === void 0 || j.addonId === filter.addonId) && (filter.integrationId === void 0 || j.integrationId === filter.integrationId)).sort((a, b) => b.startedAt - a.startedAt || b.jobId.localeCompare(a.jobId)).map(snapshot);
13207
+ }
13208
+ /** Cooperative cancel — the in-flight candidate finishes, the rest do not start. */
12620
13209
  cancel(jobId) {
12621
13210
  const job = this.jobs.get(jobId);
12622
13211
  if (!job || job.state !== "running") return false;
@@ -13494,6 +14083,104 @@ function sleep(ms) {
13494
14083
  });
13495
14084
  }
13496
14085
  //#endregion
14086
+ //#region src/builtins/device-manager/wireable-enum-catalog.ts
14087
+ /**
14088
+ * Per-device value catalogs for wireable fields (`status.fieldEnums` on a cap).
14089
+ *
14090
+ * A status field such as `error.code` or `event-emitter.lastEvent.eventType` is a
14091
+ * plain string in the schema, but the device's integration DECLARES the closed set
14092
+ * of values at runtime (`error.listFaultTypes`, the event vocabulary). This module
14093
+ * asks the device's own provider and returns the values the editor offers as a
14094
+ * dropdown. A read that fails answers `null` — the caller leaves `enumValues`
14095
+ * absent (free text stays) and logs; it is never an empty list (D393, D315).
14096
+ */
14097
+ var RecordSchema = zod.z.record(zod.z.string(), zod.z.unknown());
14098
+ function isProviderShape(value) {
14099
+ return typeof value === "object" && value !== null;
14100
+ }
14101
+ function listOf(answer, source) {
14102
+ const record = RecordSchema.safeParse(answer);
14103
+ if (!record.success) return null;
14104
+ const list = zod.z.array(RecordSchema).safeParse(record.data[source.listKey]);
14105
+ if (!list.success) return null;
14106
+ const values = [];
14107
+ for (const entry of list.data) {
14108
+ const value = entry[source.valueKey];
14109
+ if (typeof value !== "string") return null;
14110
+ if (!values.includes(value)) values.push(value);
14111
+ }
14112
+ return values;
14113
+ }
14114
+ async function readAnswer(provider, source, deviceId) {
14115
+ const fn = provider[source.from === "method" ? source.method : "getStatus"];
14116
+ if (typeof fn !== "function") return void 0;
14117
+ return await Reflect.apply(fn, provider, [{ deviceId }]);
14118
+ }
14119
+ var TIMED_OUT = Symbol("catalog-read-timed-out");
14120
+ async function raceBudget(work, budgetMs) {
14121
+ let timer;
14122
+ const deadline = new Promise((resolve) => {
14123
+ timer = setTimeout(() => resolve(TIMED_OUT), budgetMs);
14124
+ timer.unref?.();
14125
+ });
14126
+ try {
14127
+ return await Promise.race([work, deadline]);
14128
+ } finally {
14129
+ if (timer !== void 0) clearTimeout(timer);
14130
+ }
14131
+ }
14132
+ /**
14133
+ * The device's declared values for one field, or `null` when there are none to
14134
+ * offer. A provider without the catalog, a cold (null) slice or an empty catalog
14135
+ * is a quiet absence; a thrown read, a timeout or a malformed answer is warned
14136
+ * with the device tag. Either way the field stays free text.
14137
+ */
14138
+ async function readFieldCatalog(read) {
14139
+ const { registry, logger, capName, deviceId, path, source, budgetMs } = read;
14140
+ try {
14141
+ const provider = registry.getProviderForDevice(capName, deviceId);
14142
+ if (!isProviderShape(provider)) return null;
14143
+ const answer = await raceBudget(readAnswer(provider, source, deviceId), budgetMs);
14144
+ if (answer === TIMED_OUT) {
14145
+ logger.warn("wireable field catalog: read timed out, field stays free text", {
14146
+ tags: { deviceId },
14147
+ meta: {
14148
+ deviceId,
14149
+ capName,
14150
+ path,
14151
+ budgetMs
14152
+ }
14153
+ });
14154
+ return null;
14155
+ }
14156
+ if (answer === void 0 || answer === null) return null;
14157
+ const values = listOf(answer, source);
14158
+ if (values === null) {
14159
+ logger.warn("wireable field catalog: answer has an unexpected shape", {
14160
+ tags: { deviceId },
14161
+ meta: {
14162
+ deviceId,
14163
+ capName,
14164
+ path
14165
+ }
14166
+ });
14167
+ return null;
14168
+ }
14169
+ return values.length > 0 ? values : null;
14170
+ } catch (err) {
14171
+ logger.warn("wireable field catalog: read failed, field stays free text", {
14172
+ tags: { deviceId },
14173
+ meta: {
14174
+ deviceId,
14175
+ capName,
14176
+ path,
14177
+ error: err instanceof Error ? err.message : String(err)
14178
+ }
14179
+ });
14180
+ return null;
14181
+ }
14182
+ }
14183
+ //#endregion
13497
14184
  //#region src/builtins/device-manager/device-aggregation-merge.ts
13498
14185
  /**
13499
14186
  * Pure aggregator-merge + field-tagging helpers for the device-manager
@@ -13663,11 +14350,11 @@ function mergeAggregates(parts) {
13663
14350
  * per-row path (`connection.password`, `rows[].pin`) is not mapped onto a form
13664
14351
  * field and keeps the driver's hydration.
13665
14352
  */
13666
- function isRecord$3(value) {
14353
+ function isRecord$4(value) {
13667
14354
  return typeof value === "object" && value !== null && !Array.isArray(value);
13668
14355
  }
13669
14356
  function isConfigFieldWithValue(field) {
13670
- if (!isRecord$3(field)) return false;
14357
+ if (!isRecord$4(field)) return false;
13671
14358
  return typeof field.type === "string" && typeof field.key === "string" && "value" in field;
13672
14359
  }
13673
14360
  /** The declared paths that name a top-level config key. */
@@ -13675,7 +14362,7 @@ function topLevelKeys(paths) {
13675
14362
  return new Set(paths.filter((p) => p.length > 0 && !p.includes(".") && !p.includes("[")));
13676
14363
  }
13677
14364
  function viewField(field, stored, declared) {
13678
- if (!isRecord$3(field)) return field;
14365
+ if (!isRecord$4(field)) return field;
13679
14366
  const nested = field["fields"];
13680
14367
  if (Array.isArray(nested)) return {
13681
14368
  ...field,
@@ -13684,7 +14371,7 @@ function viewField(field, stored, declared) {
13684
14371
  const tabs = field["tabs"];
13685
14372
  if (Array.isArray(tabs)) return {
13686
14373
  ...field,
13687
- tabs: tabs.map((tab) => isRecord$3(tab) && Array.isArray(tab["fields"]) ? {
14374
+ tabs: tabs.map((tab) => isRecord$4(tab) && Array.isArray(tab["fields"]) ? {
13688
14375
  ...tab,
13689
14376
  fields: tab["fields"].map((f) => viewField(f, stored, declared))
13690
14377
  } : tab)
@@ -13793,7 +14480,7 @@ function isDeclaredCollectionCap(capName) {
13793
14480
  function isDeclaredNonWrapperCap(capName) {
13794
14481
  return DECLARED_NON_WRAPPER_CAPS.has(capName);
13795
14482
  }
13796
- function isRecord$2(value) {
14483
+ function isRecord$3(value) {
13797
14484
  return typeof value === "object" && value !== null && !Array.isArray(value);
13798
14485
  }
13799
14486
  /** A persisted activation of a wrapper on a cap that has none (see module docblock). */
@@ -13836,12 +14523,12 @@ var StaleWrapperActivations = class {
13836
14523
  if (this.checked) return;
13837
14524
  this.checked = true;
13838
14525
  const devices = store.deviceBindings;
13839
- if (!isRecord$2(devices)) return;
14526
+ if (!isRecord$3(devices)) return;
13840
14527
  for (const [deviceKey, perDevice] of Object.entries(devices)) {
13841
14528
  const deviceId = Number(deviceKey);
13842
- if (!Number.isInteger(deviceId) || !isRecord$2(perDevice)) continue;
14529
+ if (!Number.isInteger(deviceId) || !isRecord$3(perDevice)) continue;
13843
14530
  for (const [capName, row] of Object.entries(perDevice)) {
13844
- const wrapperAddonId = isRecord$2(row) ? row["wrapperAddonId"] : void 0;
14531
+ const wrapperAddonId = isRecord$3(row) ? row["wrapperAddonId"] : void 0;
13845
14532
  if (typeof wrapperAddonId === "string" && isDeclaredNonWrapperCap(capName)) this.report(deviceId, capName, wrapperAddonId);
13846
14533
  }
13847
14534
  }
@@ -15494,6 +16181,7 @@ async function readDeviceConfigs(pctx, deviceIds) {
15494
16181
  return pctx.settings.readDeviceStoreBatch(deviceIds);
15495
16182
  }
15496
16183
  async function listAll(pctx, input) {
16184
+ await pctx.freshTagNames();
15497
16185
  const ownerFilter = Reflect.get(input, "addonId");
15498
16186
  if (ownerFilter !== void 0 && (typeof ownerFilter !== "string" || ownerFilter.length === 0)) throw new Error(`deviceManager.listAll: addonId must be a non-empty string or be omitted — got ${JSON.stringify(ownerFilter)}. An owner filter that is present but empty is never widened to every device. On an addon context the id is \`ctx.id\`; there is no \`ctx.addonId\`.`);
15499
16187
  const callerAddonId = pctx.metaStore.rows.censusArmed ? extractCallerAddonId(input) : void 0;
@@ -15581,6 +16269,7 @@ async function listAll(pctx, input) {
15581
16269
  }
15582
16270
  async function getDevice(pctx, input) {
15583
16271
  const { deviceId } = input;
16272
+ await pctx.freshTagNames();
15584
16273
  if (pctx.registry) {
15585
16274
  const found = resolveDeviceById(pctx.registry, deviceId);
15586
16275
  if (found) {
@@ -17175,6 +17864,36 @@ function wireableEntryForDef(capName, def) {
17175
17864
  };
17176
17865
  }
17177
17866
  /**
17867
+ * Fill `enumValues` of the fields the cap declares a per-device catalog for
17868
+ * (`status.fieldEnums`) from the device's own provider. A failed or empty read
17869
+ * leaves the field untouched (free text), never an empty list.
17870
+ */
17871
+ async function withDeclaredCatalogs(deps, registry, deviceId, entry, def) {
17872
+ const declared = def.status?.fieldEnums;
17873
+ if (!declared) return entry;
17874
+ const fields = await Promise.all(entry.fields.map(async (field) => {
17875
+ const source = declared[field.path];
17876
+ if (!source || field.item === true) return field;
17877
+ const values = await readFieldCatalog({
17878
+ registry,
17879
+ logger: deps.ctx.logger,
17880
+ capName: entry.cap,
17881
+ deviceId,
17882
+ path: field.path,
17883
+ source,
17884
+ budgetMs: CONTRIBUTION_BUDGET_MS
17885
+ });
17886
+ return values === null ? field : {
17887
+ ...field,
17888
+ enumValues: values
17889
+ };
17890
+ }));
17891
+ return {
17892
+ ...entry,
17893
+ fields
17894
+ };
17895
+ }
17896
+ /**
17178
17897
  * Per-device wireable-field catalog — the domain status fields a device's
17179
17898
  * bound caps expose, for the operator's cross-device wiring UI. Binding-driven:
17180
17899
  * walks `getBindings(deviceId)`, skips wrapper caps (their status schemas are
@@ -17195,14 +17914,19 @@ async function getWireableFields(deps, input) {
17195
17914
  const { entries } = await getBindings(deps.bindingsDeps, { deviceId });
17196
17915
  const seen = /* @__PURE__ */ new Set();
17197
17916
  const caps = [];
17917
+ const pending = [];
17198
17918
  for (const entry of entries) {
17199
17919
  if (seen.has(entry.capName)) continue;
17200
17920
  seen.add(entry.capName);
17201
17921
  const def = reg.getDefinition(entry.capName);
17202
17922
  if (!def || def.kind === "wrapper") continue;
17203
17923
  const wireable = wireableEntryForDef(entry.capName, def);
17204
- if (wireable) caps.push(wireable);
17924
+ if (wireable) pending.push({
17925
+ wireable,
17926
+ def
17927
+ });
17205
17928
  }
17929
+ caps.push(...await Promise.all(pending.map(({ wireable, def }) => withDeclaredCatalogs(deps, reg, deviceId, wireable, def))));
17206
17930
  if (input.includeSynthesizable === true) {
17207
17931
  const deviceType = (await deps.bindingsDeps.rows.get(deviceId))?.meta.type;
17208
17932
  if (deviceType !== void 0) for (const def of require_rename_composition_block.ALL_CAPABILITY_DEFINITIONS) {
@@ -17400,8 +18124,9 @@ async function searchDevices(deps, input) {
17400
18124
  let compatibleTotal = 0;
17401
18125
  let hiddenIncompatible = 0;
17402
18126
  const filters = input.filters;
18127
+ const locationFilter = filters?.locations?.map((value) => deps.roomNameOf?.(value) ?? value);
17403
18128
  for (const c of textPass) {
17404
- const okLocation = matches(filters?.locations, c.device.location);
18129
+ const okLocation = matches(locationFilter, c.device.location);
17405
18130
  const okIntegration = matches(filters?.integrationIds, c.integrationId);
17406
18131
  const okType = matches(filters?.types, c.device.type);
17407
18132
  if (c.compatible) {
@@ -17734,7 +18459,7 @@ async function setWrapperActive(deps, input) {
17734
18459
  }
17735
18460
  });
17736
18461
  }
17737
- function isRecord$1(value) {
18462
+ function isRecord$2(value) {
17738
18463
  return typeof value === "object" && value !== null && !Array.isArray(value);
17739
18464
  }
17740
18465
  /** The key of this addon's store that holds every wrapper activation. */
@@ -17774,19 +18499,19 @@ async function readWrapperActivation(deps, query) {
17774
18499
  error: "the store holds no deviceBindings row — an empty snapshot is not evidence of an unbind"
17775
18500
  };
17776
18501
  const deviceBindings = read.value;
17777
- if (!isRecord$1(deviceBindings)) return {
18502
+ if (!isRecord$2(deviceBindings)) return {
17778
18503
  kind: "failed",
17779
18504
  error: "stored deviceBindings is not a map"
17780
18505
  };
17781
18506
  const perDevice = deviceBindings[String(query.deviceId)];
17782
18507
  if (perDevice === void 0) return { kind: "missing" };
17783
- if (!isRecord$1(perDevice)) return {
18508
+ if (!isRecord$2(perDevice)) return {
17784
18509
  kind: "failed",
17785
18510
  error: `stored bindings of device ${query.deviceId} are not a map`
17786
18511
  };
17787
18512
  const activation = perDevice[query.capName];
17788
18513
  if (activation === void 0) return { kind: "missing" };
17789
- if (!isRecord$1(activation)) return {
18514
+ if (!isRecord$2(activation)) return {
17790
18515
  kind: "failed",
17791
18516
  error: `stored "${query.capName}" activation is not a record`
17792
18517
  };
@@ -18256,7 +18981,7 @@ function deviceIdOfSuffix(suffix) {
18256
18981
  }
18257
18982
  /** Every field row of one device scope, or a throw. */
18258
18983
  async function readScope(door, addonId, deviceId) {
18259
- return require_prefix_walk.loadPrefixed(door, DEVICE_SETTINGS_COLLECTION, scopeOf(addonId, deviceId));
18984
+ return require_named_entity_store.loadPrefixed(door, DEVICE_SETTINGS_COLLECTION, scopeOf(addonId, deviceId));
18260
18985
  }
18261
18986
  function createDeviceSettingsStore(door, addonId) {
18262
18987
  return {
@@ -18280,7 +19005,7 @@ function createDeviceSettingsStore(door, addonId) {
18280
19005
  if (deviceIds.length === 0) return out;
18281
19006
  for (const id of deviceIds) out.set(id, {});
18282
19007
  const wanted = new Set(deviceIds);
18283
- const all = await require_prefix_walk.loadPrefixed(door, DEVICE_SETTINGS_COLLECTION, `${addonId}:`);
19008
+ const all = await require_named_entity_store.loadPrefixed(door, DEVICE_SETTINGS_COLLECTION, `${addonId}:`);
18284
19009
  for (const [suffix, value] of Object.entries(all)) {
18285
19010
  const id = deviceIdOfSuffix(suffix);
18286
19011
  if (id === null || !wanted.has(id)) continue;
@@ -18290,7 +19015,7 @@ function createDeviceSettingsStore(door, addonId) {
18290
19015
  return out;
18291
19016
  },
18292
19017
  async listIds() {
18293
- const all = await require_prefix_walk.loadPrefixed(door, DEVICE_SETTINGS_COLLECTION, `${addonId}:`, () => null);
19018
+ const all = await require_named_entity_store.loadPrefixed(door, DEVICE_SETTINGS_COLLECTION, `${addonId}:`, () => null);
18294
19019
  const ids = /* @__PURE__ */ new Set();
18295
19020
  for (const suffix of Object.keys(all)) {
18296
19021
  const id = deviceIdOfSuffix(suffix);
@@ -18917,7 +19642,7 @@ function nearestLocatedAncestor(byId, startParentId) {
18917
19642
  visited.add(cursor);
18918
19643
  const ancestor = byId.get(cursor);
18919
19644
  if (!ancestor) return null;
18920
- if (ancestor.location !== null) return ancestor;
19645
+ if (ancestor.locationId !== void 0 && ancestor.locationId !== null) return ancestor;
18921
19646
  cursor = ancestor.parentDeviceId;
18922
19647
  }
18923
19648
  return null;
@@ -18947,15 +19672,16 @@ function planNullLocationFills(rows) {
18947
19672
  const byId = new Map(rows.map((r) => [r.id, r]));
18948
19673
  const plan = [];
18949
19674
  for (const row of rows) {
18950
- if (row.location !== null) continue;
19675
+ if (row.locationId !== void 0 && row.locationId !== null) continue;
18951
19676
  if (row.parentDeviceId === null) continue;
18952
19677
  const hit = nearestLocatedAncestor(byId, row.parentDeviceId);
18953
19678
  if (hit === null) continue;
18954
19679
  if (hit.type !== require_device_type.DeviceType.Container) continue;
18955
- if (hit.location === null) continue;
19680
+ if (hit.locationId === void 0 || hit.locationId === null) continue;
18956
19681
  plan.push({
18957
19682
  id: row.id,
18958
19683
  location: hit.location,
19684
+ locationId: hit.locationId,
18959
19685
  ancestorId: hit.id
18960
19686
  });
18961
19687
  }
@@ -18980,7 +19706,14 @@ async function resolveInheritedLocation(rows, parentDeviceId) {
18980
19706
  visited.add(cursor);
18981
19707
  const ancestor = await rows.get(cursor);
18982
19708
  if (ancestor === null) return null;
18983
- if (ancestor.meta.location !== null) return ancestor.meta.type === require_device_type.DeviceType.Container ? ancestor.meta.location : null;
19709
+ const locationId = ancestor.meta.locationId ?? null;
19710
+ if (locationId !== null) {
19711
+ if (ancestor.meta.type !== require_device_type.DeviceType.Container) return null;
19712
+ return {
19713
+ locationId,
19714
+ location: ancestor.meta.location
19715
+ };
19716
+ }
18984
19717
  cursor = ancestor.meta.parentDeviceId;
18985
19718
  }
18986
19719
  return null;
@@ -19015,8 +19748,8 @@ async function runLocationBackfillAtBoot(pctx, bootRows) {
19015
19748
  const plan = planNullLocationFills((await pctx.metaStore.rows.listAll()).map((r) => r.meta));
19016
19749
  for (const fill of plan) try {
19017
19750
  const current = await pctx.metaStore.rows.get(fill.id);
19018
- if (current === null || current.meta.location !== null) continue;
19019
- await pctx.metaStore.rows.patch(fill.id, { location: fill.location });
19751
+ if (current === null || (current.meta.locationId ?? null) !== null) continue;
19752
+ await pctx.metaStore.rows.patch(fill.id, { locationId: fill.locationId });
19020
19753
  patched.push(fill);
19021
19754
  } catch (err) {
19022
19755
  failed.push({
@@ -19225,12 +19958,13 @@ async function migrateDevice$1(deps, input) {
19225
19958
  try {
19226
19959
  await deps.swapIds(sourceId, targetId);
19227
19960
  } catch (err) {
19228
- if (err instanceof require_device_row_store.MigrationRefusedError) return rollBackRefusal(deps, ids, prior, err);
19961
+ if (err instanceof require_record_kinds.MigrationRefusedError) return rollBackRefusal(deps, ids, prior, err);
19229
19962
  alarmPartialMigration(deps, ids, "swapIds", err);
19230
19963
  throw err;
19231
19964
  }
19965
+ let secretScopes;
19232
19966
  try {
19233
- await deps.swapHardwareState(sourceId, targetId);
19967
+ secretScopes = await deps.swapHardwareState(sourceId, targetId);
19234
19968
  } catch (err) {
19235
19969
  alarmPartialMigration(deps, ids, "swapHardwareState", err);
19236
19970
  throw err;
@@ -19256,7 +19990,8 @@ async function migrateDevice$1(deps, input) {
19256
19990
  targetId,
19257
19991
  switches: [...down, ...up],
19258
19992
  sourceStillLive,
19259
- swapped: true
19993
+ swapped: true,
19994
+ secretScopes
19260
19995
  };
19261
19996
  }
19262
19997
  //#endregion
@@ -19293,6 +20028,15 @@ async function migrateDevice$1(deps, input) {
19293
20028
  * stream-profile assignment (the live authority is the stream broker's own
19294
20029
  * map — see `StreamsTab.tsx`, which stopped writing it), and either copy
19295
20030
  * names stream ids of the wrong hardware after a swap.
20031
+ * - A secret marker inside the swapped config names the keychain scope of ONE
20032
+ * number (`secret://<owner>/device/<id>/<field>`; the ref is the AAD of the
20033
+ * ciphertext). Swapping the marker alone left each number pointing at the
20034
+ * other's scope, so removing either device purged the secret the other still
20035
+ * used (D1093, live 2026-11-23). The configs swap with their markers
20036
+ * unchanged (each still reads its value), then `repairCrossedSecretScopes`
20037
+ * brings every value under the number whose config holds it, through staged
20038
+ * copies, so a crash at any step is finished by a re-run of the repair.
20039
+ * - The location (room) is role state and stays on the number (`swapIds`).
19296
20040
  * - The runtime-state blobs (`__device-state:<id>` — battery snapshot, sleep
19297
20041
  * flag, feature probe) SWAP wholesale: every slice mirrors the box — never
19298
20042
  * while either carries `$owned` (D663): the migration is refused first
@@ -19337,7 +20081,7 @@ var FieldClaimsBlockMigrationError = class extends Error {
19337
20081
  * moved — so it is a {@link MigrationRefusedError}: both cameras' switches are
19338
20082
  * restored, and the claim stays on the number it names.
19339
20083
  */
19340
- var ClaimLandedDuringMigrationError = class extends require_device_row_store.MigrationRefusedError {
20084
+ var ClaimLandedDuringMigrationError = class extends require_record_kinds.MigrationRefusedError {
19341
20085
  sourceId;
19342
20086
  targetId;
19343
20087
  blocked;
@@ -19418,11 +20162,21 @@ function splitConfig(config) {
19418
20162
  * incident this module exists to prevent, and it must never be reported as a
19419
20163
  * success.
19420
20164
  */
19421
- async function swapHardwareState(settings, sourceId, targetId) {
20165
+ async function swapHardwareState(settings, sourceId, targetId, secrets) {
19422
20166
  const sourceConfig = await settings.readDeviceStore(sourceId);
19423
20167
  const targetConfig = await settings.readDeviceStore(targetId);
20168
+ const crossed = [{
20169
+ deviceId: sourceId,
20170
+ markers: crossedIn(sourceConfig, targetId)
20171
+ }, {
20172
+ deviceId: targetId,
20173
+ markers: crossedIn(targetConfig, sourceId)
20174
+ }].filter((c) => c.markers > 0);
20175
+ if (crossed.length > 0) throw new Error(new SecretScopesCrossedError(sourceId, targetId, crossed).message);
19424
20176
  const source = splitConfig(sourceConfig);
19425
20177
  const target = splitConfig(targetConfig);
20178
+ const marked = hasDeviceMarkers(source.hardware, sourceId, targetId) || hasDeviceMarkers(target.hardware, sourceId, targetId);
20179
+ if (secrets === void 0 && marked) throw new Error(`keychain door unavailable - devices ${sourceId} and ${targetId} hold keychain secrets and the migration cannot move them; nothing was changed`);
19426
20180
  await settings.clearDeviceStore(sourceId);
19427
20181
  await settings.writeDeviceStore(sourceId, {
19428
20182
  ...target.hardware,
@@ -19437,15 +20191,217 @@ async function swapHardwareState(settings, sourceId, targetId) {
19437
20191
  const targetRuntimeState = await settings.readDeviceRuntimeState(targetId);
19438
20192
  await settings.writeDeviceRuntimeState(sourceId, targetRuntimeState);
19439
20193
  await settings.writeDeviceRuntimeState(targetId, sourceRuntimeState);
20194
+ let secretScopes = {
20195
+ exchanged: false,
20196
+ markersRepointed: 0,
20197
+ refsAtSource: [],
20198
+ refsAtTarget: []
20199
+ };
20200
+ if (marked) try {
20201
+ const repaired = await repairCrossedSecretScopes(settings, secrets, sourceId, targetId, true);
20202
+ secretScopes = {
20203
+ exchanged: repaired.outcome === "repaired",
20204
+ markersRepointed: repaired.markersRepointedAtA + repaired.markersRepointedAtB,
20205
+ refsAtSource: repaired.refsNowAtA,
20206
+ refsAtTarget: repaired.refsNowAtB
20207
+ };
20208
+ } catch (err) {
20209
+ throw new Error(`migration: configs swapped but the secrets are not yet under their own numbers (${err instanceof Error ? err.message : String(err)}); every marker still reads its value - run deviceManager.repairMigrationSecrets { deviceA: ${sourceId}, deviceB: ${targetId}, apply: true }`, { cause: err });
20210
+ }
19440
20211
  return {
19441
20212
  runtimeStateNowAtSource: targetRuntimeState,
19442
20213
  runtimeStateNowAtTarget: sourceRuntimeState,
19443
20214
  hardwareKeysToSource: Object.keys(target.hardware).toSorted(),
19444
20215
  hardwareKeysToTarget: Object.keys(source.hardware).toSorted(),
19445
20216
  roleKeysKeptAtSource: Object.keys(source.role).toSorted(),
19446
- roleKeysKeptAtTarget: Object.keys(target.role).toSorted()
20217
+ roleKeysKeptAtTarget: Object.keys(target.role).toSorted(),
20218
+ secretScopes
19447
20219
  };
19448
20220
  }
20221
+ /** The suffix of the staging copy a repair keeps while a value changes scope. */
20222
+ var REPAIR_STAGING_SUFFIX = "~repair";
20223
+ function refWithin(parts, deviceId, fieldPath) {
20224
+ return require_scoped_settings.buildSecretRef({
20225
+ ...parts,
20226
+ scope: {
20227
+ kind: "device",
20228
+ deviceId
20229
+ },
20230
+ fieldPath
20231
+ });
20232
+ }
20233
+ /**
20234
+ * The markers of `config` (the config of `ownId`) the repair must move: those
20235
+ * naming `otherId`'s scope, and the staging copies of an interrupted run.
20236
+ */
20237
+ function repairMarkers(config, ownId, otherId) {
20238
+ const found = [];
20239
+ for (const current of collectMarkerRefs(config)) {
20240
+ const parts = require_scoped_settings.parseSecretRef(current);
20241
+ if (parts === null || parts.scope.kind !== "device") continue;
20242
+ const staged = parts.fieldPath.endsWith(REPAIR_STAGING_SUFFIX);
20243
+ if (!(parts.scope.deviceId === otherId || staged && parts.scope.deviceId === ownId)) continue;
20244
+ const fieldPath = staged ? parts.fieldPath.slice(0, -7) : parts.fieldPath;
20245
+ found.push({
20246
+ current,
20247
+ staging: staged ? current : refWithin(parts, ownId, `${fieldPath}${REPAIR_STAGING_SUFFIX}`),
20248
+ dest: refWithin(parts, ownId, fieldPath),
20249
+ owner: parts.owner,
20250
+ staged
20251
+ });
20252
+ }
20253
+ return found;
20254
+ }
20255
+ /**
20256
+ * Repair a pair a migration left with CROSSED secrets (it ran before the
20257
+ * secrets followed the config): a number's config carries markers naming the
20258
+ * OTHER number's keychain scope, so removing either device would purge the
20259
+ * secret the other still reads. Each such marker's value is brought under the
20260
+ * number whose config holds it.
20261
+ *
20262
+ * The configs ARE the state machine, so a crash at any step is re-run to the
20263
+ * right end state — never a double exchange, never a value lost:
20264
+ * 1. stage: copy each value to a staging ref in its own number's scope
20265
+ * (idempotent puts; the originals are untouched);
20266
+ * 2. point both configs at the staging refs — from here every marker reads a
20267
+ * value that is not about to be overwritten;
20268
+ * 3. put each value at its end ref (idempotent: the source is the staging ref);
20269
+ * 4. point both configs at the end refs;
20270
+ * 5. delete the staging refs and any original no config names any more.
20271
+ * A re-run reads each marker's CURRENT ref, so a marker already at a staging
20272
+ * or end ref continues from there. One-sided pairs and a pair where only some
20273
+ * fields are crossed work the same way, field by field.
20274
+ *
20275
+ * Idempotent: a pair with no marker to move is left alone. `apply: false` is
20276
+ * the dry run: counts only. A missing keychain door with markers to move THROWS.
20277
+ */
20278
+ async function repairCrossedSecretScopes(settings, secrets, deviceA, deviceB, apply) {
20279
+ const configA = await settings.readDeviceStore(deviceA);
20280
+ const configB = await settings.readDeviceStore(deviceB);
20281
+ const markersA = repairMarkers(configA, deviceA, deviceB);
20282
+ const markersB = repairMarkers(configB, deviceB, deviceA);
20283
+ const counts = {
20284
+ markersRepointedAtA: markersA.length,
20285
+ markersRepointedAtB: markersB.length
20286
+ };
20287
+ if (markersA.length === 0 && markersB.length === 0) return {
20288
+ outcome: "nothing-to-repair",
20289
+ ...counts,
20290
+ refsNowAtA: [],
20291
+ refsNowAtB: []
20292
+ };
20293
+ if (secrets === void 0) throw new Error(`repairMigrationSecrets: no keychain door on this node — devices ${deviceA} and ${deviceB} hold markers that must move; nothing was changed`);
20294
+ if (!apply) return {
20295
+ outcome: "would-repair",
20296
+ ...counts,
20297
+ refsNowAtA: [],
20298
+ refsNowAtB: []
20299
+ };
20300
+ const all = [...markersA, ...markersB];
20301
+ const valueOf = async (owner, ref) => {
20302
+ const answer = (await secrets.forOwner(owner).resolve([ref]))[ref];
20303
+ if (answer?.kind === "value") return answer.value;
20304
+ throw new Error(`repairMigrationSecrets: ${ref} cannot be read (${answer?.kind ?? "no answer"}); nothing was changed`);
20305
+ };
20306
+ const rewritten = (pick) => {
20307
+ const mapOf = (markers) => {
20308
+ const byCurrent = new Map(markers.map((m) => [m.current, pick(m)]));
20309
+ return (ref) => byCurrent.get(ref);
20310
+ };
20311
+ return [rewriteMarkerRefs(configA, mapOf(markersA)), rewriteMarkerRefs(configB, mapOf(markersB))];
20312
+ };
20313
+ const writeBoth = async (pick) => {
20314
+ const [nextA, nextB] = rewritten(pick);
20315
+ await settings.writeDeviceStore(deviceA, nextA);
20316
+ await settings.writeDeviceStore(deviceB, nextB);
20317
+ };
20318
+ for (const m of all) if (!m.staged) await secrets.forOwner(m.owner).put(m.staging, await valueOf(m.owner, m.current));
20319
+ await writeBoth((m) => m.staging);
20320
+ for (const m of all) await secrets.forOwner(m.owner).put(m.dest, await valueOf(m.owner, m.staging));
20321
+ await writeBoth((m) => m.dest);
20322
+ const finalRefs = new Set(rewritten((m) => m.dest).flatMap(collectMarkerRefs));
20323
+ for (const m of all) {
20324
+ const stale = [m.staging, ...m.staged || finalRefs.has(m.current) ? [] : [m.current]];
20325
+ await secrets.forOwner(m.owner).delete(stale);
20326
+ }
20327
+ for (const ref of finalRefs) {
20328
+ const parts = require_scoped_settings.parseSecretRef(ref);
20329
+ if (parts === null || parts.scope.kind !== "device") continue;
20330
+ const strays = [deviceA, deviceB].map((id) => refWithin(parts, id, `${parts.fieldPath.replace(/~repair$/, "")}${REPAIR_STAGING_SUFFIX}`)).filter((stray) => !finalRefs.has(stray));
20331
+ await secrets.forOwner(parts.owner).delete(strays);
20332
+ }
20333
+ return {
20334
+ outcome: "repaired",
20335
+ ...counts,
20336
+ refsNowAtA: markersA.map((m) => m.dest),
20337
+ refsNowAtB: markersB.map((m) => m.dest)
20338
+ };
20339
+ }
20340
+ /**
20341
+ * The refusal of a migration over a pair whose configs hold markers naming the
20342
+ * OTHER number's keychain scope (an earlier migration crossed them): swapping
20343
+ * again would mix the passwords. Nothing moved; run the repair first.
20344
+ */
20345
+ var SecretScopesCrossedError = class extends require_record_kinds.MigrationRefusedError {
20346
+ sourceId;
20347
+ targetId;
20348
+ crossed;
20349
+ constructor(sourceId, targetId, crossed) {
20350
+ super(`secret-scopes-crossed: migration ${sourceId} → ${targetId} refused: ${crossed.map((c) => `device ${c.deviceId} holds ${c.markers} secret marker(s) naming the other number's keychain scope`).join("; ")} — run deviceManager.repairMigrationSecrets first (nothing moved)`);
20351
+ this.sourceId = sourceId;
20352
+ this.targetId = targetId;
20353
+ this.crossed = crossed;
20354
+ this.name = "SecretScopesCrossedError";
20355
+ }
20356
+ };
20357
+ /** True when `config` holds a marker in the keychain scope of device `a` or `b`. */
20358
+ function hasDeviceMarkers(config, a, b) {
20359
+ return collectMarkerRefs(config).some((ref) => {
20360
+ const parts = require_scoped_settings.parseSecretRef(ref);
20361
+ return parts !== null && parts.scope.kind === "device" && (parts.scope.deviceId === a || parts.scope.deviceId === b);
20362
+ });
20363
+ }
20364
+ function crossedIn(config, otherId) {
20365
+ return collectMarkerRefs(config).filter((ref) => {
20366
+ const parts = require_scoped_settings.parseSecretRef(ref);
20367
+ return parts !== null && parts.scope.kind === "device" && parts.scope.deviceId === otherId;
20368
+ }).length;
20369
+ }
20370
+ /**
20371
+ * Refuse a migration when either config already names the other number's
20372
+ * keychain scope. Read from the stored configs (D49: an unreadable config
20373
+ * throws, never reads as "not crossed").
20374
+ */
20375
+ async function assertNoCrossedSecretScopes(settings, sourceId, targetId) {
20376
+ const crossed = [{
20377
+ deviceId: sourceId,
20378
+ markers: crossedIn(await settings.readDeviceStore(sourceId), targetId)
20379
+ }, {
20380
+ deviceId: targetId,
20381
+ markers: crossedIn(await settings.readDeviceStore(targetId), sourceId)
20382
+ }].filter((c) => c.markers > 0);
20383
+ if (crossed.length > 0) throw new SecretScopesCrossedError(sourceId, targetId, crossed);
20384
+ }
20385
+ /** Every secret marker's ref in a config, at any depth. */
20386
+ function collectMarkerRefs(value) {
20387
+ if (Array.isArray(value)) return value.flatMap(collectMarkerRefs);
20388
+ if (require_scoped_settings.isSecretMarker(value)) return [value.$secret];
20389
+ if (isRecord$1(value)) return Object.values(value).flatMap(collectMarkerRefs);
20390
+ return [];
20391
+ }
20392
+ /** A copy of `value` whose markers name `map(ref)` where it answers (others untouched). */
20393
+ function rewriteMarkerRefs(value, map) {
20394
+ const walk = (node) => {
20395
+ if (Array.isArray(node)) return node.map(walk);
20396
+ if (require_scoped_settings.isSecretMarker(node)) return require_scoped_settings.makeSecretMarker(map(node.$secret) ?? node.$secret);
20397
+ if (isRecord$1(node)) return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, walk(v)]));
20398
+ return node;
20399
+ };
20400
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, walk(v)]));
20401
+ }
20402
+ function isRecord$1(value) {
20403
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20404
+ }
19449
20405
  //#endregion
19450
20406
  //#region src/builtins/device-manager/migrate-reload.ts
19451
20407
  async function reloadMigratedDevices(pctx, targets) {
@@ -19493,6 +20449,274 @@ async function reloadMigratedDevices(pctx, targets) {
19493
20449
  }));
19494
20450
  }
19495
20451
  //#endregion
20452
+ //#region src/builtins/device-manager/room-actions.ts
20453
+ /**
20454
+ * Rooms and site zones as records with an id (D1089).
20455
+ *
20456
+ * The entity methods (`ensureRoom`, `listRooms`, `updateRoom`, `deleteRoom`) are
20457
+ * the model: a rename, a new icon or a new description is ONE write to ONE
20458
+ * `rooms` record, and no device is rewritten (a device meta carries only
20459
+ * `locationId`; its `location` name is derived at read). A delete clears the
20460
+ * references in one operation.
20461
+ *
20462
+ * Everything else here — `listLocations`, `addLocation`, `removeLocation`,
20463
+ * `renameLocation`, the icon / description maps, the site-zone methods and
20464
+ * `setLocationZone` — is a thin SHIM over those, answering the same shapes as
20465
+ * before so the admin UI and the viewer keep working until they move to the ids.
20466
+ * A shim is removed once nothing calls it (D1089).
20467
+ */
20468
+ /** Room record → the wire shape. */
20469
+ function toRoom(entity) {
20470
+ return entity;
20471
+ }
20472
+ function requireName(name, code, what) {
20473
+ const trimmed = name.trim();
20474
+ if (trimmed.length === 0) throw require_camstack_error.userError(code, void 0, `[device-manager] ${what}: name must be non-empty`);
20475
+ return trimmed;
20476
+ }
20477
+ /** Drop a field when the patch says `null`, keep it when absent, set it otherwise. */
20478
+ function applied(patch, current) {
20479
+ if (patch === void 0) return current;
20480
+ if (patch === null) return void 0;
20481
+ return patch;
20482
+ }
20483
+ function emitLocationChanged(pctx, deviceId, value) {
20484
+ pctx.host.ctx.eventBus.emit({
20485
+ id: (0, node_crypto.randomUUID)(),
20486
+ timestamp: /* @__PURE__ */ new Date(),
20487
+ source: {
20488
+ type: "device",
20489
+ id: deviceId
20490
+ },
20491
+ category: require_base_addon.EventCategory.DeviceMetaChanged,
20492
+ data: {
20493
+ deviceId,
20494
+ field: "location",
20495
+ value
20496
+ }
20497
+ });
20498
+ }
20499
+ /** The ids of every device whose room is `roomId`. */
20500
+ async function devicesInRoom(pctx, roomId) {
20501
+ return (await pctx.metaStore.rows.listAll()).filter((row) => row.meta.locationId === roomId).map((row) => row.meta.id);
20502
+ }
20503
+ async function ensureRoom(pctx, input) {
20504
+ const name = requireName(input.name, "system.location-name-required", "ensureRoom");
20505
+ return toRoom(await pctx.rooms.rooms.ensure(name, {}));
20506
+ }
20507
+ async function listRooms(pctx) {
20508
+ return pctx.rooms.rooms.list().map(toRoom);
20509
+ }
20510
+ async function updateRoom(pctx, input) {
20511
+ const { id, patch } = input;
20512
+ const before = pctx.rooms.rooms.get(id);
20513
+ let updated;
20514
+ try {
20515
+ updated = await pctx.rooms.rooms.update(id, (current) => {
20516
+ return {
20517
+ name: patch.name ?? current.name,
20518
+ icon: applied(patch.icon, current.icon),
20519
+ description: applied(patch.description, current.description),
20520
+ zoneId: applied(patch.zoneId, current.zoneId),
20521
+ colour: applied(patch.colour, current.colour),
20522
+ order: applied(patch.order, current.order)
20523
+ };
20524
+ });
20525
+ } catch (err) {
20526
+ if (err instanceof require_named_entity_store.EntityNotFoundError) throw require_camstack_error.userError("system.room-not-found", void 0, `[device-manager] room not found: ${id}`);
20527
+ if (err instanceof require_named_entity_store.EntityNameTakenError) throw require_camstack_error.userError("system.room-name-taken", void 0, `[device-manager] ${err.message}`);
20528
+ throw err;
20529
+ }
20530
+ if (before !== null && before.name !== updated.name) for (const deviceId of await devicesInRoom(pctx, id)) emitLocationChanged(pctx, deviceId, updated.name);
20531
+ return toRoom(updated);
20532
+ }
20533
+ async function deleteRoom(pctx, input) {
20534
+ if (!await pctx.rooms.rooms.delete(input.id)) return { cleared: 0 };
20535
+ const cleared = await pctx.metaStore.withMetaWriteLock(async () => {
20536
+ const out = [];
20537
+ for (const row of await pctx.metaStore.rows.listAll()) {
20538
+ if (row.meta.locationId !== input.id) continue;
20539
+ await pctx.metaStore.rows.patch(row.meta.id, { locationId: null });
20540
+ out.push(row.meta.id);
20541
+ }
20542
+ return out;
20543
+ });
20544
+ for (const deviceId of cleared) emitLocationChanged(pctx, deviceId, null);
20545
+ return { cleared: cleared.length };
20546
+ }
20547
+ /**
20548
+ * The id a write names: `locationId` wins, else `location` (text) is resolved
20549
+ * through `ensureRoom`. `undefined` = the caller named neither, `null` = clear.
20550
+ */
20551
+ async function resolveRoomId(pctx, input) {
20552
+ if (input.locationId !== void 0) {
20553
+ if (input.locationId !== null && pctx.rooms.rooms.get(input.locationId) === null) throw require_camstack_error.userError("system.room-not-found", void 0, `[device-manager] room not found: ${input.locationId}`);
20554
+ return input.locationId;
20555
+ }
20556
+ if (input.location === void 0) return void 0;
20557
+ if (input.location === null || input.location.trim().length === 0) return null;
20558
+ return (await pctx.rooms.rooms.ensure(input.location.trim(), {})).id;
20559
+ }
20560
+ async function listLocations(pctx) {
20561
+ return pctx.rooms.rooms.list().map((room) => room.name).toSorted((a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }));
20562
+ }
20563
+ async function addLocation(pctx, input) {
20564
+ const name = requireName(input.name, "system.location-name-required", "addLocation");
20565
+ await pctx.rooms.rooms.ensure(name, {});
20566
+ }
20567
+ async function removeLocation(pctx, input) {
20568
+ const room = pctx.rooms.rooms.findByName(input.name);
20569
+ if (room === null) return;
20570
+ if (input.cascade === true) {
20571
+ await deleteRoom(pctx, { id: room.id });
20572
+ return;
20573
+ }
20574
+ if ((await devicesInRoom(pctx, room.id)).length > 0) {
20575
+ await updateRoom(pctx, {
20576
+ id: room.id,
20577
+ patch: {
20578
+ icon: null,
20579
+ description: null,
20580
+ zoneId: null
20581
+ }
20582
+ });
20583
+ return;
20584
+ }
20585
+ await pctx.rooms.rooms.delete(room.id);
20586
+ }
20587
+ async function renameLocation(pctx, input) {
20588
+ const from = requireName(input.from, "system.location-name-required", "renameLocation");
20589
+ const to = requireName(input.to, "system.location-name-required", "renameLocation");
20590
+ const source = pctx.rooms.rooms.findByName(from);
20591
+ if (source === null) return { moved: 0 };
20592
+ const target = pctx.rooms.rooms.findByName(to);
20593
+ if (target === null || target.id === source.id) {
20594
+ await updateRoom(pctx, {
20595
+ id: source.id,
20596
+ patch: { name: to }
20597
+ });
20598
+ return { moved: (await devicesInRoom(pctx, source.id)).length };
20599
+ }
20600
+ const moved = await pctx.metaStore.withMetaWriteLock(async () => {
20601
+ const out = [];
20602
+ for (const row of await pctx.metaStore.rows.listAll()) {
20603
+ if (row.meta.locationId !== source.id) continue;
20604
+ await pctx.metaStore.rows.patch(row.meta.id, { locationId: target.id });
20605
+ out.push(row.meta.id);
20606
+ }
20607
+ return out;
20608
+ });
20609
+ await pctx.rooms.rooms.delete(source.id);
20610
+ for (const deviceId of moved) emitLocationChanged(pctx, deviceId, target.name);
20611
+ return { moved: moved.length };
20612
+ }
20613
+ async function listLocationIcons(pctx) {
20614
+ return pctx.rooms.rooms.list().flatMap((room) => room.icon === void 0 ? [] : [{
20615
+ locationKey: require_named_entity_store.entityNameKey(room.name),
20616
+ icon: room.icon
20617
+ }]).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20618
+ }
20619
+ async function setLocationIcon(pctx, input) {
20620
+ const name = requireName(input.location, "system.location-required", "setLocationIcon");
20621
+ const existing = pctx.rooms.rooms.findByName(name);
20622
+ if (existing === null && input.icon === null) return;
20623
+ const room = existing ?? await pctx.rooms.rooms.ensure(name, {});
20624
+ const icon = input.icon;
20625
+ await updateRoom(pctx, {
20626
+ id: room.id,
20627
+ patch: { icon }
20628
+ });
20629
+ }
20630
+ async function listLocationDescriptions(pctx) {
20631
+ return pctx.rooms.rooms.list().flatMap((room) => room.description === void 0 ? [] : [{
20632
+ locationKey: require_named_entity_store.entityNameKey(room.name),
20633
+ description: room.description
20634
+ }]).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20635
+ }
20636
+ async function setLocationDescription(pctx, input) {
20637
+ const name = requireName(input.location, "system.location-required", "setLocationDescription");
20638
+ const text = input.description === null ? "" : input.description.trim();
20639
+ const existing = pctx.rooms.rooms.findByName(name);
20640
+ if (existing === null && text.length === 0) return;
20641
+ await updateRoom(pctx, {
20642
+ id: (existing ?? await pctx.rooms.rooms.ensure(name, {})).id,
20643
+ patch: { description: text.length === 0 ? null : text }
20644
+ });
20645
+ }
20646
+ function zoneFolded(zone) {
20647
+ return require_named_entity_store.entityNameKey(zone.name);
20648
+ }
20649
+ async function listSiteZones(pctx) {
20650
+ const rooms = pctx.rooms.rooms.list();
20651
+ return pctx.rooms.zones.list().map((zone) => ({
20652
+ zoneKey: zoneFolded(zone),
20653
+ label: zone.name,
20654
+ icon: zone.icon ?? null,
20655
+ locationKeys: rooms.filter((room) => room.zoneId === zone.id).map((room) => require_named_entity_store.entityNameKey(room.name)).toSorted((a, b) => a.localeCompare(b))
20656
+ })).toSorted((a, b) => a.zoneKey.localeCompare(b.zoneKey));
20657
+ }
20658
+ async function setSiteZone(pctx, input) {
20659
+ const label = requireName(input.name, "system.site-zone-name-required", "setSiteZone");
20660
+ const zone = await pctx.rooms.zones.ensure(label, {});
20661
+ await pctx.rooms.zones.update(zone.id, (current) => {
20662
+ const next = { name: label };
20663
+ const icon = input.icon === void 0 ? current.icon : input.icon === null ? void 0 : input.icon;
20664
+ if (icon !== void 0) next.icon = icon;
20665
+ return next;
20666
+ });
20667
+ }
20668
+ /** Clear `zoneId` on every room that names `zoneId`; one record write per room. */
20669
+ async function detachRooms(pctx, zoneId, to) {
20670
+ for (const room of pctx.rooms.rooms.list()) {
20671
+ if (room.zoneId !== zoneId) continue;
20672
+ await updateRoom(pctx, {
20673
+ id: room.id,
20674
+ patch: { zoneId: to }
20675
+ });
20676
+ }
20677
+ }
20678
+ async function removeSiteZone(pctx, input) {
20679
+ const zone = pctx.rooms.zones.findByName(input.name);
20680
+ if (zone === null) return;
20681
+ await detachRooms(pctx, zone.id, null);
20682
+ await pctx.rooms.zones.delete(zone.id);
20683
+ }
20684
+ async function renameSiteZone(pctx, input) {
20685
+ const to = requireName(input.to, "system.site-zone-name-required", "renameSiteZone");
20686
+ const source = pctx.rooms.zones.findByName(input.from);
20687
+ if (source === null) return;
20688
+ const target = pctx.rooms.zones.findByName(to);
20689
+ if (target === null || target.id === source.id) {
20690
+ await pctx.rooms.zones.update(source.id, (current) => ({
20691
+ ...current,
20692
+ name: to
20693
+ }));
20694
+ return;
20695
+ }
20696
+ await detachRooms(pctx, source.id, target.id);
20697
+ await pctx.rooms.zones.delete(source.id);
20698
+ }
20699
+ async function setLocationZone(pctx, input) {
20700
+ const name = requireName(input.location, "system.location-required", "setLocationZone");
20701
+ if (input.zone === null) {
20702
+ const existing = pctx.rooms.rooms.findByName(name);
20703
+ if (existing === null || existing.zoneId === void 0) return;
20704
+ await updateRoom(pctx, {
20705
+ id: existing.id,
20706
+ patch: { zoneId: null }
20707
+ });
20708
+ return;
20709
+ }
20710
+ const zoneName = requireName(input.zone, "system.site-zone-name-required", "setLocationZone");
20711
+ const zone = await pctx.rooms.zones.ensure(zoneName, {});
20712
+ const room = await pctx.rooms.rooms.ensure(name, {});
20713
+ if (room.zoneId === zone.id) return;
20714
+ await updateRoom(pctx, {
20715
+ id: room.id,
20716
+ patch: { zoneId: zone.id }
20717
+ });
20718
+ }
20719
+ //#endregion
19496
20720
  //#region src/builtins/device-manager/device-meta-actions.ts
19497
20721
  /**
19498
20722
  * Device meta-mutation + persistence actions for the device-manager addon —
@@ -19568,6 +20792,7 @@ async function allocateDeviceId(pctx, input) {
19568
20792
  type: "generic",
19569
20793
  name: stableId,
19570
20794
  location: null,
20795
+ locationId: null,
19571
20796
  disabled: false,
19572
20797
  parentDeviceId: null,
19573
20798
  id
@@ -19662,7 +20887,16 @@ async function migrateDevice(pctx, input) {
19662
20887
  assertNoFieldClaims: async (a, b) => {
19663
20888
  try {
19664
20889
  await assertNoFieldClaims(pctx.settings, a, b);
20890
+ await assertNoCrossedSecretScopes(pctx.settings, a, b);
19665
20891
  } catch (err) {
20892
+ if (err instanceof SecretScopesCrossedError) for (const c of err.crossed) ctx.logger.warn("migrateDevice refused: secret scopes crossed", {
20893
+ tags: { deviceId: c.deviceId },
20894
+ meta: {
20895
+ sourceId: a,
20896
+ targetId: b,
20897
+ markers: c.markers
20898
+ }
20899
+ });
19666
20900
  if (err instanceof FieldClaimsBlockMigrationError) for (const blocked of err.blocked) ctx.logger.warn("migrateDevice refused: fields claimed by a customization", {
19667
20901
  tags: { deviceId: blocked.deviceId },
19668
20902
  meta: {
@@ -19675,7 +20909,8 @@ async function migrateDevice(pctx, input) {
19675
20909
  }
19676
20910
  },
19677
20911
  swapHardwareState: async (a, b) => {
19678
- const swapped = await swapHardwareState(pctx.settings, a, b);
20912
+ const forOwner = pctx.host.ctx.secrets?.forOwner;
20913
+ const swapped = await swapHardwareState(pctx.settings, a, b, forOwner === void 0 || forOwner === null ? void 0 : { forOwner });
19679
20914
  pctx.host.seedMirror(a, pctx.host.withResetSessionProbe(swapped.runtimeStateNowAtSource), "replace");
19680
20915
  pctx.host.seedMirror(b, pctx.host.withResetSessionProbe(swapped.runtimeStateNowAtTarget), "replace");
19681
20916
  ctx.logger.info("migration: hardware-scoped device state swapped", {
@@ -19686,9 +20921,11 @@ async function migrateDevice(pctx, input) {
19686
20921
  hardwareKeysToSource: swapped.hardwareKeysToSource,
19687
20922
  hardwareKeysToTarget: swapped.hardwareKeysToTarget,
19688
20923
  roleKeysKeptAtSource: swapped.roleKeysKeptAtSource,
19689
- roleKeysKeptAtTarget: swapped.roleKeysKeptAtTarget
20924
+ roleKeysKeptAtTarget: swapped.roleKeysKeptAtTarget,
20925
+ secretScopes: swapped.secretScopes
19690
20926
  }
19691
20927
  });
20928
+ return swapped.secretScopes;
19692
20929
  },
19693
20930
  forgetStreamState: async (deviceId) => {
19694
20931
  await ctx.api.streamBroker.forgetDeviceHardware.mutate({ deviceId });
@@ -19772,10 +21009,10 @@ async function registerDevice(pctx, input) {
19772
21009
  deviceType: type,
19773
21010
  features: settledFeatures
19774
21011
  });
19775
- const priorLocation = existingMeta?.location ?? null;
21012
+ const priorLocationId = existingMeta?.locationId ?? null;
19776
21013
  const resolvedParentId = parentDeviceId ?? null;
19777
21014
  const parentChanged = existingMeta !== void 0 && (existingMeta.parentDeviceId ?? null) !== resolvedParentId;
19778
- const inherited = priorLocation === null && resolvedParentId !== null && (isFirst || parentChanged) ? await resolveInheritedLocation(pctx.metaStore.rows, resolvedParentId) : null;
21015
+ const inherited = priorLocationId === null && resolvedParentId !== null && (isFirst || parentChanged) ? await resolveInheritedLocation(pctx.metaStore.rows, resolvedParentId) : null;
19779
21016
  await pctx.metaStore.rows.upsertRegistration({
19780
21017
  deviceId: id,
19781
21018
  addonId,
@@ -19783,7 +21020,7 @@ async function registerDevice(pctx, input) {
19783
21020
  type,
19784
21021
  name: resolvedName,
19785
21022
  userNamed: wasUserNamed,
19786
- location: priorLocation ?? inherited,
21023
+ locationId: priorLocationId ?? inherited?.locationId ?? null,
19787
21024
  disabled: existingMeta?.disabled ?? false,
19788
21025
  parentDeviceId: resolvedParentId,
19789
21026
  registered: true,
@@ -19799,7 +21036,7 @@ async function registerDevice(pctx, input) {
19799
21036
  if (inherited !== null) for (const descendant of await collectDescendants(pctx.metaStore, id)) {
19800
21037
  if (descendant.location !== null) continue;
19801
21038
  try {
19802
- await pctx.metaStore.rows.patch(descendant.id, { location: inherited });
21039
+ await pctx.metaStore.rows.patch(descendant.id, { locationId: inherited.locationId });
19803
21040
  descendantsFilled.push(descendant.id);
19804
21041
  } catch (err) {
19805
21042
  descendantsFailed.push({
@@ -19813,7 +21050,7 @@ async function registerDevice(pctx, input) {
19813
21050
  storedFeatures: settledFeatures,
19814
21051
  exportFingerprint: fingerprint,
19815
21052
  fingerprintChanged: existingMeta?.exportFingerprint !== fingerprint,
19816
- inheritedLocation: inherited,
21053
+ inheritedLocation: inherited?.location ?? null,
19817
21054
  inheritedDescendantIds: descendantsFilled,
19818
21055
  inheritFailed: descendantsFailed,
19819
21056
  filledRole: roleToFill
@@ -20079,8 +21316,38 @@ function removalSteps(pctx, deviceId, providerAddonId, deletedAt) {
20079
21316
  })
20080
21317
  ];
20081
21318
  }
21319
+ /**
21320
+ * The rows that belong to `deviceId` and cannot outlive it: its accessory
21321
+ * children (`parentDeviceId === id`). A row that merely LINKS to it
21322
+ * (`linkDeviceId`: an operator-picked link, or an entity of another integration
21323
+ * adopted under its own container) is a device of its own and stays.
21324
+ */
21325
+ async function ownedRowIds(pctx, deviceId) {
21326
+ return (await pctx.metaStore.rows.listByParent(deviceId)).map((row) => row.meta.id).filter((id) => id !== deviceId);
21327
+ }
21328
+ /**
21329
+ * Removing a device removes what it owns (an accessory child never outlives its
21330
+ * parent: a Reolink siren row survived its camera with a dangling
21331
+ * `parentDeviceId`). Each child goes through the same tombstoned removal, so
21332
+ * its data stores, its removal hooks and its identity fence are the parent's.
21333
+ */
20082
21334
  async function removeDevice(pctx, input) {
20083
- const { deviceId } = input;
21335
+ await removeDeviceTree(pctx, input.deviceId, /* @__PURE__ */ new Set());
21336
+ }
21337
+ async function removeDeviceTree(pctx, deviceId, seen) {
21338
+ if (seen.has(deviceId)) return;
21339
+ seen.add(deviceId);
21340
+ const ownedIds = await ownedRowIds(pctx, deviceId);
21341
+ await removeOneDevice(pctx, deviceId);
21342
+ for (const childId of ownedIds) {
21343
+ pctx.host.ctx.logger.info("removed device: cascading to an owned child", {
21344
+ tags: { deviceId: childId },
21345
+ meta: { parentDeviceId: deviceId }
21346
+ });
21347
+ await removeDeviceTree(pctx, childId, seen);
21348
+ }
21349
+ }
21350
+ async function removeOneDevice(pctx, deviceId) {
20084
21351
  const persisted = await pctx.metaStore.resolvePersistedById(deviceId);
20085
21352
  if (!persisted) return;
20086
21353
  const { addonId, stableId, meta: persistedMeta } = persisted;
@@ -20347,15 +21614,18 @@ async function collectDescendants(metaStore, rootId) {
20347
21614
  * consumers (the linked-devices picker, which suggests by location) see exactly what landed.
20348
21615
  */
20349
21616
  async function setLocation(pctx, input) {
20350
- const { deviceId, location } = input;
21617
+ const { deviceId } = input;
21618
+ const locationId = await resolveRoomId(pctx, input);
21619
+ if (locationId === void 0) throw new Error("[device-manager] setLocation: name `location` or `locationId`");
21620
+ const location = pctx.rooms.nameOf(locationId);
20351
21621
  const cascaded = [];
20352
21622
  const failed = [];
20353
21623
  await pctx.metaStore.withMetaWriteLock(async () => {
20354
21624
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setLocation: unknown device id=${deviceId}`);
20355
- await pctx.metaStore.rows.patch(deviceId, { location });
21625
+ await pctx.metaStore.rows.patch(deviceId, { locationId });
20356
21626
  const descendants = await collectDescendants(pctx.metaStore, deviceId);
20357
21627
  for (const descendant of descendants) try {
20358
- await pctx.metaStore.rows.patch(descendant.id, { location });
21628
+ await pctx.metaStore.rows.patch(descendant.id, { locationId });
20359
21629
  cascaded.push(descendant.id);
20360
21630
  } catch (err) {
20361
21631
  failed.push({
@@ -20409,10 +21679,24 @@ async function setLocation(pctx, input) {
20409
21679
  }
20410
21680
  });
20411
21681
  }
20412
- /** The tags a write stores: normalised, `null` (the column's absent form) when none are left. */
20413
- function storedTags(tags) {
20414
- const normalized = require_tag.normalizeTags(tags);
20415
- return normalized.length === 0 ? null : normalized;
21682
+ /** The current names of tag ids; an id with no tag record is left out, never shown raw. */
21683
+ function tagNamesOf(pctx, ids) {
21684
+ if (ids === null) return null;
21685
+ return ids.flatMap((id) => {
21686
+ const name = pctx.tagNameOf(id);
21687
+ return name === null ? [] : [name];
21688
+ });
21689
+ }
21690
+ /**
21691
+ * The tag ids a write names: `tagIds` wins, else `tags` (text) is resolved through
21692
+ * `ensureTag` (D1089, accepted for one release). `[]` stays `[]`: the operator cleared
21693
+ * them, and `null` would let the kept names of an older row read back as tags again.
21694
+ */
21695
+ async function resolveTagIds(pctx, input) {
21696
+ if (input.tagIds !== void 0) return [...new Set(input.tagIds)];
21697
+ const names = require_tag.normalizeTags(input.tags ?? []);
21698
+ if (names.length === 0) return [];
21699
+ return [...new Set(await pctx.ensureTagIds(names))];
20416
21700
  }
20417
21701
  /**
20418
21702
  * Replace the operator tags of one device (D1054). Normalised on write; `[]`
@@ -20421,10 +21705,11 @@ function storedTags(tags) {
20421
21705
  */
20422
21706
  async function setTags(pctx, input) {
20423
21707
  const { deviceId } = input;
20424
- const tags = storedTags(input.tags);
21708
+ const tagIds = await resolveTagIds(pctx, input);
21709
+ const tags = tagNamesOf(pctx, tagIds);
20425
21710
  await pctx.metaStore.withMetaWriteLock(async () => {
20426
21711
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] setTags: unknown device id=${deviceId}`);
20427
- await pctx.metaStore.rows.patch(deviceId, { tags });
21712
+ await pctx.metaStore.rows.patch(deviceId, { tagIds });
20428
21713
  });
20429
21714
  pctx.host.ctx.eventBus.emit({
20430
21715
  id: (0, node_crypto.randomUUID)(),
@@ -20716,12 +22001,14 @@ async function setRoleDisplayDefaults(pctx, input) {
20716
22001
  */
20717
22002
  async function applyInitialMeta(pctx, input) {
20718
22003
  const { deviceId, name, location, tags, type, integrationId, linkDeviceId, role } = input;
22004
+ const locationId = location === void 0 && input.locationId === void 0 ? void 0 : await resolveRoomId(pctx, input);
22005
+ const tagIds = tags === void 0 && input.tagIds === void 0 ? void 0 : await resolveTagIds(pctx, input);
20719
22006
  await pctx.metaStore.withMetaWriteLock(async () => {
20720
22007
  if (!await pctx.metaStore.resolvePersistedById(deviceId)) throw new Error(`[device-manager] applyInitialMeta: unknown device id=${deviceId}`);
20721
22008
  await pctx.metaStore.rows.patch(deviceId, {
20722
22009
  ...name !== void 0 ? { name } : {},
20723
- ...location !== void 0 ? { location } : {},
20724
- ...tags !== void 0 ? { tags: storedTags(tags) } : {},
22010
+ ...locationId !== void 0 ? { locationId } : {},
22011
+ ...tagIds !== void 0 ? { tagIds } : {},
20725
22012
  ...type !== void 0 ? { type } : {},
20726
22013
  ...integrationId !== void 0 ? { integrationId } : {},
20727
22014
  ...linkDeviceId !== void 0 ? { linkDeviceId } : {},
@@ -20745,8 +22032,8 @@ async function applyInitialMeta(pctx, input) {
20745
22032
  });
20746
22033
  };
20747
22034
  if (name !== void 0) emitMetaChanged("name", name);
20748
- if (location !== void 0) emitMetaChanged("location", location);
20749
- if (tags !== void 0) emitMetaChanged("tags", storedTags(tags) ?? []);
22035
+ if (locationId !== void 0) emitMetaChanged("location", pctx.rooms.nameOf(locationId));
22036
+ if (tagIds !== void 0) emitMetaChanged("tags", tagNamesOf(pctx, tagIds) ?? []);
20750
22037
  if (type !== void 0) emitMetaChanged("type", type);
20751
22038
  if (integrationId !== void 0) emitMetaChanged("integrationId", integrationId);
20752
22039
  if (linkDeviceId !== void 0) emitMetaChanged("linkDeviceId", linkDeviceId);
@@ -20858,480 +22145,109 @@ async function loadRuntimeState(pctx, input) {
20858
22145
  return splitRuntimeBlob(pctx.host.seedMirrorFromRow(deviceId, data, pctx.settings)).native;
20859
22146
  }
20860
22147
  /**
20861
- * Union of (1) operator-curated location registry and (2) labels
20862
- * currently in use on persisted devices. Case-insensitive
20863
- * dedupe (preserves the first-seen casing). Sorted
20864
- * case-insensitively for stable UI. Drives the Device Info
20865
- * location autocomplete.
22148
+ * `deviceManager.repairMigrationSecrets` — the live repair for a pair a
22149
+ * migration left with crossed keychain scopes (see `repairCrossedSecretScopes`).
22150
+ * Under the meta write lock the migration itself ran under: a config write
22151
+ * racing it would read the half this repair is moving. The running devices
22152
+ * keep their loaded config until the next reload.
20866
22153
  */
20867
- async function listLocations(pctx) {
20868
- const locations = (await pctx.metaStore.readStore()).locations ?? [];
20869
- const seen = /* @__PURE__ */ new Map();
20870
- const consider = (raw) => {
20871
- if (typeof raw !== "string") return;
20872
- const trimmed = raw.trim();
20873
- if (trimmed.length === 0) return;
20874
- const key = trimmed.toLowerCase();
20875
- if (!seen.has(key)) seen.set(key, trimmed);
20876
- };
20877
- for (const label of locations) consider(label);
20878
- for (const row of await pctx.metaStore.rows.listAll()) consider(row.meta.location);
20879
- return [...seen.values()].toSorted((a, b) => a.localeCompare(b, void 0, { sensitivity: "base" }));
20880
- }
20881
- /**
20882
- * Add a label to the curated location registry. Idempotent:
20883
- * existing entries (case-insensitive match) are silently kept.
20884
- * Empty / whitespace-only inputs throw — operators must supply a
20885
- * meaningful label.
20886
- */
20887
- async function addLocation(pctx, input) {
20888
- const trimmed = input.name.trim();
20889
- if (trimmed.length === 0) throw require_camstack_error.userError("system.location-name-required", void 0, "[device-manager] addLocation: name must be non-empty");
20890
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20891
- const current = (await pctx.metaStore.readStore()).locations ?? [];
20892
- if (current.some((l) => l.toLowerCase() === trimmed.toLowerCase())) return;
20893
- await pctx.settings.writeAddonStore({ locations: [...current, trimmed] });
20894
- });
20895
- }
20896
- /**
20897
- * Every location that carries an icon, as `(locationKey, icon)` pairs.
20898
- *
20899
- * ADDITIVE beside `listLocations`, which still answers `string[]` — the
20900
- * autocomplete, the HA adoption import and the recorder all read a list of
20901
- * LABELS and a shape change there would break every one of them. A surface
20902
- * that wants icons asks for them and joins on `locationIconKey`.
20903
- *
20904
- * Returns only what was actually stored. A location with no assignment is
20905
- * ABSENT, never `map-pin`: the fallback belongs to the renderer
20906
- * (`resolveIconKey`), and folding it in here would make "the operator
20907
- * picked the pin" indistinguishable from "the operator picked nothing" —
20908
- * which is the difference an icon picker has to draw.
20909
- */
20910
- async function listLocationIcons(pctx) {
20911
- const icons = (await pctx.metaStore.readStore()).locationIcons ?? {};
20912
- return Object.entries(icons).map(([locationKey, icon]) => ({
20913
- locationKey,
20914
- icon
20915
- })).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20916
- }
20917
- /**
20918
- * Set (or clear) the icon of a location label.
20919
- *
20920
- * Keyed on `locationIconKey` — trimmed + lower-cased, the equality the
20921
- * registry matches on everywhere — so a case-only rename keeps the icon and
20922
- * two spellings of one room can never carry two different icons.
20923
- *
20924
- * The label need NOT be registered: `setLocation` accepts a free-form string
20925
- * and `listLocations` folds in whatever devices carry, so requiring
20926
- * registration here would leave exactly the ad-hoc rooms unable to have an
20927
- * icon. An empty label throws — there is no room to name.
20928
- *
20929
- * Same read-modify-write and same lock as `addLocation`: the map is one key of
20930
- * the addon store, and `writeAddonStore` re-inserts the whole key range, so an
20931
- * unordered write carries a stale copy of every other key.
20932
- */
20933
- async function setLocationIcon(pctx, input) {
20934
- const trimmed = input.location.trim();
20935
- if (trimmed.length === 0) throw require_camstack_error.userError("system.location-required", void 0, "[device-manager] setLocationIcon: location must be non-empty");
20936
- const key = require_addon_settings_cap.locationIconKey(trimmed);
20937
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20938
- const icons = (await pctx.metaStore.readStore()).locationIcons ?? {};
20939
- if (input.icon === null) {
20940
- if (!(key in icons)) return;
20941
- const { [key]: _cleared, ...kept } = icons;
20942
- await pctx.settings.writeAddonStore({ locationIcons: kept });
20943
- return;
20944
- }
20945
- if (icons[key] === input.icon) return;
20946
- await pctx.settings.writeAddonStore({ locationIcons: {
20947
- ...icons,
20948
- [key]: input.icon
20949
- } });
20950
- });
20951
- }
20952
- /**
20953
- * Every location that carries a description, sorted by key.
20954
- *
20955
- * Only what was WRITTEN — a location with no description is absent, and the
20956
- * digest then tells the model the location name alone, exactly as it did
20957
- * before descriptions existed.
20958
- */
20959
- async function listLocationDescriptions(pctx) {
20960
- const descriptions = (await pctx.metaStore.readStore()).locationDescriptions ?? {};
20961
- return Object.entries(descriptions).map(([locationKey, description]) => ({
20962
- locationKey,
20963
- description
20964
- })).toSorted((a, b) => a.locationKey.localeCompare(b.locationKey));
20965
- }
20966
- /**
20967
- * Set (or clear) a location's description.
20968
- *
20969
- * A BLANK description clears, exactly as `null` does: an empty line handed to
20970
- * a vision model costs attention and says nothing, so the two must not be
20971
- * different states. The label is folded with `locationIconKey` — the same key
20972
- * the icon uses, which is the whole point of this living here.
20973
- *
20974
- * Same read-modify-write and same lock as `setLocationIcon`; `writeAddonStore`
20975
- * re-inserts the whole key range, so an unordered write carries a stale copy
20976
- * of every other key.
20977
- */
20978
- async function setLocationDescription(pctx, input) {
20979
- const trimmed = input.location.trim();
20980
- if (trimmed.length === 0) throw new Error("[device-manager] setLocationDescription: location must be non-empty");
20981
- const key = require_addon_settings_cap.locationIconKey(trimmed);
20982
- const text = input.description === null ? "" : input.description.trim();
20983
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
20984
- const descriptions = (await pctx.metaStore.readStore()).locationDescriptions ?? {};
20985
- if (text.length === 0) {
20986
- if (!(key in descriptions)) return;
20987
- const { [key]: _cleared, ...kept } = descriptions;
20988
- await pctx.settings.writeAddonStore({ locationDescriptions: kept });
20989
- return;
22154
+ async function repairMigrationSecrets(pctx, input) {
22155
+ const { deviceA, deviceB, apply } = input;
22156
+ const ctx = pctx.host.ctx;
22157
+ const forOwner = ctx.secrets?.forOwner ?? null;
22158
+ const report = await pctx.metaStore.withMetaWriteLock(() => repairCrossedSecretScopes(pctx.settings, forOwner === null ? void 0 : { forOwner }, deviceA, deviceB, apply));
22159
+ for (const deviceId of [deviceA, deviceB]) ctx.logger.info("repairMigrationSecrets", {
22160
+ tags: { deviceId },
22161
+ meta: {
22162
+ deviceA,
22163
+ deviceB,
22164
+ apply,
22165
+ outcome: report.outcome
20990
22166
  }
20991
- if (descriptions[key] === text) return;
20992
- await pctx.settings.writeAddonStore({ locationDescriptions: {
20993
- ...descriptions,
20994
- [key]: text
20995
- } });
20996
- });
20997
- }
20998
- /**
20999
- * Every site zone, with its rooms, sorted by key.
21000
- *
21001
- * Membership is inverted HERE rather than stored both ways: the store keeps
21002
- * `location → zone`, which is what makes "one zone per room" structural, and a
21003
- * second copy keyed the other way is a second thing that can disagree with the
21004
- * first.
21005
- */
21006
- async function listSiteZones(pctx) {
21007
- const store = await pctx.metaStore.readStore();
21008
- const zones = store.siteZones ?? {};
21009
- const membership = store.locationZones ?? {};
21010
- const rooms = /* @__PURE__ */ new Map();
21011
- for (const [locationKey, zoneKey] of Object.entries(membership)) {
21012
- const list = rooms.get(zoneKey);
21013
- if (list === void 0) rooms.set(zoneKey, [locationKey]);
21014
- else list.push(locationKey);
21015
- }
21016
- return Object.entries(zones).map(([zoneKey, record]) => ({
21017
- zoneKey,
21018
- label: record.label,
21019
- icon: record.icon ?? null,
21020
- locationKeys: (rooms.get(zoneKey) ?? []).toSorted((a, b) => a.localeCompare(b))
21021
- })).toSorted((a, b) => a.zoneKey.localeCompare(b.zoneKey));
21022
- }
21023
- /**
21024
- * Create a zone, or set the icon of one that already exists.
21025
- *
21026
- * `icon: null` clears the icon and KEEPS the zone. Conflating the two would
21027
- * make a mis-click on "no icon" delete every room's membership — the icon is a
21028
- * decoration and the grouping is the data.
21029
- *
21030
- * `icon` OMITTED leaves whatever icon is there: creating a zone from a screen
21031
- * with no picker must not silently clear the glyph a previous screen set.
21032
- */
21033
- async function setSiteZone(pctx, input) {
21034
- const label = input.name.trim();
21035
- if (label.length === 0) throw require_camstack_error.userError("system.site-zone-name-required", void 0, "[device-manager] setSiteZone: name must be non-empty");
21036
- const key = require_device_manager_cap.siteZoneKey(label);
21037
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21038
- const zones = (await pctx.metaStore.readStore()).siteZones ?? {};
21039
- const existing = zones[key];
21040
- const icon = input.icon === void 0 ? existing?.icon : input.icon === null ? void 0 : input.icon;
21041
- const next = icon === void 0 ? { label } : {
21042
- label,
21043
- icon
21044
- };
21045
- if (existing?.label === next.label && existing.icon === next.icon) return;
21046
- await pctx.settings.writeAddonStore({ siteZones: {
21047
- ...zones,
21048
- [key]: next
21049
- } });
21050
- });
21051
- }
21052
- /**
21053
- * Delete a zone. Its LOCATIONS survive, unattached.
21054
- *
21055
- * Deleting a grouping must never delete what was grouped — the rooms exist
21056
- * independently and the devices in them were never touched to begin with.
21057
- */
21058
- async function removeSiteZone(pctx, input) {
21059
- const key = require_device_manager_cap.siteZoneKey(input.name);
21060
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21061
- const store = await pctx.metaStore.readStore();
21062
- const zones = store.siteZones ?? {};
21063
- const membership = store.locationZones ?? {};
21064
- const hadZone = key in zones;
21065
- const orphaned = Object.entries(membership).filter(([, zoneKey]) => zoneKey === key);
21066
- if (!hadZone && orphaned.length === 0) return;
21067
- const { [key]: _dropped, ...keptZones } = zones;
21068
- const keptMembership = Object.fromEntries(Object.entries(membership).filter(([, zoneKey]) => zoneKey !== key));
21069
- await pctx.settings.writeAddonStore({
21070
- ...hadZone ? { siteZones: keptZones } : {},
21071
- ...orphaned.length > 0 ? { locationZones: keptMembership } : {}
21072
- });
21073
- });
21074
- }
21075
- /**
21076
- * Rename a zone, carrying its icon AND every room in it.
21077
- *
21078
- * It exists so that renaming is not delete-then-recreate, which drops both.
21079
- * A rename onto an existing zone MERGES: the target keeps its own icon and the
21080
- * rooms are unioned, the same rule `renameLocation` follows.
21081
- */
21082
- async function renameSiteZone(pctx, input) {
21083
- const toLabel = input.to.trim();
21084
- if (toLabel.length === 0) throw new Error("[device-manager] renameSiteZone: target name must be non-empty");
21085
- const fromKey = require_device_manager_cap.siteZoneKey(input.from);
21086
- const toKey = require_device_manager_cap.siteZoneKey(toLabel);
21087
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21088
- const store = await pctx.metaStore.readStore();
21089
- const zones = store.siteZones ?? {};
21090
- const moved = zones[fromKey];
21091
- if (moved === void 0) return;
21092
- const { [fromKey]: _dropped, ...rest } = zones;
21093
- const target = rest[toKey];
21094
- const nextZones = {
21095
- ...rest,
21096
- [toKey]: target ?? (moved.icon === void 0 ? { label: toLabel } : {
21097
- label: toLabel,
21098
- icon: moved.icon
21099
- })
21100
- };
21101
- const membership = store.locationZones ?? {};
21102
- const nextMembership = Object.fromEntries(Object.entries(membership).map(([locationKey, zoneKey]) => [locationKey, zoneKey === fromKey ? toKey : zoneKey]));
21103
- await pctx.settings.writeAddonStore({
21104
- siteZones: nextZones,
21105
- locationZones: nextMembership
21106
- });
21107
22167
  });
22168
+ return report;
21108
22169
  }
22170
+ //#endregion
22171
+ //#region src/builtins/device-manager/room-store.ts
21109
22172
  /**
21110
- * Put a location in a zone, or take it out with `zone: null`.
22173
+ * The rooms and site zones of the property, as records with an id (D1089).
21111
22174
  *
21112
- * ONE slot per location, so a second call moves the room rather than listing it
21113
- * twice. The zone is created if it does not exist — a screen that assigns
21114
- * before creating is a normal order, and refusing it would be the only place in
21115
- * this registry that demands registration first.
22175
+ * `rooms` and `zones` are record kinds the device manager owns; a device meta
22176
+ * carries `locationId`, a room carries `zoneId`. The store keeps both in memory
22177
+ * once read — a device read resolves a room name through {@link RoomStore.nameOf}
22178
+ * without a query, and an unknown id reads as unset.
21116
22179
  */
21117
- async function setLocationZone(pctx, input) {
21118
- const location = input.location.trim();
21119
- if (location.length === 0) throw new Error("[device-manager] setLocationZone: location must be non-empty");
21120
- const locationKey = require_addon_settings_cap.locationIconKey(location);
21121
- const label = input.zone === null ? null : input.zone.trim();
21122
- if (label !== null && label.length === 0) throw new Error("[device-manager] setLocationZone: zone must be non-empty or null");
21123
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21124
- const store = await pctx.metaStore.readStore();
21125
- const membership = store.locationZones ?? {};
21126
- if (label === null) {
21127
- if (!(locationKey in membership)) return;
21128
- const { [locationKey]: _cleared, ...kept } = membership;
21129
- await pctx.settings.writeAddonStore({ locationZones: kept });
21130
- return;
21131
- }
21132
- const zoneKey = require_device_manager_cap.siteZoneKey(label);
21133
- const zones = store.siteZones ?? {};
21134
- const needsZone = !(zoneKey in zones);
21135
- if (membership[locationKey] === zoneKey && !needsZone) return;
21136
- await pctx.settings.writeAddonStore({
21137
- ...needsZone ? { siteZones: {
21138
- ...zones,
21139
- [zoneKey]: { label }
21140
- } } : {},
21141
- locationZones: {
21142
- ...membership,
21143
- [locationKey]: zoneKey
22180
+ var RoomStore = class RoomStore {
22181
+ rooms;
22182
+ zones;
22183
+ constructor(rooms, zones) {
22184
+ this.rooms = rooms;
22185
+ this.zones = zones;
22186
+ }
22187
+ static of(records) {
22188
+ return new RoomStore(new require_named_entity_store.NamedEntityStore("room", records.kind(require_record_kinds.deviceManagerRecordKinds.rooms), (body) => require_device_manager_cap.RoomBodySchema.parse(body)), new require_named_entity_store.NamedEntityStore("zone", records.kind(require_record_kinds.deviceManagerRecordKinds.zones), (body) => require_device_manager_cap.ZoneBodySchema.parse(body)));
22189
+ }
22190
+ async load() {
22191
+ await this.rooms.load();
22192
+ await this.zones.load();
22193
+ }
22194
+ /** The current name of room `id`; `null` when unset or unknown. */
22195
+ nameOf(id) {
22196
+ return this.rooms.nameOf(id);
22197
+ }
22198
+ };
22199
+ var TagNames = class {
22200
+ source;
22201
+ logger;
22202
+ now;
22203
+ names = /* @__PURE__ */ new Map();
22204
+ refreshedAt = 0;
22205
+ inFlight = null;
22206
+ constructor(source, logger, now = Date.now) {
22207
+ this.source = source;
22208
+ this.logger = logger;
22209
+ this.now = now;
22210
+ }
22211
+ nameOf(id) {
22212
+ return this.names.get(id) ?? null;
22213
+ }
22214
+ /** Revalidate when older than the window. A failed read keeps the last answer. */
22215
+ async fresh() {
22216
+ if (this.source === null) return;
22217
+ if (this.now() - this.refreshedAt < 5e3) return;
22218
+ await this.refresh();
22219
+ }
22220
+ async refresh() {
22221
+ const source = this.source;
22222
+ if (source === null) return;
22223
+ if (this.inFlight !== null) return this.inFlight;
22224
+ const run = (async () => {
22225
+ try {
22226
+ const tags = await source.list();
22227
+ this.names = new Map(tags.map((tag) => [tag.id, tag.name]));
22228
+ this.refreshedAt = this.now();
22229
+ } catch (err) {
22230
+ this.logger.warn("tag names not refreshed — keeping the last answer", { meta: { error: require_scoped_settings.errMsg(err) } });
22231
+ } finally {
22232
+ this.inFlight = null;
21144
22233
  }
21145
- });
21146
- });
21147
- }
21148
- /**
21149
- * Move a location's zone membership from one key to another, for
21150
- * `renameLocation`. Same shape as the icon and description movers.
21151
- */
21152
- function renameLocationZone(membership, fromKey, toKey) {
21153
- const moved = membership[fromKey];
21154
- if (moved === void 0) return null;
21155
- if (fromKey === toKey) return null;
21156
- const { [fromKey]: _dropped, ...rest } = membership;
21157
- return toKey in rest ? rest : {
21158
- ...rest,
21159
- [toKey]: moved
21160
- };
21161
- }
21162
- /**
21163
- * Move a location's description from one key to another, for `renameLocation`.
21164
- *
21165
- * Identical rule to {@link renameLocationIcon}, deliberately: a merge keeps the
21166
- * TARGET's description, because renaming "Sala" into "Hall" moves devices
21167
- * into Hall and does not re-describe it. Split from the icon mover only
21168
- * because the value types differ; if one ever changes, the other must.
21169
- */
21170
- function renameLocationDescription(descriptions, fromKey, toKey) {
21171
- const moved = descriptions[fromKey];
21172
- if (moved === void 0) return null;
21173
- if (fromKey === toKey) return null;
21174
- const { [fromKey]: _dropped, ...rest } = descriptions;
21175
- return toKey in rest ? rest : {
21176
- ...rest,
21177
- [toKey]: moved
21178
- };
21179
- }
21180
- /**
21181
- * Move a location's icon from one key to another, for `renameLocation`.
21182
- *
21183
- * Returns `null` when NOTHING changes, so the caller can leave the key out of
21184
- * its `writeAddonStore` patch instead of re-writing an identical map.
21185
- *
21186
- * A rename onto a room that already has an icon is a MERGE, and the surviving
21187
- * room keeps its own: the operator renaming "Sala" into "Hall" is moving
21188
- * devices into Hall, not restyling it. The source key is dropped either way.
21189
- * Pure — builds a new record, mutates nothing.
21190
- */
21191
- function renameLocationIcon(icons, fromKey, toKey) {
21192
- const moved = icons[fromKey];
21193
- if (moved === void 0) return null;
21194
- if (fromKey === toKey) return null;
21195
- const { [fromKey]: _dropped, ...rest } = icons;
21196
- return toKey in rest ? rest : {
21197
- ...rest,
21198
- [toKey]: moved
21199
- };
21200
- }
21201
- /**
21202
- * Remove a label from the curated registry. Match is
21203
- * case-insensitive. Devices that still reference this label keep
21204
- * their `meta.location` value (the registry is a suggestion
21205
- * list, not a foreign key) — pass `cascade: true` to also clear
21206
- * `setLocation` on every device that referenced this exact
21207
- * label. Cascade only matches case-insensitively + trimmed, same
21208
- * as the registry equality check.
21209
- */
21210
- /**
21211
- * Rename a room in ONE server operation: the registry label in place, then
21212
- * every device that carried it.
21213
- *
21214
- * The lock order is the one `removeLocation` documents and must not be
21215
- * "simplified": the registry edit takes the addon-store lock and RELEASES it
21216
- * before the cascade takes the meta lock. Holding both, in that order, is the
21217
- * reverse of `allocateNextDeviceId`'s meta ⊃ addon-store nesting — the pair
21218
- * that deadlocks.
21219
- *
21220
- * Validation happens BEFORE either lock. A rename that throws halfway is the
21221
- * exact failure this function exists to remove, so an empty target must be
21222
- * refused while nothing has been written yet.
21223
- */
21224
- async function renameLocation(pctx, input) {
21225
- const from = input.from.trim();
21226
- const to = input.to.trim();
21227
- if (from.length === 0) throw new Error("[device-manager] renameLocation: `from` must be non-empty");
21228
- if (to.length === 0) throw new Error("[device-manager] renameLocation: `to` must be non-empty");
21229
- const fromKey = from.toLowerCase();
21230
- const toKey = to.toLowerCase();
21231
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21232
- const store = await pctx.metaStore.readStore();
21233
- const current = store.locations ?? [];
21234
- const registered = current.some((l) => l.trim().toLowerCase() === fromKey);
21235
- const movedIcons = renameLocationIcon(store.locationIcons ?? {}, fromKey, toKey);
21236
- const movedDescriptions = renameLocationDescription(store.locationDescriptions ?? {}, fromKey, toKey);
21237
- const movedZones = renameLocationZone(store.locationZones ?? {}, fromKey, toKey);
21238
- if (!registered && movedIcons === null && movedDescriptions === null && movedZones === null) return;
21239
- const kept = current.filter((l) => {
21240
- const key = l.trim().toLowerCase();
21241
- return key !== fromKey && key !== toKey;
21242
- });
21243
- await pctx.settings.writeAddonStore({
21244
- ...registered ? { locations: [...kept, to] } : {},
21245
- ...movedIcons !== null ? { locationIcons: movedIcons } : {},
21246
- ...movedDescriptions !== null ? { locationDescriptions: movedDescriptions } : {},
21247
- ...movedZones !== null ? { locationZones: movedZones } : {}
21248
- });
21249
- });
21250
- const moved = await pctx.metaStore.withMetaWriteLock(async () => {
21251
- const out = [];
21252
- for (const row of await pctx.metaStore.rows.listAll()) {
21253
- const location = row.meta.location;
21254
- if (typeof location !== "string") continue;
21255
- if (location.trim().toLowerCase() !== fromKey) continue;
21256
- await pctx.metaStore.rows.patch(row.meta.id, { location: to });
21257
- out.push(row.meta.id);
21258
- }
21259
- return out;
21260
- });
21261
- for (const deviceId of moved) pctx.host.ctx.eventBus.emit({
21262
- id: (0, node_crypto.randomUUID)(),
21263
- timestamp: /* @__PURE__ */ new Date(),
21264
- source: {
21265
- type: "device",
21266
- id: deviceId
21267
- },
21268
- category: require_base_addon.EventCategory.DeviceMetaChanged,
21269
- data: {
21270
- deviceId,
21271
- field: "location",
21272
- value: to
21273
- }
21274
- });
21275
- pctx.host.ctx.logger.info("renameLocation: room renamed", { meta: {
21276
- from,
21277
- to,
21278
- moved: moved.length
21279
- } });
21280
- return { moved: moved.length };
21281
- }
21282
- async function removeLocation(pctx, input) {
21283
- const trimmed = input.name.trim();
21284
- if (trimmed.length === 0) return;
21285
- await pctx.bindingsDeps.withAddonStoreWriteLock(async () => {
21286
- const store = await pctx.metaStore.readStore();
21287
- const current = store.locations ?? [];
21288
- const key = require_addon_settings_cap.locationIconKey(trimmed);
21289
- const remaining = current.filter((l) => l.toLowerCase() !== key);
21290
- const droppedLabel = remaining.length !== current.length;
21291
- const icons = store.locationIcons ?? {};
21292
- const droppedIcon = key in icons;
21293
- const descriptions = store.locationDescriptions ?? {};
21294
- const droppedDescription = key in descriptions;
21295
- const membership = store.locationZones ?? {};
21296
- const droppedZone = key in membership;
21297
- if (!droppedLabel && !droppedIcon && !droppedDescription && !droppedZone) return;
21298
- const { [key]: _removedIcon, ...keptIcons } = icons;
21299
- const { [key]: _removedDescription, ...keptDescriptions } = descriptions;
21300
- const { [key]: _removedZone, ...keptMembership } = membership;
21301
- await pctx.settings.writeAddonStore({
21302
- ...droppedLabel ? { locations: remaining } : {},
21303
- ...droppedIcon ? { locationIcons: keptIcons } : {},
21304
- ...droppedDescription ? { locationDescriptions: keptDescriptions } : {},
21305
- ...droppedZone ? { locationZones: keptMembership } : {}
21306
- });
21307
- });
21308
- if (input.cascade !== true) return;
21309
- const cleared = await pctx.metaStore.withMetaWriteLock(async () => {
21310
- const out = [];
21311
- for (const row of await pctx.metaStore.rows.listAll()) {
21312
- const location = row.meta.location;
21313
- if (typeof location !== "string") continue;
21314
- if (location.trim().toLowerCase() !== trimmed.toLowerCase()) continue;
21315
- await pctx.metaStore.rows.patch(row.meta.id, { location: null });
21316
- out.push(row.meta.id);
21317
- }
21318
- return out;
21319
- });
21320
- for (const deviceId of cleared) pctx.host.ctx.eventBus.emit({
21321
- id: (0, node_crypto.randomUUID)(),
21322
- timestamp: /* @__PURE__ */ new Date(),
21323
- source: {
21324
- type: "device",
21325
- id: deviceId
21326
- },
21327
- category: require_base_addon.EventCategory.DeviceMetaChanged,
21328
- data: {
21329
- deviceId,
21330
- field: "location",
21331
- value: null
22234
+ })();
22235
+ this.inFlight = run;
22236
+ return run;
22237
+ }
22238
+ /** Resolve text names to ids through `ensureTag`; a name no tag cap can mint is left out. */
22239
+ async ensureIds(names) {
22240
+ const source = this.source;
22241
+ if (source === null) return [];
22242
+ const ids = [];
22243
+ for (const name of names) {
22244
+ const tag = await source.ensure(name);
22245
+ ids.push(tag.id);
21332
22246
  }
21333
- });
21334
- }
22247
+ await this.refresh();
22248
+ return ids;
22249
+ }
22250
+ };
21335
22251
  //#endregion
21336
22252
  //#region src/builtins/device-manager/device-identifiers-action.ts
21337
22253
  /**
@@ -21781,7 +22697,6 @@ var IdentityLinkReconciler = class {
21781
22697
  };
21782
22698
  //#endregion
21783
22699
  //#region src/builtins/device-manager/identity-links-store.ts
21784
- var import_read_all_rows = require_read_all_rows$1.require_read_all_rows();
21785
22700
  var IdentityLinksStore = class IdentityLinksStore {
21786
22701
  kind;
21787
22702
  links = null;
@@ -21789,7 +22704,7 @@ var IdentityLinksStore = class IdentityLinksStore {
21789
22704
  this.kind = kind;
21790
22705
  }
21791
22706
  static of(records) {
21792
- return new IdentityLinksStore(records.kind(require_device_row_store.deviceManagerRecordKinds["identity-links"]));
22707
+ return new IdentityLinksStore(records.kind(require_record_kinds.deviceManagerRecordKinds["identity-links"]));
21793
22708
  }
21794
22709
  async load() {
21795
22710
  const rows = await (0, import_read_all_rows.readAllRows)(this.kind);
@@ -22325,7 +23240,7 @@ var DeviceTemplateHost = class {
22325
23240
  }
22326
23241
  }
22327
23242
  const entries = [...rows.values()];
22328
- const mirror = new require_prefix_walk.ConditionMirror(templateMirrorSources(entries));
23243
+ const mirror = new require_named_entity_store.ConditionMirror(templateMirrorSources(entries));
22329
23244
  const report = await mirror.refresh({
22330
23245
  fetchSlice: (deviceId, cap) => this.deps.fetchSlice(deviceId, cap),
22331
23246
  fetchStableIds: async () => /* @__PURE__ */ new Map()
@@ -22865,130 +23780,6 @@ var DeviceTemplateActions = class {
22865
23780
  }
22866
23781
  };
22867
23782
  //#endregion
22868
- //#region src/builtins/device-manager/device-meta-types.ts
22869
- /**
22870
- * Decode the raw `ctx.settings.readAddonStore()` record into {@link AddonStore}.
22871
- *
22872
- * A field of the wrong shape reads as ABSENT rather than being trusted through
22873
- * a cast: the store is JSON on disk and a hand-edit or a partial restore must
22874
- * cost the caller its default, never a downstream `TypeError`.
22875
- */
22876
- function decodeAddonStore(raw) {
22877
- const nextDeviceId = raw["nextDeviceId"];
22878
- const locations = raw["locations"];
22879
- const roleDisplayDefaults = raw["roleDisplayDefaults"];
22880
- const locationIcons = decodeLocationIcons(raw["locationIcons"]);
22881
- const locationDescriptions = decodeLocationDescriptions(raw["locationDescriptions"]);
22882
- const siteZones = decodeSiteZones(raw["siteZones"]);
22883
- const locationZones = decodeStringMap(raw["locationZones"]);
22884
- return {
22885
- ...typeof nextDeviceId === "number" && Number.isFinite(nextDeviceId) ? { nextDeviceId } : {},
22886
- ...Array.isArray(locations) ? { locations: locations.filter((l) => typeof l === "string") } : {},
22887
- ...isRoleDisplayDefaults(roleDisplayDefaults) ? { roleDisplayDefaults } : {},
22888
- ...locationIcons !== null ? { locationIcons } : {},
22889
- ...locationDescriptions !== null ? { locationDescriptions } : {},
22890
- ...siteZones !== null ? { siteZones } : {},
22891
- ...locationZones !== null ? { locationZones } : {}
22892
- };
22893
- }
22894
- /**
22895
- * Decode the `locationIcons` map, dropping every entry whose value is not a
22896
- * member of the closed vocabulary.
22897
- *
22898
- * Dropping, not passing through: the icon's whole point is that both surfaces
22899
- * can draw it, and an id from a hand-edit or a newer hub is exactly the value
22900
- * that draws nothing. Absent reads as "no icon chosen", which every renderer
22901
- * already degrades to the fallback pin. Returns `null` when the key itself is
22902
- * absent or of the wrong shape, so the field stays OMITTED rather than being
22903
- * written back as an empty object.
22904
- */
22905
- function decodeLocationIcons(raw) {
22906
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22907
- const out = {};
22908
- for (const [key, value] of Object.entries(raw)) {
22909
- const icon = require_tag.canonicalIconKey(value);
22910
- if (icon === void 0) continue;
22911
- out[key] = icon;
22912
- }
22913
- return out;
22914
- }
22915
- /**
22916
- * Decode the `locationDescriptions` map, dropping every entry that is not a
22917
- * non-blank string.
22918
- *
22919
- * Same posture as the icons: a blank description and a missing one are the
22920
- * same instruction to every reader, and storing the first would send an empty
22921
- * line to a vision model. Over-long text is TRUNCATED rather than dropped —
22922
- * losing the whole description because a hand-edit ran long is a worse answer
22923
- * than losing its tail.
22924
- */
22925
- function decodeLocationDescriptions(raw) {
22926
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22927
- const out = {};
22928
- for (const [key, value] of Object.entries(raw)) {
22929
- if (typeof value !== "string") continue;
22930
- const text = value.trim();
22931
- if (text.length === 0) continue;
22932
- out[key] = text.slice(0, 400);
22933
- }
22934
- return out;
22935
- }
22936
- /**
22937
- * Decode the zone registry, dropping any entry without a usable label.
22938
- *
22939
- * A zone whose label did not survive a hand-edit cannot be shown or renamed —
22940
- * it would be a row the operator can see the effects of and never name. An
22941
- * icon outside the vocabulary is dropped on its own, leaving the zone: losing
22942
- * a glyph is a smaller loss than losing the grouping.
22943
- */
22944
- function decodeSiteZones(raw) {
22945
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22946
- const out = {};
22947
- for (const [key, value] of Object.entries(raw)) {
22948
- if (value === null || typeof value !== "object" || Array.isArray(value)) continue;
22949
- const rec = value;
22950
- const label = typeof rec["label"] === "string" ? rec["label"].trim() : "";
22951
- if (label.length === 0) continue;
22952
- const icon = require_tag.canonicalIconKey(rec["icon"]);
22953
- out[key] = icon === void 0 ? { label } : {
22954
- label,
22955
- icon
22956
- };
22957
- }
22958
- return out;
22959
- }
22960
- /** Decode a plain `string → string` map, dropping anything else. */
22961
- function decodeStringMap(raw) {
22962
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
22963
- const out = {};
22964
- for (const [key, value] of Object.entries(raw)) {
22965
- if (typeof value !== "string" || value.trim().length === 0) continue;
22966
- out[key] = value;
22967
- }
22968
- return out;
22969
- }
22970
- function isRoleDisplayDefaults(value) {
22971
- return value !== null && typeof value === "object" && !Array.isArray(value);
22972
- }
22973
- //#endregion
22974
- //#region src/builtins/device-manager/write-lock.ts
22975
- function createWriteLock() {
22976
- let chain = Promise.resolve();
22977
- return async (fn) => {
22978
- const previous = chain;
22979
- let release = () => {};
22980
- chain = new Promise((resolve) => {
22981
- release = resolve;
22982
- });
22983
- try {
22984
- await previous.catch(() => {});
22985
- return await fn();
22986
- } finally {
22987
- release();
22988
- }
22989
- };
22990
- }
22991
- //#endregion
22992
23783
  //#region src/builtins/device-manager/device-meta-store.ts
22993
23784
  var DeviceMetaStore = class {
22994
23785
  settings;
@@ -23001,7 +23792,7 @@ var DeviceMetaStore = class {
23001
23792
  * ownership without awaiting. Kept in sync with every register/remove and
23002
23793
  * warmed from persistence on boot. */
23003
23794
  idToAddonId = /* @__PURE__ */ new Map();
23004
- constructor(settings, registry, rows, withAddonStoreWriteLock = createWriteLock()) {
23795
+ constructor(settings, registry, rows, withAddonStoreWriteLock = require_named_entity_store.createWriteLock()) {
23005
23796
  this.settings = settings;
23006
23797
  this.registry = registry;
23007
23798
  this.rows = rows;
@@ -23036,7 +23827,7 @@ var DeviceMetaStore = class {
23036
23827
  this.inFlightRead = read;
23037
23828
  return read;
23038
23829
  };
23039
- withMetaWriteLock = createWriteLock();
23830
+ withMetaWriteLock = require_named_entity_store.createWriteLock();
23040
23831
  /** The whole persisted row for one device, or `null`. */
23041
23832
  getRow = async (deviceId) => this.rows.get(deviceId);
23042
23833
  /**
@@ -23118,7 +23909,7 @@ var DeviceTombstoneStore = class DeviceTombstoneStore {
23118
23909
  }
23119
23910
  static of(records, logger) {
23120
23911
  return new DeviceTombstoneStore({
23121
- kind: records.kind(require_device_row_store.deviceManagerRecordKinds.tombstones),
23912
+ kind: records.kind(require_record_kinds.deviceManagerRecordKinds.tombstones),
23122
23913
  logger
23123
23914
  });
23124
23915
  }
@@ -23281,7 +24072,7 @@ var DiscoveryProposalStore = class DiscoveryProposalStore {
23281
24072
  this.now = now;
23282
24073
  }
23283
24074
  static of(records, now) {
23284
- return new DiscoveryProposalStore(records.kind(require_device_row_store.deviceManagerRecordKinds["discovery-proposals"]), now);
24075
+ return new DiscoveryProposalStore(records.kind(require_record_kinds.deviceManagerRecordKinds["discovery-proposals"]), now);
23285
24076
  }
23286
24077
  /** Record what a provider classified. Returns how many proposals are NEW. */
23287
24078
  async observe(addonId, candidates) {
@@ -23731,7 +24522,7 @@ function errorMessage$3(err) {
23731
24522
  * moved yet, so it is a {@link MigrationRefusedError}: the migration refuses
23732
24523
  * and restores both cameras' switches.
23733
24524
  */
23734
- var RuntimeStateDrainError = class extends require_device_row_store.MigrationRefusedError {
24525
+ var RuntimeStateDrainError = class extends require_record_kinds.MigrationRefusedError {
23735
24526
  deviceId;
23736
24527
  constructor(deviceId, reason, options) {
23737
24528
  super(`migration refused: the runtime state of device ${deviceId} could not be drained before the swap (${reason}) — nothing moved; retry the migration`, options);
@@ -26705,16 +27496,20 @@ var REMOVAL_RETRY_DELAYS_MS = [
26705
27496
  12e4,
26706
27497
  6e5
26707
27498
  ];
26708
- async function attempt(steps) {
27499
+ async function attempt(steps, concurrent) {
26709
27500
  const counts = {};
26710
27501
  const failed = [];
26711
27502
  const errors = {};
26712
- for (const step of steps) try {
26713
- counts[step.store] = await step.run();
26714
- } catch (err) {
26715
- failed.push(step);
26716
- errors[step.store] = require_scoped_settings.errMsg(err);
26717
- }
27503
+ const runOne = async (step) => {
27504
+ try {
27505
+ counts[step.store] = await step.run();
27506
+ } catch (err) {
27507
+ failed.push(step);
27508
+ errors[step.store] = require_scoped_settings.errMsg(err);
27509
+ }
27510
+ };
27511
+ if (concurrent) await Promise.all(steps.map(runOne));
27512
+ else for (const step of steps) await runOne(step);
26718
27513
  return {
26719
27514
  counts,
26720
27515
  failed,
@@ -26723,6 +27518,7 @@ async function attempt(steps) {
26723
27518
  }
26724
27519
  function createRemovalCleanup(opts) {
26725
27520
  const label = opts.label ?? "device removal cleanup";
27521
+ const concurrent = opts.concurrent ?? false;
26726
27522
  const delays = opts.retryDelaysMs ?? REMOVAL_RETRY_DELAYS_MS;
26727
27523
  const setTimer = opts.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
26728
27524
  const clearTimer = opts.clearTimer ?? ((handle) => clearTimeout(handle));
@@ -26749,7 +27545,7 @@ function createRemovalCleanup(opts) {
26749
27545
  pending.add(handle);
26750
27546
  };
26751
27547
  const retry = async (deviceId, steps, retryIndex) => {
26752
- const result = await attempt(steps);
27548
+ const result = await attempt(steps, concurrent);
26753
27549
  opts.logger.info(`${label} retried`, {
26754
27550
  tags: { deviceId },
26755
27551
  meta: {
@@ -26762,7 +27558,7 @@ function createRemovalCleanup(opts) {
26762
27558
  };
26763
27559
  return {
26764
27560
  async run(deviceId, steps) {
26765
- const result = await attempt(steps);
27561
+ const result = await attempt(steps, concurrent);
26766
27562
  const failedStores = result.failed.map((s) => s.store);
26767
27563
  const meta = {
26768
27564
  counts: result.counts,
@@ -27095,7 +27891,7 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27095
27891
  * bindings purge reach the store through `BindingsDeps` — and two locks over
27096
27892
  * one key range is the same defect one level up. Handed to both.
27097
27893
  */
27098
- addonStoreWriteLock = createWriteLock();
27894
+ addonStoreWriteLock = require_named_entity_store.createWriteLock();
27099
27895
  /** Stored activations of RETIRED wrappers, said once per process (task 17 review M1). */
27100
27896
  staleWrapperActivationsImpl = null;
27101
27897
  get staleWrapperActivations() {
@@ -27174,6 +27970,7 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27174
27970
  return /* @__PURE__ */ new Map();
27175
27971
  }
27176
27972
  },
27973
+ roomNameOf: (value) => pctx.rooms.nameOf(value),
27177
27974
  logger: this.ctx.logger
27178
27975
  }, input);
27179
27976
  }
@@ -27226,12 +28023,30 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27226
28023
  const settingsStoreApi = this.ctx.api?.settingsStore;
27227
28024
  if (!settingsStoreApi) throw new Error("[device-manager] settings-store API not available — refusing to serve a fleet it cannot persist");
27228
28025
  const identityIndex = new DeviceIdentityIndex();
27229
- const deviceRows = new require_device_row_store.DeviceRowStore(require_device_row_store.deviceRowBackendOf(settingsStoreApi), this.ctx.logger.child("rows"), void 0, identityIndex);
28026
+ const deviceRows = new require_record_kinds.DeviceRowStore(require_record_kinds.deviceRowBackendOf(settingsStoreApi), this.ctx.logger.child("rows"), void 0, identityIndex);
27230
28027
  await deviceRows.declare();
27231
28028
  this.deviceRows = deviceRows;
27232
28029
  const records = this.ctx.records;
27233
28030
  if (records === void 0) throw new Error("[device-manager] ctx.records is required on the hub");
27234
- await records.declare(require_device_row_store.deviceManagerRecordKinds);
28031
+ await records.declare(require_record_kinds.deviceManagerRecordKinds);
28032
+ await this.runMigrations(require_base_addon.defineAddonMigrations(ROOMS_AND_TAGS_MIGRATIONS, deviceManagerMigrationPorts({
28033
+ readStoredKey: (key) => this.readStoredGlobalKey(key),
28034
+ rows: deviceRows,
28035
+ rooms: records.kind(require_record_kinds.deviceManagerRecordKinds.rooms),
28036
+ zones: records.kind(require_record_kinds.deviceManagerRecordKinds.zones),
28037
+ report: (message, meta) => this.ctx.logger.info(message, { meta })
28038
+ })));
28039
+ const rooms = RoomStore.of(records);
28040
+ await rooms.load();
28041
+ const tagApi = this.ctx.api?.tags;
28042
+ const tagNames = new TagNames(tagApi === void 0 ? null : {
28043
+ list: () => tagApi.listTags.query({}),
28044
+ ensure: (name) => tagApi.ensureTag.mutate({ name })
28045
+ }, this.ctx.logger.child("tag-names"));
28046
+ deviceRows.setDerivedNames({
28047
+ room: (id) => rooms.nameOf(id),
28048
+ tag: (id) => tagNames.nameOf(id)
28049
+ });
27235
28050
  const tombstones = DeviceTombstoneStore.of(records, this.ctx.logger.child("tombstones"));
27236
28051
  const identityLinksStore = IdentityLinksStore.of(records);
27237
28052
  await identityLinksStore.load();
@@ -27336,6 +28151,10 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27336
28151
  const templates = this.makeTemplateActions();
27337
28152
  const pctx = {
27338
28153
  host: this.providerHost,
28154
+ rooms,
28155
+ freshTagNames: () => tagNames.fresh(),
28156
+ tagNameOf: (id) => tagNames.nameOf(id),
28157
+ ensureTagIds: (names) => tagNames.ensureIds(names),
27339
28158
  metaStore,
27340
28159
  settings,
27341
28160
  registry,
@@ -27381,11 +28200,29 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27381
28200
  } catch (err) {
27382
28201
  this.ctx.logger.warn("linked-devices manual backfill failed — auto links are NOT materialised", { meta: { error: require_scoped_settings.errMsg(err) } });
27383
28202
  }
28203
+ try {
28204
+ await this.runMigrations(require_base_addon.defineAddonMigrations(ORPHAN_CHILDREN_MIGRATIONS, {
28205
+ listRows: async () => (await deviceRows.listAll()).map((row) => ({
28206
+ id: row.meta.id,
28207
+ parentDeviceId: row.meta.parentDeviceId
28208
+ })),
28209
+ rowLimit: require_record_kinds.DEVICE_ROWS_FLEET_LIMIT,
28210
+ removeDevice: (deviceId) => removeDevice(pctx, { deviceId }),
28211
+ summary: (counts) => this.ctx.logger.info("device-manager: orphan children found", { meta: counts }),
28212
+ info: (message, deviceId, parentDeviceId) => this.ctx.logger.info(message, {
28213
+ tags: { deviceId },
28214
+ meta: { parentDeviceId }
28215
+ })
28216
+ }));
28217
+ } catch (err) {
28218
+ this.ctx.logger.warn("orphan-children migration failed — rows stay as they are", { meta: { error: require_scoped_settings.errMsg(err) } });
28219
+ }
27384
28220
  const provider = {
27385
28221
  resolveDeviceOwnerSync: (deviceId) => resolveDeviceOwnerSync(pctx, deviceId),
27386
28222
  resolveNativeCapOwnerSync: (capName, deviceId) => resolveNativeCapOwnerSync(pctx, capName, deviceId),
27387
28223
  allocateDeviceId: (input) => allocateDeviceId(pctx, input),
27388
28224
  migrateDevice: (input) => migrateDevice(pctx, input),
28225
+ repairMigrationSecrets: (input) => repairMigrationSecrets(pctx, input),
27389
28226
  registerDevice: (input) => registerDevice(pctx, input),
27390
28227
  removeDevice: (input) => removeDevice(pctx, input),
27391
28228
  listDeletedSince: ({ sinceMs }) => tombstones.listSince(sinceMs),
@@ -27431,6 +28268,10 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27431
28268
  setMetadata: (input) => setMetadata(pctx, input),
27432
28269
  setDisabled: (input) => setDisabled(pctx, input),
27433
28270
  loadRuntimeState: (input) => loadRuntimeState(pctx, input),
28271
+ ensureRoom: (input) => ensureRoom(pctx, input),
28272
+ listRooms: () => listRooms(pctx),
28273
+ updateRoom: (input) => updateRoom(pctx, input),
28274
+ deleteRoom: (input) => deleteRoom(pctx, input),
27434
28275
  listLocations: () => listLocations(pctx),
27435
28276
  addLocation: (input) => addLocation(pctx, input),
27436
28277
  removeLocation: (input) => removeLocation(pctx, input),
@@ -27650,7 +28491,8 @@ var DeviceManagerAddon = class extends require_base_addon.BaseAddon {
27650
28491
  get removalHooksCleanup() {
27651
28492
  if (this.removalHooksCleanupImpl === null) this.removalHooksCleanupImpl = createRemovalCleanup({
27652
28493
  logger: this.ctx.logger,
27653
- label: "device removal hooks"
28494
+ label: "device removal hooks",
28495
+ concurrent: true
27654
28496
  });
27655
28497
  return this.removalHooksCleanupImpl;
27656
28498
  }