@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,619 @@
1
+ ---
2
+ title: Send a payment-reminder SMS to delinquent customers with a pay-invoice link
3
+ summary: End-to-end standard workflow — provision a Dunning SMS workflow over the AR customer dataset, ingest two Stripe customer rows (one phone + tax-id verified, one missing tax-id) through a customer interop contract, run the workflow so the SMS-reachable-and-KYC-complete filter routes each row, read the rendered SMS back from the message dataset, and close the connected-app reply loop. No agent, no LLM.
4
+ industry: accounts_receivable
5
+ slug: dunning-sms-for-delinquent
6
+ vitest_source:
7
+ - integration-tests/tests/accounts_receivable/dunning-sms-workflow.test.ts
8
+ - integration-tests/tests/accounts_receivable/interoperability-contracts.test.ts
9
+ - integration-tests/tests/accounts_receivable/run-dac-single.test.ts
10
+ - integration-tests/tests/accounts_receivable/create-dac.test.ts
11
+ - integration-tests/tests/accounts_receivable/tools.test.ts
12
+ - integration-tests/tests/accounts_receivable/data-sources.test.ts
13
+ - integration-tests/tests/accounts_receivable/bootstrap.test.ts
14
+ status: green
15
+ ---
16
+
17
+ # Problem
18
+
19
+ When an invoice goes unpaid, the billing team wants to send a
20
+ payment-reminder ("dunning") SMS with a self-serve pay link — but
21
+ only to customers it is both *allowed* and *able* to contact. The
22
+ customer must be SMS-reachable (a phone on file) and KYC-complete
23
+ (a verified tax id). A customer missing either precondition should
24
+ be skipped, not errored, and certainly not chased.
25
+
26
+ The classic implementation queries the customers table, branches
27
+ on phone-present and tax-id-present, and hands the survivors to an
28
+ SMS sender — with both preconditions living in application code.
29
+
30
+ The Alvera platform's standard workflow primitive keeps both
31
+ checks inside the platform. An AR `customer` dataset is the
32
+ workflow's event source; a pure-Liquid filter gates on
33
+ `customer.phone and customer.tax_id`; a single SMS action carries
34
+ a deep-link to a connected-app payment portal. The
35
+ reachable-and-verified decision is a one-line filter, not a code
36
+ branch.
37
+
38
+ This cookbook walks the **whole** scenario, not just the
39
+ provisioning: it creates the workflow, ingests two Stripe-shaped
40
+ customer rows through the production data-activation chain (one
41
+ phone + tax-id verified, one missing the tax id), runs the
42
+ workflow so the filter routes each row, reads the rendered dunning
43
+ SMS back out of the message dataset, and finally resolves the
44
+ connected-app deep-link the SMS carries — closing the SMS → reply
45
+ loop.
46
+
47
+ The scenario is anchored to
48
+ `platform/integration-tests/tests/accounts_receivable/dunning-sms-workflow.test.ts`
49
+ — a green end-to-end test (§1–§8) that exercises this exact shape.
50
+ This cookbook is a prose re-presentation of what that test walks.
51
+ The setup file `_setup/accounts_receivable.md` already provisioned
52
+ the tenant, datalake, and industry-admin client; this cookbook
53
+ starts from there.
54
+
55
+ # Composition
56
+
57
+ | Resource provisioned | Owner |
58
+ |----------------------------------|-------------|
59
+ | SMS tool (SNS-backed) | build |
60
+ | Dunning payment-portal connected app | build |
61
+ | Dunning SMS workflow | build |
62
+ | Stripe data source | build |
63
+ | Manual Upload tool | build |
64
+ | Stripe Customer interop contract | build |
65
+ | Manual-upload DAC | build |
66
+
67
+ The setup file `_setup/accounts_receivable.md` already
68
+ provisioned the tenant + datalake + tenant-scoped client; this
69
+ cookbook starts from there.
70
+
71
+ # Walkthrough
72
+
73
+ ## 001 — create the SMS tool
74
+
75
+ The Dunning SMS workflow's action invokes an SMS tool. The tool's
76
+ `body.tool_body_type: 'sns'` means it routes via AWS SNS; local
77
+ dev points it at LocalStack on `http://localhost:4566` via
78
+ `endpoint_url` so no real AWS credentials are needed. The
79
+ `intent: 'sms'` tags this tool for workflow actions that send SMS
80
+ (versus `data_exchange` for ingestion tools).
81
+
82
+ ```typescript
83
+ const smsToolResp = await api.tools.create(tenantSlug, datalakeSlug, {
84
+ name: `Cookbook SMS Tool ${runSuffix}`,
85
+ description: 'SNS-backed SMS dispatcher for the Dunning SMS workflow, wired to LocalStack.',
86
+ intent: 'sms',
87
+ status: 'active',
88
+ datalake_id: ctx.datalakeId,
89
+ body: {
90
+ tool_body_type: 'sns',
91
+ auth_method: 'access_key',
92
+ region: 'us-east-1',
93
+ phone_number: '+15551234567',
94
+ endpoint_url: 'http://localhost:4566',
95
+ access_key_id: 'test',
96
+ secret_access_key: 'test',
97
+ },
98
+ })
99
+ toolId = smsToolResp.data.id!
100
+ ```
101
+
102
+ ## 002 — create the Dunning payment-portal connected app
103
+
104
+ The workflow's SMS action carries a deep-link to a connected-app
105
+ page so the customer can open the self-serve payment portal. The
106
+ connected app is a thin registration of the portal's URL and
107
+ mode; the actual page is hosted outside the platform
108
+ (`mode: 'self_hosted'`). The server-derived `slug` is captured for
109
+ the resolve-page call in §013.
110
+
111
+ ```typescript
112
+ const connectedAppResp = await api.connectedApps.create(tenantSlug, datalakeSlug, {
113
+ name: `Cookbook Dunning Payment Portal ${runSuffix}`,
114
+ description: 'Self-serve invoice payment portal linked from the outbound dunning SMS.',
115
+ mode: 'self_hosted',
116
+ urls: [
117
+ {
118
+ url: 'https://dunning.example.local',
119
+ is_primary: true,
120
+ label: 'production',
121
+ },
122
+ ],
123
+ })
124
+ connectedAppId = connectedAppResp.data.id!
125
+ ctx.connectedAppSlug = connectedAppResp.data.slug!
126
+ ```
127
+
128
+ ## 003 — create the Dunning SMS workflow
129
+
130
+ The workflow has the standard shape: a filter (Liquid; passes
131
+ customers who are both SMS-reachable *and* KYC-complete —
132
+ `customer.phone and customer.tax_id`), a decision (a literal
133
+ Liquid array naming one decision key), and one SMS action. The
134
+ SMS body references `{{ customer.customer_number }}` so the
135
+ recipient sees which account is overdue, and
136
+ `{{ connected_app_form_url }}` so the platform can bake in the
137
+ `/t/<token>` pay-link.
138
+
139
+ Two details matter. `dataset_type: 'customer'` makes the AR
140
+ customer dataset the event source; the workflow context injects
141
+ the regulated customer row under the `customer` key, so the
142
+ filter reads `customer.phone` and `customer.tax_id` directly. A
143
+ `context_datasets` entry queries the `message` dataset for any
144
+ dunning SMS already sent to this customer in the last thirty days
145
+ — the platform's built-in guard against dunning the same customer
146
+ twice in a billing cycle. On a fresh tenant that lookup returns
147
+ empty, which is harmless.
148
+
149
+ ```typescript
150
+ const FILTER_BODY = '{% if customer.phone and customer.tax_id %}true{% endif %}'
151
+ const DECISION_KEY = 'send_dunning_sms'
152
+ const DECISION_BODY = `["${DECISION_KEY}"]`
153
+ const DECISION_OUTPUT_SCHEMA = '{"type":"array","items":{"type":"string"}}'
154
+ const SMS_TO_TEMPLATE = '{{ mdm_output.regulated_customer.phone }}'
155
+ const SMS_BODY_TEMPLATE =
156
+ 'Hi {{ mdm_output.regulated_customer.name }}, an invoice on account ' +
157
+ '{{ customer.customer_number }} needs your attention. ' +
158
+ 'Pay now: {{ connected_app_form_url }}'
159
+
160
+ const workflowResp = await api.workflows.create(tenantSlug, datalakeSlug, {
161
+ name: `Cookbook Dunning SMS Workflow ${runSuffix}`,
162
+ description: 'Sends a payment-reminder SMS to delinquent contracted customers with a self-serve pay link.',
163
+ dataset_type: 'customer',
164
+ status: 'live',
165
+ filter_config: {
166
+ type: 'custom',
167
+ body: FILTER_BODY,
168
+ output_schema: '{"type":"boolean"}',
169
+ },
170
+ decision_config: {
171
+ type: 'custom',
172
+ body: DECISION_BODY,
173
+ output_schema: DECISION_OUTPUT_SCHEMA,
174
+ },
175
+ context_datasets: [
176
+ {
177
+ dataset_type: 'message',
178
+ where_clause:
179
+ `rm.customer_id = '{{ customer_id }}' AND rm.decision_key = '${DECISION_KEY}' ` +
180
+ "AND rm.sent_at > NOW() - INTERVAL '30 days'",
181
+ limit: 1,
182
+ position: 0,
183
+ },
184
+ ],
185
+ actions: [
186
+ {
187
+ action_type: 'sms',
188
+ tool_id: toolId,
189
+ decision_key: DECISION_KEY,
190
+ position: 0,
191
+ trigger_template: 'now',
192
+ idempotency_template: '{{ customer_id }}-{{ decision_key }}-{{ "" | uuid }}',
193
+ connected_app_id: connectedAppId,
194
+ connected_app_route: '/portal/pay',
195
+ connected_app_metadata_template:
196
+ '{"customer_id":"{{ mdm_output.customer.id }}","customer_number":"{{ customer.customer_number }}"}',
197
+ tool_call: {
198
+ tool_call_type: 'sms_request',
199
+ to: { type: 'custom', body: SMS_TO_TEMPLATE },
200
+ body: { type: 'custom', body: SMS_BODY_TEMPLATE },
201
+ sms_type: 'transactional',
202
+ },
203
+ },
204
+ ],
205
+ })
206
+ workflowId = workflowResp.data.id!
207
+ ctx.workflowSlug = workflowResp.data.slug!
208
+ ```
209
+
210
+ ## 004 — create the Stripe data source
211
+
212
+ A workflow runs on rows; rows arrive through the data-activation
213
+ chain. The chain's first link is a `DataSource` — a registration
214
+ of where the rows originate. The `uri` is the system-of-record
215
+ address; it flows into each ingested row's `source_uri`, which
216
+ the customer template renders onto the MDM identifier `system`
217
+ URN.
218
+
219
+ ```typescript
220
+ const dataSourceResp = await api.dataSources.create(tenantSlug, datalakeSlug, {
221
+ name: `Cookbook Stripe Source ${runSuffix}`,
222
+ uri: 'stripe.example.com',
223
+ description: 'Stripe billing system — origin of the customer rows the dunning workflow runs on.',
224
+ status: 'active',
225
+ is_default: false,
226
+ })
227
+ dataSourceId = dataSourceResp.data.id!
228
+ ```
229
+
230
+ ## 005 — create the Manual Upload tool
231
+
232
+ The Data Activation Client needs a tool. For inline-JSON ingest a
233
+ `manual_upload` tool is the minimal choice — `intent:
234
+ 'data_exchange'` distinguishes it from the SMS tool, and
235
+ `tool_body_type: 'manual_upload'` needs no endpoint or credential
236
+ wiring (the rows arrive in the ingest call body, not by the tool
237
+ fetching them).
238
+
239
+ ```typescript
240
+ const manualUploadToolResp = await api.tools.create(tenantSlug, datalakeSlug, {
241
+ name: `Cookbook Manual Upload Tool ${runSuffix}`,
242
+ description: 'Manual-upload data-exchange tool — backs the DAC that ingests Stripe customer rows.',
243
+ intent: 'data_exchange',
244
+ status: 'active',
245
+ datalake_id: ctx.datalakeId,
246
+ data_source_id: dataSourceId,
247
+ body: { tool_body_type: 'manual_upload' },
248
+ })
249
+ ctx.manualUploadToolId = manualUploadToolResp.data.id!
250
+ ```
251
+
252
+ ## 006 — create the Stripe Customer interoperability contract
253
+
254
+ The interoperability contract is the row-shaping rule: a Liquid
255
+ template that maps an inbound Stripe customer row into an AR
256
+ `Customer` upsert. This cookbook loads the production Stripe
257
+ customer + MDM templates from the vendored fixtures directory
258
+ rather than inlining the Liquid.
259
+
260
+ Two template slots matter. `template_config` shapes the Customer
261
+ resource — including the nested `regulated_customer` object that
262
+ carries the PII fields (`name`, `email`, `phone`, `tax_id`).
263
+ `mdm_input_config` shapes the MDM input — the identifier
264
+ (`customer_number`), name, and contact fields the platform's
265
+ master-data resolution keys on to decide whether this is a new
266
+ customer or an existing one.
267
+
268
+ ```typescript
269
+ const { readFileSync } = await import('node:fs')
270
+ const { join } = await import('node:path')
271
+ const customerTemplate = readFileSync(
272
+ join(process.env.COOKBOOK_FIXTURES_DIR!, 'accounts_receivable/_customers_accounts_receivable_customer.liquid'),
273
+ 'utf8',
274
+ )
275
+ const mdmTemplate = readFileSync(
276
+ join(process.env.COOKBOOK_FIXTURES_DIR!, 'accounts_receivable/_customers_accounts_receivable_mdm.liquid'),
277
+ 'utf8',
278
+ )
279
+
280
+ const contractResp = await api.interoperabilityContracts.create(tenantSlug, datalakeSlug, {
281
+ name: `Cookbook Stripe Customer Contract ${runSuffix}`,
282
+ description: 'Stripe customers → AccountsReceivable Customer (custom Liquid + MDM input).',
283
+ resource_type: 'customer',
284
+ template_config: { type: 'custom', body: customerTemplate },
285
+ mdm_input_config: { type: 'custom', body: mdmTemplate },
286
+ generic_table_id: null,
287
+ })
288
+ interopContractId = contractResp.data.id!
289
+ ```
290
+
291
+ ## 007 — create the manual-upload DAC
292
+
293
+ The Data Activation Client binds the three preceding pieces — the
294
+ manual-upload tool, the data source, and the interop contract —
295
+ into one ingestion endpoint. `tool_call.tool_call_type:
296
+ 'manual_upload'` selects the inline-JSON ingest path. The
297
+ server-derived `slug` is the handle §008 ingests rows against.
298
+
299
+ ```typescript
300
+ const dacResp = await api.dataActivationClients.create(tenantSlug, datalakeSlug, {
301
+ name: `Cookbook Stripe Customer DAC ${runSuffix}`,
302
+ description: 'Manual-upload DAC — ingests Stripe customer rows into Customer via the interop contract.',
303
+ tool_id: ctx.manualUploadToolId,
304
+ data_source_id: dataSourceId,
305
+ tool_call: { tool_call_type: 'manual_upload' },
306
+ interoperability_contract_ids: [interopContractId],
307
+ })
308
+ dacId = dacResp.data.id!
309
+ ctx.dacSlug = dacResp.data.slug!
310
+ ```
311
+
312
+ ## 008 — ingest two Stripe customer rows
313
+
314
+ Two rows, ingested as inline JSON through the manual-upload DAC.
315
+ Both carry a phone number; they differ in `tax_id`. The first row
316
+ is KYC-complete — it has a verified tax id — so the filter
317
+ (`customer.phone and customer.tax_id`) will pass it. The second
318
+ omits `tax_id` entirely; even though it has a phone, the filter
319
+ must reject it. Each ingest call gets its own batch id; both are
320
+ pinned for the run scope in §010.
321
+
322
+ ```typescript
323
+ const phone4 = String(Date.now()).slice(-4)
324
+
325
+ const verifiedRow = {
326
+ customer_number: `CUST-KYC-${runSuffix}`,
327
+ customer_type: 'individual',
328
+ status: 'contracted',
329
+ name: 'Priya Anand',
330
+ email: `priya-${runSuffix}@example.com`,
331
+ phone: `+1202555${phone4}`,
332
+ tax_id: '123-45-6789',
333
+ currency: 'USD',
334
+ delinquent: 'true',
335
+ }
336
+ const unverifiedRow = {
337
+ customer_number: `CUST-NOKYC-${runSuffix}`,
338
+ customer_type: 'individual',
339
+ status: 'contracted',
340
+ name: 'Daniel Foster',
341
+ email: `daniel-${runSuffix}@example.com`,
342
+ phone: `+1203555${phone4}`,
343
+ currency: 'USD',
344
+ delinquent: 'true',
345
+ // tax_id intentionally absent — the workflow filter must reject this row
346
+ }
347
+
348
+ const [verifiedIngest, unverifiedIngest] = await Promise.all([
349
+ api.dataActivationClients.ingest(tenantSlug, datalakeSlug, ctx.dacSlug, { data: verifiedRow }),
350
+ api.dataActivationClients.ingest(tenantSlug, datalakeSlug, ctx.dacSlug, { data: unverifiedRow }),
351
+ ])
352
+ ctx.batchVerified = verifiedIngest.data.batch_id!
353
+ ctx.batchUnverified = unverifiedIngest.data.batch_id!
354
+ ```
355
+
356
+ ## 009 — wait for both ingest batches to reach steady-state
357
+
358
+ Ingestion is async — the DAC enqueues per-row jobs that the
359
+ `BatchMergeWorker` drains into the regulated customer table. Poll
360
+ the DAC's activation logs until both batches show a row with
361
+ `rows_ingested >= 1` and a non-empty `output_files` array (the
362
+ merged Parquet landed in object storage). Only then is it safe to
363
+ run the workflow against these rows.
364
+
365
+ ```typescript
366
+ const targetBatches = new Set([ctx.batchVerified, ctx.batchUnverified])
367
+ const deadline = Date.now() + 90_000
368
+ let greenCount = 0
369
+ while (Date.now() < deadline) {
370
+ const { data } = await api.dataActivationClients.logs.list(tenantSlug, datalakeSlug, ctx.dacSlug)
371
+ const green = new Set<string>()
372
+ for (const row of (data.data ?? []) as Array<Record<string, unknown>>) {
373
+ const b = row.batch_id
374
+ if (typeof b !== 'string' || !targetBatches.has(b)) continue
375
+ if (typeof row.rows_ingested !== 'number' || row.rows_ingested < 1) continue
376
+ const files = row.output_files
377
+ if (!Array.isArray(files) || files.length === 0) continue
378
+ green.add(b)
379
+ }
380
+ greenCount = green.size
381
+ if (greenCount === targetBatches.size) break
382
+ await new Promise((r) => setTimeout(r, 1_000))
383
+ }
384
+ if (greenCount !== targetBatches.size) {
385
+ throw new Error(`only ${greenCount}/2 customer batches reached steady-state within 90s`)
386
+ }
387
+ ```
388
+
389
+ ## 010 — run the workflow against the two batches
390
+
391
+ `workflows.run` with `manual_override: false` evaluates the
392
+ filter, so the `customer.phone and customer.tax_id` filter
393
+ genuinely routes each row. The SQL where-clause scopes the run to
394
+ exactly the two batches §008 ingested (`ra` is the
395
+ regulated-customer alias the run-query exposes).
396
+
397
+ The SMS action's `trigger_template: 'now'` dispatches the action
398
+ immediately rather than scheduling it, so the run reaches a
399
+ terminal status on its own — poll `batchLogs.refresh` until it
400
+ leaves `:pending`. A `:partial` status is expected and fine here:
401
+ one row passed and one was filtered.
402
+
403
+ ```typescript
404
+ const runResp = await api.workflows.run(tenantSlug, datalakeSlug, ctx.workflowSlug, {
405
+ sql_where_clause: `ra.batch_id IN ('${ctx.batchVerified}', '${ctx.batchUnverified}')`,
406
+ mode: 'live',
407
+ manual_override: false,
408
+ })
409
+ ctx.runLogId = runResp.data.workflow_run_log_id!
410
+ ctx.runBatchId = runResp.data.batch_id!
411
+
412
+ const deadline = Date.now() + 120_000
413
+ let status: string | null = null
414
+ while (Date.now() < deadline) {
415
+ const { data: log } = await api.workflows.batchLogs.refresh(tenantSlug, datalakeSlug, ctx.workflowSlug, ctx.runLogId)
416
+ status = log.status ?? null
417
+ if (status && status !== 'pending') break
418
+ await new Promise((r) => setTimeout(r, 2_000))
419
+ }
420
+ if (status === 'failed') throw new Error('workflow run reached :failed')
421
+ if (!status || status === 'pending') {
422
+ throw new Error('workflow run did not leave :pending within 120s')
423
+ }
424
+ ```
425
+
426
+ ## 011 — verify the filter routed: verified passes, unverified is filtered
427
+
428
+ Each row produced a Workflow Execution Log. The KYC-complete
429
+ customer (phone + tax id) passes the filter, so its WEL is
430
+ `:executing` or `:completed`. The customer missing the tax id
431
+ fails the filter, so its WEL is `:filtered`. A run where both
432
+ passed — or both were filtered — would mean the filter is not
433
+ actually evaluating both `customer.phone` and `customer.tax_id`.
434
+
435
+ ```typescript
436
+ const { data: wfLogs } = await api.workflows.workflowLogs.list(tenantSlug, datalakeSlug, ctx.workflowSlug)
437
+ const ourWels = (wfLogs.data ?? []).filter(
438
+ (w) => (w as { batch_id?: string }).batch_id === ctx.runBatchId,
439
+ )
440
+ if (ourWels.length !== 2) {
441
+ throw new Error(`expected 2 WELs for the run, got ${ourWels.length}`)
442
+ }
443
+
444
+ const byStatus: Record<string, number> = {}
445
+ for (const w of ourWels) {
446
+ const st = (w as { status?: string }).status ?? 'unknown'
447
+ byStatus[st] = (byStatus[st] ?? 0) + 1
448
+ }
449
+ const passCount = (byStatus.executing ?? 0) + (byStatus.completed ?? 0)
450
+ if (passCount !== 1) {
451
+ throw new Error(`expected 1 pass-branch WEL, got ${passCount} — distribution ${JSON.stringify(byStatus)}`)
452
+ }
453
+ if ((byStatus.filtered ?? 0) !== 1) {
454
+ throw new Error(
455
+ `expected 1 :filtered WEL (the tax-id-missing customer) — distribution ${JSON.stringify(byStatus)}`,
456
+ )
457
+ }
458
+ ```
459
+
460
+ ## 012 — read the rendered dunning SMS back from the message dataset
461
+
462
+ A `trigger_template: 'now'` action that passed the filter fires
463
+ immediately and persists a row in the regulated `message`
464
+ dataset, carrying the fully-rendered SMS body. Search that
465
+ dataset scoped to this workflow, poll until the row appears, and
466
+ extract the `/t/<token>` shortlink the platform baked into the
467
+ body when it minted the connected-app page token.
468
+
469
+ ```typescript
470
+ const { data: userSearch } = await api.datasets.createUserSearch(tenantSlug, datalakeSlug, 'message', {
471
+ search_query: `rm.workflow_id = '${workflowId}'`,
472
+ })
473
+ if (userSearch.status !== 'completed') {
474
+ throw new Error(`message user-search status=${userSearch.status} error=${userSearch.error_message ?? '(none)'}`)
475
+ }
476
+
477
+ const deadline = Date.now() + 45_000
478
+ let messages: Array<Record<string, unknown>> = []
479
+ while (Date.now() < deadline && messages.length === 0) {
480
+ const { data } = await api.datasets.search(tenantSlug, datalakeSlug, 'message', {
481
+ userSearchId: userSearch.id!,
482
+ dataAccessMode: 'regulated',
483
+ })
484
+ messages = (data.data ?? []) as Array<Record<string, unknown>>
485
+ if (messages.length === 0) await new Promise((r) => setTimeout(r, 1_000))
486
+ }
487
+ if (messages.length === 0) {
488
+ throw new Error('no dunning SMS message persisted for the workflow within 45s')
489
+ }
490
+
491
+ const withLink = messages
492
+ .map((m) => String(m.body ?? ''))
493
+ .find((body) => body.includes('/t/') && body.includes('needs your attention'))
494
+ if (!withLink) {
495
+ throw new Error(`no rendered dunning body with a /t/ link — bodies: ${JSON.stringify(messages.map((m) => m.body))}`)
496
+ }
497
+ const tokenMatch = withLink.match(/\/t\/([A-Za-z0-9_-]+)/)
498
+ if (!tokenMatch) {
499
+ throw new Error(`no /t/<token> in rendered body: ${withLink}`)
500
+ }
501
+ ctx.dunningShortPath = tokenMatch[1]!
502
+ ```
503
+
504
+ ## 013 — resolve the connected-app deep-link and post tracking
505
+
506
+ The `/t/<token>` shortlink the SMS carries resolves via
507
+ `connectedApps.resolvePage` — the `route_path` must match the
508
+ action's `connected_app_route`. Posting `opened_at` +
509
+ `form_submitted_at` via `updateMessageTracking` then mirrors what
510
+ the connected-app frontend does when the customer opens the
511
+ payment portal, closing the SMS → reply loop end-to-end.
512
+
513
+ ```typescript
514
+ const { data: resolved } = await api.connectedApps.resolvePage(tenantSlug, datalakeSlug, ctx.connectedAppSlug, {
515
+ short_path: ctx.dunningShortPath,
516
+ user_agent: 'cookbook-doctest/dunning-sms',
517
+ })
518
+ if (resolved.route_path !== '/portal/pay') {
519
+ throw new Error(`resolvePage route_path mismatch: ${resolved.route_path}`)
520
+ }
521
+ if (!(resolved.message?.body ?? '').includes('needs your attention')) {
522
+ throw new Error('resolved page message body missing the dunning copy')
523
+ }
524
+
525
+ const now = new Date().toISOString()
526
+ const { data: tracked } = await api.connectedApps.updateMessageTracking(tenantSlug, datalakeSlug, ctx.connectedAppSlug, {
527
+ short_path: ctx.dunningShortPath,
528
+ opened_at: now,
529
+ form_submitted_at: now,
530
+ })
531
+ if (!tracked.message?.opened_at || !tracked.message?.form_submitted_at) {
532
+ throw new Error('message tracking did not persist opened_at + form_submitted_at')
533
+ }
534
+ ```
535
+
536
+ # Branches
537
+
538
+ - **The unverified customer is filtered, not failed** — §011
539
+ asserts the tax-id-missing customer's WEL is `:filtered`, a
540
+ distinct terminal status from `:failed`. A filtered row is a
541
+ *correct* outcome: the workflow looked at it, the
542
+ `customer.phone and customer.tax_id` filter rendered empty
543
+ because one conjunct was falsy, and the platform recorded the
544
+ row as intentionally skipped. No SMS runs for a filtered row —
545
+ exactly the business rule (never dun a customer whose KYC is
546
+ incomplete).
547
+ - **Both conjuncts are load-bearing** — the filter is an `and` of
548
+ two preconditions. The §008 unverified row has a phone, so it
549
+ is the *tax-id* conjunct that fails it. A row missing the phone
550
+ instead would fail the same filter on the other conjunct. The
551
+ anchor vitest's §8 proves the opposite extreme: a filter gated
552
+ on a sentinel no customer can satisfy filters *every* row.
553
+ - **The thirty-day recency guard** — §003's `context_datasets`
554
+ entry queries the `message` dataset for a prior dunning SMS to
555
+ the same customer in the last 30 days. On this fresh tenant it
556
+ returns empty, so the action runs. On a tenant with history, a
557
+ recent prior dunning message would make the action skip — the
558
+ platform's built-in guard against dunning the same customer
559
+ repeatedly within one billing cycle.
560
+
561
+ # Rollback
562
+
563
+ The cookbook doctest harness does not currently tear down created
564
+ resources. The `_setup/accounts_receivable.md` setup file's
565
+ runSuffix-scoped tenant / datalake / user names mean each run is
566
+ naturally isolated; the seeded local DB is cheap to reset
567
+ (`mix ecto.reset` on the platform repo).
568
+
569
+ # Outcome
570
+
571
+ After this cookbook's thirteen steps run green:
572
+
573
+ - An accounts-receivable tenant exists with an
574
+ accounts-receivable-domain datalake
575
+ - An SMS tool, a Dunning payment-portal connected app, and a
576
+ Dunning SMS standard workflow (status `live`, `customer`
577
+ dataset) are registered
578
+ - A Stripe data source, a Manual Upload tool, a Stripe Customer
579
+ interop contract, and a manual-upload DAC form a working
580
+ ingestion chain
581
+ - Two customers have been ingested through that chain — one
582
+ KYC-complete, one missing a tax id
583
+ - Running the workflow routed them correctly: the verified
584
+ customer passed the phone + tax-id filter and dispatched an
585
+ SMS; the unverified customer was `:filtered`
586
+ - The rendered dunning SMS is readable from the `message`
587
+ dataset, carrying the "needs your attention" copy with the
588
+ overdue account number and a `/t/` deep-link
589
+ - The connected-app deep-link the SMS carried resolves, and
590
+ message tracking records the open + form-submit timestamps
591
+
592
+ The business outcome — a payment-reminder SMS sent to a reachable
593
+ and KYC-complete delinquent customer, with a working pay-invoice
594
+ link — is demonstrated end-to-end, not merely provisioned.
595
+
596
+ # See also
597
+
598
+ - `_setup/accounts_receivable.md` — the inlined bootstrap that
599
+ provisions the tenant + datalake this cookbook starts from
600
+ - `welcome-sms-for-customers.md` — the sibling AR cookbook; same
601
+ customer-dataset shape, a simpler phone-only filter
602
+ - `.agent/tools.md` — SMS (`tool_body_type: sns`) and
603
+ manual-upload tool body shapes; intent classification
604
+ - `.agent/connected_apps.md` — connected-app registration + the
605
+ resolve-page / message-tracking reply loop
606
+ - `.agent/interoperability_contracts.md` — custom contract shape,
607
+ `template_config` vs `mdm_input_config`
608
+ - `.agent/data_activation_clients.md` — data source → tool →
609
+ interop contract → DAC ingestion chain
610
+ - `.agent/workflows.md` — standard workflow primitive (filter +
611
+ decision + actions), `context_datasets`, `workflows.run`
612
+ - `.agent/cookbook/_fixtures/accounts_receivable/` — the vendored
613
+ Stripe customer / MDM Liquid templates §006 loads
614
+ - `integration-tests/tests/accounts_receivable/dunning-sms-workflow.test.ts` —
615
+ the anchor green test (§1–§8) these snippets are lifted from
616
+ - `integration-tests/tests/accounts_receivable/interoperability-contracts.test.ts`,
617
+ `run-dac-single.test.ts`, `create-dac.test.ts`, `tools.test.ts`,
618
+ `data-sources.test.ts` — the per-resource create + ingest
619
+ snippets §004–§009 are lifted from