@alvera-ai/platform-sdk 0.10.0-rc.2 → 0.10.0-rc.21

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 (55) hide show
  1. package/.agent/AGENTS.md +440 -0
  2. package/.agent/account_management.md +455 -0
  3. package/.agent/action_status_updaters.md +262 -0
  4. package/.agent/ai_agents.md +423 -0
  5. package/.agent/ai_sandbox.md +265 -0
  6. package/.agent/async.md +111 -0
  7. package/.agent/connected_apps.md +407 -0
  8. package/.agent/cookbook/_fixtures/README.md +99 -0
  9. package/.agent/cookbook/_fixtures/accounts_receivable/_customers_accounts_receivable_customer.liquid +32 -0
  10. package/.agent/cookbook/_fixtures/accounts_receivable/_customers_accounts_receivable_mdm.liquid +20 -0
  11. package/.agent/cookbook/_fixtures/foundation/_lead_submissions_foundation_generic_table.liquid +33 -0
  12. package/.agent/cookbook/_fixtures/foundation/_lead_submissions_foundation_legal_entity.liquid +88 -0
  13. package/.agent/cookbook/_fixtures/foundation/_lead_submissions_foundation_mdm.liquid +48 -0
  14. package/.agent/cookbook/_fixtures/healthcare/_cahps_appointments_healthcare_appointment.liquid +47 -0
  15. package/.agent/cookbook/_fixtures/healthcare/_cahps_appointments_healthcare_mdm.liquid +24 -0
  16. package/.agent/cookbook/_fixtures/healthcare/_cahps_appointments_healthcare_patient.liquid +38 -0
  17. package/.agent/cookbook/_fixtures/payment_risk/_compliance_screenings_payment_risk_compliance_screening.liquid +59 -0
  18. package/.agent/cookbook/_fixtures/payment_risk/_compliance_screenings_payment_risk_mdm.liquid +36 -0
  19. package/.agent/cookbook/_fixtures/payment_risk/_payment_accounts_payment_risk_mdm.liquid +30 -0
  20. package/.agent/cookbook/_fixtures/payment_risk/_payment_accounts_payment_risk_payment_account.liquid +55 -0
  21. package/.agent/cookbook/_setup/accounts_receivable.md +282 -0
  22. package/.agent/cookbook/_setup/foundation.md +277 -0
  23. package/.agent/cookbook/_setup/healthcare.md +279 -0
  24. package/.agent/cookbook/_setup/payment_risk.md +283 -0
  25. package/.agent/cookbook/appointment-review-sms-workflow.md +761 -0
  26. package/.agent/cookbook/birthday-greeting-sms-trigger.md +656 -0
  27. package/.agent/cookbook/contact-us-triage-with-llm.md +603 -0
  28. package/.agent/cookbook/dunning-sms-for-delinquent.md +619 -0
  29. package/.agent/cookbook/kyc-notification-on-account-activation.md +619 -0
  30. package/.agent/cookbook/sanctions-screening-with-agent-review.md +711 -0
  31. package/.agent/cookbook/score-leads-with-llm-categorization.md +602 -0
  32. package/.agent/cookbook/welcome-sms-for-customers.md +607 -0
  33. package/.agent/data_activation_clients.md +557 -0
  34. package/.agent/data_sources.md +234 -0
  35. package/.agent/datalakes.md +712 -0
  36. package/.agent/debugging.md +137 -0
  37. package/.agent/errors.md +196 -0
  38. package/.agent/generic_tables.md +351 -0
  39. package/.agent/interoperability_contracts.md +351 -0
  40. package/.agent/mdm.md +293 -0
  41. package/.agent/mutations.md +152 -0
  42. package/.agent/templates.md +98 -0
  43. package/.agent/tool-call-configs.md +90 -0
  44. package/.agent/tools.md +546 -0
  45. package/.agent/type_naming.md +131 -0
  46. package/.agent/workflows.md +601 -0
  47. package/README.md +46 -0
  48. package/dist/bin/platform-sdk.d.mts +1 -0
  49. package/dist/bin/platform-sdk.mjs +106 -0
  50. package/dist/bin/platform-sdk.mjs.map +1 -0
  51. package/dist/index.d.mts +1200 -43201
  52. package/dist/index.d.mts.map +1 -1
  53. package/dist/index.mjs +1859 -7319
  54. package/dist/index.mjs.map +1 -1
  55. package/package.json +19 -10
