open-loam 0.1.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 (245) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +71 -0
  3. data/LICENSE +21 -0
  4. data/README.md +177 -0
  5. data/app/jobs/loam/custom_field_reindex_job.rb +22 -0
  6. data/app/jobs/loam/event_delivery_job.rb +26 -0
  7. data/app/jobs/loam/event_redelivery_sweep_job.rb +21 -0
  8. data/app/jobs/loam/webhook_delivery_job.rb +59 -0
  9. data/app/models/loam/api_token.rb +40 -0
  10. data/app/models/loam/audit_record.rb +18 -0
  11. data/app/models/loam/auth_attempt.rb +13 -0
  12. data/app/models/loam/business_rule.rb +49 -0
  13. data/app/models/loam/business_rule_run.rb +27 -0
  14. data/app/models/loam/comment.rb +28 -0
  15. data/app/models/loam/config.rb +27 -0
  16. data/app/models/loam/custom_field_value.rb +18 -0
  17. data/app/models/loam/dashboard_widget.rb +16 -0
  18. data/app/models/loam/dictionary.rb +20 -0
  19. data/app/models/loam/dictionary_entry.rb +31 -0
  20. data/app/models/loam/event_delivery.rb +38 -0
  21. data/app/models/loam/field_definition.rb +48 -0
  22. data/app/models/loam/inbound_webhook_delivery.rb +24 -0
  23. data/app/models/loam/inbound_webhook_source.rb +55 -0
  24. data/app/models/loam/membership.rb +27 -0
  25. data/app/models/loam/mfa_credential.rb +114 -0
  26. data/app/models/loam/notification.rb +36 -0
  27. data/app/models/loam/pending_action.rb +208 -0
  28. data/app/models/loam/perspective.rb +104 -0
  29. data/app/models/loam/progress_job.rb +103 -0
  30. data/app/models/loam/record_lock.rb +19 -0
  31. data/app/models/loam/scheduled_job.rb +42 -0
  32. data/app/models/loam/search_token.rb +9 -0
  33. data/app/models/loam/sso_identity.rb +13 -0
  34. data/app/models/loam/sso_provider.rb +35 -0
  35. data/app/models/loam/tenant.rb +20 -0
  36. data/app/models/loam/translation.rb +17 -0
  37. data/app/models/loam/webhook_endpoint.rb +26 -0
  38. data/app/views/loam/attachments/_attachments.html.erb +16 -0
  39. data/app/views/loam/comments/_comments.html.erb +24 -0
  40. data/app/views/loam/custom_fields/_fields.html.erb +35 -0
  41. data/lib/generators/loam/entity/entity_generator.rb +160 -0
  42. data/lib/generators/loam/entity/templates/api_controller.rb +67 -0
  43. data/lib/generators/loam/entity/templates/controller.rb +181 -0
  44. data/lib/generators/loam/entity/templates/entity_test.rb +107 -0
  45. data/lib/generators/loam/entity/templates/migration.rb +26 -0
  46. data/lib/generators/loam/entity/templates/model.rb +27 -0
  47. data/lib/generators/loam/entity/templates/policy.rb +10 -0
  48. data/lib/generators/loam/entity/templates/views/_form.html.erb +63 -0
  49. data/lib/generators/loam/entity/templates/views/deleted.html.erb +41 -0
  50. data/lib/generators/loam/entity/templates/views/edit.html.erb +3 -0
  51. data/lib/generators/loam/entity/templates/views/index.html.erb +90 -0
  52. data/lib/generators/loam/entity/templates/views/new.html.erb +3 -0
  53. data/lib/generators/loam/entity/templates/views/show.html.erb +36 -0
  54. data/lib/generators/loam/install/install_generator.rb +288 -0
  55. data/lib/generators/loam/install/templates/AGENTS.md +341 -0
  56. data/lib/generators/loam/install/templates/admin/api_docs_controller.rb +17 -0
  57. data/lib/generators/loam/install/templates/admin/api_docs_index.html.erb +34 -0
  58. data/lib/generators/loam/install/templates/admin/api_tokens_controller.rb +30 -0
  59. data/lib/generators/loam/install/templates/admin/api_tokens_index.html.erb +39 -0
  60. data/lib/generators/loam/install/templates/admin/base_controller.rb +224 -0
  61. data/lib/generators/loam/install/templates/admin/business_rules_controller.rb +64 -0
  62. data/lib/generators/loam/install/templates/admin/business_rules_edit.html.erb +3 -0
  63. data/lib/generators/loam/install/templates/admin/business_rules_form.html.erb +32 -0
  64. data/lib/generators/loam/install/templates/admin/business_rules_index.html.erb +45 -0
  65. data/lib/generators/loam/install/templates/admin/business_rules_new.html.erb +3 -0
  66. data/lib/generators/loam/install/templates/admin/comments_controller.rb +39 -0
  67. data/lib/generators/loam/install/templates/admin/configs_controller.rb +46 -0
  68. data/lib/generators/loam/install/templates/admin/configs_edit.html.erb +22 -0
  69. data/lib/generators/loam/install/templates/admin/configs_index.html.erb +30 -0
  70. data/lib/generators/loam/install/templates/admin/dashboard_controller.rb +10 -0
  71. data/lib/generators/loam/install/templates/admin/dashboard_index.html.erb +26 -0
  72. data/lib/generators/loam/install/templates/admin/dashboard_widgets_controller.rb +23 -0
  73. data/lib/generators/loam/install/templates/admin/dashboard_widgets_index.html.erb +24 -0
  74. data/lib/generators/loam/install/templates/admin/dictionaries_controller.rb +55 -0
  75. data/lib/generators/loam/install/templates/admin/dictionaries_edit.html.erb +45 -0
  76. data/lib/generators/loam/install/templates/admin/dictionaries_form.html.erb +10 -0
  77. data/lib/generators/loam/install/templates/admin/dictionaries_index.html.erb +21 -0
  78. data/lib/generators/loam/install/templates/admin/dictionaries_new.html.erb +5 -0
  79. data/lib/generators/loam/install/templates/admin/dictionary_entries_controller.rb +47 -0
  80. data/lib/generators/loam/install/templates/admin/event_deliveries_controller.rb +23 -0
  81. data/lib/generators/loam/install/templates/admin/event_deliveries_index.html.erb +49 -0
  82. data/lib/generators/loam/install/templates/admin/events_controller.rb +42 -0
  83. data/lib/generators/loam/install/templates/admin/features_controller.rb +35 -0
  84. data/lib/generators/loam/install/templates/admin/features_index.html.erb +37 -0
  85. data/lib/generators/loam/install/templates/admin/field_definitions_controller.rb +52 -0
  86. data/lib/generators/loam/install/templates/admin/field_definitions_index.html.erb +30 -0
  87. data/lib/generators/loam/install/templates/admin/field_definitions_new.html.erb +39 -0
  88. data/lib/generators/loam/install/templates/admin/history_controller.rb +38 -0
  89. data/lib/generators/loam/install/templates/admin/history_index.html.erb +35 -0
  90. data/lib/generators/loam/install/templates/admin/imports_controller.rb +75 -0
  91. data/lib/generators/loam/install/templates/admin/imports_new.html.erb +10 -0
  92. data/lib/generators/loam/install/templates/admin/imports_preview.html.erb +32 -0
  93. data/lib/generators/loam/install/templates/admin/imports_summary.html.erb +32 -0
  94. data/lib/generators/loam/install/templates/admin/inbound_webhook_sources_controller.rb +61 -0
  95. data/lib/generators/loam/install/templates/admin/inbound_webhook_sources_index.html.erb +49 -0
  96. data/lib/generators/loam/install/templates/admin/inbound_webhook_sources_new.html.erb +32 -0
  97. data/lib/generators/loam/install/templates/admin/layout.html.erb +76 -0
  98. data/lib/generators/loam/install/templates/admin/mfa_activated.html.erb +12 -0
  99. data/lib/generators/loam/install/templates/admin/mfa_controller.rb +61 -0
  100. data/lib/generators/loam/install/templates/admin/mfa_new.html.erb +23 -0
  101. data/lib/generators/loam/install/templates/admin/mfa_show.html.erb +19 -0
  102. data/lib/generators/loam/install/templates/admin/notifications_controller.rb +23 -0
  103. data/lib/generators/loam/install/templates/admin/notifications_index.html.erb +32 -0
  104. data/lib/generators/loam/install/templates/admin/overrides_controller.rb +14 -0
  105. data/lib/generators/loam/install/templates/admin/overrides_index.html.erb +29 -0
  106. data/lib/generators/loam/install/templates/admin/pagination.rb +23 -0
  107. data/lib/generators/loam/install/templates/admin/pending_actions_controller.rb +38 -0
  108. data/lib/generators/loam/install/templates/admin/pending_actions_index.html.erb +40 -0
  109. data/lib/generators/loam/install/templates/admin/perspectives_controller.rb +98 -0
  110. data/lib/generators/loam/install/templates/admin/perspectives_index.html.erb +38 -0
  111. data/lib/generators/loam/install/templates/admin/progress_jobs_controller.rb +19 -0
  112. data/lib/generators/loam/install/templates/admin/progress_jobs_index.html.erb +31 -0
  113. data/lib/generators/loam/install/templates/admin/record_locks_controller.rb +17 -0
  114. data/lib/generators/loam/install/templates/admin/scheduled_jobs_controller.rb +69 -0
  115. data/lib/generators/loam/install/templates/admin/scheduled_jobs_edit.html.erb +5 -0
  116. data/lib/generators/loam/install/templates/admin/scheduled_jobs_form.html.erb +16 -0
  117. data/lib/generators/loam/install/templates/admin/scheduled_jobs_index.html.erb +28 -0
  118. data/lib/generators/loam/install/templates/admin/scheduled_jobs_new.html.erb +5 -0
  119. data/lib/generators/loam/install/templates/admin/search_controller.rb +49 -0
  120. data/lib/generators/loam/install/templates/admin/search_index.html.erb +23 -0
  121. data/lib/generators/loam/install/templates/admin/sessions_controller.rb +248 -0
  122. data/lib/generators/loam/install/templates/admin/sessions_mfa_challenge.html.erb +18 -0
  123. data/lib/generators/loam/install/templates/admin/sessions_new.html.erb +45 -0
  124. data/lib/generators/loam/install/templates/admin/sso_providers_controller.rb +65 -0
  125. data/lib/generators/loam/install/templates/admin/sso_providers_edit.html.erb +3 -0
  126. data/lib/generators/loam/install/templates/admin/sso_providers_form.html.erb +32 -0
  127. data/lib/generators/loam/install/templates/admin/sso_providers_index.html.erb +26 -0
  128. data/lib/generators/loam/install/templates/admin/sso_providers_new.html.erb +3 -0
  129. data/lib/generators/loam/install/templates/admin/sudo_controller.rb +45 -0
  130. data/lib/generators/loam/install/templates/admin/sudo_new.html.erb +24 -0
  131. data/lib/generators/loam/install/templates/admin/translations_controller.rb +37 -0
  132. data/lib/generators/loam/install/templates/admin/translations_index.html.erb +21 -0
  133. data/lib/generators/loam/install/templates/admin/webhook_endpoints_controller.rb +38 -0
  134. data/lib/generators/loam/install/templates/admin/webhook_endpoints_index.html.erb +32 -0
  135. data/lib/generators/loam/install/templates/admin/webhook_endpoints_new.html.erb +28 -0
  136. data/lib/generators/loam/install/templates/admin.css +29 -0
  137. data/lib/generators/loam/install/templates/api_base_controller.rb +90 -0
  138. data/lib/generators/loam/install/templates/guardrails_test.rb +79 -0
  139. data/lib/generators/loam/install/templates/import_job.rb +25 -0
  140. data/lib/generators/loam/install/templates/inbound_webhooks_controller.rb +17 -0
  141. data/lib/generators/loam/install/templates/initializer.rb +218 -0
  142. data/lib/generators/loam/install/templates/migrations/create_loam_api_tokens.rb +15 -0
  143. data/lib/generators/loam/install/templates/migrations/create_loam_audit_records.rb +14 -0
  144. data/lib/generators/loam/install/templates/migrations/create_loam_auth_attempts.rb +11 -0
  145. data/lib/generators/loam/install/templates/migrations/create_loam_business_rules.rb +29 -0
  146. data/lib/generators/loam/install/templates/migrations/create_loam_comments.rb +13 -0
  147. data/lib/generators/loam/install/templates/migrations/create_loam_configs.rb +21 -0
  148. data/lib/generators/loam/install/templates/migrations/create_loam_custom_field_values.rb +19 -0
  149. data/lib/generators/loam/install/templates/migrations/create_loam_dashboard_widgets.rb +12 -0
  150. data/lib/generators/loam/install/templates/migrations/create_loam_dictionaries.rb +11 -0
  151. data/lib/generators/loam/install/templates/migrations/create_loam_dictionary_entries.rb +18 -0
  152. data/lib/generators/loam/install/templates/migrations/create_loam_event_deliveries.rb +17 -0
  153. data/lib/generators/loam/install/templates/migrations/create_loam_field_definitions.rb +15 -0
  154. data/lib/generators/loam/install/templates/migrations/create_loam_inbound_webhooks.rb +31 -0
  155. data/lib/generators/loam/install/templates/migrations/create_loam_memberships.rb +11 -0
  156. data/lib/generators/loam/install/templates/migrations/create_loam_mfa_credentials.rb +13 -0
  157. data/lib/generators/loam/install/templates/migrations/create_loam_notifications.rb +15 -0
  158. data/lib/generators/loam/install/templates/migrations/create_loam_pending_actions.rb +26 -0
  159. data/lib/generators/loam/install/templates/migrations/create_loam_perspectives.rb +17 -0
  160. data/lib/generators/loam/install/templates/migrations/create_loam_progress_jobs.rb +20 -0
  161. data/lib/generators/loam/install/templates/migrations/create_loam_record_locks.rb +16 -0
  162. data/lib/generators/loam/install/templates/migrations/create_loam_scheduled_jobs.rb +20 -0
  163. data/lib/generators/loam/install/templates/migrations/create_loam_search_tokens.rb +18 -0
  164. data/lib/generators/loam/install/templates/migrations/create_loam_sso_providers.rb +34 -0
  165. data/lib/generators/loam/install/templates/migrations/create_loam_tenants.rb +9 -0
  166. data/lib/generators/loam/install/templates/migrations/create_loam_translations.rb +15 -0
  167. data/lib/generators/loam/install/templates/migrations/create_loam_webhook_endpoints.rb +13 -0
  168. data/lib/generators/loam/install/templates/migrations/create_users.rb +13 -0
  169. data/lib/generators/loam/install/templates/user.rb +21 -0
  170. data/lib/generators/loam/primary_key_options.rb +101 -0
  171. data/lib/loam/attachable.rb +27 -0
  172. data/lib/loam/auditable.rb +67 -0
  173. data/lib/loam/auth_throttle.rb +83 -0
  174. data/lib/loam/base32.rb +23 -0
  175. data/lib/loam/bulk.rb +59 -0
  176. data/lib/loam/business_rules/actions.rb +92 -0
  177. data/lib/loam/business_rules/condition.rb +102 -0
  178. data/lib/loam/business_rules.rb +123 -0
  179. data/lib/loam/commentable.rb +22 -0
  180. data/lib/loam/configs.rb +115 -0
  181. data/lib/loam/cron.rb +98 -0
  182. data/lib/loam/csv.rb +18 -0
  183. data/lib/loam/current.rb +21 -0
  184. data/lib/loam/custom_field_index.rb +262 -0
  185. data/lib/loam/custom_fields.rb +114 -0
  186. data/lib/loam/dashboard.rb +17 -0
  187. data/lib/loam/dictionaries.rb +55 -0
  188. data/lib/loam/durable_events.rb +174 -0
  189. data/lib/loam/encryptable.rb +145 -0
  190. data/lib/loam/encryption/cipher.rb +75 -0
  191. data/lib/loam/encryption/key_provider.rb +43 -0
  192. data/lib/loam/encryption.rb +125 -0
  193. data/lib/loam/engine.rb +57 -0
  194. data/lib/loam/enrichers.rb +105 -0
  195. data/lib/loam/errors.rb +49 -0
  196. data/lib/loam/eval.rb +47 -0
  197. data/lib/loam/event_stream.rb +80 -0
  198. data/lib/loam/eventful.rb +45 -0
  199. data/lib/loam/events.rb +51 -0
  200. data/lib/loam/export.rb +74 -0
  201. data/lib/loam/features.rb +75 -0
  202. data/lib/loam/generated_key.rb +37 -0
  203. data/lib/loam/import.rb +168 -0
  204. data/lib/loam/inbound_webhooks.rb +125 -0
  205. data/lib/loam/lifecycle.rb +180 -0
  206. data/lib/loam/locales/loam.en.yml +80 -0
  207. data/lib/loam/mcp/server.rb +60 -0
  208. data/lib/loam/mcp.rb +304 -0
  209. data/lib/loam/notifications.rb +36 -0
  210. data/lib/loam/open_api.rb +194 -0
  211. data/lib/loam/overrides.rb +110 -0
  212. data/lib/loam/pending_actions.rb +60 -0
  213. data/lib/loam/permissions.rb +79 -0
  214. data/lib/loam/perspectives.rb +62 -0
  215. data/lib/loam/policy.rb +106 -0
  216. data/lib/loam/progress.rb +31 -0
  217. data/lib/loam/record_locks.rb +89 -0
  218. data/lib/loam/scheduler.rb +153 -0
  219. data/lib/loam/search/driver.rb +31 -0
  220. data/lib/loam/search/like_driver.rb +29 -0
  221. data/lib/loam/search/token_driver.rb +88 -0
  222. data/lib/loam/search.rb +27 -0
  223. data/lib/loam/searchable.rb +90 -0
  224. data/lib/loam/soft_deletable.rb +72 -0
  225. data/lib/loam/sso/claims.rb +10 -0
  226. data/lib/loam/sso/fake_provider.rb +51 -0
  227. data/lib/loam/sso/http_client.rb +42 -0
  228. data/lib/loam/sso/oidc_provider.rb +64 -0
  229. data/lib/loam/sso.rb +129 -0
  230. data/lib/loam/telemetry.rb +43 -0
  231. data/lib/loam/tenant_record.rb +36 -0
  232. data/lib/loam/test_helpers.rb +15 -0
  233. data/lib/loam/totp.rb +63 -0
  234. data/lib/loam/translatable.rb +88 -0
  235. data/lib/loam/undo.rb +126 -0
  236. data/lib/loam/version.rb +3 -0
  237. data/lib/loam/webhooks.rb +34 -0
  238. data/lib/loam/widgets.rb +77 -0
  239. data/lib/loam/workflow.rb +256 -0
  240. data/lib/loam.rb +122 -0
  241. data/lib/open-loam.rb +5 -0
  242. data/lib/tasks/loam.rake +171 -0
  243. data/lib/tasks/loam_eval.rake +32 -0
  244. data/lib/tasks/loam_mcp.rake +20 -0
  245. metadata +332 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0c2e0e075f887239d67b9dfdcefeeba0c825cc7c8faf1fe1f32c813e7916c687
