@facilis.dev/nitro 0.0.0-stage → 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 (267) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -2
  3. package/dist/config.d.ts +30 -0
  4. package/dist/config.js +112 -0
  5. package/dist/constants.d.ts +24 -0
  6. package/dist/constants.js +24 -0
  7. package/dist/facade.d.ts +37 -0
  8. package/dist/facade.js +121 -0
  9. package/dist/index.d.ts +17 -0
  10. package/dist/index.js +14 -0
  11. package/dist/middleware/context.d.ts +5 -0
  12. package/dist/middleware/context.js +86 -0
  13. package/dist/middleware/cors.d.ts +10 -0
  14. package/dist/middleware/cors.js +34 -0
  15. package/dist/middleware/session.d.ts +9 -0
  16. package/dist/middleware/session.js +18 -0
  17. package/dist/module.d.ts +7 -0
  18. package/dist/module.js +234 -0
  19. package/dist/rolldown-parser.d.ts +3 -0
  20. package/dist/rolldown-parser.js +66 -0
  21. package/dist/route-metadata.d.ts +22 -0
  22. package/dist/route-metadata.js +161 -0
  23. package/dist/routes/dev-query.post.d.ts +10 -0
  24. package/dist/routes/dev-query.post.js +49 -0
  25. package/dist/routes/dev-schema.get.d.ts +9 -0
  26. package/dist/routes/dev-schema.get.js +34 -0
  27. package/dist/routes/dev-view.post.d.ts +11 -0
  28. package/dist/routes/dev-view.post.js +61 -0
  29. package/dist/routes/health.get.d.ts +8 -0
  30. package/dist/routes/health.get.js +18 -0
  31. package/dist/routes/manifest-revision.get.d.ts +8 -0
  32. package/dist/routes/manifest-revision.get.js +26 -0
  33. package/dist/routes/manifest.get.d.ts +8 -0
  34. package/dist/routes/manifest.get.js +68 -0
  35. package/dist/routes/openapi.get.d.ts +8 -0
  36. package/dist/routes/openapi.get.js +29 -0
  37. package/dist/routes/sso.d.ts +2 -0
  38. package/dist/routes/sso.js +216 -0
  39. package/dist/routes/token.post.d.ts +10 -0
  40. package/dist/routes/token.post.js +75 -0
  41. package/dist/runtime/boot-runtimes.d.ts +21 -0
  42. package/dist/runtime/boot-runtimes.js +38 -0
  43. package/dist/runtime/bootstrap.d.ts +47 -0
  44. package/dist/runtime/bootstrap.js +214 -0
  45. package/dist/runtime/config.d.ts +27 -0
  46. package/dist/runtime/config.js +44 -0
  47. package/dist/runtime/cors-policy.d.ts +16 -0
  48. package/dist/runtime/cors-policy.js +88 -0
  49. package/dist/runtime/db-bootstrap.d.ts +9 -0
  50. package/dist/runtime/db-bootstrap.js +87 -0
  51. package/dist/runtime/db-target.d.ts +21 -0
  52. package/dist/runtime/db-target.js +52 -0
  53. package/dist/runtime/dev-db-persistence.d.ts +39 -0
  54. package/dist/runtime/dev-db-persistence.js +124 -0
  55. package/dist/runtime/dev-query.d.ts +38 -0
  56. package/dist/runtime/dev-query.js +87 -0
  57. package/dist/runtime/env.d.ts +9 -0
  58. package/dist/runtime/env.js +14 -0
  59. package/dist/runtime/http-guard.d.ts +16 -0
  60. package/dist/runtime/http-guard.js +42 -0
  61. package/dist/runtime/http.d.ts +11 -0
  62. package/dist/runtime/http.js +18 -0
  63. package/dist/runtime/jobs/boot.d.ts +20 -0
  64. package/dist/runtime/jobs/boot.js +77 -0
  65. package/dist/runtime/jobs/contracts.d.ts +161 -0
  66. package/dist/runtime/jobs/contracts.js +1 -0
  67. package/dist/runtime/jobs/db-store.d.ts +21 -0
  68. package/dist/runtime/jobs/db-store.js +210 -0
  69. package/dist/runtime/jobs/definitions.d.ts +14 -0
  70. package/dist/runtime/jobs/definitions.js +31 -0
  71. package/dist/runtime/jobs/engine-support.d.ts +22 -0
  72. package/dist/runtime/jobs/engine-support.js +32 -0
  73. package/dist/runtime/jobs/engine.d.ts +6 -0
  74. package/dist/runtime/jobs/engine.js +261 -0
  75. package/dist/runtime/jobs/executor.d.ts +11 -0
  76. package/dist/runtime/jobs/executor.js +27 -0
  77. package/dist/runtime/jobs/memory-store.d.ts +7 -0
  78. package/dist/runtime/jobs/memory-store.js +183 -0
  79. package/dist/runtime/jobs/row-mapping.d.ts +28 -0
  80. package/dist/runtime/jobs/row-mapping.js +61 -0
  81. package/dist/runtime/jobs/runtime.d.ts +24 -0
  82. package/dist/runtime/jobs/runtime.js +86 -0
  83. package/dist/runtime/logging/audit-chain.d.ts +54 -0
  84. package/dist/runtime/logging/audit-chain.js +102 -0
  85. package/dist/runtime/logging/bootstrap-logging.d.ts +28 -0
  86. package/dist/runtime/logging/bootstrap-logging.js +26 -0
  87. package/dist/runtime/logging/entry.d.ts +14 -0
  88. package/dist/runtime/logging/entry.js +85 -0
  89. package/dist/runtime/logging/file-sink.d.ts +24 -0
  90. package/dist/runtime/logging/file-sink.js +128 -0
  91. package/dist/runtime/logging/log-settings.d.ts +52 -0
  92. package/dist/runtime/logging/log-settings.js +93 -0
  93. package/dist/runtime/logging/log-sink.d.ts +18 -0
  94. package/dist/runtime/logging/log-sink.js +22 -0
  95. package/dist/runtime/logging/redact.d.ts +31 -0
  96. package/dist/runtime/logging/redact.js +106 -0
  97. package/dist/runtime/logging/runtime.d.ts +25 -0
  98. package/dist/runtime/logging/runtime.js +114 -0
  99. package/dist/runtime/logging/sudo-bridge.d.ts +13 -0
  100. package/dist/runtime/logging/sudo-bridge.js +38 -0
  101. package/dist/runtime/manifest-data.d.ts +28 -0
  102. package/dist/runtime/manifest-data.js +70 -0
  103. package/dist/runtime/manifest-response.d.ts +45 -0
  104. package/dist/runtime/manifest-response.js +50 -0
  105. package/dist/runtime/manifest-sections.d.ts +20 -0
  106. package/dist/runtime/manifest-sections.js +59 -0
  107. package/dist/runtime/manifest-service.d.ts +16 -0
  108. package/dist/runtime/manifest-service.js +66 -0
  109. package/dist/runtime/project-config.d.ts +8 -0
  110. package/dist/runtime/project-config.js +22 -0
  111. package/dist/runtime/project-files.d.ts +12 -0
  112. package/dist/runtime/project-files.js +99 -0
  113. package/dist/runtime/rate-limit.d.ts +6 -0
  114. package/dist/runtime/rate-limit.js +6 -0
  115. package/dist/runtime/revision-service.d.ts +15 -0
  116. package/dist/runtime/revision-service.js +26 -0
  117. package/dist/runtime/sql.d.ts +8 -0
  118. package/dist/runtime/sql.js +23 -0
  119. package/dist/runtime/sso.d.ts +40 -0
  120. package/dist/runtime/sso.js +98 -0
  121. package/dist/runtime/state.d.ts +7 -0
  122. package/dist/runtime/state.js +7 -0
  123. package/dist/runtime/storage-keys.d.ts +9 -0
  124. package/dist/runtime/storage-keys.js +82 -0
  125. package/dist/runtime/storage-target.d.ts +25 -0
  126. package/dist/runtime/storage-target.js +155 -0
  127. package/dist/runtime/system-role.d.ts +9 -0
  128. package/dist/runtime/system-role.js +21 -0
  129. package/dist/runtime/tasks/boot.d.ts +20 -0
  130. package/dist/runtime/tasks/boot.js +32 -0
  131. package/dist/runtime/tasks/contracts.d.ts +70 -0
  132. package/dist/runtime/tasks/contracts.js +1 -0
  133. package/dist/runtime/tasks/db-store.d.ts +18 -0
  134. package/dist/runtime/tasks/db-store.js +139 -0
  135. package/dist/runtime/tasks/row-mapping.d.ts +11 -0
  136. package/dist/runtime/tasks/row-mapping.js +69 -0
  137. package/dist/runtime/tasks/runtime.d.ts +7 -0
  138. package/dist/runtime/tasks/runtime.js +162 -0
  139. package/dist/runtime/tasks/tasks-test-harness.d.ts +16 -0
  140. package/dist/runtime/tasks/tasks-test-harness.js +70 -0
  141. package/dist/runtime/tenant.d.ts +10 -0
  142. package/dist/runtime/tenant.js +13 -0
  143. package/dist/runtime/workflows/boot.d.ts +25 -0
  144. package/dist/runtime/workflows/boot.js +75 -0
  145. package/dist/runtime/workflows/contracts.d.ts +96 -0
  146. package/dist/runtime/workflows/contracts.js +1 -0
  147. package/dist/runtime/workflows/db-store.d.ts +18 -0
  148. package/dist/runtime/workflows/db-store.js +128 -0
  149. package/dist/runtime/workflows/definitions.d.ts +14 -0
  150. package/dist/runtime/workflows/definitions.js +50 -0
  151. package/dist/runtime/workflows/dispatch.d.ts +4 -0
  152. package/dist/runtime/workflows/dispatch.js +119 -0
  153. package/dist/runtime/workflows/row-mapping.d.ts +5 -0
  154. package/dist/runtime/workflows/row-mapping.js +38 -0
  155. package/dist/runtime/workflows/runner.d.ts +15 -0
  156. package/dist/runtime/workflows/runner.js +89 -0
  157. package/dist/runtime/workflows/runtime.d.ts +14 -0
  158. package/dist/runtime/workflows/runtime.js +129 -0
  159. package/dist/runtime/workflows/steps.d.ts +14 -0
  160. package/dist/runtime/workflows/steps.js +49 -0
  161. package/dist/runtime/workflows/support.d.ts +20 -0
  162. package/dist/runtime/workflows/support.js +36 -0
  163. package/dist/runtime/workflows/transitions.d.ts +8 -0
  164. package/dist/runtime/workflows/transitions.js +184 -0
  165. package/dist/runtime/workflows/workflows-test-harness.d.ts +62 -0
  166. package/dist/runtime/workflows/workflows-test-harness.js +178 -0
  167. package/dist/session-cookie.d.ts +13 -0
  168. package/dist/session-cookie.js +48 -0
  169. package/dist/storage.d.ts +50 -0
  170. package/dist/storage.js +118 -0
  171. package/dist/types.d.ts +44 -0
  172. package/dist/types.js +1 -0
  173. package/dist/virtual-ids.d.ts +17 -0
  174. package/dist/virtual-ids.js +17 -0
  175. package/dist/vite.d.ts +22 -0
  176. package/dist/vite.js +135 -0
  177. package/package.json +61 -4
  178. package/src/config.ts +120 -0
  179. package/src/constants.ts +24 -0
  180. package/src/facade.ts +153 -0
  181. package/src/index.ts +44 -0
  182. package/src/middleware/context.ts +106 -0
  183. package/src/middleware/cors.ts +42 -0
  184. package/src/middleware/session.ts +23 -0
  185. package/src/module.ts +278 -0
  186. package/src/rolldown-parser.ts +79 -0
  187. package/src/route-metadata-test-harness.ts +62 -0
  188. package/src/route-metadata.ts +194 -0
  189. package/src/routes/dev-query.post.ts +53 -0
  190. package/src/routes/dev-schema.get.ts +43 -0
  191. package/src/routes/dev-view.post.ts +66 -0
  192. package/src/routes/health.get.ts +26 -0
  193. package/src/routes/manifest-revision.get.ts +38 -0
  194. package/src/routes/manifest.get.ts +111 -0
  195. package/src/routes/openapi.get.ts +34 -0
  196. package/src/routes/sso.ts +247 -0
  197. package/src/routes/token.post.ts +89 -0
  198. package/src/runtime/boot-runtimes.ts +69 -0
  199. package/src/runtime/bootstrap.ts +300 -0
  200. package/src/runtime/config.ts +60 -0
  201. package/src/runtime/cors-policy.ts +107 -0
  202. package/src/runtime/db-bootstrap.ts +99 -0
  203. package/src/runtime/db-target.ts +87 -0
  204. package/src/runtime/dev-db-persistence.ts +146 -0
  205. package/src/runtime/dev-query.ts +124 -0
  206. package/src/runtime/env.ts +18 -0
  207. package/src/runtime/http-guard.ts +50 -0
  208. package/src/runtime/http.ts +30 -0
  209. package/src/runtime/jobs/boot.ts +97 -0
  210. package/src/runtime/jobs/contracts.ts +165 -0
  211. package/src/runtime/jobs/db-store-test-harness.ts +98 -0
  212. package/src/runtime/jobs/db-store.ts +273 -0
  213. package/src/runtime/jobs/definitions.ts +42 -0
  214. package/src/runtime/jobs/engine-support.ts +44 -0
  215. package/src/runtime/jobs/engine.ts +296 -0
  216. package/src/runtime/jobs/executor.ts +37 -0
  217. package/src/runtime/jobs/memory-store.ts +222 -0
  218. package/src/runtime/jobs/row-mapping.ts +67 -0
  219. package/src/runtime/jobs/runtime.ts +110 -0
  220. package/src/runtime/logging/audit-chain.ts +135 -0
  221. package/src/runtime/logging/bootstrap-logging.ts +62 -0
  222. package/src/runtime/logging/entry.ts +99 -0
  223. package/src/runtime/logging/file-sink.ts +157 -0
  224. package/src/runtime/logging/log-settings.ts +166 -0
  225. package/src/runtime/logging/log-sink.ts +31 -0
  226. package/src/runtime/logging/redact.ts +108 -0
  227. package/src/runtime/logging/runtime.ts +163 -0
  228. package/src/runtime/logging/sudo-bridge.ts +41 -0
  229. package/src/runtime/manifest-data.ts +103 -0
  230. package/src/runtime/manifest-response.ts +95 -0
  231. package/src/runtime/manifest-sections.ts +79 -0
  232. package/src/runtime/manifest-service.ts +83 -0
  233. package/src/runtime/project-config.ts +25 -0
  234. package/src/runtime/project-files.ts +103 -0
  235. package/src/runtime/rate-limit.ts +12 -0
  236. package/src/runtime/revision-service.ts +38 -0
  237. package/src/runtime/sql.ts +24 -0
  238. package/src/runtime/sso.ts +153 -0
  239. package/src/runtime/state.ts +7 -0
  240. package/src/runtime/storage-keys.ts +95 -0
  241. package/src/runtime/storage-target.ts +238 -0
  242. package/src/runtime/system-role.ts +26 -0
  243. package/src/runtime/tasks/boot.ts +49 -0
  244. package/src/runtime/tasks/contracts.ts +77 -0
  245. package/src/runtime/tasks/db-store.ts +191 -0
  246. package/src/runtime/tasks/row-mapping.ts +75 -0
  247. package/src/runtime/tasks/runtime.ts +192 -0
  248. package/src/runtime/tasks/tasks-test-harness.ts +92 -0
  249. package/src/runtime/tenant.ts +15 -0
  250. package/src/runtime/workflows/boot.ts +97 -0
  251. package/src/runtime/workflows/contracts.ts +114 -0
  252. package/src/runtime/workflows/db-store.ts +156 -0
  253. package/src/runtime/workflows/definitions.ts +75 -0
  254. package/src/runtime/workflows/dispatch.ts +148 -0
  255. package/src/runtime/workflows/row-mapping.ts +54 -0
  256. package/src/runtime/workflows/runner.ts +105 -0
  257. package/src/runtime/workflows/runtime.ts +161 -0
  258. package/src/runtime/workflows/steps.ts +74 -0
  259. package/src/runtime/workflows/support.ts +60 -0
  260. package/src/runtime/workflows/transitions.ts +259 -0
  261. package/src/runtime/workflows/workflows-test-harness.ts +238 -0
  262. package/src/session-cookie.ts +69 -0
  263. package/src/storage.ts +173 -0
  264. package/src/types.ts +51 -0
  265. package/src/virtual-ids.ts +18 -0
  266. package/src/virtual-modules.d.ts +53 -0
  267. package/src/vite.ts +175 -0