@@ -0,0 +1,656 @@
1
+ ---
2
+ title: Send a happy-birthday SMS on each contact's next birthday
3
+ summary: End-to-end standard workflow — provision a pure-Liquid year-roll trigger workflow, ingest legal-entity rows through a manual-upload DAC, run the workflow, fast-forward the scheduled SMS via trigger_override, and close the connected-app reply loop. No agent, no LLM.
4
+ industry: foundation
5
+ slug: birthday-greeting-sms-trigger
6
+ vitest_source:
7
+ - integration-tests/tests/foundation/standard-workflow.test.ts
8
+ - integration-tests/tests/foundation/data-sources.test.ts
9
+ - integration-tests/tests/foundation/tools.test.ts
10
+ - integration-tests/tests/foundation/interoperability-contracts.test.ts
11
+ - integration-tests/tests/foundation/create-dac.test.ts
12
+ - integration-tests/tests/foundation/bootstrap.test.ts
13
+ status: green
14
+ ---
15
+
16
+ # Problem
17
+
18
+ Most outbound customer-engagement systems handle the "send a
19
+ greeting on the customer's birthday" use case with a cron job that
20
+ queries the contacts table every morning and emits one task per
21
+ match. That works but pulls the date-of-birth-matching logic into
22
+ application code, splits scheduling between the cron window and the
23
+ engagement system, and forces the operator to keep the cron in sync
24
+ with timezone and feature-flag changes.
25
+
26
+ The Alvera platform's standard workflow primitive flips this: the
27
+ workflow declares, in pure Liquid, when each contact's next birthday
28
+ SMS should fire, and the platform schedules the action to dispatch at
29
+ that moment. No cron, no application code computing the birthday
30
+ year-roll, no drift between the source of truth and the scheduler.
31
+
32
+ This cookbook walks the **whole** scenario, not just the provisioning:
33
+ it creates the workflow, ingests legal-entity rows through the
34
+ production data-activation chain, runs the workflow so the filter
35
+ routes each row, fast-forwards the future-scheduled SMS via
36
+ `trigger_override` so the dispatch is observable inside one sitting,
37
+ and finally resolves the connected-app deep-link the SMS carries —
38
+ closing the SMS → reply loop.
39
+
40
+ The scenario is anchored to
41
+ `platform/integration-tests/tests/foundation/standard-workflow.test.ts`
42
+ — a green end-to-end test (§1–§12) that exercises this exact shape.
43
+ This cookbook is a prose re-presentation of what that test walks.
44
+ The setup file `_setup/foundation.md` already provisioned the tenant,
45
+ datalake, and industry-admin client; this cookbook starts from there.
46
+
47
+ # Composition
48
+
49
+ | Resource provisioned | Owner |
50
+ |----------------------------------|-------------|
51
+ | SMS tool (SNS-backed) | build |
52
+ | Birthday Greeting connected app | build |
53
+ | Happy Birthday workflow | build |
54
+ | Lead-form data source | build |
55
+ | Manual Upload tool | build |
56
+ | LegalEntity interop contract | build |
57
+ | Manual-upload DAC | build |
58
+
59
+ The setup file `_setup/foundation.md` already provisioned the tenant +
60
+ datalake + tenant-scoped client; this cookbook starts from there.
61
+
62
+ # Walkthrough
63
+
64
+ ## 001 — create the SMS tool
65
+
66
+ The Happy Birthday workflow's scheduled action invokes an SMS tool.
67
+ The tool's `body.tool_body_type: 'sns'` means it routes via AWS SNS;
68
+ local dev points it at LocalStack on `http://localhost:4566` via
69
+ `endpoint_url` so no real AWS credentials are needed. The
70
+ `intent: 'sms'` tags this tool for workflow actions that send SMS
71
+ (versus `data_exchange` for ingestion tools).
72
+
73
+ ```typescript
74
+ const smsToolResp = await api.tools.create(tenantSlug, datalakeSlug, {
75
+ name: `Cookbook SMS Tool ${runSuffix}`,
76
+ description: 'SNS-backed SMS dispatcher for the Happy Birthday workflow, wired to LocalStack.',
77
+ intent: 'sms',
78
+ status: 'active',
79
+ datalake_id: ctx.datalakeId,
80
+ body: {
81
+ tool_body_type: 'sns',
82
+ auth_method: 'access_key',
83
+ region: 'us-east-1',
84
+ phone_number: '+15551234567',
85
+ endpoint_url: 'http://localhost:4566',
86
+ access_key_id: 'test',
87
+ secret_access_key: 'test',
88
+ },
89
+ })
90
+ toolId = smsToolResp.data.id!
91
+ ```
92
+
93
+ ## 002 — create the Birthday Greeting connected app
94
+
95
+ The workflow's SMS action carries a deep-link to a connected-app page
96
+ so the recipient can complete a follow-up form (a birthday photo
97
+ upload, an event RSVP — whichever the operator wires up). The
98
+ connected app is a thin registration of the form's URL and mode; the
99
+ actual page is hosted outside the platform (`mode: 'self_hosted'`).
100
+ The server-derived `slug` is captured for the resolve-page call in
101
+ §014.
102
+
103
+ ```typescript
104
+ const connectedAppResp = await api.connectedApps.create(tenantSlug, datalakeSlug, {
105
+ name: `Cookbook Birthday Greeting Form ${runSuffix}`,
106
+ description: 'Birthday-greeting form linked from outbound SMS — used by the Happy Birthday workflow.',
107
+ mode: 'self_hosted',
108
+ urls: [
109
+ {
110
+ url: 'https://birthday.example.local',
111
+ is_primary: true,
112
+ label: 'production',
113
+ },
114
+ ],
115
+ })
116
+ connectedAppId = connectedAppResp.data.id!
117
+ ctx.connectedAppSlug = connectedAppResp.data.slug!
118
+ ```
119
+
120
+ ## 003 — create the Happy Birthday workflow
121
+
122
+ The workflow has the standard shape: a filter (Liquid; passes
123
+ legal entities whose `date_of_birth` is non-null), a decision (a
124
+ literal Liquid array naming one decision key), and one SMS action
125
+ whose `trigger_template` computes the next birthday in pure Liquid via
126
+ year-roll math. The trigger template is the heart of the cookbook —
127
+ by branching on whether today's MM-DD has passed the contact's DoB's
128
+ MM-DD, it always renders the upcoming birthday whether it falls this
129
+ year or next.
130
+
131
+ The SMS body references `{{ connected_app_form_url }}` — the platform
132
+ injects that variable at action-execution time after minting the
133
+ connected-app page token. Without the reference the `/t/<token>`
134
+ deep-link is minted but never lands in the rendered body, so §014
135
+ (resolve the deep-link) could not close the SMS → reply loop.
136
+
137
+ ```typescript
138
+ const FILTER_BODY =
139
+ '{% if mdm_output.regulated_legal_entity.date_of_birth %}true{% endif %}'
140
+ const DECISION_KEY = 'send_happy_birthday_sms'
141
+ const DECISION_BODY = `["${DECISION_KEY}"]`
142
+ const DECISION_OUTPUT_SCHEMA = '{"type":"array","items":{"type":"string"}}'
143
+ const TRIGGER_TEMPLATE =
144
+ '{% assign year = "" | now | date: "%Y" %}' +
145
+ '{% assign today_mmdd = "" | now | date: "%m-%d" %}' +
146
+ '{% assign dob_mmdd = mdm_output.regulated_legal_entity.date_of_birth | date: "%m-%d" %}' +
147
+ '{% if dob_mmdd >= today_mmdd %}{{ year }}-{{ dob_mmdd }} 00:00:00' +
148
+ '{% else %}{{ year | plus: 1 }}-{{ dob_mmdd }} 00:00:00{% endif %}'
149
+ const SMS_TO_TEMPLATE =
150
+ '{{ mdm_output.regulated_legal_entity.phone_numbers | first | map: "phone_number" }}'
151
+ const SMS_BODY_TEMPLATE =
152
+ 'Happy birthday {{ mdm_output.regulated_legal_entity.first_name }}! \u{1F382}' +
153
+ ' Share a photo: {{ connected_app_form_url }}'
154
+
155
+ const workflowResp = await api.workflows.create(tenantSlug, datalakeSlug, {
156
+ name: `Cookbook Happy Birthday Workflow ${runSuffix}`,
157
+ description: "Sends a happy-birthday SMS on each contact's next birthday — pure-Liquid trigger does the year-roll math.",
158
+ dataset_type: 'legal_entity',
159
+ status: 'live',
160
+ skip_mdm_resolution: false,
161
+ filter_config: {
162
+ type: 'custom',
163
+ body: FILTER_BODY,
164
+ },
165
+ decision_config: {
166
+ type: 'custom',
167
+ body: DECISION_BODY,
168
+ output_schema: DECISION_OUTPUT_SCHEMA,
169
+ },
170
+ actions: [
171
+ {
172
+ action_type: 'sms',
173
+ tool_id: toolId,
174
+ decision_key: DECISION_KEY,
175
+ position: 0,
176
+ trigger_template: TRIGGER_TEMPLATE,
177
+ idempotency_template:
178
+ '{{ subject_id }}-{{ workflow_id }}-{{ action_id }}-{{ "" | uuid }}',
179
+ connected_app_id: connectedAppId,
180
+ connected_app_route: '/forms/birthday-greeting',
181
+ connected_app_metadata_template:
182
+ '{"legal_entity_id":"{{ legal_entity.id }}"}',
183
+ tool_call: {
184
+ tool_call_type: 'sms_request',
185
+ to: { type: 'custom', body: SMS_TO_TEMPLATE },
186
+ body: { type: 'custom', body: SMS_BODY_TEMPLATE },
187
+ sms_type: 'transactional',
188
+ },
189
+ },
190
+ ],
191
+ })
192
+ workflowId = workflowResp.data.id!
193
+ ctx.workflowSlug = workflowResp.data.slug!
194
+ ```
195
+
196
+ ## 004 — create the lead-form data source
197
+
198
+ A workflow runs on rows; rows arrive through the data-activation
199
+ chain. The chain's first link is a `DataSource` — a registration of
200
+ where the rows originate. The `uri` is the system-of-record address;
201
+ it flows into each ingested row's `source_uri`, which the
202
+ legal-entity dedupe keys on alongside the contact's email.
203
+
204
+ ```typescript
205
+ const dataSourceResp = await api.dataSources.create(tenantSlug, datalakeSlug, {
206
+ name: `Cookbook Lead Form Source ${runSuffix}`,
207
+ uri: 'https://app.alvera.ai',
208
+ description: 'Inbound lead-capture form — origin of the legal-entity rows the birthday workflow runs on.',
209
+ status: 'active',
210
+ is_default: false,
211
+ })
212
+ dataSourceId = dataSourceResp.data.id!
213
+ ```
214
+
215
+ ## 005 — create the Manual Upload tool
216
+
217
+ The Data Activation Client needs a tool. For inline-JSON ingest a
218
+ `manual_upload` tool is the minimal choice — `intent: 'data_exchange'`
219
+ distinguishes it from the SMS tool, and `tool_body_type: 'manual_upload'`
220
+ needs no endpoint or credential wiring (the rows arrive in the ingest
221
+ call body, not by the tool fetching them).
222
+
223
+ ```typescript
224
+ const manualUploadToolResp = await api.tools.create(tenantSlug, datalakeSlug, {
225
+ name: `Cookbook Manual Upload Tool ${runSuffix}`,
226
+ description: 'Manual-upload data-exchange tool — backs the DAC that ingests legal-entity rows.',
227
+ intent: 'data_exchange',
228
+ status: 'active',
229
+ datalake_id: ctx.datalakeId,
230
+ data_source_id: dataSourceId,
231
+ body: { tool_body_type: 'manual_upload' },
232
+ })
233
+ ctx.manualUploadToolId = manualUploadToolResp.data.id!
234
+ ```
235
+
236
+ ## 006 — create the LegalEntity interoperability contract
237
+
238
+ The interoperability contract is the row-shaping rule: a Liquid
239
+ template that maps an inbound lead-form row into a `LegalEntity`
240
+ upsert. This cookbook loads the production Foundation Airflow
241
+ lead-form template from the vendored fixtures directory rather than
242
+ inlining several hundred lines of Liquid. `mdm_input_config: 'null'`
243
+ means the contract performs no MDM resolution of its own — the
244
+ legal entity is upserted directly, keyed by its email digital
245
+ identifier.
246
+
247
+ The template renders the optional `date_of_birth` and `phone_numbers`
248
+ fields when the inbound row carries them; that is what lets §003's
249
+ has-DoB filter and the year-roll trigger have something to read.
250
+
251
+ ```typescript
252
+ const { readFileSync } = await import('node:fs')
253
+ const { join } = await import('node:path')
254
+ const leTemplate = readFileSync(
255
+ join(
256
+ process.env.COOKBOOK_FIXTURES_DIR!,
257
+ 'foundation/_lead_submissions_foundation_legal_entity.liquid',
258
+ ),
259
+ 'utf8',
260
+ )
261
+
262
+ const contractResp = await api.interoperabilityContracts.create(tenantSlug, datalakeSlug, {
263
+ name: `Cookbook Lead Form to LegalEntity ${runSuffix}`,
264
+ description: 'Foundation Airflow lead-form row → LegalEntity (custom Liquid, no MDM input).',
265
+ resource_type: 'legal_entity',
266
+ template_config: { type: 'custom', body: leTemplate },
267
+ mdm_input_config: { type: 'null' },
268
+ generic_table_id: null,
269
+ })
270
+ interopContractId = contractResp.data.id!
271
+ ```
272
+
273
+ ## 007 — create the manual-upload DAC
274
+
275
+ The Data Activation Client binds the three preceding pieces — the
276
+ manual-upload tool, the data source, and the interop contract — into
277
+ one ingestion endpoint. `tool_call.tool_call_type: 'manual_upload'`
278
+ selects the inline-JSON ingest path. The server-derived `slug` is the
279
+ handle §008 ingests rows against.
280
+
281
+ ```typescript
282
+ const dacResp = await api.dataActivationClients.create(tenantSlug, datalakeSlug, {
283
+ name: `Cookbook Lead Form DAC ${runSuffix}`,
284
+ description: 'Manual-upload DAC — ingests lead-form rows into LegalEntity via the interop contract.',
285
+ tool_id: ctx.manualUploadToolId,
286
+ data_source_id: dataSourceId,
287
+ tool_call: { tool_call_type: 'manual_upload' },
288
+ interoperability_contract_ids: [interopContractId],
289
+ })
290
+ dacId = dacResp.data.id!
291
+ ctx.dacSlug = dacResp.data.slug!
292
+ ```
293
+
294
+ ## 008 — ingest two legal-entity rows
295
+
296
+ Two rows, ingested as inline JSON through the manual-upload DAC. One
297
+ carries a `date_of_birth` (MM-DD of tomorrow, year stamped 30 years
298
+ back so the past-date guard on the LegalEntity changeset is
299
+ satisfied) — the workflow filter will pass it. The other omits
300
+ `date_of_birth` entirely — the filter must reject it. Each ingest
301
+ call gets its own batch id; both are pinned for the run scope in
302
+ §010.
303
+
304
+ Tomorrow's MM-DD is deliberate: §012 fast-forwards the SMS via
305
+ `trigger_override`, and a *future* scheduled time is what makes the
306
+ fast-forward observable (a birthday-today row renders a past time and
307
+ would dispatch regardless).
308
+
309
+ ```typescript
310
+ const today = new Date()
311
+ const tomorrow = new Date(today.getTime() + 86_400_000)
312
+ const tomorrowMM = String(tomorrow.getUTCMonth() + 1).padStart(2, '0')
313
+ const tomorrowDD = String(tomorrow.getUTCDate()).padStart(2, '0')
314
+ const dobYear = today.getUTCFullYear() - 30
315
+ const phoneDigits = String(Date.now()).slice(-7).padStart(7, '0')
316
+ ctx.birthdayPhone = `+1555${phoneDigits}`
317
+
318
+ const birthdayRow = {
319
+ submission_id: `BD-${runSuffix}`,
320
+ name: 'Maria Birthday',
321
+ email: `maria-bd-${runSuffix}@example.com`,
322
+ phone: ctx.birthdayPhone,
323
+ company: '',
324
+ message: 'My birthday is tomorrow',
325
+ lead_source: 'cookbook_birthday',
326
+ source_uri: 'https://app.alvera.ai',
327
+ date_of_birth: `${dobYear}-${tomorrowMM}-${tomorrowDD}`,
328
+ }
329
+ const noDobRow = {
330
+ submission_id: `NODOB-${runSuffix}`,
331
+ name: 'Priya NoDob',
332
+ email: `priya-nodob-${runSuffix}@example.com`,
333
+ phone: `+1556${phoneDigits}`,
334
+ company: '',
335
+ message: 'I have no DoB on file',
336
+ lead_source: 'cookbook_birthday',
337
+ source_uri: 'https://app.alvera.ai',
338
+ // date_of_birth intentionally absent — the workflow filter must reject this row
339
+ }
340
+
341
+ const [birthdayIngest, noDobIngest] = await Promise.all([
342
+ api.dataActivationClients.ingest(tenantSlug, datalakeSlug, ctx.dacSlug, { data: birthdayRow }),
343
+ api.dataActivationClients.ingest(tenantSlug, datalakeSlug, ctx.dacSlug, { data: noDobRow }),
344
+ ])
345
+ ctx.batchBirthday = birthdayIngest.data.batch_id!
346
+ ctx.batchNoDob = noDobIngest.data.batch_id!
347
+ ```
348
+
349
+ ## 009 — wait for both ingest batches to reach steady-state
350
+
351
+ Ingestion is async — the DAC enqueues per-row jobs that the
352
+ `BatchMergeWorker` drains into `legal_entities`. Poll the DAC's
353
+ activation logs until both batches show a `legal_entities` row with
354
+ `dataset_updated >= 1` and a non-empty `output_files` array (the
355
+ merged Parquet landed in object storage). Only then is it safe to run
356
+ the workflow against these rows.
357
+
358
+ ```typescript
359
+ const targetBatches = new Set([ctx.batchBirthday, ctx.batchNoDob])
360
+ const deadline = Date.now() + 90_000
361
+ let greenCount = 0
362
+ while (Date.now() < deadline) {
363
+ const { data } = await api.dataActivationClients.logs.list(tenantSlug, datalakeSlug, ctx.dacSlug)
364
+ const green = new Set<string>()
365
+ for (const row of (data.data ?? []) as Array<Record<string, unknown>>) {
366
+ const b = row.batch_id
367
+ if (typeof b !== 'string' || !targetBatches.has(b)) continue
368
+ if (row.dataset_table !== 'legal_entities') continue
369
+ if (typeof row.dataset_updated !== 'number' || row.dataset_updated < 1) continue
370
+ const files = row.output_files
371
+ if (!Array.isArray(files) || files.length === 0) continue
372
+ green.add(b)
373
+ }
374
+ greenCount = green.size
375
+ if (greenCount === targetBatches.size) break
376
+ await new Promise((r) => setTimeout(r, 1_000))
377
+ }
378
+ if (greenCount !== targetBatches.size) {
379
+ throw new Error(`only ${greenCount}/2 lead-row batches reached steady-state within 90s`)
380
+ }
381
+ ```
382
+
383
+ ## 010 — run the workflow against the two batches
384
+
385
+ `workflows.run` with `manual_override: false` evaluates the filter,
386
+ so the has-DoB filter genuinely routes each row. The SQL where-clause
387
+ scopes the run to exactly the two batches §008 ingested (`rle` is the
388
+ regulated-legal-entities alias the run-query exposes).
389
+
390
+ The batch run-log never reaches a terminal status — the birthday row's
391
+ WEL holds a future-scheduled action and stays `:executing` for the
392
+ life of the run. So this step polls on `total_wels` (every per-row job
393
+ has produced a WEL) rather than waiting for the run to conclude.
394
+
395
+ ```typescript
396
+ const runResp = await api.workflows.run(tenantSlug, datalakeSlug, ctx.workflowSlug, {
397
+ sql_where_clause: `rle.batch_id IN ('${ctx.batchBirthday}', '${ctx.batchNoDob}')`,
398
+ mode: 'live',
399
+ manual_override: false,
400
+ })
401
+ ctx.runLogId = runResp.data.workflow_run_log_id!
402
+ ctx.runBatchId = runResp.data.batch_id!
403
+
404
+ const deadline = Date.now() + 60_000
405
+ let totalWels = 0
406
+ while (Date.now() < deadline) {
407
+ const { data: log } = await api.workflows.batchLogs.refresh(tenantSlug, datalakeSlug, ctx.workflowSlug, ctx.runLogId)
408
+ if (log.status === 'failed') throw new Error('workflow run reached :failed')
409
+ totalWels = typeof log.total_wels === 'number' ? log.total_wels : 0
410
+ if (totalWels >= 2) break
411
+ await new Promise((r) => setTimeout(r, 1_500))
412
+ }
413
+ if (totalWels < 2) throw new Error(`workflow run produced only ${totalWels}/2 WELs within 60s`)
414
+ ```
415
+
416
+ ## 011 — verify the filter routed: one passes, one is filtered
417
+
418
+ Each row produced a Workflow Execution Log. The birthday row (has
419
+ DoB) passes the filter, so its WEL is `:executing` (a future SMS
420
+ action is scheduled) or `:completed`. The no-DoB row fails the
421
+ filter, so its WEL is `:filtered`. A run where both passed — or both
422
+ were filtered — would mean the filter is not actually evaluating; the
423
+ old shallow version of this cookbook could never catch that because
424
+ it never ran the workflow at all.
425
+
426
+ ```typescript
427
+ const { data: wfLogs } = await api.workflows.workflowLogs.list(tenantSlug, datalakeSlug, ctx.workflowSlug)
428
+ const ourWels = (wfLogs.data ?? []).filter(
429
+ (w) => (w as { batch_id?: string }).batch_id === ctx.runBatchId,
430
+ )
431
+ if (ourWels.length !== 2) {
432
+ throw new Error(`expected 2 WELs for the run, got ${ourWels.length}`)
433
+ }
434
+
435
+ const byStatus: Record<string, number> = {}
436
+ for (const w of ourWels) {
437
+ const st = (w as { status?: string }).status ?? 'unknown'
438
+ byStatus[st] = (byStatus[st] ?? 0) + 1
439
+ }
440
+ const passCount = (byStatus.executing ?? 0) + (byStatus.completed ?? 0)
441
+ if (passCount !== 1) {
442
+ throw new Error(`expected 1 pass-branch WEL, got ${passCount} — distribution ${JSON.stringify(byStatus)}`)
443
+ }
444
+ if ((byStatus.filtered ?? 0) !== 1) {
445
+ throw new Error(`expected 1 :filtered WEL (the no-DoB row) — distribution ${JSON.stringify(byStatus)}`)
446
+ }
447
+ ```
448
+
449
+ ## 012 — fast-forward the scheduled SMS with trigger_override
450
+
451
+ The birthday row's SMS action is scheduled for tomorrow 00:00 UTC —
452
+ in the future, so it will not dispatch on its own inside this
453
+ sitting. `workflows.execute` with `trigger_override: true` tells the
454
+ platform to fast-forward the queued Oban job (`Oban.retry_job`
455
+ promotes it to `:available`) so the SMS dispatches now. The
456
+ `ActionExecutionLog` still records the year-roll-rendered
457
+ `scheduled_at` — only the job is moved, which localises the override's
458
+ blast radius.
459
+
460
+ `workflows.execute` is addressed by `dataset_id` (the unregulated
461
+ legal-entity id), so first resolve the birthday row's id via a
462
+ dataset search scoped to its batch.
463
+
464
+ ```typescript
465
+ const { data: us } = await api.datasets.createUserSearch(tenantSlug, datalakeSlug, 'legal_entity', {
466
+ search_query: `rle.batch_id = '${ctx.batchBirthday}'`,
467
+ })
468
+ if (us.status !== 'completed') {
469
+ throw new Error(`legal_entity user-search status=${us.status} error=${us.error_message ?? '(none)'}`)
470
+ }
471
+ const { data: search } = await api.datasets.search(tenantSlug, datalakeSlug, 'legal_entity', {
472
+ userSearchId: us.id!,
473
+ dataAccessMode: 'unregulated',
474
+ })
475
+ const birthdayLegalEntityId = (search.data?.[0] as { id?: string } | undefined)?.id
476
+ if (!birthdayLegalEntityId) throw new Error('birthday row legal_entity not found via search')
477
+
478
+ const { data: execResp } = await api.workflows.execute(tenantSlug, datalakeSlug, ctx.workflowSlug, {
479
+ dataset_id: birthdayLegalEntityId,
480
+ decision_key: 'send_happy_birthday_sms',
481
+ manual_override: true,
482
+ trigger_override: true,
483
+ })
484
+ ctx.forceExecWelId = execResp.workflow_execution_log_id!
485
+
486
+ const deadline = Date.now() + 60_000
487
+ let welStatus: string | null = null
488
+ while (Date.now() < deadline) {
489
+ const { data: wel } = await api.workflows.workflowLogs.get(tenantSlug, datalakeSlug, ctx.workflowSlug, ctx.forceExecWelId)
490
+ welStatus = (wel as { status?: string }).status ?? null
491
+ if (welStatus && welStatus !== 'pending' && welStatus !== 'executing') break
492
+ await new Promise((r) => setTimeout(r, 2_000))
493
+ }
494
+ if (welStatus !== 'completed') {
495
+ throw new Error(`fast-forwarded WEL did not reach :completed (last status: ${welStatus})`)
496
+ }
497
+ ```
498
+
499
+ ## 013 — confirm the SMS landed in LocalStack SNS
500
+
501
+ The SMS tool publishes direct-to-phone-number via AWS SNS; LocalStack
502
+ records every direct publish under `/_aws/sns/sms-messages` keyed by
503
+ recipient phone. Poll the birthday row's phone for a record whose body
504
+ carries the rendered greeting — proof the workflow's stated business
505
+ outcome (a birthday SMS) actually happened, not just that the
506
+ resources exist.
507
+
508
+ ```typescript
509
+ const LOCALSTACK = 'http://localhost:4566'
510
+ const deadline = Date.now() + 30_000
511
+ let matched: { Message: string; PhoneNumber: string } | undefined
512
+ while (Date.now() < deadline && !matched) {
513
+ const resp = await fetch(`${LOCALSTACK}/_aws/sns/sms-messages`)
514
+ if (resp.ok) {
515
+ const body = (await resp.json()) as {
516
+ sms_messages?: Record<string, Array<{ Message: string; PhoneNumber: string }>>
517
+ }
518
+ const records = body.sms_messages?.[ctx.birthdayPhone] ?? []
519
+ matched = records.find(
520
+ (m) => m.Message.includes('Happy birthday') && m.Message.includes('Maria'),
521
+ )
522
+ }
523
+ if (!matched) await new Promise((r) => setTimeout(r, 500))
524
+ }
525
+ if (!matched) {
526
+ throw new Error(`no "Happy birthday" SMS landed in LocalStack SNS for ${ctx.birthdayPhone} within 30s`)
527
+ }
528
+ ```
529
+
530
+ ## 014 — resolve the connected-app deep-link and post tracking
531
+
532
+ The dispatched SMS carries a `/t/<token>` shortlink minted from the
533
+ action's `connected_app_id` + `connected_app_route`. Read the executed
534
+ WEL in regulated mode to get the raw rendered `message_body`, extract
535
+ the token, and resolve it via `connectedApps.resolvePage` — the
536
+ `route_path` must match the action's `connected_app_route`. Posting
537
+ `opened_at` + `form_submitted_at` via `updateMessageTracking` then
538
+ mirrors what the connected-app frontend does when the recipient opens
539
+ the page, closing the SMS → reply loop end-to-end.
540
+
541
+ ```typescript
542
+ const { data: regulatedWel } = await api.workflows.workflowLogs.get(
543
+ tenantSlug,
544
+ datalakeSlug,
545
+ ctx.workflowSlug,
546
+ ctx.forceExecWelId,
547
+ { dataAccessMode: 'regulated' },
548
+ )
549
+ const aelWithBody = (regulatedWel.action_execution_logs ?? []).find(
550
+ (ael) => typeof ael.message_body === 'string' && ael.message_body.length > 0,
551
+ )
552
+ if (!aelWithBody?.message_body) {
553
+ throw new Error('no AEL message_body on the executed WEL')
554
+ }
555
+ const tokenMatch = aelWithBody.message_body.match(/\/t\/([A-Za-z0-9_-]+)/)
556
+ if (!tokenMatch) {
557
+ throw new Error(`no /t/<token> in rendered SMS body: ${aelWithBody.message_body}`)
558
+ }
559
+ const shortPath = tokenMatch[1]!
560
+
561
+ const { data: resolved } = await api.connectedApps.resolvePage(tenantSlug, datalakeSlug, ctx.connectedAppSlug, {
562
+ short_path: shortPath,
563
+ user_agent: 'cookbook-doctest/birthday-greeting',
564
+ })
565
+ if (resolved.route_path !== '/forms/birthday-greeting') {
566
+ throw new Error(`resolvePage route_path mismatch: ${resolved.route_path}`)
567
+ }
568
+
569
+ const now = new Date().toISOString()
570
+ const { data: tracked } = await api.connectedApps.updateMessageTracking(tenantSlug, datalakeSlug, ctx.connectedAppSlug, {
571
+ short_path: shortPath,
572
+ opened_at: now,
573
+ form_submitted_at: now,
574
+ })
575
+ if (!tracked.message?.opened_at || !tracked.message?.form_submitted_at) {
576
+ throw new Error('message tracking did not persist opened_at + form_submitted_at')
577
+ }
578
+ ```
579
+
580
+ # Branches
581
+
582
+ - **The no-DoB row is filtered, not failed** — §011 asserts the no-DoB
583
+ row's WEL is `:filtered`, a distinct terminal status from `:failed`.
584
+ A filtered row is a *correct* outcome: the workflow looked at it,
585
+ the has-DoB filter rendered empty, and the platform recorded that
586
+ the row was intentionally skipped. No SMS action is scheduled for a
587
+ filtered row.
588
+ - **trigger_override deferred vs immediate** — §012 uses
589
+ `trigger_override: true` to fast-forward the SMS. With
590
+ `trigger_override: false` (the default) the same action stays
591
+ queued at its year-roll `scheduled_at` — the WEL settles at
592
+ `:executing` with a `:pending` action and no SMS dispatches inside
593
+ the test window. The anchor vitest's §8 covers that deferred branch
594
+ explicitly.
595
+ - **Trigger fires this calendar year vs next** — the Liquid trigger
596
+ branches on `dob_mmdd >= today_mmdd`. If the contact's birthday this
597
+ year has already passed, the trigger renders the same month-day in
598
+ the next calendar year. Year-roll is implicit in the template;
599
+ there is no application code to audit.
600
+
601
+ # Rollback
602
+
603
+ The cookbook doctest harness does not currently tear down created
604
+ resources. The `_setup/foundation.md` setup file's runSuffix-scoped
605
+ tenant / datalake / user names mean each run is naturally isolated;
606
+ the seeded local DB is cheap to reset (`mix ecto.reset` on the
607
+ platform repo).
608
+
609
+ # Outcome
610
+
611
+ After this cookbook's fourteen steps run green:
612
+
613
+ - A foundation tenant exists with a foundation-domain datalake
614
+ - An SMS tool, a Birthday Greeting connected app, and a Happy Birthday
615
+ standard workflow (status `live`, year-roll trigger) are registered
616
+ - A data source, a Manual Upload tool, a LegalEntity interop contract,
617
+ and a manual-upload DAC form a working ingestion chain
618
+ - Two legal entities have been ingested through that chain — one with
619
+ a date of birth, one without
620
+ - Running the workflow routed them correctly: the dated row passed the
621
+ filter and scheduled an SMS; the undated row was `:filtered`
622
+ - The scheduled SMS, fast-forwarded via `trigger_override`, **actually
623
+ dispatched** — it is observable in LocalStack SNS with the rendered
624
+ "Happy birthday" greeting
625
+ - The connected-app deep-link the SMS carried resolves, and message
626
+ tracking records the open + form-submit timestamps
627
+
628
+ The business outcome — a birthday SMS sent to a contact, with a
629
+ working reply link — is demonstrated end-to-end, not merely
630
+ provisioned.
631
+
632
+ # See also
633
+
634
+ - `_setup/foundation.md` — the inlined bootstrap that provisions the
635
+ tenant + datalake this cookbook starts from
636
+ - `score-leads-with-llm-categorization.md` — the agent-driven
637
+ foundation cookbook; same SMS + ingestion shape, LLM in the decision
638
+ - `.agent/tools.md` — SMS (`tool_body_type: sns`) and manual-upload
639
+ tool body shapes; intent classification
640
+ - `.agent/connected_apps.md` — connected-app registration + the
641
+ resolve-page / message-tracking reply loop
642
+ - `.agent/data_activation_clients.md` — data source → tool → interop
643
+ contract → DAC ingestion chain
644
+ - `.agent/workflows.md` — standard workflow primitive (filter +
645
+ decision + actions), `workflows.run` vs `workflows.execute`, and
646
+ `trigger_override`
647
+ - `.agent/ai_sandbox.md` — bounds on the Liquid sandbox the filter and
648
+ trigger templates execute inside
649
+ - `.agent/cookbook/_fixtures/foundation/` — the vendored
650
+ lead-form LegalEntity Liquid template §006 loads
651
+ - `integration-tests/tests/foundation/standard-workflow.test.ts` — the
652
+ anchor green test (§1–§12) these snippets are lifted from
653
+ - `integration-tests/tests/foundation/data-sources.test.ts`,
654
+ `tools.test.ts`, `interoperability-contracts.test.ts`,
655
+ `create-dac.test.ts` — the per-resource create snippets §004–§007 are
656
+ lifted from