4
+ data.tar.gz: 51b1ee994cfc4f118369463bc999c302e699232bd122e20cf19511e213a9fd91
5
+ SHA512:
6
+ metadata.gz: be8e513778bc4d402e6365304054a865a64f96441868e079b6ccffe41a26046d5d8f8d40c7f2870e6fe33eb26dcace0f708e49a5df83d069a301977c0ad9329a
7
+ data.tar.gz: 3fd4050284ae72d54324b0b69a5aee6f9bd86939cf92dc4299a253e4c4d861c616ad8321def46b673816fd3afda85e245745d165115973deb1f8f86a19a83785
data/CHANGELOG.md ADDED
@@ -0,0 +1,71 @@
1
+ # Changelog
2
+
3
+ Notable changes to Loam. This project follows [semantic versioning](https://semver.org),
4
+ with the caveat that 0.x releases may break the public surface; the
5
+ [backward-compatibility contract](BACKWARD_COMPATIBILITY.md) names what is
6
+ frozen and what is not.
7
+
8
+ ## 0.1.0 — 2026-09-04
9
+
10
+ First public release. Loam is a working, tested prototype: the foundation and
11
+ the agent workflow are complete end to end, but no production deployment has
12
+ used it yet. Evaluate it as a prototype, not as proven infrastructure.
13
+
14
+ ### The foundation
15
+
16
+ - **Multi-tenancy** — `Loam::TenantRecord` scopes every query, job and event to
17
+ the current tenant. A missing tenant context raises `Loam::MissingTenantError`
18
+ rather than silently widening a query.
19
+ - **Authorization** — roles, policies, field-level write access, and
20
+ deny-by-default wildcard feature permissions (`equipment.*`).
21
+ - **Authentication** — password auth, MFA with step-up, rate-limiting and
22
+ lockout, and per-tenant OIDC single sign-on with JIT provisioning.
23
+ - **Audit and history** — audit trails, record history, undo, soft deletion,
24
+ and optimistic-locking protection against concurrent edits.
25
+ - **Encryption** — per-tenant AES-256-GCM field encryption with AAD binding,
26
+ and blind indexes for exact-match lookup on encrypted values.
27
+ - **Business modelling** — runtime custom fields with a read-model index,
28
+ managed dictionaries, declared workflows with role-gated approvals, saved
29
+ views, configurable dashboards, content translations, comments and
30
+ attachments.
31
+ - **Integration** — token-authenticated JSON APIs with generated OpenAPI 3.1
32
+ docs, signed outbound webhooks, replay-resistant inbound webhooks, and a
33
+ two-tier event bus (in-process subscribers plus durable, retryable delivery
34
+ with dead-lettering).
35
+ - **Operations** — notifications, live browser updates, an atomic-claim
36
+ scheduler, long-running task progress, and policy-aware bulk CSV
37
+ import/export.
38
+
39
+ ### For AI coding agents
40
+
41
+ - **`AGENTS.md`** — the contract, generated into the host app, telling an agent
42
+ where code belongs and which boundaries it must preserve.
43
+ - **Generators as the interface** — `loam:install` and `loam:entity` are the
44
+ supported way to add a feature, for humans and agents alike.
45
+ - **Structural guardrails** — tests that fail the build on a missing tenant
46
+ scope, a stray `.unscoped`, or an oversized `AGENTS.md`.
47
+ - **A human-approval gate** — `Loam::PendingActions` stages an agent-proposed
48
+ mutation for review before it touches business data.
49
+ - **The golden-tasks benchmark** and `Loam::Eval` scorer. Results, methodology
50
+ and caveats are published at
51
+ <https://deliveristsio.github.io/open-loam/agents/golden-tasks/>; they come
52
+ from a single internal run and are not independently reproduced.
53
+
54
+ ### Database keys
55
+
56
+ - Generators follow the host app's primary key type — `bigint`, `uuid` or
57
+ `string` — resolved from `--primary-key-type`, then the app's own
58
+ `config.generators` setting, then `bigint`. This covers `create_table`,
59
+ `t.references`, and the polymorphic `*_id` columns that cannot use
60
+ `t.references`.
61
+ - `Loam::GeneratedKey` assigns a UUID before create when the key is not an
62
+ integer, since a string primary key has no database default. Integer keys are
63
+ still generated by the database.
64
+
65
+ ### Known limitations
66
+
67
+ - No production validation. The next milestone is one measured real build, not
68
+ more modules.
69
+ - The benchmark is internal and has been run once.
70
+ - Requires Rails 7.1 or newer and Ruby 3.2 or newer. The demo and CI run on
71
+ SQLite; other adapters are untested.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Grzegorz Smajdor and Loam contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,177 @@
1
+ # Loam 🌱
2
+
3
+ **In short:** Loam is a Rails starter kit for business apps — multi-tenancy,
4
+ permissions, audit trails, workflows, and an event bus already built in, so you
5
+ skip months of plumbing and start on real features. It's also AI-native:
6
+ convention-driven code that AI coding agents (Claude Code, Codex, etc.) can
7
+ safely extend, with human-approval gates before any agent write takes effect.
8
+
9
+ **The fertile Rails foundation where AI agents grow business software.**
10
+
11
+ 📖 **Documentation: [deliveristsio.github.io/open-loam/](https://deliveristsio.github.io/open-loam/)**
12
+
13
+ ---
14
+
15
+ ## Why Loam exists
16
+
17
+ Every serious back-office app — CRM, ERP, ops console, internal tool — re-derives
18
+ the same ~80%: who's the tenant, who's allowed, what changed and when, how do
19
+ modules talk, where's the admin. Teams burn months on this before shipping a
20
+ single thing a customer cares about.
21
+
22
+ And now a second shift: **AI coding agents** (Claude Code, Codex, opencode) can
23
+ write real features — *if* the codebase is legible to them. Sprawling, snowflake
24
+ architectures confuse agents as much as they confuse new hires. Convention is
25
+ what makes a codebase safe for an agent to extend.
26
+
27
+ Loam fuses the two: **a pre-built business foundation that is deliberately
28
+ agent-legible.** Rails already leans convention-over-configuration — arguably the
29
+ most agent-friendly framework there is. Loam extends that philosophy from "how to
30
+ structure a controller" up to "how a multi-tenant, permissioned, audited business
31
+ domain is built" — and ships the agent conventions to match.
32
+
33
+ ## Where Loam sits
34
+
35
+ The pieces exist in Rails, but scattered — foundation shape in Bullet Train and
36
+ the commerce products, an event backbone in Rails Event Store, custom-entity
37
+ modeling only inside commerce. No Rails project unifies them into a single,
38
+ agent-legible business foundation. The closest structural analogs live in other
39
+ stacks: Frappe/ERPNext in Python, and
40
+ **[Open Mercato](https://github.com/open-mercato/open-mercato)** in TypeScript —
41
+ whose module system and convention-first, agent-legible approach directly
42
+ inspired Loam. Loam brings that idea to Rails, the substrate it always suited.
43
+
44
+ ---
45
+
46
+ ## What's already decided
47
+
48
+ Each pillar ships as a convention with sane defaults, overridable when you truly
49
+ need to — never a blank page.
50
+
51
+ | Pillar | What you get, out of the box |
52
+ |--------|------------------------------|
53
+ | 🏢 **Multi-tenancy** | Tenant isolation baked into every query, background job, and event. New models are tenant-scoped by default; a missing tenant context raises, never silently widens a query. |
54
+ | 🔐 **Permissions & auth** | Password login, roles, policies, and field-level write access — declared, not hand-rolled per controller. Tenant selection limited to a user's memberships. Plus **feature-string permissions** (`Loam::Permissions`): grant a role wildcard capability strings (`equipment.*`) and check `Loam.can?("equipment.edit")` / `require_permission!` — deny-by-default, a finer layer under the coarse role. |
55
+ | 🌾 **Custom fields** | Define fields at runtime (a `custom_fields` JSON column + a `Loam::FieldDefinition` row), so agents and admins extend a model without a migration for every idea. Filtering and sorting on a custom field is **index-backed** at scale via a typed read-model projection (`Loam::CustomFieldIndex`), not a per-row JSON scan — with **coverage accounting** (is the index complete or drifting?), a read-time gap that **falls back to the authoritative source for correctness** and **self-heals** in the background (deduped), and an honest "results may be incomplete" signal while it does. A field can declare `readable_roles`: filtering or sorting on a field a role **may not read** is refused, so a filter can't become an **inference oracle** on a restricted value. |
56
+ | 🔀 **Workflow** | Declared states, transitions, and role-gated approvals on any entity; each transition emits an event and is audited. |
57
+ | 📡 **Event backbone** | A first-class domain event bus (`domain.thing.happened`, publish/subscribe) so modules stay decoupled and workflows are legible. Two subscriber tiers with a **formal contract**: *ephemeral* (`Loam::Events.subscribe`, in-process, synchronous, best-effort) for cheap fan-out, and *durable* (`Loam::DurableEvents.register`) which **persists each delivery as a row** in the event's tenant and hands it to a background job — **at-least-once with retry + backoff**, a **dead-letter** view with manual requeue, and a periodic **sweep** that redelivers a lost job (row state, not the queue, is the source of truth). A handler is resolved from a boot-time registry, never constantized from the stored row. |
58
+ | 🔔 **Notifications** | Tenant-scoped in-app notifications, created from events, surfaced in the admin. |
59
+ | 🔌 **API & webhooks** | Token-authenticated JSON API per entity (policy-aware) and per-tenant signed **outbound** webhooks on domain events. **Inbound** webhooks too: a public `/webhooks/:token` receiver that HMAC-verifies each call over the raw body, resists replays (a `(source, delivery-id)` idempotency ledger), answers every auth failure with a uniform `401`, and publishes the verified event onto the bus so durable subscribers react. |
60
+ | 🧾 **Audit** | Every change — who, what, when, in which tenant — recorded by default. |
61
+ | ↩️ **Undo / history** | The audit trail is an **undo stack**: each record's History screen reverts a change with one click, and the undo is itself recorded — so undoing an `undo` is redo. Walks back one step at a time (never clobbers a newer edit); **encrypted fields and workflow state are never reverted** here (state changes undo via the reverse transition). |
62
+ | 🗑️ **Soft-delete** | Deleting a record hides it instead of erasing it — excluded from every query by default, still tenant-scoped in the recycle bin, restorable, and recorded in the audit trail. |
63
+ | ⚙️ **Settings** | A key-value settings store with a global default and a per-tenant override — typed values, resolved override → global → default, cached per request, and never leaking between tenants. |
64
+ | 🚩 **Feature flags** | Runtime on/off capabilities per tenant for rollout or kill-switch — a global default plus per-tenant override, a `Loam::Features.on?` guard, and an admin screen. Gates a **capability**, not a person — distinct from roles and policies. |
65
+ | 🔒 **Encryption at rest** | Mark a field `encrypts` and it is transparently AES-256-GCM encrypted with a **per-tenant** key (HKDF, KMS-pluggable) and decrypted on read — a DB dump leaks nothing and tenant A's key never opens tenant B's data. A keyed blind index keeps an encrypted email/phone findable by exact match; the audit trail records the change, never the value. |
66
+ | 🔑 **MFA & step-up auth** | TOTP second factor for admin login (RFC 6238, no dependency), with single-use recovery codes; the secret is encrypted per-user so it verifies in any tenant. `require_sudo!` re-challenges for sensitive actions within a short window — orthogonal to role. MFA can be required per role. Failed password / TOTP / sudo attempts are **rate-limited and locked out** (per-identifier, configurable), so an online brute-force of a 6-digit code is throttled — and a lockout is enumeration-safe (a locked known and unknown identifier respond identically). |
67
+ | 🚦 **AI approval gate** | An agent running under confirm-mode **stages** a write as a `PendingAction` with a before/after preview instead of committing it; a manager approves (a role-gated workflow transition) and only then does it execute — audited to the approver. The human-in-the-loop primitive for agent writes; encrypted fields never appear in the preview or audit. |
68
+ | 🤖 **MCP server** | An [MCP](https://modelcontextprotocol.io) server (`bin/rails loam:mcp:serve`, stdio) exposes Loam to an AI agent: discover entities/schema/policy, **read** tenant-scoped records (only fields the role may see), and **propose** writes that are *staged for human approval* — never committed. Every gate is a Loam gate reused (tenancy, read-ACL, the approval gate); the agent acts as its API token's user, no more. |
69
+ | 👓 **Saved views** | A user names a view of an entity's admin index — filters, sort, columns — and keeps it private, shares it to a role, or makes it the tenant default. Filters only ever touch whitelisted data columns; a stored view is optimistic-locked so shared edits don't clobber. |
70
+ | 🔏 **Concurrent-edit safety** | Optimistic locking (`lock_version`) turns a stale save into a clean "this changed since you opened it" conflict — with a diff and a retry, never a silent clobber — and an advisory `RecordLock` shows "Anna is editing this" with a manager take-over. The version check is the guarantee; the lock is the courtesy. |
71
+ | 📡 **Real-time updates** | A per-tenant Server-Sent-Events stream pushes selected events to the browser — the notification bell increments live, no polling. Opt-in per event pattern (default off, tenant- and audience-filtered), behind a broadcaster seam so Redis/SolidCable drops in for multi-process. |
72
+ | 🧩 **Response enrichers** | One module attaches a computed block onto another's entity at read time — no foreign-key coupling (billing annotates an Equipment without Equipment knowing billing exists). A batch path resolves N records in one query; a failing enricher is isolated, and each runs tenant-scoped. |
73
+ | ⚡ **Business rules** | A manager declares, per tenant, WHEN a condition holds THEN run actions — evaluated on domain events, no deploy. The condition is **data, never code**: a whitelisted `{field, op, value}` tree over real columns and custom fields (no `eval`, no `send`, tenant/encrypted columns refused), and the actions are a fixed safe vocabulary (notify, emit an event, set a whitelisted field, veto a transition). Rules fire tenant-scoped in priority order, each isolated, with an execution log that shows why it acted. |
74
+ | 🔎 **Pluggable search** | `searchable_by` and `Model.search(q)` stay put; the strategy behind them is a swappable **driver**. Ships two: a portable substring **LIKE** (default, zero-setup) and a **word-level token index** (order-independent, AND-semantics, still plain SQL — no external service), with the seam ready for Meilisearch/Elasticsearch. Swapping is a one-line initializer change, no call-site edits. Tenant-scoped, and an encrypted field's plaintext is never tokenized. |
75
+ | 🪪 **SSO (OIDC)** | Per-tenant single sign-on: each tenant connects its own identity provider. **Home-realm discovery** routes a user to their IdP by email domain; a verified identity is **just-in-time provisioned** (or linked to an existing account), with IdP group → role mapping. The client secret is encrypted at rest (per-tenant key). An unverified email is refused — no silent account takeover. OIDC ships end-to-end; SAML and SCIM are documented seams behind a protocol interface. |
76
+ | 📚 **Dictionaries** | Per-tenant managed lookup lists — named sets of entries (value/label/color/icon/position/default) an admin curates without a deploy. Usable as a **custom-field type**: a `dictionary` field renders a select of the list's active entries and stores the chosen value, showing its label on read. Tenant-scoped and cached per request. |
77
+ | ⏳ **Task progress** | A long-running job (import, reindex, report) reports percent / counts / ETA to the admin, pushed **live over SSE** — no polling. `Loam::Progress.start`/`advance`/`complete!`; the browser bar moves as the job runs. The broadcast is throttled to once per whole percent, the job supports a cooperative cancel, and a stalled job (dead heartbeat) is flagged. Tenant-scoped; the frame carries only id/percent/status. |
78
+ | 🕰️ **Scheduler** | Per-tenant recurring jobs — cron (`0 7 * * *`) or interval — that enqueue an ActiveJob on schedule. A runner (`loam:scheduler:tick`, wired to system cron) claims due jobs **atomically** (Postgres `SKIP LOCKED`; SQLite a transactional claim), so multiple workers **never double-fire** one. `job_class` is whitelisted to a real ActiveJob (no arbitrary code). Tenant-scope jobs run per tenant; system-scope once. A stdlib cron-next calculator (no gem), timezone-aware. |
79
+ | 📥 **Bulk import / export** | CSV **export** of any entity's current filtered view — policy- and encryption-aware (an encrypted field is redacted, never a plaintext dump). CSV **import** with a column-mapping engine: dedupe by a key (update-or-create), per-row validation with a skipped-row error log and a **downloadable error file**, a **dry-run** that commits nothing, and live progress (backgrounded, reported via the task bar). The mapping only targets policy-permitted fields — no crafted column reaches `tenant_id` or a field a role can't write. Plus **datatable bulk actions** (select rows → soft-delete / set-field / export), policy-checked per record and tenant-scoped. |
80
+ | 📊 **Configurable dashboard** | The admin home is a grid of module-provided **widgets** on a registry — a metric or short list each. A manager picks which widgets appear and in what order, per tenant; a widget's `roles:` filter is enforced server-side (a hidden widget's data is never even computed). Widgets query tenant-scoped models (no cross-tenant leak), and a raising widget is isolated into an error tile — the dashboard never breaks. Ships built-ins (recent activity, unread notifications, pending approvals, running tasks). |
81
+ | 📜 **Auto OpenAPI** | The JSON API documents itself. `Loam::OpenApi` introspects the generated per-entity API controllers — columns/types, exposed fields, custom fields, the bearer-token security scheme, and the tenancy guarantee — into an **OpenAPI 3.1** document, with **no hand-written annotations and no external gem**. A server-rendered explorer at `/admin/api_docs` (no Swagger-UI/external JS), a `.json` endpoint for tooling, and `loam:openapi:export` for CI. Request schemas expose only writable fields (never `tenant_id`); encrypted fields are typed as plain strings — the doc describes shape, never data. |
82
+ | 🌐 **Content translations** | Translate the DATA in a record's fields per locale — a product name, a category label — distinct from Rails i18n (developer UI strings, still Rails-native). `translates :name` adds a read-time **overlay**: `record.name` returns the current locale's translation when one exists, else the record's own column (the base value, never lost). Locale is request state (a `/admin` switcher); translations are tenant-scoped, audited, additive rows. An **encrypted field can't be translated** — that would store plaintext, so it's refused at load. |
83
+ | 🧬 **Override registry** | Disable or replace an entry in one of Loam's keyed registries — a built-in dashboard widget, a default broadcast pattern — from an initializer, **without forking or monkeypatching**: `Loam::Overrides.disable(:widgets, "open_progress")` / `.replace(:widgets, "audit_recent") { … }`. The value over a raw monkeypatch: a **stale override** (a key that no longer exists) is warned about at boot, so a typo isn't a silent no-op. Deliberately small — structural pieces (views, controllers, routes) still use standard Rails path-shadowing; this fills the gap for the in-gem registries. |
84
+ | 🖥️ **Admin surface** | An internal console generated from your models — comments, attachments, global search, filtering, pagination — not a second app to maintain. |
85
+ | 🤖 **Agent conventions** | An `AGENTS.md` (byte-budgeted), generators as the one interface, and structural guardrails so an AI agent can add a domain feature **safely** — and a human can read what it did. |
86
+
87
+ You write the **20% that is your business**. Loam is the 80% that every business
88
+ app shares.
89
+
90
+ ---
91
+
92
+ ## Agent-native by design
93
+
94
+ Loam treats "an AI agent will extend this" as a first-class constraint:
95
+
96
+ - **One obvious way** to add an entity, a permission, an event, a screen — so an
97
+ agent's output is predictable and reviewable.
98
+ - **A contract they read** — an `AGENTS.md` map plus generators as the only
99
+ interface, so an agent extends the app the same way every time. (Live schema
100
+ access over MCP is on the roadmap.)
101
+ - **Boundaries agents can't accidentally cross** — tenancy and permissions are
102
+ structural, not conventions an agent might forget.
103
+
104
+ The result: a codebase where "add a `Subscription` entity with an admin screen,
105
+ tenant-scoped, audited, emitting `subscription.created`" is a *small, safe* task —
106
+ for an agent or a human.
107
+
108
+ ---
109
+
110
+ ## Status
111
+
112
+ **Working prototype — every pillar in the table above is built, tested, and
113
+ exercised end to end** by a demo app, a generator harness, and an agent
114
+ benchmark. Some two dozen `Loam::` modules, from tenancy through SSO, each
115
+ added the same way: a small in-gem implementation behind a convention, wired to
116
+ agree with the rest.
117
+
118
+ **What's in the repo**
119
+
120
+ | Path | What it is |
121
+ |------|-----------|
122
+ | `lib/` | The `loam` gem — every pillar as a small `Loam::` module, plus the `loam:install` and `loam:entity` generators that are the whole interface. |
123
+ | `demo/` | An equipment-rental app built with those generators (454 tests / 1,534 assertions as of 2026-08-22), carrying the generated guardrail tests: tenant isolation, no-context-raises, a lint against `.unscoped` in `app/`, and a 32 KB `AGENTS.md` budget. |
124
+ | `ai/` | The agent benchmark — `golden_tasks.md` and recorded runs. First run: **10/10 tasks, zero isolation or authorization violations**; a vanilla-Rails control under the same prompts enforced isolation in **1/10**. |
125
+ | `docs/_agents/` | Deep-dive conventions (encryption, SSO, scheduler, …) linked from `AGENTS.md`, so the agent contract stays inside its byte budget. |
126
+ | `.github/` | CI runs the generator harness and the demo suite on every push. |
127
+
128
+ **Security-hardened by adversarial review.** Each batch of features went through
129
+ an independent adversarial security review; the reviews found and closed real
130
+ cross-tenant account-takeover chains, privilege escalations, and PII-leak
131
+ vectors — every fix landing with a regression test that reproduces the exploit.
132
+ That the *power* features (a business-rules engine, bulk import, SSO) are where
133
+ the holes appeared, and that the guardrails and reviews caught them, is the
134
+ whole thesis in miniature.
135
+
136
+ **How honest the "prototype" label is** — deliberately, each pillar is a
137
+ *minimal in-gem implementation* rather than a wrapper around
138
+ `acts_as_tenant`/`pundit`/`paper_trail`/Rails Event Store: the smallest surface
139
+ that proves the conventions and the agent flow. Swapping the proven gems back in
140
+ *behind the same `Loam::` conventions* is the roadmap, not a reversal. Custom
141
+ fields use the portable Rails `json` column (not Postgres `jsonb`/GIN) because
142
+ the demo runs on SQLite. See [How Loam works](docs/_foundation/overview.md) for
143
+ the pillar-by-pillar breakdown and the decisions behind them.
144
+
145
+ **Try it**
146
+
147
+ ```bash
148
+ cd demo && bundle install && bin/rails db:migrate db:seed
149
+ bin/rails test # guardrail + entity tests
150
+ bin/rails server # → http://localhost:3000/admin
151
+ ```
152
+
153
+ Sign in as `anna@example.com` (manager in both branches, so she gets the tenant
154
+ picker) or `tomek@example.com` (Warsaw only) — password `password123` for both.
155
+
156
+ **New here? Start with the [Getting Started walkthrough](https://deliveristsio.github.io/open-loam/getting-started/)** —
157
+ it builds a multi-tenant feature from `rails new` to a working approval flow,
158
+ showing the real commands and exactly what you *didn't* have to write.
159
+
160
+ - [**Architecture map**](https://claude.ai/code/artifact/949311d3-5e14-4f07-a8ad-7b1bb5bd87ad) — a visual tour: the module graph, a request lifecycle, the event flow
161
+ - [Getting started](https://deliveristsio.github.io/open-loam/getting-started/) — hands-on, install to first feature
162
+ - [Overview](OVERVIEW.md) — plain-language product, use cases, evidence, and risks
163
+ - [Concept & positioning](https://deliveristsio.github.io/open-loam/concept/)
164
+ - [How Loam works](https://deliveristsio.github.io/open-loam/foundation/overview/) — the diagrams above + how every pillar is built
165
+ - [Tenant isolation](https://deliveristsio.github.io/open-loam/foundation/tenant-isolation/) & [Authorization](https://deliveristsio.github.io/open-loam/foundation/authorization/) — the two flagship guarantees, in depth
166
+ - [Agents](https://deliveristsio.github.io/open-loam/agents/) — the agent contract, guardrails, the golden-tasks benchmark, and subsystem deep-dives (encryption, SSO, scheduler, events, inbound webhooks, bulk, confirm-mode)
167
+ - Reference — [configuration](https://deliveristsio.github.io/open-loam/reference/configuration/), [generators](https://deliveristsio.github.io/open-loam/reference/generators/), [backward compatibility](https://deliveristsio.github.io/open-loam/reference/compatibility/)
168
+ - [Roadmap](ROADMAP.md) — ordered backlog, Mercato-informed
169
+ - [Backward-compatibility contract](BACKWARD_COMPATIBILITY.md) — the frozen public surfaces
170
+ - [Architecture decisions](https://deliveristsio.github.io/open-loam/adr/) & [lessons](ai/lessons.md) — why things are the way they are, and the gotchas
171
+ - [Agent pack](.loam/agents/) — everything an AI agent should load to extend a Loam app correctly
172
+ - [Manifesto](https://deliveristsio.github.io/open-loam/manifesto/)
173
+ - [Contributing](CONTRIBUTING.md)
174
+
175
+ ---
176
+
177
+ *MIT licensed — open-core, like the foundations it stands on.*
@@ -0,0 +1,22 @@
1
+ module Loam
2
+ # Heals a custom-field index gap in the background: rebuilds one model's
3
+ # read-model index (Loam::CustomFieldIndex) for one tenant. Enqueued (deduped)
4
+ # by CustomFieldIndex when a filter/order runs over an incomplete index, so a
5
+ # gap self-heals without an operator running a rake task. Inherits
6
+ # ActiveJob::Base, not the app's ApplicationRecord-owned base (the gem must not
7
+ # depend on a class the app configures), and carries the tenant explicitly.
8
+ class CustomFieldReindexJob < ActiveJob::Base
9
+ queue_as :default
10
+
11
+ def perform(tenant_id, model_name)
12
+ tenant = Loam::Tenant.find_by(id: tenant_id)
13
+ model = model_name.to_s.safe_constantize
14
+ return unless tenant && model.is_a?(Class) && model < Loam::TenantRecord
15
+
16
+ Loam.as_tenant(tenant) { Loam::CustomFieldIndex.reindex(model) }
17
+ ensure
18
+ # Release the dedup marker so a later real gap can enqueue again.
19
+ Loam::CustomFieldIndex.clear_pending(tenant_id, model_name.to_s)
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,26 @@
1
+ module Loam
2
+ # Runs one durable event delivery (Loam::DurableEvents). Inherits
3
+ # ActiveJob::Base rather than the host app's ApplicationJob — the gem must not
4
+ # depend on a class the app owns and may have configured for its own retries —
5
+ # and carries the tenant explicitly (ActiveJob doesn't serialize Loam::Current).
6
+ #
7
+ # A missing row is an ANSWER, not an error: with an async queue adapter the job
8
+ # can start before the creating transaction commits, so the row isn't visible
9
+ # yet. The job no-ops; the redelivery sweep picks the row up once it commits.
10
+ # Retry state lives in the ROW (Loam::DurableEvents.deliver), never here.
11
+ class EventDeliveryJob < ActiveJob::Base
12
+ queue_as :default
13
+
14
+ def perform(tenant_id, delivery_id)
15
+ tenant = Loam::Tenant.find_by(id: tenant_id)
16
+ return if tenant.nil?
17
+
18
+ Loam.as_tenant(tenant) do
19
+ delivery = Loam::EventDelivery.find_by(id: delivery_id)
20
+ return if delivery.nil? # not visible yet (txn race) or gone — the sweep covers it
21
+
22
+ Loam::DurableEvents.deliver(delivery)
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,21 @@
1
+ module Loam
2
+ # Periodic durability sweep: re-enqueues due-but-undelivered event deliveries
3
+ # whose accelerator job was lost (worker crash, dropped message, an async
4
+ # adapter racing the creating transaction). This — not perform_later at publish
5
+ # — is what makes persistent delivery durable.
6
+ #
7
+ # Registered per-tenant via Loam::Scheduler (see Loam::Engine), so `sync_tenant`
8
+ # materializes a schedule row per tenant and the scheduler allowlist already
9
+ # covers the class. Tenant-scoped: the scheduler enqueues it with tenant_id and
10
+ # the sweep runs inside that tenant, so there is no cross-tenant scan.
11
+ class EventRedeliverySweepJob < ActiveJob::Base
12
+ queue_as :default
13
+
14
+ def perform(tenant_id: nil)
15
+ tenant = Loam::Tenant.find_by(id: tenant_id)
16
+ return if tenant.nil?
17
+
18
+ Loam.as_tenant(tenant) { Loam::DurableEvents.redeliver_stuck }
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,59 @@
1
+ require "net/http"
2
+ require "openssl"
3
+
4
+ module Loam
5
+ # Delivers one event to one endpoint. Inherits ActiveJob::Base rather than
6
+ # the host app's ApplicationJob: the gem must not depend on a class the app
7
+ # owns and may have configured for its own retries.
8
+ #
9
+ # Signing: the receiver recomputes HMAC-SHA256 of the exact body with the
10
+ # endpoint's secret and compares it to X-Loam-Signature. Body building and
11
+ # signing are class methods so both sides — and the tests — can call them
12
+ # without a network.
13
+ class WebhookDeliveryJob < ActiveJob::Base
14
+ queue_as :default
15
+
16
+ TIMEOUT_SECONDS = 5
17
+
18
+ def self.body_for(event_name, payload, tenant_id)
19
+ JSON.generate(event: event_name, payload: payload, tenant_id: tenant_id)
20
+ end
21
+
22
+ def self.signature(secret, body)
23
+ "sha256=#{OpenSSL::HMAC.hexdigest('SHA256', secret.to_s, body)}"
24
+ end
25
+
26
+ def perform(tenant_id, endpoint_id, event_name, payload)
27
+ tenant = Loam::Tenant.find_by(id: tenant_id)
28
+ return if tenant.nil?
29
+
30
+ Loam.as_tenant(tenant) do
31
+ endpoint = Loam::WebhookEndpoint.find_by(id: endpoint_id)
32
+ # The endpoint may have been deleted or switched off between enqueue
33
+ # and delivery — that is an answer, not an error.
34
+ next if endpoint.nil? || !endpoint.active?
35
+
36
+ deliver(endpoint, self.class.body_for(event_name, payload, tenant_id), event_name)
37
+ end
38
+ end
39
+
40
+ private
41
+
42
+ def deliver(endpoint, body, event_name)
43
+ uri = URI.parse(endpoint.url)
44
+
45
+ http = Net::HTTP.new(uri.host, uri.port)
46
+ http.use_ssl = uri.scheme == "https"
47
+ http.open_timeout = TIMEOUT_SECONDS
48
+ http.read_timeout = TIMEOUT_SECONDS
49
+
50
+ request = Net::HTTP::Post.new(uri.request_uri)
51
+ request["Content-Type"] = "application/json"
52
+ request["X-Loam-Event"] = event_name
53
+ request["X-Loam-Signature"] = self.class.signature(endpoint.secret, body)
54
+ request.body = body
55
+
56
+ http.request(request)
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,40 @@
1
+ module Loam
2
+ # A bearer token that lets a machine act as one user in one tenant. Same
3
+ # rules as a human session: whatever the token's user may do in that tenant,
4
+ # no more. Plumbing, so not audited and not evented.
5
+ class ApiToken < Loam::TenantRecord
6
+ self.table_name = "loam_api_tokens"
7
+
8
+ belongs_to :user
9
+
10
+ validates :token, presence: true, uniqueness: true
11
+
12
+ before_validation on: :create do
13
+ self.token ||= SecureRandom.hex(24)
14
+ end
15
+
16
+ # THE blessed cross-tenant lookup, and the reason it lives in the gem.
17
+ #
18
+ # A bearer token arrives with no tenant context — the token IS how the
19
+ # request discovers which tenant it belongs to, so this one query must
20
+ # bypass the tenant scope. That is exactly what host apps are forbidden to
21
+ # do (`test/loam_guardrails_test.rb` fails the build on it), so the escape
22
+ # hatch is vetted framework code here, used once, at the edge: find the
23
+ # token, establish Loam::Current, and everything downstream is ordinary
24
+ # tenant-scoped code again.
25
+ #
26
+ # Returns the token, or nil for an unknown/blank one — callers render 401.
27
+ def self.authenticate(raw_token)
28
+ return nil if raw_token.blank?
29
+
30
+ api_token = unscoped.find_by(token: raw_token)
31
+ return nil unless api_token
32
+
33
+ Loam::Current.tenant = api_token.tenant
34
+ Loam::Current.actor = api_token.user
35
+ api_token.update_column(:last_used_at, Time.current)
36
+
37
+ api_token
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,18 @@
1
+ module Loam
2
+ # One row per change: who (actor), what (auditable + action + changeset),
3
+ # when (created_at), in which tenant (tenant_id, via TenantRecord).
4
+ # Append-only by convention; not itself audited or evented.
5
+ class AuditRecord < Loam::TenantRecord
6
+ self.table_name = "loam_audit_records"
7
+
8
+ belongs_to :actor, class_name: "User", optional: true
9
+
10
+ validates :auditable_type, :auditable_id, :action, presence: true
11
+
12
+ serialize :changeset, coder: JSON
13
+
14
+ def auditable
15
+ auditable_type.constantize.unscoped.find_by(id: auditable_id)
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,13 @@
1
+ module Loam
2
+ # A single failed authentication attempt, for rate-limiting/lockout
3
+ # (Loam::AuthThrottle). Deliberately NOT tenant-scoped — authentication happens
4
+ # BEFORE a tenant is chosen (login), so this is a global auth-layer table keyed
5
+ # by the submitted identifier (the same reason Loam::MfaCredential is global).
6
+ # Allowlisted in the guardrails tenancy lint.
7
+ class AuthAttempt < ApplicationRecord
8
+ include Loam::GeneratedKey
9
+ self.table_name = "loam_auth_attempts"
10
+
11
+ validates :identifier, :kind, presence: true
12
+ end
13
+ end
@@ -0,0 +1,49 @@
1
+ module Loam
2
+ # A per-tenant, admin-configurable rule: WHEN a condition holds THEN run
3
+ # actions. Declared as DATA (a trigger event pattern + a safe condition tree +
4
+ # a typed action list), never as code — see Loam::BusinessRules for the engine
5
+ # that evaluates it. Audited like any business record.
6
+ class BusinessRule < Loam::TenantRecord
7
+ self.table_name = "loam_business_rules"
8
+
9
+ include Loam::Auditable
10
+
11
+ has_many :runs, class_name: "Loam::BusinessRuleRun", dependent: :delete_all
12
+
13
+ validates :name, :trigger, presence: true
14
+ # A rule may only target a tenant-scoped model (or none, for an event-only
15
+ # rule). Refusing a global class like `User` at SAVE time means a poisoned
16
+ # rule can't even be persisted — kept in lockstep with
17
+ # Loam::BusinessRules.subject_for, which refuses the same at run time.
18
+ validate :entity_type_targets_a_tenant_record
19
+
20
+ scope :active, -> { where(active: true) }
21
+ scope :by_priority, -> { order(priority: :desc, id: :asc) }
22
+ scope :for_entity, ->(entity_type) { where(entity_type: entity_type.to_s) }
23
+
24
+ def matches_trigger?(event_name)
25
+ Loam::Events.pattern_matches?(trigger, event_name)
26
+ end
27
+
28
+ # The stored json, defensively — a hand-created row could hold a non-hash /
29
+ # non-array.
30
+ def condition_tree
31
+ condition.is_a?(Hash) ? condition : {}
32
+ end
33
+
34
+ def action_list
35
+ actions.is_a?(Array) ? actions : []
36
+ end
37
+
38
+ private
39
+
40
+ def entity_type_targets_a_tenant_record
41
+ return if entity_type.blank? # event-only rule, no subject to load
42
+
43
+ klass = entity_type.safe_constantize
44
+ unless klass.is_a?(Class) && klass < Loam::TenantRecord
45
+ errors.add(:entity_type, "must name a Loam tenant-scoped model (not #{entity_type.inspect})")
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,27 @@
1
+ module Loam
2
+ # The log of why a business rule did (or did not) act — so the admin can see
3
+ # WHY something happened. Plumbing, like Loam::RecordLock: NOT audited (a log
4
+ # of a log is noise). Capped per rule so the table stays lean.
5
+ class BusinessRuleRun < Loam::TenantRecord
6
+ self.table_name = "loam_business_rule_runs"
7
+
8
+ KEEP_PER_RULE = 50
9
+
10
+ belongs_to :business_rule, class_name: "Loam::BusinessRule"
11
+
12
+ scope :recent, -> { order(created_at: :desc) }
13
+
14
+ after_create_commit :prune_old_runs
15
+
16
+ private
17
+
18
+ # Keep the last KEEP_PER_RULE runs per rule; drop the rest. Cheap and bounded.
19
+ def prune_old_runs
20
+ stale = self.class.where(business_rule_id: business_rule_id)
21
+ .order(created_at: :desc)
22
+ .offset(KEEP_PER_RULE)
23
+ .ids
24
+ self.class.where(id: stale).delete_all if stale.any?
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,28 @@
1
+ module Loam
2
+ # A note by one person, on one record, in one tenant. Polymorphic, so any
3
+ # entity that `include Loam::Commentable` gets a discussion for free.
4
+ #
5
+ # Not audited on purpose: the comment IS the activity record. A
6
+ # Loam::AuditRecord saying "someone created a comment" beside a comment
7
+ # saying what they wrote is the same fact stored twice.
8
+ #
9
+ # Evented on purpose, in Loam's own domain ("loam.comment.created"), because
10
+ # a new comment is exactly the kind of thing an app wants to react to —
11
+ # notify the watchers, ping a webhook — without every app inventing its own
12
+ # event name for it.
13
+ class Comment < Loam::TenantRecord
14
+ include Loam::Eventful
15
+
16
+ self.table_name = "loam_comments"
17
+
18
+ event_domain :loam
19
+ event_entity :comment # not "loam_comment", which the namespace would give
20
+
21
+ belongs_to :commentable, polymorphic: true
22
+ belongs_to :author, class_name: "User"
23
+
24
+ validates :body, presence: true
25
+
26
+ scope :oldest_first, -> { order(:created_at) }
27
+ end
28
+ end
@@ -0,0 +1,27 @@
1
+ module Loam
2
+ # A single configuration setting: one namespaced key, one JSON-able value.
3
+ #
4
+ # Deliberately NOT a Loam::TenantRecord. A setting exists at two levels — a
5
+ # GLOBAL default (tenant_id NULL) that every tenant sees, and a per-tenant
6
+ # OVERRIDE (tenant_id set) that wins for that one tenant — so tenancy is a
7
+ # nullable column here, not a default_scope. Resolving a key means reading
8
+ # across both levels at once, which is why the lookup lives in vetted gem code
9
+ # (Loam::Configs), never in app code (see the tenancy allowlist in
10
+ # test/loam_guardrails_test.rb).
11
+ #
12
+ # The value goes in a json column, so a bool, number, string, array, or hash
13
+ # all round-trip under the same key. Row existence — not the value — is what
14
+ # marks a key as set, so the value may legitimately be JSON null.
15
+ class Config < ApplicationRecord
16
+ include Loam::GeneratedKey
17
+ self.table_name = "loam_configs"
18
+
19
+ belongs_to :tenant, class_name: "Loam::Tenant", optional: true
20
+
21
+ validates :key, presence: true
22
+ # One global per key, one override per key per tenant. AR renders the nil
23
+ # scope as `tenant_id IS NULL`, so this covers both cases; the two partial
24
+ # indexes in the migration are the race-proof guarantee behind it.
25
+ validates :key, uniqueness: { scope: :tenant_id }
26
+ end
27
+ end