@@ -0,0 +1,70 @@
1
+ import type { PolicyScopedDatabase } from "@facilis.dev/db";
2
+ import type { JobJson, TaskDecision, TaskKind, TaskStatus } from "@facilis.dev/core";
3
+ /** One task as the store sees it: JSON data plus real Dates (the API ISO-izes them). */
4
+ export interface StoredTask {
5
+ readonly id: string;
6
+ readonly workflowId: string | null;
7
+ readonly stepIndex: number | null;
8
+ readonly kind: TaskKind;
9
+ readonly status: TaskStatus;
10
+ readonly decision: TaskDecision | null;
11
+ readonly titleKey: string;
12
+ readonly titleParams: JobJson;
13
+ readonly payload: JobJson | null;
14
+ readonly requestedBy: string | null;
15
+ readonly assignedPermission: string | null;
16
+ readonly expiresAt: Date | null;
17
+ readonly decidedBy: string | null;
18
+ readonly decidedAt: Date | null;
19
+ readonly comment: string | null;
20
+ readonly createdAt: Date;
21
+ }
22
+ /** What the API writes for a new task; status/decision belong to the store. */
23
+ export interface NewStoredTask {
24
+ readonly id: string;
25
+ readonly workflowId: string | null;
26
+ readonly stepIndex: number | null;
27
+ readonly kind: TaskKind;
28
+ readonly titleKey: string;
29
+ readonly titleParams: JobJson;
30
+ readonly payload: JobJson | null;
31
+ readonly requestedBy: string | null;
32
+ readonly assignedPermission: string | null;
33
+ readonly expiresAt: Date | null;
34
+ readonly createdAt: Date;
35
+ }
36
+ export interface TaskListFilters {
37
+ readonly status?: TaskStatus | readonly TaskStatus[];
38
+ readonly workflowId?: string;
39
+ readonly assignedPermission?: string;
40
+ /** Already normalised by the API (default 50, max 200). */
41
+ readonly limit: number;
42
+ }
43
+ /** A decision write: decider, instant and comment land atomically with the status change. */
44
+ export interface TaskDecisionWrite {
45
+ readonly decision: TaskDecision;
46
+ readonly decidedBy: string | null;
47
+ readonly comment: string | null;
48
+ readonly now: Date;
49
+ }
50
+ export interface TaskStore {
51
+ insert(task: NewStoredTask): Promise<void>;
52
+ get(id: string): Promise<StoredTask | null>;
53
+ list(filters: TaskListFilters): Promise<StoredTask[]>;
54
+ /**
55
+ * Marks up to `limit` due pending tasks expired and returns them: the workflow runner
56
+ * fails the chains waiting on them (docs/WORKFLOWS.md §8.1).
57
+ */
58
+ expireDue(now: Date, limit: number): Promise<StoredTask[]>;
59
+ /** pending -> decided when the row is still pending and not expired; null otherwise. */
60
+ decide(id: string, write: TaskDecisionWrite): Promise<StoredTask | null>;
61
+ /** pending -> expired (lazy expiry, called by decide); false when the row is not pending. */
62
+ expire(id: string, now: Date): Promise<boolean>;
63
+ /** pending -> cancelled; false when the row is no longer pending. */
64
+ cancel(id: string, now: Date): Promise<boolean>;
65
+ /**
66
+ * Optional view whose operations join the request's policy transaction instead of opening
67
+ * a new one: PGlite is single-connection, so a nested BEGIN would deadlock (D-107, JOBS §8).
68
+ */
69
+ scoped?(scope: PolicyScopedDatabase): TaskStore;
70
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ import type { FacilisDb, PolicyScopedDatabase } from "@facilis.dev/db";
2
+ import type { TaskStore } from "./contracts.js";
3
+ /**
4
+ * The persistent TaskStore over facilis_tasks. A missing table is not handled here: boot
5
+ * probes it with isTasksTableAvailable and disables the API instead (D-135: no memory mode),
6
+ * so these methods may throw when the project is not migrated.
7
+ */
8
+ export declare function createDbTaskStore(options: {
9
+ readonly db: FacilisDb;
10
+ readonly tenantId: string;
11
+ /** Request transaction to join (from TaskStore.scoped); absent for runtime-owned work. */
12
+ readonly scope?: PolicyScopedDatabase;
13
+ }): TaskStore;
14
+ /**
15
+ * Probe used by boot: to_regclass answers null for a missing table instead of raising, which
16
+ * is exactly the "project not migrated yet" case (D-135).
17
+ */
18
+ export declare function isTasksTableAvailable(db: FacilisDb): Promise<boolean>;
@@ -0,0 +1,139 @@
1
+ // The Drizzle-backed task store (D-135, docs/WORKFLOWS.md §7).
2
+ //
3
+ // Every operation runs through runWithPolicyScope, i.e. as facilis_app with app.tenant_id
4
+ // set: a new row's tenant_id comes from the tenantColumn default (the same GUC the
5
+ // restrictive policy reads), and a query cannot reach another tenant's tasks. The workflow
6
+ // runner (W2) reuses this store; only the actor differs.
7
+ import { and, asc, eq, gt, inArray, isNull, lte, or, sql } from "drizzle-orm";
8
+ import { facilisTasks, runWithPolicyScope } from "@facilis.dev/db";
9
+ import { toStoredTask } from "./row-mapping.js";
10
+ /**
11
+ * The persistent TaskStore over facilis_tasks. A missing table is not handled here: boot
12
+ * probes it with isTasksTableAvailable and disables the API instead (D-135: no memory mode),
13
+ * so these methods may throw when the project is not migrated.
14
+ */
15
+ export function createDbTaskStore(options) {
16
+ const { db, tenantId, scope } = options;
17
+ // One policy-scoped transaction per operation; when a scope is bound (a handler's
18
+ // ctx.tasks), the operation joins that request transaction instead (D-135, JOBS §8).
19
+ function run(fn) {
20
+ return scope === undefined ? runWithPolicyScope(db, { tenantId }, fn) : fn(scope);
21
+ }
22
+ return {
23
+ async insert(task) {
24
+ await run((tx) => tx.insert(facilisTasks).values({
25
+ id: task.id,
26
+ workflowId: task.workflowId,
27
+ stepIndex: task.stepIndex,
28
+ kind: task.kind,
29
+ status: "pending",
30
+ titleKey: task.titleKey,
31
+ titleParams: task.titleParams,
32
+ payload: task.payload,
33
+ requestedBy: task.requestedBy,
34
+ assignedPermission: task.assignedPermission,
35
+ expiresAt: task.expiresAt,
36
+ createdAt: task.createdAt,
37
+ }));
38
+ },
39
+ async get(id) {
40
+ return run(async (tx) => {
41
+ const rows = await tx.select().from(facilisTasks).where(eq(facilisTasks.id, id)).limit(1);
42
+ const row = rows[0];
43
+ return row === undefined ? null : toStoredTask(row);
44
+ });
45
+ },
46
+ async list(filters) {
47
+ return run(async (tx) => {
48
+ const conditions = [];
49
+ if (filters.status !== undefined) {
50
+ conditions.push(typeof filters.status === "string"
51
+ ? eq(facilisTasks.status, filters.status)
52
+ : inArray(facilisTasks.status, [...filters.status]));
53
+ }
54
+ if (filters.workflowId !== undefined) {
55
+ conditions.push(eq(facilisTasks.workflowId, filters.workflowId));
56
+ }
57
+ if (filters.assignedPermission !== undefined) {
58
+ conditions.push(eq(facilisTasks.assignedPermission, filters.assignedPermission));
59
+ }
60
+ const rows = await tx
61
+ .select()
62
+ .from(facilisTasks)
63
+ .where(conditions.length === 0 ? undefined : and(...conditions))
64
+ // FIFO: the inbox shows the oldest pending request first.
65
+ .orderBy(asc(facilisTasks.createdAt))
66
+ .limit(filters.limit);
67
+ return rows.map(toStoredTask);
68
+ });
69
+ },
70
+ async decide(id, write) {
71
+ return run(async (tx) => {
72
+ const rows = await tx
73
+ .update(facilisTasks)
74
+ .set({
75
+ status: "decided",
76
+ decision: write.decision,
77
+ decidedBy: write.decidedBy,
78
+ decidedAt: write.now,
79
+ comment: write.comment,
80
+ })
81
+ // Compare-and-set: only the first decider wins, and an expired row cannot be decided.
82
+ .where(and(eq(facilisTasks.id, id), eq(facilisTasks.status, "pending"), or(isNull(facilisTasks.expiresAt), gt(facilisTasks.expiresAt, write.now))))
83
+ .returning();
84
+ const row = rows[0];
85
+ return row === undefined ? null : toStoredTask(row);
86
+ });
87
+ },
88
+ async expireDue(now, limit) {
89
+ return run(async (tx) => {
90
+ const due = await tx
91
+ .select({ id: facilisTasks.id })
92
+ .from(facilisTasks)
93
+ .where(and(eq(facilisTasks.status, "pending"), lte(facilisTasks.expiresAt, now)))
94
+ .orderBy(asc(facilisTasks.createdAt))
95
+ .limit(limit);
96
+ if (due.length === 0)
97
+ return [];
98
+ const rows = await tx
99
+ .update(facilisTasks)
100
+ .set({ status: "expired" })
101
+ .where(and(eq(facilisTasks.status, "pending"), lte(facilisTasks.expiresAt, now), inArray(facilisTasks.id, due.map((row) => row.id))))
102
+ .returning();
103
+ return rows.map(toStoredTask);
104
+ });
105
+ },
106
+ async expire(id, now) {
107
+ return run(async (tx) => {
108
+ const rows = await tx
109
+ .update(facilisTasks)
110
+ .set({ status: "expired" })
111
+ .where(and(eq(facilisTasks.id, id), eq(facilisTasks.status, "pending"), lte(facilisTasks.expiresAt, now)))
112
+ .returning({ id: facilisTasks.id });
113
+ return rows.length > 0;
114
+ });
115
+ },
116
+ async cancel(id, _now) {
117
+ return run(async (tx) => {
118
+ const rows = await tx
119
+ .update(facilisTasks)
120
+ .set({ status: "cancelled" })
121
+ .where(and(eq(facilisTasks.id, id), eq(facilisTasks.status, "pending")))
122
+ .returning({ id: facilisTasks.id });
123
+ return rows.length > 0;
124
+ });
125
+ },
126
+ /** Joins task operations to an existing request transaction (see run above). */
127
+ scoped(next) {
128
+ return createDbTaskStore({ db, tenantId, scope: next });
129
+ },
130
+ };
131
+ }
132
+ /**
133
+ * Probe used by boot: to_regclass answers null for a missing table instead of raising, which
134
+ * is exactly the "project not migrated yet" case (D-135).
135
+ */
136
+ export async function isTasksTableAvailable(db) {
137
+ const result = await db.db.execute(sql `select to_regclass('public.facilis_tasks') is not null as available`);
138
+ return result.rows[0]?.["available"] === true;
139
+ }
@@ -0,0 +1,11 @@
1
+ import type { TaskDecision, TaskKind, TaskRecord, TaskStatus } from "@facilis.dev/core";
2
+ import type { FacilisTaskRow } from "@facilis.dev/db";
3
+ import type { StoredTask } from "./contracts.js";
4
+ /** Maps a row to the store contract; JSONB columns are TaskJson by construction. */
5
+ export declare function toStoredTask(row: FacilisTaskRow): StoredTask;
6
+ /** The API record: JSON-friendly timestamps, JSON data. */
7
+ export declare function toTaskRecord(task: StoredTask): TaskRecord;
8
+ /** Narrows the text status column; an unknown value is corrupt row data, not a task. */
9
+ export declare function toTaskStatus(value: string): TaskStatus;
10
+ export declare function toTaskKind(value: string): TaskKind;
11
+ export declare function toTaskDecision(value: string): TaskDecision;
@@ -0,0 +1,69 @@
1
+ // Row <-> store-contract mapping for manual tasks (D-135).
2
+ //
3
+ // Kept apart from db-store.ts so each file stays well under the 300-line limit and the text
4
+ // status/decision columns are decoded in exactly one place.
5
+ import { TASK_DECISIONS, TASK_KINDS, TASK_STATUSES } from "@facilis.dev/core";
6
+ /** Maps a row to the store contract; JSONB columns are TaskJson by construction. */
7
+ export function toStoredTask(row) {
8
+ return {
9
+ id: row.id,
10
+ workflowId: row.workflowId,
11
+ stepIndex: row.stepIndex,
12
+ kind: toTaskKind(row.kind),
13
+ status: toTaskStatus(row.status),
14
+ decision: row.decision === null ? null : toTaskDecision(row.decision),
15
+ titleKey: row.titleKey,
16
+ titleParams: row.titleParams,
17
+ payload: (row.payload ?? null),
18
+ requestedBy: row.requestedBy,
19
+ assignedPermission: row.assignedPermission,
20
+ expiresAt: row.expiresAt,
21
+ decidedBy: row.decidedBy,
22
+ decidedAt: row.decidedAt,
23
+ comment: row.comment,
24
+ createdAt: row.createdAt,
25
+ };
26
+ }
27
+ /** The API record: JSON-friendly timestamps, JSON data. */
28
+ export function toTaskRecord(task) {
29
+ return {
30
+ id: task.id,
31
+ workflowId: task.workflowId,
32
+ stepIndex: task.stepIndex,
33
+ kind: task.kind,
34
+ status: task.status,
35
+ decision: task.decision,
36
+ titleKey: task.titleKey,
37
+ titleParams: task.titleParams,
38
+ payload: task.payload,
39
+ requestedBy: task.requestedBy,
40
+ assignedPermission: task.assignedPermission,
41
+ expiresAt: task.expiresAt === null ? null : task.expiresAt.toISOString(),
42
+ decidedBy: task.decidedBy,
43
+ decidedAt: task.decidedAt === null ? null : task.decidedAt.toISOString(),
44
+ comment: task.comment,
45
+ createdAt: task.createdAt.toISOString(),
46
+ };
47
+ }
48
+ /** Narrows the text status column; an unknown value is corrupt row data, not a task. */
49
+ export function toTaskStatus(value) {
50
+ for (const status of TASK_STATUSES) {
51
+ if (status === value)
52
+ return status;
53
+ }
54
+ throw new Error('facilis_tasks: unknown status "' + value + '"');
55
+ }
56
+ export function toTaskKind(value) {
57
+ for (const kind of TASK_KINDS) {
58
+ if (kind === value)
59
+ return kind;
60
+ }
61
+ throw new Error('facilis_tasks: unknown kind "' + value + '"');
62
+ }
63
+ export function toTaskDecision(value) {
64
+ for (const decision of TASK_DECISIONS) {
65
+ if (decision === value)
66
+ return decision;
67
+ }
68
+ throw new Error('facilis_tasks: unknown decision "' + value + '"');
69
+ }
@@ -0,0 +1,7 @@
1
+ import type { TaskActorContext, TasksApi } from "@facilis.dev/core";
2
+ import type { TaskStore } from "./contracts.js";
3
+ /**
4
+ * Adapts a TaskStore to the handler-facing API. The actor is the session user id (or null
5
+ * for a system-created task); bindScope re-binds both the transaction and the actor.
6
+ */
7
+ export declare function createTasksApi(store: TaskStore, context?: TaskActorContext): TasksApi;
@@ -0,0 +1,162 @@
1
+ // The server-only task API (D-135, docs/WORKFLOWS.md §7).
2
+ //
3
+ // Validation, JSON serialization and error classification live here; the store only knows
4
+ // rows. A decision is a compare-and-set on the task row: who decided, when and with what
5
+ // comment are recorded in one atomic write, and the decider's identity comes from the
6
+ // request context bound by the route wrapper, never from the request body.
7
+ import { randomUUID } from "node:crypto";
8
+ import { TaskError, serializeTaskData } from "@facilis.dev/core";
9
+ import { toTaskRecord } from "./row-mapping.js";
10
+ const DEFAULT_LIMIT = 50;
11
+ const MAX_LIMIT = 200;
12
+ const MAX_TITLE_KEY_LENGTH = 200;
13
+ const MAX_COMMENT_LENGTH = 1000;
14
+ const TITLE_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
15
+ const PERMISSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9:_-]*$/;
16
+ const MAX_PERMISSION_LENGTH = 100;
17
+ /**
18
+ * Adapts a TaskStore to the handler-facing API. The actor is the session user id (or null
19
+ * for a system-created task); bindScope re-binds both the transaction and the actor.
20
+ */
21
+ export function createTasksApi(store, context = { actor: null }) {
22
+ const api = {
23
+ async request(input) {
24
+ const task = normalizeTask(input, context.actor);
25
+ await store.insert(task);
26
+ const stored = await store.get(task.id);
27
+ if (stored === null)
28
+ throw new TaskError("task_not_found", "The task was not persisted.");
29
+ return toTaskRecord(stored);
30
+ },
31
+ async get(id) {
32
+ const task = await store.get(id);
33
+ return task === null ? null : toTaskRecord(task);
34
+ },
35
+ async list(options = {}) {
36
+ return (await store.list(normalizeFilters(options))).map(toTaskRecord);
37
+ },
38
+ async decide(id, decision) {
39
+ const kind = decision?.kind;
40
+ if (kind !== "approve" && kind !== "reject") {
41
+ throw invalid('decision.kind must be "approve" or "reject".');
42
+ }
43
+ const comment = normalizeComment(decision.comment);
44
+ const now = new Date();
45
+ const updated = await store.decide(id, {
46
+ decision: kind,
47
+ decidedBy: context.actor,
48
+ comment,
49
+ now,
50
+ });
51
+ if (updated !== null)
52
+ return toTaskRecord(updated);
53
+ // The CAS matched nothing: classify why, lazily expiring the row when its instant passed.
54
+ const row = await store.get(id);
55
+ if (row === null)
56
+ throw new TaskError("task_not_found", "Task " + id + " does not exist.");
57
+ if (row.status === "pending") {
58
+ if (row.expiresAt !== null && row.expiresAt.getTime() <= now.getTime()) {
59
+ await store.expire(id, now);
60
+ throw new TaskError("task_expired", "Task " + id + " expired before it was decided.");
61
+ }
62
+ // Another decider won the CAS between the read and the update.
63
+ throw new TaskError("task_already_decided", "Task " + id + " has already been decided.");
64
+ }
65
+ if (row.status === "expired") {
66
+ throw new TaskError("task_expired", "Task " + id + " expired before it was decided.");
67
+ }
68
+ throw new TaskError("task_already_decided", "Task " + id + " is no longer pending.");
69
+ },
70
+ cancel(id) {
71
+ return store.cancel(id, new Date());
72
+ },
73
+ };
74
+ // Framework plumbing: the handler's calls join its policy transaction and carry its actor.
75
+ api.bindScope = (scope, next) => createTasksApi(store.scoped?.(scope) ?? store, next);
76
+ return api;
77
+ }
78
+ function normalizeTask(input, actor) {
79
+ if (typeof input !== "object" || input === null) {
80
+ throw invalid("A task request must be an object.");
81
+ }
82
+ const titleKey = input.titleKey;
83
+ if (typeof titleKey !== "string" ||
84
+ titleKey.length === 0 ||
85
+ titleKey.length > MAX_TITLE_KEY_LENGTH ||
86
+ !TITLE_KEY_PATTERN.test(titleKey)) {
87
+ throw invalid("titleKey must be a flat i18n key (letters, digits, dot, dash, underscore).");
88
+ }
89
+ return {
90
+ id: randomUUID(),
91
+ workflowId: null,
92
+ stepIndex: null,
93
+ kind: "approval",
94
+ titleKey,
95
+ titleParams: normalizeTitleParams(input.titleParams),
96
+ payload: input.payload === undefined ? null : serializeTaskData(input.payload),
97
+ requestedBy: actor,
98
+ assignedPermission: normalizePermission(input.assignedPermission),
99
+ expiresAt: normalizeExpiresAt(input.expiresAt),
100
+ createdAt: new Date(),
101
+ };
102
+ }
103
+ function normalizeTitleParams(value) {
104
+ if (value === undefined)
105
+ return {};
106
+ const parsed = serializeTaskData(value);
107
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
108
+ throw invalid("titleParams must be a JSON object.");
109
+ }
110
+ return parsed;
111
+ }
112
+ function normalizePermission(value) {
113
+ if (value === undefined)
114
+ return null;
115
+ if (typeof value !== "string" ||
116
+ value.length === 0 ||
117
+ value.length > MAX_PERMISSION_LENGTH ||
118
+ !PERMISSION_PATTERN.test(value)) {
119
+ throw invalid("assignedPermission must be a permission name (letters, digits, colon, dash, underscore).");
120
+ }
121
+ return value;
122
+ }
123
+ function normalizeExpiresAt(value) {
124
+ if (value === undefined)
125
+ return null;
126
+ const instant = value instanceof Date ? value : new Date(value);
127
+ if (Number.isNaN(instant.getTime())) {
128
+ throw invalid("expiresAt is not a valid ISO-8601 instant.");
129
+ }
130
+ return instant;
131
+ }
132
+ function normalizeComment(value) {
133
+ if (value === undefined)
134
+ return null;
135
+ if (typeof value !== "string" || value.length > MAX_COMMENT_LENGTH) {
136
+ throw invalid("comment must be a string of at most 1000 characters.");
137
+ }
138
+ const trimmed = value.trim();
139
+ return trimmed.length === 0 ? null : trimmed;
140
+ }
141
+ function normalizeFilters(options) {
142
+ const status = options.status;
143
+ const workflowId = options.workflowId;
144
+ const assignedPermission = options.assignedPermission;
145
+ return {
146
+ ...(status === undefined ? {} : { status }),
147
+ ...(workflowId === undefined ? {} : { workflowId }),
148
+ ...(assignedPermission === undefined ? {} : { assignedPermission }),
149
+ limit: normalizeLimit(options.limit),
150
+ };
151
+ }
152
+ function normalizeLimit(value) {
153
+ if (value === undefined)
154
+ return DEFAULT_LIMIT;
155
+ if (!Number.isInteger(value) || value < 1) {
156
+ throw invalid("limit must be a positive integer.");
157
+ }
158
+ return Math.min(value, MAX_LIMIT);
159
+ }
160
+ function invalid(message) {
161
+ return new TaskError("task_invalid_input", message);
162
+ }
@@ -0,0 +1,16 @@
1
+ import type { FacilisDb } from "@facilis.dev/db";
2
+ import type { NewStoredTask } from "./contracts.js";
3
+ import { createDbTaskStore } from "./db-store.js";
4
+ /** Deployment tenant; a second tenant proves the RLS boundary cannot be crossed. */
5
+ export declare const TENANT_ID = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee";
6
+ export declare const OTHER_TENANT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
7
+ export declare const BASE: Date;
8
+ export declare const LATER: Date;
9
+ export interface TasksTestContext {
10
+ readonly db: FacilisDb;
11
+ readonly store: ReturnType<typeof createDbTaskStore>;
12
+ }
13
+ export declare function createTasksTestContext(): Promise<TasksTestContext>;
14
+ /** Empties the table as the connecting superuser, so each test starts from a clean slate. */
15
+ export declare function clearTasks(db: FacilisDb): Promise<void>;
16
+ export declare function newTask(overrides?: Partial<NewStoredTask>): NewStoredTask;
@@ -0,0 +1,70 @@
1
+ // Shared PGlite fixture for the manual-task store suite (D-135). It creates the real
2
+ // drizzle table definition, its policies and the tenant-column default, so the store is
3
+ // exercised through the same RLS boundary the runtime uses in dev.
4
+ import { randomUUID } from "node:crypto";
5
+ import { sql } from "drizzle-orm";
6
+ import { getTableConfig, PgDialect } from "drizzle-orm/pg-core";
7
+ import { createDb, ensureAppRole, facilisTasks, policyCreateSql, tenantDefaultSql, } from "@facilis.dev/db";
8
+ import { createDbTaskStore } from "./db-store.js";
9
+ /** Deployment tenant; a second tenant proves the RLS boundary cannot be crossed. */
10
+ export const TENANT_ID = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee";
11
+ export const OTHER_TENANT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
12
+ export const BASE = new Date("2026-11-10T12:00:00.000Z");
13
+ export const LATER = new Date("2026-11-10T12:30:00.000Z");
14
+ export async function createTasksTestContext() {
15
+ const db = await createDb();
16
+ const tenantDefault = new PgDialect().sqlToQuery(tenantDefaultSql()).sql;
17
+ const statements = [
18
+ `CREATE TABLE facilis_tasks (
19
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
20
+ workflow_id uuid,
21
+ step_index integer,
22
+ kind text NOT NULL,
23
+ status text NOT NULL,
24
+ decision text,
25
+ title_key text NOT NULL,
26
+ title_params jsonb NOT NULL DEFAULT '{}'::jsonb,
27
+ payload jsonb,
28
+ requested_by text,
29
+ assigned_permission text,
30
+ expires_at timestamptz,
31
+ decided_by text,
32
+ decided_at timestamptz,
33
+ comment text,
34
+ created_at timestamptz NOT NULL DEFAULT now(),
35
+ tenant_id uuid NOT NULL DEFAULT ` +
36
+ tenantDefault +
37
+ `
38
+ )`,
39
+ "ALTER TABLE facilis_tasks ENABLE ROW LEVEL SECURITY",
40
+ ...getTableConfig(facilisTasks).policies.map((policy) => policyCreateSql("facilis_tasks", policy)),
41
+ ];
42
+ await db.db.transaction(async (tx) => {
43
+ for (const statement of statements)
44
+ await tx.execute(sql.raw(statement));
45
+ });
46
+ await ensureAppRole(db);
47
+ return { db, store: createDbTaskStore({ db, tenantId: TENANT_ID }) };
48
+ }
49
+ /** Empties the table as the connecting superuser, so each test starts from a clean slate. */
50
+ export async function clearTasks(db) {
51
+ await db.db.execute(sql.raw("delete from facilis_tasks"));
52
+ }
53
+ let sequence = 0;
54
+ export function newTask(overrides = {}) {
55
+ sequence += 1;
56
+ return {
57
+ id: randomUUID(),
58
+ workflowId: null,
59
+ stepIndex: null,
60
+ kind: "approval",
61
+ titleKey: "todos.approval",
62
+ titleParams: { title: "Buy milk" },
63
+ payload: { todoId: "todo-1" },
64
+ requestedBy: "system:test",
65
+ assignedPermission: null,
66
+ expiresAt: null,
67
+ createdAt: new Date(BASE.getTime() + sequence),
68
+ ...overrides,
69
+ };
70
+ }
@@ -0,0 +1,10 @@
1
+ import { DEFAULT_TENANT_ID } from "@facilis.dev/core";
2
+ /**
3
+ * Single-tenant fallback tenant id (DECISIONS O-003).
4
+ *
5
+ * The constant lives in @facilis.dev/core so the middleware, the handler scoping and generated
6
+ * apps cannot drift apart (a mismatch makes RLS reject every insert). It is also the value the
7
+ * session middleware requires a session's user row to carry (D-040).
8
+ */
9
+ export { DEFAULT_TENANT_ID };
10
+ export declare function readDefaultTenantId(environment?: NodeJS.ProcessEnv): string;
@@ -0,0 +1,13 @@
1
+ import { DEFAULT_TENANT_ID } from "@facilis.dev/core";
2
+ /**
3
+ * Single-tenant fallback tenant id (DECISIONS O-003).
4
+ *
5
+ * The constant lives in @facilis.dev/core so the middleware, the handler scoping and generated
6
+ * apps cannot drift apart (a mismatch makes RLS reject every insert). It is also the value the
7
+ * session middleware requires a session's user row to carry (D-040).
8
+ */
9
+ export { DEFAULT_TENANT_ID };
10
+ export function readDefaultTenantId(environment = process.env) {
11
+ const configured = environment["FACILIS_TENANT_ID"]?.trim();
12
+ return configured !== undefined && configured.length > 0 ? configured : DEFAULT_TENANT_ID;
13
+ }
@@ -0,0 +1,25 @@
1
+ import type { FacilisJobsConfig, FacilisWorkflowsConfig, ManifestWarning } from "@facilis.dev/core";
2
+ import type { FacilisDb } from "@facilis.dev/db";
3
+ import type { JobsRuntime } from "../jobs/runtime.js";
4
+ import type { WorkflowModule } from "./contracts.js";
5
+ import { type WorkflowsRuntime } from "./runner.js";
6
+ export interface BootWorkflowsOptions {
7
+ readonly db: FacilisDb;
8
+ readonly tenantId: string;
9
+ readonly modules: readonly WorkflowModule[];
10
+ /** The booted job queue; null disables workflows, because a step cannot run without it. */
11
+ readonly jobs: JobsRuntime | null;
12
+ readonly jobsConfig: FacilisJobsConfig;
13
+ readonly workflowsConfig: FacilisWorkflowsConfig;
14
+ /** Session-wide manifest warnings; boot pushes into it instead of throwing. */
15
+ readonly warnings: ManifestWarning[];
16
+ }
17
+ /**
18
+ * Boots the workflow runtime (D-135, docs/WORKFLOWS.md §8).
19
+ *
20
+ * Never throws: without both tables (or without the job queue) the API is unavailable with a
21
+ * manifest warning, because a suspended chain needs durable rows and jobs (there is
22
+ * deliberately no in-memory mode). The returned runtime is carried by BootstrapState and
23
+ * exposed as ctx.workflows.
24
+ */
25
+ export declare function bootWorkflows(options: BootWorkflowsOptions): Promise<WorkflowsRuntime | null>;