@lovable.dev/workflows-sdk 0.0.0-dev.2 → 0.0.0-dev.20

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.
package/README.md CHANGED
@@ -15,11 +15,11 @@ from [`@tanstack/workflow-core`](https://github.com/TanStack/workflow).
15
15
  Schema validation libraries implementing Standard Schema, such as Zod, provide
16
16
  input and output inference.
17
17
 
18
- Keep the app's workflow collection in `app/workflows/index.ts`. Each workflow
19
- lives in `app/workflows/{workflow-name}/index.ts`, with its helpers alongside it:
18
+ Keep the app's workflow collection in `src/lib/workflows/index.ts`. Each workflow
19
+ lives in `src/lib/workflows/{workflow-name}/index.ts`, with its helpers alongside it:
20
20
 
21
21
  ```text
22
- app/workflows/
22
+ src/lib/workflows/
23
23
  ├── index.ts
24
24
  └── greet/
25
25
  ├── index.ts
@@ -43,40 +43,241 @@ names. An empty collection is valid. Registration copies the list, retains the
43
43
  definitions, and does not execute handlers or register global state. Treat
44
44
  definitions as immutable after registration.
45
45
 
46
- See [the authoring example](examples/workflows.ts) for schemas, typed middleware,
47
- and a durable step. The package typecheck includes this example.
46
+ See [the authoring example](examples/src/lib/workflows/greet/index.ts) for schemas,
47
+ typed middleware, and a durable step. The package typecheck includes this example.
48
+
49
+ Every durable operation needs a static, user-facing description. Lovable's
50
+ agent supplies this text so the workflow UI can explain each operation before
51
+ and during a run. Put it in the operation's options:
52
+
53
+ | Operation | Description field |
54
+ | --- | --- |
55
+ | `ctx.step` | Third argument: `meta.description` |
56
+ | `ctx.sleep`, `ctx.sleepUntil` | Second argument: `meta.description` |
57
+ | `ctx.waitForEvent` | Second argument: `meta.description` |
58
+ | `ctx.now`, `ctx.uuid` | First argument: `meta.description` |
59
+ | `ctx.approve` | First argument: `description` |
60
+
61
+ ```ts
62
+ await ctx.step("load-customer", () => loadCustomer(ctx.input.customerId), {
63
+ meta: { description: "Load the customer record" },
64
+ });
65
+ ```
66
+
67
+ Manifest generation rejects a missing or computed description. A step declared
68
+ inside a loop or callback also needs a group with a stable ID and user-facing
69
+ label. The group identifies the repeated callsite while each runtime step keeps
70
+ its own concrete ID:
71
+
72
+ ```ts
73
+ await Promise.all(
74
+ ctx.input.items.map((item) =>
75
+ ctx.step(`process-${item.id}`, () => processItem(item), {
76
+ meta: {
77
+ description: "Process an item",
78
+ group: { id: "process-items", label: "Process items" },
79
+ },
80
+ }),
81
+ ),
82
+ );
83
+ ```
84
+
85
+ Group IDs are unique per workflow callsite. Ordinary sequential steps and
86
+ fixed `Promise.all([stepA, stepB])` branches do not need a group.
87
+
88
+ ## Triggers
89
+
90
+ A workflow runs when something triggers it, and a schedule is the first kind of
91
+ trigger: a clock. Triggers go in `registerWorkflows({ workflows, triggers })`,
92
+ and each carries a `type` naming its kind. Webhook and app-event triggers will
93
+ join the same array.
94
+
95
+ A schedule's *cadence* is how often the clock fires. `hourly()`, `daily()`,
96
+ and `weekly()` build one; there is no raw cron.
48
97
 
49
98
  ## Schedules
50
99
 
51
- Declare a schedule with `defineSchedule({ id, workflow, cron, timeZone, input })`
52
- and include it in `registerWorkflows({ workflows, schedules })`. `workflow` refers
53
- to the same definition object included in `workflows`; `input` is required and
54
- inferred from that workflow. Multiple schedules can target one workflow.
100
+ Declare a schedule with `defineSchedule({ id, workflow, cadence, timeZone, input })` and
101
+ include it in `registerWorkflows({ workflows, triggers })`. `workflow` refers to
102
+ the same definition object included in `workflows`; `input` is required and
103
+ inferred from that workflow. Multiple schedules can target one workflow. Schedule
104
+ IDs must be unique within the app's collection. This API declares schedules but
105
+ does not install timers or start runs.
55
106
 
56
- Use a five-field cron expression (minute, hour, day, month, weekday) and an IANA
57
- time zone; the default is UTC. Schedule IDs must be unique within the app's
58
- collection. Registration checks field count and time zone; cron syntax and
59
- calendar semantics remain the engine's responsibility. This API declares
60
- schedules but does not install timers or start runs. Periodic intervals,
61
- catch-up, and overlap policies remain follow-ups.
107
+ ```ts
108
+ import { daily, defineSchedule, hourly, weekly } from "@lovable.dev/workflows-sdk";
109
+
110
+ defineSchedule({ id: "sweep", workflow: sync, cadence: hourly(), timeZone: "UTC", input: {} });
111
+ defineSchedule({ id: "digest", workflow: digest, cadence: daily(), timeZone: "Europe/Stockholm", input: {} });
112
+
113
+ defineSchedule({
114
+ id: "refresh",
115
+ workflow: sync,
116
+ cadence: daily({ at: [0, 6, 12, 18] }),
117
+ timeZone: "UTC",
118
+ input: {},
119
+ });
120
+
121
+ defineSchedule({
122
+ id: "weekday-digest",
123
+ workflow: digest,
124
+ cadence: daily({ at: 9, days: ["mon", "tue", "wed", "thu", "fri"] }),
125
+ timeZone: "America/New_York",
126
+ input: {},
127
+ });
128
+
129
+ defineSchedule({
130
+ id: "monday-report",
131
+ workflow: report,
132
+ cadence: weekly({ on: "monday", at: 7 }),
133
+ timeZone: "Europe/Stockholm",
134
+ input: {},
135
+ });
136
+ ```
62
137
 
63
- The [example](examples/workflows.ts) declares a daily greeting at 09:00 in
64
- Europe/Stockholm with static workflow input.
138
+ | Field | Default | Meaning |
139
+ | --- | --- | --- |
140
+ | `cadence` | — | `hourly()`, `daily()`, or `weekly()` |
141
+ | `timeZone` | — | IANA region name the cadence is interpreted in |
142
+ | `overlapPolicy` | `"skip"` | `skip`, `allow`, or `buffer-one` |
143
+ | `enabled` | `true` | `false` declares a paused schedule without deleting it |
144
+
145
+ There are three cadences and no raw cron:
146
+
147
+ | Cadence | Says | Example |
148
+ | --- | --- | --- |
149
+ | `hourly()` | once an hour | `hourly()` |
150
+ | `daily({ at, days })` | hours of the day, days of the week | `daily({ at: [0, 6, 12, 18] })` |
151
+ | `weekly({ on, at })` | one weekday, hours of the day | `weekly({ on: "monday", at: 7 })` |
152
+
153
+ **The SDK never derives a cron.** The manifest carries the cadence, and the
154
+ `app-workflows-service` backend translates it when it registers the schedule.
155
+ An app declares intent; one service owns the translation, so there is no second
156
+ implementation to drift. Every cadence here is shaped to be exactly
157
+ translatable — that constraint is why the vocabulary is closed and why `at` is
158
+ whole hours.
159
+
160
+ ### Hours, never minutes
161
+
162
+ `at` is a whole hour, `0` through `23`, or a list of them. There is no minute:
163
+ an app says *which hours*, and the platform picks where inside the hour a run
164
+ actually starts (see [Timing](#timing)). `hourly()` takes no options for the
165
+ same reason. An app that could pin a minute would opt itself out of the smear,
166
+ and the herd would come back.
167
+
168
+ This is also what keeps the vocabulary exactly translatable by the backend.
169
+ Cron pairs every value in its minute field with every value in its hour field,
170
+ so a cadence that could say 09:15 and 17:45 has no faithful cron — it would
171
+ become `15,45 9,17 * * *` and fire four times a day instead of twice. With the
172
+ minute fixed, any set of hours translates exactly.
173
+
174
+ `at` accepts a list, so several runs a day need one schedule rather than
175
+ several: `daily({ at: [0, 6, 12, 18] })` is four evenly spaced runs, and
176
+ `daily({ at: [9, 17] })` is two uneven ones — the start and end of a working
177
+ day, which no fixed interval can express. The list is sorted and deduplicated,
178
+ so two orderings are one schedule.
179
+
180
+ ### One schedule, one representation
181
+
182
+ `weekly({ on, at })` is the single-day shorthand for `daily({ at, days: [on] })`
183
+ and resolves into exactly that cadence. There is one internal representation of
184
+ a day-restricted schedule, so the two spellings emit byte-identical manifests
185
+ and hash alike.
186
+
187
+ There is no `"weekdays"` or `"weekends"` shorthand: it would add a third
188
+ spelling of a set `days` already states, and "the weekend" is Friday and
189
+ Saturday in much of the world, so the word would quietly mean the wrong days.
190
+
191
+ There is no interval cadence — no `every("6h")`, no `every("3d")`. Intervals
192
+ are not calendar positions and have no faithful cron: `0 0 */3 * *` restarts its
193
+ count every month, so it means "every 3 days" only until the 28th and then fires
194
+ twice in two days. The sub-daily intervals that *are* faithful are exactly the
195
+ ones `daily({ at })` already covers, and `daily({ at: [0, 6, 12, 18] })` says the
196
+ same thing as "every 6 hours" while staying anchored to the calendar and to the
197
+ app's time zone.
198
+
199
+ ## Timing
200
+
201
+ **A declared hour is approximate, and an app does not control how approximate.**
202
+ Tens of thousands of apps declaring `daily()` must not fire in the same minute,
203
+ so the platform spreads each schedule over a window — a *smear* — and then keeps
204
+ that schedule on the same offset for every later run.
205
+
206
+ Apps do not declare the smear, and there is no field for it. The platform
207
+ derives the window per schedule from the cadence, so what an app leaves
208
+ unspecified is exactly what the platform is free to choose:
209
+
210
+ | Cadence | Smeared across |
211
+ | --- | --- |
212
+ | `daily()` | the whole day |
213
+ | `daily({ at })`, `weekly({ on, at })` | a window around each declared hour |
214
+ | `hourly()` | the hour |
215
+
216
+ Higher plans get tighter windows, so a declared 07:00 lands nearer to 07:00 the
217
+ more an app pays; the exact windows belong to the platform and can change
218
+ without an SDK release.
219
+
220
+ Two consequences worth designing around. A schedule that must run at an exact
221
+ instant is not expressible, by design. And the offset is stable per schedule,
222
+ not random per run, so a report that reads "yesterday's rows" reads the same
223
+ shape every day.
224
+
225
+ Neither the smear nor the schedule itself runs yet; see
226
+ [Next PRs](#next-prs).
227
+
228
+ ### Time zone
229
+
230
+ `timeZone` is required on every schedule. There is no default, because every
231
+ available default is wrong: `daily({ at: 9 })` in UTC is not the 09:00 a reader
232
+ of the digest expects, and the build machine's own zone would make one app
233
+ source fire at different times depending on where it was built.
234
+
235
+ It must be `"UTC"` or a canonical IANA name as `Intl.supportedValuesOf("timeZone")`
236
+ lists it, such as `"Europe/Stockholm"`. That rejects the fixed-offset family
237
+ `Intl` otherwise accepts — `"+05:00"`, `"-0800"`, `"EST"`, `"GMT"`,
238
+ `"Etc/GMT+5"` — none of which observe daylight saving, so `"EST"` is an hour
239
+ off US Eastern for two-thirds of the year, and `"Etc/GMT+5"` is UTC-5 rather
240
+ than UTC+5. It also rejects tzdata's backward-compatibility aliases such as
241
+ `"US/Pacific"`; write the canonical `"America/Los_Angeles"`, so one zone has
242
+ one spelling and one manifest.
243
+
244
+ ### Overlap policy
245
+
246
+ `overlapPolicy` says what happens when an occurrence comes due while the
247
+ previous run is still going: `skip` drops it, `allow` lets runs overlap, and
248
+ `buffer-one` holds the earliest due occurrence and fires it once the in-flight
249
+ run finishes.
250
+
251
+ ### Validation
252
+
253
+ Everything is validated when the schedule is defined, at build time: an hour
254
+ outside `0`-`23`, a fractional hour, a weekday name that is not a weekday, an
255
+ unknown `overlapPolicy`, a missing or non-canonical zone, and a hand-written
256
+ cadence object no constructor produced all fail the build. `registerWorkflows`
257
+ likewise rejects any key other than `workflows` and `triggers`, so a collection
258
+ left on the old `schedules:` name fails the build instead of emitting an empty
259
+ manifest.
260
+
261
+ The [example](examples/src/lib/workflows/index.ts) declares a 09:00 greeting in
262
+ Europe/Stockholm, a weekday greeting in America/New_York, a Monday report, a
263
+ four-times-daily refresh, an hourly sweep, and a paused daily digest.
65
264
 
66
265
  ## Manifest generation
67
266
 
68
- Add `workflowsManifest({ entry: "app/workflows/index.ts" })` from
69
- `@lovable.dev/workflows-sdk/vite` to the app's Vite plugins. The entry must
70
- default-export its `registerWorkflows()` collection. Each production build writes
267
+ Add `workflowsPlugin()` from `@lovable.dev/workflows-sdk/vite` to the app's Vite
268
+ plugins. Its `entry` defaults to `src/lib/workflows/index.ts` and must
269
+ default-export the app's `registerWorkflows()` collection. Each production build writes
71
270
  one manifest per workflow to `.lovable/workflows/{workflow-name}.json` relative
72
271
  to the app root. For example, `greet` produces `.lovable/workflows/greet.json`.
73
272
  Generation errors fail the build. See [the Vite example](examples/vite.config.ts).
74
273
 
75
274
  Each version-1 manifest contains a single `workflow` with its ID, description,
76
275
  version, and input/output/state JSON Schemas, a `graph` for visualization, and a
77
- `schedules` array containing only that workflow's schedules and static inputs. It is an SDK discovery format,
78
- not the engine's deployment or execution contract. Handlers and middleware stay
79
- in app code. Schedule IDs and JSON object keys are sorted for stable output.
276
+ `triggers` array containing only that workflow's triggers and static inputs. Each
277
+ entry names its kind in `type` — `"schedule"` today — and a schedule entry carries
278
+ its `cadence`, `timeZone`, `enabled`, `overlapPolicy`, and `input`. It is an SDK discovery format, not the engine's deployment or execution
279
+ contract. Handlers and middleware stay in app code. Triggers and JSON object keys
280
+ are sorted for stable output.
80
281
 
81
282
  The SDK manages the JSON files in `.lovable/workflows/`. Successful generation
82
283
  removes manifests for deleted or renamed workflows; an empty collection removes
@@ -109,52 +310,389 @@ from a Lovable template already have it. Without it — or with a copy exposing
109
310
  stable JS API, as TypeScript 7 does before 7.1 — the build still succeeds and
110
311
  every graph carries one `unknown` node and the diagnostic
111
312
  `Install typescript to infer step graphs`.
112
- Sequential awaited `ctx.step("name", callback)` calls produce order edges;
313
+ Sequential awaited `ctx.step("name", callback, options)` calls produce order edges;
113
314
  `await Promise.all([ctx.step(...), ctx.step(...)])` produces parallel branches
114
- that join at the next step. Returned step promises work too. Keep step IDs literal.
315
+ that join at the next step. A `Promise.all()` mapped over a collection with the
316
+ step ID template `step-${item.id}` produces one dynamic parallel node labeled
317
+ from `meta.group.label`. Returned step promises work too. Keep step IDs literal
318
+ outside this mapped form.
319
+
320
+ An `if` whose body contains durable operations produces a `branch` node. Every
321
+ durable operation inside it includes an outer-to-inner `meta.branches` path;
322
+ each entry has a static `id` and agent-written `description`. Both sides of one
323
+ condition use the same entry. The AST determines nesting and whether an edge is
324
+ the `true` or `false` outcome, so metadata never declares topology. Branch IDs
325
+ identify one `if` statement within the workflow.
326
+
327
+ ```ts
328
+ meta: {
329
+ description: "Publish the approved draft",
330
+ branches: [{ id: "editor-approved", description: "The editor approved the draft" }],
331
+ }
332
+ ```
115
333
 
116
334
  | Field | Meaning |
117
335
  | --- | --- |
118
336
  | `nodes[].id` | Unique occurrence ID within this graph; use as the UI node key |
119
- | `nodes[].kind` | `step` or `unknown` |
120
- | `nodes[].stepId` | Literal step name, present for known steps |
121
- | `nodes[].label` | Step name or explanation of unsupported code |
122
- | `edges[]` | `{ source, target, kind: "order" }`, referencing node IDs |
337
+ | `nodes[].kind` | Durable operation, `branch`, `parallel`, or `unknown` |
338
+ | `nodes[].stepId` | Runtime durable ID for every statically known operation |
339
+ | `nodes[].description` | User-facing description for every known durable operation and branch |
340
+ | `nodes[].branchId` | Stable ID for an inferred `if` node |
341
+ | `nodes[].condition` | Source expression from the corresponding `if` statement |
342
+ | `nodes[].groupId` | Stable callsite ID for a dynamic parallel node |
343
+ | `nodes[].cardinality` | `dynamic` for a runtime-sized parallel fan-out |
344
+ | `nodes[].operation.kind` | Durable operation repeated by a parallel node |
345
+ | `nodes[].operation.stepIdTemplate` | Display template for steps in a dynamic parallel node |
346
+ | `nodes[].operation.description` | User-facing description shared by the repeated steps |
347
+ | `nodes[].label` | Step ID, branch description, group label, or explanation of unsupported code |
348
+ | `edges[]` | Order edges or branch edges with an AST-derived boolean `outcome`, referencing node IDs |
123
349
  | `complete` | Whether the handler uses only supported syntax |
124
350
  | `diagnostics` | Reasons the graph is partial |
125
351
 
126
352
  For example, `read` followed by parallel `transform-a` and `transform-b`, then
127
353
  `save`, produces `read → transform-a → save` and `read → transform-b → save`.
128
- Repeated step names remain separate nodes. Node IDs are deterministic for the
129
- same source, but may change when the handler is edited.
354
+ Node IDs are deterministic for the same source, but may change when the handler
355
+ is edited.
356
+
357
+ Known durable nodes use the same `stepId` as runtime progress records. An
358
+ explicit `{ id }` wins; otherwise the graph and runtime share the operation's
359
+ derived default. `label` remains the display name.
130
360
 
131
361
  Graphs have `source: "inferred"` and `scope: "handler"`. They describe source
132
362
  structure, not run history or data dependencies, and exclude middleware and
133
- initialization. Branches, loops, helper calls, dynamic step IDs, nested steps,
363
+ initialization. A mapped `Promise.all` is complete when its callback directly
364
+ returns `ctx.step()` with a template-literal ID derived from a callback parameter.
365
+ Loops, switch statements, conditional expressions, helper calls, dynamic step IDs,
134
366
  and unawaited steps produce `unknown` nodes and `complete: false`; steps inside
135
- unsupported code are not expanded. The UI should show these unknown nodes and
136
- mark partial graphs. Transforms that rewrite the handler may also produce a
137
- partial graph. A handler with no steps can have an empty graph.
367
+ unsupported code are not expanded. The UI should show these unknown nodes and mark
368
+ partial graphs. Transforms that rewrite the handler may also produce a partial
369
+ graph. A handler with no steps can have an empty graph.
370
+
371
+ A step body is one atomic execution unit. Manifest generation rejects statically
372
+ visible durable calls inside it, including `ctx.step`, `ctx.sleep`, `ctx.now`,
373
+ and the other `ctx.*` operations. Move each durable operation into the workflow
374
+ handler and pass its result into the step instead.
375
+
376
+ Keep the workflow context in the handler. Manifest generation rejects passing,
377
+ aliasing, destructuring, or returning `ctx`, and rejects detached durable methods
378
+ such as `helper(ctx.step)`. Pass only extracted data such as `ctx.input` to
379
+ helpers instead. This keeps durable control flow visible in the handler source
380
+ used to build the graph.
381
+
382
+ ## Steps endpoint (TanStack Start)
383
+
384
+ The same `workflowsPlugin` that writes the manifests also emits
385
+ `src/routes/api/workflows/$workflowId/steps.ts`, serving every registered
386
+ workflow. There is no opt-in: a declared workflow with no endpoint cannot run.
387
+ One plugin and one `entry` feed the manifest and route, so they cannot describe
388
+ different workflow collections:
389
+
390
+ ```ts
391
+ import { tanstackStart } from "@tanstack/react-start/plugin/vite";
392
+ import { workflowsPlugin } from "@lovable.dev/workflows-sdk/vite";
393
+
394
+ export default defineConfig({
395
+ plugins: [workflowsPlugin(), tanstackStart()],
396
+ });
397
+ ```
398
+
399
+ A missing `entry` file is the only thing that suppresses the route: an app with
400
+ no collection gets no endpoint.
401
+
402
+ ### The route is unauthenticated
403
+
404
+ **Any caller who reaches the route can run any declared workflow.** The SDK
405
+ ships no request authentication today; signed invocation is the next piece of
406
+ work on this endpoint. Until it lands, treat the endpoint as public and keep
407
+ anything a stranger must not trigger — spend, mutation of another user's data,
408
+ outbound mail — out of a declared workflow, or guard it inside the handler.
409
+
410
+ Reachability is the lever an app has in the meantime. Public apps expose the
411
+ route to the internet. Workspace and private apps are gated by the Lovable host,
412
+ which is why `path` matters (below).
413
+
414
+ ### Relocating the route with `path`
415
+
416
+ `path` sets the URL prefix; the workflow ID is appended as a dynamic segment,
417
+ and the emitted file name follows the path. Workspace and private apps reach
418
+ anonymous traffic only under an `/api/public` prefix — everything else is
419
+ blocked by the host before it reaches the app — so those projects must move the
420
+ route there for it to be reachable at all:
421
+
422
+ ```ts
423
+ workflowsPlugin({ path: "/api/public/workflows" });
424
+ ```
425
+
426
+ That emits `src/routes/api/public/workflows/$workflowId/steps.ts` and serves
427
+ `POST /api/public/workflows/{workflow-id}/steps`. The trade is explicit: the
428
+ prefix that makes the route reachable also makes it anonymously reachable.
429
+
430
+ The emitted file imports the collection and mounts its package handler. All
431
+ runtime logic stays in the package. A generated banner is the plugin's
432
+ ownership token: it rewrites and deletes only files that have it, and deletes
433
+ its own orphans when `path` or `workflowIdParam` changes. Delete the banner line
434
+ to take the route over. That is also the supported way to add a check of your
435
+ own in front of the handler.
436
+
437
+ | Option | Default | Meaning |
438
+ | --- | --- | --- |
439
+ | `entry` | `src/lib/workflows/index.ts` | Collection entry; a missing file means no route |
440
+ | `routesDir` | `src/routes` | Where the route file is written |
441
+ | `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
442
+ | `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
443
+
444
+ ### How the emitted file imports the collection
445
+
446
+ The plugin prefers an alias, so the specifier does not change when `path` moves:
447
+
448
+ ```ts
449
+ import workflows from "@/lib/workflows/index";
450
+ ```
451
+
452
+ It does not assume `@`. It reads the app's Vite `resolve.alias` and its
453
+ tsconfig `compilerOptions.paths`, and picks an alias whose target directory
454
+ contains the collection entry — preferring one both sources declare, then the
455
+ deepest match.
456
+
457
+ An alias is only emitted when the *bundler* can resolve it: a Vite
458
+ `resolve.alias` entry, or a tsconfig `paths` entry when a plugin such as
459
+ `vite-tsconfig-paths` is active. A tsconfig `paths` entry alone instructs the
460
+ typechecker and not the bundler, so emitting it would fail the build.
461
+
462
+ When no alias qualifies, the plugin falls back to a relative specifier
463
+ (`../../../lib/workflows/index`), which always resolves. An app with no alias
464
+ configured still builds; only the specifier is uglier, and its depth tracks
465
+ `path`.
466
+
467
+ ### Calling it
468
+
469
+ Each workflow gets one route for an external engine to drive one atomic step per
470
+ request.
471
+
472
+ | Route | Does |
473
+ | --- | --- |
474
+ | `POST /api/workflows/{id}/steps` | Advances a singleton frontier or executes one selected step |
475
+
476
+ An unknown workflow ID returns 404 and an unparseable body 400.
477
+
478
+ ### The memo is the run
479
+
480
+ There is no run store. A run's entire state is its **memo** — the list of
481
+ settled operations — and the caller carries it between calls:
482
+
483
+ ```jsonc
484
+ [{
485
+ "seq": 0,
486
+ "stepId": "greeting",
487
+ "occurrence": 0,
488
+ "kind": "step",
489
+ "meta": { "description": "Create a personalized greeting" },
490
+ "status": "completed",
491
+ "result": "Hello, yehya!"
492
+ }]
493
+ ```
494
+
495
+ An entry is keyed by `stepId` and `occurrence` (which call of that id in the
496
+ run, from 0) — never by position or `seq`. Two parallel branches can reach the
497
+ same pair of operations in either order from one pass to the next, so call order
498
+ is reported but is not the identity.
499
+
500
+ Every response returns a `memoDelta` and an `inputHash`. Merge the delta into the
501
+ memo by `(stepId, occurrence)`, then send the full memo, `inputHash`, `runId`, and
502
+ the same `input` on the next call. Replay re-runs the handler from the top, and
503
+ the memo does not carry the input. `inputHash` binds the memo to the input it came
504
+ from: resuming with a different one is a 400. Key order in the input does not
505
+ affect it. Because state travels in the request, a run survives a restart and can
506
+ continue on a different instance.
507
+
508
+ Replay is what makes this work: the handler re-runs from the top on every call,
509
+ settled operations answer from the memo instead of executing again, and
510
+ `ctx.state` plus ordinary control flow rebuild themselves. A settled operation
511
+ can sit beside an earlier pending one — `ctx.now()` pinned next to a step still
512
+ waiting in the same `Promise.all`. An entry must match the kind of operation
513
+ replay finds at its id, so a tampered or stale memo fails the call rather than
514
+ answering the wrong one:
515
+
516
+ ```json
517
+ { "disposition": "failed", "error": "non-deterministic replay: memo has approve \"thing\" (#0), replay produced step" }
518
+ ```
519
+
520
+ **Every step ID must be unique within a workflow.** Manifest generation rejects
521
+ a repeated literal ID in sequential calls, parallel branches, mutually exclusive
522
+ branches, loops, and callbacks. Dynamic IDs cannot be proven at build time, so
523
+ the runtime refuses the second step that resolves to an ID already reached.
524
+
525
+ `ctx.now()`, `ctx.uuid()`, `ctx.sleep(ms)` and the other durable operations fall
526
+ back to a default ID. Two calls sharing one cannot be told apart on replay, so
527
+ the second is refused. Pass `{ id }` per call site: `ctx.now({ id: "started" })`.
528
+
529
+ Manifest generation rejects this before a run exists, when the arguments are
530
+ literal:
531
+
532
+ ```text
533
+ workflow "greet" calls ctx.now() 2 times with the default id "now";
534
+ replay cannot tell them apart, so pass an explicit { id } per call site
535
+ ```
536
+
537
+ The same applies to two `ctx.sleep(1000)` calls, two waits on one event name, or
538
+ two approvals with one title. Their default ID is derived from the argument, so
539
+ only a repeated argument collides. A dynamic argument is left to the runtime
540
+ check.
541
+
542
+ **Handler code outside a step runs on every call.** Keep side effects inside
543
+ `ctx.step`, which is memoized; a bare `fetch` in the handler body repeats each
544
+ pass. A pass also allows only a bounded amount of such work — 5s by default —
545
+ before reporting the run stalled.
546
+
547
+ ### The memo is unauthenticated input
548
+
549
+ **A caller supplies the memo, and the route does not authenticate it.** Anything
550
+ the memo says is already settled is taken as settled, including an approval's
551
+ decision. A caller who can reach the route can therefore hand back
552
+ `{"kind": "approve", "status": "completed", "result": {"approved": true}}` and
553
+ skip the human, or mark an expensive step completed with a fabricated result and
554
+ skip the work. `inputHash` binds a memo to one input, so a forged memo cannot be
555
+ replayed against a different record, but it is computed from the request and so
556
+ is no barrier on its own.
557
+
558
+ Until signed invocation lands, **do not treat `ctx.approve` as a security
559
+ boundary on these routes**, and do not put an operation behind one that a
560
+ stranger must not be able to declare done. Reachability is the only control an
561
+ app has in the meantime; see `path` above.
562
+
563
+ ### Stepping through a run
564
+
565
+ ```bash
566
+ POST /api/workflows/greet/steps
567
+ { "input": { "name": "yehya" } }
568
+ -> { "disposition": "advanced",
569
+ "executed": { "stepId": "greeting", "occurrence": 0, "kind": "step", "status": "completed" },
570
+ "memoDelta": [{ "stepId": "greeting", "occurrence": 0, ... }],
571
+ "next": [{ "seq": 1, "stepId": "shout", "occurrence": 0, "kind": "step" }] }
572
+
573
+ POST /api/workflows/greet/steps
574
+ { "action": "execute", "step": { "stepId": "shout", "occurrence": 0, "kind": "step" },
575
+ "input": { "name": "yehya" }, "memo": [...], "inputHash": "9f2c...", "runId": "run_..." }
576
+ -> { "disposition": "completed", "memoDelta": [...], "next": [], "output": "HELLO, YEHYA!" }
577
+ ```
578
+
579
+ Omitting `action` means `"advance"`. When the current frontier contains exactly
580
+ one app-executable step, `advance` executes it and returns the next frontier. A
581
+ sequential workflow therefore needs one HTTP call per step, including the first.
582
+
583
+ ### Driving a run from an orchestrator
584
+
585
+ Use the response disposition to choose the next call:
586
+
587
+ | Disposition | Engine action |
588
+ | --- | --- |
589
+ | `advanced` | Merge `memoDelta`, then execute the single entry in `next`. |
590
+ | `fork` | Merge `memoDelta`, then execute each app-executable entry in `next` in a separate concurrent request using that same memo. |
591
+ | `waiting` | Settle the external operations in `next`, then call `advance`. |
592
+ | `completed` | Persist `output`; the run is done. |
593
+ | `failed` | Apply the engine's retry or failure policy. |
594
+
595
+ At a fork, every `execute` request receives the same base memo and selects one
596
+ `{ kind: "step", stepId, occurrence }`. Merge all returned deltas, then call
597
+ `advance` once. That replay crosses the join and immediately executes a
598
+ singleton tail when one exists. Do not schedule from one branch's `next`: a
599
+ partial branch response cannot see results still running in its siblings.
600
+
601
+ An `execute` call runs only its selected step. The endpoint returns 409
602
+ `stale_step` if that reference is not executable from the supplied memo.
603
+
604
+ Keep a step's result small: it travels in the memo on every later call, so a
605
+ large payload is resent for the rest of the run. Write bulk data to storage
606
+ inside the step and return the key.
607
+
608
+ Each call re-runs the handler from the top. Step bodies run only in their
609
+ selected request, so side effects belong inside a step.
610
+
611
+ `next` reports an operation's `stepId`, `kind`, and author-supplied `meta`,
612
+ including its description and group. An approval's top-level authoring
613
+ description is copied into runtime metadata for the same response shape. `next`
614
+ does not report a step's input:
615
+ `ctx.step(id, fn, options)` closes over its arguments rather than declaring
616
+ them, so the input is not knowable without running `fn`. Deterministic values
617
+ (`ctx.now`, `ctx.uuid`) are pinned into `memoDelta`, so concurrent calls replay
618
+ the same values after the engine merges the delta.
619
+
620
+ ### Waiting on something outside the app
621
+
622
+ `ctx.sleep`, `ctx.waitForEvent` and `ctx.approve` cannot be settled by the app,
623
+ so they are never executed — they come back as pending operations carrying what
624
+ a caller needs to resolve them:
625
+
626
+ ```json
627
+ { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
628
+ "meta": { "description": "Ask a reviewer to approve the refund" },
629
+ "config": { "title": "Approve refund", "description": "Ask a reviewer to approve the refund" } }
630
+ ```
631
+
632
+ The endpoint returns `waiting` with that list in `next`. Resume by appending the
633
+ decision to the memo, preserving its `meta`, and calling `advance`:
634
+
635
+ ```jsonc
636
+ { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
637
+ "meta": { "description": "Ask a reviewer to approve the refund" },
638
+ "status": "completed", "result": { "approved": true, "approvalId": "apr_1" } }
639
+ ```
640
+
641
+ `createTanStackWorkflowHandler` is still exported for the engine-backed path
642
+ (`runWorkflow` plus a `RunStore`, `inMemoryRunStore()` by default). No emitted
643
+ route uses it: a process-local store loses runs on restart and is invisible to
644
+ other instances, which is what the memo model replaces.
645
+
646
+ ### Not yet carried over
647
+
648
+ `ctx.step`'s `retries` and `timeout` options are accepted and ignored — the
649
+ caller decides whether to re-issue a failed step. Step retry, timeouts, and
650
+ `previousVersions` routing are follow-ups.
651
+
652
+ The path carries no build ID. Version pinning belongs to the signed invocation,
653
+ which leaves it stable across deployments and safe to publish in a manifest.
654
+ Triggers name a workflow rather than an endpoint, so no trigger identifier
655
+ appears in the URL.
656
+
657
+ ## Public entry points
658
+
659
+ The package has two, and neither mirrors the source tree:
660
+
661
+ | Import | Provides |
662
+ | --- | --- |
663
+ | `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and the `createStepsHandler` route handler |
664
+ | `@lovable.dev/workflows-sdk/vite` | `workflowsPlugin`, the build-time Vite plugin |
665
+
666
+ The export map is a contract; the directory layout under `src/` is not. They are
667
+ deliberately decoupled, so the package can be reorganised without a breaking
668
+ change for apps that already have an emitted route.
669
+
670
+ The package sets `"sideEffects": false` and the handler is a plain re-export, so
671
+ a client bundle importing only authoring APIs drops the execution engine.
138
672
 
139
673
  ## Next PRs
140
674
 
141
675
  Connect the manifest and app code to Lovable deployment and runtime execution.
142
- Define support for TanStack primitives, version routing, and schedule policies.
676
+ Derive and apply the per-schedule smear on the control plane. Define support for
677
+ TanStack primitives, version routing, and schedule policies.
678
+ Add webhook and app-event triggers to the same `triggers` array.
143
679
 
144
680
  ## Publishing dev builds
145
681
 
146
682
  The [publishing workflow](../../.github/workflows/publish-workflows-sdk.yml)
147
- publishes the version committed in `package.json` to npm's `dev` tag when SDK
683
+ publishes the version committed in `package.json` to npm's `latest` tag when SDK
148
684
  changes land on `main`. Manage versions manually: `0.0.0-dev`, `0.0.0-dev.1`,
149
685
  `0.0.0-dev.2`, and so on. The workflow rejects versions outside this series and
150
686
  skips versions already published. Manual runs default to a dry run.
151
687
  See [the setup guide](PUBLISHING.md) for the
152
688
  one-time bootstrap and npm trusted-publisher configuration.
153
689
 
154
- Install a published build with `npm install @lovable.dev/workflows-sdk@dev`,
155
- or pin the exact version shown in the workflow run's summary.
690
+ Install the newest build with `npm install @lovable.dev/workflows-sdk`, or pin
691
+ the exact version shown in the workflow run's summary. `latest` tracks every dev
692
+ publish while the SDK is pre-1.0; the older `dev` tag is frozen at `0.0.0-dev.2`.
156
693
 
157
- The existing internal [`@lovable/workflow-sdk`](../../packages/workflow-sdk)
694
+ The engine's embedded SDK
695
+ ([`sdk_embed/index.ts`](../../go/workflows/services/workflows/internal/bundler/sdk_embed/index.ts))
158
696
  provides the engine contract. Use [`mcp-js`](../lovable-mcp-js) as the reference
159
697
  for separating authoring, manifest extraction, and framework integration. The
160
698
  workflow prototype's `ts/workflow-sdk` supplies adapter and manifest examples.