@camstack/server 1.2.942 → 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 (158) hide show
  1. package/CHANGELOG.md +26 -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 +22 -26
  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-config-secrets.d.ts +14 -0
  60. package/system/dist/builtins/device-manager/device-manager.addon.js +1655 -764
  61. package/system/dist/builtins/device-manager/device-manager.addon.mjs +1641 -750
  62. package/system/dist/builtins/device-manager/device-meta-actions.d.ts +13 -136
  63. package/system/dist/builtins/device-manager/device-meta-types.d.ts +5 -1
  64. package/system/dist/builtins/device-manager/device-provider-context.d.ts +9 -0
  65. package/system/dist/builtins/device-manager/device-row-store.d.ts +21 -4
  66. package/system/dist/builtins/device-manager/device-search.d.ts +6 -0
  67. package/system/dist/builtins/device-manager/location-alignment.d.ts +9 -2
  68. package/system/dist/builtins/device-manager/migrate-device.d.ts +7 -2
  69. package/system/dist/builtins/device-manager/migrate-hardware-state.d.ts +132 -1
  70. package/system/dist/builtins/device-manager/migrations/device-tag-ids.d.ts +25 -0
  71. package/system/dist/builtins/device-manager/migrations/index.d.ts +16 -0
  72. package/system/dist/builtins/device-manager/migrations/orphan-children.d.ts +33 -0
  73. package/system/dist/builtins/device-manager/migrations/ports.d.ts +17 -0
  74. package/system/dist/builtins/device-manager/migrations/rooms-as-records.d.ts +52 -0
  75. package/system/dist/builtins/device-manager/record-kinds.d.ts +3 -1
  76. package/system/dist/builtins/device-manager/removal-cleanup.d.ts +7 -0
  77. package/system/dist/builtins/device-manager/room-actions.d.ts +27 -0
  78. package/system/dist/builtins/device-manager/room-store.d.ts +19 -0
  79. package/system/dist/builtins/device-manager/tag-names.d.ts +32 -0
  80. package/system/dist/builtins/device-manager/wireable-enum-catalog.d.ts +18 -0
  81. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  82. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  83. package/system/dist/builtins/keychain/index.js +2 -2
  84. package/system/dist/builtins/keychain/index.mjs +2 -2
  85. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  86. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  87. package/system/dist/builtins/local-auth/local-auth.addon.js +1 -1
  88. package/system/dist/builtins/local-auth/local-auth.addon.mjs +1 -1
  89. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  90. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  91. package/system/dist/builtins/loki-logging/index.js +2 -2
  92. package/system/dist/builtins/loki-logging/index.mjs +2 -2
  93. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  94. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  95. package/system/dist/builtins/platform-probe/index.js +1 -1
  96. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  97. package/system/dist/builtins/record-entries/index.js +1 -1
  98. package/system/dist/builtins/record-entries/index.mjs +1 -1
  99. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  100. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  101. package/system/dist/builtins/snapshot/index.js +1 -1
  102. package/system/dist/builtins/snapshot/index.mjs +1 -1
  103. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  104. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  105. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  106. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  107. package/system/dist/builtins/sqlite-storage/migrations/migration-engine.d.ts +3 -1
  108. package/system/dist/builtins/sqlite-storage/migrations/migrations-provider.d.ts +1 -0
  109. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +15 -10
  110. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +15 -10
  111. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  112. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  113. package/system/dist/builtins/system-config/system-config.addon.js +1 -1
  114. package/system/dist/builtins/system-config/system-config.addon.mjs +1 -1
  115. package/system/dist/builtins/winston-logging/index.js +2 -2
  116. package/system/dist/builtins/winston-logging/index.mjs +2 -2
  117. package/system/dist/{command-catalog-C29hVOOg.js → command-catalog-CI0tu1Nt.js} +1 -1
  118. package/system/dist/{command-catalog-xAeqxbZk.mjs → command-catalog-zwlIA3T5.mjs} +1 -1
  119. package/system/dist/{composition-sources-C327LGFn.mjs → composition-sources-CXxXfh1z.mjs} +1 -1
  120. package/system/dist/{composition-sources-Do5qM6EB.js → composition-sources-DNgSItK-.js} +1 -1
  121. package/system/dist/{core-blocks.cap-CdTGUKtr.js → core-blocks.cap-BHEok4VO.js} +125 -373
  122. package/system/dist/{core-blocks.cap-DLkEfV5b.mjs → core-blocks.cap-CPgZRcpj.mjs} +109 -327
  123. package/system/dist/{device-manager.cap-DJs8izI6.js → device-manager.cap-B9qVf7ag.js} +163 -22
  124. package/system/dist/{device-manager.cap-eYrj1Ezp.mjs → device-manager.cap-CV4KGp3e.mjs} +134 -17
  125. package/system/dist/{error.cap-CU1FB6uE.mjs → error.cap-B8l7L8e4.mjs} +7 -1
  126. package/system/dist/{error.cap-BuKbL3Ac.js → error.cap-BqlvgBJd.js} +7 -1
  127. package/system/dist/file-host-worker.js +1 -1
  128. package/system/dist/file-host-worker.mjs +1 -1
  129. package/system/dist/index.js +7 -7
  130. package/system/dist/index.mjs +6 -6
  131. package/system/dist/{legacy-integration-rows-door-CdqYAj-o.js → legacy-integration-rows-door-BK8eoGlF.js} +1 -1
  132. package/system/dist/{legacy-integration-rows-door-LSgpClpX.mjs → legacy-integration-rows-door-CwzC5XNk.mjs} +1 -1
  133. package/system/dist/{migration-DGAc6ywR.mjs → migration-BvbfW9g-.mjs} +6 -0
  134. package/system/dist/{migration-BOQlFZCN.js → migration-CHPdAdNh.js} +6 -0
  135. package/system/dist/{prefix-walk-BFnw8NBu.js → named-entity-store-DFwLij9c.js} +244 -90
  136. package/system/dist/{prefix-walk-Mtij0NNT.mjs → named-entity-store-DOnyyFFf.mjs} +195 -89
  137. package/system/dist/{notification-rules.cap-BUIuYPlQ.mjs → notification-rules.cap-ClvK6QT1.mjs} +10 -5
  138. package/system/dist/{notification-rules.cap-BJKUjizS.js → notification-rules.cap-uSLoe2pA.js} +10 -5
  139. package/system/dist/{notification-targets-DMW7xgR2.js → notification-targets-ChqpBbtR.js} +2 -2
  140. package/system/dist/{notification-targets-4bGYH5J7.mjs → notification-targets-DUA6-F2t.mjs} +2 -2
  141. package/system/dist/{device-row-store-CTocYKqC.mjs → record-kinds-BD2xv4Pd.mjs} +222 -93
  142. package/system/dist/{device-row-store-C0P2H18h.js → record-kinds-BV8Gcpsx.js} +246 -93
  143. package/system/dist/records/named-entity-store.d.ts +60 -0
  144. package/system/dist/{rename-composition-block-Cdh-dRmY.mjs → rename-composition-block-C3QQ9UUE.mjs} +134 -33
  145. package/system/dist/{rename-composition-block-D9Uc1AF7.js → rename-composition-block-Cx3X8QSm.js} +134 -33
  146. package/system/dist/{retention-source.cap-C6Hy0hlM.js → retention-source.cap-A-TMhU5O.js} +1 -1
  147. package/system/dist/{retention-source.cap-550kkyp5.mjs → retention-source.cap-Ct07pM30.mjs} +1 -1
  148. package/system/dist/{storage-admin.cap-Ci4QbL6P.mjs → storage-admin.cap-C54s9_B9.mjs} +8 -2
  149. package/system/dist/{storage-admin.cap-DqW1ol4j.js → storage-admin.cap-DSPHi7ut.js} +8 -2
  150. package/system/dist/{stream-catalog.cap-CjEQFknc.js → stream-catalog.cap-7WPsugOy.js} +1 -1
  151. package/system/dist/{stream-catalog.cap-DVniDdRD.mjs → stream-catalog.cap-CzwRDaqT.mjs} +1 -1
  152. package/system/dist/{tag-BxLazvVb.js → tag-BLraBqvp.js} +12 -0
  153. package/system/dist/{tag-uZBAq6ox.mjs → tag-DU8pm9Bi.mjs} +7 -1
  154. package/system/dist/time-window-B6UhCArd.js +679 -0
  155. package/system/dist/time-window-BnUBULgu.mjs +578 -0
  156. package/system/dist/{wal-maintenance-BgYiAy5b.js → wal-maintenance-CkPfVApC.js} +0 -0
  157. package/system/dist/{wal-maintenance-Bey5ChBb.mjs → wal-maintenance-u84_1sVl.mjs} +0 -0
  158. package/system/package.json +1 -1
@@ -1,27 +1,29 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_chunk = require("../../chunk-Cek0wNdY.js");
3
- const require_stream_catalog_cap = require("../../stream-catalog.cap-CjEQFknc.js");
4
- const require_base_addon = require("../../base-addon-CRsXtYFG.js");
3
+ const require_stream_catalog_cap = require("../../stream-catalog.cap-7WPsugOy.js");
4
+ const require_base_addon = require("../../base-addon-BG7p06Hb.js");
5
5
  const require_scoped_settings = require("../../scoped-settings-CylSSq_8.js");
6
- const require_rename_composition_block = require("../../rename-composition-block-D9Uc1AF7.js");
7
- const require_notification_targets = require("../../notification-targets-DMW7xgR2.js");
8
- const require_notification_rules_cap = require("../../notification-rules.cap-BJKUjizS.js");
6
+ const require_rename_composition_block = require("../../rename-composition-block-Cx3X8QSm.js");
7
+ const require_notification_targets = require("../../notification-targets-ChqpBbtR.js");
8
+ const require_camstack_error = require("../../camstack-error-DJ-TUAi1.js");
9
+ const require_notification_rules_cap = require("../../notification-rules.cap-uSLoe2pA.js");
9
10
  const require_record_kind = require("../../record-kind-DoBfYHCs.js");
10
11
  const require_entry_kind = require("../../entry-kind-cq90c--V.js");
11
- const require_device_manager_cap = require("../../device-manager.cap-DJs8izI6.js");
12
+ const require_device_manager_cap = require("../../device-manager.cap-B9qVf7ag.js");
12
13
  const require_command_origin_claim = require("../../command-origin-claim-Cief660O.js");
13
14
  const require_quantity = require("../../quantity-lY1KiTSZ.js");
14
- const require_tag = require("../../tag-BxLazvVb.js");
15
+ const require_tag = require("../../tag-BLraBqvp.js");
15
16
  const require_device_type = require("../../device-type-Cnc0NiSX.js");
16
17
  const require_device_kind = require("../../device-kind-FMhJg8uC.js");
17
- const require_action_index = require("../../action-index-B_cLRwXJ.js");
18
- const require_core_blocks_cap = require("../../core-blocks.cap-CdTGUKtr.js");
18
+ const require_core_blocks_cap = require("../../core-blocks.cap-BHEok4VO.js");
19
+ const require_action_index = require("../../action-index-Dz9rd1qa.js");
19
20
  const require_compile = require("../../compile-SpeAhaZ6.js");
20
- const require_prefix_walk = require("../../prefix-walk-BFnw8NBu.js");
21
+ const require_time_window = require("../../time-window-B6UhCArd.js");
22
+ const require_named_entity_store = require("../../named-entity-store-DFwLij9c.js");
21
23
  const require_l10n = require("../../l10n-CGMvp7NF.js");
22
24
  const require_integration_instances_cap = require("../../integration-instances.cap-DSieF1w3.js");
23
25
  const require_cap_call_context = require("../../cap-call-context-Bd76CbOW.js");
24
- const require_composition_sources = require("../../composition-sources-Do5qM6EB.js");
26
+ const require_composition_sources = require("../../composition-sources-DNgSItK-.js");
25
27
  const require_declared_device = require("../../declared-device-BWphj9WE.js");
26
28
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
27
29
  const require_capture_engine = require("../../capture-engine-D_1IJmMs.js");
