command_tower 0.23.0 → 0.24.0

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 (74) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/command_tower/admin/home_notices_controller.rb +39 -0
  3. data/app/controllers/command_tower/me/home_notices_controller.rb +79 -0
  4. data/app/deserializers/command_tower/deserializers/admin/home_notices/control_deserializer.rb +40 -0
  5. data/app/deserializers/command_tower/deserializers/home_notices/notice_id_deserializer.rb +42 -0
  6. data/app/errors/command_tower/errors/home_notices/linked_message_unavailable_error.rb +23 -0
  7. data/app/errors/command_tower/errors/home_notices/rate_limit_error.rb +25 -0
  8. data/app/errors/command_tower/errors/home_notices/unavailable_error.rb +22 -0
  9. data/app/jobs/command_tower/home_notices/prune_ended_job.rb +14 -0
  10. data/app/models/command_tower/home_notice.rb +41 -0
  11. data/app/models/command_tower/home_notice_control.rb +12 -0
  12. data/app/serializers/command_tower/serializers/home_notices/control_serializer.rb +14 -0
  13. data/app/serializers/command_tower/serializers/home_notices/dismissal_serializer.rb +19 -0
  14. data/app/serializers/command_tower/serializers/home_notices/mutation_serializer.rb +16 -0
  15. data/app/serializers/command_tower/serializers/home_notices/notice_serializer.rb +35 -0
  16. data/app/serializers/command_tower/serializers/home_notices/selection_serializer.rb +21 -0
  17. data/app/services/command_tower/home_notices/campaign.rb +28 -0
  18. data/app/services/command_tower/home_notices/campaigns/update_app.rb +77 -0
  19. data/app/services/command_tower/home_notices/catalog/validator.rb +92 -0
  20. data/app/services/command_tower/home_notices/catalog.rb +92 -0
  21. data/app/services/command_tower/home_notices/context.rb +10 -0
  22. data/app/services/command_tower/home_notices/delivery.rb +43 -0
  23. data/app/services/command_tower/home_notices/notice.rb +88 -0
  24. data/app/services/command_tower/home_notices/notice_record.rb +28 -0
  25. data/app/services/command_tower/messaging/contract/inbox.rb +29 -0
  26. data/app/services/command_tower/messaging/contract/requests/document_for_communication.rb +24 -0
  27. data/app/services/command_tower/messaging/contract/results/inbox_document.rb +17 -0
  28. data/app/services/command_tower/services/auth/purge_user_associated_data.rb +6 -0
  29. data/app/services/command_tower/services/home_notices/acknowledge.rb +149 -0
  30. data/app/services/command_tower/services/home_notices/check_mutation_eligibility.rb +84 -0
  31. data/app/services/command_tower/services/home_notices/check_rate_limit.rb +52 -0
  32. data/app/services/command_tower/services/home_notices/compose.rb +113 -0
  33. data/app/services/command_tower/services/home_notices/deliver.rb +111 -0
  34. data/app/services/command_tower/services/home_notices/dismiss.rb +147 -0
  35. data/app/services/command_tower/services/home_notices/load_candidates.rb +85 -0
  36. data/app/services/command_tower/services/home_notices/pick_notices.rb +139 -0
  37. data/app/services/command_tower/services/home_notices/prune_ended.rb +93 -0
  38. data/app/services/command_tower/services/home_notices/read_controls.rb +31 -0
  39. data/app/services/command_tower/services/home_notices/record_impression.rb +154 -0
  40. data/app/services/command_tower/services/home_notices/resolve_notice.rb +69 -0
  41. data/app/services/command_tower/services/home_notices/select.rb +136 -0
  42. data/app/services/command_tower/services/home_notices/update_control.rb +56 -0
  43. data/app/workflows/command_tower/workflows/admin/home_notices/update_control_workflow.rb +64 -0
  44. data/app/workflows/command_tower/workflows/home_notices/acknowledge_workflow.rb +140 -0
  45. data/app/workflows/command_tower/workflows/home_notices/dismiss_workflow.rb +107 -0
  46. data/app/workflows/command_tower/workflows/home_notices/prune_ended_workflow.rb +25 -0
  47. data/app/workflows/command_tower/workflows/home_notices/record_impression_workflow.rb +92 -0
  48. data/app/workflows/command_tower/workflows/home_notices/show_workflow.rb +44 -0
  49. data/config/routes.rb +9 -0
  50. data/db/migrate/20261124200001_create_command_tower_home_notices.rb +43 -0
  51. data/db/migrate/20261124200002_create_command_tower_home_notice_controls.rb +12 -0
  52. data/docs/api_reference.md +108 -1
  53. data/docs/audit.md +12 -0
  54. data/docs/bootstrap/08-initializer.md +15 -0
  55. data/docs/bootstrap/09-rbac.md +6 -0
  56. data/docs/bootstrap/13-optional.md +12 -0
  57. data/docs/extending.md +2 -0
  58. data/docs/home_notices.md +236 -0
  59. data/docs/messaging_integration_guide.md +4 -0
  60. data/docs/models.md +4 -0
  61. data/docs/principal_capabilities.md +1 -0
  62. data/docs/ui.md +13 -0
  63. data/docs/upgrades/0.24.0.md +50 -0
  64. data/lib/command_tower/authorization/default.yml +10 -0
  65. data/lib/command_tower/configuration/config.rb +6 -0
  66. data/lib/command_tower/configuration/home_notices/config.rb +67 -0
  67. data/lib/command_tower/configuration/registry/audit/config.rb +61 -0
  68. data/lib/command_tower/configuration/registry/principal_capabilities/config.rb +1 -1
  69. data/lib/command_tower/engine.rb +1 -0
  70. data/lib/command_tower/install/baseline.rb +2 -0
  71. data/lib/command_tower/ui/document.rb +26 -5
  72. data/lib/command_tower/version.rb +1 -1
  73. data/lib/tasks/home_notices.rake +11 -0
  74. metadata +53 -2
