From 0df830b7f491afb75bef68c7748c53a4a854a4c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 20 Sep 2026 07:23:42 +0000 Subject: [PATCH 1/2] fix(example-todo): move both loop bodies into `config.body` so `currentTask` binds Claude-Session: https://claude.ai/code/session_01AhQASwqJr2Z7XfGWUdvnbF Co-authored-by: Claude --- examples/app-todo/src/flows/task.flow.ts | 172 ++++++++++++++++++----- 1 file changed, 136 insertions(+), 36 deletions(-) diff --git a/examples/app-todo/src/flows/task.flow.ts b/examples/app-todo/src/flows/task.flow.ts index 03ea85ac79d..e4a35ee1f31 100644 --- a/examples/app-todo/src/flows/task.flow.ts +++ b/examples/app-todo/src/flows/task.flow.ts @@ -58,21 +58,69 @@ export const TaskReminderFlow: Flow = { config: { objectName: 'todo_task', filter: { due_date: '{tomorrow}', status: { $ne: 'completed' } }, outputVariable: 'tasksToRemind', limit: 200 }, }, { + // #19206 — the per-item steps live in `config.body`, and that is what + // binds `currentTask` at all. A `loop` node carrying only `collection` + + // `iteratorVariable` takes the LEGACY flat-graph path + // (`loop-node.ts`: `if (raw.body == null)`), which sets `$loopItems` / + // `$loopIndex` and returns WITHOUT ever binding `iteratorVariable` — so + // every `{currentTask.X}` token in the nodes wired after it resolved to + // nothing. The structured container (ADR-0031) is the form that + // iterates: it binds `iteratorVariable` in the enclosing scope and runs + // the body region once per item, and the node's ordinary out-edge + // (`→ end`) is the after-loop continuation. id: 'loop_tasks', type: 'loop', label: 'Loop Through Tasks', - config: { collection: '{tasksToRemind}', iteratorVariable: 'currentTask' }, - }, - { - // `notify` is what actually delivers (#4343): it hands the messaging - // service the notification — the in-app inbox by default, and email once - // `@objectstack/plugin-email` is installed. The `script` node this - // replaced only ever logged a line and reported success. - id: 'send_reminder', type: 'notify', label: 'Send Reminder', config: { - recipients: '{currentTask.owner}', - title: 'Task due tomorrow: {currentTask.subject}', - message: 'Due {currentTask.due_date} · priority {currentTask.priority}.', - sourceObject: 'todo_task', - sourceId: '{currentTask.id}', + collection: '{tasksToRemind}', + iteratorVariable: 'currentTask', + // The read above is capped at `limit: 200`, so this cap is the same + // bound stated on the side that iterates it — the engine FAILS the + // node on a longer collection rather than truncating in silence. + maxIterations: 200, + body: { + nodes: [ + { + // Per-iteration containment (`flow-loop-body-uncontained`). A + // `loop` body has no error handling of its own: the container + // iterates with a bare `await`, so a body node answering + // `success: false` propagates straight out and ends the WHOLE + // sweep. `notify` fails on an empty resolved recipient set, so + // one task with a blank `owner` would leave every later task + // unreminded. The guard is a `try_catch` INSIDE the body. + id: 'guard_reminder', type: 'try_catch', label: 'Guarded Reminder', + config: { + try: { + nodes: [ + { + // `notify` is what actually delivers (#4343): it hands the + // messaging service the notification — the in-app inbox by + // default, and email once `@objectstack/plugin-email` is + // installed. The `script` node this replaced only ever + // logged a line and reported success. + id: 'send_reminder', type: 'notify', label: 'Send Reminder', + config: { + recipients: '{currentTask.owner}', + title: 'Task due tomorrow: {currentTask.subject}', + message: 'Due {currentTask.due_date} · priority {currentTask.priority}.', + sourceObject: 'todo_task', + sourceId: '{currentTask.id}', + }, + }, + ], + }, + // The shortest handler that works: ONE bare `assignment` node + // with no `config`. A `catch` region cannot be empty — + // `FlowRegionSchema.nodes` is `.min(1)`, so `catch: {}` and + // `catch: { nodes: [] }` are both refused by the parse, and + // omitting `catch` entirely parses while containing NOTHING. + catch: { + nodes: [ + { id: 'reminder_failed', type: 'assignment', label: 'Reminder Failed (contained)' }, + ], + }, + }, + }, + ], + }, }, }, { id: 'end', type: 'end', label: 'End' }, @@ -81,8 +129,9 @@ export const TaskReminderFlow: Flow = { edges: [ { id: 'e1', source: 'start', target: 'get_upcoming_tasks', type: 'default' }, { id: 'e2', source: 'get_upcoming_tasks', target: 'loop_tasks', type: 'default' }, - { id: 'e3', source: 'loop_tasks', target: 'send_reminder', type: 'default' }, - { id: 'e4', source: 'send_reminder', target: 'end', type: 'default' }, + // The loop's ordinary out-edge is the AFTER-loop continuation; the + // per-item step is `config.body`, not a node wired after the container. + { id: 'e3', source: 'loop_tasks', target: 'end', type: 'default' }, ], }; @@ -117,26 +166,78 @@ export const OverdueEscalationFlow: Flow = { }, }, { + // #19206 — same repair as `task_reminder` above, and this is the flow + // where the omission was MEASURED: with the per-item steps wired as + // ordinary nodes AFTER a body-less `loop`, `currentTask` was never + // bound, and the run died at `update_priority` with "refusing to run - + // 1 filter condition(s) resolved to nothing: {currentTask.id} (at id)". + // `notify_owner` sits one node BEHIND that refusal, so no escalation + // notice was ever sent — the loud refusal is the only reason a filter + // that resolved to nothing did not match every task in the table. id: 'loop_overdue', type: 'loop', label: 'Loop Through Overdue Tasks', - config: { collection: '{overdueTasks}', iteratorVariable: 'currentTask' }, - }, - { - id: 'update_priority', type: 'update_record', label: 'Escalate Priority', config: { - objectName: 'todo_task', - filter: { id: '{currentTask.id}' }, - fields: { priority: 'urgent', tags: ['important', 'follow_up'] }, - }, - }, - { - id: 'notify_owner', type: 'notify', label: 'Notify Task Owner', - config: { - recipients: '{currentTask.owner}', - title: 'URGENT: task overdue — {currentTask.subject}', - message: 'Due {currentTask.due_date}, {currentTask.days_overdue} day(s) overdue.', - severity: 'critical', - sourceObject: 'todo_task', - sourceId: '{currentTask.id}', + collection: '{overdueTasks}', + iteratorVariable: 'currentTask', + // Same bound as the read above (`limit: 200`), stated on the side + // that iterates: a longer collection fails the node rather than + // truncating in silence. + maxIterations: 200, + body: { + nodes: [ + { + // Per-iteration containment (`flow-loop-body-uncontained`): both + // per-item steps are fallible — `update_record` answers + // `success: false` on a refused write, `notify` on an empty + // resolved recipient set — and an uncontained failure propagates + // straight out of the container, ending the sweep at the first + // bad row with every later task left unescalated. + // + // ONE `try_catch` over BOTH steps, not one per step: the notice + // announces the escalation the update performs, so a row whose + // update was refused must not be told its priority was raised. + id: 'guard_escalation', type: 'try_catch', label: 'Guarded Escalation', + config: { + try: { + nodes: [ + { + id: 'update_priority', type: 'update_record', label: 'Escalate Priority', + config: { + objectName: 'todo_task', + filter: { id: '{currentTask.id}' }, + fields: { priority: 'urgent', tags: ['important', 'follow_up'] }, + }, + }, + { + id: 'notify_owner', type: 'notify', label: 'Notify Task Owner', + config: { + recipients: '{currentTask.owner}', + title: 'URGENT: task overdue — {currentTask.subject}', + // `days_overdue` is the formula field the record + // projection carries (#18584); the loop binding this + // template reads it from is what #19206 restores. + message: 'Due {currentTask.due_date}, {currentTask.days_overdue} day(s) overdue.', + severity: 'critical', + sourceObject: 'todo_task', + sourceId: '{currentTask.id}', + }, + }, + ], + edges: [ + { id: 'be1', source: 'update_priority', target: 'notify_owner', type: 'default' }, + ], + }, + // One bare `assignment` — the shortest handler that works; a + // `catch` region's `nodes` is `.min(1)`, so an empty one is + // refused at parse and an omitted one contains nothing. + catch: { + nodes: [ + { id: 'escalation_failed', type: 'assignment', label: 'Escalation Failed (contained)' }, + ], + }, + }, + }, + ], + }, }, }, { id: 'end', type: 'end', label: 'End' }, @@ -145,9 +246,8 @@ export const OverdueEscalationFlow: Flow = { edges: [ { id: 'e1', source: 'start', target: 'get_overdue_tasks', type: 'default' }, { id: 'e2', source: 'get_overdue_tasks', target: 'loop_overdue', type: 'default' }, - { id: 'e3', source: 'loop_overdue', target: 'update_priority', type: 'default' }, - { id: 'e4', source: 'update_priority', target: 'notify_owner', type: 'default' }, - { id: 'e5', source: 'notify_owner', target: 'end', type: 'default' }, + // The container's ordinary out-edge is the after-loop continuation. + { id: 'e3', source: 'loop_overdue', target: 'end', type: 'default' }, ], }; From c6ca194c2bbd21e5d6491ce2b55e9e5020b881bf Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 20 Sep 2026 07:38:09 +0000 Subject: [PATCH 2/2] test(example-todo): drive both loop bodies on a real engine, with the pre-fix control Claude-Session: https://claude.ai/code/session_01AhQASwqJr2Z7XfGWUdvnbF Co-authored-by: Claude --- .../app-todo/test/loop-body-iteration.test.ts | 247 ++++++++++++++++++ .../overdue-escalation-days-overdue.test.ts | 38 ++- 2 files changed, 283 insertions(+), 2 deletions(-) create mode 100644 examples/app-todo/test/loop-body-iteration.test.ts diff --git a/examples/app-todo/test/loop-body-iteration.test.ts b/examples/app-todo/test/loop-body-iteration.test.ts new file mode 100644 index 00000000000..968d4d019ea --- /dev/null +++ b/examples/app-todo/test/loop-body-iteration.test.ts @@ -0,0 +1,247 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#19206] Both `loop` nodes own a `config.body`, so `currentTask` is bound and + * the per-item steps actually run. + * + * The defect this pins was a shipped example app whose scheduled sweep died one + * node in. Both loops declared `collection` + `iteratorVariable` and NO + * `config.body`, which is the LEGACY flat-graph form — `loop-node.ts` opens with + * `if (raw.body == null)`, sets `$loopItems` / `$loopIndex` and returns WITHOUT + * binding `iteratorVariable`. The per-item steps were wired as ordinary nodes + * AFTER the container, so every `{currentTask.X}` token in them resolved to + * nothing: `update_priority` refused to run (its filter had been erased), and + * `notify_owner` — one node BEHIND that refusal — was never reached. No + * escalation notice was sent at all. + * + * ⭐ WHY THIS SUITE DRIVES THE ENGINE INSTEAD OF ASSERTING ON METADATA. + * "the flow declares a `config.body`" and "the loop body executes with the + * iterator bound" are different questions, and only the second one decides + * whether a notice is sent. A suite that asserts the shape would have stayed + * green through the entire defect had the shape merely been spelled + * differently; so the flow is registered on a real `AutomationEngine`, over a + * real sqlite-wasm database holding the app's real `todo_task`, and the run's + * EFFECTS are read back: the row the loop escalated, and the notification the + * messaging service was handed. + * + * The `messaging` service is the one double here, and it is a capture, not a + * simulation: `notify` resolves whatever object is registered under that + * service and calls `emit()` (`notify-node.ts`), so capturing the call is how + * the RENDERED notice — title and body, after interpolation — becomes readable + * at all. Everything else in the chain is the real thing. + * + * The last test is the positive control: the pre-fix shape, rebuilt from the + * real flow by deleting `config.body` and re-wiring the flat edges, still dies + * at `update_priority`. Without it a green suite could not distinguish "the + * loop body ran" from "nothing in this harness can fail". + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin } from '@objectstack/objectql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; +import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; + +import { OverdueEscalationFlow, TaskReminderFlow } from '../src/flows/index.js'; +import { Task } from '../src/objects/task.object.js'; + +/** One captured `messaging.emit()` call — the notice as the service received it. */ +interface CapturedEmit { + topic: string; + audience: string[]; + payload: Record; + severity?: string; + source?: { object: string; id: string }; +} + +const openDrivers: Array<{ disconnect?: () => Promise }> = []; +afterEach(async () => { + while (openDrivers.length) { + try { await openDrivers.pop()?.disconnect?.(); } catch { /* noop */ } + } +}); + +/** `n` whole days before today, as a `Field.date` string (UTC); negative = future. */ +function daysAgoIso(n: number): string { + const d = new Date(); + d.setUTCHours(0, 0, 0, 0); + d.setUTCDate(d.getUTCDate() - n); + return d.toISOString().slice(0, 10); +} + +/** + * A real kernel with the app's real `todo_task` over in-process sqlite-wasm, + * the real automation engine, and a capturing `messaging` service. + */ +async function bootTodoKernel(): Promise<{ + automation: AutomationEngine & Record; + data: any; + emits: CapturedEmit[]; +}> { + const emits: CapturedEmit[] = []; + const messaging = { + async emit(input: CapturedEmit) { + emits.push(input); + return { notificationId: `ntf_${emits.length}`, delivered: input.audience.length, failed: 0 }; + }, + }; + + const kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AutomationServicePlugin()); + await kernel.use({ + name: 'test.messaging-capture', + type: 'standard' as const, + version: '1.0.0', + dependencies: [] as string[], + async init(ctx: any) { ctx.registerService('messaging', messaging); }, + async start() { /* noop */ }, + } as any); + await kernel.bootstrap(); + + const objectql: any = kernel.getService('objectql'); + const data: any = kernel.getService('data'); + const automation = kernel.getService('automation') as AutomationEngine & Record; + + const driver: any = new SqliteWasmDriver({ filename: ':memory:' }); + await driver.connect(); + objectql.registerDriver(driver, true); + openDrivers.push(driver); + objectql.registry.registerObject(Task, 'todo', 'todo'); + await objectql.syncSchemas(); + + automation.registerFlow(OverdueEscalationFlow.name, OverdueEscalationFlow); + automation.registerFlow(TaskReminderFlow.name, TaskReminderFlow); + return { automation, data, emits }; +} + +const SYSTEM = { context: { isSystem: true } }; + +/** Seed one task `days` days past due, and return its id. */ +async function seedOverdueTask(data: any, subject: string, days: number, owner = 'usr_test_owner'): Promise { + const row = await data.insert('todo_task', { + subject, status: 'not_started', priority: 'normal', + due_date: daysAgoIso(days), owner, + }, SYSTEM); + return String(row.id ?? row); +} + +describe('#19206 — the loop body runs and binds `currentTask`', () => { + it('ESCALATION: the run reaches `notify_owner` and the notice renders the real day count', async () => { + const { automation, data, emits } = await bootTodoKernel(); + const id = await seedOverdueTask(data, 'Renew the domain', 5); + + const result: any = await automation.execute('overdue_escalation'); + expect(result.success, result.error).toBe(true); + + // 1. The loop body's FIRST node ran against the right row. `update_priority` + // filters on `{currentTask.id}`; unbound, that condition is erased and + // the node refuses (which is how the defect surfaced at all). + const row: any = await data.findOne('todo_task', { where: { id }, context: { isSystem: true } }); + expect(row.priority, 'the escalated row').toBe('urgent'); + + // 2. The node BEHIND that one was reached: exactly one notice, for this row. + expect(emits).toHaveLength(1); + expect(emits[0].source).toEqual({ object: 'todo_task', id }); + expect(emits[0].severity).toBe('critical'); + expect(emits[0].audience).toEqual(['usr_test_owner']); + + // 3. And what it RENDERS — the reading the card is unblocking. Every + // `{currentTask.X}` hole is filled, `days_overdue` (#18584) included. + expect(emits[0].payload.title).toBe('URGENT: task overdue — Renew the domain'); + expect(emits[0].payload.body).toBe(`Due ${daysAgoIso(5)}, 5 day(s) overdue.`); + expect(String(emits[0].payload.body)).not.toContain('{'); + }); + + it('EVERY item is processed, and each one carries its own values', async () => { + const { automation, data, emits } = await bootTodoKernel(); + await seedOverdueTask(data, 'Alpha', 4, 'usr_a'); + await seedOverdueTask(data, 'Bravo', 9, 'usr_b'); + await seedOverdueTask(data, 'Charlie', 12, 'usr_c'); + + const result: any = await automation.execute('overdue_escalation'); + expect(result.success, result.error).toBe(true); + + // A binding that leaked across iterations (one item reused for all three) + // would show up here as three identical notices. Compared SORTED: the + // sweep's `get_record` step declares no `orderBy`, so the row order is the + // driver's and asserting it would pin something this card does not own. + const rendered = emits + .map((e) => [e.audience[0], e.payload.title, e.payload.body]) + .sort((a, b) => String(a[0]).localeCompare(String(b[0]))); + expect(rendered).toEqual([ + ['usr_a', 'URGENT: task overdue — Alpha', `Due ${daysAgoIso(4)}, 4 day(s) overdue.`], + ['usr_b', 'URGENT: task overdue — Bravo', `Due ${daysAgoIso(9)}, 9 day(s) overdue.`], + ['usr_c', 'URGENT: task overdue — Charlie', `Due ${daysAgoIso(12)}, 12 day(s) overdue.`], + ]); + + const rows: any[] = await data.find('todo_task', { where: {}, context: { isSystem: true } }); + expect(rows.map((r) => r.priority)).toEqual(['urgent', 'urgent', 'urgent']); + }); + + it('CONTAINMENT: one un-notifiable row does not end the sweep', async () => { + const { automation, data, emits } = await bootTodoKernel(); + await seedOverdueTask(data, 'Alpha', 4, 'usr_a'); + // `notify` refuses an empty resolved recipient set (`notify-node.ts`), so + // this row's iteration fails INSIDE the body's `try_catch`. + await seedOverdueTask(data, 'Orphan', 6, ''); + await seedOverdueTask(data, 'Charlie', 12, 'usr_c'); + + const result: any = await automation.execute('overdue_escalation'); + expect(result.success, result.error).toBe(true); + + // The two notifiable rows were both reached — the failure between them was + // contained per iteration rather than ending the run. + expect(emits.map((e) => e.audience[0]).sort()).toEqual(['usr_a', 'usr_c']); + }); + + it('REMINDER: the second loop in the file binds its iterator too', async () => { + const { automation, data, emits } = await bootTodoKernel(); + await data.insert('todo_task', { + subject: 'Pay the invoice', status: 'not_started', priority: 'high', + due_date: daysAgoIso(-1), owner: 'usr_test_owner', + }, SYSTEM); + + const result: any = await automation.execute('task_reminder'); + expect(result.success, result.error).toBe(true); + + expect(emits).toHaveLength(1); + expect(emits[0].payload.title).toBe('Task due tomorrow: Pay the invoice'); + expect(emits[0].payload.body).toBe(`Due ${daysAgoIso(-1)} · priority high.`); + expect(String(emits[0].payload.body)).not.toContain('{'); + }); + + it('CONTROL: the pre-fix body-less shape still dies at `update_priority`', async () => { + const { automation, data, emits } = await bootTodoKernel(); + await seedOverdueTask(data, 'Renew the domain', 5); + + // The pre-#19206 shape, rebuilt from the real flow so it cannot drift: the + // body region hoisted back out into flat nodes wired after the container. + const legacy = JSON.parse(JSON.stringify(OverdueEscalationFlow)) as any; + legacy.name = 'overdue_escalation_bodyless_fixture'; + const loop = legacy.nodes.find((n: any) => n.id === 'loop_overdue'); + const guard = loop.config.body.nodes[0]; + delete loop.config.body; + delete loop.config.maxIterations; + legacy.nodes.splice(legacy.nodes.indexOf(loop) + 1, 0, ...guard.config.try.nodes); + legacy.edges = [ + { id: 'e1', source: 'start', target: 'get_overdue_tasks', type: 'default' }, + { id: 'e2', source: 'get_overdue_tasks', target: 'loop_overdue', type: 'default' }, + { id: 'e3', source: 'loop_overdue', target: 'update_priority', type: 'default' }, + { id: 'e4', source: 'update_priority', target: 'notify_owner', type: 'default' }, + { id: 'e5', source: 'notify_owner', target: 'end', type: 'default' }, + ]; + automation.registerFlow(legacy.name, legacy); + + const result: any = await automation.execute(legacy.name); + expect(result.success).toBe(false); + // The exact refusal the card reports, and the reason it is loud rather than + // catastrophic: an erased filter condition is refused, not widened. + expect(String(result.error)).toContain('update_record: refusing to run'); + expect(String(result.error)).toContain('{currentTask.id}'); + + // And the observable the card is about: nothing was notified, because the + // run never reached the node that notifies. + expect(emits).toHaveLength(0); + }); +}); diff --git a/examples/app-todo/test/overdue-escalation-days-overdue.test.ts b/examples/app-todo/test/overdue-escalation-days-overdue.test.ts index 470644019f5..cf0e96b33db 100644 --- a/examples/app-todo/test/overdue-escalation-days-overdue.test.ts +++ b/examples/app-todo/test/overdue-escalation-days-overdue.test.ts @@ -44,9 +44,43 @@ afterEach(async () => { } }); -/** A node of the app's real flow, by id. */ +/** + * A node of the app's real flow, by id — searched at EVERY depth. + * + * [#19206] `notify_owner` and `update_priority` now live inside the `loop` + * container's `config.body` region (that is what binds `currentTask` at all), + * so a search of the top-level `nodes[]` alone reports them as gone. The walk + * below descends the ADR-0031 region slots — `loop.config.body`, + * `try_catch.config.try` / `.catch`, `parallel.config.branches[]` — because the + * question this suite asks is about the node's CONFIG, which is unchanged by + * where the node is nested. + */ function node(id: string): { type?: string; config?: Record } { - const found = OverdueEscalationFlow.nodes?.find((n) => n.id === id); + type AnyNode = { id?: string; type?: string; config?: Record }; + const regionsOf = (cfg: Record | undefined): AnyNode[][] => { + const out: AnyNode[][] = []; + for (const slot of ['body', 'try', 'catch']) { + const region = cfg?.[slot] as { nodes?: AnyNode[] } | undefined; + if (Array.isArray(region?.nodes)) out.push(region!.nodes!); + } + const branches = cfg?.branches as Array<{ nodes?: AnyNode[] }> | undefined; + if (Array.isArray(branches)) { + for (const branch of branches) if (Array.isArray(branch?.nodes)) out.push(branch.nodes!); + } + return out; + }; + const walk = (nodes: AnyNode[] | undefined): AnyNode | undefined => { + for (const n of nodes ?? []) { + if (n?.id === id) return n; + for (const region of regionsOf(n?.config)) { + const hit = walk(region); + if (hit) return hit; + } + } + return undefined; + }; + + const found = walk(OverdueEscalationFlow.nodes as AnyNode[] | undefined); if (!found) throw new Error(`#18584 harness: node '${id}' is gone from overdue_escalation`); return found as { type?: string; config?: Record }; }