adula 2.1.0 → 2.3.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 (269) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -12
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +6 -4
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_assistant_prune.d.ts +10 -0
  7. package/build/commands/adula_assistant_prune.js +12 -0
  8. package/build/commands/adula_outbox.d.ts +10 -0
  9. package/build/commands/adula_outbox.js +11 -0
  10. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  11. package/build/commands/adula_restore_reconcile.js +34 -0
  12. package/build/commands/adula_runtime_health.d.ts +10 -0
  13. package/build/commands/adula_runtime_health.js +27 -0
  14. package/build/commands/adula_uploads_prune.d.ts +10 -0
  15. package/build/commands/adula_uploads_prune.js +16 -0
  16. package/build/commands/app.d.ts +10 -0
  17. package/build/commands/app.js +64 -0
  18. package/build/commands/backup_create.d.ts +11 -0
  19. package/build/commands/backup_create.js +99 -0
  20. package/build/commands/backup_open.d.ts +16 -0
  21. package/build/commands/backup_open.js +48 -0
  22. package/build/commands/backup_restore_files.d.ts +11 -0
  23. package/build/commands/backup_restore_files.js +44 -0
  24. package/build/commands/backup_restore_test.d.ts +12 -0
  25. package/build/commands/backup_restore_test.js +188 -0
  26. package/build/commands/backup_seal.d.ts +12 -0
  27. package/build/commands/backup_seal.js +36 -0
  28. package/build/commands/backup_services.d.ts +33 -0
  29. package/build/commands/backup_services.js +6 -0
  30. package/build/commands/backup_verify.d.ts +9 -0
  31. package/build/commands/backup_verify.js +59 -0
  32. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  33. package/build/commands/backup_verify_snapshot.js +37 -0
  34. package/build/commands/client.d.ts +16 -0
  35. package/build/commands/client.js +71 -0
  36. package/build/commands/doctor.js +21 -1
  37. package/build/commands/install.d.ts +8 -0
  38. package/build/commands/install.js +69 -45
  39. package/build/commands/main.d.ts +3 -2
  40. package/build/commands/main.js +32 -0
  41. package/build/commands/module_add.js +4 -20
  42. package/build/commands/resource.d.ts +2 -0
  43. package/build/commands/resource.js +12 -3
  44. package/build/commands/resource_migration.d.ts +15 -0
  45. package/build/commands/resource_migration.js +81 -0
  46. package/build/commands/resource_snapshot.d.ts +2 -0
  47. package/build/commands/resource_snapshot.js +21 -4
  48. package/build/commands/sla_evaluate.d.ts +14 -0
  49. package/build/commands/sla_evaluate.js +16 -0
  50. package/build/commands/ui.js +4 -2
  51. package/build/commands/ui_css.d.ts +9 -0
  52. package/build/commands/ui_css.js +19 -0
  53. package/build/commands/upgrade.d.ts +1 -1
  54. package/build/commands/upgrade.js +1 -1
  55. package/build/configure.js +1 -1
  56. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  57. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  58. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  59. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  60. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  61. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  62. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  63. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  64. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  65. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  66. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  67. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  68. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  69. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  70. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  71. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  72. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  73. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  74. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  75. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  76. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  77. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  78. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  79. package/build/database/migrations/1770000000056_appearance.js +10 -0
  80. package/build/index.d.ts +87 -11
  81. package/build/index.js +50 -7
  82. package/build/providers/adula_provider.d.ts +2 -0
  83. package/build/providers/adula_provider.js +7 -0
  84. package/build/src/admin/contracts.js +1 -1
  85. package/build/src/admin/controller.d.ts +14 -1
  86. package/build/src/admin/controller.js +91 -13
  87. package/build/src/admin/errors.d.ts +32 -0
  88. package/build/src/admin/errors.js +63 -1
  89. package/build/src/admin/presentation.d.ts +21 -2
  90. package/build/src/admin/resource/editor.d.ts +60 -0
  91. package/build/src/admin/resource/editor.js +345 -0
  92. package/build/src/admin/resource/export.d.ts +54 -0
  93. package/build/src/admin/resource/export.js +262 -0
  94. package/build/src/admin/resource/lifecycle.d.ts +23 -0
  95. package/build/src/admin/resource/lifecycle.js +91 -0
  96. package/build/src/admin/resource/query.d.ts +111 -0
  97. package/build/src/admin/resource/query.js +595 -0
  98. package/build/src/admin/resource/read.d.ts +109 -0
  99. package/build/src/admin/resource/read.js +388 -0
  100. package/build/src/admin/resource/shared.d.ts +93 -0
  101. package/build/src/admin/resource/shared.js +265 -0
  102. package/build/src/admin/resource/trash.d.ts +10 -0
  103. package/build/src/admin/resource/trash.js +56 -0
  104. package/build/src/admin/resource/write.d.ts +57 -0
  105. package/build/src/admin/resource/write.js +603 -0
  106. package/build/src/admin/resource_service.d.ts +80 -193
  107. package/build/src/admin/resource_service.js +81 -1343
  108. package/build/src/admin/resource_tools.d.ts +111 -0
  109. package/build/src/admin/resource_tools.js +139 -0
  110. package/build/src/ai/assistant.d.ts +100 -0
  111. package/build/src/ai/assistant.js +487 -0
  112. package/build/src/ai/client.d.ts +49 -0
  113. package/build/src/ai/client.js +85 -0
  114. package/build/src/ai/prompt.d.ts +23 -0
  115. package/build/src/ai/prompt.js +83 -0
  116. package/build/src/ai/settings.d.ts +56 -0
  117. package/build/src/ai/settings.js +214 -0
  118. package/build/src/ai/usage.d.ts +16 -0
  119. package/build/src/ai/usage.js +33 -0
  120. package/build/src/appearance/appearance.d.ts +134 -0
  121. package/build/src/appearance/appearance.js +461 -0
  122. package/build/src/appearance/colors.d.ts +43 -0
  123. package/build/src/appearance/colors.js +99 -0
  124. package/build/src/appearance/logo.d.ts +32 -0
  125. package/build/src/appearance/logo.js +112 -0
  126. package/build/src/attachments/attachment_service.d.ts +46 -2
  127. package/build/src/attachments/attachment_service.js +96 -4
  128. package/build/src/auth/actor_store.d.ts +5 -1
  129. package/build/src/auth/actor_store.js +8 -4
  130. package/build/src/auth/conditions.d.ts +5 -0
  131. package/build/src/auth/conditions.js +26 -3
  132. package/build/src/auth/sql.js +17 -5
  133. package/build/src/auth/two_factor.d.ts +96 -0
  134. package/build/src/auth/two_factor.js +259 -0
  135. package/build/src/backups/archive.d.ts +52 -0
  136. package/build/src/backups/archive.js +362 -0
  137. package/build/src/backups/cloud_backups.d.ts +133 -0
  138. package/build/src/backups/cloud_backups.js +650 -0
  139. package/build/src/backups/doctor.d.ts +7 -0
  140. package/build/src/backups/doctor.js +55 -0
  141. package/build/src/backups/providers.d.ts +81 -0
  142. package/build/src/backups/providers.js +470 -0
  143. package/build/src/collaboration/assignments.d.ts +59 -2
  144. package/build/src/collaboration/assignments.js +196 -74
  145. package/build/src/collaboration/record_collaboration.d.ts +21 -4
  146. package/build/src/collaboration/record_collaboration.js +126 -51
  147. package/build/src/collaboration/shared.d.ts +24 -0
  148. package/build/src/collaboration/shared.js +34 -0
  149. package/build/src/commands/app_scaffold.d.ts +72 -0
  150. package/build/src/commands/app_scaffold.js +285 -0
  151. package/build/src/commands/capabilities.js +35 -9
  152. package/build/src/commands/doctor.d.ts +24 -2
  153. package/build/src/commands/doctor.js +81 -6
  154. package/build/src/commands/gap_report.d.ts +1 -1
  155. package/build/src/commands/gap_report.js +2 -2
  156. package/build/src/commands/generator.d.ts +37 -1
  157. package/build/src/commands/generator.js +61 -18
  158. package/build/src/commands/snapshot.d.ts +24 -13
  159. package/build/src/commands/snapshot.js +54 -14
  160. package/build/src/commands/source_markers.d.ts +10 -0
  161. package/build/src/commands/source_markers.js +29 -0
  162. package/build/src/core/activity.d.ts +2 -0
  163. package/build/src/core/activity.js +7 -1
  164. package/build/src/core/administrators.d.ts +38 -0
  165. package/build/src/core/administrators.js +145 -0
  166. package/build/src/core/avatar_image.d.ts +33 -0
  167. package/build/src/core/avatar_image.js +278 -0
  168. package/build/src/core/html_sanitizer.d.ts +20 -0
  169. package/build/src/core/html_sanitizer.js +261 -0
  170. package/build/src/core/like.d.ts +5 -0
  171. package/build/src/core/like.js +5 -0
  172. package/build/src/core/lookups.d.ts +80 -0
  173. package/build/src/core/lookups.js +319 -0
  174. package/build/src/core/mail_settings.d.ts +83 -0
  175. package/build/src/core/mail_settings.js +274 -0
  176. package/build/src/core/mail_test.d.ts +16 -0
  177. package/build/src/core/mail_test.js +81 -6
  178. package/build/src/core/message_templates.d.ts +15 -2
  179. package/build/src/core/message_templates.js +81 -11
  180. package/build/src/core/module_seed.js +2 -1
  181. package/build/src/core/notification_channels.d.ts +235 -0
  182. package/build/src/core/notification_channels.js +660 -0
  183. package/build/src/core/roles.js +26 -9
  184. package/build/src/core/saved_views.d.ts +8 -1
  185. package/build/src/core/saved_views.js +91 -26
  186. package/build/src/core/sequences.d.ts +32 -0
  187. package/build/src/core/sequences.js +97 -0
  188. package/build/src/core/settings.d.ts +5 -0
  189. package/build/src/core/settings.js +31 -3
  190. package/build/src/core/template_language.d.ts +61 -0
  191. package/build/src/core/template_language.js +141 -0
  192. package/build/src/core/ui_preferences.d.ts +10 -0
  193. package/build/src/core/ui_preferences.js +15 -1
  194. package/build/src/core/user_avatars.d.ts +79 -0
  195. package/build/src/core/user_avatars.js +186 -0
  196. package/build/src/core/user_invitations.d.ts +5 -1
  197. package/build/src/core/user_invitations.js +7 -1
  198. package/build/src/core/user_preferences.d.ts +36 -0
  199. package/build/src/core/user_preferences.js +125 -0
  200. package/build/src/core/users.d.ts +2 -0
  201. package/build/src/core/users.js +5 -3
  202. package/build/src/database/calendar_days.d.ts +19 -0
  203. package/build/src/database/calendar_days.js +36 -0
  204. package/build/src/database/schema.d.ts +201 -2
  205. package/build/src/database/schema.js +713 -59
  206. package/build/src/database/schema_diff.d.ts +70 -0
  207. package/build/src/database/schema_diff.js +190 -0
  208. package/build/src/events/record_mutation.d.ts +2 -1
  209. package/build/src/events/record_mutation.js +1 -0
  210. package/build/src/integrations/api_client.d.ts +37 -0
  211. package/build/src/integrations/api_client.js +567 -0
  212. package/build/src/integrations/import_adapters.d.ts +37 -0
  213. package/build/src/integrations/import_adapters.js +35 -0
  214. package/build/src/integrations/imports.d.ts +130 -16
  215. package/build/src/integrations/imports.js +434 -73
  216. package/build/src/integrations/openapi.d.ts +3 -1
  217. package/build/src/integrations/openapi.js +465 -31
  218. package/build/src/integrations/outbound.d.ts +94 -0
  219. package/build/src/integrations/outbound.js +276 -0
  220. package/build/src/integrations/print.d.ts +22 -1
  221. package/build/src/integrations/print.js +68 -22
  222. package/build/src/integrations/print_templates.d.ts +216 -0
  223. package/build/src/integrations/print_templates.js +1017 -0
  224. package/build/src/integrations/sync_jobs.d.ts +139 -0
  225. package/build/src/integrations/sync_jobs.js +416 -0
  226. package/build/src/integrations/webhooks.d.ts +12 -12
  227. package/build/src/integrations/webhooks.js +34 -43
  228. package/build/src/integrations/xlsx.d.ts +41 -0
  229. package/build/src/integrations/xlsx.js +519 -0
  230. package/build/src/languages/ar.d.ts +11 -0
  231. package/build/src/languages/ar.js +358 -0
  232. package/build/src/languages/ar_ui.d.ts +461 -0
  233. package/build/src/languages/ar_ui.js +464 -0
  234. package/build/src/languages/catalog.d.ts +66 -0
  235. package/build/src/languages/catalog.js +152 -0
  236. package/build/src/languages/en.d.ts +7 -0
  237. package/build/src/languages/en.js +352 -0
  238. package/build/src/languages/en_ui.d.ts +3 -0
  239. package/build/src/languages/en_ui.js +458 -0
  240. package/build/src/languages/validation.d.ts +26 -0
  241. package/build/src/languages/validation.js +60 -0
  242. package/build/src/lists/bulk_actions.d.ts +89 -0
  243. package/build/src/lists/bulk_actions.js +268 -0
  244. package/build/src/lists/dashboards.d.ts +138 -0
  245. package/build/src/lists/dashboards.js +290 -0
  246. package/build/src/mcp/tools.js +9 -104
  247. package/build/src/resource/define_resource.d.ts +18 -1
  248. package/build/src/resource/define_resource.js +212 -18
  249. package/build/src/resource/definition.d.ts +44 -0
  250. package/build/src/resource/definition.js +171 -0
  251. package/build/src/resource/registry.js +15 -4
  252. package/build/src/resource/types.d.ts +313 -16
  253. package/build/src/resource/values.d.ts +56 -1
  254. package/build/src/resource/values.js +237 -5
  255. package/build/src/services/settings.d.ts +2 -0
  256. package/build/src/services/settings.js +5 -1
  257. package/build/src/upgrade/legacy.js +2 -2
  258. package/build/src/workflows/calendar.d.ts +9 -0
  259. package/build/src/workflows/calendar.js +44 -0
  260. package/build/src/workflows/define_workflow.d.ts +48 -3
  261. package/build/src/workflows/define_workflow.js +57 -13
  262. package/build/src/workflows/delegations.d.ts +107 -0
  263. package/build/src/workflows/delegations.js +326 -0
  264. package/build/src/workflows/engine.d.ts +80 -4
  265. package/build/src/workflows/engine.js +466 -86
  266. package/build/src/workflows/sla.d.ts +15 -0
  267. package/build/src/workflows/sla.js +8 -0
  268. package/build/stubs/resource_contract.txt +12 -1
  269. package/package.json +9 -2