@@ -0,0 +1,236 @@
1
+ # Home Notices
2
+
3
+ Home Notices let a host show a notice to a signed-in user on the home surface. The host declares each notice as a class. The platform owns pacing, windows, selection and audit. This page covers **authoring** and the boot checks. Selection is covered below. Later behavior (endpoints, delivery, kill switch) is added here as it ships.
4
+
5
+ Home Notices are off by default. With `config.home_notices.enabled = false` the catalog is not loaded.
6
+
7
+ ## Two kinds
8
+
9
+ | Kind | Base class | Use it for | Source of truth |
10
+ |---|---|---|---|
11
+ | Campaign | `CommandTower::HomeNotices::Campaign` | A notice the host derives from application state ("make your picks") | The host's `show?` and `period_key`; the platform materializes one row per user per period |
12
+ | Delivery | `CommandTower::HomeNotices::Delivery` | A notice a host workflow pushes to one user ("class canceled") | A persisted row per user |
13
+
14
+ Subclass `Campaign` or `Delivery`. Never subclass `Notice` directly. Macros that belong to one kind are rejected on the other at boot.
15
+
16
+ ## Macros
17
+
18
+ Macros set a value when given an argument and read it when called bare. Subclasses inherit them.
19
+
20
+ | Macro | Kind | Meaning |
21
+ |---|---|---|
22
+ | `key "host.name"` | both | Required, unique. Lowercase letters, digits and `_`, with at least one `.`. The `ct.` prefix is reserved for the platform |
23
+ | `severity :blocking` or `:dismissible` | both | Required |
24
+ | `priority 50` | both | Required Integer; higher wins |
25
+ | `blocking_reason "..."` | both | Required for `:blocking`, at least 20 characters. Records why the notice may interrupt the user |
26
+ | `window starts_at:, ends_at:` | both | Optional absolute UTC window. Either bound may be nil. `starts_at` must be before `ends_at` |
27
+ | `impressions max:, cooldown:` | Campaign | Pacing. Required for a dismissible campaign |
28
+ | `period_key { \|user:, context:\| ... }` | Campaign | Identity of the current period. Impressions and acknowledgement reset when it changes |
29
+ | `composer :message` | Delivery | Links the delivery to a Messaging communication. A linked delivery needs no `show?` or `compose` |
30
+
31
+ ## Instance methods
32
+
33
+ ```ruby
34
+ def show?(user:, context:, notice:) # whether the notice applies now; no network I/O
35
+ def compose(builder, user:, context:, notice:) # builds the content on the document builder
36
+ ```
37
+
38
+ - `notice` is a read-only `NoticeRecord`, or `nil` for a campaign that has no row yet.
39
+ - `context` is a `CommandTower::HomeNotices::Context` with `now`, `time_zone`, `app_version`, `platform`, `ui_catalog`, `client_compatibility` and `impersonating`.
40
+ - Both methods must be pure. The class holds no per-user state.
41
+
42
+ ## Example
43
+
44
+ ```ruby
45
+ class MakeYourPicks < CommandTower::HomeNotices::Campaign
46
+ key "pickem.make_your_picks"
47
+ severity :dismissible
48
+ priority 50
49
+ impressions max: 4, cooldown: 12.hours
50
+
51
+ def show?(user:, context:, notice:)
52
+ PicksOpen.for(user:)
53
+ end
54
+
55
+ def compose(builder, user:, context:, notice:)
56
+ # build content on the builder
57
+ end
58
+ end
59
+ ```
60
+
61
+ Working samples (fictional values) live in the engine's dummy app: `rails_app/app/messages/studio_tips_notice.rb` (dismissible campaign), `terms_update_notice.rb` (blocking campaign with `period_key`) and `class_canceled_notice.rb` (blocking delivery).
62
+
63
+ ## Registering notices
64
+
65
+ ```ruby
66
+ CommandTower.configure do |config|
67
+ config.home_notices.enabled = true
68
+ config.home_notices.notices = %w[MakeYourPicks]
69
+ end
70
+ ```
71
+
72
+ Class names are Strings so reloading works. Config options are listed in [`bootstrap/08-initializer.md`](bootstrap/08-initializer.md).
73
+
74
+ ## Boot checks
75
+
76
+ When `enabled`, the engine's `to_prepare` runs `CommandTower::HomeNotices::Catalog.load!`. The first problem raises `Catalog::InvalidNoticeError` in every environment. The checks:
77
+
78
+ - Each name constantizes and subclasses `Campaign` or `Delivery`.
79
+ - `key` is present, matches the format, does not use `ct.`, and is unique.
80
+ - `severity` and `priority` are present.
81
+ - A blocking notice has a `blocking_reason` of at least 20 characters.
82
+ - A dismissible campaign declares `impressions`.
83
+ - `composer` is used only on a Delivery; `impressions` and `period_key` only on a Campaign.
84
+ - `show?` is overridden. A linked delivery (`composer :message`) counts as overriding it.
85
+ - `compose` is overridden, unless the delivery is linked.
86
+ - `window` has `starts_at` before `ends_at`.
87
+
88
+ `global_cooldown` below 1 hour also fails at boot.
89
+
90
+ ## Selection
91
+
92
+ `CommandTower::Services::HomeNotices::Select` chooses at most one blocking and one dismissible notice for a user and request. Every time rule uses `context.now`. Success data is `{ candidates:, controls_available:, blocking:, dismissible: }`.
93
+
94
+ 1. **Load.** `LoadCandidates` gathers the user's open deliveries (unacknowledged, not ended, oldest first, at most `max_open_deliveries`, registered Delivery keys only) and every registered campaign with its current-period row, or no row yet. A campaign whose `period_key` block raises is skipped and `period_key_failed` is published.
95
+ 2. **Drop.** A candidate is dropped when it is killed, outside its window, acknowledged, dismissed into the future (`dismissed_until > now`), or (campaigns only) at its period impression `max` or inside its item `cooldown` (`last_shown_at + cooldown > now`). The kill switch reads `command_tower_home_notice_controls`; an absent row means enabled. Windows apply to the class `window` and to the row's own `starts_at` / `ends_at`; `starts_at` is inclusive and `ends_at` exclusive. Deliveries have no item pacing.
96
+ 3. **Order.** Highest `priority` first, ties to the oldest row (`created_at`). A campaign with no row counts as newest.
97
+ 4. **Pick.** `PickNotices` makes one pass per severity. Nothing is picked when `context.ui_catalog` is below 2. Otherwise the first candidate that passes its gate, then `show?`, then `compose` wins; a notice whose compose fails is skipped.
98
+ - **Blocking daily cap.** A notice already started (`first_shown_at` set) is always re-served until acknowledged. A new one needs fewer than `blocking_daily_cap` of the user's blocking rows first shown in the current UTC day.
99
+ - **Dismissible global cooldown.** Clear when the latest `last_shown_at` over the user's dismissible rows plus `global_cooldown` is at or before `now`. A delivery also passes when its `ends_at` is at or before the moment the cooldown clears. Blocking impressions do not start the cooldown.
100
+ - **`show?` budget.** `show?` has 50 ms. An overrun publishes `show_if_slow` and the answer is still used. An exception means "not shown" and publishes `show_if_failed`.
101
+
102
+ ### Failure behavior
103
+
104
+ If the controls cannot be read, selection fails closed: no candidates, no picks, `controls_available: false`, and `controls_unavailable` is published (user id and error class).
105
+
106
+ ### Events
107
+
108
+ All are in category `home_notices`. Payloads carry ids, keys, counts and error classes, never document content.
109
+
110
+ | Event | When |
111
+ |---|---|
112
+ | `selected` | Selection finished: user id, candidate count, picked blocking and dismissible keys |
113
+ | `controls_unavailable` | The controls read failed |
114
+ | `period_key_failed` | A campaign `period_key` block raised |
115
+ | `show_if_slow` | `show?` took longer than 50 ms |
116
+ | `show_if_failed` | `show?` raised |
117
+ | `delivery_over_cap` | `Deliver` ignored a delivery over `max_open_deliveries` (key only) |
118
+ | `linked_mark_failed` | Acknowledge could not mark the linked inbox item viewed (ids, error class) |
119
+
120
+ ### Cap overshoot
121
+
122
+ The blocking daily cap is not transactional. Selection counts rows before any impression is recorded, so concurrent requests can each start a different blocking notice before either impression lands. The cap can be exceeded by one per concurrent request. This is accepted (design D5): re-serving a started notice is always allowed, and the next request sees the new rows and holds the cap.
123
+
124
+ ## Deliver
125
+
126
+ `CommandTower::Services::HomeNotices::Deliver` pushes one `Delivery` notice to one user. A host workflow calls it directly, usually right after `Produce`.
127
+
128
+ | Input | Meaning |
129
+ |---|---|
130
+ | `user`, `notice` | The recipient and the `Delivery` subclass (anything else fails validation) |
131
+ | `identity` | The caller's stable key for this occurrence |
132
+ | `communication_id` | Required for a linked delivery (`composer :message`) |
133
+ | `starts_at`, `ends_at`, `metadata` | Optional window and a Hash of ids and small values |
134
+
135
+ - **Idempotent** on `(user, identity)`: a repeat returns the existing row and writes nothing.
136
+ - **Cap.** Over `max_open_deliveries` open rows the delivery is ignored and `delivery_over_cap` is published (key only).
137
+ - **Linked delivery.** The row is refused with `linked_message_unavailable` when the inbox item is missing, deleted, foreign or undefined, checked through `Messaging::Contract::Inbox.document_for_communication` ([Messaging guide](messaging_integration_guide.md)). No row is written.
138
+ - Success data is `{ delivered:, public_id: }`. `delivered` is true only when this call wrote the row; `public_id` is nil when ignored over the cap.
139
+
140
+ ### Linked deliveries
141
+
142
+ A delivery with `composer :message` needs no `show?` or `compose`:
143
+
144
+ - **Document.** `Compose` takes the inbox item's own document from `document_for_communication` instead of calling `compose`. It is redacted and validated like any other notice. A missing, deleted, archived, foreign or undefined item yields no document, so the notice is not shown.
145
+ - **Shown while unviewed.** The `Delivery#show?` default is true while `viewed_for_communication?` is false, and false when it is true (viewed) or nil (unavailable). Hosts may override `show?` and call `super`. An unlinked delivery must override `show?`.
146
+ - **Acknowledge marks viewed.** After the acknowledge commits (also on an idempotent repeat), the workflow calls `mark_viewed_for_communication`. This is best effort: a failure publishes `linked_mark_failed` (ids and error class) and never fails the acknowledgement.
147
+
148
+ Sample: `rails_app/app/messages/class_canceled_notice.rb`.
149
+
150
+ ## HTTP
151
+
152
+ `GET /me/home-notices` (engine-relative; hosts mounting at `/api` use `GET /api/me/home-notices`). Full contract: [API reference](api_reference.md#get-mehome-notices).
153
+
154
+ - Routed only when `config.home_notices.enabled` is true; otherwise **404**.
155
+ - RBAC entity `me_home_notices` (`Me::HomeNoticesController`). Not part of `member`; hosts grant it explicitly. RBAC fails closed, so a user without the grant gets **403**.
156
+ - Response `data`: `{ blocking, dismissible, readOnly }`. Each notice is `null` or a serialized document. `readOnly` is true while impersonating, or when impersonation state is unknown. An impersonated response redacts the documents.
157
+ - A client below UI catalog 2 (`X-UI-Catalog`) gets both notices `null`.
158
+ - Always sends `Cache-Control: no-store`.
159
+ - Rate limit: `config.home_notices.rate_limit_per_minute` (30) per user. The 31st call in a minute returns **429** `home_notices_rate_limited`. A limiter failure fails open (200) and publishes `rate_limiter_unavailable`.
160
+
161
+ ## Kill switch runbook
162
+
163
+ Use the kill switch to stop one notice key everywhere without a deploy. A key with no control row is enabled; the first change creates the row.
164
+
165
+ ```
166
+ PATCH /admin/home-notices/<key> (add the /api prefix on a host that mounts there)
167
+ { "enabled": false }
168
+ ```
169
+
170
+ - `<key>` is the notice key (`[a-z0-9_]` segments joined by dots, at most 128 characters). It must be a registered notice in the loaded catalog; an unknown key is **404** and nothing is written.
171
+ - Send a strict boolean `enabled`. `false` kills the key; `true` restores it.
172
+ - Effect: the next `GET /me/home-notices` drops the key, and impression, acknowledge and dismiss for it return 404. No restart is needed. Rows already persisted are kept, so re-enabling resumes pacing where it left off.
173
+ - Needs the `admin_home_notices_kill` grant. RBAC fails closed: at least one host role must grant the entity, or every caller gets `403`, owner included. Once a host role grants it, `owner` (`entities: true`) passes; every other role needs the explicit grant too (see [Bootstrap RBAC](bootstrap/09-rbac.md); the dummy app's `home_notices_operator` is an example). It is not a principal capability, so no client gates on it. The call is refused while impersonating.
174
+ - Repeating the current state is a **200** no-op and is not audited. A change emits `home_notice_control_changed` ([Audit](audit.md)).
175
+ - Contract: [API reference](api_reference.md#patch-adminhome-noticeskey).
176
+ - If the controls cannot be read or written, the platform fails closed: selection returns no notices and mutations return **503** `home_notices_unavailable`.
177
+
178
+ ## Local verification
179
+
180
+ Verify against the dummy app with `curl`. Tokens go in **header files** under `rails_app/tmp/lane-auth/` (gitignored through `/rails_app/tmp/`) and are passed with `curl -H @file`. A token never appears on a command line or in a log. Do not `cat` or print these files.
181
+
182
+ 1. Write the mint script to `rails_app/tmp/lane-auth/mint.rb`. It creates (or reuses) three users and writes one header file each:
183
+
184
+ ```ruby
185
+ dir = Rails.root.join("tmp/lane-auth")
186
+ FileUtils.mkdir_p(dir)
187
+
188
+ def lane_user(email, username, roles)
189
+ User.find_by(email:) || User.create!(
190
+ email:, username:, first_name: "Lane", last_name: username.capitalize,
191
+ password: SecureRandom.hex(16), email_validated: true, roles:
192
+ )
193
+ end
194
+
195
+ def write_header(dir, name, token)
196
+ path = dir.join(name)
197
+ File.write(path, "Authorization: Bearer #{token}\n")
198
+ File.chmod(0o600, path)
199
+ end
200
+
201
+ owner = lane_user("lane-owner@example.com", "laneowner", ["owner"])
202
+ nogrant = lane_user("lane-nogrant@example.com", "lanenogrant", [])
203
+ target = lane_user("lane-target@example.com", "lanetarget", ["home_notices_reader"])
204
+
205
+ write_header(dir, "owner.header", CommandTower::Jwt::LoginCreate.call(user: owner).token)
206
+ write_header(dir, "nogrant.header", CommandTower::Jwt::LoginCreate.call(user: nogrant).token)
207
+
208
+ session = CommandTower::Services::Impersonation::Create.call(actor: owner, target:).data[:session]
209
+ write_header(dir, "impersonation.header",
210
+ CommandTower::Jwt::LoginCreate.call(user: owner, impersonation_session_id: session.id).token)
211
+ ```
212
+
213
+ 2. Run it: `make runner CMD='load Rails.root.join("tmp/lane-auth/mint.rb").to_s'`. It prints nothing. Re-run it to refresh tokens (they expire with `config.jwt.ttl`; the impersonation session also has idle and absolute timeouts).
214
+ 3. Call the endpoint with `curl -i -H @rails_app/tmp/lane-auth/owner.header -H 'X-UI-Catalog: 2' http://localhost:3000/me/home-notices` (add the `/api` prefix on a host that mounts there). Use `X-UI-Catalog: 1` for the null-notices case.
215
+
216
+ Expected results:
217
+
218
+ | Header file | Expected |
219
+ |---|---|
220
+ | `owner.header` | 200, `Cache-Control: no-store`, `readOnly: false` |
221
+ | `nogrant.header` | 403 |
222
+ | `impersonation.header` | 200, `readOnly: true`, documents redacted (the target holds `home_notices_reader`) |
223
+ | `owner.header` against `GET /auth/principal-capabilities` | `principalCapabilities` includes `me_home_notices` |
224
+ | `nogrant.header` against `GET /auth/principal-capabilities` | does not include `me_home_notices` |
225
+
226
+ The dummy app's `home_notices_reader` group is in `rails_app/config/rbac_groups.yml`.
227
+
228
+ ## Persistence
229
+
230
+ Two tables, both additive: `command_tower_home_notices` (one row per user and notice, with `period_key` empty for deliveries and `campaign_key` NULL for deliveries) and `command_tower_home_notice_controls`. See [Models](models.md).
231
+
232
+ ## Related
233
+
234
+ - [Initializer config](bootstrap/08-initializer.md)
235
+ - [UI](ui.md)
236
+ - [Models](models.md)
@@ -94,6 +94,10 @@ Notes:
94
94
 
95
95
  The Me Inbox detail `content` field (`inbox_document_v1`, see [api_reference.md](api_reference.md#me-inbox)) is built by `InboxDocumentRenderer`. An `inbox_document.json.erb` view is **not** read (the override was replaced). A notification type customizes the document through `declaration.inbox_document_composer`, a pure-Ruby class called with `communication:` that returns an `InboxDocument`. The generic document is built in Ruby from `communication.body` and `metadata`. A missing, raising, or invalid composer falls back silently to the generic document — the Inbox read path never surfaces a `RenderError` and never 500s.
96
96
 
97
+ ### Inbox contract reads for Home Notices
98
+
99
+ `CommandTower::Messaging::Contract::Inbox.document_for_communication(request)` takes `Requests::DocumentForCommunication` (`communication_id:`, `recipient_id:`, `impersonating:`) and returns `Results::InboxDocument` (`communication_id`, `inbox_item_id`, `document`: the catalog 2 `UI::Document`). It returns `nil` when the communication is missing, not the recipient's, deleted or archived, not inbox-backed, or its type has no `MessageDefinition`. It is read-only and emits no audit. Home Notices use it to render a linked delivery ([home_notices.md](home_notices.md#deliver)); `viewed_for_communication?` and `mark_viewed_for_communication` are unchanged.
100
+
97
101
  ## Me Inbox HTTP (summary)
98
102
 
99
103
  | Concern | Contract |
data/docs/models.md CHANGED
@@ -44,6 +44,10 @@ end
44
44
 
45
45
  Engine-owned messaging persistence (communications, endpoints, preferences, and related records) ships with CommandTower. Prefer platform services/workflows for mutations; do not dual-author schema in the host ([Initializing](initializing.md)).
46
46
 
47
+ ## Home Notice models
48
+
49
+ `CommandTower::HomeNotice` (`command_tower_home_notices`) persists one row per user and notice, and `CommandTower::HomeNoticeControl` (`command_tower_home_notice_controls`) holds platform controls. Hosts author notices as classes, not rows. See [Home Notices](home_notices.md).
50
+
47
51
  ## Audit ledger
48
52
 
49
53
  `CommandTower::Audit::Event` is the append-only platform ledger (`command_tower_audit_events`). Only `CommandTower::Audit::Persistence::Subscriber` writes rows. There are no foreign keys to users. Envelope `changes` persist as `change_set`. See [Audit](audit.md).
@@ -45,6 +45,7 @@ Lookup: `CommandTower.config.registry.principal_capabilities.fetch(:admin_worksp
45
45
  | `admin_messaging_gallery_test_send` | Gate the gallery test send. Only `owner` holds it by default; hosts grant it explicitly. |
46
46
  | `admin_impersonation` | Gate Impersonate affordances (5.6 composition). Possession does not start a session by itself. |
47
47
  | `me_audit_events` | Gate Account **Activity** / self-audit Explorer presentation (4.7.1). Hosts own who receives the entity. |
48
+ | `me_home_notices` | Gate Home Notices presentation (`GET /me/home-notices`). Not in `member`; hosts grant it explicitly. |
48
49
 
49
50
  Me/Auth route gates (`session`, `me`, …) and unimplemented Admin entities are **not** seeded. Adding a new CT RBAC entity later requires an explicit slice decision to also register a principal capability.
50
51
 
data/docs/ui.md CHANGED
@@ -124,6 +124,19 @@ A `time` node, `TimeFormatter`, `TextDerivation` and `Email::Renderer` accept `z
124
124
 
125
125
  `Document#validate!(profile: :message)` adds one rule to the default checks: the document has exactly one `facts` node. The default profile is unchanged.
126
126
 
127
+ ## Blocking notice profile
128
+
129
+ `Document#validate!(profile: :blocking_notice)` keeps every default check and rejects, with codes only (hrefs are never echoed):
130
+
131
+ | Rejected | Code | Path |
132
+ |---|---|---|
133
+ | Primary button | `primary_button_not_allowed` | the button node |
134
+ | Navigate action with an internal `path` | `internal_navigation_not_allowed` | the action node |
135
+ | Navigate action with a `mailto:` or `tel:` href | `external_scheme_not_allowed` | the action node |
136
+ | Plain `http` href | `unsafe_scheme` (base rule) | the action node |
137
+
138
+ Only `https` external links remain. The `default` and `message` profiles are unchanged.
139
+
127
140
  ## Redaction
128
141
 
129
142
  `UI::Redaction.call(document, impersonating:)` returns a new document in which every `code` node becomes a `text` node reading "Open the app to check in" (variant `body`, `textTone: secondary`, label dropped), so the code value never reaches the serialised document. Only `impersonating: false` skips it; any other value redacts.
@@ -0,0 +1,50 @@
1
+ # Upgrade: CommandTower 0.24.0
2
+
3
+ **From:** `0.23.0`
4
+ **To:** `0.24.0`
5
+
6
+ Minor release: Home Notices. A host registers `Campaign` and `Delivery` notices that appear once for a signed-in user as a blocking takeover or a dismissible card. Authoring, selection, pacing, events and the kill switch runbook: [Home Notices](../home_notices.md). Everything is off by default (`config.home_notices.enabled` is false), so a host that changes nothing sees no behavior change except the additions listed below.
7
+
8
+ ## Host-visible additions
9
+
10
+ | Change | Host impact |
11
+ |--------|-------------|
12
+ | Migration `CreateCommandTowerHomeNotices` | Creates `command_tower_home_notices` (one row per user and notice) with indexes. Additive and reversible. |
13
+ | Migration `CreateCommandTowerHomeNoticeControls` | Creates `command_tower_home_notice_controls` (kill switch rows, keyed by notice key). Additive and reversible. |
14
+ | `config.home_notices` | `enabled` (false), `notices` (`[]`), `global_cooldown` (8 hours, at least 1 hour), `blocking_daily_cap` (2), `max_open_deliveries` (20), `rate_limit_per_minute` (30), `mutation_rate_limit_per_minute` (120), `update_app_campaign` (true). Invalid values fail the boot check. |
15
+ | Routes | `GET /me/home-notices`, `POST /me/home-notices/:id/impression`, `.../acknowledge`, `.../dismiss`, and `PATCH /admin/home-notices/:key`. All are routed only when `config.home_notices.enabled`; otherwise 404. See [API reference](../api_reference.md#home-notices). |
16
+ | Entity `me_home_notices` | Needed for the four `/me` routes. Also a seeded principal capability, so clients gate on `GET /auth/principal-capabilities`. |
17
+ | Entity `admin_home_notices_kill` | Needed for the kill switch. Not a principal capability. |
18
+ | Audit events | `home_notice_impression`, `home_notice_acknowledged`, `home_notice_dismissed`, `home_notice_control_changed`. See [Audit](../audit.md). |
19
+ | Instrumentation events | Category `home_notices`: `selected`, `controls_unavailable`, `period_key_failed`, `show_if_slow`, `show_if_failed`, `delivery_over_cap`, `linked_mark_failed`. See [Home Notices](../home_notices.md#events). |
20
+ | UI profile `:blocking_notice` | HTTPS external links only, no primary button. Used for blocking notices. |
21
+ | `CommandTower::Services::HomeNotices::Deliver` | Pushes a `Delivery` notice to one user, optionally linked to an inbox item. |
22
+ | Built-in `ct.update_app` campaign | Active when `config.home_notices.enabled` and `config.home_notices.update_app_campaign` are true. Set the latter false to turn it off. |
23
+ | Rake `command_tower:home_notices:prune` | Deletes ended notice rows idle for 180 days. Run through `CommandTower::HomeNotices::PruneEndedJob`. |
24
+ | Account purge | `Services::Auth::PurgeUserAssociatedData` also deletes the user's home notice rows. Audit rows are untouched. |
25
+
26
+ ## Host actions
27
+
28
+ 1. Bump gem to `0.24.0` (or `>= 0.24.0`) and run `bundle install`.
29
+ 2. **Run the migrations** (`db:migrate`) before the new code serves traffic. Both are additive.
30
+ 3. **Grant the entities explicitly.** `me_home_notices` is not part of `member`; `admin_home_notices_kill` is never auto-granted. RBAC fails closed, so a user without the grant gets `403`. At least one host role must grant each entity; `owner` (`entities: true`) passes only after that. The dummy app's `home_notices_reader` and `home_notices_operator` groups in `rails_app/config/rbac_groups.yml` is an example ([RBAC bootstrap](../bootstrap/09-rbac.md)).
31
+ 4. To adopt: list notice classes in `config.home_notices.notices`, then set `config.home_notices.enabled = true`.
32
+ 5. **Schedule the prune.** The gem schedules nothing. Run `command_tower:home_notices:prune` daily from the host scheduler, or enqueue `CommandTower::HomeNotices::PruneEndedJob`. See [Optional bootstrap](../bootstrap/13-optional.md#home-notices-prune).
33
+ 6. Know the kill switch runbook before enabling: [Kill switch runbook](../home_notices.md#kill-switch-runbook).
34
+
35
+ ## `secret_key_base` note
36
+
37
+ A blocking notice stores an HMAC-SHA256 content hash of the document it showed, keyed from `secret_key_base`. Rotating `secret_key_base` makes stored hashes unverifiable, so users who already acknowledged a blocking notice may see it again. Plan rotations accordingly.
38
+
39
+ ## Rolling deploy
40
+
41
+ Migrate first, then roll the app. Old nodes do not know the tables or routes. Do not enable `config.home_notices.enabled` until every node runs 0.24.0.
42
+
43
+ ## Also in this release
44
+
45
+ The platform commits between tag `0.23.0` and this release are the Home Notices slices only. The lane-ready Makefile (`.env.run` include, env ports, `make spec` / `make rubocop`) and the earlier UI foundation and message-definition work (`#61` to `#63`) were already described in 0.23.0 or touch only the repo's own tooling; no further host-visible change is known.
46
+
47
+ ## Not in this release
48
+
49
+ - No scheduler inside the gem (hosts schedule the prune).
50
+ - No change to authentication, sessions or CSRF.
@@ -88,6 +88,13 @@ entities:
88
88
  - index
89
89
  - show
90
90
  - filter_options
91
+ - name: me_home_notices
92
+ controller: CommandTower::Me::HomeNoticesController
93
+ only:
94
+ - index
95
+ - impression
96
+ - acknowledge
97
+ - dismiss
91
98
  - name: admin_messaging_announcements
92
99
  controller: CommandTower::Admin::Messaging::AnnouncementsController
93
100
  only: create
@@ -105,6 +112,9 @@ entities:
105
112
  - index
106
113
  - show
107
114
  - filter_options
115
+ - name: admin_home_notices_kill
116
+ controller: CommandTower::Admin::HomeNoticesController
117
+ only: update
108
118
  - name: admin_workspace
109
119
  controller: CommandTower::Admin::WorkspaceController
110
120
  only: show
@@ -11,6 +11,7 @@ require "command_tower/configuration/base"
11
11
  require "command_tower/configuration/credentials/config"
12
12
  require "command_tower/configuration/email/config"
13
13
  require "command_tower/configuration/email_theme/config"
14
+ require "command_tower/configuration/home_notices/config"
14
15
  require "command_tower/configuration/identity/config"
15
16
  require "command_tower/configuration/impersonation/config"
16
17
  require "command_tower/configuration/jwt/config"
@@ -99,6 +100,11 @@ module CommandTower
99
100
  allowed: Configuration::Messaging::Config,
100
101
  default: Configuration::Messaging::Config.new
101
102
 
103
+ add_composer :home_notices,
104
+ desc: "Home Notices: host-registered campaigns and deliveries shown on Home, with blocking cadence limits",
105
+ allowed: Configuration::HomeNotices::Config,
106
+ default: Configuration::HomeNotices::Config.new
107
+
102
108
  add_composer :account_deletion,
103
109
  desc: "Account self-service deletion host hooks",
104
110
  allowed: Configuration::AccountDeletion::Config,
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "class_composer"
4
+ require "command_tower/configuration/base"
5
+
6
+ module CommandTower
7
+ module Configuration
8
+ module HomeNotices
9
+ class Config < ::CommandTower::Configuration::Base
10
+ include ClassComposer::Generator
11
+
12
+ MINIMUM_GLOBAL_COOLDOWN = 1.hour
13
+
14
+ add_composer :enabled,
15
+ desc: "Turns Home Notices on. When false the catalog is not loaded and the endpoints return 404.",
16
+ allowed: [TrueClass, FalseClass],
17
+ default: false
18
+
19
+ add_composer :notices,
20
+ desc: "Class names (Strings) of Campaign and Delivery subclasses. Checked at boot when enabled.",
21
+ allowed: Array,
22
+ default: [],
23
+ default_shown: "[]"
24
+
25
+ add_composer :global_cooldown,
26
+ desc: "Minimum time between blocking notices for a user. Must be at least 1 hour.",
27
+ allowed: ActiveSupport::Duration,
28
+ default: 8.hours,
29
+ validator: ->(val) { val >= MINIMUM_GLOBAL_COOLDOWN },
30
+ invalid_message: ->(_val) { "Expected a Duration of at least 1 hour" }
31
+
32
+ add_composer :blocking_daily_cap,
33
+ desc: "Maximum number of blocking notices started per user per day.",
34
+ allowed: Integer,
35
+ default: 2
36
+
37
+ add_composer :max_open_deliveries,
38
+ desc: "Maximum number of open Delivery notices per user.",
39
+ allowed: Integer,
40
+ default: 20
41
+
42
+ add_composer :rate_limit_per_minute,
43
+ desc: "GET /me/home-notices requests allowed per user per minute.",
44
+ allowed: Integer,
45
+ default: 30
46
+
47
+ add_composer :mutation_rate_limit_per_minute,
48
+ desc: "Shared bucket of impression, acknowledge and dismiss requests allowed per user per minute.",
49
+ allowed: Integer,
50
+ default: 120
51
+
52
+ add_composer :update_app_campaign,
53
+ desc: "Whether the built-in ct.update_app campaign is active.",
54
+ allowed: [TrueClass, FalseClass],
55
+ default: true
56
+
57
+ def validate!
58
+ if global_cooldown.nil? || global_cooldown < MINIMUM_GLOBAL_COOLDOWN
59
+ raise ArgumentError, "config.home_notices.global_cooldown must be at least 1 hour"
60
+ end
61
+
62
+ self
63
+ end
64
+ end
65
+ end
66
+ end
67
+ end
@@ -315,6 +315,67 @@ module CommandTower
315
315
  retention: :permanent,
316
316
  subject_required: false,
317
317
  affected_user_required: true
318
+ },
319
+ # The first impression of a home notice per period (campaign) or per delivery. Later
320
+ # impressions only increment the row's impression_count.
321
+ home_notice_impression: {
322
+ label: "Home notice first shown",
323
+ tags: %w[home_notices engagement],
324
+ enabled: true,
325
+ enablement_configurable: false,
326
+ user_history: false,
327
+ sensitive_fields: [],
328
+ allowed_changes: [],
329
+ retention: :ninety_days,
330
+ subject_required: false,
331
+ subject_type: "",
332
+ affected_user_required: true,
333
+ global_visible_in_host_scope: false
334
+ },
335
+ # A user acknowledged a home notice. Metadata is ids only; the content hash of a
336
+ # blocking acknowledgement stays on the notice row.
337
+ home_notice_acknowledged: {
338
+ label: "Home notice acknowledged",
339
+ tags: %w[home_notices engagement],
340
+ enabled: true,
341
+ enablement_configurable: false,
342
+ user_history: true,
343
+ sensitive_fields: [],
344
+ allowed_changes: [],
345
+ retention: :one_year,
346
+ subject_required: true,
347
+ subject_type: "User",
348
+ affected_user_required: true,
349
+ global_visible_in_host_scope: true
350
+ },
351
+ # A user dismissed a dismissible home notice. Metadata is ids only.
352
+ home_notice_dismissed: {
353
+ label: "Home notice dismissed",
354
+ tags: %w[home_notices engagement],
355
+ enabled: true,
356
+ enablement_configurable: false,
357
+ user_history: false,
358
+ sensitive_fields: [],
359
+ allowed_changes: [],
360
+ retention: :ninety_days,
361
+ subject_required: false,
362
+ subject_type: "",
363
+ affected_user_required: true,
364
+ global_visible_in_host_scope: false
365
+ },
366
+ # An admin switched a home notice key on or off (the kill switch). No affected user;
367
+ # metadata carries the key only.
368
+ home_notice_control_changed: {
369
+ label: "Home notice kill switch changed",
370
+ tags: %w[home_notices admin],
371
+ enabled: true,
372
+ enablement_configurable: false,
373
+ user_history: false,
374
+ sensitive_fields: [],
375
+ allowed_changes: %i[enabled],
376
+ retention: :permanent,
377
+ subject_required: false,
378
+ affected_user_required: false
318
379
  }
319
380
  }.freeze
320
381
 
@@ -20,7 +20,7 @@ module CommandTower
20
20
  admin_users_update
21
21
  admin_rbac_assignments
22
22
  admin_impersonation
23
- me_audit_events
23
+ me_audit_events me_home_notices
24
24
  ].freeze
25
25
 
26
26
  def initialize
@@ -74,6 +74,7 @@ module CommandTower
74
74
  CommandTower.config.registry.principal_capabilities.validate_required_entities!(entities)
75
75
  CommandTower.config.registry.client_compatibility.validate!(entities)
76
76
  CommandTower.config.admin_scope.validate_scoped_tools!
77
+ CommandTower::HomeNotices::Catalog.load! if CommandTower.config.home_notices.enabled
77
78
  end
78
79
  CommandTower::Logging::Subscriber.attach!
79
80
  CommandTower::Audit::Persistence::Subscriber.attach! unless skip_composition_validation
@@ -21,6 +21,8 @@ module CommandTower
21
21
  20261012000001_add_provider_metadata_to_messaging_delivery_attempts.rb
22
22
  20261012000002_add_finished_at_index_to_messaging_delivery_attempts.rb
23
23
  20261124000001_add_message_definition_columns_to_messaging_communications.rb
24
+ 20261124200001_create_command_tower_home_notices.rb
25
+ 20261124200002_create_command_tower_home_notice_controls.rb
24
26
  ].freeze
25
27
 
26
28
  module_function
@@ -9,10 +9,11 @@ module CommandTower
9
9
  # (a `code` value, spans and times must not reach logs or exceptions).
10
10
  #
11
11
  # `validate!(profile:)` is the seam for rule sets. :default is the base rule
12
- # set. :message adds "exactly one `facts` node" (message definitions). The
13
- # blocking-notice profile in Set 3 will add external-links-only.
12
+ # set. :message adds "exactly one `facts` node" (message definitions).
13
+ # :blocking_notice adds "https external links only, no primary button":
14
+ # internal navigation, mailto and tel hrefs, and primary buttons are rejected.
14
15
  class Document
15
- PROFILES = %i[default message].freeze
16
+ PROFILES = %i[default message blocking_notice].freeze
16
17
  MESSAGE_ERROR_LIMIT = 10
17
18
 
18
19
  attr_reader :root, :text_fallback
@@ -39,7 +40,7 @@ module CommandTower
39
40
  def validation_errors(profile: :default)
40
41
  raise ArgumentError, "unknown validation profile" unless PROFILES.include?(profile)
41
42
 
42
- walker = Walker.new
43
+ walker = Walker.new(profile)
43
44
  walker.check_envelope(self)
44
45
  walker.walk(root, "root", 1) if root.is_a?(Nodes::Node)
45
46
  walker.check_facts_block if profile == :message
@@ -72,7 +73,8 @@ module CommandTower
72
73
  class Walker
73
74
  attr_reader :details
74
75
 
75
- def initialize
76
+ def initialize(profile = :default)
77
+ @blocking_notice = profile == :blocking_notice
76
78
  @details = []
77
79
  @nodes = 0
78
80
  @components = 0
@@ -106,6 +108,7 @@ module CommandTower
106
108
  return if object.node? && reject_node?(object, path, depth)
107
109
 
108
110
  collect_errors(object, path)
111
+ check_blocking_notice(object, path) if @blocking_notice
109
112
  object.each_child { |relative, child| walk(child, "#{path}.#{relative}", depth + (child.node? ? 1 : 0)) }
110
113
  leave_node(object, path)
111
114
  end
@@ -163,6 +166,24 @@ module CommandTower
163
166
  end
164
167
  end
165
168
 
169
+ # :blocking_notice profile. Codes only; hrefs are never echoed. A plain
170
+ # http href is already rejected by the base rules (unsafe_scheme).
171
+ def check_blocking_notice(object, path)
172
+ if object.is_a?(Nodes::Button) && object.primary?
173
+ add(path, :primary_button_not_allowed)
174
+ elsif object.is_a?(Nodes::Action::Navigate)
175
+ check_blocking_destination(object, path)
176
+ end
177
+ end
178
+
179
+ def check_blocking_destination(action, path)
180
+ if action.path
181
+ add(path, :internal_navigation_not_allowed)
182
+ elsif action.href.to_s.start_with?("mailto:", "tel:")
183
+ add(path, :external_scheme_not_allowed)
184
+ end
185
+ end
186
+
166
187
  def collect_errors(object, path)
167
188
  object.valid?
168
189
  object.errors.each do |error|
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module CommandTower
4
- VERSION = "0.23.0"
4
+ VERSION = "0.24.0"
5
5
  end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ namespace :command_tower do
4
+ namespace :home_notices do
5
+ desc "Delete ended home notice rows idle for 180 days (hosts schedule this daily)"
6
+ task prune: :environment do
7
+ CommandTower::HomeNotices::PruneEndedJob.perform_now
8
+ puts "home notices pruned"
9
+ end
10
+ end
11
+ end