@@ -1195,7 +1197,9 @@ function emitLeaf(trigger, path) {
1195
1197
  function emitStepBody(action) {
1196
1198
  switch (action.kind) {
1197
1199
  case "wait": return ` await sleep(${j(action.seconds * 1e3)})`;
1198
- case "command": return ` await actuateTarget(scope, ${j(action.target)}, ${j(action.actionId)}, ${j(action.args ?? {})}, vars)`;
1200
+ case "command":
1201
+ if (action.onFor !== void 0) return ` await holdTargetOn(scope, ${j(action.target)}, ${j(action.actionId)}, ${j(action.onFor.seconds * 1e3)}, vars)`;
1202
+ return ` await actuateTarget(scope, ${j(action.target)}, ${j(action.actionId)}, ${j(action.args ?? {})}, vars)`;
1199
1203
  case "action": return ` // an Action run, awaited: the step takes THAT run's outcome
1200
1204
  await runActionBody(${j(action)}, {
1201
1205
  ...env,
@@ -1277,7 +1281,7 @@ ${branches}
1277
1281
  /** The devices whose report can change a tree's answer; null when one is named by a stable id (any report wakes it). */
1278
1282
  function wakeDevicesOf(when) {
1279
1283
  const ids = [];
1280
- for (const source of require_prefix_walk.collectWhenMirrorSources(when)) {
1284
+ for (const source of require_named_entity_store.collectWhenMirrorSources(when)) {
1281
1285
  if (source.kind !== "device") return null;
1282
1286
  if (!ids.includes(source.deviceId)) ids.push(source.deviceId);
1283
1287
  }
@@ -1397,12 +1401,13 @@ function renderAutomationBlock(input) {
1397
1401
  ...elseSteps(a),
1398
1402
  ...require_core_blocks_cap.nestedStepsOf(a)
1399
1403
  ]).some((a) => a.kind === "command" && a.target.kind === "domain");
1400
- const guardHoldTrees = recipe.actions.flatMap((a, i) => require_core_blocks_cap.stepConditionsOf(a).flatMap(({ path, when }) => require_prefix_walk.hasHoldLeaves(when) ? [{
1404
+ const guardHoldTrees = recipe.actions.flatMap((a, i) => require_core_blocks_cap.stepConditionsOf(a).flatMap(({ path, when }) => require_named_entity_store.hasHoldLeaves(when) ? [{
1401
1405
  path: `actions.${i}.${path}`,
1402
1406
  when
1403
1407
  }] : []));
1404
- const hasTime = require_prefix_walk.hasTimeLeaves(recipe.when) || recipe.actions.some((a) => require_core_blocks_cap.stepConditionsOf(a).some(({ when }) => require_prefix_walk.hasTimeLeaves(when)));
1408
+ const hasTime = require_named_entity_store.hasTimeLeaves(recipe.when) || recipe.actions.some((a) => require_core_blocks_cap.stepConditionsOf(a).some(({ when }) => require_named_entity_store.hasTimeLeaves(when)));
1405
1409
  const hasWaitUntil = recipe.actions.some((a) => a.kind === "wait-until" || require_core_blocks_cap.nestedStepsOf(a).some((n) => n.kind === "wait-until"));
1410
+ const hasOnFor = recipe.actions.some((a) => [a, ...require_core_blocks_cap.nestedStepsOf(a)].some((n) => n.kind === "command" && n.onFor !== void 0));
1406
1411
  const eventLeaves = [];
1407
1412
  require_core_blocks_cap.forEachLeaf(recipe.when, (leaf, path) => {
1408
1413
  if (require_core_blocks_cap.isEventLeaf(leaf)) eventLeaves.push({
@@ -1419,6 +1424,7 @@ function renderAutomationBlock(input) {
1419
1424
  AutomationWhen,
1420
1425
  AutomationStepTrace,
1421
1426
  BodyEnv,
1427
+ OnForHold,
1422
1428
  RunnableStep,
1423
1429
  StepScope,
1424
1430
  TimeSite,
@@ -1431,6 +1437,8 @@ import {
1431
1437
  BecomesWatch,
1432
1438
  ConditionMirror,
1433
1439
  HoldTracker,
1440
+ OnForHolds,
1441
+ switchRunLimitOf,
1434
1442
  DetectionTriggerFilter,
1435
1443
  DeviceFiredWatch,
1436
1444
  EventCategory,
@@ -1504,7 +1512,7 @@ const STEP_META: ReadonlyArray<{ kind: string; cap?: string; method?: string; ac
1504
1512
  const HAS_DOMAIN_TARGET = ${hasDomainTarget}
1505
1513
 
1506
1514
  /** A state leaf of the tree carries a \`for\`: its clock is fed on every mirror update, so it counts while nothing fires. */
1507
- const HAS_HOLD = ${require_prefix_walk.hasHoldLeaves(recipe.when)}
1515
+ const HAS_HOLD = ${require_named_entity_store.hasHoldLeaves(recipe.when)}
1508
1516
 
1509
1517
  /** A \`time-is\` leaf (in the tree or a guard) reads the site clock: the site is kept in memory and a timer wakes the tree at each boundary. */
1510
1518
  const HAS_TIME = ${hasTime}
@@ -1512,6 +1520,12 @@ const HAS_TIME = ${hasTime}
1512
1520
  /** Guards (a step's \`if\`) with a \`for\`: they keep their own mirror and clocks, fed the same way. */
1513
1521
  const GUARD_HOLD_TREES: ReadonlyArray<{ path: string; when: AutomationWhen }> = ${j(guardHoldTrees)}
1514
1522
 
1523
+ /** A command step holds its device on for a time: the block listens for that device's reports. */
1524
+ const HAS_ON_FOR = ${hasOnFor}
1525
+
1526
+ /** Where each holdable cap says "on". */
1527
+ const ON_FOR_FIELDS: Readonly<Record<string, string>> = { switch: 'on' }
1528
+
1515
1529
  /** setTimeout cannot arm past 2^31-1 ms; a longer wait re-arms on wake. */
1516
1530
  const MAX_TIMER_MS = 2_000_000_000
1517
1531
 
@@ -1637,8 +1651,10 @@ ${hasTime ? ` /** The site clock a \`time-is\` leaf reads: memory only at evalu
1637
1651
  try {
1638
1652
  const doc = await ctx.api.coreBlocks.getAutomationRunState.query({ blockId: BLOCK_ID })
1639
1653
  lastRunStartedAt = doc.lastRunStartedAt
1654
+ onFor.restore(doc.onForHolds ?? [])
1640
1655
  } catch (err: unknown) {
1641
1656
  stampUnknown = true
1657
+ if (HAS_ON_FOR) retryOnForRestore(BLOCK_ID)
1642
1658
  ctx.logger.warn('could not read the stored cooldown stamp — the first run is let through', {
1643
1659
  blockId: BLOCK_ID,
1644
1660
  error: err instanceof Error ? err.message : String(err),
@@ -1646,7 +1662,21 @@ ${hasTime ? ` /** The site clock a \`time-is\` leaf reads: memory only at evalu
1646
1662
  }
1647
1663
  }
1648
1664
 
1649
- function send(payload: { trace?: AutomationRunTrace; runStartedAt?: number }): Promise<void> {
1665
+ /** The holds, written through the same ordered chain, but a failure REJECTS: the caller knows the hold is not durable. */
1666
+ function persistOnFor(holds: readonly OnForHold[]): Promise<void> {
1667
+ if (BLOCK_ID === null) return Promise.resolve()
1668
+ const blockId = BLOCK_ID
1669
+ const run = sendChain.then(() =>
1670
+ ctx.api.coreBlocks.reportAutomationRun.mutate({ blockId, keepTraces: KEEP_TRACES, onForHolds: [...holds] }),
1671
+ )
1672
+ sendChain = run.then(
1673
+ () => undefined,
1674
+ () => undefined,
1675
+ )
1676
+ return run.then(() => undefined)
1677
+ }
1678
+
1679
+ function send(payload: { trace?: AutomationRunTrace; runStartedAt?: number; onForHolds?: OnForHold[] }): Promise<void> {
1650
1680
  if (BLOCK_ID === null) return Promise.resolve()
1651
1681
  const blockId = BLOCK_ID
1652
1682
  sendChain = sendChain.then(async () => {
@@ -1872,6 +1902,125 @@ ${hasTime ? ` // a time-is leaf changes sides at a boundary with no device ev
1872
1902
  await runForDevices(resolved.deviceIds, scope, (deviceId) => actuate(scope, deviceId, cap, method, callArgs, vars))
1873
1903
  }
1874
1904
 
1905
+ /** "On for N" (on-for.ts): the devices this block turned on and owes an off. They outlive every run. */
1906
+ const onFor = new OnForHolds<ReturnType<typeof setTimeout>>({
1907
+ timers: {
1908
+ set: (fn, ms) => setTimeout(fn, Math.min(ms, MAX_TIMER_MS)),
1909
+ clear: (handle) => clearTimeout(handle),
1910
+ now: () => Date.now(),
1911
+ },
1912
+ readOn: async (deviceId, action) => {
1913
+ const read = await readField(deviceId, action.cap, action.fieldPath)
1914
+ return read.ok && typeof read.value === 'boolean' ? read.value : null
1915
+ },
1916
+ send: async (deviceId, actionId) => {
1917
+ const call = vocabCall(actionId, {})
1918
+ await callCap(deviceId, call.cap, call.method, call.args)
1919
+ ctx.logger.info('on-for: sent ' + actionId, { tags: { deviceId } })
1920
+ },
1921
+ persist: (holds) => persistOnFor(holds),
1922
+ // a hold never outlasts what the device may be kept on for (switch-run-limits.ts): cut at arming, stored holds too
1923
+ limitSecondsOf: async (deviceId) => {
1924
+ const [row] = await ctx.api.deviceManager.listAll.query({ deviceIds: [deviceId], projection: 'slim' })
1925
+ return row === undefined ? null : switchRunLimitOf(row.type, row.role).maxSeconds
1926
+ },
1927
+ onLimitUnknown: (deviceId) => {
1928
+ ctx.logger.warn('on-for: the device limit could not be read — the hold is kept as asked', {
1929
+ tags: { deviceId },
1930
+ })
1931
+ },
1932
+ onClamped: (deviceId, askedMs, limitMs) => {
1933
+ ctx.logger.warn('on-for: ' + askedMs / 1000 + ' s is over what the device may be held on — cut to ' + limitMs / 1000 + ' s', {
1934
+ tags: { deviceId },
1935
+ })
1936
+ },
1937
+ onError: (deviceId, what, err) => {
1938
+ ctx.logger.error('on-for: ' + what, {
1939
+ tags: { deviceId },
1940
+ error: err instanceof Error ? err.message : String(err),
1941
+ })
1942
+ },
1943
+ onDropped: (hold, reason) => {
1944
+ ctx.logger.error('on-for: ' + reason + ' — the hold is given up, the device may still be on', {
1945
+ tags: { deviceId: hold.deviceId },
1946
+ })
1947
+ },
1948
+ })
1949
+ disposers.push(() => onFor.dispose())
1950
+ if (HAS_ON_FOR) {
1951
+ // a held device that reports "off" was switched by someone else: the hold ends
1952
+ disposers.push(
1953
+ ctx.eventBus.subscribe({ category: EventCategory.DeviceStateChanged }, (event) => {
1954
+ const deviceId = event.data['deviceId']
1955
+ if (typeof deviceId !== 'number') return
1956
+ const hold = onFor.list().find((h) => h.deviceId === deviceId)
1957
+ if (hold === undefined) return
1958
+ void readField(deviceId, hold.cap, ON_FOR_FIELDS[hold.cap] ?? 'on').then((read) => {
1959
+ if (read.ok && typeof read.value === 'boolean') onFor.observe(deviceId, hold.cap, read.value)
1960
+ })
1961
+ }),
1962
+ )
1963
+ }
1964
+
1965
+ /** The stored holds could not be read at start: asked again until the hub answers. */
1966
+ function retryOnForRestore(blockId: string): void {
1967
+ const timer = setTimeout(() => {
1968
+ if (stopped) return
1969
+ ctx.api.coreBlocks.getAutomationRunState.query({ blockId }).then(
1970
+ (doc) => onFor.restore(doc.onForHolds ?? []),
1971
+ () => retryOnForRestore(blockId),
1972
+ )
1973
+ }, RECONCILE_MS)
1974
+ disposers.push(() => clearTimeout(timer))
1975
+ }
1976
+
1977
+ async function holdTargetOn(
1978
+ scope: StepScope,
1979
+ target: ActionTarget,
1980
+ actionId: string,
1981
+ ms: number,
1982
+ vars: Record<string, unknown>,
1983
+ ): Promise<void> {
1984
+ const resolved = await targets.resolve(target, actionId, vars, {
1985
+ actionId,
1986
+ owner: BLOCK_ID ?? undefined,
1987
+ })
1988
+ if (resolved.deviceIds.length === 0) {
1989
+ scope.markEmpty(resolved.emptyReason ?? 'the target matched no device')
1990
+ return
1991
+ }
1992
+ const hold = async (deviceId: number): Promise<void> => {
1993
+ const outcome = await onFor.trigger(deviceId, actionId, ms)
1994
+ scope.setArgs({ onForMs: ms, outcome })
1995
+ const tags = { tags: { deviceId } }
1996
+ switch (outcome) {
1997
+ case 'turned-on':
1998
+ ctx.logger.info('on-for: turned on, off in ' + ms / 1000 + ' s', tags)
1999
+ return
2000
+ case 'extended':
2001
+ ctx.logger.info('on-for: the time restarts, off in ' + ms / 1000 + ' s', tags)
2002
+ return
2003
+ case 'already-on':
2004
+ ctx.logger.info('on-for: already on — nothing sent, and it will not be turned off', tags)
2005
+ return
2006
+ case 'unknown':
2007
+ ctx.logger.warn('on-for: the state could not be read — nothing sent', tags)
2008
+ throw new Error('the device state could not be read')
2009
+ case 'failed':
2010
+ throw new Error('the device could not be turned on')
2011
+ case 'not-holdable':
2012
+ throw new Error(actionId + ' cannot be held on for a time')
2013
+ }
2014
+ }
2015
+ const [only] = resolved.deviceIds
2016
+ if (resolved.deviceIds.length === 1 && only !== undefined) {
2017
+ scope.setDeviceId(only)
2018
+ await hold(only)
2019
+ return
2020
+ }
2021
+ await runForDevices(resolved.deviceIds, scope, hold)
2022
+ }
2023
+
1875
2024
  function warnMissingVar(name: string): void {
1876
2025
  ctx.logger.warn('template referenced a var that was never set', { var: name })
1877
2026
  }
@@ -1917,6 +2066,16 @@ ${hasTime ? ` // a time-is leaf changes sides at a boundary with no device ev
1917
2066
  const resolved: Record<string, unknown> =
1918
2067
  substituted !== null && typeof substituted === 'object' ? { ...substituted } : {}
1919
2068
  scope.setArgs(resolved)
2069
+ await callCap(deviceId, cap, method, resolved)
2070
+ }
2071
+
2072
+ /** One device method call, through the cap's router. */
2073
+ async function callCap(
2074
+ deviceId: number,
2075
+ cap: string,
2076
+ method: string,
2077
+ resolved: Record<string, unknown>,
2078
+ ): Promise<void> {
1920
2079
  // Forked-addon ctx.api namespaces are tRPC Proxies over a noop function
1921
2080
  // (typeof === 'function'), not plain objects — reject only null/undefined.
1922
2081
  const client: unknown = Reflect.get(ctx.api, capToRouterKey(cap))
@@ -2281,9 +2440,9 @@ async function assertStepsOffered(steps, reader) {
2281
2440
  //#region ../types/dist/esm/automation/step-condition.mjs
2282
2441
  /** Fill a mirror for the tree's leaves from `fetchers` and judge it NOW. */
2283
2442
  async function evaluateStepCondition(when, fetchers, now = Date.now, history, site, trigger) {
2284
- const mirror = history?.mirror ?? new require_prefix_walk.ConditionMirror(require_prefix_walk.collectWhenMirrorSources(when));
2443
+ const mirror = history?.mirror ?? new require_named_entity_store.ConditionMirror(require_named_entity_store.collectWhenMirrorSources(when));
2285
2444
  await mirror.refresh(fetchers);
2286
- const evaluation = require_prefix_walk.evaluateWhenTree(when, mirror, now(), {
2445
+ const evaluation = require_named_entity_store.evaluateWhenTree(when, mirror, now(), {
2287
2446
  ...history === void 0 ? {} : {
2288
2447
  holds: history.holds,
2289
2448
  rootPath: history.rootPath
@@ -3483,15 +3642,25 @@ var BUILTIN_REMOTE_COMPONENTS = [
3483
3642
  * traces and run modes apply; the template only fixes the shape. The operator
3484
3643
  * reads and writes it from the COMMANDED device's Customize tab.
3485
3644
  *
3486
- * Sources are events only: a device that fired (`device-fired`, optionally one
3487
- * part, event, shared kind and payload predicates) or a device event of a
3488
- * category. The action is a plain on, off or toggle of one capability of the
3489
- * target. A linked trigger commands the target; it never claims the target's
3490
- * state (that belongs to the target's own provider, D663).
3645
+ * A source is something that HAPPENS: a device that fired (`device-fired`,
3646
+ * optionally one part, event, shared kind and payload predicates), a device
3647
+ * event of a category, a device field taking a value (`device-becomes`: motion
3648
+ * detected), or a camera detecting a class (`detection`). The action is a plain
3649
+ * on, off or toggle of one capability of the target. "On" may be held for a
3650
+ * time (`onForSeconds`): the engine turns the target on only if it is off and
3651
+ * off again when the time is up, each new event restarting the time
3652
+ * (`automation/on-for.ts`). An optional time window limits when it runs. A
3653
+ * linked trigger commands the target; it never claims the target's state (that
3654
+ * belongs to the target's own provider, D663).
3491
3655
  */
3492
3656
  var LINKED_TRIGGER_TEMPLATE_ID = "builtin:linked-trigger";
3493
3657
  /** The input key whose value is the commanded device: the read keys on it. */
3494
3658
  var LINKED_TRIGGER_TARGET_INPUT = "target";
3659
+ /** The template input keys of the optional duration and time window. */
3660
+ var LINKED_TRIGGER_ON_FOR_INPUT = "onFor";
3661
+ var LINKED_TRIGGER_WINDOW_INPUT = "active";
3662
+ /** The optional limit on the state of a device (a derived "is night"). */
3663
+ var LINKED_TRIGGER_STATE_INPUT = "activeWhen";
3495
3664
  //#endregion
3496
3665
  //#region ../types/dist/esm/template/builtin-automation-templates.mjs
3497
3666
  /**
@@ -3503,114 +3672,13 @@ var LINKED_TRIGGER_TARGET_INPUT = "target";
3503
3672
  */
3504
3673
  var BUILTIN_TEMPLATE_ID_PREFIX = "builtin:";
3505
3674
  /** The optional limit a built-in ends with: no value, no limit. */
3506
- var ACTIVE_WINDOW_KEY = "active";
3675
+ var ACTIVE_WINDOW_KEY = LINKED_TRIGGER_WINDOW_INPUT;
3507
3676
  var BUILTIN_AUTOMATION_TEMPLATES = [{
3508
- id: `${BUILTIN_TEMPLATE_ID_PREFIX}motion-light`,
3509
- name: "Motion → light, off after a delay",
3510
- payload: {
3511
- version: 1,
3512
- description: "Turns lights on when a motion sensor detects motion and off once it has been quiet for the delay. New motion restarts the delay.",
3513
- body: {
3514
- when: {
3515
- kind: "device-becomes",
3516
- cap: "motion",
3517
- fieldPath: "detected",
3518
- becomes: true
3519
- },
3520
- actions: [
3521
- {
3522
- kind: "command",
3523
- actionId: "switch.on"
3524
- },
3525
- {
3526
- kind: "wait",
3527
- seconds: 300
3528
- },
3529
- {
3530
- kind: "command",
3531
- actionId: "switch.off"
3532
- }
3533
- ],
3534
- runMode: { mode: "restart" }
3535
- },
3536
- inputs: [
3537
- {
3538
- kind: "device",
3539
- key: "sensor",
3540
- label: "Motion sensor",
3541
- filter: { capability: "motion" }
3542
- },
3543
- {
3544
- kind: "device",
3545
- key: "lights",
3546
- label: "Lights",
3547
- multiple: true,
3548
- filter: { capability: "switch" }
3549
- },
3550
- {
3551
- kind: "duration",
3552
- key: "delay",
3553
- label: "Off after (seconds)",
3554
- min: 10,
3555
- max: 3600,
3556
- default: 300
3557
- },
3558
- {
3559
- kind: "time-window",
3560
- key: ACTIVE_WINDOW_KEY,
3561
- label: "Only when",
3562
- description: "Limit the automation to a time of day, to some days, or both.",
3563
- optional: true
3564
- }
3565
- ],
3566
- bindings: [
3567
- {
3568
- kind: "value",
3569
- input: "sensor",
3570
- path: ["when", "deviceId"]
3571
- },
3572
- {
3573
- kind: "value",
3574
- input: "lights",
3575
- path: [
3576
- "actions",
3577
- 0,
3578
- "target"
3579
- ],
3580
- as: "target"
3581
- },
3582
- {
3583
- kind: "value",
3584
- input: "delay",
3585
- path: [
3586
- "actions",
3587
- 1,
3588
- "seconds"
3589
- ]
3590
- },
3591
- {
3592
- kind: "value",
3593
- input: "lights",
3594
- path: [
3595
- "actions",
3596
- 2,
3597
- "target"
3598
- ],
3599
- as: "target"
3600
- },
3601
- {
3602
- kind: "gate",
3603
- input: ACTIVE_WINDOW_KEY,
3604
- path: ["when"]
3605
- }
3606
- ]
3607
- }
3608
- }, {
3609
3677
  id: LINKED_TRIGGER_TEMPLATE_ID,
3610
3678
  name: "Linked trigger",
3611
3679
  payload: {
3612
3680
  version: 1,
3613
- description: "Commands one device (on, off or toggle) when a device fires an event.",
3681
+ description: "Commands one device (on, off, toggle, or on for a time) when a device fires an event, reports a state or a camera detects a class.",
3614
3682
  body: {
3615
3683
  when: {
3616
3684
  kind: "any",
@@ -3639,8 +3707,36 @@ var BUILTIN_AUTOMATION_TEMPLATES = [{
3639
3707
  key: "when",
3640
3708
  label: "When",
3641
3709
  entry: "trigger",
3642
- allow: ["device-fired", "device-event"],
3710
+ allow: [
3711
+ "device-fired",
3712
+ "device-event",
3713
+ "device-becomes",
3714
+ "detection"
3715
+ ],
3643
3716
  maxItems: 10
3717
+ },
3718
+ {
3719
+ kind: "duration",
3720
+ key: LINKED_TRIGGER_ON_FOR_INPUT,
3721
+ label: "On for (seconds)",
3722
+ description: "Turns it on only if it is off, and off again after this long. A new event restarts the time.",
3723
+ min: 1,
3724
+ max: require_core_blocks_cap.ON_FOR_MAX_SECONDS,
3725
+ optional: true
3726
+ },
3727
+ {
3728
+ kind: "time-window",
3729
+ key: ACTIVE_WINDOW_KEY,
3730
+ label: "Only when",
3731
+ description: "Limit the automation to a time of day, to some days, or both.",
3732
+ optional: true
3733
+ },
3734
+ {
3735
+ kind: "device-state",
3736
+ key: LINKED_TRIGGER_STATE_INPUT,
3737
+ label: "Only while",
3738
+ description: "Limit the automation to while a device reads a value, such as a derived night.",
3739
+ optional: true
3644
3740
  }
3645
3741
  ],
3646
3742
  bindings: [
@@ -3663,6 +3759,26 @@ var BUILTIN_AUTOMATION_TEMPLATES = [{
3663
3759
  kind: "entries",
3664
3760
  input: "when",
3665
3761
  path: ["when", "children"]
3762
+ },
3763
+ {
3764
+ kind: "value",
3765
+ input: LINKED_TRIGGER_ON_FOR_INPUT,
3766
+ path: [
3767
+ "actions",
3768
+ 0,
3769
+ "onFor",
3770
+ "seconds"
3771
+ ]
3772
+ },
3773
+ {
3774
+ kind: "gate",
3775
+ input: ACTIVE_WINDOW_KEY,
3776
+ path: ["when"]
3777
+ },
3778
+ {
3779
+ kind: "gate",
3780
+ input: LINKED_TRIGGER_STATE_INPUT,
3781
+ path: ["when"]
3666
3782
  }
3667
3783
  ]
3668
3784
  }
@@ -8478,13 +8594,16 @@ var BlockSupervisor = class {
8478
8594
  * then never re-launch it.
8479
8595
  */
8480
8596
  /**
8481
- * The block row is already gone. The next apply names it retired so its
8482
- * claims are released before this resolves. A release that does not land is
8483
- * returned; the id stays retired so the following pass tries again.
8597
+ * The block row is already gone. ONE composer apply names it retired so its
8598
+ * claims are released before this resolves. It is NOT queued on the converge
8599
+ * chain: that chain also launches, stops and reports every code block, and a
8600
+ * delete waiting behind a pass that is compiling or spawning one paid for all
8601
+ * of it. The composer serialises its own applies, so this one is ordered
8602
+ * against a concurrent pass there. A release that does not land is returned;
8603
+ * the id stays retired so the following pass tries again.
8484
8604
  */
8485
8605
  retireComposition(blockId) {
8486
- this.retiredBlockIds = new Set([...this.retiredBlockIds, blockId]);
8487
- return this.converge().then(() => this.claimsOf(blockId));
8606
+ return this.releaseRetired(blockId);
8488
8607
  }
8489
8608
  /**
8490
8609
  * One apply, awaited. Used when an edit replaced a block's caps: the
@@ -8567,7 +8686,7 @@ var BlockSupervisor = class {
8567
8686
  }
8568
8687
  await this.launch(block);
8569
8688
  }
8570
- await this.convergeCompositions(blocks, snapshots);
8689
+ await this.convergeCompositions(snapshots);
8571
8690
  }
8572
8691
  /**
8573
8692
  * Send every composition placed here to the composer and mirror its verdicts
@@ -8575,8 +8694,8 @@ var BlockSupervisor = class {
8575
8694
  * does not trust its store or seed yet) is mirrored as `starting`; the next
8576
8695
  * pass of this same converge is the retry — no timer of its own (D3).
8577
8696
  */
8578
- async convergeCompositions(blocks, runners) {
8579
- const compositions = blocks.flatMap((block) => {
8697
+ async convergeCompositions(runners) {
8698
+ const compositions = this.deps.store.list().flatMap((block) => {
8580
8699
  const composition = require_core_blocks_cap.coreBlockComposition(block);
8581
8700
  return composition !== null && this.isPlacedHere(block) ? [{
8582
8701
  block,
@@ -8600,6 +8719,7 @@ var BlockSupervisor = class {
8600
8719
  return;
8601
8720
  }
8602
8721
  const restart = this.pendingCompositionRestarts;
8722
+ const sentRetired = this.retiredBlockIds;
8603
8723
  const integrationId = this.deps.integrationId();
8604
8724
  const storeLoaded = this.deps.storeLoaded();
8605
8725
  try {
@@ -8615,7 +8735,7 @@ var BlockSupervisor = class {
8615
8735
  })),
8616
8736
  restartBlockIds: [...restart],
8617
8737
  unreadableBlocks: [...unreadable],
8618
- retiredBlockIds: [...this.retiredBlockIds]
8738
+ retiredBlockIds: [...sentRetired]
8619
8739
  });
8620
8740
  if (this.failedApplies > 0) {
8621
8741
  this.deps.logger.info("the composer answered again", { meta: { failedApplies: this.failedApplies } });
@@ -8623,7 +8743,7 @@ var BlockSupervisor = class {
8623
8743
  }
8624
8744
  this.pendingCompositionRestarts = new Set([...this.pendingCompositionRestarts].filter((id) => !restart.has(id)));
8625
8745
  this.emptyAppliesOwed = !nothingToSay || !result.acted ? 2 : Math.max(0, this.emptyAppliesOwed - 1);
8626
- this.noteRelease(result);
8746
+ this.noteRelease(result, sentRetired);
8627
8747
  const verdicts = new Map(result.blocks.map((v) => [v.blockId, v]));
8628
8748
  for (const { block } of compositions) {
8629
8749
  const verdict = verdicts.get(block.id);
@@ -8644,12 +8764,57 @@ var BlockSupervisor = class {
8644
8764
  for (const { block } of compositions) if (block.status === "stopped" && block.enabled) await this.report(block.id, "starting", `the composer is not reachable yet: ${error}`);
8645
8765
  }
8646
8766
  }
8647
- claimsOf(blockId) {
8648
- if (this.releaseReport.error !== null) throw new Error(`core-blocks: claims of "${blockId}" were not released — ${this.releaseReport.error}`);
8649
- return this.releaseReport.unreleased.filter((claim) => claim.owner === blockId);
8767
+ async releaseRetired(blockId) {
8768
+ const composer = this.deps.composer;
8769
+ if (composer === null) throw new Error(`core-blocks: claims of "${blockId}" were not released — no composer is available on this node — claims cannot be released`);
8770
+ const sent = new Set([...this.retiredBlockIds, blockId]);
8771
+ this.retiredBlockIds = sent;
8772
+ let result;
8773
+ try {
8774
+ result = await composer.apply(this.compositionApplyInput(/* @__PURE__ */ new Set(), sent));
8775
+ } catch (err) {
8776
+ throw new Error(`core-blocks: claims of "${blockId}" were not released — ${require_scoped_settings.errMsg(err)}`, { cause: err });
8777
+ }
8778
+ const unreleased = result.unreleasedClaims ?? [];
8779
+ if (!result.acted) throw new Error(`core-blocks: claims of "${blockId}" were not released — the composer did not apply — claims stay until it does`);
8780
+ this.settleRetired(sent, unreleased);
8781
+ return unreleased.filter((claim) => claim.owner === blockId);
8782
+ }
8783
+ /**
8784
+ * After an apply that acted: an id it SENT stays retired only while it still
8785
+ * holds a claim; an id added meanwhile (not in `sent`) is left alone — a
8786
+ * concurrent apply must not forget a retirement it never carried.
8787
+ */
8788
+ settleRetired(sent, unreleased) {
8789
+ const failed = new Set(unreleased.map((claim) => claim.owner));
8790
+ this.retiredBlockIds = new Set([...this.retiredBlockIds].filter((id) => !sent.has(id) || failed.has(id)));
8791
+ }
8792
+ /** What one composer apply carries: every composition placed here, plus the retired ids. */
8793
+ compositionApplyInput(restart, retired) {
8794
+ const compositions = this.deps.store.list().flatMap((block) => {
8795
+ const composition = require_core_blocks_cap.coreBlockComposition(block);
8796
+ return composition !== null && this.isPlacedHere(block) ? [{
8797
+ block,
8798
+ composition
8799
+ }] : [];
8800
+ });
8801
+ return {
8802
+ integrationId: this.deps.integrationId(),
8803
+ storeLoaded: this.deps.storeLoaded(),
8804
+ blocks: compositions.map(({ block, composition }) => ({
8805
+ id: block.id,
8806
+ name: block.name,
8807
+ enabled: block.enabled,
8808
+ updatedAt: block.updatedAt,
8809
+ composition
8810
+ })),
8811
+ restartBlockIds: [...restart],
8812
+ unreadableBlocks: [...this.deps.store.unreadableCompositions()],
8813
+ retiredBlockIds: [...retired]
8814
+ };
8650
8815
  }
8651
8816
  /** Remember which retired ids still hold a claim. An apply that did not act keeps every id. */
8652
- noteRelease(result) {
8817
+ noteRelease(result, sent) {
8653
8818
  const unreleased = result.unreleasedClaims ?? [];
8654
8819
  if (!result.acted) {
8655
8820
  this.releaseReport = {
@@ -8662,8 +8827,7 @@ var BlockSupervisor = class {
8662
8827
  error: null,
8663
8828
  unreleased
8664
8829
  };
8665
- const failed = new Set(unreleased.map((claim) => claim.owner));
8666
- this.retiredBlockIds = new Set([...this.retiredBlockIds].filter((id) => failed.has(id)));
8830
+ this.settleRetired(sent, unreleased);
8667
8831
  }
8668
8832
  /** Compile, write the package, spawn. Each failure is reported ON the block
8669
8833
  * — the author asked for this to run, so they are owed the reason it does
@@ -8776,6 +8940,7 @@ var ActionRowBodySchema = zod.z.object({
8776
8940
  variables: zod.z.array(require_rename_composition_block.ActionVariableSchema).max(20).optional(),
8777
8941
  minDelaySec: require_rename_composition_block.ActionMinDelaySecSchema.optional(),
8778
8942
  tags: require_tag.TagsFieldSchema.optional(),
8943
+ tagIds: require_tag.TagIdsFieldSchema.optional(),
8779
8944
  createdAt: zod.z.number(),
8780
8945
  updatedAt: zod.z.number()
8781
8946
  });
@@ -8787,10 +8952,12 @@ var TemplateRowBodySchema = zod.z.object({
8787
8952
  name: zod.z.string().min(1).max(120),
8788
8953
  payload: zod.z.unknown(),
8789
8954
  tags: require_tag.TagsFieldSchema.optional(),
8955
+ tagIds: require_tag.TagIdsFieldSchema.optional(),
8790
8956
  createdAt: zod.z.number(),
8791
8957
  updatedAt: zod.z.number()
8792
8958
  });
8793
8959
  var TagStyleRowBodySchema = require_tag.TagStyleSchema;
8960
+ var TagRowBodySchema = require_device_manager_cap.TagBodySchema;
8794
8961
  var TimedRunRowBodySchema = zod.z.object({
8795
8962
  activeUntil: zod.z.number(),
8796
8963
  requestedBy: zod.z.string().nullable(),
@@ -8877,13 +9044,21 @@ var _coreBlocksRecordKinds = require_record_kind.defineRecordKinds({
8877
9044
  retention: { none: "operator delete only; a template a device still uses is refused" },
8878
9045
  maxDataBytes: 256 * 1024
8879
9046
  },
9047
+ tags: {
9048
+ schema: TagRowBodySchema,
9049
+ class: "config",
9050
+ writeTrigger: "ensureTag / updateTag / deleteTag, and the tags-as-records migration (D1089)",
9051
+ device: "none",
9052
+ at: "none",
9053
+ retention: { none: "operator action only: deleting the tag" }
9054
+ },
8880
9055
  "tag-styles": {
8881
9056
  schema: TagStyleRowBodySchema,
8882
9057
  class: "config",
8883
- writeTrigger: "the operator styles a tag (setStyle); a rename moves it; a remove deletes it",
9058
+ writeTrigger: "legacy only — the tags-as-records migration reads then deletes rows (D1089)",
8884
9059
  device: "none",
8885
9060
  at: "none",
8886
- retention: { none: "operator action only: removing or renaming the tag" }
9061
+ retention: { none: "rows deleted by the tags-as-records migration" }
8887
9062
  },
8888
9063
  settings: {
8889
9064
  schema: CoreBlockSettingsBodySchema,
@@ -8940,7 +9115,7 @@ async function clearNodeSettings(door, nodeId) {
8940
9115
  */
8941
9116
  async function readUnscopedAddonSettings(door, addonId) {
8942
9117
  try {
8943
- const all = await require_prefix_walk.loadPrefixed(door, ADDON_SETTINGS_COLLECTION, `${addonId}.`);
9118
+ const all = await require_named_entity_store.loadPrefixed(door, ADDON_SETTINGS_COLLECTION, `${addonId}.`);
8944
9119
  const value = Object.fromEntries(Object.entries(all).filter(([key]) => (0, _camstack_types_addon.nodeIdOfScopedKey)(key) === null));
8945
9120
  return Object.keys(value).length === 0 ? { kind: "absent" } : {
8946
9121
  kind: "present",
@@ -8959,7 +9134,7 @@ function createAddonSettingsStore(door, addonId) {
8959
9134
  const store = {
8960
9135
  async read() {
8961
9136
  try {
8962
- const value = await require_prefix_walk.loadPrefixed(door, ADDON_SETTINGS_COLLECTION, prefix);
9137
+ const value = await require_named_entity_store.loadPrefixed(door, ADDON_SETTINGS_COLLECTION, prefix);
8963
9138
  return Object.keys(value).length === 0 ? { kind: "absent" } : {
8964
9139
  kind: "present",
8965
9140
  value
@@ -8979,7 +9154,7 @@ function createAddonSettingsStore(door, addonId) {
8979
9154
  });
8980
9155
  return row === void 0 || row === null ? { kind: "absent" } : {
8981
9156
  kind: "present",
8982
- value: require_prefix_walk.unwrapStoredValue(row)
9157
+ value: require_named_entity_store.unwrapStoredValue(row)
8983
9158
  };
8984
9159
  } catch (err) {
8985
9160
  return {
@@ -9962,6 +10137,19 @@ var CoreBlockStore = class CoreBlockStore {
9962
10137
  await this.persist(next);
9963
10138
  this.byId.set(next.id, next);
9964
10139
  }
10140
+ /** Replace the tag ids of a block (D1089); everything else is left as it is. */
10141
+ async setTagIds(blockId, tagIds) {
10142
+ const existing = this.byId.get(blockId);
10143
+ if (!existing) throw new Error(`core block not found: ${blockId}`);
10144
+ const { tagIds: _previous, ...rest } = existing;
10145
+ const unique = [...new Set(tagIds)];
10146
+ const next = require_core_blocks_cap.CoreBlockSchema.parse(unique.length === 0 ? rest : {
10147
+ ...rest,
10148
+ tagIds: unique
10149
+ });
10150
+ await this.persist(next);
10151
+ this.byId.set(next.id, next);
10152
+ }
9965
10153
  /**
9966
10154
  * Store a composition block (D659): hub-placed, no code, never `running` on
9967
10155
  * creation — the composer's verdict, mirrored by the supervisor, says that.
@@ -10793,6 +10981,260 @@ async function splitPumpCycleFromFountain(ports) {
10793
10981
  };
10794
10982
  }
10795
10983
  //#endregion
10984
+ //#region src/builtins/core-blocks/migrations/tag-ids.ts
10985
+ /**
10986
+ * Every core-blocks record that carries tags gets the ids of those tags (D1089, the
10987
+ * core-blocks step of the tags migration): `tagIds` is added beside the kept `tags` names,
10988
+ * aligned by index, each id derived from the folded name (`tagIdFromKey`) so the device
10989
+ * manager and the notification rules mint the same id for the same name without reading each
10990
+ * other. The names stay for one release.
10991
+ *
10992
+ * Four owners: core blocks (the tags sit on the block inside the row body), schedulers,
10993
+ * templates and actions. A row with no tags, or one that already has `tagIds`, is left
10994
+ * alone, so a rerun edits nothing. A row whose names repeat one tag in two spellings is
10995
+ * rewritten with both fields de-duplicated, so the index alignment holds. Each row is
10996
+ * replaced only if it is still at the revision that was read; a row changed meanwhile fails
10997
+ * the run, which retries on the next boot.
10998
+ */
10999
+ var CORE_BLOCKS_TAG_IDS_ID = "core-blocks/2026-11-23-tag-ids";
11000
+ function stringList(value) {
11001
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
11002
+ }
11003
+ function tagsOfBlock(block) {
11004
+ return {
11005
+ tags: stringList(block["tags"]),
11006
+ hasTagIds: Array.isArray(block["tagIds"])
11007
+ };
11008
+ }
11009
+ function tagIdsPortsOver(kinds, logger) {
11010
+ const rowOf = (owner, row, tags, hasTagIds) => ({
11011
+ owner,
11012
+ id: row.id,
11013
+ rev: row.rev,
11014
+ tags,
11015
+ hasTagIds
11016
+ });
11017
+ return {
11018
+ listTaggedRows: async () => {
11019
+ const blocks = (await (0, import_read_all_rows.readAllRows)(kinds.blocks)).map((row) => {
11020
+ const { tags, hasTagIds } = tagsOfBlock(row.data.block);
11021
+ return rowOf("blocks", row, tags, hasTagIds);
11022
+ });
11023
+ const schedulers = (await (0, import_read_all_rows.readAllRows)(kinds.schedulers)).map((row) => rowOf("schedulers", row, row.data.tags ?? [], row.data.tagIds !== void 0));
11024
+ const templates = (await (0, import_read_all_rows.readAllRows)(kinds.templates)).map((row) => rowOf("templates", row, row.data.tags ?? [], row.data.tagIds !== void 0));
11025
+ const actions = (await (0, import_read_all_rows.readAllRows)(kinds.actions)).map((row) => rowOf("actions", row, row.data.tags ?? [], row.data.tagIds !== void 0));
11026
+ return [
11027
+ ...blocks,
11028
+ ...schedulers,
11029
+ ...templates,
11030
+ ...actions
11031
+ ];
11032
+ },
11033
+ writeTagIds: async (row, tagIds, tags) => {
11034
+ const ids = [...tagIds];
11035
+ const names = tags === null ? null : [...tags];
11036
+ switch (row.owner) {
11037
+ case "blocks": {
11038
+ const current = await kinds.blocks.get(row.id);
11039
+ if (current === null || current.rev !== row.rev) throw movedError(row);
11040
+ const block = {
11041
+ ...current.data.block,
11042
+ tagIds: ids,
11043
+ ...names === null ? {} : { tags: names }
11044
+ };
11045
+ await kinds.blocks.put({
11046
+ id: row.id,
11047
+ data: {
11048
+ ...current.data,
11049
+ block
11050
+ }
11051
+ }, { ifRev: row.rev });
11052
+ return;
11053
+ }
11054
+ case "schedulers": {
11055
+ const current = await kinds.schedulers.get(row.id);
11056
+ if (current === null || current.rev !== row.rev) throw movedError(row);
11057
+ await kinds.schedulers.put({
11058
+ id: row.id,
11059
+ data: {
11060
+ ...current.data,
11061
+ tagIds: ids,
11062
+ ...names === null ? {} : { tags: names }
11063
+ }
11064
+ }, { ifRev: row.rev });
11065
+ return;
11066
+ }
11067
+ case "templates": {
11068
+ const current = await kinds.templates.get(row.id);
11069
+ if (current === null || current.rev !== row.rev) throw movedError(row);
11070
+ await kinds.templates.put({
11071
+ id: row.id,
11072
+ data: {
11073
+ ...current.data,
11074
+ tagIds: ids,
11075
+ ...names === null ? {} : { tags: names }
11076
+ }
11077
+ }, { ifRev: row.rev });
11078
+ return;
11079
+ }
11080
+ case "actions": {
11081
+ const current = await kinds.actions.get(row.id);
11082
+ if (current === null || current.rev !== row.rev) throw movedError(row);
11083
+ await kinds.actions.put({
11084
+ id: row.id,
11085
+ data: {
11086
+ ...current.data,
11087
+ tagIds: ids,
11088
+ ...names === null ? {} : { tags: names }
11089
+ }
11090
+ }, { ifRev: row.rev });
11091
+ return;
11092
+ }
11093
+ }
11094
+ },
11095
+ info: (message, meta) => {
11096
+ logger.info(message, { meta });
11097
+ }
11098
+ };
11099
+ }
11100
+ function movedError(row) {
11101
+ return /* @__PURE__ */ new Error(`${row.owner} record ${row.id} changed since it was read`);
11102
+ }
11103
+ async function addTagIds(ports) {
11104
+ const rows = await ports.listTaggedRows();
11105
+ let written = 0;
11106
+ for (const row of rows) {
11107
+ if (row.hasTagIds) continue;
11108
+ const names = require_tag.normalizeTags(row.tags);
11109
+ if (names.length === 0) continue;
11110
+ const sameNames = names.length === row.tags.length;
11111
+ await ports.writeTagIds(row, names.map((name) => require_named_entity_store.tagIdFromKey(require_tag.tagKey(name))), sameNames ? null : names);
11112
+ written += 1;
11113
+ }
11114
+ if (written === 0) return {
11115
+ outcome: "already-done",
11116
+ summary: { records: 0 }
11117
+ };
11118
+ ports.info("core-blocks tag ids added", { records: written });
11119
+ return {
11120
+ outcome: "done",
11121
+ summary: { records: written }
11122
+ };
11123
+ }
11124
+ //#endregion
11125
+ //#region src/builtins/core-blocks/migrations/tags-as-records.ts
11126
+ /**
11127
+ * Tags become records with an id (D1089, the last step of the tags migration).
11128
+ *
11129
+ * Before: a tag was a NAME on the records it labelled; its only registry was a style row
11130
+ * (`tag-styles`: colour and icon). After: one `tags` record per tag in use or styled, whose
11131
+ * id is the one the per-owner steps already wrote into `tagIds` (`tagIdFromKey` of the folded
11132
+ * name), carrying the colour and icon of its style. The style rows are then deleted.
11133
+ *
11134
+ * Idempotent and ordered so a crash loses nothing: every record is written BEFORE any style
11135
+ * row is deleted, an existing record is never overwritten (a seed never overwrites), and a
11136
+ * rerun finds no style row and every tag present. The display spelling is the style's, else
11137
+ * the one used most (the first alphabetically on a tie).
11138
+ *
11139
+ * `dependsOn` the owner steps that add `tagIds`, so a record exists under the id they used.
11140
+ * Names held by owners outside this addon (the device manager, the notification rules) are
11141
+ * read best effort: one that cannot be reached right now is logged and skipped, because its
11142
+ * tag is created on first use by `ensureTag` and its rows keep the kept names meanwhile; a
11143
+ * styled tag is carried either way.
11144
+ */
11145
+ var TAGS_AS_RECORDS_ID = "core-blocks/2026-11-23-tags-as-records";
11146
+ function tagsAsRecordsPortsOver(input) {
11147
+ return {
11148
+ localNames: async () => (await input.tagIds.listTaggedRows()).flatMap((row) => [...row.tags]),
11149
+ externalNames: async () => {
11150
+ try {
11151
+ return await input.external();
11152
+ } catch (err) {
11153
+ input.logger.warn("tags migration: another owner could not be read, skipped", { meta: { error: err instanceof Error ? err.message : String(err) } });
11154
+ return null;
11155
+ }
11156
+ },
11157
+ listStyles: async () => (await (0, import_read_all_rows.readAllRows)(input.styles)).map((row) => ({
11158
+ id: row.id,
11159
+ style: row.data
11160
+ })),
11161
+ existingTagIds: async () => new Set((await (0, import_read_all_rows.readAllRows)(input.tags)).map((row) => row.id)),
11162
+ createTag: async (id, body) => {
11163
+ await input.tags.put({
11164
+ id,
11165
+ data: body
11166
+ }, { ifRev: 0 });
11167
+ },
11168
+ deleteStyle: async (id) => {
11169
+ await input.styles.delete(id);
11170
+ },
11171
+ info: (message, meta) => {
11172
+ input.logger.info(message, { meta });
11173
+ },
11174
+ warn: (message, meta) => {
11175
+ input.logger.warn(message, { meta });
11176
+ }
11177
+ };
11178
+ }
11179
+ function mostUsed(counts) {
11180
+ const best = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0];
11181
+ return best === void 0 ? "" : best[0];
11182
+ }
11183
+ async function writeTagRecords(ports) {
11184
+ const styles = await ports.listStyles();
11185
+ const external = await ports.externalNames();
11186
+ if (external === null) {
11187
+ ports.warn("tags migration: another owner could not be read, will retry on the next boot", {});
11188
+ throw new Error("tags migration: names of other owners could not be read, retrying next boot");
11189
+ }
11190
+ const spellings = /* @__PURE__ */ new Map();
11191
+ for (const name of [...await ports.localNames(), ...external]) {
11192
+ const trimmed = name.trim();
11193
+ if (trimmed.length === 0) continue;
11194
+ const counts = spellings.get(require_tag.tagKey(trimmed)) ?? /* @__PURE__ */ new Map();
11195
+ counts.set(trimmed, (counts.get(trimmed) ?? 0) + 1);
11196
+ spellings.set(require_tag.tagKey(trimmed), counts);
11197
+ }
11198
+ const styleOf = new Map(styles.map((row) => [require_tag.tagKey(row.style.name), row.style]));
11199
+ const existing = await ports.existingTagIds();
11200
+ const keys = new Set([...spellings.keys(), ...styleOf.keys()]);
11201
+ let created = 0;
11202
+ for (const key of [...keys].sort()) {
11203
+ const id = require_named_entity_store.tagIdFromKey(key);
11204
+ if (existing.has(id)) continue;
11205
+ const style = styleOf.get(key);
11206
+ const counts = spellings.get(key);
11207
+ const name = style?.name ?? (counts === void 0 ? key : mostUsed(counts));
11208
+ await ports.createTag(id, {
11209
+ name,
11210
+ ...style === void 0 ? {} : {
11211
+ colour: style.color,
11212
+ icon: style.icon
11213
+ }
11214
+ });
11215
+ created += 1;
11216
+ }
11217
+ for (const row of styles) await ports.deleteStyle(row.id);
11218
+ if (created === 0 && styles.length === 0) return {
11219
+ outcome: "already-done",
11220
+ summary: {
11221
+ tags: 0,
11222
+ styles: 0
11223
+ }
11224
+ };
11225
+ ports.info("tags are records", {
11226
+ tags: created,
11227
+ styles: styles.length
11228
+ });
11229
+ return {
11230
+ outcome: "done",
11231
+ summary: {
11232
+ tags: created,
11233
+ styles: styles.length
11234
+ }
11235
+ };
11236
+ }
11237
+ //#endregion
10796
11238
  //#region src/builtins/core-blocks/migrations/remote-config-migrations.ts
10797
11239
  /**
10798
11240
  * Two shape changes of a stored remote, both owned by core-blocks (it owns the
@@ -11065,9 +11507,6 @@ async function renameRemoteColourRoles(ports) {
11065
11507
  }
11066
11508
  };
11067
11509
  }
11068
- //#endregion
11069
- //#region src/builtins/core-blocks/migrations/index.ts
11070
- /** The `core-blocks` catalogue (D987): offered to the engine when the hub-resident addon initialises. */
11071
11510
  var ADDON_MIGRATIONS = [
11072
11511
  {
11073
11512
  meta: {
@@ -11164,6 +11603,42 @@ var ADDON_MIGRATIONS = [
11164
11603
  fixtureMark: "the block createdBy and name, which the migration does not know"
11165
11604
  },
11166
11605
  procedure: regenerateAutomationsConfirmedView
11606
+ },
11607
+ {
11608
+ meta: {
11609
+ id: CORE_BLOCKS_TAG_IDS_ID,
11610
+ owner: "core-blocks",
11611
+ level: "addon-state",
11612
+ seq: 7,
11613
+ dependsOn: [],
11614
+ store: "settings",
11615
+ scope: "cluster",
11616
+ onFailure: "tolerate",
11617
+ bodyKind: "procedure",
11618
+ description: "Add the ids of its tags to each block, scheduler, template and action beside the kept names, derived from the folded name",
11619
+ fixtureMark: "the name and the enabled flag of each record, which the migration does not know"
11620
+ },
11621
+ procedure: addTagIds
11622
+ },
11623
+ {
11624
+ meta: {
11625
+ id: TAGS_AS_RECORDS_ID,
11626
+ owner: "core-blocks",
11627
+ level: "addon-state",
11628
+ seq: 8,
11629
+ dependsOn: [
11630
+ CORE_BLOCKS_TAG_IDS_ID,
11631
+ "device-manager/2026-11-23-device-tag-ids",
11632
+ "pipeline-analytics/2026-11-23-rule-tag-ids"
11633
+ ],
11634
+ store: "settings",
11635
+ scope: "cluster",
11636
+ onFailure: "tolerate",
11637
+ bodyKind: "procedure",
11638
+ description: "Write one tags record per tag in use or styled, carrying the colour and icon of its style, then delete the tag style rows",
11639
+ fixtureMark: "the colour and icon of each styled tag"
11640
+ },
11641
+ procedure: writeTagRecords
11167
11642
  }
11168
11643
  ];
11169
11644
  //#endregion
@@ -11217,15 +11692,15 @@ function conditionDoorOver(api) {
11217
11692
  reason: "this node has no ctx.api to read state through"
11218
11693
  };
11219
11694
  if (readable !== void 0) {
11220
- if (require_prefix_walk.collectWhenMirrorSources(when).filter((source) => source.kind === "stable" || !readable.includes(source.deviceId)).length > 0) return {
11695
+ if (require_named_entity_store.collectWhenMirrorSources(when).filter((source) => source.kind === "stable" || !readable.includes(source.deviceId)).length > 0) return {
11221
11696
  result: "unknown",
11222
11697
  reason: "the condition reads a device this caller was not proven to see"
11223
11698
  };
11224
11699
  }
11225
11700
  let site;
11226
- if (require_prefix_walk.hasTimeLeaves(when)) try {
11701
+ if (require_named_entity_store.hasTimeLeaves(when)) try {
11227
11702
  const reading = await current.system.getSiteLocation.query();
11228
- site = require_core_blocks_cap.siteFor(reading) ?? require_core_blocks_cap.zoneOnlySite(reading.timeZone);
11703
+ site = require_time_window.siteFor(reading) ?? require_time_window.zoneOnlySite(reading.timeZone);
11229
11704
  } catch (error) {
11230
11705
  return {
11231
11706
  result: "unknown",
@@ -11238,7 +11713,7 @@ function conditionDoorOver(api) {
11238
11713
  capName: cap,
11239
11714
  confirmed: true
11240
11715
  }),
11241
- fetchStableIds: async () => require_prefix_walk.stableIdMapOf(await current.deviceManager.listAll.query({}))
11716
+ fetchStableIds: async () => require_named_entity_store.stableIdMapOf(await current.deviceManager.listAll.query({}))
11242
11717
  }, () => Date.now(), void 0, site);
11243
11718
  };
11244
11719
  }
@@ -11310,7 +11785,8 @@ var RunsLedger = class {
11310
11785
  version: 1,
11311
11786
  lastRunStartedAt: row.data.lastRunStartedAt,
11312
11787
  traces: row.data.traces,
11313
- lastError: row.data.lastError
11788
+ lastError: row.data.lastError,
11789
+ ...row.data.onForHolds === void 0 ? {} : { onForHolds: row.data.onForHolds }
11314
11790
  };
11315
11791
  }
11316
11792
  /** Several owners in ONE read; an owner with no row is idle. */
@@ -11322,7 +11798,8 @@ var RunsLedger = class {
11322
11798
  version: 1,
11323
11799
  lastRunStartedAt: row.data.lastRunStartedAt,
11324
11800
  traces: row.data.traces,
11325
- lastError: row.data.lastError
11801
+ lastError: row.data.lastError,
11802
+ ...row.data.onForHolds === void 0 ? {} : { onForHolds: row.data.onForHolds }
11326
11803
  });
11327
11804
  return out;
11328
11805
  }
@@ -11342,6 +11819,7 @@ var RunsLedger = class {
11342
11819
  const traces = report.trace === void 0 ? current.traces.slice(-keep) : require_core_blocks_cap.appendTrace(current.traces, report.trace, keep);
11343
11820
  const failure = report.trace === void 0 ? void 0 : failureOf(report.trace);
11344
11821
  const lastError = report.trace === void 0 || isSkip(report.trace) ? current.lastError : failure;
11822
+ const onForHolds = report.onForHolds ?? current.onForHolds;
11345
11823
  await this.runs.put({
11346
11824
  id: owner,
11347
11825
  data: {
@@ -11349,7 +11827,8 @@ var RunsLedger = class {
11349
11827
  lastRunStartedAt: report.runStartedAt ?? current.lastRunStartedAt,
11350
11828
  traces,
11351
11829
  lastError: lastError ?? null,
11352
- updatedAt: this.now()
11830
+ updatedAt: this.now(),
11831
+ ...onForHolds === void 0 ? {} : { onForHolds: [...onForHolds] }
11353
11832
  }
11354
11833
  });
11355
11834
  }
@@ -12253,6 +12732,20 @@ var ActionsStore = class ActionsStore {
12253
12732
  }
12254
12733
  });
12255
12734
  }
12735
+ /** Replace the tag ids of an internal action (D1089); everything else is left as it is. */
12736
+ async setTagIds(actionId, tagIds) {
12737
+ const existing = require_rename_composition_block.isInternalActionId(actionId) ? await this.actions.get(uuidOf(actionId)) : null;
12738
+ if (existing === null) throw new require_rename_composition_block.ActionError("not-found", `no internal action "${actionId}"`);
12739
+ const { tagIds: _previous, ...rest } = existing.data;
12740
+ const unique = [...new Set(tagIds)];
12741
+ await this.actions.put({
12742
+ id: existing.id,
12743
+ data: unique.length === 0 ? rest : {
12744
+ ...rest,
12745
+ tagIds: unique
12746
+ }
12747
+ });
12748
+ }
12256
12749
  async delete(actionId) {
12257
12750
  if (!require_rename_composition_block.isInternalActionId(actionId)) return false;
12258
12751
  return this.actions.delete(uuidOf(actionId));
@@ -12352,14 +12845,15 @@ function buildRunsApi(ledger, logger) {
12352
12845
  return {
12353
12846
  async reportAutomationRun(input) {
12354
12847
  requireOwner(input, "reportAutomationRun");
12355
- if (input.trace === void 0 && input.runStartedAt === void 0) {
12848
+ if (input.trace === void 0 && input.runStartedAt === void 0 && input.onForHolds === void 0) {
12356
12849
  logger.warn("reportAutomationRun ignored — it carried neither a trace nor a stamp", { meta: { blockId: input.blockId } });
12357
12850
  throw new Error("core-blocks: reportAutomationRun needs a trace or a runStartedAt");
12358
12851
  }
12359
12852
  await ledger.report(automationOwner(input.blockId), {
12360
12853
  ...input.trace === void 0 ? {} : { trace: input.trace },
12361
12854
  ...input.runStartedAt === void 0 ? {} : { runStartedAt: input.runStartedAt },
12362
- ...input.keepTraces === void 0 ? {} : { keepTraces: input.keepTraces }
12855
+ ...input.keepTraces === void 0 ? {} : { keepTraces: input.keepTraces },
12856
+ ...input.onForHolds === void 0 ? {} : { onForHolds: input.onForHolds }
12363
12857
  });
12364
12858
  },
12365
12859
  async getAutomationRunState(input) {
@@ -12368,7 +12862,8 @@ function buildRunsApi(ledger, logger) {
12368
12862
  return {
12369
12863
  version: 1,
12370
12864
  lastRunStartedAt: view.lastRunStartedAt,
12371
- traces: [...view.traces]
12865
+ traces: [...view.traces],
12866
+ ...view.onForHolds === void 0 ? {} : { onForHolds: [...view.onForHolds] }
12372
12867
  };
12373
12868
  },
12374
12869
  async getTraces(input) {
@@ -13236,11 +13731,11 @@ function addLocalDays(localDate, days) {
13236
13731
  * refused at save, this is the read side).
13237
13732
  */
13238
13733
  function timeSiteOf(reading) {
13239
- return require_core_blocks_cap.siteFor(reading) ?? require_core_blocks_cap.zoneOnlySite(reading.timeZone);
13734
+ return require_time_window.siteFor(reading) ?? require_time_window.zoneOnlySite(reading.timeZone);
13240
13735
  }
13241
13736
  /** The instant a local day ends (the next local midnight). */
13242
13737
  function endOfLocalDay(localDate, site) {
13243
- return require_core_blocks_cap.occurrenceOn({
13738
+ return require_time_window.occurrenceOn({
13244
13739
  kind: "clock",
13245
13740
  hh: 0,
13246
13741
  mm: 0
@@ -13248,7 +13743,7 @@ function endOfLocalDay(localDate, site) {
13248
13743
  }
13249
13744
  /** The instant a local day starts. */
13250
13745
  function startOfLocalDay(localDate, site) {
13251
- return require_core_blocks_cap.occurrenceOn({
13746
+ return require_time_window.occurrenceOn({
13252
13747
  kind: "clock",
13253
13748
  hh: 0,
13254
13749
  mm: 0
@@ -13261,7 +13756,7 @@ function startOfLocalDay(localDate, site) {
13261
13756
  function profileTimeline(profile, localDate, site) {
13262
13757
  const placed = profile.points.map((point) => ({
13263
13758
  point,
13264
- at: require_core_blocks_cap.occurrenceOn(point.at, localDate, site)
13759
+ at: require_time_window.occurrenceOn(point.at, localDate, site)
13265
13760
  })).filter((p) => p.at !== null).toSorted((a, b) => a.at - b.at);
13266
13761
  const dayEnd = endOfLocalDay(localDate, site);
13267
13762
  return placed.map((entry, i) => ({
@@ -13281,9 +13776,9 @@ function profileState(scheduler, profile, localDate, isTrue) {
13281
13776
  if (!scheduler.enabled) return "scheduler-disabled";
13282
13777
  if (!isTrue(scheduler.activeWhen)) return "scheduler-inactive";
13283
13778
  if (!profile.enabled) return "profile-disabled";
13284
- if (!profile.days.includes(require_core_blocks_cap.weekdayOfLocalDate(localDate))) return "not-today";
13779
+ if (!profile.days.includes(require_time_window.weekdayOfLocalDate(localDate))) return "not-today";
13285
13780
  if (!isTrue(profile.activeWhen)) return "profile-inactive";
13286
- return scheduler.profiles.slice(0, scheduler.profiles.indexOf(profile)).some((p) => p.enabled && p.days.includes(require_core_blocks_cap.weekdayOfLocalDate(localDate)) && isTrue(p.activeWhen)) ? "shadowed" : "in-force";
13781
+ return scheduler.profiles.slice(0, scheduler.profiles.indexOf(profile)).some((p) => p.enabled && p.days.includes(require_time_window.weekdayOfLocalDate(localDate)) && isTrue(p.activeWhen)) ? "shadowed" : "in-force";
13287
13782
  }
13288
13783
  /**
13289
13784
  * The profile in force on `localDate`: scheduler and profile enabled, both
@@ -13299,7 +13794,7 @@ function selectProfile(scheduler, localDate, isTrue) {
13299
13794
  profile: null,
13300
13795
  idleReason: "the scheduler is not active (its condition is false)"
13301
13796
  };
13302
- const weekday = require_core_blocks_cap.weekdayOfLocalDate(localDate);
13797
+ const weekday = require_time_window.weekdayOfLocalDate(localDate);
13303
13798
  for (const profile of scheduler.profiles) {
13304
13799
  if (!profile.enabled || !profile.days.includes(weekday)) continue;
13305
13800
  if (!isTrue(profile.activeWhen)) continue;
@@ -13315,7 +13810,7 @@ function selectProfile(scheduler, localDate, isTrue) {
13315
13810
  }
13316
13811
  /** The local date of `epochMs` in the site's zone. */
13317
13812
  function localDateIn(epochMs, site) {
13318
- return require_core_blocks_cap.localDateOf(epochMs, site.timeZone);
13813
+ return require_time_window.localDateOf(epochMs, site.timeZone);
13319
13814
  }
13320
13815
  //#endregion
13321
13816
  //#region src/builtins/core-blocks/scheduler/scheduler-trace.ts
@@ -13796,7 +14291,7 @@ var SchedulerEngine = class {
13796
14291
  location: null,
13797
14292
  timeZone: "UTC"
13798
14293
  });
13799
- mirror = new require_prefix_walk.ConditionMirror([]);
14294
+ mirror = new require_named_entity_store.ConditionMirror([]);
13800
14295
  /** `deviceId|cap` → the schedulers that read it. */
13801
14296
  watchers = /* @__PURE__ */ new Map();
13802
14297
  dirty = /* @__PURE__ */ new Set();
@@ -13934,7 +14429,7 @@ var SchedulerEngine = class {
13934
14429
  }
13935
14430
  }
13936
14431
  truthAt(now) {
13937
- return (when) => when === void 0 || require_prefix_walk.evaluateWhenTree(when, this.mirror, now, { site: this.site }).pass;
14432
+ return (when) => when === void 0 || require_named_entity_store.evaluateWhenTree(when, this.mirror, now, { site: this.site }).pass;
13938
14433
  }
13939
14434
  /** Every (device, cap) a scheduler's rules or holds read, so state events can wake it. */
13940
14435
  async rebuildMirror() {
@@ -13950,17 +14445,17 @@ var SchedulerEngine = class {
13950
14445
  };
13951
14446
  for (const s of this.schedulers) {
13952
14447
  if (!s.enabled) continue;
13953
- for (const src of require_prefix_walk.collectWhenMirrorSources(s.activeWhen)) add(s.id, src);
14448
+ for (const src of require_named_entity_store.collectWhenMirrorSources(s.activeWhen)) add(s.id, src);
13954
14449
  for (const profile of s.profiles) {
13955
- for (const src of require_prefix_walk.collectWhenMirrorSources(profile.activeWhen)) add(s.id, src);
14450
+ for (const src of require_named_entity_store.collectWhenMirrorSources(profile.activeWhen)) add(s.id, src);
13956
14451
  for (const point of profile.points) {
13957
- for (const src of require_prefix_walk.collectWhenMirrorSources(point.conditions)) add(s.id, src);
14452
+ for (const src of require_named_entity_store.collectWhenMirrorSources(point.conditions)) add(s.id, src);
13958
14453
  if (point.mode !== "hold") continue;
13959
14454
  for (const src of await this.holdSources(s, point)) add(s.id, src);
13960
14455
  }
13961
14456
  }
13962
14457
  }
13963
- this.mirror = new require_prefix_walk.ConditionMirror([...sources.values()]);
14458
+ this.mirror = new require_named_entity_store.ConditionMirror([...sources.values()]);
13964
14459
  this.watchers = watchers;
13965
14460
  const report = await this.mirror.refresh({
13966
14461
  fetchSlice: (deviceId, cap) => this.deps.host.fetchSlice(deviceId, cap),
@@ -14023,7 +14518,7 @@ var SchedulerEngine = class {
14023
14518
  for (const profile of s.profiles) {
14024
14519
  if (!profile.enabled) continue;
14025
14520
  for (const point of profile.points) {
14026
- const at = require_core_blocks_cap.nextOccurrence(point.at, from, this.site, { days: profile.days });
14521
+ const at = require_time_window.nextOccurrence(point.at, from, this.site, { days: profile.days });
14027
14522
  if (at !== null) this.queue.push({
14028
14523
  kind: "point",
14029
14524
  at,
@@ -14076,7 +14571,7 @@ var SchedulerEngine = class {
14076
14571
  let due;
14077
14572
  for (const tree of trees) {
14078
14573
  if (tree === void 0) continue;
14079
- const ms = require_prefix_walk.nextTimeBoundaryInMs(tree, now, this.site);
14574
+ const ms = require_named_entity_store.nextTimeBoundaryInMs(tree, now, this.site);
14080
14575
  if (ms !== void 0) due = due === void 0 ? ms : Math.min(due, ms);
14081
14576
  }
14082
14577
  if (due !== void 0) this.insert({
@@ -14090,7 +14585,7 @@ var SchedulerEngine = class {
14090
14585
  const profile = scheduler?.profiles.find((p) => p.id === entry.profileId);
14091
14586
  const point = profile?.points.find((p) => p.id === entry.pointId);
14092
14587
  if (scheduler === void 0 || profile === void 0 || point === void 0) return;
14093
- const next = require_core_blocks_cap.nextOccurrence(point.at, entry.at, this.site, { days: profile.days });
14588
+ const next = require_time_window.nextOccurrence(point.at, entry.at, this.site, { days: profile.days });
14094
14589
  if (next !== null) this.insert({
14095
14590
  ...entry,
14096
14591
  at: next
@@ -14506,7 +15001,7 @@ var SchedulersService = class {
14506
15001
  }
14507
15002
  const out = /* @__PURE__ */ new Map();
14508
15003
  for (const date of dates) {
14509
- const weekday = require_core_blocks_cap.weekdayOfLocalDate(date);
15004
+ const weekday = require_time_window.weekdayOfLocalDate(date);
14510
15005
  const windows = [];
14511
15006
  for (const profile of scheduler.profiles) {
14512
15007
  if (!profile.enabled || !profile.days.includes(weekday)) continue;
@@ -14632,6 +15127,21 @@ var SchedulersStore = class SchedulersStore {
14632
15127
  data: body
14633
15128
  });
14634
15129
  }
15130
+ /** Replace the tag ids of a scheduler (D1089); everything else is left as it is. */
15131
+ async setTagIds(schedulerId, tagIds) {
15132
+ const existing = await this.schedulers.get(schedulerId);
15133
+ if (existing === null) throw new require_core_blocks_cap.SchedulerError("not-found", `no scheduler "${schedulerId}"`);
15134
+ const { tagIds: _previous, ...rest } = existing.data;
15135
+ const unique = [...new Set(tagIds)];
15136
+ const body = unique.length === 0 ? rest : {
15137
+ ...rest,
15138
+ tagIds: unique
15139
+ };
15140
+ await this.schedulers.put({
15141
+ id: existing.id,
15142
+ data: body
15143
+ });
15144
+ }
14635
15145
  async delete(schedulerId) {
14636
15146
  const removed = await this.schedulers.delete(schedulerId);
14637
15147
  if (removed) await this.state.delete(schedulerId);
@@ -14670,7 +15180,7 @@ function hostOver(api) {
14670
15180
  confirmed: true
14671
15181
  }),
14672
15182
  fetchStableIds: async () => {
14673
- return require_prefix_walk.stableIdMapOf(await need().deviceManager.listAll.query({ projection: "slim" }));
15183
+ return require_named_entity_store.stableIdMapOf(await need().deviceManager.listAll.query({ projection: "slim" }));
14674
15184
  },
14675
15185
  invokeCap: invokeCapOver(api)
14676
15186
  };
@@ -18625,20 +19135,21 @@ async function readComposedDeviceNames(port) {
18625
19135
  //#endregion
18626
19136
  //#region src/builtins/core-blocks/tags-service.ts
18627
19137
  /**
18628
- * The `tags` cap (D1054). A tag lives on the record it labels — a core block, a
18629
- * scheduler, a template, an action, a device, a notification rule — and only
18630
- * its STYLE (colour token, icon) is registered here. This service is the one place that knows every owner
18631
- * kind, so `rename` and `remove` are ONE server operation that rewrites all of
18632
- * them; the browser never drives that sequence (a closed tab would split the
18633
- * fleet across two spellings).
19138
+ * The `tags` cap (D1089). A tag is a RECORD with an opaque id; a core block, a
19139
+ * scheduler, a template, an action, a device and a notification rule carry the
19140
+ * id, and the name, colour, icon and description live on the record only. So
19141
+ * `updateTag` — a rename included — is ONE write to ONE record, and no owner
19142
+ * has to be reachable. `deleteTag` keeps the one fan-out that remains: it
19143
+ * clears the id from every owner, and refuses while an owner cannot be read.
19144
+ *
19145
+ * `list`, `setStyle`, `rename` and `remove` are the old name-based surface, now
19146
+ * thin shims over the entity methods (kept for one release).
18634
19147
  *
18635
19148
  * Owners are reached through {@link TagOwnerPort}s: the local stores directly,
18636
19149
  * the devices and notification rules through their caps over `ctx.api` — never
18637
- * a second copy. An owner that cannot be read degrades `list` (its count is
18638
- * `null`) and refuses `rename` / `remove` before any write.
18639
- * Tags compare trimmed and case-insensitively (`sameTag`).
19150
+ * a second copy. A names-only owner (a notification rule, until its own
19151
+ * migration lands) still carries text; the service keeps its names in step.
18640
19152
  */
18641
- /** The order owners are read and rewritten in; also the order a first spelling is picked. */
18642
19153
  var OWNER_KINDS = [
18643
19154
  "coreBlocks",
18644
19155
  "schedulers",
@@ -18647,6 +19158,14 @@ var OWNER_KINDS = [
18647
19158
  "devices",
18648
19159
  "notificationRules"
18649
19160
  ];
19161
+ var zeroCounts = () => ({
19162
+ coreBlocks: 0,
19163
+ schedulers: 0,
19164
+ templates: 0,
19165
+ actions: 0,
19166
+ devices: 0,
19167
+ notificationRules: 0
19168
+ });
18650
19169
  /** The list counts: an owner that could not be read is `null`, never `0` (D393). */
18651
19170
  function withUnknown(counts, unreachable) {
18652
19171
  return {
@@ -18659,8 +19178,8 @@ function withUnknown(counts, unreachable) {
18659
19178
  };
18660
19179
  }
18661
19180
  /**
18662
- * A rename or remove refused because one owner kind could not be read. Nothing
18663
- * was written; `owner` names which one, so the operator knows what to bring back.
19181
+ * A delete refused because one owner kind could not be read. Nothing was
19182
+ * written; `owner` names which one, so the operator knows what to bring back.
18664
19183
  */
18665
19184
  var TagOwnerUnreachableError = class extends Error {
18666
19185
  owner;
@@ -18670,36 +19189,72 @@ var TagOwnerUnreachableError = class extends Error {
18670
19189
  this.owner = owner;
18671
19190
  }
18672
19191
  };
18673
- var NO_UPDATES = {
18674
- coreBlocks: 0,
18675
- schedulers: 0,
18676
- templates: 0,
18677
- actions: 0,
18678
- devices: 0,
18679
- notificationRules: 0
18680
- };
18681
19192
  function requireName(value, what) {
18682
19193
  const parsed = require_tag.TagNameSchema.safeParse(value);
18683
19194
  if (!parsed.success) throw new Error(`[tags] ${what} is not a valid tag name: ${parsed.error.issues[0]?.message ?? "invalid"}`);
18684
19195
  return parsed.data;
18685
19196
  }
19197
+ /** A patch field: absent keeps the current value, `null` clears it, a value replaces it. */
19198
+ function applied(patch, current) {
19199
+ if (patch === void 0) return current;
19200
+ return patch === null ? void 0 : patch;
19201
+ }
19202
+ /** Does `record` carry the tag? By id; a record not migrated yet by its kept name. */
19203
+ function carries(record, tag) {
19204
+ if (record.tagIds.includes(tag.id)) return true;
19205
+ if (record.tagIds.length > 0) return false;
19206
+ return record.tags.some((name) => require_tag.tagKey(name) === require_tag.tagKey(tag.name));
19207
+ }
18686
19208
  var TagsService = class {
18687
19209
  deps;
19210
+ store;
19211
+ loaded = null;
18688
19212
  constructor(deps) {
18689
19213
  this.deps = deps;
19214
+ this.store = new require_named_entity_store.NamedEntityStore("tag", deps.tags, (body) => TagRowBodySchema.parse(body));
18690
19215
  }
18691
- async readStyles() {
18692
- const out = [];
18693
- let cursor;
18694
- do {
18695
- const page = await this.deps.styles.query(cursor === void 0 ? {} : { cursor });
18696
- for (const row of page.records) out.push(row.data);
18697
- cursor = page.nextCursor ?? void 0;
18698
- } while (cursor !== void 0);
18699
- return out;
19216
+ /** Read the records once; every method awaits it. */
19217
+ ready() {
19218
+ this.loaded ??= this.store.load();
19219
+ return this.loaded;
18700
19220
  }
19221
+ ensureTag = async ({ name }) => {
19222
+ await this.ready();
19223
+ const clean = requireName(name, "a tag name");
19224
+ return this.store.ensure(clean, {}, require_named_entity_store.tagIdFromKey(require_tag.tagKey(clean)));
19225
+ };
19226
+ listTags = async () => {
19227
+ await this.ready();
19228
+ return [...this.store.list()];
19229
+ };
19230
+ updateTag = async ({ id, patch }) => {
19231
+ await this.ready();
19232
+ try {
19233
+ const before = this.store.get(id);
19234
+ const updated = await this.store.update(id, (current) => this.patched(current, patch));
19235
+ if (before !== null && before.name !== updated.name) await this.followRenameOnNamesOnlyOwners(before.name, updated.name);
19236
+ return updated;
19237
+ } catch (err) {
19238
+ if (err instanceof require_named_entity_store.EntityNotFoundError) throw require_camstack_error.userError("system.tag-not-found", void 0, `[tags] tag not found: ${id}`);
19239
+ if (err instanceof require_named_entity_store.EntityNameTakenError) throw require_camstack_error.userError("system.tag-name-taken", void 0, `[tags] ${err.message}`);
19240
+ throw err;
19241
+ }
19242
+ };
19243
+ deleteTag = async ({ id }) => {
19244
+ await this.ready();
19245
+ const tag = this.store.get(id);
19246
+ if (tag === null) return { updated: { ...zeroCounts() } };
19247
+ const updated = await this.clearFromOwners(tag, null);
19248
+ await this.store.delete(id);
19249
+ this.deps.logger.info("tag deleted", { meta: {
19250
+ id,
19251
+ name: tag.name,
19252
+ updated
19253
+ } });
19254
+ return { updated };
19255
+ };
18701
19256
  list = async () => {
18702
- const styles = new Map((await this.readStyles()).map((s) => [require_tag.tagKey(s.name), s]));
19257
+ await this.ready();
18703
19258
  const unreachable = /* @__PURE__ */ new Set();
18704
19259
  const read = [];
18705
19260
  for (const kind of OWNER_KINDS) try {
@@ -18714,56 +19269,89 @@ var TagsService = class {
18714
19269
  error: err instanceof Error ? err.message : String(err)
18715
19270
  } });
18716
19271
  }
18717
- const zero = () => ({ ...NO_UPDATES });
18718
19272
  const entries = /* @__PURE__ */ new Map();
18719
- for (const style of styles.values()) entries.set(require_tag.tagKey(style.name), {
18720
- name: style.name,
18721
- counts: zero()
19273
+ for (const tag of this.store.list()) entries.set(tag.id, {
19274
+ name: tag.name,
19275
+ styled: true,
19276
+ counts: zeroCounts(),
19277
+ record: tag
18722
19278
  });
19279
+ const byKey = new Map([...entries].map(([id, e]) => [require_tag.tagKey(e.name), id]));
18723
19280
  for (const { kind, records } of read) for (const record of records) {
18724
19281
  const seen = /* @__PURE__ */ new Set();
18725
- for (const tag of record.tags) {
18726
- const key = require_tag.tagKey(tag);
18727
- if (key.length === 0 || seen.has(key)) continue;
18728
- seen.add(key);
18729
- const entry = entries.get(key) ?? {
18730
- name: tag.trim(),
18731
- counts: zero()
19282
+ const touch = (entryId, name, record0) => {
19283
+ if (seen.has(entryId)) return;
19284
+ seen.add(entryId);
19285
+ const entry = entries.get(entryId) ?? {
19286
+ name,
19287
+ styled: false,
19288
+ counts: zeroCounts(),
19289
+ record: record0
18732
19290
  };
18733
19291
  entry.counts[kind] += 1;
18734
- entries.set(key, entry);
19292
+ entries.set(entryId, entry);
19293
+ };
19294
+ for (const id of record.tagIds) {
19295
+ const known = this.store.get(id);
19296
+ if (known !== null) touch(id, known.name, known);
19297
+ }
19298
+ if (record.tagIds.length === 0) for (const name of record.tags) {
19299
+ const key = require_tag.tagKey(name);
19300
+ if (key.length === 0) continue;
19301
+ const existing = byKey.get(key);
19302
+ if (existing === void 0) byKey.set(key, `name:${key}`);
19303
+ touch(existing ?? `name:${key}`, name.trim(), null);
18735
19304
  }
18736
19305
  }
18737
19306
  const out = [];
18738
- for (const [key, entry] of entries) {
18739
- const style = styles.get(key);
18740
- out.push({
18741
- name: entry.name,
18742
- color: style?.color ?? require_tag.defaultTagColorId(entry.name),
18743
- icon: style?.icon ?? "tag",
18744
- styled: style !== void 0,
18745
- counts: withUnknown(entry.counts, unreachable)
18746
- });
18747
- }
19307
+ for (const entry of entries.values()) out.push({
19308
+ name: entry.name,
19309
+ color: entry.record?.colour ?? require_tag.defaultTagColorId(entry.name),
19310
+ icon: entry.record?.icon ?? "tag",
19311
+ styled: entry.record?.colour !== void 0 || entry.record?.icon !== void 0,
19312
+ counts: withUnknown(entry.counts, unreachable)
19313
+ });
18748
19314
  return out.toSorted((a, b) => a.name.localeCompare(b.name));
18749
19315
  };
18750
19316
  setStyle = async ({ name, color, icon }) => {
18751
- const trimmed = requireName(name, "a tag name");
18752
- await this.deps.styles.put({
18753
- id: require_tag.tagKey(trimmed),
18754
- data: {
18755
- name: trimmed,
18756
- color,
19317
+ const tag = await this.ensureTag({ name });
19318
+ await this.updateTag({
19319
+ id: tag.id,
19320
+ patch: {
19321
+ colour: color,
18757
19322
  icon
18758
19323
  }
18759
19324
  });
18760
19325
  };
18761
19326
  rename = async ({ from, to }) => {
19327
+ await this.ready();
18762
19328
  const source = requireName(from, "the tag to rename");
18763
19329
  const target = requireName(to, "the new tag name");
18764
- const updated = await this.rewrite(source, (tags) => require_tag.renameInTags(tags, source, target));
18765
- await this.moveStyle(source, target);
18766
- this.deps.logger.info("tag renamed", { meta: {
19330
+ const sourceTag = this.store.findByName(source);
19331
+ if (sourceTag === null) {
19332
+ const updated = await this.renameNamesOnly(source, target);
19333
+ this.deps.logger.info("tag renamed (names only)", { meta: {
19334
+ from: source,
19335
+ to: target
19336
+ } });
19337
+ return { updated };
19338
+ }
19339
+ const targetTag = this.store.findByName(target);
19340
+ if (targetTag === null || targetTag.id === sourceTag.id) {
19341
+ await this.updateTag({
19342
+ id: sourceTag.id,
19343
+ patch: { name: target }
19344
+ });
19345
+ const updated = await this.countCarrying(sourceTag, target);
19346
+ this.deps.logger.info("tag renamed", { meta: {
19347
+ from: source,
19348
+ to: target
19349
+ } });
19350
+ return { updated };
19351
+ }
19352
+ const updated = await this.clearFromOwners(sourceTag, targetTag);
19353
+ await this.store.delete(sourceTag.id);
19354
+ this.deps.logger.info("tags merged", { meta: {
18767
19355
  from: source,
18768
19356
  to: target,
18769
19357
  updated
@@ -18771,90 +19359,139 @@ var TagsService = class {
18771
19359
  return { updated };
18772
19360
  };
18773
19361
  remove = async ({ name }) => {
19362
+ await this.ready();
18774
19363
  const target = requireName(name, "the tag to remove");
18775
- const updated = await this.rewrite(target, (tags) => require_tag.removeFromTags(tags, target));
18776
- await this.deps.styles.delete(require_tag.tagKey(target));
18777
- this.deps.logger.info("tag removed", { meta: {
18778
- name: target,
18779
- updated
18780
- } });
19364
+ const tag = this.store.findByName(target);
19365
+ if (tag === null) return { updated: await this.removeNamesOnly(target) };
19366
+ const { updated } = await this.deleteTag({ id: tag.id });
18781
19367
  return { updated };
18782
19368
  };
19369
+ patched(current, patch) {
19370
+ const next = { name: patch.name ?? current.name };
19371
+ const colour = applied(patch.colour, current.colour);
19372
+ const icon = applied(patch.icon, current.icon);
19373
+ const description = applied(patch.description, current.description);
19374
+ const order = applied(patch.order, current.order);
19375
+ if (colour !== void 0) next.colour = colour;
19376
+ if (icon !== void 0) next.icon = icon;
19377
+ if (description !== void 0) next.description = description;
19378
+ if (order !== void 0) next.order = order;
19379
+ return next;
19380
+ }
18783
19381
  /**
18784
- * Apply `change` to every record carrying `tag`, on every owner kind. A record
18785
- * that fails is logged and the rest are still attempted; the call then throws,
18786
- * and the style is NOT touched — the tag still names the failed records, so the
18787
- * operator repeats the same call (every step is idempotent).
19382
+ * Remove `tag` from every owner record that carries it, or — with `into` —
19383
+ * replace it with that tag. Every owner is READ first: one that cannot be
19384
+ * read refuses the whole call before anything is written.
18788
19385
  */
18789
- async rewrite(tag, change) {
18790
- const updated = { ...NO_UPDATES };
18791
- const failed = [];
19386
+ async clearFromOwners(tag, into) {
18792
19387
  const plan = [];
18793
- for (const kind of OWNER_KINDS) for (const record of await this.readOwnerOrRefuse(kind, tag)) {
18794
- const next = change(record.tags);
18795
- if (next === null) continue;
18796
- if (next.length > 20) throw new Error(`[tags] "${tag}" cannot be applied: ${kind}:${record.id} would carry ${next.length} tags (max 20); nothing was written`);
18797
- plan.push({
19388
+ for (const kind of OWNER_KINDS) {
19389
+ let records;
19390
+ try {
19391
+ records = await this.deps.owners[kind].list();
19392
+ } catch (err) {
19393
+ throw new TagOwnerUnreachableError(kind, tag.name, err);
19394
+ }
19395
+ for (const record of records) if (carries(record, tag)) plan.push({
18798
19396
  kind,
18799
- id: record.id,
18800
- next
19397
+ record
18801
19398
  });
18802
19399
  }
18803
- for (const { kind, id, next } of plan) try {
18804
- await this.deps.owners[kind].setTags(id, next);
19400
+ const updated = zeroCounts();
19401
+ const failed = [];
19402
+ for (const { kind, record } of plan) try {
19403
+ await this.rewriteRecord(kind, record, tag, into);
18805
19404
  updated[kind] += 1;
18806
19405
  } catch (err) {
18807
- failed.push(`${kind}:${id}`);
18808
- const deviceId = kind === "devices" ? Number(id) : void 0;
19406
+ failed.push(`${kind}:${record.id}`);
19407
+ const deviceId = kind === "devices" ? Number(record.id) : void 0;
18809
19408
  this.deps.logger.error("tag rewrite failed for one record — the rest were still attempted", {
18810
19409
  ...deviceId === void 0 || !Number.isFinite(deviceId) ? {} : { tags: { deviceId } },
18811
19410
  meta: {
18812
- tag,
19411
+ tag: tag.name,
18813
19412
  kind,
18814
- recordId: id,
19413
+ recordId: record.id,
18815
19414
  error: err instanceof Error ? err.message : String(err)
18816
19415
  }
18817
19416
  });
18818
19417
  }
18819
- if (failed.length > 0) throw new Error(`[tags] "${tag}" was not rewritten on ${failed.length} record(s) (${failed.slice(0, 5).join(", ")}); the style was left alone — repeat the call`);
19418
+ if (failed.length > 0) throw new Error(`[tags] "${tag.name}" was not cleared on ${failed.length} record(s) (${failed.slice(0, 5).join(", ")}); the tag was left alone — repeat the call`);
18820
19419
  return updated;
18821
19420
  }
19421
+ async rewriteRecord(kind, record, tag, into) {
19422
+ const port = this.deps.owners[kind];
19423
+ const names = into === null ? require_tag.removeFromTags(record.tags, tag.name) : require_tag.renameInTags(record.tags, tag.name, into.name);
19424
+ if (port.storage === "names") {
19425
+ if (names !== null) await port.setTags(record.id, names);
19426
+ return;
19427
+ }
19428
+ const withoutTag = record.tagIds.filter((id) => id !== tag.id);
19429
+ const ids = into === null || withoutTag.includes(into.id) ? withoutTag : [...withoutTag, into.id];
19430
+ const nextIds = record.tagIds.length === 0 && into !== null ? [into.id] : ids;
19431
+ if (port.setTagsAndIds !== void 0) {
19432
+ await port.setTagsAndIds(record.id, [...names ?? record.tags], nextIds);
19433
+ return;
19434
+ }
19435
+ await port.setTagIds(record.id, nextIds);
19436
+ if (names !== null) await port.setTags(record.id, names);
19437
+ }
19438
+ /** How many records carry `tag` (by id or kept name) — the shim's `updated`; an unreadable owner counts 0. */
19439
+ async countCarrying(tag, newName) {
19440
+ const counts = zeroCounts();
19441
+ for (const kind of OWNER_KINDS) try {
19442
+ for (const record of await this.deps.owners[kind].list()) if (carries(record, tag) || carries(record, {
19443
+ id: tag.id,
19444
+ name: newName
19445
+ })) counts[kind] += 1;
19446
+ } catch {}
19447
+ return counts;
19448
+ }
18822
19449
  /**
18823
- * An owner's records for a rewrite. One that cannot be read refuses the whole
18824
- * call BEFORE anything is written: a rename applied to only some owners would
18825
- * leave the fleet split across two spellings.
19450
+ * A safety net for a record that still holds text only (an owner, or a node whose
19451
+ * notification center has not run its tag-ids step yet): the tag record was renamed once, so
19452
+ * the names such a record keeps are moved here, or it would keep naming a tag nothing
19453
+ * carries any more.
19454
+ * An owner that cannot be read is logged and skipped, never the cause of a failed rename.
18826
19455
  */
18827
- async readOwnerOrRefuse(kind, tag) {
18828
- try {
18829
- return await this.deps.owners[kind].list();
18830
- } catch (err) {
18831
- throw new TagOwnerUnreachableError(kind, tag, err);
18832
- }
18833
- }
18834
- /** The style follows the tag; a merge onto a styled target keeps the TARGET's style. */
18835
- async moveStyle(from, to) {
18836
- const fromKey = require_tag.tagKey(from);
18837
- const toKey = require_tag.tagKey(to);
18838
- const fromStyle = await this.deps.styles.get(fromKey);
18839
- if (fromKey === toKey) {
18840
- if (fromStyle !== null) await this.deps.styles.put({
18841
- id: toKey,
18842
- data: {
18843
- ...fromStyle.data,
18844
- name: to
19456
+ async followRenameOnNamesOnlyOwners(from, to) {
19457
+ for (const kind of OWNER_KINDS) {
19458
+ const port = this.deps.owners[kind];
19459
+ try {
19460
+ for (const record of await port.list()) {
19461
+ if (port.storage === "ids" && record.tagIds.length > 0) continue;
19462
+ const next = require_tag.renameInTags(record.tags, from, to);
19463
+ if (next !== null) await port.setTags(record.id, next);
18845
19464
  }
18846
- });
18847
- return;
18848
- }
18849
- if (fromStyle === null) return;
18850
- if (await this.deps.styles.get(toKey) === null) await this.deps.styles.put({
18851
- id: toKey,
18852
- data: {
18853
- ...fromStyle.data,
18854
- name: to
19465
+ } catch (err) {
19466
+ this.deps.logger.warn("tag renamed, but a names-only owner could not follow", { meta: {
19467
+ owner: kind,
19468
+ from,
19469
+ to,
19470
+ error: err instanceof Error ? err.message : String(err)
19471
+ } });
18855
19472
  }
18856
- });
18857
- await this.deps.styles.delete(fromKey);
19473
+ }
19474
+ }
19475
+ /** Names-only tags: a name on owners that have no record for it (a pre-migration state). */
19476
+ async renameNamesOnly(from, to) {
19477
+ const updated = zeroCounts();
19478
+ for (const kind of OWNER_KINDS) for (const record of await this.deps.owners[kind].list()) {
19479
+ const next = require_tag.renameInTags(record.tags, from, to);
19480
+ if (next === null) continue;
19481
+ await this.deps.owners[kind].setTags(record.id, next);
19482
+ updated[kind] += 1;
19483
+ }
19484
+ return updated;
19485
+ }
19486
+ async removeNamesOnly(name) {
19487
+ const updated = zeroCounts();
19488
+ for (const kind of OWNER_KINDS) for (const record of await this.deps.owners[kind].list()) {
19489
+ const next = require_tag.removeFromTags(record.tags, name);
19490
+ if (next === null) continue;
19491
+ await this.deps.owners[kind].setTags(record.id, next);
19492
+ updated[kind] += 1;
19493
+ }
19494
+ return updated;
18858
19495
  }
18859
19496
  };
18860
19497
  //#endregion
@@ -18866,35 +19503,47 @@ var TagsService = class {
18866
19503
  */
18867
19504
  function coreBlocksPort(blocks) {
18868
19505
  return {
19506
+ storage: "ids",
18869
19507
  list: async () => blocks().list().map((b) => ({
18870
19508
  id: b.id,
18871
- tags: b.tags ?? []
19509
+ tags: b.tags ?? [],
19510
+ tagIds: b.tagIds ?? []
18872
19511
  })),
18873
19512
  setTags: async (id, tags) => {
18874
19513
  await blocks().setTags(id, tags);
19514
+ },
19515
+ setTagIds: async (id, tagIds) => {
19516
+ await blocks().setTagIds(id, tagIds);
18875
19517
  }
18876
19518
  };
18877
19519
  }
18878
19520
  function schedulersPort(store) {
18879
19521
  return {
19522
+ storage: "ids",
18880
19523
  list: async () => (await store.list()).map((s) => ({
18881
19524
  id: s.id,
18882
- tags: s.tags ?? []
19525
+ tags: s.tags ?? [],
19526
+ tagIds: s.tagIds ?? []
18883
19527
  })),
18884
- setTags: (id, tags) => store.setTags(id, tags)
19528
+ setTags: (id, tags) => store.setTags(id, tags),
19529
+ setTagIds: (id, tagIds) => store.setTagIds(id, tagIds)
18885
19530
  };
18886
19531
  }
18887
19532
  function actionsPort(store) {
18888
19533
  return {
19534
+ storage: "ids",
18889
19535
  list: async () => (await store.list()).map((a) => ({
18890
19536
  id: a.id,
18891
- tags: a.tags ?? []
19537
+ tags: a.tags ?? [],
19538
+ tagIds: a.tagIds ?? []
18892
19539
  })),
18893
- setTags: (id, tags) => store.setTags(id, tags)
19540
+ setTags: (id, tags) => store.setTags(id, tags),
19541
+ setTagIds: (id, tagIds) => store.setTagIds(id, tagIds)
18894
19542
  };
18895
19543
  }
18896
19544
  function templatesPort(templates) {
18897
19545
  return {
19546
+ storage: "ids",
18898
19547
  list: async () => {
18899
19548
  const out = [];
18900
19549
  let cursor;
@@ -18902,7 +19551,8 @@ function templatesPort(templates) {
18902
19551
  const page = await templates.query(cursor === void 0 ? {} : { cursor });
18903
19552
  for (const row of page.records) out.push({
18904
19553
  id: row.id,
18905
- tags: row.data.tags ?? []
19554
+ tags: row.data.tags ?? [],
19555
+ tagIds: row.data.tagIds ?? []
18906
19556
  });
18907
19557
  cursor = page.nextCursor ?? void 0;
18908
19558
  } while (cursor !== void 0);
@@ -18920,6 +19570,19 @@ function templatesPort(templates) {
18920
19570
  tags: normalized
18921
19571
  }
18922
19572
  });
19573
+ },
19574
+ setTagIds: async (id, tagIds) => {
19575
+ const row = await templates.get(id);
19576
+ if (row === null) throw new Error(`no template "${id}"`);
19577
+ const { tagIds: _previous, ...rest } = row.data;
19578
+ const unique = [...new Set(tagIds)];
19579
+ await templates.put({
19580
+ id,
19581
+ data: unique.length === 0 ? rest : {
19582
+ ...rest,
19583
+ tagIds: unique
19584
+ }
19585
+ });
18923
19586
  }
18924
19587
  };
18925
19588
  }
@@ -18930,10 +19593,12 @@ function devicesPort(api) {
18930
19593
  return current;
18931
19594
  };
18932
19595
  return {
19596
+ storage: "ids",
18933
19597
  list: async () => {
18934
19598
  return (await need().deviceManager.listAll.query({ projection: "slim" })).map((d) => ({
18935
19599
  id: String(d.id),
18936
- tags: d.tags ?? []
19600
+ tags: d.tags ?? [],
19601
+ tagIds: d.tagIds ?? []
18937
19602
  }));
18938
19603
  },
18939
19604
  setTags: async (id, tags) => {
@@ -18941,6 +19606,12 @@ function devicesPort(api) {
18941
19606
  deviceId: Number(id),
18942
19607
  tags
18943
19608
  });
19609
+ },
19610
+ setTagIds: async (id, tagIds) => {
19611
+ await need().deviceManager.setTags.mutate({
19612
+ deviceId: Number(id),
19613
+ tagIds
19614
+ });
18944
19615
  }
18945
19616
  };
18946
19617
  }
@@ -18967,22 +19638,30 @@ function parseRuleTagOwnerId(id) {
18967
19638
  };
18968
19639
  }
18969
19640
  function notificationRulesPort(api) {
19641
+ const entries = async () => (await needApi(api).notificationRules.listRuleTags.query({})).rules.map((r) => ({
19642
+ id: ruleTagOwnerId(r.kind, r.ruleId),
19643
+ tags: r.tags,
19644
+ tagIds: r.tagIds
19645
+ }));
19646
+ const write = async (id, tags, tagIds) => {
19647
+ const { kind, ruleId } = parseRuleTagOwnerId(id);
19648
+ await needApi(api).notificationRules.setRuleTags.mutate({
19649
+ kind,
19650
+ ruleId,
19651
+ tags,
19652
+ ...tagIds === void 0 ? {} : { tagIds }
19653
+ });
19654
+ };
18970
19655
  return {
18971
- list: async () => {
18972
- const { rules } = await needApi(api).notificationRules.listRuleTags.query({});
18973
- return rules.map((r) => ({
18974
- id: ruleTagOwnerId(r.kind, r.ruleId),
18975
- tags: r.tags
18976
- }));
19656
+ storage: "ids",
19657
+ list: entries,
19658
+ setTagIds: async (id, tagIds) => {
19659
+ const current = (await entries()).find((entry) => entry.id === id);
19660
+ if (current === void 0) throw new Error(`[tags] notification rule not found: ${id}`);
19661
+ await write(id, [...current.tags], tagIds);
18977
19662
  },
18978
- setTags: async (id, tags) => {
18979
- const { kind, ruleId } = parseRuleTagOwnerId(id);
18980
- await needApi(api).notificationRules.setRuleTags.mutate({
18981
- kind,
18982
- ruleId,
18983
- tags
18984
- });
18985
- }
19663
+ setTagsAndIds: (id, tags, tagIds) => write(id, tags, tagIds),
19664
+ setTags: (id, tags) => write(id, tags, void 0)
18986
19665
  };
18987
19666
  }
18988
19667
  function buildTagsService(deps) {
@@ -19002,7 +19681,7 @@ function buildTagsService(deps) {
19002
19681
  devices: deps.devices ?? devicesPort(deps.api),
19003
19682
  notificationRules: deps.notificationRules ?? notificationRulesPort(deps.api)
19004
19683
  },
19005
- styles: records.kind(coreBlocksRecordKinds["tag-styles"]),
19684
+ tags: records.kind(coreBlocksRecordKinds.tags),
19006
19685
  logger: deps.logger
19007
19686
  });
19008
19687
  }
@@ -19129,7 +19808,23 @@ var CoreBlocksAddon = class extends require_base_addon.BaseAddon {
19129
19808
  await records.declare(coreBlocksRecordKinds);
19130
19809
  await records.declare(blocksInstanceRecordKinds);
19131
19810
  this.blocksInstances = buildBlocksInstances(records);
19811
+ const migrationLogger = this.ctx.logger.child("migrations");
19812
+ const tagIdsPorts = tagIdsPortsOver({
19813
+ blocks: records.kind(coreBlocksRecordKinds.blocks),
19814
+ schedulers: records.kind(coreBlocksRecordKinds.schedulers),
19815
+ templates: records.kind(coreBlocksRecordKinds.templates),
19816
+ actions: records.kind(coreBlocksRecordKinds.actions)
19817
+ }, migrationLogger);
19818
+ const api = () => this.ctx.api;
19132
19819
  await this.runMigrations(require_base_addon.defineAddonMigrations(ADDON_MIGRATIONS, {
19820
+ ...tagIdsPorts,
19821
+ ...tagsAsRecordsPortsOver({
19822
+ tagIds: tagIdsPorts,
19823
+ external: async () => [...await devicesPort(api).list(), ...await notificationRulesPort(api).list()].flatMap((owner) => owner.tags),
19824
+ styles: records.kind(coreBlocksRecordKinds["tag-styles"]),
19825
+ tags: records.kind(coreBlocksRecordKinds.tags),
19826
+ logger: migrationLogger
19827
+ }),
19133
19828
  ...coreBlocksMigrationPorts(records.kind(coreBlocksRecordKinds.blocks), this.ctx.logger.child("migrations"), () => Date.now()),
19134
19829
  ...remoteMigrationPortsOver(this.ctx.settings ?? NO_DEVICE_STORES, records.kind(coreBlocksRecordKinds.templates), this.ctx.logger.child("migrations"))
19135
19830
  }));