@@ -0,0 +1,107 @@
1
+ import type { Knex } from 'knex';
2
+ /** A user's approvals routed to a delegate for an inclusive date range (ADR 044). */
3
+ export type WorkflowDelegation = {
4
+ id: number;
5
+ delegatorId: number;
6
+ delegatorName: string | null;
7
+ /** The delegator's versioned picture URL, or null without one (ADR 050). */
8
+ delegatorAvatarUrl?: string | null;
9
+ delegateId: number;
10
+ delegateName: string | null;
11
+ /** The delegate's versioned picture URL, or null without one (ADR 050). */
12
+ delegateAvatarUrl?: string | null;
13
+ /** Inclusive dates (YYYY-MM-DD), days in the system time zone (UTC by default). */
14
+ startsOn: string;
15
+ endsOn: string;
16
+ note: string | null;
17
+ status: 'scheduled' | 'active' | 'ended' | 'revoked';
18
+ createdBy: number | null;
19
+ createdAt: string;
20
+ revokedAt: string | null;
21
+ };
22
+ export type WorkflowDelegationInput = {
23
+ delegatorId: number;
24
+ delegateId: unknown;
25
+ startsOn: unknown;
26
+ endsOn: unknown;
27
+ note?: unknown;
28
+ };
29
+ export type WorkflowDelegationOptions = {
30
+ now?: () => Date;
31
+ /** The system time zone whose calendar days delegation ranges use (default UTC). */
32
+ timeZone?: string;
33
+ };
34
+ /** The activity log subject for delegation changes. */
35
+ export declare const DELEGATION_ACTIVITY = "core.workflow_delegations";
36
+ /**
37
+ * Narrows an assignments query (aliased `a`) to the rows a user may act on today:
38
+ * - their own rows, and rows routed to them through a delegation still in force;
39
+ * - rows routed away from them (on_behalf_of): the approver always keeps them;
40
+ * - as a delegate, the open approvals of users who delegated to them for today,
41
+ * including rows routed earlier through a delegation that has since ended.
42
+ * A delegate never holds an approval of a run they started themselves, so delegation
43
+ * cannot let anyone approve their own request. Delegation never widens record access:
44
+ * every caller still checks the record with the acting user's own rights.
45
+ */
46
+ export declare function actionableBy(db: Knex, actorId: number, today: string): (query: Knex.QueryBuilder) => Knex.QueryBuilder<any, any>;
47
+ /** The SQL flag `delegation_active` for an assignments query aliased `a`. */
48
+ export declare function delegationActive(db: Knex, today: string): Knex.Raw<any>;
49
+ /**
50
+ * Out-of-office delegation of workflow approvals. A user delegates to one person per
51
+ * date range (overlapping ranges are refused); administrators manage delegations for
52
+ * others. Creation and revocation are written to the activity log and the delegate is
53
+ * notified. Manual tasks are never delegated, only workflow approvals.
54
+ */
55
+ export declare class WorkflowDelegations {
56
+ private db;
57
+ private options;
58
+ constructor(db: Knex, options?: WorkflowDelegationOptions);
59
+ /** A user's own delegations (given and received), newest first. */
60
+ forUser(userId: number): Promise<{
61
+ given: WorkflowDelegation[];
62
+ received: WorkflowDelegation[];
63
+ }>;
64
+ /**
65
+ * Active users a delegate can be chosen from (id and display name only), at most 20.
66
+ * The search needs two characters and matches names, or an e-mail address exactly, so
67
+ * the picker cannot list the whole user directory or probe e-mail fragments.
68
+ * `exceptId` is the delegator: only users on the delegator's organization path (the same
69
+ * unit, an ancestor or a descendant) are offered, by name or e-mail, the rule create()
70
+ * applies to a user's own delegation. 0 (administrators managing anyone's delegation)
71
+ * offers every active user.
72
+ */
73
+ candidates(search: unknown, exceptId: number): Promise<{
74
+ id: number;
75
+ name: string;
76
+ avatarUrl?: string | null;
77
+ }[]>;
78
+ /** Every delegation that has not ended, for administrators. */
79
+ current(): Promise<WorkflowDelegation[]>;
80
+ /** The delegation in force today for a user, if any. */
81
+ active(delegatorId: number, db?: Knex): Promise<{
82
+ id: number;
83
+ delegateId: number;
84
+ } | null>;
85
+ /**
86
+ * Creates a delegation; the caller decides whether `createdBy` may act for the delegator.
87
+ * When `createdBy` is the delegator, the delegate must be on their organization path (see
88
+ * candidates()); a caller acting for someone else (administrators) may choose any active
89
+ * user.
90
+ */
91
+ create(input: WorkflowDelegationInput, createdBy: number): Promise<WorkflowDelegation>;
92
+ /**
93
+ * Ends a delegation now. `ownerId` must be the delegator unless `any` (administrators);
94
+ * unknown or foreign ids read as not found. `actorId` (default `ownerId`) is recorded,
95
+ * for example the administrator behind an impersonation. Open approvals routed through
96
+ * the delegation return to their approver.
97
+ */
98
+ revoke(id: unknown, ownerId: number, options?: {
99
+ any?: boolean;
100
+ actorId?: number;
101
+ }): Promise<void>;
102
+ private date;
103
+ private query;
104
+ private present;
105
+ private now;
106
+ private today;
107
+ }
@@ -0,0 +1,326 @@
1
+ import { AdulaError } from '../admin/errors.js';
2
+ import { logActivity } from '../core/activity.js';
3
+ import { notifyWithTemplate } from '../core/message_templates.js';
4
+ import { escapeLike } from '../core/like.js';
5
+ import { assertTimeZone, calendarDate } from './calendar.js';
6
+ import { avatarUrlFor, avatarVersionColumn } from '../core/user_avatars.js';
7
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
8
+ const MAX_DAYS = 366;
9
+ const NOTE_LIMIT = 500;
10
+ /** The activity log subject for delegation changes. */
11
+ export const DELEGATION_ACTIVITY = 'core.workflow_delegations';
12
+ /** node-postgres reads a date column as local midnight; read it back with local fields. */
13
+ function dateText(value) {
14
+ if (value instanceof Date)
15
+ return `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`;
16
+ return String(value).slice(0, 10);
17
+ }
18
+ /**
19
+ * Narrows an assignments query (aliased `a`) to the rows a user may act on today:
20
+ * - their own rows, and rows routed to them through a delegation still in force;
21
+ * - rows routed away from them (on_behalf_of): the approver always keeps them;
22
+ * - as a delegate, the open approvals of users who delegated to them for today,
23
+ * including rows routed earlier through a delegation that has since ended.
24
+ * A delegate never holds an approval of a run they started themselves, so delegation
25
+ * cannot let anyone approve their own request. Delegation never widens record access:
26
+ * every caller still checks the record with the acting user's own rights.
27
+ */
28
+ export function actionableBy(db, actorId, today) {
29
+ const active = (alias) => db.raw(`${alias}.revoked_at IS NULL AND ${alias}.starts_on <= ?::date AND ${alias}.ends_on >= ?::date`, [today, today]);
30
+ const routedActive = () => db('workflow_delegations as dr').whereRaw('dr.id = a.delegation_id').whereRaw(active('dr'));
31
+ const ownRun = () => db('workflow_runs as ws').whereRaw('ws.id = a.workflow_run_id').where('ws.started_by', actorId);
32
+ const delegators = () => db('workflow_delegations as dd')
33
+ .where('dd.delegate_id', actorId)
34
+ .whereRaw(active('dd'))
35
+ .select('dd.delegator_id');
36
+ return (query) => query.where((where) => {
37
+ where
38
+ .where((own) => own
39
+ .where('a.assignee_id', actorId)
40
+ .where((routed) => routed
41
+ .whereNull('a.delegation_id')
42
+ .orWhere((held) => held.whereExists(routedActive()).whereNotExists(ownRun()))))
43
+ .orWhere('a.on_behalf_of', actorId)
44
+ .orWhere((delegated) => delegated
45
+ .whereNotNull('a.workflow_run_id')
46
+ .whereNotExists(ownRun())
47
+ .where((source) => source
48
+ .where((plain) => plain.whereNull('a.delegation_id').whereIn('a.assignee_id', delegators()))
49
+ .orWhere((stale) => stale
50
+ .whereNotNull('a.delegation_id')
51
+ .whereNotExists(routedActive())
52
+ .whereIn('a.on_behalf_of', delegators()))));
53
+ });
54
+ }
55
+ /**
56
+ * For a users query aliased `u`: members of a unit on the same organization path as one of
57
+ * `userId`'s units (that unit, an ancestor or a descendant), the tree rule of user fields.
58
+ * A user without units shares a path with nobody.
59
+ */
60
+ function sharesOrgPath(db, userId) {
61
+ return db('user_org_units as m')
62
+ .join('org_units as o', 'o.id', 'm.org_unit_id')
63
+ .whereRaw('m.user_id = u.id')
64
+ .whereExists(db('user_org_units as dm')
65
+ .join('org_units as d', 'd.id', 'dm.org_unit_id')
66
+ .where('dm.user_id', userId)
67
+ .whereRaw('(o.path <@ d.path OR o.path @> d.path)'));
68
+ }
69
+ /** The SQL flag `delegation_active` for an assignments query aliased `a`. */
70
+ export function delegationActive(db, today) {
71
+ return db.raw('EXISTS (SELECT 1 FROM workflow_delegations wd WHERE wd.id = a.delegation_id AND wd.revoked_at IS NULL AND wd.starts_on <= ?::date AND wd.ends_on >= ?::date) AS delegation_active', [today, today]);
72
+ }
73
+ /**
74
+ * Out-of-office delegation of workflow approvals. A user delegates to one person per
75
+ * date range (overlapping ranges are refused); administrators manage delegations for
76
+ * others. Creation and revocation are written to the activity log and the delegate is
77
+ * notified. Manual tasks are never delegated, only workflow approvals.
78
+ */
79
+ export class WorkflowDelegations {
80
+ db;
81
+ options;
82
+ constructor(db, options = {}) {
83
+ this.db = db;
84
+ this.options = options;
85
+ if (options.timeZone)
86
+ assertTimeZone(options.timeZone);
87
+ }
88
+ /** A user's own delegations (given and received), newest first. */
89
+ async forUser(userId) {
90
+ const rows = await this.query()
91
+ .where((q) => q.where('d.delegator_id', userId).orWhere('d.delegate_id', userId))
92
+ .orderBy('d.id', 'desc')
93
+ .limit(100);
94
+ const list = rows.map((row) => this.present(row));
95
+ return {
96
+ given: list.filter((item) => item.delegatorId === userId),
97
+ received: list.filter((item) => item.delegateId === userId && item.status !== 'revoked'),
98
+ };
99
+ }
100
+ /**
101
+ * Active users a delegate can be chosen from (id and display name only), at most 20.
102
+ * The search needs two characters and matches names, or an e-mail address exactly, so
103
+ * the picker cannot list the whole user directory or probe e-mail fragments.
104
+ * `exceptId` is the delegator: only users on the delegator's organization path (the same
105
+ * unit, an ancestor or a descendant) are offered, by name or e-mail, the rule create()
106
+ * applies to a user's own delegation. 0 (administrators managing anyone's delegation)
107
+ * offers every active user.
108
+ */
109
+ async candidates(search, exceptId) {
110
+ const text = typeof search === 'string' ? search.trim().slice(0, 100) : '';
111
+ if (text.length < 2)
112
+ return [];
113
+ const rows = await this.db('users as u')
114
+ .whereNull('u.disabled_at')
115
+ .whereNot('u.id', exceptId)
116
+ .modify((q) => {
117
+ if (exceptId > 0)
118
+ q.whereExists(sharesOrgPath(this.db, exceptId));
119
+ })
120
+ .where((q) => q
121
+ .whereILike('u.full_name', `%${escapeLike(text)}%`)
122
+ .orWhereRaw('lower(u.email) = lower(?)', [text]))
123
+ .orderBy('u.full_name')
124
+ .limit(20)
125
+ .select('u.id', 'u.full_name', 'u.email', avatarVersionColumn(this.db, 'u.id'));
126
+ return rows.map((row) => ({
127
+ id: Number(row.id),
128
+ name: String(row.full_name ?? row.email ?? `#${row.id}`),
129
+ avatarUrl: avatarUrlFor(row.id, row.avatar_version),
130
+ }));
131
+ }
132
+ /** Every delegation that has not ended, for administrators. */
133
+ async current() {
134
+ const rows = await this.query()
135
+ .whereNull('d.revoked_at')
136
+ .where('d.ends_on', '>=', this.today())
137
+ .orderBy('d.starts_on')
138
+ .limit(500);
139
+ return rows.map((row) => this.present(row));
140
+ }
141
+ /** The delegation in force today for a user, if any. */
142
+ async active(delegatorId, db = this.db) {
143
+ const today = this.today();
144
+ const row = await db('workflow_delegations')
145
+ .where('delegator_id', delegatorId)
146
+ .whereNull('revoked_at')
147
+ .where('starts_on', '<=', today)
148
+ .where('ends_on', '>=', today)
149
+ .orderBy('id', 'desc')
150
+ .first('id', 'delegate_id');
151
+ return row ? { id: Number(row.id), delegateId: Number(row.delegate_id) } : null;
152
+ }
153
+ /**
154
+ * Creates a delegation; the caller decides whether `createdBy` may act for the delegator.
155
+ * When `createdBy` is the delegator, the delegate must be on their organization path (see
156
+ * candidates()); a caller acting for someone else (administrators) may choose any active
157
+ * user.
158
+ */
159
+ async create(input, createdBy) {
160
+ const delegatorId = Number(input.delegatorId);
161
+ const delegateId = Number(input.delegateId);
162
+ if (!Number.isSafeInteger(delegatorId) || delegatorId <= 0)
163
+ throw new AdulaError(422, 'E_DELEGATION_USER', 'المستخدم غير صالح');
164
+ if (!Number.isSafeInteger(delegateId) || delegateId <= 0)
165
+ throw new AdulaError(422, 'E_DELEGATE', 'اختر المفوَّض إليه');
166
+ if (delegateId === delegatorId)
167
+ throw new AdulaError(422, 'E_DELEGATE', 'لا يمكن التفويض إلى النفس');
168
+ const startsOn = this.date(input.startsOn, 'تاريخ البداية');
169
+ const endsOn = this.date(input.endsOn, 'تاريخ النهاية');
170
+ if (endsOn < startsOn)
171
+ throw new AdulaError(422, 'E_DELEGATION_RANGE', 'تاريخ النهاية قبل تاريخ البداية');
172
+ if (endsOn < this.today())
173
+ throw new AdulaError(422, 'E_DELEGATION_RANGE', 'لا يمكن إنشاء تفويض انتهت مدته');
174
+ if ((Date.parse(endsOn) - Date.parse(startsOn)) / 86400000 >= MAX_DAYS)
175
+ throw new AdulaError(422, 'E_DELEGATION_RANGE', 'مدة التفويض لا تتجاوز سنة');
176
+ const note = input.note === undefined || input.note === null || input.note === ''
177
+ ? null
178
+ : typeof input.note === 'string' && input.note.trim().length <= NOTE_LIMIT
179
+ ? input.note.trim() || null
180
+ : undefined;
181
+ if (note === undefined)
182
+ throw new AdulaError(422, 'E_DELEGATION_NOTE', 'الملاحظة لا تتجاوز 500 حرف');
183
+ return this.db.transaction(async (trx) => {
184
+ // The delegator's row serializes concurrent requests, so overlap checks hold.
185
+ // Locked in id order and without blocking foreign-key checks on these users.
186
+ const users = await trx('users')
187
+ .whereIn('id', [delegatorId, delegateId])
188
+ .orderBy('id')
189
+ .forNoKeyUpdate();
190
+ const delegator = users.find((user) => Number(user.id) === delegatorId);
191
+ const delegate = users.find((user) => Number(user.id) === delegateId);
192
+ if (!delegator)
193
+ throw new AdulaError(422, 'E_DELEGATION_USER', 'المستخدم غير صالح');
194
+ // A user's own delegation goes to someone on their organization path, the picker's
195
+ // rule; the same answer as an unknown user, so ids cannot be probed for names.
196
+ if (!delegate ||
197
+ delegate.disabled_at ||
198
+ (createdBy === delegatorId &&
199
+ !(await trx('users as u')
200
+ .where('u.id', delegateId)
201
+ .whereExists(sharesOrgPath(trx, delegatorId))
202
+ .first('u.id'))))
203
+ throw new AdulaError(422, 'E_DELEGATE', 'المفوَّض إليه غير موجود أو معطّل');
204
+ const overlap = await trx('workflow_delegations')
205
+ .where('delegator_id', delegatorId)
206
+ .whereNull('revoked_at')
207
+ .where('starts_on', '<=', endsOn)
208
+ .where('ends_on', '>=', startsOn)
209
+ .first('id');
210
+ if (overlap)
211
+ throw new AdulaError(409, 'E_DELEGATION_OVERLAP', 'يوجد تفويض آخر في هذه المدة؛ ألغه أو اختر مدة أخرى');
212
+ const [row] = await trx('workflow_delegations')
213
+ .insert({
214
+ delegator_id: delegatorId,
215
+ delegate_id: delegateId,
216
+ starts_on: startsOn,
217
+ ends_on: endsOn,
218
+ note,
219
+ created_by: createdBy,
220
+ })
221
+ .returning('id');
222
+ const id = Number(row.id);
223
+ await logActivity(trx, {
224
+ resource: DELEGATION_ACTIVITY,
225
+ recordId: id,
226
+ actorId: createdBy,
227
+ action: 'delegation_created',
228
+ changes: { delegatorId, delegateId, startsOn, endsOn },
229
+ });
230
+ await notifyWithTemplate(trx, delegateId, 'workflow.delegated', {
231
+ delegator: delegator.full_name ?? delegator.email ?? `#${delegatorId}`,
232
+ from: startsOn,
233
+ to: endsOn,
234
+ });
235
+ return this.present(await this.query(trx).where('d.id', id).first());
236
+ });
237
+ }
238
+ /**
239
+ * Ends a delegation now. `ownerId` must be the delegator unless `any` (administrators);
240
+ * unknown or foreign ids read as not found. `actorId` (default `ownerId`) is recorded,
241
+ * for example the administrator behind an impersonation. Open approvals routed through
242
+ * the delegation return to their approver.
243
+ */
244
+ async revoke(id, ownerId, options = {}) {
245
+ const key = Number(id);
246
+ const actorId = options.actorId ?? ownerId;
247
+ if (!Number.isSafeInteger(key) || key <= 0)
248
+ throw new AdulaError(404, 'E_DELEGATION_NOT_FOUND', 'التفويض غير موجود');
249
+ await this.db.transaction(async (trx) => {
250
+ const row = await trx('workflow_delegations').where('id', key).forUpdate().first();
251
+ if (!row || (!options.any && Number(row.delegator_id) !== ownerId))
252
+ throw new AdulaError(404, 'E_DELEGATION_NOT_FOUND', 'التفويض غير موجود');
253
+ if (row.revoked_at)
254
+ return;
255
+ await trx('workflow_delegations')
256
+ .where('id', key)
257
+ .update({ revoked_at: this.now(), revoked_by: actorId });
258
+ const returned = await trx('assignments')
259
+ .where({ delegation_id: key, status: 'open' })
260
+ .update({
261
+ assignee_id: trx.raw('on_behalf_of'),
262
+ on_behalf_of: null,
263
+ delegation_id: null,
264
+ });
265
+ await logActivity(trx, {
266
+ resource: DELEGATION_ACTIVITY,
267
+ recordId: key,
268
+ actorId,
269
+ action: 'delegation_revoked',
270
+ changes: {
271
+ delegatorId: Number(row.delegator_id),
272
+ delegateId: Number(row.delegate_id),
273
+ returned,
274
+ },
275
+ });
276
+ });
277
+ }
278
+ date(value, field) {
279
+ // Round-trip the date: Date.parse accepts impossible days such as 2027-02-30.
280
+ if (typeof value !== 'string' ||
281
+ !DATE.test(value) ||
282
+ Number.isNaN(Date.parse(value)) ||
283
+ new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) !== value)
284
+ throw new AdulaError(422, 'E_DELEGATION_RANGE', `${field} غير صالح`);
285
+ return value;
286
+ }
287
+ query(db = this.db) {
288
+ return db('workflow_delegations as d')
289
+ .leftJoin('users as f', 'f.id', 'd.delegator_id')
290
+ .leftJoin('users as t', 't.id', 'd.delegate_id')
291
+ .select('d.*', 'f.full_name as delegator_name', 't.full_name as delegate_name', avatarVersionColumn(db, 'd.delegator_id', 'delegator_avatar'), avatarVersionColumn(db, 'd.delegate_id', 'delegate_avatar'));
292
+ }
293
+ present(row) {
294
+ const today = this.today();
295
+ const startsOn = dateText(row.starts_on);
296
+ const endsOn = dateText(row.ends_on);
297
+ return {
298
+ id: Number(row.id),
299
+ delegatorId: Number(row.delegator_id),
300
+ delegatorName: row.delegator_name ? String(row.delegator_name) : null,
301
+ delegatorAvatarUrl: avatarUrlFor(row.delegator_id, row.delegator_avatar),
302
+ delegateId: Number(row.delegate_id),
303
+ delegateName: row.delegate_name ? String(row.delegate_name) : null,
304
+ delegateAvatarUrl: avatarUrlFor(row.delegate_id, row.delegate_avatar),
305
+ startsOn,
306
+ endsOn,
307
+ note: row.note ? String(row.note) : null,
308
+ status: row.revoked_at
309
+ ? 'revoked'
310
+ : endsOn < today
311
+ ? 'ended'
312
+ : startsOn > today
313
+ ? 'scheduled'
314
+ : 'active',
315
+ createdBy: row.created_by === null ? null : Number(row.created_by),
316
+ createdAt: new Date(row.created_at).toISOString(),
317
+ revokedAt: row.revoked_at ? new Date(row.revoked_at).toISOString() : null,
318
+ };
319
+ }
320
+ now() {
321
+ return this.options.now?.() ?? new Date();
322
+ }
323
+ today() {
324
+ return calendarDate(this.now(), this.options.timeZone);
325
+ }
326
+ }
@@ -6,7 +6,11 @@ import type { JsonValue } from '../resource/types.js';
6
6
  import type { DomainEvent, Listener } from '../events/outbox.js';
7
7
  import type { HttpPoster } from '../integrations/webhooks.js';
8
8
  import type { Assignments } from '../collaboration/assignments.js';
9
+ import { type ActorLoader } from '../collaboration/shared.js';
9
10
  import { type WorkflowDefinition } from './define_workflow.js';
11
+ import { type SlaEvaluation, type WorkflowSlaStatus } from './sla.js';
12
+ export { slaState } from './sla.js';
13
+ export type { SlaEvaluation, SlaState, WorkflowSlaStatus } from './sla.js';
10
14
  export type WorkflowRunStatus = 'pending_definition' | 'running' | 'waiting' | 'completed' | 'failed' | 'cancelled';
11
15
  export type WorkflowRun = {
12
16
  id: string;
@@ -30,7 +34,13 @@ export type WorkflowRun = {
30
34
  history: {
31
35
  step: string | null;
32
36
  event: string;
37
+ /** The user who acted; null for system steps («النظام»). */
38
+ actorId?: number | null;
33
39
  actorName: string | null;
40
+ /** The actor's versioned picture URL, or null without one (ADR 050). */
41
+ actorAvatarUrl?: string | null;
42
+ /** Set when the actor decided as a delegate (ADR 044). */
43
+ onBehalfOfName?: string | null;
34
44
  detail: {
35
45
  [key: string]: JsonValue;
36
46
  };
@@ -42,7 +52,14 @@ export type WorkflowRun = {
42
52
  title: string;
43
53
  /** Set at a decision step: its outcomes in declaration order (#42). */
44
54
  decision?: WorkflowDecisionForm;
55
+ /** The approver the viewer decides for as their delegate; null for their own approval. */
56
+ onBehalfOf?: {
57
+ id: number;
58
+ name: string | null;
59
+ } | null;
45
60
  } | null;
61
+ /** The current step's SLA deadline while the run waits on approvers; null without one. */
62
+ sla?: WorkflowSlaStatus | null;
46
63
  };
47
64
  /** What an approver needs to take a decision at a decision step. */
48
65
  export type WorkflowDecisionForm = {
@@ -60,6 +77,11 @@ export type WorkflowOptions = {
60
77
  step: string;
61
78
  }) => void | Promise<void>;
62
79
  now?: () => Date;
80
+ /**
81
+ * The system time zone (IANA name, default UTC). Due dates (dueOn) and delegation
82
+ * ranges are calendar days in this zone (ADR 044).
83
+ */
84
+ timeZone?: string;
63
85
  };
64
86
  /**
65
87
  * Durable workflow engine over workflow_runs. Every step runs inside the run's
@@ -75,9 +97,7 @@ export declare class WorkflowEngine {
75
97
  private actors;
76
98
  private assignments;
77
99
  private options;
78
- constructor(db: Knex, registry: ResourceRegistry, resources: ResourceService, actors: {
79
- load(id: number): Promise<Actor>;
80
- }, assignments: Assignments, definitions: readonly WorkflowDefinition[], options?: WorkflowOptions);
100
+ constructor(db: Knex, registry: ResourceRegistry, resources: ResourceService, actors: ActorLoader, assignments: Assignments, definitions: readonly WorkflowDefinition[], options?: WorkflowOptions);
81
101
  register(definition: WorkflowDefinition): this;
82
102
  /** The newest version of each workflow attached to a resource. */
83
103
  private latestFor;
@@ -102,6 +122,21 @@ export declare class WorkflowEngine {
102
122
  decide(runId: string, actor: Actor, decision: string, comment?: unknown): Promise<WorkflowRun>;
103
123
  /** Administrators put a failed run back to its failed step. */
104
124
  retry(runId: string, actorId: number): Promise<void>;
125
+ /**
126
+ * One pass of the `sla:` job family (ADR 044). Approvers whose deadline is near get one
127
+ * reminder; overdue approvals run their step's escalation policy once: mark overdue
128
+ * (tell the approvers), notify a target, or reassign to it. Every action happens under
129
+ * the run's row lock and is recorded in workflow_escalations, whose unique key per
130
+ * assignment and level makes a repeated or concurrent pass a no-op.
131
+ */
132
+ evaluateSla(options?: {
133
+ limit?: number;
134
+ }): Promise<SlaEvaluation>;
135
+ private remind;
136
+ private escalate;
137
+ /** Records one SLA action per assignment and level; false when it was already recorded. */
138
+ private record;
139
+ private notifyDeadline;
105
140
  /**
106
141
  * Explicit version migration for runs that have not finished: `mapStep` returns
107
142
  * the equivalent step name in the new version.
@@ -124,14 +159,55 @@ export declare class WorkflowEngine {
124
159
  private fail;
125
160
  private cancelRuns;
126
161
  private context;
127
- /** Workflow writes are system writes attributed to the submitter, with history. */
162
+ /**
163
+ * Workflow writes are system writes attributed to the submitter, with history. They go
164
+ * through systemSave, so the resource validator, hooks, relation checks and the
165
+ * optimistic lock apply; a rejected write fails the step like any other step error.
166
+ */
128
167
  private updateRecord;
129
168
  private cancelDocument;
130
169
  private recipients;
131
170
  /** A role reference is its stable key; for compatibility a display name also matches. */
132
171
  private roleId;
172
+ /** permits() on a given connection: denial (403/404) is false, other errors propagate. */
173
+ private viewable;
174
+ /**
175
+ * Whether a user may view the run's record, read on `db`. Callers inside a transaction
176
+ * pass it: a second pool connection while the run is locked lets concurrent decisions,
177
+ * submissions and worker passes exhaust the pool.
178
+ */
133
179
  private canView;
134
180
  private log;
181
+ /**
182
+ * Opens one approval per approver. An approver with a delegation in force today is
183
+ * replaced by the delegate when the delegate may view the record (ADR 044); the row
184
+ * keeps the approver in on_behalf_of, so both see it while the delegation lasts.
185
+ * Returns the routed pairs for the run log.
186
+ */
187
+ private openApprovals;
188
+ /** The SLA deadline of a step opening now, or null when the step declares none. */
189
+ private deadline;
190
+ private escalationTargets;
191
+ /**
192
+ * The approver's managers in the org tree: active holders of the role whose role is
193
+ * scoped to the approver's unit or, failing that, to the nearest ancestor unit.
194
+ */
195
+ private managers;
196
+ /**
197
+ * The delegate an approver's approvals go to today, or null to keep them with the
198
+ * approver (ADR 044). Routing is one hop and only to someone who can act: never the
199
+ * person who started the run (no self-approval), never a delegate who is away and
200
+ * delegating in turn, and never a delegate who cannot view the record.
201
+ */
202
+ private delegateFor;
203
+ /**
204
+ * Who is told about an open approval now: the delegate it was routed to while that
205
+ * delegation lasts; otherwise its approver, or the approver's current delegate when
206
+ * the approver is away today.
207
+ */
208
+ private holder;
209
+ private userName;
210
+ private today;
135
211
  private now;
136
212
  }
137
213
  /**