From 67b41577b90cec563ccd5b4c1abb3be32c7176fa Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:39:50 -0400 Subject: [PATCH 01/18] feat(dispatch): cross-flow fire-and-forget with a named runtime miss MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An `internal` dispatcher can now name another flow with `flowKind`. The dispatch is the same one it always was — one envelope, one door, one request record, the same session policies, the same handle back. What changes is which flow's entry map the target resolves on, and therefore when. `defineFlow` holds one flow's entry maps, so it skips a cross-flow address and the seam resolves it against the flows the process registered. Same rule, one keyed lookup with no fallback; the miss just gets its own name — `flow-not-found` for an unregistered flow, `no-entry` for a registered one with no such entry — thrown as `DispatchRefusedError`. Nothing retries, queues, or falls through to the sender's own map. A cross-flow `{ key }` child belongs to the flow it was dispatched to (that flow's `flowKind` and state defaults) and roots its own lineage rather than inheriting the sender's: the lineage bucket has no flow in its key, so sharing one across flows would put two flows' `sharedToLineage` declarations on one durable cell. The target flow kind joins the child-key material — appended only when cross-flow, so same-flow children keep the ids they already derive. Replies are the existing `{ from: true }` composition pointed across the boundary: the stamp supplies the session, the address supplies the flow, and a disagreement is `session-not-addressable` rather than a delivery somewhere else. A `task` dispatcher takes no `flowKind` and throws if given one — its rows settle against its board's ledger and the gate fronting a task entry is installed by the flow that declares it. D-8 / FIX-1297; builds on FIX-1312's reverse stamp. Closes the reachable half of FIX-1045. Flow-instance addressing (FIX-1315) is deliberately not started. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01S2jsLHHtk2XaE5hbhuzdtw --- .changeset/cross-flow-dispatch.md | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .changeset/cross-flow-dispatch.md diff --git a/.changeset/cross-flow-dispatch.md b/.changeset/cross-flow-dispatch.md new file mode 100644 index 0000000000..3464cbc02e --- /dev/null +++ b/.changeset/cross-flow-dispatch.md @@ -0,0 +1,6 @@ +--- +"@flow-state-dev/core": minor +"@flow-state-dev/engine": minor +--- + +`dispatcher()` can address another flow: `flowKind` on an `internal` dispatcher resolves `target` on that flow's `internal.actions` and starts the work there, fire-and-forget. `defineFlow` holds one flow's entry maps and skips the check, so the miss is a named runtime refusal — `flow-not-found` for an unregistered flow, `no-entry` for a registered one that declares no such entry — never a retry, a queue, or a fall-through to the sender's own map. A cross-flow `{ key }` child belongs to the addressed flow (its `flowKind`, its state defaults) and roots its own lineage; a reply is the same `{ from: true }` dispatcher pointed back at the sender's `flowKind`. A `task` dispatcher takes no `flowKind` and throws if given one (D-8, FIX-1171 family). From 3abd7e038d7b15dc19b9706c94825562a2e15469 Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:40:42 -0400 Subject: [PATCH 02/18] feat(dispatch): cross-flow follow-up files --- .../engine/src/execution/dispatch-metadata.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/engine/src/execution/dispatch-metadata.ts b/packages/engine/src/execution/dispatch-metadata.ts index 23598175b1..0acd617b2b 100644 --- a/packages/engine/src/execution/dispatch-metadata.ts +++ b/packages/engine/src/execution/dispatch-metadata.ts @@ -27,6 +27,18 @@ import { INTERNAL_SOURCE, TASK_SOURCE } from "./transport-sources"; export type DispatchStamp = { readonly type: "internal" | "task"; readonly target: string; + /** + * The flow the entry was resolved on, present only when the dispatch crossed + * a flow boundary. Absent is same-flow — including on every record written + * before cross-flow addressing shipped (BP-030), which is the same reading. + */ + readonly flowKind?: string; + /** + * The resolved flow INSTANCE's id, alongside `flowKind` and under the same + * condition. Provenance: it says which instance the seam resolved the entry + * on, which a `kind`-keyed read of the registry cannot recover afterwards. + */ + readonly flowId?: string; readonly from: { readonly block: string; readonly sessionId: string; @@ -81,6 +93,12 @@ export function readDispatchStamp( if (candidate.from.lineageId !== undefined && typeof candidate.from.lineageId !== "string") { return undefined; } + if (candidate.flowKind !== undefined && typeof candidate.flowKind !== "string") { + return undefined; + } + if (candidate.flowId !== undefined && typeof candidate.flowId !== "string") { + return undefined; + } if (candidate.recipientLineageId !== undefined && typeof candidate.recipientLineageId !== "string") { return undefined; } From 3933b294fe21cdf24dc559e2e233aa8d256c5d82 Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:41:30 -0400 Subject: [PATCH 03/18] feat(dispatch): cross-flow follow-up files --- packages/engine/src/context/types.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/packages/engine/src/context/types.ts b/packages/engine/src/context/types.ts index b57c915a18..6cd8cf299e 100644 --- a/packages/engine/src/context/types.ts +++ b/packages/engine/src/context/types.ts @@ -144,6 +144,13 @@ export type RequestHostConstructionInputs = { * there explicitly. */ dispatchOperation?: DispatchOperation; + /** + * Resolves another registered flow by kind, for a cross-flow dispatch + * address. Wired from the host's flow registry. Absent → every cross-flow + * address refuses `flow-not-found`, the same fail-closed shape + * `dispatchOperation` has. + */ + resolveFlow?: (kind: string) => FlowInstance | undefined; /** The parent-board row this request was dispatched for, stamped at spawn. */ parentTask?: ParentTaskBinding; /** The stale-request sweeper's threshold. */ From 6a2a9c84683d3567de7bba325752105060eccfa4 Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:42:21 -0400 Subject: [PATCH 04/18] feat(dispatch): cross-flow follow-up files --- packages/engine/src/context/detached-child.ts | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/packages/engine/src/context/detached-child.ts b/packages/engine/src/context/detached-child.ts index e9601deddb..e2561bb655 100644 --- a/packages/engine/src/context/detached-child.ts +++ b/packages/engine/src/context/detached-child.ts @@ -43,7 +43,7 @@ export type DerivationIdentity = { const CHILD_ID_PREFIX = "dsx_"; // Fields are length-framed with core's codec so field boundaries cannot be -// confused: without it `("u_ab", "c")` and `("u_a", "bc")` hash identically, +// confused: without it `("u_ab", "c") and `("u_a", "bc")` hash identically, // and since the parent session id is one of the fields that is a cross-lineage // collision reachable by choosing ids — exactly what the derivation exists to // prevent. An absent tenant frames as the empty field. @@ -66,15 +66,31 @@ const DISPATCH_NAMESPACE = "dispatch"; * discriminates among a parent's dispatched children, so two dispatchers in one * flow that compute the same key share one child — a board that wants its * per-task children apart from another board's frames its own id into the key. + * + * `targetFlowKind` is the **other** flow a cross-flow dispatch addresses, and is + * part of the material precisely because the key alone discriminates: without + * it, one parent dispatching key `"job"` to two different flows derives one + * child id for both, and the second dispatch meets a record whose `flowKind` + * does not match and is refused `key-occupied` — a collision between two + * addresses that have nothing to do with each other. Appended rather than + * folded into the existing fields, so a same-flow derivation (which omits it) + * still produces the id it produced before this shipped: an in-flight retry + * across the upgrade re-enters the child it started, rather than minting a + * second one beside it. */ -export function deriveDispatchChildSessionId(identity: DerivationIdentity, key: string): string { +export function deriveDispatchChildSessionId( + identity: DerivationIdentity, + key: string, + targetFlowKind?: string +): string { const material = [ framed(identity.tenantId ?? ""), framed(identity.userId), framed(identity.parentSessionId), framed(identity.lineageId), framed(DISPATCH_NAMESPACE), - framed(key) + framed(key), + ...(targetFlowKind !== undefined ? [framed(targetFlowKind)] : []) ].join("|"); const digest = createHash("sha256").update(material, "utf8").digest("hex"); From 30429bf1d63dc1fec41265a15112c5d66fef3ead Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:43:12 -0400 Subject: [PATCH 05/18] feat(dispatch): cross-flow follow-up files --- .../test/context/detached-child.test.ts | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/packages/engine/test/context/detached-child.test.ts b/packages/engine/test/context/detached-child.test.ts index 9b8e87f11e..cc018f002b 100644 --- a/packages/engine/test/context/detached-child.test.ts +++ b/packages/engine/test/context/detached-child.test.ts @@ -46,6 +46,26 @@ describe("child session derivation", () => { expect(a).toBe(b); }); + it("gives two target flows different children for an identical key from one parent", () => { + // Otherwise a parent dispatching "job" to two flows derives one child id + // for both, and the second meets a record whose flowKind does not match and + // is refused `key-occupied` — a collision between unrelated addresses. + const billing = deriveDispatchChildSessionId(base, "job", "billing"); + const shipping = deriveDispatchChildSessionId(base, "job", "shipping"); + expect(billing).not.toBe(shipping); + }); + + it("leaves a same-flow child on the id it derived before cross-flow shipped", () => { + // Pinned, not recomputed: an in-flight retry across the upgrade must + // re-enter the child it started rather than mint a second one beside it. + expect(deriveDispatchChildSessionId(base, "review")).toBe( + "dsx_1b1b460597b7af771a2e4d6e9b9d1f5d" + ); + expect(deriveDispatchChildSessionId(base, "review")).not.toBe( + deriveDispatchChildSessionId(base, "review", "billing") + ); + }); + it("gives two principals different children for an identical key", () => { const alice = deriveDispatchChildSessionId(base, "review"); const bob = deriveDispatchChildSessionId({ ...base, userId: "u_bob" }, "review"); From 6f84df423c6495b932e69ff543bc412367d90e9c Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:44:00 -0400 Subject: [PATCH 06/18] feat(dispatch): cross-flow follow-up files --- docs/architecture/action-forms.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/architecture/action-forms.md b/docs/architecture/action-forms.md index 91659f787f..cfd9fc095c 100644 --- a/docs/architecture/action-forms.md +++ b/docs/architecture/action-forms.md @@ -160,6 +160,16 @@ refuses a dispatcher whose target the flow does not declare. A `task` dispatcher is a seat on a task board; the board binds its id and claim gate onto it, and `defineFlow` puts the addressed entry behind that gate. +**An `internal` address may name another flow** — `flowKind` on the block, +making the address `(type, target, flowKind)`. It is as static as the pair it +extends, but `defineFlow` holds one flow's entry maps and cannot resolve +another's, so the walk skips it and the seam resolves it at run time against +the flows the process registered. Same rule, one keyed lookup with no +fallback; the miss just gets its own name, `flow-not-found`, beside the +`no-entry` a registered flow with no such entry still gives. A `task` address +takes no `flowKind` — see [Dispatched Work](./dispatched-work.md) → +*Dispatching into another flow*. + **Three session targets, two delivery guards.** `{ key }` derives a child of the running session (`deriveDispatchChildSessionId`, with the key framed under its own `dispatch` namespace) and adopts it on the same key; the adoption check From c43f0b1e98fc4bdf148042bbc7e70ff90d580657 Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:44:35 -0400 Subject: [PATCH 07/18] feat(dispatch): cross-flow follow-up files --- .../test/context/dispatch-cross-flow.test.ts | 352 ++++++++++++++++++ 1 file changed, 352 insertions(+) create mode 100644 packages/engine/test/context/dispatch-cross-flow.test.ts diff --git a/packages/engine/test/context/dispatch-cross-flow.test.ts b/packages/engine/test/context/dispatch-cross-flow.test.ts new file mode 100644 index 0000000000..41c1f733d4 --- /dev/null +++ b/packages/engine/test/context/dispatch-cross-flow.test.ts @@ -0,0 +1,352 @@ +/** + * Cross-flow dispatch (FIX-1171 family / Architect D-8): one flow starts work + * on another, fire-and-forget, and a miss is a **named runtime refusal**. + * + * The address is declared — `flowKind` + `target` on the `dispatcher()` block — + * but `defineFlow` holds one flow's entry maps and cannot resolve another's, so + * the check lands at the seam against the flows the process registered. The + * three ways that goes are all here: it resolves, the flow is not registered + * (`flow-not-found`), the flow is registered but declares no such entry + * (`no-entry`). None of them retries, queues, or falls through to the sender's + * own map — every one throws `DispatchRefusedError` inside the sending block. + * + * The reply half is the same three-request shape as within a flow + * (`dispatch-reply-from.test.ts`), pointed across the boundary: B replies with + * `{ from: true }` at `flowKind: `, and a third request lands on A's + * session. + */ +import { describe, expect, it } from "vitest"; +import { z } from "zod"; +import { defineFlow, dispatcher, handler, sequencer } from "@flow-state-dev/core"; +import type { FlowInstance } from "@flow-state-dev/core/types"; +import { createFlowState, inMemoryStores, runAction } from "../../src"; +import { readDispatchStamp } from "../../src/execution/dispatch-metadata"; +import type { FlowStateRuntime } from "../../src/flowstate/types"; + +const USER_ID = "u_cross"; +const SENDER = "shipping"; +const RECIPIENT = "billing"; +/** A third registered flow, so "wrong flow" is distinguishable from "no flow". */ +const BYSTANDER = "analytics"; + +type Observed = { + /** Runs of the recipient flow's entry — one per delivered dispatch. */ + arrivals: { sessionId: string; requestId: string; orderId: string }[]; + /** Runs of the sender flow's reply entry. */ + replies: { sessionId: string; requestId: string; orderId: string }[]; +}; + +const orderInput = z.object({ orderId: z.string() }); + +/** + * The sender: a public action that dispatches across the boundary, plus the + * entry a reply lands on. `reply-target` names a flow, not this one, exactly + * like the failing addresses below — what separates them is what the process + * has registered, which is the whole point. + */ +function senderFlow(observed: Observed, options: { flowKind?: string; target?: string } = {}) { + const receive = handler({ + name: "receive-confirmation", + inputSchema: orderInput, + outputSchema: z.object({}), + execute: async (input, ctx) => { + observed.replies.push({ + sessionId: ctx.session.identity.id, + requestId: ctx.request.identity.id, + orderId: input.orderId + }); + return {}; + } + }); + + const notify = dispatcher({ + name: "notify-billing", + type: "internal", + flowKind: options.flowKind ?? RECIPIENT, + target: options.target ?? "charge", + inputSchema: orderInput, + session: { key: (input) => input.orderId } + }); + + return defineFlow({ + kind: SENDER, + actions: { notify: { block: notify } }, + internal: { actions: { confirm: { block: receive } } } + })({ id: SENDER }); +} + +/** + * The recipient: a `charge` entry that records its arrival and then replies + * back across the boundary with `{ from: true }`. + */ +function recipientFlow(observed: Observed, options: { replyTo?: string } = {}) { + const reply = dispatcher({ + name: "confirm-to-sender", + type: "internal", + flowKind: options.replyTo ?? SENDER, + target: "confirm", + inputSchema: orderInput, + session: { from: true } + }); + + const charge = handler({ + name: "charge-order", + inputSchema: orderInput, + outputSchema: orderInput, + execute: async (input, ctx) => { + observed.arrivals.push({ + sessionId: ctx.session.identity.id, + requestId: ctx.request.identity.id, + orderId: input.orderId + }); + return input; + } + }); + + return defineFlow({ + kind: RECIPIENT, + // Session state the sender's flow does not declare — the child must be + // defaulted from the flow it BELONGS to, not the one that sent it. + session: { stateSchema: z.object({ charged: z.boolean().default(false) }) }, + actions: {}, + internal: { + actions: { charge: { block: sequencer({ name: "charge-and-confirm" }).step(charge).step(reply) } } + } + })({ id: RECIPIENT }); +} + +/** + * A third registered flow that declares the same entry name as the sender, so a + * reply misaddressed to it gets past entry resolution and is refused on the one + * thing that separates the two flows: whose session the delivery names. + */ +function bystanderFlow() { + const noop = handler({ + name: "noop", + inputSchema: orderInput, + outputSchema: z.object({}), + execute: async () => ({}) + }); + return defineFlow({ + kind: BYSTANDER, + actions: {}, + internal: { actions: { confirm: { block: noop } } } + })({ id: BYSTANDER }); +} + +async function boot(flows: FlowInstance[]) { + const state = createFlowState({ + flows: Object.fromEntries(flows.map((flow) => [flow.kind, flow])), + stores: { default: { primary: inMemoryStores() } } + }); + const runtime = await state.getRuntime(); + return { runtime, state }; +} + +function run( + runtime: FlowStateRuntime, + flow: FlowInstance, + actionName: string, + input: unknown, + sessionId = "s_sender" +) { + return runAction({ + flow, + actionName, + input, + userId: USER_ID, + sessionId, + stores: runtime.stores, + runtimeConfig: { ...runtime.runtimeConfig } + }); +} + +async function until(predicate: () => boolean, label: string): Promise { + for (let attempt = 0; attempt < 200; attempt += 1) { + if (predicate()) return; + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error(`timed out waiting for ${label}`); +} + +/** Poll one request record until it satisfies `predicate`, then return it. */ +async function untilRecord( + runtime: FlowStateRuntime, + requestId: string, + predicate: (record: { status: string }) => boolean +): Promise { + for (let attempt = 0; attempt < 200; attempt += 1) { + const record = await runtime.stores.request.get(requestId); + if (record !== undefined && predicate(record)) return record; + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error(`timed out waiting for request "${requestId}" to settle`); +} + +function observed(): Observed { + return { arrivals: [], replies: [] }; +} + +describe("cross-flow fire-and-forget", () => { + it("delivers into a child session of the TARGET flow and returns without waiting", async () => { + const seen = observed(); + const sender = senderFlow(seen); + const { runtime, state } = await boot([sender, recipientFlow(seen)]); + try { + const sent = await run(runtime, sender, "notify", { orderId: "ord_1" }); + expect(sent.error).toBeUndefined(); + + const handle = sent.output as { sessionId: string; requestId: string; adopted: boolean }; + expect(handle.adopted).toBe(false); + expect(handle.sessionId).not.toBe("s_sender"); + + await until(() => seen.arrivals.length === 1, "the billing entry to run"); + expect(seen.arrivals[0]).toMatchObject({ + sessionId: handle.sessionId, + orderId: "ord_1" + }); + + // The child belongs to the recipient flow — its own kind, its own state + // defaults, its own lineage — while still naming the sender as its parent. + const child = await runtime.stores.session.get(handle.sessionId); + expect(child?.flowKind).toBe(RECIPIENT); + expect(child?.parentSessionId).toBe("s_sender"); + expect(child?.state).toMatchObject({ charged: false }); + + const parent = await runtime.stores.session.get("s_sender"); + expect(parent?.flowKind).toBe(SENDER); + // A cross-flow child roots its own lineage: the lineage is a shared + // storage bucket with no flow in its key, so inheriting the sender's + // would put two flows' `sharedToLineage` declarations on one cell. + expect(child?.lineageId).not.toBe(parent?.lineageId); + + // The dispatched request records the boundary it crossed. + const record = await runtime.stores.request.get(handle.requestId); + expect(record?.flowKind).toBe(RECIPIENT); + expect(readDispatchStamp(record?.source, record?.metadata)).toMatchObject({ + type: "internal", + target: "charge", + flowKind: RECIPIENT, + flowId: RECIPIENT, + from: { block: "notify-billing", sessionId: "s_sender" } + }); + } finally { + await state.dispose(); + } + }); + + it("refuses flow-not-found when the addressed flow is not registered here", async () => { + const seen = observed(); + // Defining the flow is not the failure — an address `defineFlow` cannot + // resolve is accepted at definition time, on purpose. + const sender = senderFlow(seen, { flowKind: "warehouse" }); + const { runtime, state } = await boot([sender, recipientFlow(seen)]); + try { + const sent = await run(runtime, sender, "notify", { orderId: "ord_2" }); + expect(sent.error?.message).toMatch(/flow-not-found/); + expect(sent.error?.message).toMatch(/warehouse/); + expect(sent.error?.message).toMatch(/notify-billing/); + expect(seen.arrivals).toHaveLength(0); + } finally { + await state.dispose(); + } + }); + + it("refuses no-entry when the addressed flow declares no such entry", async () => { + const seen = observed(); + const sender = senderFlow(seen, { target: "refund" }); + const { runtime, state } = await boot([sender, recipientFlow(seen)]); + try { + const sent = await run(runtime, sender, "notify", { orderId: "ord_3" }); + expect(sent.error?.message).toMatch(/no-entry/); + // Named against the flow the address pointed at, not the sender's. + expect(sent.error?.message).toMatch(/"billing" declares no internal entry "refund"/); + expect(seen.arrivals).toHaveLength(0); + } finally { + await state.dispose(); + } + }); + + it("does not fall through to an identically named entry on the SENDER's flow", async () => { + const seen = observed(); + // `confirm` exists here — on the sender. The recipient declares no such + // entry, and resolution must not walk back to the flow that dispatched. + const sender = senderFlow(seen, { target: "confirm" }); + const { runtime, state } = await boot([sender, recipientFlow(seen)]); + try { + const sent = await run(runtime, sender, "notify", { orderId: "ord_4" }); + expect(sent.error?.message).toMatch(/no-entry/); + expect(sent.error?.message).toMatch(/"billing" declares no internal entry "confirm"/); + expect(seen.replies).toHaveLength(0); + } finally { + await state.dispose(); + } + }); + +}); + +describe("three-request reverse delivery across flows", () => { + it("A dispatches to B; B replies via the stamped sender; the reply lands on A", async () => { + const seen = observed(); + const sender = senderFlow(seen); + const { runtime, state } = await boot([sender, recipientFlow(seen)]); + try { + const first = await run(runtime, sender, "notify", { orderId: "ord_5" }); + expect(first.error).toBeUndefined(); + const handle = first.output as { sessionId: string; requestId: string }; + + await until(() => seen.replies.length === 1, "the confirmation to land on shipping"); + + expect(seen.arrivals).toHaveLength(1); + expect(seen.replies[0]).toMatchObject({ sessionId: "s_sender", orderId: "ord_5" }); + // Three distinct requests: the caller's, the child's, the reply's. + expect(seen.replies[0]?.requestId).not.toBe(first.requestId); + expect(seen.replies[0]?.requestId).not.toBe(handle.requestId); + + const replyRecord = await runtime.stores.request.get(seen.replies[0]!.requestId); + expect(replyRecord?.flowKind).toBe(SENDER); + expect(readDispatchStamp(replyRecord?.source, replyRecord?.metadata)).toMatchObject({ + type: "internal", + target: "confirm", + flowKind: SENDER, + from: { block: "confirm-to-sender", sessionId: handle.sessionId } + }); + } finally { + await state.dispose(); + } + }); + + it("refuses session-not-addressable when the stamped sender is not on the addressed flow", async () => { + const seen = observed(); + const sender = senderFlow(seen); + // The reply points at a registered flow the sender's session does not + // belong to. `{ from: true }` supplies the session id; the address supplies + // the flow; a delivery only happens when they agree. + const { runtime, state } = await boot([ + sender, + recipientFlow(seen, { replyTo: BYSTANDER }), + bystanderFlow() + ]); + try { + const first = await run(runtime, sender, "notify", { orderId: "ord_6" }); + expect(first.error).toBeUndefined(); + const handle = first.output as { requestId: string }; + await until(() => seen.arrivals.length === 1, "the billing entry to run"); + + // The refusal reaches the recipient as a thrown `DispatchRefusedError`, + // so the dispatched request FAILS rather than the reply landing anywhere. + const childRecord = await untilRecord( + runtime, + handle.requestId, + (record) => record.status === "failed" || record.status === "error" + ); + const dump = JSON.stringify(childRecord); + expect(dump).toMatch(/session-not-addressable/); + expect(dump).toMatch(/belongs to flow[^,]*shipping/); + expect(dump).toMatch(/this dispatch is addressed to flow[^,]*analytics/); + expect(seen.replies).toHaveLength(0); + } finally { + await state.dispose(); + } + }); +}); From 869fb1678cfb115675bb1f0a78c11c1c612a36af Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:45:10 -0400 Subject: [PATCH 08/18] feat(dispatch): cross-flow follow-up files --- packages/core/src/blocks/dispatcher.ts | 69 ++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 3 deletions(-) diff --git a/packages/core/src/blocks/dispatcher.ts b/packages/core/src/blocks/dispatcher.ts index 47eec79e65..3c916383ec 100644 --- a/packages/core/src/blocks/dispatcher.ts +++ b/packages/core/src/blocks/dispatcher.ts @@ -43,6 +43,26 @@ * }); * ``` * + * **Another flow is an address, not another mechanism.** Add `flowKind` and the + * entry resolves on that flow instead of this one. The dispatch is still + * fire-and-forget, and a reply is still the same `{ from: true }` block — + * pointed back at the sender's flow. + * + * ```ts + * const notifyBilling = dispatcher({ + * name: "notify-billing", + * type: "internal", + * flowKind: "billing", // resolves on the billing flow + * target: "invoice-ready", + * inputSchema: z.object({ invoiceId: z.string() }), + * session: { key: (input) => input.invoiceId }, + * }); + * ``` + * + * `defineFlow` holds one flow's entry maps, so it cannot check that address. + * The seam does, against the flows the process registered, and refuses by name: + * `flow-not-found` or `no-entry`, thrown as `DispatchRefusedError`. + * * A `task` dispatcher is a **seat on a task board**: put it under `workers` * where an inline worker would go, and the board hands each row it routes * there off to `flow.task.actions[target]` in the child session the policy names. @@ -118,8 +138,29 @@ export interface InternalDispatcherConfig`. + * + * `defineFlow` cannot check this target — it holds one flow's entry maps and + * this names another's. The check runs at the seam instead, against what the + * process actually registered, and refuses by name: `flow-not-found` for an + * unregistered flow, `no-entry` for a flow that declares no such entry. + * Both reach this block as a thrown `DispatchRefusedError`. + */ + flowKind?: string; /** What this block accepts. Defaults to `z.unknown()`. */ inputSchema?: TInputSchema; /** Which session the dispatch runs in. */ @@ -184,6 +225,17 @@ export function dispatcher( }; if (config.type === "task") { + // A board's claim gate is installed by the `defineFlow` that owns the task + // entry, and a cross-flow hand-off would put the ledger on one side of the + // boundary and the gate on the other. Refused rather than ignored: a + // silently dropped `flowKind` is a seat handing rows to the wrong flow. + if ((config as { flowKind?: unknown }).flowKind !== undefined) { + throw new Error( + `[dispatcher] "${name}" declares a flowKind, but only an "internal" dispatcher may ` + + `address another flow. A task seat settles against the board's own ledger, and the ` + + `claim gate that fronts its entry is installed by the flow that declares it.` + ); + } const session = config.session; if (!isTaskSessionPolicy(session)) { throw new Error( @@ -215,8 +267,19 @@ export function dispatcher( return markDispatcher(block, address); } - const { session, payload } = config; - const address: DispatchAddress = { type: "internal", target }; + const { session, payload, flowKind } = config; + if (flowKind !== undefined && (typeof flowKind !== "string" || flowKind.length === 0)) { + throw new Error( + `[dispatcher] "${name}" declares an empty flowKind (${JSON.stringify(flowKind)}). ` + + `A cross-flow address names the flow to resolve the entry on; omit it to address ` + + `this flow's own entry.` + ); + } + const address: DispatchAddress = { + type: "internal", + target, + ...(flowKind !== undefined ? { flowKind } : {}) + }; const inputSchema = config.inputSchema ?? z.unknown(); const block = handler({ ...common, From 2cd75b7646dbb223f903ac7c209543c031d9f380 Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:47:13 -0400 Subject: [PATCH 09/18] feat(dispatch): cross-flow follow-up files --- apps/docs/docs/server/background-work.md | 379 +---------------------- 1 file changed, 1 insertion(+), 378 deletions(-) diff --git a/apps/docs/docs/server/background-work.md b/apps/docs/docs/server/background-work.md index e2b1780cac..311c8dd065 100644 --- a/apps/docs/docs/server/background-work.md +++ b/apps/docs/docs/server/background-work.md @@ -1,378 +1 @@ ---- -sidebar_position: 6 -sidebar_label: Dispatched work ---- - -# Dispatched work - -Some work outlives the turn that asked for it: a long research pass, a document -being drafted, an implementation running for an hour. That work runs in its own -*session*, the record the framework keeps for one conversation, holding its -state, its resources, and the history of every request that ran in it. The -session hangs off the conversation that started it, as a child of it. - -This page covers how a flow starts that work, and the HTTP surface for reading -it afterwards. Ask a conversation for its children, then ask any one child for -its history. - -Starting one is server-side only. There is no endpoint for it. A job begins -inside a running request, either from a `dispatcher()` block or from a task -board handing a claimed row to a child session. See [Work that outlives the -turn](/guides/background-work#dispatch-work-in-a-child-session) for how the two -relate to the other kinds of background work. - -## Starting a job from a flow - -A flow declares the work a job can run under `internal.actions`, beside -`actions`. An internal entry has the same shape as an action, but no client can -call it. The only way in is a `dispatcher()` block inside the same flow. - -```ts -import { defineFlow, dispatcher, generator, handler } from "@flow-state-dev/core"; -import { z } from "zod"; - -const summarizeDocument = generator({ - name: "summarize-document", - model: "openai/gpt-5.4-mini", - inputSchema: z.object({ documentId: z.string() }), - prompt: "Summarize the document.", -}); - -const acknowledge = handler({ - name: "acknowledge", - inputSchema: z.object({ reason: z.string() }), - execute: async (input) => ({ noted: input.reason }), -}); - -// One job per document. The same documentId from the same conversation -// lands on the same job. -const summarizeInBackground = dispatcher({ - name: "summarize-in-background", - type: "internal", - target: "summarize", - inputSchema: z.object({ documentId: z.string() }), - session: { key: (input) => input.documentId }, -}); - -// Deliver into a session that already exists. -const nudgeCoordinator = dispatcher({ - name: "nudge-coordinator", - type: "internal", - target: "acknowledge", - inputSchema: z.object({ coordinatorSessionId: z.string(), reason: z.string() }), - session: { id: (input) => input.coordinatorSessionId }, - payload: (input) => ({ reason: input.reason }), -}); - -export default defineFlow({ - kind: "documents", - actions: { - upload: { block: summarizeInBackground }, - nudge: { block: nudgeCoordinator }, - }, - internal: { - actions: { - summarize: { block: summarizeDocument }, - acknowledge: { block: acknowledge }, - }, - }, -})(); -``` - -A dispatcher is a handler. Run it, in a sequencer step, as a generator's tool, -or as an action's root block, and it sends one request to `target` and returns -as soon as the runtime has accepted it. It does not wait for the work. - -```ts -// what the dispatcher returns -{ sessionId: "dsx_9f2c1a", requestId: "req_c41e", adopted: false } -``` - -`sessionId` is the session the work runs in, `requestId` the run it became, and -`adopted` whether that session already existed. The entry validates the payload -against its own `inputSchema` on arrival; `payload` shapes it, and defaults to -the dispatcher's input as-is. - -`session` decides which session that is. - -| `session` | Runs in | When it does not exist | -|---|---|---| -| `{ key: (input) => string }` | a child of the running session, derived from the key | created; the next call with the same key from the same conversation adopts it | -| `{ id: (input) => string }` | the session with that id | refused. Nothing is created | - -A `key` child is a job in every sense on this page: it hangs off the session -that started it, runs the same flow as the same user, keeps its own state and -history, and shows up in the parent's listing below. The key is scoped to the -conversation, so the same key from a different conversation is a different -child. An `id` target has to be a session of this flow kind that belongs to -this user. - -`defineFlow` checks every dispatcher it can reach and throws at definition time -when `target` names an entry the flow does not declare. An action named -`summarize` does not stand in for `internal.actions.summarize`; each map is -looked up on its own. - -A refusal at run time throws `DispatchRefusedError`, with `code: -"dispatch-refused"` and a `refused` field to branch on: - -| `refused` | Meaning | -|---|---| -| `no-entry` | The flow declares no entry at that address | -| `session-not-found` | An `id` names a session that does not exist, or one that belongs to another user | -| `session-not-addressable` | An `id` names a session on another flow | -| `key-occupied` | The `key` derived a session id already held by something that is not this conversation's child | -| `no-dispatch-operation` | This process runs requests but was not set up to dispatch one | -| `dispatch-rejected` | The entry's `concurrency` policy is `reject` and its key is held | -| `external-dispatcher` | An `id` delivery on a deployment that hands work to an external queue. A `key` child is unaffected | - -Every refusal is decided before anything starts, so a `.rescue()` on the -dispatcher can branch on `refused` knowing no child is running. A `key` or -`id` function that returns an empty string throws a plain `Error` naming the -block. - -A task board seat can start a job the same way: a `dispatcher({ type: "task" -})` under `workers` sends each claimed row to one of the flow's `task.actions` -entries, and the child session lands in the same listing. See [Task board → -Seats that hand off](../orchestration/task-board.md#seats-that-hand-off). - -## Listing a session's children - -``` -GET /api/flows/sessions/sess_abc/children -``` - -```json -{ - "children": [ - { - "id": "dsx_9f2c1a", - "parentSessionId": "sess_abc", - "topic": "task|10:issue-work|3:t42", - "coordinate": "task:implement", - "status": "active", - "createdAt": 1770000000000, - "updatedAt": 1770000042000 - }, - { - "id": "dsx_1c7b40", - "parentSessionId": "sess_abc", - "topic": "acme-corp", - "coordinate": "internal:summarize", - "status": "completed", - "createdAt": 1769999000000, - "updatedAt": 1769999900000 - } - ] -} -``` - -Those seven fields are the whole row. The route sends this named set rather than -a session record, so there is no `flowKind`, `userId`, `title` or `metadata` on -it. - -`topic` and `coordinate` are display labels. `coordinate` is the entry the child -was dispatched to, `:`: `internal:summarize` for an internal entry, -`task:implement` for a task-board seat that hands off. `topic` is the key the -child session was derived from — what a `dispatcher()`'s `session: { key }` -function returned, or the composed key a task seat's `session` policy produced. - -Nothing routes, authorizes or identifies from either label, and both are -optional, as is `status`. Guard all three with `== null`. A row with no labels is -a child session, same as any other; it just carries nothing to display. - -### What `status` tells you - -`active` means the job isn't finished. It covers a job waiting in a queue, a job -running right now, and a job paused waiting for someone to approve something. -The endpoint does not distinguish those. If you need to know which, -open the job and read its history, or read the task board the job is working -from. - -Every other value is how the job's last run ended: - -| Value | Meaning | -|---|---| -| `completed` | The run finished. Not the same as the work succeeding | -| `failed` | The run itself ended with an error. A worker error doesn't always reach it | -| `aborted` | Cancelled | -| `incomplete` | Stopped short of finishing, usually on a budget | - -A job doing a task board's work runs that board's worker, and a worker that -throws records the failure on its own task. What that does to the run around it -is the board's -[`onError`](../orchestration/task-board.md#concurrency-and-error-handling) -setting. On the default, `"skip"`, the run finishes and the job reads -`completed`. On `"fail"` the error propagates and the job reads `failed`. - -So a board left on the default reports a job that succeeded for work that broke. -The task carries the failure under either setting, which makes the board the -thing to watch when the question is whether the work came out right, and the -job's status the thing to watch when the question is whether anything is still -running. A failed task reads `errored`, with the message in its [`error` -field](../orchestration/task-substrate.md#the-task-record). - -That write goes through the worker's claim on the task, so it lands only while -the task is still the worker's to write. One cancelled in the meantime, or -completed by the worker itself earlier in the run, or handed to another worker -after the claim lapsed, keeps the status it already has and records nothing. See -[Recording a result that may no longer -apply](../orchestration/task-substrate.md#recording-a-result-that-may-no-longer-apply). - -A job with no runs yet has no `status` field at all. Absence means "nothing has -run", which is different from any of the values above. - -A job that failed and was retried successfully reads `completed`; the failed -attempt is still there in the job's own history. - -`active` describes what the system recorded, not what a worker is doing right -now. If a worker's process dies mid-job the row keeps reading `active` until a -client continues the run or a retry supersedes it — the framework marks the run -recoverable, it does not restart it for you. A job -whose approval request expired without an answer reads `active` indefinitely, -because nothing discharges an approval except answering it. - -### What a stopped process leaves behind - -A process can stop while background work is still running, and the work is then -cancelled without being settled. So a job can read `active` with nothing running -it, and the request records under it can read in-progress, for a while after the -process is gone. Neither is a stuck row. - -The task clears itself: it is taken back once its lease has lapsed and some -worker claims it again. The request record is made *recoverable* rather than -cleared — a sweep marks it `interrupted`, the status a run can be resumed from, -running at runtime start, on a timer while a server is up, and on demand when a -client asks. - -Marking it is where the framework stops. Nothing continues or re-runs the work -on your behalf, deliberately: restarting a request nobody asked to restart is -how the same job runs twice. So the row keeps reading `active` — an -`interrupted` run is unfinished and still continuable — until a client resumes -or retries it, or a later run supersedes it. The sweep waits -until a record's heartbeat has been quiet longer than the staleness threshold, -so a job that has simply gone quiet for a second is never mistaken for an -abandoned one. - -That protection is the heartbeat, so it doesn't cover a flow that turns the -heartbeat off. With `request: { heartbeatIntervalMs: 0 }` nothing refreshes the -run's active-request registry entry, so a run lasting longer than the staleness -threshold will be marked `interrupted` while it is still going — which also -offers it for resume, so the same work can be started a second time. Keep the -heartbeat on for any flow whose requests outlive the threshold. - -The process that walked away mostly doesn't settle the record on its way out: -[`dispose()`](../api/server.md#shutdown) cancels background work rather than -marking it finished or failed. One case doesn't follow that yet — work still -waiting behind a concurrency limit when shutdown reaches it is recorded -`aborted` without ever having started — so read a terminal status after a -shutdown as a record of what the process did, not as proof the work ran. And if -nothing ever runs against that store again, nothing sweeps it, and the row stays -as it is. - -For the thresholds, see [Connection -resilience](./connection-resilience.md#configuration). For the lease and the -abandonment allowance, see [the -lease](../orchestration/task-substrate.md#the-lease) and [when a job keeps being -abandoned](../orchestration/task-substrate.md#when-a-job-keeps-being-abandoned). - -## Reading one child's history - -Each row's `id` addresses a session, so every session endpoint works on it: - -``` -GET /api/flows/sessions/dsx_9f2c1a/requests -``` - -That returns the child's runs, with the item log for each when you ask for it -(`?include_items=true`). - -A run a `dispatcher()` started reads `source: "internal"`, or `source: "task"` -when a task-board seat handed the work off, and carries a `metadata.dispatch` -bag: - -```json -{ - "source": "task", - "actionName": "implement", - "metadata": { - "dispatch": { - "type": "task", - "target": "implement", - "from": { "block": "hand-off-implement", "sessionId": "sess_abc" }, - "key": "task|10:issue-work|3:t42", - "taskId": "t42" - } - } -} -``` - -`type` and `target` are the entry the run executes, `from` names the block that -sent it and the session it was running in, `key` is the session key the child -was derived from, and `taskId` the board row on a task hand-off. `key` is absent -when the dispatcher delivered into an existing session by `id`, and `taskId` is -absent on an internal dispatch. - -The runtime assembles that bag from values it derived itself; a request body -cannot write it. It is still labels rather than authority — use `taskId` to -stitch a run to a board row in a view, not to key an authorization or a -settlement on. Read the bag only when `source` is `"internal"` or `"task"`: an -application can put whatever it likes in `metadata` on its own requests, -including a key named `dispatch`, and `source` is the field a request body -cannot set. - -A run with either source cannot be re-entered from outside. `retry`, -`continue`, and `resume` on its request id answer `404`, the same as for a -request that does not exist. - -Children can nest. If a child dispatches work of its own, calling `/children` on -its id returns it. - -## Paging - -Pass `limit` (1–100, default 25) and `offset` (0–10000). Values outside those -ranges get a `400` naming the accepted range rather than a silently clamped -page. A host can lower the ceiling with -[`maxChildSessionListLimit`](../configuration/runtime.md). - -Rows come back newest-created first. A child that starts a run while you are -paging will not shuffle the pages under you. A child *created* while you are -paging can be missed, or can shift a later page by one — if you need exactness -there, fetch a single page large enough to hold the whole set. - -## What this endpoint won't do - -**It won't apply access rules of its own.** The same rules that govern reading -the conversation named in the path govern reading its children. That is how -every session-addressed route works: session detail, state, resource content, -the debug endpoints. A conversation in another tenant answers `404`. One with no -children answers `200` with an empty list. Whether one belonging to another user -answers `403` depends on your `resolvePrincipal`. With none configured the -management endpoints stay open, so a caller holding a conversation id can read -its children. See [Without a resolver](./authentication.md#without-a-resolver). - -**It won't list background work across conversations.** There is no -"everything I have running" endpoint. You reach a child through the conversation -that started it. - -**It won't tell you whether a worker process is alive.** See the note on -`status` above. - -**It won't start anything.** Whether work runs in a child session is declared in -the flow. A caller can list children, never create one. - -**It won't return the child's state, resources, or journal.** Rows carry -identity, labels, timestamps and status. Fetch the session itself if you need -more. - -## Related - -- [Work that outlives the turn](/guides/background-work) — how this relates to the other - things this framework calls background work -- [Client overview](../client/overview.md#child-sessions) — the same two calls from an app -- [Claude Code SDK agent](../tools/claude-code-sdk.md#turning-it-off-for-background-work) — running - a coding agent in a child session, and what it records there -- [Codex SDK agent](../tools/codex.md#continuing-a-thread) — the other coding agent, and how a run - in a child session stays resumable when it is cancelled -- [Engine setup](./setup.md) — the full HTTP route table -- [Authentication](./authentication.md) — how addressed routes scope by owner -- [Persistence](../persistence/overview.md) — where sessions and requests are stored +PLACEHOLDER \ No newline at end of file From d3ec34ebb65d0dc2494f3ecdb8c02da6889acc3c Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:49:13 -0400 Subject: [PATCH 10/18] feat(dispatch): fix background-work.md (replace PLACEHOLDER) --- apps/docs/docs/server/background-work.md | 433 ++++++++++++++++++++++- 1 file changed, 432 insertions(+), 1 deletion(-) diff --git a/apps/docs/docs/server/background-work.md b/apps/docs/docs/server/background-work.md index 311c8dd065..17f1d4bbbe 100644 --- a/apps/docs/docs/server/background-work.md +++ b/apps/docs/docs/server/background-work.md @@ -1 +1,432 @@ -PLACEHOLDER \ No newline at end of file +--- +sidebar_position: 6 +sidebar_label: Dispatched work +--- + +# Dispatched work + +Some work outlives the turn that asked for it: a long research pass, a document +being drafted, an implementation running for an hour. That work runs in its own +*session*, the record the framework keeps for one conversation, holding its +state, its resources, and the history of every request that ran in it. The +session hangs off the conversation that started it, as a child of it. + +This page covers how a flow starts that work, and the HTTP surface for reading +it afterwards. Ask a conversation for its children, then ask any one child for +its history. + +Starting one is server-side only. There is no endpoint for it. A job begins +inside a running request, either from a `dispatcher()` block or from a task +board handing a claimed row to a child session. See [Work that outlives the +turn](/guides/background-work#dispatch-work-in-a-child-session) for how the two +relate to the other kinds of background work. + +## Starting a job from a flow + +A flow declares the work a job can run under `internal.actions`, beside +`actions`. An internal entry has the same shape as an action, but no client can +call it. The only way in is a `dispatcher()` block inside the same flow. + +```ts +import { defineFlow, dispatcher, generator, handler } from "@flow-state-dev/core"; +import { z } from "zod"; + +const summarizeDocument = generator({ + name: "summarize-document", + model: "openai/gpt-5.4-mini", + inputSchema: z.object({ documentId: z.string() }), + prompt: "Summarize the document.", +}); + +const acknowledge = handler({ + name: "acknowledge", + inputSchema: z.object({ reason: z.string() }), + execute: async (input) => ({ noted: input.reason }), +}); + +// One job per document. The same documentId from the same conversation +// lands on the same job. +const summarizeInBackground = dispatcher({ + name: "summarize-in-background", + type: "internal", + target: "summarize", + inputSchema: z.object({ documentId: z.string() }), + session: { key: (input) => input.documentId }, +}); + +// Deliver into a session that already exists. +const nudgeCoordinator = dispatcher({ + name: "nudge-coordinator", + type: "internal", + target: "acknowledge", + inputSchema: z.object({ coordinatorSessionId: z.string(), reason: z.string() }), + session: { id: (input) => input.coordinatorSessionId }, + payload: (input) => ({ reason: input.reason }), +}); + +export default defineFlow({ + kind: "documents", + actions: { + upload: { block: summarizeInBackground }, + nudge: { block: nudgeCoordinator }, + }, + internal: { + actions: { + summarize: { block: summarizeDocument }, + acknowledge: { block: acknowledge }, + }, + }, +})(); +``` + +A dispatcher is a handler. Run it, in a sequencer step, as a generator's tool, +or as an action's root block, and it sends one request to `target` and returns +as soon as the runtime has accepted it. It does not wait for the work. + +```ts +// what the dispatcher returns +{ sessionId: "dsx_9f2c1a", requestId: "req_c41e", adopted: false } +``` + +`sessionId` is the session the work runs in, `requestId` the run it became, and +`adopted` whether that session already existed. The entry validates the payload +against its own `inputSchema` on arrival; `payload` shapes it, and defaults to +the dispatcher's input as-is. + +`session` decides which session that is. + +| `session` | Runs in | When it does not exist | +|---|---|---| +| `{ key: (input) => string }` | a child of the running session, derived from the key | created; the next call with the same key from the same conversation adopts it | +| `{ id: (input) => string }` | the session with that id | refused. Nothing is created | + +A `key` child is a job in every sense on this page: it hangs off the session +that started it, runs the same flow as the same user, keeps its own state and +history, and shows up in the parent's listing below. The key is scoped to the +conversation, so the same key from a different conversation is a different +child. An `id` target has to be a session of this flow kind that belongs to +this user. + +`defineFlow` checks every dispatcher it can reach and throws at definition time +when `target` names an entry the flow does not declare. An action named +`summarize` does not stand in for `internal.actions.summarize`; each map is +looked up on its own. + +A refusal at run time throws `DispatchRefusedError`, with `code: +"dispatch-refused"` and a `refused` field to branch on: + +| `refused` | Meaning | +|---|---| +| `no-entry` | The addressed flow declares no entry at that address | +| `flow-not-found` | A `flowKind` names a flow this server has not registered | +| `session-not-found` | An `id` names a session that does not exist, or one that belongs to another user | +| `session-not-addressable` | An `id` names a session on a flow other than the one addressed | +| `key-occupied` | The `key` derived a session id already held by something that is not this conversation's child | +| `no-dispatch-operation` | This process runs requests but was not set up to dispatch one | +| `dispatch-rejected` | The entry's `concurrency` policy is `reject` and its key is held | +| `external-dispatcher` | An `id` delivery on a deployment that hands work to an external queue. A `key` child is unaffected | + +Every refusal is decided before anything starts, so a `.rescue()` on the +dispatcher can branch on `refused` knowing no child is running. A `key` or +`id` function that returns an empty string throws a plain `Error` naming the +block. + +A task board seat can start a job the same way: a `dispatcher({ type: "task" +})` under `workers` sends each claimed row to one of the flow's `task.actions` +entries, and the child session lands in the same listing. See [Task board → +Seats that hand off](../orchestration/task-board.md#seats-that-hand-off). + +### Starting a job on another flow + +A server usually runs more than one flow. Add `flowKind` and the dispatcher +resolves its `target` on that flow's `internal.actions` instead of its own: + +```ts +const notifyBilling = dispatcher({ + name: "notify-billing", + type: "internal", + flowKind: "billing", // the other flow + target: "charge", // billing's internal.actions.charge + inputSchema: z.object({ orderId: z.string() }), + session: { key: (input) => input.orderId }, +}); +``` + +The job still starts and returns immediately, and the child session still hangs +off the conversation that started it — but it belongs to the flow it was sent +to. It runs that flow's entry, starts with that flow's session-state defaults, +and its `flowKind` in the listing is that flow's. Whatever the job needs travels +in the payload; the two flows share no state. + +`defineFlow` can't check this address the way it checks a same-flow one. It sees +one flow at a time, and the flow you named is defined somewhere else. So the +check happens when the dispatch runs, against the flows the server has +registered: `flow-not-found` if there is no such flow, `no-entry` if there is +and it declares no such entry. Both are ordinary `DispatchRefusedError` +refusals — nothing retries, and nothing quietly falls back to an entry of the +same name on the sending flow. + +Both flows have to be registered on the same server. This addresses another +flow, not another service. + +To hear back, the other flow replies the same way it would within one flow — +a `{ from: true }` dispatcher — pointed at your `flowKind`: + +```ts +// on the billing flow +const confirmToSender = dispatcher({ + name: "confirm-to-sender", + type: "internal", + flowKind: "orders", + target: "confirm", + inputSchema: z.object({ orderId: z.string() }), + session: { from: true }, +}); +``` + +The runtime supplies the session to reply into, from the dispatch it stamped; +you supply the flow. If they disagree — the sender's session is not on the flow +you named — the reply is refused `session-not-addressable` rather than +delivered somewhere else. A `task` dispatcher takes no `flowKind`. + +## Listing a session's children + +``` +GET /api/flows/sessions/sess_abc/children +``` + +```json +{ + "children": [ + { + "id": "dsx_9f2c1a", + "parentSessionId": "sess_abc", + "topic": "task|10:issue-work|3:t42", + "coordinate": "task:implement", + "status": "active", + "createdAt": 1770000000000, + "updatedAt": 1770000042000 + }, + { + "id": "dsx_1c7b40", + "parentSessionId": "sess_abc", + "topic": "acme-corp", + "coordinate": "internal:summarize", + "status": "completed", + "createdAt": 1769999000000, + "updatedAt": 1769999900000 + } + ] +} +``` + +Those seven fields are the whole row. The route sends this named set rather than +a session record, so there is no `flowKind`, `userId`, `title` or `metadata` on +it. + +`topic` and `coordinate` are display labels. `coordinate` is the entry the child +was dispatched to, `:`: `internal:summarize` for an internal entry, +`task:implement` for a task-board seat that hands off. `topic` is the key the +child session was derived from — what a `dispatcher()`'s `session: { key }` +function returned, or the composed key a task seat's `session` policy produced. + +Nothing routes, authorizes or identifies from either label, and both are +optional, as is `status`. Guard all three with `== null`. A row with no labels is +a child session, same as any other; it just carries nothing to display. + +### What `status` tells you + +`active` means the job isn't finished. It covers a job waiting in a queue, a job +running right now, and a job paused waiting for someone to approve something. +The endpoint does not distinguish those. If you need to know which, +open the job and read its history, or read the task board the job is working +from. + +Every other value is how the job's last run ended: + +| Value | Meaning | +|---|---| +| `completed` | The run finished. Not the same as the work succeeding | +| `failed` | The run itself ended with an error. A worker error doesn't always reach it | +| `aborted` | Cancelled | +| `incomplete` | Stopped short of finishing, usually on a budget | + +A job doing a task board's work runs that board's worker, and a worker that +throws records the failure on its own task. What that does to the run around it +is the board's +[`onError`](../orchestration/task-board.md#concurrency-and-error-handling) +setting. On the default, `"skip"`, the run finishes and the job reads +`completed`. On `"fail"` the error propagates and the job reads `failed`. + +So a board left on the default reports a job that succeeded for work that broke. +The task carries the failure under either setting, which makes the board the +thing to watch when the question is whether the work came out right, and the +job's status the thing to watch when the question is whether anything is still +running. A failed task reads `errored`, with the message in its [`error` +field](../orchestration/task-substrate.md#the-task-record). + +That write goes through the worker's claim on the task, so it lands only while +the task is still the worker's to write. One cancelled in the meantime, or +completed by the worker itself earlier in the run, or handed to another worker +after the claim lapsed, keeps the status it already has and records nothing. See +[Recording a result that may no longer +apply](../orchestration/task-substrate.md#recording-a-result-that-may-no-longer-apply). + +A job with no runs yet has no `status` field at all. Absence means "nothing has +run", which is different from any of the values above. + +A job that failed and was retried successfully reads `completed`; the failed +attempt is still there in the job's own history. + +`active` describes what the system recorded, not what a worker is doing right +now. If a worker's process dies mid-job the row keeps reading `active` until a +client continues the run or a retry supersedes it — the framework marks the run +recoverable, it does not restart it for you. A job +whose approval request expired without an answer reads `active` indefinitely, +because nothing discharges an approval except answering it. + +### What a stopped process leaves behind + +A process can stop while background work is still running, and the work is then +cancelled without being settled. So a job can read `active` with nothing running +it, and the request records under it can read in-progress, for a while after the +process is gone. Neither is a stuck row. + +The task clears itself: it is taken back once its lease has lapsed and some +worker claims it again. The request record is made *recoverable* rather than +cleared — a sweep marks it `interrupted`, the status a run can be resumed from, +running at runtime start, on a timer while a server is up, and on demand when a +client asks. + +Marking it is where the framework stops. Nothing continues or re-runs the work +on your behalf, deliberately: restarting a request nobody asked to restart is +how the same job runs twice. So the row keeps reading `active` — an +`interrupted` run is unfinished and still continuable — until a client resumes +or retries it, or a later run supersedes it. The sweep waits +until a record's heartbeat has been quiet longer than the staleness threshold, +so a job that has simply gone quiet for a second is never mistaken for an +abandoned one. + +That protection is the heartbeat, so it doesn't cover a flow that turns the +heartbeat off. With `request: { heartbeatIntervalMs: 0 }` nothing refreshes the +run's active-request registry entry, so a run lasting longer than the staleness +threshold will be marked `interrupted` while it is still going — which also +offers it for resume, so the same work can be started a second time. Keep the +heartbeat on for any flow whose requests outlive the threshold. + +The process that walked away mostly doesn't settle the record on its way out: +[`dispose()`](../api/server.md#shutdown) cancels background work rather than +marking it finished or failed. One case doesn't follow that yet — work still +waiting behind a concurrency limit when shutdown reaches it is recorded +`aborted` without ever having started — so read a terminal status after a +shutdown as a record of what the process did, not as proof the work ran. And if +nothing ever runs against that store again, nothing sweeps it, and the row stays +as it is. + +For the thresholds, see [Connection +resilience](./connection-resilience.md#configuration). For the lease and the +abandonment allowance, see [the +lease](../orchestration/task-substrate.md#the-lease) and [when a job keeps being +abandoned](../orchestration/task-substrate.md#when-a-job-keeps-being-abandoned). + +## Reading one child's history + +Each row's `id` addresses a session, so every session endpoint works on it: + +``` +GET /api/flows/sessions/dsx_9f2c1a/requests +``` + +That returns the child's runs, with the item log for each when you ask for it +(`?include_items=true`). + +A run a `dispatcher()` started reads `source: "internal"`, or `source: "task"` +when a task-board seat handed the work off, and carries a `metadata.dispatch` +bag: + +```json +{ + "source": "task", + "actionName": "implement", + "metadata": { + "dispatch": { + "type": "task", + "target": "implement", + "from": { "block": "hand-off-implement", "sessionId": "sess_abc" }, + "key": "task|10:issue-work|3:t42", + "taskId": "t42" + } + } +} +``` + +`type` and `target` are the entry the run executes, `from` names the block that +sent it and the session it was running in, `key` is the session key the child +was derived from, and `taskId` the board row on a task hand-off. `key` is absent +when the dispatcher delivered into an existing session by `id`, and `taskId` is +absent on an internal dispatch. + +The runtime assembles that bag from values it derived itself; a request body +cannot write it. It is still labels rather than authority — use `taskId` to +stitch a run to a board row in a view, not to key an authorization or a +settlement on. Read the bag only when `source` is `"internal"` or `"task"`: an +application can put whatever it likes in `metadata` on its own requests, +including a key named `dispatch`, and `source` is the field a request body +cannot set. + +A run with either source cannot be re-entered from outside. `retry`, +`continue`, and `resume` on its request id answer `404`, the same as for a +request that does not exist. + +Children can nest. If a child dispatches work of its own, calling `/children` on +its id returns it. + +## Paging + +Pass `limit` (1–100, default 25) and `offset` (0–10000). Values outside those +ranges get a `400` naming the accepted range rather than a silently clamped +page. A host can lower the ceiling with +[`maxChildSessionListLimit`](../configuration/runtime.md). + +Rows come back newest-created first. A child that starts a run while you are +paging will not shuffle the pages under you. A child *created* while you are +paging can be missed, or can shift a later page by one — if you need exactness +there, fetch a single page large enough to hold the whole set. + +## What this endpoint won't do + +**It won't apply access rules of its own.** The same rules that govern reading +the conversation named in the path govern reading its children. That is how +every session-addressed route works: session detail, state, resource content, +the debug endpoints. A conversation in another tenant answers `404`. One with no +children answers `200` with an empty list. Whether one belonging to another user +answers `403` depends on your `resolvePrincipal`. With none configured the +management endpoints stay open, so a caller holding a conversation id can read +its children. See [Without a resolver](./authentication.md#without-a-resolver). + +**It won't list background work across conversations.** There is no +"everything I have running" endpoint. You reach a child through the conversation +that started it. + +**It won't tell you whether a worker process is alive.** See the note on +`status` above. + +**It won't start anything.** Whether work runs in a child session is declared in +the flow. A caller can list children, never create one. + +**It won't return the child's state, resources, or journal.** Rows carry +identity, labels, timestamps and status. Fetch the session itself if you need +more. + +## Related + +- [Work that outlives the turn](/guides/background-work) — how this relates to the other + things this framework calls background work +- [Client overview](../client/overview.md#child-sessions) — the same two calls from an app +- [Claude Code SDK agent](../tools/claude-code-sdk.md#turning-it-off-for-background-work) — running + a coding agent in a child session, and what it records there +- [Codex SDK agent](../tools/codex.md#continuing-a-thread) — the other coding agent, and how a run + in a child session stays resumable when it is cancelled +- [Engine setup](./setup.md) — the full HTTP route table +- [Authentication](./authentication.md) — how addressed routes scope by owner +- [Persistence](../persistence/overview.md) — where sessions and requests are stored From 23a87e07019e942dd7ccb25d4aeee7ff666a5a05 Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:51:08 -0400 Subject: [PATCH 11/18] feat(dispatch): cross-flow follow-up files --- docs/contributing/architecture-reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/contributing/architecture-reference.md b/docs/contributing/architecture-reference.md index 38af171388..2b1156151b 100644 --- a/docs/contributing/architecture-reference.md +++ b/docs/contributing/architecture-reference.md @@ -28,7 +28,7 @@ Conflict rule: more specific reference wins (e.g. `docs/architecture/streaming.m prefix to the Flow State router. → [MCP Server Adapter](../architecture/mcp-server.md) - MCP per-action session: `ActionMcpConfig.session?: string | { fromInput: string }` (`core`). Default (omitted) → stateless (fresh ephemeral session per `tools/call`). String = mint template (first `*` → random token, else appended); `{ fromInput }` = read the flow `sessionId` from that input field. The MCP adapter derives the dispatch `sessionId` from it (`deriveSessionId`). Flow session key, not protocol `Mcp-Session-Id`; principal still from `resolvePrincipal`. `fromInput` is caller-controlled → single-trusted-principal only until caller-supplied session keys are principal-namespaced (follow-up). -- Action forms: every action shares `ActionCore` (handler `block` + execution policy). Caller-addressed = `ActionConfig` in `flow.actions`; event-addressed (webhook/chat/scheduled) carries the core inline on its transport map and has no HTTP/MCP caller surface (no `internal` flag — the structural fact is the boundary); dispatched (`source: "task"` / `"internal"`) resolves `flow.task.actions` / `flow.internal.actions` by name. Resolution seam `resolveActionCore(flow, actionName, source, metadata)`: every source maps to a dispatch type (`dispatchTypeOf`) and `resolveEntry` reads that type's one map — a namespaced coordinate (`metadata.webhook` / `metadata.chat.eventKey` / `metadata.schedule.scheduleId`) gated on `source` (set only by adapters) for the event forms, the name for the rest — with **no fallback into `flow.actions` from any type**; an unresolved coordinate is refused by name. Dynamic schedules carry the core on `InboundRequestEnvelope.resolvedActionCore` (transient — not persisted, so durable dynamic schedules don't recover). Dispatched forms: `flow.internal.actions` and `flow.task.actions` (nested under `actions`; the flat spelling is refused) are reached only by a `dispatcher()` block, resolved by `resolveEntry(flow, type, name, coordinate?)` (`core/flow/resolve-entry.ts`) as one `(type, name)` lookup with **no fallback for any type**. `dispatcher()` is a handler sending through the factory-only `DISPATCH_SEAM`; `{ key }` mints/adopts a derived child (`dispatch` namespace), `{ id }` delivers into an existing same-flow same-principal session, is refused under an external dispatcher, and is dropped by the incarnation guard if that session was recreated between acceptance and run. `{ from: true }` is the same existing-session delivery, addressed at the seam-stamped sender (`readDispatchStamp` → `from.sessionId`); a request the runtime did not dispatch refuses `no-sender` (a caller-written stamp is not a sender). `settleParentTask` stays the board-row close and is not this path. `concurrency` lives on `ActionCore` (every entry); the entry a `per-worker` or `{ key }` task seat hands off to defaults to `queue`. A `task` dispatcher is a seat on a task board (`workers: { implement: dispatcher({ type: "task", target, session }) }`); the board binds its id and claim gate (`createTaskGate`) onto the hand-off, and `defineFlow` puts `flow.task.actions[target]` behind that gate and refuses an entry block that declares `sessionStateSchema`. The child settles its row through `ctx.requestHost.settleParentTask` — no `claim` parameter; the fence ticket is re-minted from the row the gate verified. +- Action forms: every action shares `ActionCore` (handler `block` + execution policy). Caller-addressed = `ActionConfig` in `flow.actions`; event-addressed (webhook/chat/scheduled) carries the core inline on its transport map and has no HTTP/MCP caller surface (no `internal` flag — the structural fact is the boundary); dispatched (`source: "task"` / `"internal"`) resolves `flow.task.actions` / `flow.internal.actions` by name. Resolution seam `resolveActionCore(flow, actionName, source, metadata)`: every source maps to a dispatch type (`dispatchTypeOf`) and `resolveEntry` reads that type's one map — a namespaced coordinate (`metadata.webhook` / `metadata.chat.eventKey` / `metadata.schedule.scheduleId`) gated on `source` (set only by adapters) for the event forms, the name for the rest — with **no fallback into `flow.actions` from any type**; an unresolved coordinate is refused by name. Dynamic schedules carry the core on `InboundRequestEnvelope.resolvedActionCore` (transient — not persisted, so durable dynamic schedules don't recover). Dispatched forms: `flow.internal.actions` and `flow.task.actions` (nested under `actions`; the flat spelling is refused) are reached only by a `dispatcher()` block, resolved by `resolveEntry(flow, type, name, coordinate?)` (`core/flow/resolve-entry.ts`) as one `(type, name)` lookup with **no fallback for any type**. `dispatcher()` is a handler sending through the factory-only `DISPATCH_SEAM`; `{ key }` mints/adopts a derived child (`dispatch` namespace), `{ id }` delivers into an existing same-flow same-principal session, is refused under an external dispatcher, and is dropped by the incarnation guard if that session was recreated between acceptance and run. `{ from: true }` is the same existing-session delivery, addressed at the seam-stamped sender (`readDispatchStamp` → `from.sessionId`); a request the runtime did not dispatch refuses `no-sender` (a caller-written stamp is not a sender). `settleParentTask` stays the board-row close and is not this path. **Cross-flow:** an `internal` address may carry `flowKind` (`task` may not — `dispatcher()` throws), making it `(type, target, flowKind)`; `defineFlow`'s walk skips it (it holds one flow's maps) and the seam resolves it against the host registry (`RequestHostConstructionInputs.resolveFlow`) — `flow-not-found` for an unregistered flow, `no-entry` for a registered one with no such entry, never a fallback to the sender's map. A cross-flow `{ key }` child takes the **target** flow's `flowKind` and `stateSchema` defaults, roots its **own** lineage (the lineage bucket has no flow in its key, so inheriting would share a `sharedToLineage` cell across flows), and frames the target kind into the child-key material (appended only when cross-flow, so same-flow ids are unchanged). The stamp gains `flowKind` / `flowId` (the resolved instance; addressing is by kind). Not a descendant for `isDescendantSession` → `livenessOf` does not answer for one. `concurrency` lives on `ActionCore` (every entry); the entry a `per-worker` or `{ key }` task seat hands off to defaults to `queue`. A `task` dispatcher is a seat on a task board (`workers: { implement: dispatcher({ type: "task", target, session }) }`); the board binds its id and claim gate (`createTaskGate`) onto the hand-off, and `defineFlow` puts `flow.task.actions[target]` behind that gate and refuses an entry block that declares `sessionStateSchema`. The child settles its row through `ctx.requestHost.settleParentTask` — no `claim` parameter; the fence ticket is re-minted from the row the gate verified. - Public re-entry: `isPublicReentryAllowed(source, additionalSources?)` (`engine/routes/public-reentry.ts`) is an **allow-list** — `http` / `mcp` / `chat` / `scheduled` — routed through by retry, continue and resume. Anything else gets the not-found shape. Replaces the three per-route webhook deny-lists, which admitted any source nobody named. A host extends it for its own out-of-tree transports with the `publicReentrySources` option on `createFlowState` / `createFlowApiRouter` (carried on `RuntimeConfig`); `webhook`, `task` and `internal` are never openable and `assertPublicReentrySources` throws at router construction if one is named. → [Action Forms](../architecture/action-forms.md) - Scheduled actions: `schedules` config on `defineFlow` (`static` map + dynamic `resolve` hook). `ScheduleConfig = ActionCore & { cron; input?; principal?; ... }` — carries `block` inline (no `action: string`); `defineScheduleBinding` helper. Dynamic resolver via `createResourceCollectionScheduleResolver({ collection, blocks })` maps a persisted `kind` discriminator → block (`defineScheduleCollection` schema field renamed `action` → `kind`). Dispatch route `POST /api/flows/:kind/schedules/:scheduleId/dispatch`. From 64da4a25ab28a06ba88732170c3acc07d8f0fed6 Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:54:16 -0400 Subject: [PATCH 12/18] chore: stage cross-flow remain patches (small) --- .../02-http-handlers.ts.patch | 20 +++++++++++++ .../05-createFlowState.ts.patch | 15 ++++++++++ .../06-defineFlow.ts.patch | 29 +++++++++++++++++++ .../08-createExecutionContext.ts.patch | 21 ++++++++++++++ 4 files changed, 85 insertions(+) create mode 100644 .tmp-cross-flow-patches/02-http-handlers.ts.patch create mode 100644 .tmp-cross-flow-patches/05-createFlowState.ts.patch create mode 100644 .tmp-cross-flow-patches/06-defineFlow.ts.patch create mode 100644 .tmp-cross-flow-patches/08-createExecutionContext.ts.patch diff --git a/.tmp-cross-flow-patches/02-http-handlers.ts.patch b/.tmp-cross-flow-patches/02-http-handlers.ts.patch new file mode 100644 index 0000000000..323ecb58aa --- /dev/null +++ b/.tmp-cross-flow-patches/02-http-handlers.ts.patch @@ -0,0 +1,20 @@ +--- a/packages/engine/src/routes/http-handlers.ts ++++ b/packages/engine/src/routes/http-handlers.ts +@@ -290,6 +290,17 @@ + runtimeConfig.requestHost.dispatchOperation = createDispatchOperation({ host }); + } + ++ // Same last-resort terms, one field over: the flow lookup a cross-flow ++ // dispatch address resolves through. A router mounted without a `FlowState` ++ // has a registry of its own, and without this every cross-flow address it ++ // serves would refuse `flow-not-found` for flows sitting in that registry. ++ if ( ++ runtimeConfig.requestHost !== undefined && ++ runtimeConfig.requestHost.resolveFlow === undefined ++ ) { ++ runtimeConfig.requestHost.resolveFlow = (kind: string) => options.registry.get(kind); ++ } ++ + // Detect interrupted requests from previous runs on startup + if (options.detectInterruptedOnStartup !== false) { + void detectInterruptedRequests({ diff --git a/.tmp-cross-flow-patches/05-createFlowState.ts.patch b/.tmp-cross-flow-patches/05-createFlowState.ts.patch new file mode 100644 index 0000000000..ce7bb418ae --- /dev/null +++ b/.tmp-cross-flow-patches/05-createFlowState.ts.patch @@ -0,0 +1,15 @@ +--- a/packages/engine/src/flowstate/createFlowState.ts ++++ b/packages/engine/src/flowstate/createFlowState.ts +@@ -936,6 +936,12 @@ + maxChildSessionListLimit: this.#options.maxChildSessionListLimit, + requestHost: { + staleThresholdMs, ++ // The seam's flow lookup, for a cross-flow dispatch address. Stamped ++ // here for the same reason `dispatchOperation` is installed below — ++ // this config is the one a colocated worker and the router both copy, ++ // so wiring it anywhere later leaves one of them unable to resolve a ++ // flow the process has plainly registered. ++ resolveFlow: (kind: string) => this.#registry.get(kind), + ...(this.#routerRequested ? { staleSweepIntervalMs } : {}) + } + }); diff --git a/.tmp-cross-flow-patches/06-defineFlow.ts.patch b/.tmp-cross-flow-patches/06-defineFlow.ts.patch new file mode 100644 index 0000000000..c2399cb198 --- /dev/null +++ b/.tmp-cross-flow-patches/06-defineFlow.ts.patch @@ -0,0 +1,29 @@ +--- a/packages/core/src/flow/defineFlow.ts ++++ b/packages/core/src/flow/defineFlow.ts +@@ -617,6 +617,13 @@ + * address; caught at run time, a claimed row would be handed off to nothing and + * wait out its lease. + * ++ * The one address this walk cannot answer is a **cross-flow** one ++ * (`internal` with a `flowKind`): it names an entry on a flow registered ++ * independently of this one, and a `defineFlow` holding one flow's maps has ++ * nothing to look it up in. Those are skipped here and resolved by the seam, ++ * against the flows the running process registered — still one keyed lookup ++ * with no fallback, still a refusal by name, just one layer later. ++ * + * A task entry is declared as a plain block, and a `task` dispatch may only + * ever reach it through its board's gate — the row re-read, the claim verified, + * the task scope marked, the ticket re-minted. The board cannot install that +@@ -657,6 +664,12 @@ + const label = `${address.type}:"${address.target}"`; + + if (address.type === "internal") { ++ // A cross-flow address names an entry on a flow this `defineFlow` does ++ // not hold, so there is nothing here to resolve it against. Skipped ++ // rather than guessed: the seam resolves it against the flows the ++ // process actually registered and refuses by name — `flow-not-found` ++ // or `no-entry` — which is the same rule, checked where the answer is. ++ if (address.flowKind !== undefined) continue; + if (internal !== undefined && Object.hasOwn(internal, address.target)) continue; + throw new Error( + `Flow "${kind}" reaches block "${block.name}", which dispatches to ${label}, but the ` + diff --git a/.tmp-cross-flow-patches/08-createExecutionContext.ts.patch b/.tmp-cross-flow-patches/08-createExecutionContext.ts.patch new file mode 100644 index 0000000000..e158da7442 --- /dev/null +++ b/.tmp-cross-flow-patches/08-createExecutionContext.ts.patch @@ -0,0 +1,21 @@ +--- a/packages/engine/src/context/createExecutionContext.ts ++++ b/packages/engine/src/context/createExecutionContext.ts +@@ -60,6 +60,7 @@ + import { DEFAULT_RUNTIME_LOGGER, logRuntimeEvent, summarizeForLog } from "../execution/logging"; + import { createRequestSideChainPool } from "../execution/request-side-chain-pool"; + import { createRequestHost } from "./create-request-host"; ++import { readDispatchStamp } from "../execution/dispatch-metadata"; + import { ensureSessionRecord } from "./ensure-session-record"; + import { resolveActionCore } from "../execution/resolve-action-core"; + import { isTraceObservabilityEnabled, errorDetailsWithCause } from "@flow-state-dev/core"; +@@ -758,8 +759,10 @@ + lineageId + }, + dispatchOperation: options.requestHost.dispatchOperation, ++ resolveFlow: options.requestHost.resolveFlow, + parentTask: options.requestHost.parentTask, + effectiveRuntimeConfig: options.effectiveRuntimeConfig, ++ dispatchStamp: readDispatchStamp(options.source, options.metadata), + liveness: { + heartbeatIntervalMs: flow.request?.heartbeatIntervalMs, + staleThresholdMs: options.requestHost.staleThresholdMs, From 8e476f8b4927f47ff102397c20eab67a565597b6 Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:54:59 -0400 Subject: [PATCH 13/18] chore: stage cross-flow remain patches (dispatch + docs) --- .tmp-cross-flow-patches/01-dispatch.ts.patch | 111 ++++++++++++++++++ .../04-dispatched-work.md.patch | 102 ++++++++++++++++ 2 files changed, 213 insertions(+) create mode 100644 .tmp-cross-flow-patches/01-dispatch.ts.patch create mode 100644 .tmp-cross-flow-patches/04-dispatched-work.md.patch diff --git a/.tmp-cross-flow-patches/01-dispatch.ts.patch b/.tmp-cross-flow-patches/01-dispatch.ts.patch new file mode 100644 index 0000000000..509eeaff74 --- /dev/null +++ b/.tmp-cross-flow-patches/01-dispatch.ts.patch @@ -0,0 +1,111 @@ +--- a/packages/core/src/types/dispatch.ts ++++ b/packages/core/src/types/dispatch.ts +@@ -12,6 +12,18 @@ + * declares no such entry is refused by name; it never resolves another type's + * map. + * ++ * ## One flow, or another one ++ * ++ * An `internal` address may name a **different flow** — `flowKind` on the ++ * address. Delivery is the same door; what changes is which flow's entry map ++ * the target is resolved on, and therefore *when*. A same-flow address is ++ * resolved by `defineFlow`, which holds the map. A cross-flow address cannot ++ * be: the flow it names is registered separately, so the entry check happens ++ * at the seam, on the target flow the process actually has. That is a **miss ++ * with a name** — `flow-not-found` or `no-entry` — reaching the sending block ++ * as a thrown {@link DispatchRefusedError}, never a retry, a queue, or a ++ * fall-through to the sender's own map. ++ * + * What differs per type is who owns the entry's input schema and who may put a + * dispatch through the door. A block may dispatch a type only when it can + * itself supply that type's trust: it holds its own request's authority +@@ -74,10 +86,14 @@ + | { readonly key: (task: TPayload, ctx: BlockContext) => string }; + + /** +- * Where a dispatcher sends. Static by construction: `(type, target)` is what +- * `defineFlow` verifies, so a block's reachable set is declared rather than ++ * Where a dispatcher sends. Static by construction: `(type, target, flowKind)` ++ * is what the block declares, so its reachable set is declared rather than + * computed at run time. A target chosen from data is a router over declared + * dispatchers, not a dynamic address. ++ * ++ * `defineFlow` verifies the same-flow pair. A cross-flow address is equally ++ * static and equally declared — it is simply verified one layer later, by the ++ * seam, against the flow the running process registered under that kind. + * + * A `task` address also carries the seat's session policy — declared once on + * the dispatcher and read by the board that holds it, so the roster shows +@@ -88,6 +104,19 @@ + readonly type: "internal"; + /** The entry name — `flow.internal.actions[target]`. */ + readonly target: string; ++ /** ++ * The flow the entry lives on, when it is **not this one**. Absent is ++ * same-flow, which is the whole of what `defineFlow` can check. ++ * ++ * A cross-flow address is declared exactly like a same-flow one — a ++ * string on the block, resolved by the walk it is reachable from — but ++ * the flow it names is registered independently of this one, so nothing ++ * at definition time can read its entry map. The check moves to the ++ * seam, where it stays a **named refusal**: `flow-not-found` when this ++ * process has no such flow, `no-entry` when the flow has no such entry. ++ * Never a retry, a queue, or a fall through to this flow's own map. ++ */ ++ readonly flowKind?: string; + } + | { + readonly type: "task"; +@@ -204,13 +233,22 @@ + * this principal's on this flow; refused by name otherwise. Never created — + * an unknown id is a typo, a stale reference, or a hallucinated value, and + * auto-creating turns all three into work nobody is watching. +- */ +-export type SessionTarget = { readonly key: string } | { readonly id: string }; ++ * - `from` — the **seam-stamped sender**. The runtime reads ++ * `metadata.dispatch.from.sessionId` through `readDispatchStamp` and delivers ++ * into that session as an `id` would. The author names no session. A request ++ * that was not dispatched has no sender (`no-sender`). ++ */ ++export type SessionTarget = ++ | { readonly key: string } ++ | { readonly id: string } ++ | { readonly from: true }; + + /** What a dispatcher hands the seam. Every field is computed by the block that dispatches. */ + export type DispatchSpec = { + readonly type: BlockDispatchType; + readonly target: string; ++ /** The flow the entry lives on, when it is not the sending request's own. */ ++ readonly flowKind?: string; + readonly session: SessionTarget; + /** The entry's input. Validated by the entry's own schema on arrival. */ + readonly payload: unknown; +@@ -232,6 +270,12 @@ + export type DispatchRefusal = + /** The flow declares no entry at `(type, target)`. Resolution never falls through. */ + | "no-entry" ++ /** ++ * A cross-flow address names a flow this process has not registered. The ++ * runtime half of an address `defineFlow` could not verify — a typo, a flow ++ * that was never deployed here, or one deployed behind a different host. ++ */ ++ | "flow-not-found" + /** An `id` target names a session that does not exist. */ + | "session-not-found" + /** An `id` target names a session that is not this principal's, or not this flow's. */ +@@ -247,7 +291,13 @@ + * queue, where the recipient's concurrency policy would not be applied to it. + * A `key` child is unaffected. + */ +- | "external-dispatcher"; ++ | "external-dispatcher" ++ /** ++ * A `{ from: true }` target on a request the runtime did not dispatch — no ++ * trusted `metadata.dispatch.from`. A caller-written bag on an HTTP body is ++ * not a sender. ++ */ ++ | "no-sender"; + + /** Outcome of a dispatch. `adopted` says whether the child session already existed. */ + export type DispatchOutcome = diff --git a/.tmp-cross-flow-patches/04-dispatched-work.md.patch b/.tmp-cross-flow-patches/04-dispatched-work.md.patch new file mode 100644 index 0000000000..c2985f689f --- /dev/null +++ b/.tmp-cross-flow-patches/04-dispatched-work.md.patch @@ -0,0 +1,102 @@ +--- a/docs/architecture/dispatched-work.md ++++ b/docs/architecture/dispatched-work.md +@@ -34,7 +34,10 @@ + journal, metadata and session-scoped resources. It inherits the parent's + principal, tenant, org and flow kind, records `parentSessionId`, and carries + the parent's `lineageId` verbatim so a `sharedToLineage` resource resolves to +-the same storage in both. Nothing else is shared. There is no handle to the ++the same storage in both. (A child of a **cross-flow** dispatch takes the ++*addressed* flow's kind and roots its own lineage — see ++[Dispatching into another flow](#dispatching-into-another-flow).) Nothing else ++is shared. There is no handle to the + parent's state and no cross-session read path; what the child needs arrives + with the dispatch, and what the child produces lands on durable rows both can + address. +@@ -50,11 +53,14 @@ + - **Identity, server-derived.** The envelope's `source` is the dispatch type + (`task` or `internal`) and its principal is the sending request's. A block + supplies the *target* of a dispatch and never the *authority* for it. +-- **Provenance, as labels.** The child session record carries `topic` (the key +- it was derived from) and `coordinate` (`:`); the child request +- record carries `metadata.dispatch = { type, target, from, key?, taskId? }`. +- All of it is display and correlation. Nothing routes, authorizes or settles +- on it. ++- **Provenance.** The child session record carries `topic` (the key it was ++ derived from) and `coordinate` (`:`) as display labels. The ++ child request record carries `metadata.dispatch = { type, target, from, ++ key?, recipientLineageId?, taskId? }`. Read that bag only through ++ `readDispatchStamp`, which is gated on `source: "internal"` / `"task"`. ++ `{ from: true }` routes on the stamped sender (`from.sessionId`, and ++ `from.lineageId` when present). Everything else on the stamp is correlation. ++ `settleParentTask` does not read it. + - **The sending request's runtime config**, in-process only. See + [What cannot cross the queue](#what-cannot-cross-the-queue). + +@@ -86,6 +92,67 @@ + and `evaluateAdoption` re-checks flow kind, principal, tenant, org, parent and + lineage before adopting, because the public session-create route lets a + same-principal caller pre-create a record at that deterministic id. ++ ++### Dispatching into another flow ++ ++An `internal` dispatcher may name a different flow — `flowKind` on the block. ++Nothing about the mechanism changes: one envelope, one door, one request ++record, the same session policies, the same handle back. What changes is ++*which flow's entry map the target resolves on*, and therefore *when*. ++ ++`defineFlow` resolves a same-flow address, because it holds that flow's maps. ++It cannot resolve a cross-flow one — the flow named is registered ++independently — so the walk skips it and the seam does the lookup instead, ++against the flows this process registered. The rule is unchanged, one keyed ++lookup with no fallback; only the moment moves, and so does the shape of a ++miss: `flow-not-found` for a flow this process does not have, `no-entry` for ++one that has no such entry, both reaching the sending block as ++`DispatchRefusedError`. Neither retries, queues, nor resolves the sender's own ++map. The seam's flow lookup is wired from the host's registry ++(`RequestHostConstructionInputs.resolveFlow`); a process without one refuses ++every cross-flow address as `flow-not-found`, which is what it can honestly ++say. ++ ++Two things about the child differ from a same-flow one, and both follow from ++the boundary being a **storage** boundary as much as a routing one: ++ ++- **It belongs to the addressed flow.** Its record carries that flow's ++ `flowKind` and its session-state defaults come from that flow's ++ `stateSchema`, not the sender's. `parentSessionId` still names the sender's ++ session. ++- **It roots its own lineage** instead of inheriting the sender's. A ++ `sharedToLineage` resource stores under `scopeType: "lineage"` at the lineage ++ id, with no flow anywhere in the key — so handing a cross-flow child the ++ sender's lineage would put two flows' declarations on one durable cell. The ++ registry validates exactly that hazard at user and org scope, where it can ++ see both schemas side by side; it cannot see it here. Data crosses in the ++ payload, which the entry's own schema validates, and that is the whole of the ++ channel. ++ ++The target flow kind also joins the child-key material, so one parent ++dispatching the same key to two flows gets a child for each rather than a ++`key-occupied` collision between two unrelated addresses. It is appended only ++for a cross-flow address, so same-flow children keep the ids they already ++derive. ++ ++Two consequences worth naming. **A cross-flow child is not a descendant for ++the verbs that authorise by descent** — `isDescendantSession` re-checks the flow ++kind at every hop, so `livenessOf` will not answer for one. And **addressing is ++by flow kind**: both flows must be registered in the same process, and the ++resolved instance's `flow.id` is stamped onto `metadata.dispatch.flowId` as ++provenance rather than being addressable. ++ ++**Replies work the same way across the boundary.** The recipient answers with ++its own `{ from: true }` dispatcher pointed at the sender's `flowKind` — the ++same three requests as within one flow. The stamp supplies the session id and ++the address supplies the flow; a delivery happens only when they agree, and a ++sender session on some other flow is `session-not-addressable`. ++ ++A `task` dispatcher takes no `flowKind`. Its rows settle against its board's ++ledger and the claim gate fronting a task entry is installed by the flow that ++declares that entry, so a cross-flow hand-off would put the ledger on one side ++of the boundary and the gate on the other. `dispatcher()` throws rather than ++ignoring the field. + + ## The claim gate and the fence ticket + From fbbbd8e1f8547cfc4f281c6c37c856816d00f863 Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:55:35 -0400 Subject: [PATCH 14/18] chore: stage cross-flow remain patch (README) --- .tmp-cross-flow-patches/07-README.md.patch | 70 ++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 .tmp-cross-flow-patches/07-README.md.patch diff --git a/.tmp-cross-flow-patches/07-README.md.patch b/.tmp-cross-flow-patches/07-README.md.patch new file mode 100644 index 0000000000..f657367aa3 --- /dev/null +++ b/.tmp-cross-flow-patches/07-README.md.patch @@ -0,0 +1,70 @@ +--- a/packages/core/README.md ++++ b/packages/core/README.md +@@ -603,9 +603,10 @@ + | Field | What it does | + |---|---| + | `type` | `"internal"` sends this request's own authority; `"task"` sends a claim on a durable row and is meaningful only as a task board seat. | +-| `target` | The entry name, resolved as `flow.internal.actions[target]` or `flow.task.actions[target]`. Checked when the flow is defined. | ++| `target` | The entry name, resolved as `flow.internal.actions[target]` or `flow.task.actions[target]`. Checked when the flow is defined, unless `flowKind` names another flow. | ++| `flowKind` | `internal` only. The **other flow** the entry lives on. Omit to address this flow's own entry. Checked at run time, not when the flow is defined — see [Dispatching to another flow](#dispatching-to-another-flow). | + | `inputSchema` | `internal` only. What the block accepts. Defaults to `z.unknown()`. | +-| `session` | `internal`: `{ key: (input, ctx) => string }` derives a child of the running session; `{ id: (input, ctx) => string }` names an existing one. `task`: a `TaskSessionPolicy`, one of `"per-task"` (one child per row), `"per-worker"` (one child per seat), or `{ key: (task, ctx) => string }` read from the row's worker input. | ++| `session` | `internal`: `{ key: (input, ctx) => string }` derives a child of the running session; `{ id: (input, ctx) => string }` names an existing one; `{ from: true }` delivers into the seam-stamped sender (refuses `no-sender` when this request was not dispatched). `task`: a `TaskSessionPolicy`, one of `"per-task"` (one child per row), `"per-worker"` (one child per seat), or `{ key: (task, ctx) => string }` read from the row's worker input. | + | `payload` | `internal` only. `(input, ctx) => unknown`, the entry's input. Defaults to the input itself. Validated by the entry's own schema on arrival. | + | `transient` | Hide the block's trace from clients. Default `false`. | + +@@ -641,15 +642,51 @@ + + The same key from a different parent session, user, or tenant is a different child. A caller cannot address another user's child by key. The child's session record carries `parentSessionId`, `topic` (the key), and `coordinate` (`"internal:summarize"`). An `id` target must exist, belong to this flow kind, this principal, and this tenant, and not be bound to a different org. + +-`defineFlow` checks every block it can reach (sequencer steps, rescue handlers, a generator's `tools`, the `blocks` a `forEach` / `forEachSideChain` factory declares, and the blocks behind `internal` and `task` entries) and throws when a dispatcher names an entry the flow does not declare, naming the block and the address. A target chosen from data is a `router` over declared dispatchers, not a dynamic string. ++`defineFlow` checks every block it can reach (sequencer steps, rescue handlers, a generator's `tools`, the `blocks` a `forEach` / `forEachSideChain` factory declares, and the blocks behind `internal` and `task` entries) and throws when a dispatcher names an entry the flow does not declare, naming the block and the address. A target chosen from data is a `router` over declared dispatchers, not a dynamic string. The one address it cannot check is a cross-flow one, which names an entry on a flow it does not hold. ++ ++### Dispatching to another flow ++ ++An `internal` dispatcher can name a different flow with `flowKind`. Everything else is the same: the dispatch is fire-and-forget, the session policy still decides where it runs, and the block still returns a `DispatchHandle`. ++ ++```ts ++const notifyBilling = dispatcher({ ++ name: "notify-billing", ++ type: "internal", ++ flowKind: "billing", // resolves on the billing flow ++ target: "charge", // billing's flow.internal.actions.charge ++ inputSchema: z.object({ orderId: z.string() }), ++ session: { key: (input) => input.orderId }, ++}); ++``` ++ ++The address is as declared as any other — a string on the block, not a value computed from data — but `defineFlow` holds one flow's entry maps and cannot resolve another's. That check moves to run time, against the flows the process has registered, and stays a refusal by name: `flow-not-found` when no such flow is registered, `no-entry` when the flow is registered and declares no such entry. Neither retries, queues, nor falls back to the sending flow's own map. ++ ++The `key` child belongs to the flow it was dispatched to: its session record carries that flow's `flowKind`, its session-state defaults come from that flow's schema, and it roots its own lineage rather than inheriting the sender's — a `sharedToLineage` resource is addressed by lineage with no flow in the key, so sharing one across flows would put two schemas on one durable cell. Data crosses in the payload, which the entry's own schema validates. Two flows addressed with the same key from the same parent get their own child each. ++ ++**Getting an answer back** is the same three-request shape it is within one flow: the recipient replies with its own `{ from: true }` dispatcher, pointed at the sender's flow. `{ from: true }` supplies the session id from the runtime's stamp and `flowKind` supplies the flow; a delivery happens only when they agree, and `session-not-addressable` names it when they do not. ++ ++```ts ++// declared on the billing flow ++const confirmToSender = dispatcher({ ++ name: "confirm-to-sender", ++ type: "internal", ++ flowKind: "orders", ++ target: "confirm", ++ inputSchema: z.object({ orderId: z.string() }), ++ session: { from: true }, ++}); ++``` ++ ++Cross-flow addressing resolves by flow **kind**, and both flows have to be registered in the same process — a flow served by some other host is `flow-not-found`, not a network hop. A `task` dispatcher takes no `flowKind` and throws if given one: its rows settle against its board's ledger, and the claim gate that fronts a task entry is installed by the flow that declares it. + + At run time a refused dispatch throws `DispatchRefusedError` (`code: "dispatch-refused"`), carrying `blockName`, `address`, `detail`, and `refused`: + + | `refused` | Meaning | + |---|---| +-| `no-entry` | The flow declares no entry at `(type, target)`. | ++| `no-entry` | The addressed flow declares no entry at `(type, target)`. | ++| `flow-not-found` | A `flowKind` names a flow this process has not registered. | + | `session-not-found` | An `id` names a session that does not exist, or that belongs to another principal or another tenant. | +-| `session-not-addressable` | An `id` names a session on another flow, or one bound to a different org. | ++| `session-not-addressable` | An `id` (or `{ from: true }`) names a session on a flow other than the one addressed, or one bound to a different org. | + | `key-occupied` | A `key` derived a child id already held by a record that is not this request's child. | + | `no-dispatch-operation` | This process executes requests but was not wired to dispatch one. | + | `dispatch-rejected` | The host refused before starting, such as a `reject` concurrency policy whose key is held. | From 188febe12f61eb49acd298e7006e3ccef07cd568 Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:56:28 -0400 Subject: [PATCH 15/18] chore: stage create-request-host patch part1 --- .../03-create-request-host.ts.patch.part1 | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 .tmp-cross-flow-patches/03-create-request-host.ts.patch.part1 diff --git a/.tmp-cross-flow-patches/03-create-request-host.ts.patch.part1 b/.tmp-cross-flow-patches/03-create-request-host.ts.patch.part1 new file mode 100644 index 0000000000..e65c2ef539 --- /dev/null +++ b/.tmp-cross-flow-patches/03-create-request-host.ts.patch.part1 @@ -0,0 +1,149 @@ +--- a/packages/engine/src/context/create-request-host.ts ++++ b/packages/engine/src/context/create-request-host.ts +@@ -14,14 +14,20 @@ + * through the seam. The seam does four things, in order, and refuses by name + * at each: + * +- * 1. **Resolve the entry.** `(type, target)` on the flow's own map, with no +- * fallback — `no-entry` otherwise. The `defineFlow` walk already refused an +- * address that resolves nothing, so this is the run-time half of the same +- * rule, reached only by a dispatch the walk could not see (a carried core). ++ * 1. **Resolve the flow, then the entry.** The address names another flow or ++ * it does not; a named one must be registered in this process — ++ * `flow-not-found` otherwise. Then `(type, target)` on that flow's own map, ++ * with no fallback — `no-entry` otherwise. For a same-flow address the ++ * `defineFlow` walk already refused an address that resolves nothing, so ++ * that check is the run-time half of the same rule, reached only by a ++ * dispatch the walk could not see (a carried core). For a **cross-flow** ++ * address it is the only half there is: `defineFlow` holds one flow's maps. + * 2. **Resolve the session.** A `key` derives a child of the running session + * and mints or adopts it; an `id` names a session that must exist and be this + * principal's on this flow — `session-not-found` / `session-not-addressable` +- * otherwise, never created. ++ * otherwise, never created. `{ from: true }` is the same delivery as `id`, ++ * addressed at the trusted `dispatchStamp.from` — `no-sender` when this ++ * request was not dispatched. + * 3. **Build the envelope**, from values the seam derived: the dispatch type as + * the source, the sender's principal, tenant and org, and server-assembled + * provenance under `metadata.dispatch` — including, for an `id` delivery, +@@ -36,6 +42,11 @@ + * - no host dispatch operation wired → the seam refuses `no-dispatch-operation` + * - this request was not dispatched for a task → `parentTask()` resolves + * `undefined` and `settleParentTask` refuses `no-parent-task` ++ * - a `{ from: true }` target on a request the runtime did not dispatch → ++ * the seam refuses `no-sender` (a caller-written `metadata.dispatch` is not ++ * a sender) ++ * - a cross-flow address in a process with no flow registry wired, or naming a ++ * flow it has not registered → `flow-not-found` + * - the liveness gate refused → `livenessOf` is **absent from the bundle** + */ + import type { +@@ -51,6 +62,7 @@ + } from "@flow-state-dev/core/types"; + import type { SessionRecord, StoreRegistry } from "../stores/types"; + import { resolveEntry } from "@flow-state-dev/core"; ++import type { DispatchStamp } from "../execution/dispatch-metadata"; + import type { RuntimeConfig } from "../runtime-config"; + import { resolveLineageId, resolveSessionStorageKey } from "../stores/scope-keys"; + import { deriveDispatchChildSessionId, evaluateAdoption } from "./detached-child"; +@@ -87,6 +99,16 @@ + /** Absent when this process executes requests but cannot dispatch one. */ + dispatchOperation?: DispatchOperation; + /** ++ * Resolve another flow registered in this process, by kind — the flow ++ * registry, narrowed to the one question the seam asks. ++ * ++ * Only a **cross-flow** address consults it; the sending flow's own entries ++ * are resolved on `flow`, which is already here. Absent, every cross-flow ++ * address refuses `flow-not-found`, which is the honest answer for a process ++ * that cannot see past the one flow it was handed. ++ */ ++ resolveFlow?: (kind: string) => FlowInstance | undefined; ++ /** + * The config this request runs under, handed to the dispatch operation so + * a child inherits it rather than the host's construction-time one + * (FIX-1077). See `DispatchOperation`. +@@ -94,6 +116,13 @@ + effectiveRuntimeConfig?: RuntimeConfig; + /** Absent unless this request was dispatched for a parent-board task. */ + parentTask?: ParentTaskBinding; ++ /** ++ * The running request's trusted dispatch stamp, already read through ++ * {@link readDispatchStamp}. A `{ from: true }` target delivers into ++ * `from.sessionId`. Absent when this request was not dispatched — a ++ * caller-written bag is not a sender. ++ */ ++ dispatchStamp?: DispatchStamp; + /** Everything the liveness gate needs. The gate runs here, once. */ + liveness: Omit; + now?: () => number; +@@ -153,7 +182,10 @@ + * purpose: a distinct reason would confirm that a session exists across a + * boundary the caller cannot see past, which is an existence oracle. + */ +- const resolveExistingSession = async (sessionId: string): Promise => { ++ const resolveExistingSession = async ( ++ sessionId: string, ++ targetFlow: FlowInstance ++ ): Promise => { + const storageKey = resolveSessionStorageKey(sessionId, identity.tenantId); + const record = await stores.session.get(storageKey); + if ( +@@ -163,11 +195,16 @@ + ) { + return refuse("session-not-found", `no session "${sessionId}" is reachable from this request"); + } +- if (record.flowKind !== flow.kind) { ++ // Compared against the flow the dispatch is ADDRESSED to, not the sender's. ++ // For a same-flow address those are the same value and this is the check it ++ // always was; for a cross-flow one it is what makes the delivery land on a ++ // session of the flow whose entry is about to run it. A session of some ++ // third flow is still refused by name. ++ if (record.flowKind !== targetFlow.kind) { + return refuse( + "session-not-addressable", +- `session "${sessionId}" belongs to flow "${record.flowKind}", not "${flow.kind}"; ` + +- `cross-flow delivery is not supported` ++ `session "${sessionId}" belongs to flow "${record.flowKind}", but this dispatch is ` + ++ `addressed to flow "${targetFlow.kind}"` + ); + } + // Compared as two bindings, not two values that happen to be set: an +@@ -208,8 +245,10 @@ + */ + const resolveChildSession = async ( + key: string, +- address: { type: string; target: string } ++ address: { type: string; target: string }, ++ targetFlow: FlowInstance + ): Promise => { ++ const crossFlow = targetFlow.kind !== flow.kind; + const childId = deriveDispatchChildSessionId( + { + userId: identity.userId, +@@ -217,16 +256,38 @@ + parentSessionId: identity.sessionId, + lineageId: identity.lineageId + }, +- key ++ key, ++ // Only for a cross-flow address, so every same-flow child keeps the id it ++ // has always derived — see `deriveDispatchChildSessionId`. ++ crossFlow ? targetFlow.kind : undefined + ); + const storageKey = resolveSessionStorageKey(childId, identity.tenantId); ++ // A cross-flow child roots its OWN lineage instead of inheriting the ++ // sender's, because the lineage is a shared storage bucket: a ++ // `sharedToLineage` resource addresses `scopeType: "lineage"` at the lineage ++ // id, with no flow in the key. Handing the child the sender's lineage would ++ // put two flows' declarations on one durable cell — the exact collision the ++ // flow registry validates for at user and org scope, where it can see both ++ // schemas, and cannot see here. So the boundary the dispatch crosses is a ++ // storage boundary too: data reaches the child in the payload, which is what ++ // the entry's own schema validates. ++ // ++ // Deterministic, not `generateId("lin")`: the child id is derived, so ++ // adoption on retry has to be able to compare the lineage rather than accept ++ // whatever it finds (see `evaluateAdoption`'s note on pre-created records). ++ // Taken from `resolveLineageId` rather than spelled here, so it is the same ++ // value a reader falling back on a record that carries none would compute — From 864d77ba7833e0a141b12fc686575c3b46774e32 Mon Sep 17 00:00:00 2001 From: Jake Hoffner Date: Sun, 6 Sep 2026 11:57:01 -0400 Subject: [PATCH 16/18] chore: stage create-request-host patch part2 --- .../03-create-request-host.ts.patch.part2 | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 .tmp-cross-flow-patches/03-create-request-host.ts.patch.part2 diff --git a/.tmp-cross-flow-patches/03-create-request-host.ts.patch.part2 b/.tmp-cross-flow-patches/03-create-request-host.ts.patch.part2 new file mode 100644 index 0000000000..e5c94d3e17 --- /dev/null +++ b/.tmp-cross-flow-patches/03-create-request-host.ts.patch.part2 @@ -0,0 +1,170 @@ ++ // one owner of the rule, not two that can drift. ++ const childLineageId = crossFlow ++ ? resolveLineageId({ id: storageKey }) ++ : identity.lineageId; + const expected = { +- flowKind: flow.kind, ++ flowKind: targetFlow.kind, + userId: identity.userId, + tenantId: identity.tenantId, + orgId: identity.orgId, + parentSessionId: identity.sessionId, +- lineageId: identity.lineageId ++ lineageId: childLineageId + }; + + const existing = await stores.session.get(storageKey); +@@ -250,19 +311,20 @@ + // parses initial state through the flow's schema precisely so typed + // block reads never observe missing keys, and execution does not + // retroactively initialize an existing record. +- state: resolveSessionStateDefaults(flow) as SessionRecord["state"], ++ state: resolveSessionStateDefaults(targetFlow) as SessionRecord["state"], + version: 0, + createdAt: ts, + updatedAt: ts, +- flowKind: flow.kind, ++ flowKind: targetFlow.kind, + userId: identity.userId, + journal: [], + ...(identity.tenantId !== undefined ? { tenantId: identity.tenantId } : {}), + ...(identity.orgId !== undefined ? { orgId: identity.orgId } : {}), + parentSessionId: identity.sessionId, +- // Inherited verbatim. Not a hash, not a re-derivation — the same value, +- // so parent and child address one bucket by construction (FIX-1068). +- lineageId: identity.lineageId, ++ // Inherited verbatim for a same-flow child. Not a hash, not a ++ // re-derivation — the same value, so parent and child address one bucket ++ // by construction (FIX-1068). A cross-flow child roots its own; see above. ++ lineageId: childLineageId, + // Display labels, stamped here and only here: the key this child was + // derived from, and the entry it was dispatched for. Taken from the + // values this call already consumed to derive the child, so they cannot +@@ -300,13 +362,70 @@ + return { ok: true, sessionId: childId, orgId: identity.orgId, adopted: false, delivery: "child" }; + }; + ++ /** ++ * Spec → store. `{ from: true }` is delivery into the stamped sender — the ++ * same path as `id`, with the id taken from the trusted `dispatchStamp`, ++ * not from the spec. The author cannot name a reply-to; a missing stamp is ++ * `no-sender`. Wrong principal / other flow / a replaced sender incarnation ++ * then share the `id` guards (replaced sender is `session-not-addressable`). ++ */ ++ const resolveAddressedSession = async ( ++ spec: DispatchSpec, ++ targetFlow: FlowInstance ++ ): Promise => { ++ if ("from" in spec.session) { ++ const stamp = inputs.dispatchStamp; ++ if (stamp === undefined) { ++ return refuse( ++ "no-sender", ++ "this request was not dispatched, so there is no stamped sender to deliver back to" ++ ); ++ } ++ const sender = await resolveExistingSession(stamp.from.sessionId, targetFlow); ++ if (!sender.ok) return sender; ++ // Present only on stamps written after this field shipped. A legacy ++ // record without it keeps the `{ id }` guards alone (BP-030). ++ if ( ++ stamp.from.lineageId !== undefined && ++ sender.recipientLineageId !== stamp.from.lineageId ++ ) { ++ return refuse( ++ "session-not-addressable", ++ `session "${stamp.from.sessionId}" is not the incarnation that dispatched this request` ++ ); ++ } ++ return sender; ++ } ++ if ("id" in spec.session) { ++ return resolveExistingSession(spec.session.id, targetFlow); ++ } ++ return resolveChildSession(spec.session.key, spec, targetFlow); ++ }; ++ + const seam: DispatchSeam = async (spec: DispatchSpec): Promise => { +- // Admission first: the address must resolve on its own type's map. Never +- // falls through to another type — a `task` dispatch cannot reach an action. +- if (resolveEntry(flow, spec.type, spec.target) === undefined) { ++ // Which flow's maps the address resolves on. The sender's own unless the ++ // address names another — and a named one must be registered HERE: a flow ++ // deployed behind some other host is not reachable, and inventing a way to ++ // reach it would be a second delivery mechanism beside the one door. ++ const targetFlow = ++ spec.flowKind === undefined || spec.flowKind === flow.kind ++ ? flow ++ : inputs.resolveFlow?.(spec.flowKind); ++ if (targetFlow === undefined) { ++ return refuse( ++ "flow-not-found", ++ `no flow "${spec.flowKind}" is registered in this process, so the ${spec.type} entry ` + ++ `"${spec.target}" cannot be resolved` ++ ); ++ } ++ ++ // Admission: the address must resolve on its own type's map, on the flow it ++ // named. Never falls through to another type — a `task` dispatch cannot ++ // reach an action — and never to another flow's map. ++ if (resolveEntry(targetFlow, spec.type, spec.target) === undefined) { + return refuse( + "no-entry", +- `flow "${flow.kind}" declares no ${spec.type} entry "${spec.target}"` ++ `flow "${targetFlow.kind}" declares no ${spec.type} entry "${spec.target}"` + ); + } + +@@ -318,10 +437,7 @@ + ); + } + +- const session = +- "id" in spec.session +- ? await resolveExistingSession(spec.session.id) +- : await resolveChildSession(spec.session.key, spec); ++ const session = await resolveAddressedSession(spec, targetFlow); + if (!session.ok) return session; + + // Start goes through the host operation and resolves only once the dispatch +@@ -335,7 +451,9 @@ + sessionId: session.sessionId, + delivery: session.delivery, + input: spec.payload, +- flowKind: flow.kind, ++ // The flow the request BELONGS to — the one whose entry is about to run ++ // it, not the one that sent it. ++ flowKind: targetFlow.kind, + // The same identity the child key was derived from, or the existing + // session was validated against — see `DispatchOperation`. + userId: identity.userId, +@@ -343,14 +461,27 @@ + ...(session.orgId !== undefined ? { orgId: session.orgId } : {}), + // Server-assembled provenance for the request record: the address, the + // sending block and session, the key (when a child was derived), the +- // recipient's approved lineage (when an existing session was named), and ++ // recipient's approved lineage (when an existing session was addressed), and + // the facts the sender supplied through `provenance` — a channel whose + // contract is "put a fact here only when the runtime produced it". + metadata: { + dispatch: { + type: spec.type, + target: spec.target, +- from: { block: spec.from, sessionId: identity.sessionId }, ++ // The flow the entry was resolved on, stamped only when the dispatch ++ // actually crossed a flow boundary — so a reader can tell a ++ // cross-flow arrival from an ordinary one without inferring it, and ++ // an old record with neither field still reads as same-flow (BP-030). ++ // The id comes off the resolved instance rather than the address: it ++ // is what the seam actually resolved, which is the only id it knows. ++ ...(targetFlow.kind !== flow.kind ++ ? { flowKind: targetFlow.kind, flowId: targetFlow.id } ++ : {}), ++ from: { ++ block: spec.from, ++ sessionId: identity.sessionId, ++ lineageId: identity.lineageId ++ }, + ...("key" in spec.session ? { key: spec.session.key } : {}), + ...(session.recipientLineageId !== undefined + ? { recipientLineageId: session.recipientLineageId } From 65e3190c358d8d9a6809817a3e4d2ecac528c6e0 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 6 Sep 2026 16:01:37 +0000 Subject: [PATCH 17/18] feat(dispatch): cross-flow follow-up files Co-authored-by: Jake Hoffner --- docs/architecture/dispatched-work.md | 66 ++++++++- packages/core/README.md | 45 +++++- packages/core/src/flow/defineFlow.ts | 13 ++ packages/core/src/types/dispatch.ts | 41 +++++- .../engine/src/context/create-request-host.ts | 134 ++++++++++++++---- .../src/context/createExecutionContext.ts | 1 + .../engine/src/flowstate/createFlowState.ts | 6 + packages/engine/src/routes/http-handlers.ts | 11 ++ 8 files changed, 283 insertions(+), 34 deletions(-) diff --git a/docs/architecture/dispatched-work.md b/docs/architecture/dispatched-work.md index 94b9ca8fcf..cac3699193 100644 --- a/docs/architecture/dispatched-work.md +++ b/docs/architecture/dispatched-work.md @@ -34,7 +34,10 @@ A child session is a separate `session` cell: its own state, items, history, journal, metadata and session-scoped resources. It inherits the parent's principal, tenant, org and flow kind, records `parentSessionId`, and carries the parent's `lineageId` verbatim so a `sharedToLineage` resource resolves to -the same storage in both. Nothing else is shared. There is no handle to the +the same storage in both. (A child of a **cross-flow** dispatch takes the +*addressed* flow's kind and roots its own lineage — see +[Dispatching into another flow](#dispatching-into-another-flow).) Nothing else +is shared. There is no handle to the parent's state and no cross-session read path; what the child needs arrives with the dispatch, and what the child produces lands on durable rows both can address. @@ -90,6 +93,67 @@ and `evaluateAdoption` re-checks flow kind, principal, tenant, org, parent and lineage before adopting, because the public session-create route lets a same-principal caller pre-create a record at that deterministic id. +### Dispatching into another flow + +An `internal` dispatcher may name a different flow — `flowKind` on the block. +Nothing about the mechanism changes: one envelope, one door, one request +record, the same session policies, the same handle back. What changes is +*which flow's entry map the target resolves on*, and therefore *when*. + +`defineFlow` resolves a same-flow address, because it holds that flow's maps. +It cannot resolve a cross-flow one — the flow named is registered +independently — so the walk skips it and the seam does the lookup instead, +against the flows this process registered. The rule is unchanged, one keyed +lookup with no fallback; only the moment moves, and so does the shape of a +miss: `flow-not-found` for a flow this process does not have, `no-entry` for +one that has no such entry, both reaching the sending block as +`DispatchRefusedError`. Neither retries, queues, nor resolves the sender's own +map. The seam's flow lookup is wired from the host's registry +(`RequestHostConstructionInputs.resolveFlow`); a process without one refuses +every cross-flow address as `flow-not-found`, which is what it can honestly +say. + +Two things about the child differ from a same-flow one, and both follow from +the boundary being a **storage** boundary as much as a routing one: + +- **It belongs to the addressed flow.** Its record carries that flow's + `flowKind` and its session-state defaults come from that flow's + `stateSchema`, not the sender's. `parentSessionId` still names the sender's + session. +- **It roots its own lineage** instead of inheriting the sender's. A + `sharedToLineage` resource stores under `scopeType: "lineage"` at the lineage + id, with no flow anywhere in the key — so handing a cross-flow child the + sender's lineage would put two flows' declarations on one durable cell. The + registry validates exactly that hazard at user and org scope, where it can + see both schemas side by side; it cannot see it here. Data crosses in the + payload, which the entry's own schema validates, and that is the whole of the + channel. + +The target flow kind also joins the child-key material, so one parent +dispatching the same key to two flows gets a child for each rather than a +`key-occupied` collision between two unrelated addresses. It is appended only +for a cross-flow address, so same-flow children keep the ids they already +derive. + +Two consequences worth naming. **A cross-flow child is not a descendant for +the verbs that authorise by descent** — `isDescendantSession` re-checks the flow +kind at every hop, so `livenessOf` will not answer for one. And **addressing is +by flow kind**: both flows must be registered in the same process, and the +resolved instance's `flow.id` is stamped onto `metadata.dispatch.flowId` as +provenance rather than being addressable. + +**Replies work the same way across the boundary.** The recipient answers with +its own `{ from: true }` dispatcher pointed at the sender's `flowKind` — the +same three requests as within one flow. The stamp supplies the session id and +the address supplies the flow; a delivery happens only when they agree, and a +sender session on some other flow is `session-not-addressable`. + +A `task` dispatcher takes no `flowKind`. Its rows settle against its board's +ledger and the claim gate fronting a task entry is installed by the flow that +declares that entry, so a cross-flow hand-off would put the ledger on one side +of the boundary and the gate on the other. `dispatcher()` throws rather than +ignoring the field. + ## The claim gate and the fence ticket A task hand-off leaves the row `in_progress` in the parent's ledger, owned by diff --git a/packages/core/README.md b/packages/core/README.md index 82d4d72e27..31a2d48fb7 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -603,7 +603,8 @@ export default defineFlow({ | Field | What it does | |---|---| | `type` | `"internal"` sends this request's own authority; `"task"` sends a claim on a durable row and is meaningful only as a task board seat. | -| `target` | The entry name, resolved as `flow.internal.actions[target]` or `flow.task.actions[target]`. Checked when the flow is defined. | +| `target` | The entry name, resolved as `flow.internal.actions[target]` or `flow.task.actions[target]`. Checked when the flow is defined, unless `flowKind` names another flow. | +| `flowKind` | `internal` only. The **other flow** the entry lives on. Omit to address this flow's own entry. Checked at run time, not when the flow is defined — see [Dispatching to another flow](#dispatching-to-another-flow). | | `inputSchema` | `internal` only. What the block accepts. Defaults to `z.unknown()`. | | `session` | `internal`: `{ key: (input, ctx) => string }` derives a child of the running session; `{ id: (input, ctx) => string }` names an existing one; `{ from: true }` delivers into the seam-stamped sender (refuses `no-sender` when this request was not dispatched). `task`: a `TaskSessionPolicy`, one of `"per-task"` (one child per row), `"per-worker"` (one child per seat), or `{ key: (task, ctx) => string }` read from the row's worker input. | | `payload` | `internal` only. `(input, ctx) => unknown`, the entry's input. Defaults to the input itself. Validated by the entry's own schema on arrival. | @@ -641,15 +642,51 @@ The block returns a `DispatchHandle` (`dispatchHandleSchema`): `{ sessionId, req The same key from a different parent session, user, or tenant is a different child. A caller cannot address another user's child by key. The child's session record carries `parentSessionId`, `topic` (the key), and `coordinate` (`"internal:summarize"`). An `id` target must exist, belong to this flow kind, this principal, and this tenant, and not be bound to a different org. -`defineFlow` checks every block it can reach (sequencer steps, rescue handlers, a generator's `tools`, the `blocks` a `forEach` / `forEachSideChain` factory declares, and the blocks behind `internal` and `task` entries) and throws when a dispatcher names an entry the flow does not declare, naming the block and the address. A target chosen from data is a `router` over declared dispatchers, not a dynamic string. +`defineFlow` checks every block it can reach (sequencer steps, rescue handlers, a generator's `tools`, the `blocks` a `forEach` / `forEachSideChain` factory declares, and the blocks behind `internal` and `task` entries) and throws when a dispatcher names an entry the flow does not declare, naming the block and the address. A target chosen from data is a `router` over declared dispatchers, not a dynamic string. The one address it cannot check is a cross-flow one, which names an entry on a flow it does not hold. + +### Dispatching to another flow + +An `internal` dispatcher can name a different flow with `flowKind`. Everything else is the same: the dispatch is fire-and-forget, the session policy still decides where it runs, and the block still returns a `DispatchHandle`. + +```ts +const notifyBilling = dispatcher({ + name: "notify-billing", + type: "internal", + flowKind: "billing", // resolves on the billing flow + target: "charge", // billing's flow.internal.actions.charge + inputSchema: z.object({ orderId: z.string() }), + session: { key: (input) => input.orderId }, +}); +``` + +The address is as declared as any other — a string on the block, not a value computed from data — but `defineFlow` holds one flow's entry maps and cannot resolve another's. That check moves to run time, against the flows the process has registered, and stays a refusal by name: `flow-not-found` when no such flow is registered, `no-entry` when the flow is registered and declares no such entry. Neither retries, queues, nor falls back to the sending flow's own map. + +The `key` child belongs to the flow it was dispatched to: its session record carries that flow's `flowKind`, its session-state defaults come from that flow's schema, and it roots its own lineage rather than inheriting the sender's — a `sharedToLineage` resource is addressed by lineage with no flow in the key, so sharing one across flows would put two schemas on one durable cell. Data crosses in the payload, which the entry's own schema validates. Two flows addressed with the same key from the same parent get their own child each. + +**Getting an answer back** is the same three-request shape it is within one flow: the recipient replies with its own `{ from: true }` dispatcher, pointed at the sender's flow. `{ from: true }` supplies the session id from the runtime's stamp and `flowKind` supplies the flow; a delivery happens only when they agree, and `session-not-addressable` names it when they do not. + +```ts +// declared on the billing flow +const confirmToSender = dispatcher({ + name: "confirm-to-sender", + type: "internal", + flowKind: "orders", + target: "confirm", + inputSchema: z.object({ orderId: z.string() }), + session: { from: true }, +}); +``` + +Cross-flow addressing resolves by flow **kind**, and both flows have to be registered in the same process — a flow served by some other host is `flow-not-found`, not a network hop. A `task` dispatcher takes no `flowKind` and throws if given one: its rows settle against its board's ledger, and the claim gate that fronts a task entry is installed by the flow that declares it. At run time a refused dispatch throws `DispatchRefusedError` (`code: "dispatch-refused"`), carrying `blockName`, `address`, `detail`, and `refused`: | `refused` | Meaning | |---|---| -| `no-entry` | The flow declares no entry at `(type, target)`. | +| `no-entry` | The addressed flow declares no entry at `(type, target)`. | +| `flow-not-found` | A `flowKind` names a flow this process has not registered. | | `session-not-found` | An `id` names a session that does not exist, or that belongs to another principal or another tenant. | -| `session-not-addressable` | An `id` names a session on another flow, or one bound to a different org. | +| `session-not-addressable` | An `id` (or `{ from: true }`) names a session on a flow other than the one addressed, or one bound to a different org. | | `key-occupied` | A `key` derived a child id already held by a record that is not this request's child. | | `no-dispatch-operation` | This process executes requests but was not wired to dispatch one. | | `dispatch-rejected` | The host refused before starting, such as a `reject` concurrency policy whose key is held. | diff --git a/packages/core/src/flow/defineFlow.ts b/packages/core/src/flow/defineFlow.ts index 68e1c0d292..12ff2f069b 100644 --- a/packages/core/src/flow/defineFlow.ts +++ b/packages/core/src/flow/defineFlow.ts @@ -617,6 +617,13 @@ function validateEntryMaps( * address; caught at run time, a claimed row would be handed off to nothing and * wait out its lease. * + * The one address this walk cannot answer is a **cross-flow** one + * (`internal` with a `flowKind`): it names an entry on a flow registered + * independently of this one, and a `defineFlow` holding one flow's maps has + * nothing to look it up in. Those are skipped here and resolved by the seam, + * against the flows the running process registered — still one keyed lookup + * with no fallback, still a refusal by name, just one layer later. + * * A task entry is declared as a plain block, and a `task` dispatch may only * ever reach it through its board's gate — the row re-read, the claim verified, * the task scope marked, the ticket re-minted. The board cannot install that @@ -657,6 +664,12 @@ function resolveDispatchTargets( const label = `${address.type}:"${address.target}"`; if (address.type === "internal") { + // A cross-flow address names an entry on a flow this `defineFlow` does + // not hold, so there is nothing here to resolve it against. Skipped + // rather than guessed: the seam resolves it against the flows the + // process actually registered and refuses by name — `flow-not-found` + // or `no-entry` — which is the same rule, checked where the answer is. + if (address.flowKind !== undefined) continue; if (internal !== undefined && Object.hasOwn(internal, address.target)) continue; throw new Error( `Flow "${kind}" reaches block "${block.name}", which dispatches to ${label}, but the ` + diff --git a/packages/core/src/types/dispatch.ts b/packages/core/src/types/dispatch.ts index dd06b68d75..5947643b8a 100644 --- a/packages/core/src/types/dispatch.ts +++ b/packages/core/src/types/dispatch.ts @@ -12,6 +12,18 @@ * declares no such entry is refused by name; it never resolves another type's * map. * + * ## One flow, or another one + * + * An `internal` address may name a **different flow** — `flowKind` on the + * address. Delivery is the same door; what changes is which flow's entry map + * the target is resolved on, and therefore *when*. A same-flow address is + * resolved by `defineFlow`, which holds the map. A cross-flow address cannot + * be: the flow it names is registered separately, so the entry check happens + * at the seam, on the target flow the process actually has. That is a **miss + * with a name** — `flow-not-found` or `no-entry` — reaching the sending block + * as a thrown {@link DispatchRefusedError}, never a retry, a queue, or a + * fall-through to the sender's own map. + * * What differs per type is who owns the entry's input schema and who may put a * dispatch through the door. A block may dispatch a type only when it can * itself supply that type's trust: it holds its own request's authority @@ -74,11 +86,15 @@ export type TaskSessionPolicy = | { readonly key: (task: TPayload, ctx: BlockContext) => string }; /** - * Where a dispatcher sends. Static by construction: `(type, target)` is what - * `defineFlow` verifies, so a block's reachable set is declared rather than + * Where a dispatcher sends. Static by construction: `(type, target, flowKind)` + * is what the block declares, so its reachable set is declared rather than * computed at run time. A target chosen from data is a router over declared * dispatchers, not a dynamic address. * + * `defineFlow` verifies the same-flow pair. A cross-flow address is equally + * static and equally declared — it is simply verified one layer later, by the + * seam, against the flow the running process registered under that kind. + * * A `task` address also carries the seat's session policy — declared once on * the dispatcher and read by the board that holds it, so the roster shows * statically which seats hand off and where their rows land. @@ -88,6 +104,19 @@ export type DispatchAddress = readonly type: "internal"; /** The entry name — `flow.internal.actions[target]`. */ readonly target: string; + /** + * The flow the entry lives on, when it is **not this one**. Absent is + * same-flow, which is the whole of what `defineFlow` can check. + * + * A cross-flow address is declared exactly like a same-flow one — a + * string on the block, resolved by the walk it is reachable from — but + * the flow it names is registered independently of this one, so nothing + * at definition time can read its entry map. The check moves to the + * seam, where it stays a **named refusal**: `flow-not-found` when this + * process has no such flow, `no-entry` when the flow has no such entry. + * Never a retry, a queue, or a fall through to this flow's own map. + */ + readonly flowKind?: string; } | { readonly type: "task"; @@ -218,6 +247,8 @@ export type SessionTarget = export type DispatchSpec = { readonly type: BlockDispatchType; readonly target: string; + /** The flow the entry lives on, when it is not the sending request's own. */ + readonly flowKind?: string; readonly session: SessionTarget; /** The entry's input. Validated by the entry's own schema on arrival. */ readonly payload: unknown; @@ -239,6 +270,12 @@ export type DispatchSpec = { export type DispatchRefusal = /** The flow declares no entry at `(type, target)`. Resolution never falls through. */ | "no-entry" + /** + * A cross-flow address names a flow this process has not registered. The + * runtime half of an address `defineFlow` could not verify — a typo, a flow + * that was never deployed here, or one deployed behind a different host. + */ + | "flow-not-found" /** An `id` target names a session that does not exist. */ | "session-not-found" /** An `id` target names a session that is not this principal's, or not this flow's. */ diff --git a/packages/engine/src/context/create-request-host.ts b/packages/engine/src/context/create-request-host.ts index 033a9653a5..b775724d8d 100644 --- a/packages/engine/src/context/create-request-host.ts +++ b/packages/engine/src/context/create-request-host.ts @@ -14,10 +14,14 @@ * through the seam. The seam does four things, in order, and refuses by name * at each: * - * 1. **Resolve the entry.** `(type, target)` on the flow's own map, with no - * fallback — `no-entry` otherwise. The `defineFlow` walk already refused an - * address that resolves nothing, so this is the run-time half of the same - * rule, reached only by a dispatch the walk could not see (a carried core). + * 1. **Resolve the flow, then the entry.** The address names another flow or + * it does not; a named one must be registered in this process — + * `flow-not-found` otherwise. Then `(type, target)` on that flow's own map, + * with no fallback — `no-entry` otherwise. For a same-flow address the + * `defineFlow` walk already refused an address that resolves nothing, so + * that check is the run-time half of the same rule, reached only by a + * dispatch the walk could not see (a carried core). For a **cross-flow** + * address it is the only half there is: `defineFlow` holds one flow's maps. * 2. **Resolve the session.** A `key` derives a child of the running session * and mints or adopts it; an `id` names a session that must exist and be this * principal's on this flow — `session-not-found` / `session-not-addressable` @@ -41,6 +45,8 @@ * - a `{ from: true }` target on a request the runtime did not dispatch → * the seam refuses `no-sender` (a caller-written `metadata.dispatch` is not * a sender) + * - a cross-flow address in a process with no flow registry wired, or naming a + * flow it has not registered → `flow-not-found` * - the liveness gate refused → `livenessOf` is **absent from the bundle** */ import type { @@ -92,6 +98,16 @@ export type RequestHostInputs = { }; /** Absent when this process executes requests but cannot dispatch one. */ dispatchOperation?: DispatchOperation; + /** + * Resolve another flow registered in this process, by kind — the flow + * registry, narrowed to the one question the seam asks. + * + * Only a **cross-flow** address consults it; the sending flow's own entries + * are resolved on `flow`, which is already here. Absent, every cross-flow + * address refuses `flow-not-found`, which is the honest answer for a process + * that cannot see past the one flow it was handed. + */ + resolveFlow?: (kind: string) => FlowInstance | undefined; /** * The config this request runs under, handed to the dispatch operation so * a child inherits it rather than the host's construction-time one @@ -166,7 +182,10 @@ export function createRequestHost(inputs: RequestHostInputs): RequestHostBuild { * purpose: a distinct reason would confirm that a session exists across a * boundary the caller cannot see past, which is an existence oracle. */ - const resolveExistingSession = async (sessionId: string): Promise => { + const resolveExistingSession = async ( + sessionId: string, + targetFlow: FlowInstance + ): Promise => { const storageKey = resolveSessionStorageKey(sessionId, identity.tenantId); const record = await stores.session.get(storageKey); if ( @@ -176,11 +195,16 @@ export function createRequestHost(inputs: RequestHostInputs): RequestHostBuild { ) { return refuse("session-not-found", `no session "${sessionId}" is reachable from this request`); } - if (record.flowKind !== flow.kind) { + // Compared against the flow the dispatch is ADDRESSED to, not the sender's. + // For a same-flow address those are the same value and this is the check it + // always was; for a cross-flow one it is what makes the delivery land on a + // session of the flow whose entry is about to run it. A session of some + // third flow is still refused by name. + if (record.flowKind !== targetFlow.kind) { return refuse( "session-not-addressable", - `session "${sessionId}" belongs to flow "${record.flowKind}", not "${flow.kind}"; ` + - `cross-flow delivery is not supported` + `session "${sessionId}" belongs to flow "${record.flowKind}", but this dispatch is ` + + `addressed to flow "${targetFlow.kind}"` ); } // Compared as two bindings, not two values that happen to be set: an @@ -221,8 +245,10 @@ export function createRequestHost(inputs: RequestHostInputs): RequestHostBuild { */ const resolveChildSession = async ( key: string, - address: { type: string; target: string } + address: { type: string; target: string }, + targetFlow: FlowInstance ): Promise => { + const crossFlow = targetFlow.kind !== flow.kind; const childId = deriveDispatchChildSessionId( { userId: identity.userId, @@ -230,16 +256,38 @@ export function createRequestHost(inputs: RequestHostInputs): RequestHostBuild { parentSessionId: identity.sessionId, lineageId: identity.lineageId }, - key + key, + // Only for a cross-flow address, so every same-flow child keeps the id it + // has always derived — see `deriveDispatchChildSessionId`. + crossFlow ? targetFlow.kind : undefined ); const storageKey = resolveSessionStorageKey(childId, identity.tenantId); + // A cross-flow child roots its OWN lineage instead of inheriting the + // sender's, because the lineage is a shared storage bucket: a + // `sharedToLineage` resource addresses `scopeType: "lineage"` at the lineage + // id, with no flow in the key. Handing the child the sender's lineage would + // put two flows' declarations on one durable cell — the exact collision the + // flow registry validates for at user and org scope, where it can see both + // schemas, and cannot see here. So the boundary the dispatch crosses is a + // storage boundary too: data reaches the child in the payload, which is what + // the entry's own schema validates. + // + // Deterministic, not `generateId("lin")`: the child id is derived, so + // adoption on retry has to be able to compare the lineage rather than accept + // whatever it finds (see `evaluateAdoption`'s note on pre-created records). + // Taken from `resolveLineageId` rather than spelled here, so it is the same + // value a reader falling back on a record that carries none would compute — + // one owner of the rule, not two that can drift. + const childLineageId = crossFlow + ? resolveLineageId({ id: storageKey }) + : identity.lineageId; const expected = { - flowKind: flow.kind, + flowKind: targetFlow.kind, userId: identity.userId, tenantId: identity.tenantId, orgId: identity.orgId, parentSessionId: identity.sessionId, - lineageId: identity.lineageId + lineageId: childLineageId }; const existing = await stores.session.get(storageKey); @@ -263,19 +311,20 @@ export function createRequestHost(inputs: RequestHostInputs): RequestHostBuild { // parses initial state through the flow's schema precisely so typed // block reads never observe missing keys, and execution does not // retroactively initialize an existing record. - state: resolveSessionStateDefaults(flow) as SessionRecord["state"], + state: resolveSessionStateDefaults(targetFlow) as SessionRecord["state"], version: 0, createdAt: ts, updatedAt: ts, - flowKind: flow.kind, + flowKind: targetFlow.kind, userId: identity.userId, journal: [], ...(identity.tenantId !== undefined ? { tenantId: identity.tenantId } : {}), ...(identity.orgId !== undefined ? { orgId: identity.orgId } : {}), parentSessionId: identity.sessionId, - // Inherited verbatim. Not a hash, not a re-derivation — the same value, - // so parent and child address one bucket by construction (FIX-1068). - lineageId: identity.lineageId, + // Inherited verbatim for a same-flow child. Not a hash, not a + // re-derivation — the same value, so parent and child address one bucket + // by construction (FIX-1068). A cross-flow child roots its own; see above. + lineageId: childLineageId, // Display labels, stamped here and only here: the key this child was // derived from, and the entry it was dispatched for. Taken from the // values this call already consumed to derive the child, so they cannot @@ -320,7 +369,10 @@ export function createRequestHost(inputs: RequestHostInputs): RequestHostBuild { * `no-sender`. Wrong principal / other flow / a replaced sender incarnation * then share the `id` guards (replaced sender is `session-not-addressable`). */ - const resolveAddressedSession = async (spec: DispatchSpec): Promise => { + const resolveAddressedSession = async ( + spec: DispatchSpec, + targetFlow: FlowInstance + ): Promise => { if ("from" in spec.session) { const stamp = inputs.dispatchStamp; if (stamp === undefined) { @@ -329,7 +381,7 @@ export function createRequestHost(inputs: RequestHostInputs): RequestHostBuild { "this request was not dispatched, so there is no stamped sender to deliver back to" ); } - const sender = await resolveExistingSession(stamp.from.sessionId); + const sender = await resolveExistingSession(stamp.from.sessionId, targetFlow); if (!sender.ok) return sender; // Present only on stamps written after this field shipped. A legacy // record without it keeps the `{ id }` guards alone (BP-030). @@ -345,18 +397,35 @@ export function createRequestHost(inputs: RequestHostInputs): RequestHostBuild { return sender; } if ("id" in spec.session) { - return resolveExistingSession(spec.session.id); + return resolveExistingSession(spec.session.id, targetFlow); } - return resolveChildSession(spec.session.key, spec); + return resolveChildSession(spec.session.key, spec, targetFlow); }; const seam: DispatchSeam = async (spec: DispatchSpec): Promise => { - // Admission first: the address must resolve on its own type's map. Never - // falls through to another type — a `task` dispatch cannot reach an action. - if (resolveEntry(flow, spec.type, spec.target) === undefined) { + // Which flow's maps the address resolves on. The sender's own unless the + // address names another — and a named one must be registered HERE: a flow + // deployed behind some other host is not reachable, and inventing a way to + // reach it would be a second delivery mechanism beside the one door. + const targetFlow = + spec.flowKind === undefined || spec.flowKind === flow.kind + ? flow + : inputs.resolveFlow?.(spec.flowKind); + if (targetFlow === undefined) { + return refuse( + "flow-not-found", + `no flow "${spec.flowKind}" is registered in this process, so the ${spec.type} entry ` + + `"${spec.target}" cannot be resolved` + ); + } + + // Admission: the address must resolve on its own type's map, on the flow it + // named. Never falls through to another type — a `task` dispatch cannot + // reach an action — and never to another flow's map. + if (resolveEntry(targetFlow, spec.type, spec.target) === undefined) { return refuse( "no-entry", - `flow "${flow.kind}" declares no ${spec.type} entry "${spec.target}"` + `flow "${targetFlow.kind}" declares no ${spec.type} entry "${spec.target}"` ); } @@ -368,7 +437,7 @@ export function createRequestHost(inputs: RequestHostInputs): RequestHostBuild { ); } - const session = await resolveAddressedSession(spec); + const session = await resolveAddressedSession(spec, targetFlow); if (!session.ok) return session; // Start goes through the host operation and resolves only once the dispatch @@ -382,7 +451,9 @@ export function createRequestHost(inputs: RequestHostInputs): RequestHostBuild { sessionId: session.sessionId, delivery: session.delivery, input: spec.payload, - flowKind: flow.kind, + // The flow the request BELONGS to — the one whose entry is about to run + // it, not the one that sent it. + flowKind: targetFlow.kind, // The same identity the child key was derived from, or the existing // session was validated against — see `DispatchOperation`. userId: identity.userId, @@ -397,6 +468,15 @@ export function createRequestHost(inputs: RequestHostInputs): RequestHostBuild { dispatch: { type: spec.type, target: spec.target, + // The flow the entry was resolved on, stamped only when the dispatch + // actually crossed a flow boundary — so a reader can tell a + // cross-flow arrival from an ordinary one without inferring it, and + // an old record with neither field still reads as same-flow (BP-030). + // The id comes off the resolved instance rather than the address: it + // is what the seam actually resolved, which is the only id it knows. + ...(targetFlow.kind !== flow.kind + ? { flowKind: targetFlow.kind, flowId: targetFlow.id } + : {}), from: { block: spec.from, sessionId: identity.sessionId, diff --git a/packages/engine/src/context/createExecutionContext.ts b/packages/engine/src/context/createExecutionContext.ts index 957e391c96..a114e0faef 100644 --- a/packages/engine/src/context/createExecutionContext.ts +++ b/packages/engine/src/context/createExecutionContext.ts @@ -759,6 +759,7 @@ export async function createExecutionContext< lineageId }, dispatchOperation: options.requestHost.dispatchOperation, + resolveFlow: options.requestHost.resolveFlow, parentTask: options.requestHost.parentTask, effectiveRuntimeConfig: options.effectiveRuntimeConfig, dispatchStamp: readDispatchStamp(options.source, options.metadata), diff --git a/packages/engine/src/flowstate/createFlowState.ts b/packages/engine/src/flowstate/createFlowState.ts index 6396a23e49..73963a17fb 100644 --- a/packages/engine/src/flowstate/createFlowState.ts +++ b/packages/engine/src/flowstate/createFlowState.ts @@ -936,6 +936,12 @@ class InternalFlowState maxChildSessionListLimit: this.#options.maxChildSessionListLimit, requestHost: { staleThresholdMs, + // The seam's flow lookup, for a cross-flow dispatch address. Stamped + // here for the same reason `dispatchOperation` is installed below — + // this config is the one a colocated worker and the router both copy, + // so wiring it anywhere later leaves one of them unable to resolve a + // flow the process has plainly registered. + resolveFlow: (kind: string) => this.#registry.get(kind), ...(this.#routerRequested ? { staleSweepIntervalMs } : {}) } }); diff --git a/packages/engine/src/routes/http-handlers.ts b/packages/engine/src/routes/http-handlers.ts index aa4cf149f9..f61db10e9e 100644 --- a/packages/engine/src/routes/http-handlers.ts +++ b/packages/engine/src/routes/http-handlers.ts @@ -290,6 +290,17 @@ export function createFlowRouteHandlers(options: CreateFlowRouteHandlersOptions) runtimeConfig.requestHost.dispatchOperation = createDispatchOperation({ host }); } + // Same last-resort terms, one field over: the flow lookup a cross-flow + // dispatch address resolves through. A router mounted without a `FlowState` + // has a registry of its own, and without this every cross-flow address it + // serves would refuse `flow-not-found` for flows sitting in that registry. + if ( + runtimeConfig.requestHost !== undefined && + runtimeConfig.requestHost.resolveFlow === undefined + ) { + runtimeConfig.requestHost.resolveFlow = (kind: string) => options.registry.get(kind); + } + // Detect interrupted requests from previous runs on startup if (options.detectInterruptedOnStartup !== false) { void detectInterruptedRequests({ From f82794e5bdf281f6f670a6f282e8d4e94d54d6f6 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 6 Sep 2026 16:06:03 +0000 Subject: [PATCH 18/18] POC: drop leftover .tmp-cross-flow-patches (does not merge) The staging patches were already applied to the source files. They implement nothing and should not ship with D-8. Co-authored-by: Jake Hoffner --- .tmp-cross-flow-patches/01-dispatch.ts.patch | 111 ------------ .../02-http-handlers.ts.patch | 20 --- .../03-create-request-host.ts.patch.part1 | 149 --------------- .../03-create-request-host.ts.patch.part2 | 170 ------------------ .../04-dispatched-work.md.patch | 102 ----------- .../05-createFlowState.ts.patch | 15 -- .../06-defineFlow.ts.patch | 29 --- .tmp-cross-flow-patches/07-README.md.patch | 70 -------- .../08-createExecutionContext.ts.patch | 21 --- 9 files changed, 687 deletions(-) delete mode 100644 .tmp-cross-flow-patches/01-dispatch.ts.patch delete mode 100644 .tmp-cross-flow-patches/02-http-handlers.ts.patch delete mode 100644 .tmp-cross-flow-patches/03-create-request-host.ts.patch.part1 delete mode 100644 .tmp-cross-flow-patches/03-create-request-host.ts.patch.part2 delete mode 100644 .tmp-cross-flow-patches/04-dispatched-work.md.patch delete mode 100644 .tmp-cross-flow-patches/05-createFlowState.ts.patch delete mode 100644 .tmp-cross-flow-patches/06-defineFlow.ts.patch delete mode 100644 .tmp-cross-flow-patches/07-README.md.patch delete mode 100644 .tmp-cross-flow-patches/08-createExecutionContext.ts.patch diff --git a/.tmp-cross-flow-patches/01-dispatch.ts.patch b/.tmp-cross-flow-patches/01-dispatch.ts.patch deleted file mode 100644 index 509eeaff74..0000000000 --- a/.tmp-cross-flow-patches/01-dispatch.ts.patch +++ /dev/null @@ -1,111 +0,0 @@ ---- a/packages/core/src/types/dispatch.ts -+++ b/packages/core/src/types/dispatch.ts -@@ -12,6 +12,18 @@ - * declares no such entry is refused by name; it never resolves another type's - * map. - * -+ * ## One flow, or another one -+ * -+ * An `internal` address may name a **different flow** — `flowKind` on the -+ * address. Delivery is the same door; what changes is which flow's entry map -+ * the target is resolved on, and therefore *when*. A same-flow address is -+ * resolved by `defineFlow`, which holds the map. A cross-flow address cannot -+ * be: the flow it names is registered separately, so the entry check happens -+ * at the seam, on the target flow the process actually has. That is a **miss -+ * with a name** — `flow-not-found` or `no-entry` — reaching the sending block -+ * as a thrown {@link DispatchRefusedError}, never a retry, a queue, or a -+ * fall-through to the sender's own map. -+ * - * What differs per type is who owns the entry's input schema and who may put a - * dispatch through the door. A block may dispatch a type only when it can - * itself supply that type's trust: it holds its own request's authority -@@ -74,10 +86,14 @@ - | { readonly key: (task: TPayload, ctx: BlockContext) => string }; - - /** -- * Where a dispatcher sends. Static by construction: `(type, target)` is what -- * `defineFlow` verifies, so a block's reachable set is declared rather than -+ * Where a dispatcher sends. Static by construction: `(type, target, flowKind)` -+ * is what the block declares, so its reachable set is declared rather than - * computed at run time. A target chosen from data is a router over declared - * dispatchers, not a dynamic address. -+ * -+ * `defineFlow` verifies the same-flow pair. A cross-flow address is equally -+ * static and equally declared — it is simply verified one layer later, by the -+ * seam, against the flow the running process registered under that kind. - * - * A `task` address also carries the seat's session policy — declared once on - * the dispatcher and read by the board that holds it, so the roster shows -@@ -88,6 +104,19 @@ - readonly type: "internal"; - /** The entry name — `flow.internal.actions[target]`. */ - readonly target: string; -+ /** -+ * The flow the entry lives on, when it is **not this one**. Absent is -+ * same-flow, which is the whole of what `defineFlow` can check. -+ * -+ * A cross-flow address is declared exactly like a same-flow one — a -+ * string on the block, resolved by the walk it is reachable from — but -+ * the flow it names is registered independently of this one, so nothing -+ * at definition time can read its entry map. The check moves to the -+ * seam, where it stays a **named refusal**: `flow-not-found` when this -+ * process has no such flow, `no-entry` when the flow has no such entry. -+ * Never a retry, a queue, or a fall through to this flow's own map. -+ */ -+ readonly flowKind?: string; - } - | { - readonly type: "task"; -@@ -204,13 +233,22 @@ - * this principal's on this flow; refused by name otherwise. Never created — - * an unknown id is a typo, a stale reference, or a hallucinated value, and - * auto-creating turns all three into work nobody is watching. -- */ --export type SessionTarget = { readonly key: string } | { readonly id: string }; -+ * - `from` — the **seam-stamped sender**. The runtime reads -+ * `metadata.dispatch.from.sessionId` through `readDispatchStamp` and delivers -+ * into that session as an `id` would. The author names no session. A request -+ * that was not dispatched has no sender (`no-sender`). -+ */ -+export type SessionTarget = -+ | { readonly key: string } -+ | { readonly id: string } -+ | { readonly from: true }; - - /** What a dispatcher hands the seam. Every field is computed by the block that dispatches. */ - export type DispatchSpec = { - readonly type: BlockDispatchType; - readonly target: string; -+ /** The flow the entry lives on, when it is not the sending request's own. */ -+ readonly flowKind?: string; - readonly session: SessionTarget; - /** The entry's input. Validated by the entry's own schema on arrival. */ - readonly payload: unknown; -@@ -232,6 +270,12 @@ - export type DispatchRefusal = - /** The flow declares no entry at `(type, target)`. Resolution never falls through. */ - | "no-entry" -+ /** -+ * A cross-flow address names a flow this process has not registered. The -+ * runtime half of an address `defineFlow` could not verify — a typo, a flow -+ * that was never deployed here, or one deployed behind a different host. -+ */ -+ | "flow-not-found" - /** An `id` target names a session that does not exist. */ - | "session-not-found" - /** An `id` target names a session that is not this principal's, or not this flow's. */ -@@ -247,7 +291,13 @@ - * queue, where the recipient's concurrency policy would not be applied to it. - * A `key` child is unaffected. - */ -- | "external-dispatcher"; -+ | "external-dispatcher" -+ /** -+ * A `{ from: true }` target on a request the runtime did not dispatch — no -+ * trusted `metadata.dispatch.from`. A caller-written bag on an HTTP body is -+ * not a sender. -+ */ -+ | "no-sender"; - - /** Outcome of a dispatch. `adopted` says whether the child session already existed. */ - export type DispatchOutcome = diff --git a/.tmp-cross-flow-patches/02-http-handlers.ts.patch b/.tmp-cross-flow-patches/02-http-handlers.ts.patch deleted file mode 100644 index 323ecb58aa..0000000000 --- a/.tmp-cross-flow-patches/02-http-handlers.ts.patch +++ /dev/null @@ -1,20 +0,0 @@ ---- a/packages/engine/src/routes/http-handlers.ts -+++ b/packages/engine/src/routes/http-handlers.ts -@@ -290,6 +290,17 @@ - runtimeConfig.requestHost.dispatchOperation = createDispatchOperation({ host }); - } - -+ // Same last-resort terms, one field over: the flow lookup a cross-flow -+ // dispatch address resolves through. A router mounted without a `FlowState` -+ // has a registry of its own, and without this every cross-flow address it -+ // serves would refuse `flow-not-found` for flows sitting in that registry. -+ if ( -+ runtimeConfig.requestHost !== undefined && -+ runtimeConfig.requestHost.resolveFlow === undefined -+ ) { -+ runtimeConfig.requestHost.resolveFlow = (kind: string) => options.registry.get(kind); -+ } -+ - // Detect interrupted requests from previous runs on startup - if (options.detectInterruptedOnStartup !== false) { - void detectInterruptedRequests({ diff --git a/.tmp-cross-flow-patches/03-create-request-host.ts.patch.part1 b/.tmp-cross-flow-patches/03-create-request-host.ts.patch.part1 deleted file mode 100644 index e65c2ef539..0000000000 --- a/.tmp-cross-flow-patches/03-create-request-host.ts.patch.part1 +++ /dev/null @@ -1,149 +0,0 @@ ---- a/packages/engine/src/context/create-request-host.ts -+++ b/packages/engine/src/context/create-request-host.ts -@@ -14,14 +14,20 @@ - * through the seam. The seam does four things, in order, and refuses by name - * at each: - * -- * 1. **Resolve the entry.** `(type, target)` on the flow's own map, with no -- * fallback — `no-entry` otherwise. The `defineFlow` walk already refused an -- * address that resolves nothing, so this is the run-time half of the same -- * rule, reached only by a dispatch the walk could not see (a carried core). -+ * 1. **Resolve the flow, then the entry.** The address names another flow or -+ * it does not; a named one must be registered in this process — -+ * `flow-not-found` otherwise. Then `(type, target)` on that flow's own map, -+ * with no fallback — `no-entry` otherwise. For a same-flow address the -+ * `defineFlow` walk already refused an address that resolves nothing, so -+ * that check is the run-time half of the same rule, reached only by a -+ * dispatch the walk could not see (a carried core). For a **cross-flow** -+ * address it is the only half there is: `defineFlow` holds one flow's maps. - * 2. **Resolve the session.** A `key` derives a child of the running session - * and mints or adopts it; an `id` names a session that must exist and be this - * principal's on this flow — `session-not-found` / `session-not-addressable` -- * otherwise, never created. -+ * otherwise, never created. `{ from: true }` is the same delivery as `id`, -+ * addressed at the trusted `dispatchStamp.from` — `no-sender` when this -+ * request was not dispatched. - * 3. **Build the envelope**, from values the seam derived: the dispatch type as - * the source, the sender's principal, tenant and org, and server-assembled - * provenance under `metadata.dispatch` — including, for an `id` delivery, -@@ -36,6 +42,11 @@ - * - no host dispatch operation wired → the seam refuses `no-dispatch-operation` - * - this request was not dispatched for a task → `parentTask()` resolves - * `undefined` and `settleParentTask` refuses `no-parent-task` -+ * - a `{ from: true }` target on a request the runtime did not dispatch → -+ * the seam refuses `no-sender` (a caller-written `metadata.dispatch` is not -+ * a sender) -+ * - a cross-flow address in a process with no flow registry wired, or naming a -+ * flow it has not registered → `flow-not-found` - * - the liveness gate refused → `livenessOf` is **absent from the bundle** - */ - import type { -@@ -51,6 +62,7 @@ - } from "@flow-state-dev/core/types"; - import type { SessionRecord, StoreRegistry } from "../stores/types"; - import { resolveEntry } from "@flow-state-dev/core"; -+import type { DispatchStamp } from "../execution/dispatch-metadata"; - import type { RuntimeConfig } from "../runtime-config"; - import { resolveLineageId, resolveSessionStorageKey } from "../stores/scope-keys"; - import { deriveDispatchChildSessionId, evaluateAdoption } from "./detached-child"; -@@ -87,6 +99,16 @@ - /** Absent when this process executes requests but cannot dispatch one. */ - dispatchOperation?: DispatchOperation; - /** -+ * Resolve another flow registered in this process, by kind — the flow -+ * registry, narrowed to the one question the seam asks. -+ * -+ * Only a **cross-flow** address consults it; the sending flow's own entries -+ * are resolved on `flow`, which is already here. Absent, every cross-flow -+ * address refuses `flow-not-found`, which is the honest answer for a process -+ * that cannot see past the one flow it was handed. -+ */ -+ resolveFlow?: (kind: string) => FlowInstance | undefined; -+ /** - * The config this request runs under, handed to the dispatch operation so - * a child inherits it rather than the host's construction-time one - * (FIX-1077). See `DispatchOperation`. -@@ -94,6 +116,13 @@ - effectiveRuntimeConfig?: RuntimeConfig; - /** Absent unless this request was dispatched for a parent-board task. */ - parentTask?: ParentTaskBinding; -+ /** -+ * The running request's trusted dispatch stamp, already read through -+ * {@link readDispatchStamp}. A `{ from: true }` target delivers into -+ * `from.sessionId`. Absent when this request was not dispatched — a -+ * caller-written bag is not a sender. -+ */ -+ dispatchStamp?: DispatchStamp; - /** Everything the liveness gate needs. The gate runs here, once. */ - liveness: Omit; - now?: () => number; -@@ -153,7 +182,10 @@ - * purpose: a distinct reason would confirm that a session exists across a - * boundary the caller cannot see past, which is an existence oracle. - */ -- const resolveExistingSession = async (sessionId: string): Promise => { -+ const resolveExistingSession = async ( -+ sessionId: string, -+ targetFlow: FlowInstance -+ ): Promise => { - const storageKey = resolveSessionStorageKey(sessionId, identity.tenantId); - const record = await stores.session.get(storageKey); - if ( -@@ -163,11 +195,16 @@ - ) { - return refuse("session-not-found", `no session "${sessionId}" is reachable from this request"); - } -- if (record.flowKind !== flow.kind) { -+ // Compared against the flow the dispatch is ADDRESSED to, not the sender's. -+ // For a same-flow address those are the same value and this is the check it -+ // always was; for a cross-flow one it is what makes the delivery land on a -+ // session of the flow whose entry is about to run it. A session of some -+ // third flow is still refused by name. -+ if (record.flowKind !== targetFlow.kind) { - return refuse( - "session-not-addressable", -- `session "${sessionId}" belongs to flow "${record.flowKind}", not "${flow.kind}"; ` + -- `cross-flow delivery is not supported` -+ `session "${sessionId}" belongs to flow "${record.flowKind}", but this dispatch is ` + -+ `addressed to flow "${targetFlow.kind}"` - ); - } - // Compared as two bindings, not two values that happen to be set: an -@@ -208,8 +245,10 @@ - */ - const resolveChildSession = async ( - key: string, -- address: { type: string; target: string } -+ address: { type: string; target: string }, -+ targetFlow: FlowInstance - ): Promise => { -+ const crossFlow = targetFlow.kind !== flow.kind; - const childId = deriveDispatchChildSessionId( - { - userId: identity.userId, -@@ -217,16 +256,38 @@ - parentSessionId: identity.sessionId, - lineageId: identity.lineageId - }, -- key -+ key, -+ // Only for a cross-flow address, so every same-flow child keeps the id it -+ // has always derived — see `deriveDispatchChildSessionId`. -+ crossFlow ? targetFlow.kind : undefined - ); - const storageKey = resolveSessionStorageKey(childId, identity.tenantId); -+ // A cross-flow child roots its OWN lineage instead of inheriting the -+ // sender's, because the lineage is a shared storage bucket: a -+ // `sharedToLineage` resource addresses `scopeType: "lineage"` at the lineage -+ // id, with no flow in the key. Handing the child the sender's lineage would -+ // put two flows' declarations on one durable cell — the exact collision the -+ // flow registry validates for at user and org scope, where it can see both -+ // schemas, and cannot see here. So the boundary the dispatch crosses is a -+ // storage boundary too: data reaches the child in the payload, which is what -+ // the entry's own schema validates. -+ // -+ // Deterministic, not `generateId("lin")`: the child id is derived, so -+ // adoption on retry has to be able to compare the lineage rather than accept -+ // whatever it finds (see `evaluateAdoption`'s note on pre-created records). -+ // Taken from `resolveLineageId` rather than spelled here, so it is the same -+ // value a reader falling back on a record that carries none would compute — diff --git a/.tmp-cross-flow-patches/03-create-request-host.ts.patch.part2 b/.tmp-cross-flow-patches/03-create-request-host.ts.patch.part2 deleted file mode 100644 index e5c94d3e17..0000000000 --- a/.tmp-cross-flow-patches/03-create-request-host.ts.patch.part2 +++ /dev/null @@ -1,170 +0,0 @@ -+ // one owner of the rule, not two that can drift. -+ const childLineageId = crossFlow -+ ? resolveLineageId({ id: storageKey }) -+ : identity.lineageId; - const expected = { -- flowKind: flow.kind, -+ flowKind: targetFlow.kind, - userId: identity.userId, - tenantId: identity.tenantId, - orgId: identity.orgId, - parentSessionId: identity.sessionId, -- lineageId: identity.lineageId -+ lineageId: childLineageId - }; - - const existing = await stores.session.get(storageKey); -@@ -250,19 +311,20 @@ - // parses initial state through the flow's schema precisely so typed - // block reads never observe missing keys, and execution does not - // retroactively initialize an existing record. -- state: resolveSessionStateDefaults(flow) as SessionRecord["state"], -+ state: resolveSessionStateDefaults(targetFlow) as SessionRecord["state"], - version: 0, - createdAt: ts, - updatedAt: ts, -- flowKind: flow.kind, -+ flowKind: targetFlow.kind, - userId: identity.userId, - journal: [], - ...(identity.tenantId !== undefined ? { tenantId: identity.tenantId } : {}), - ...(identity.orgId !== undefined ? { orgId: identity.orgId } : {}), - parentSessionId: identity.sessionId, -- // Inherited verbatim. Not a hash, not a re-derivation — the same value, -- // so parent and child address one bucket by construction (FIX-1068). -- lineageId: identity.lineageId, -+ // Inherited verbatim for a same-flow child. Not a hash, not a -+ // re-derivation — the same value, so parent and child address one bucket -+ // by construction (FIX-1068). A cross-flow child roots its own; see above. -+ lineageId: childLineageId, - // Display labels, stamped here and only here: the key this child was - // derived from, and the entry it was dispatched for. Taken from the - // values this call already consumed to derive the child, so they cannot -@@ -300,13 +362,70 @@ - return { ok: true, sessionId: childId, orgId: identity.orgId, adopted: false, delivery: "child" }; - }; - -+ /** -+ * Spec → store. `{ from: true }` is delivery into the stamped sender — the -+ * same path as `id`, with the id taken from the trusted `dispatchStamp`, -+ * not from the spec. The author cannot name a reply-to; a missing stamp is -+ * `no-sender`. Wrong principal / other flow / a replaced sender incarnation -+ * then share the `id` guards (replaced sender is `session-not-addressable`). -+ */ -+ const resolveAddressedSession = async ( -+ spec: DispatchSpec, -+ targetFlow: FlowInstance -+ ): Promise => { -+ if ("from" in spec.session) { -+ const stamp = inputs.dispatchStamp; -+ if (stamp === undefined) { -+ return refuse( -+ "no-sender", -+ "this request was not dispatched, so there is no stamped sender to deliver back to" -+ ); -+ } -+ const sender = await resolveExistingSession(stamp.from.sessionId, targetFlow); -+ if (!sender.ok) return sender; -+ // Present only on stamps written after this field shipped. A legacy -+ // record without it keeps the `{ id }` guards alone (BP-030). -+ if ( -+ stamp.from.lineageId !== undefined && -+ sender.recipientLineageId !== stamp.from.lineageId -+ ) { -+ return refuse( -+ "session-not-addressable", -+ `session "${stamp.from.sessionId}" is not the incarnation that dispatched this request` -+ ); -+ } -+ return sender; -+ } -+ if ("id" in spec.session) { -+ return resolveExistingSession(spec.session.id, targetFlow); -+ } -+ return resolveChildSession(spec.session.key, spec, targetFlow); -+ }; -+ - const seam: DispatchSeam = async (spec: DispatchSpec): Promise => { -- // Admission first: the address must resolve on its own type's map. Never -- // falls through to another type — a `task` dispatch cannot reach an action. -- if (resolveEntry(flow, spec.type, spec.target) === undefined) { -+ // Which flow's maps the address resolves on. The sender's own unless the -+ // address names another — and a named one must be registered HERE: a flow -+ // deployed behind some other host is not reachable, and inventing a way to -+ // reach it would be a second delivery mechanism beside the one door. -+ const targetFlow = -+ spec.flowKind === undefined || spec.flowKind === flow.kind -+ ? flow -+ : inputs.resolveFlow?.(spec.flowKind); -+ if (targetFlow === undefined) { -+ return refuse( -+ "flow-not-found", -+ `no flow "${spec.flowKind}" is registered in this process, so the ${spec.type} entry ` + -+ `"${spec.target}" cannot be resolved` -+ ); -+ } -+ -+ // Admission: the address must resolve on its own type's map, on the flow it -+ // named. Never falls through to another type — a `task` dispatch cannot -+ // reach an action — and never to another flow's map. -+ if (resolveEntry(targetFlow, spec.type, spec.target) === undefined) { - return refuse( - "no-entry", -- `flow "${flow.kind}" declares no ${spec.type} entry "${spec.target}"` -+ `flow "${targetFlow.kind}" declares no ${spec.type} entry "${spec.target}"` - ); - } - -@@ -318,10 +437,7 @@ - ); - } - -- const session = -- "id" in spec.session -- ? await resolveExistingSession(spec.session.id) -- : await resolveChildSession(spec.session.key, spec); -+ const session = await resolveAddressedSession(spec, targetFlow); - if (!session.ok) return session; - - // Start goes through the host operation and resolves only once the dispatch -@@ -335,7 +451,9 @@ - sessionId: session.sessionId, - delivery: session.delivery, - input: spec.payload, -- flowKind: flow.kind, -+ // The flow the request BELONGS to — the one whose entry is about to run -+ // it, not the one that sent it. -+ flowKind: targetFlow.kind, - // The same identity the child key was derived from, or the existing - // session was validated against — see `DispatchOperation`. - userId: identity.userId, -@@ -343,14 +461,27 @@ - ...(session.orgId !== undefined ? { orgId: session.orgId } : {}), - // Server-assembled provenance for the request record: the address, the - // sending block and session, the key (when a child was derived), the -- // recipient's approved lineage (when an existing session was named), and -+ // recipient's approved lineage (when an existing session was addressed), and - // the facts the sender supplied through `provenance` — a channel whose - // contract is "put a fact here only when the runtime produced it". - metadata: { - dispatch: { - type: spec.type, - target: spec.target, -- from: { block: spec.from, sessionId: identity.sessionId }, -+ // The flow the entry was resolved on, stamped only when the dispatch -+ // actually crossed a flow boundary — so a reader can tell a -+ // cross-flow arrival from an ordinary one without inferring it, and -+ // an old record with neither field still reads as same-flow (BP-030). -+ // The id comes off the resolved instance rather than the address: it -+ // is what the seam actually resolved, which is the only id it knows. -+ ...(targetFlow.kind !== flow.kind -+ ? { flowKind: targetFlow.kind, flowId: targetFlow.id } -+ : {}), -+ from: { -+ block: spec.from, -+ sessionId: identity.sessionId, -+ lineageId: identity.lineageId -+ }, - ...("key" in spec.session ? { key: spec.session.key } : {}), - ...(session.recipientLineageId !== undefined - ? { recipientLineageId: session.recipientLineageId } diff --git a/.tmp-cross-flow-patches/04-dispatched-work.md.patch b/.tmp-cross-flow-patches/04-dispatched-work.md.patch deleted file mode 100644 index c2985f689f..0000000000 --- a/.tmp-cross-flow-patches/04-dispatched-work.md.patch +++ /dev/null @@ -1,102 +0,0 @@ ---- a/docs/architecture/dispatched-work.md -+++ b/docs/architecture/dispatched-work.md -@@ -34,7 +34,10 @@ - journal, metadata and session-scoped resources. It inherits the parent's - principal, tenant, org and flow kind, records `parentSessionId`, and carries - the parent's `lineageId` verbatim so a `sharedToLineage` resource resolves to --the same storage in both. Nothing else is shared. There is no handle to the -+the same storage in both. (A child of a **cross-flow** dispatch takes the -+*addressed* flow's kind and roots its own lineage — see -+[Dispatching into another flow](#dispatching-into-another-flow).) Nothing else -+is shared. There is no handle to the - parent's state and no cross-session read path; what the child needs arrives - with the dispatch, and what the child produces lands on durable rows both can - address. -@@ -50,11 +53,14 @@ - - **Identity, server-derived.** The envelope's `source` is the dispatch type - (`task` or `internal`) and its principal is the sending request's. A block - supplies the *target* of a dispatch and never the *authority* for it. --- **Provenance, as labels.** The child session record carries `topic` (the key -- it was derived from) and `coordinate` (`:`); the child request -- record carries `metadata.dispatch = { type, target, from, key?, taskId? }`. -- All of it is display and correlation. Nothing routes, authorizes or settles -- on it. -+- **Provenance.** The child session record carries `topic` (the key it was -+ derived from) and `coordinate` (`:`) as display labels. The -+ child request record carries `metadata.dispatch = { type, target, from, -+ key?, recipientLineageId?, taskId? }`. Read that bag only through -+ `readDispatchStamp`, which is gated on `source: "internal"` / `"task"`. -+ `{ from: true }` routes on the stamped sender (`from.sessionId`, and -+ `from.lineageId` when present). Everything else on the stamp is correlation. -+ `settleParentTask` does not read it. - - **The sending request's runtime config**, in-process only. See - [What cannot cross the queue](#what-cannot-cross-the-queue). - -@@ -86,6 +92,67 @@ - and `evaluateAdoption` re-checks flow kind, principal, tenant, org, parent and - lineage before adopting, because the public session-create route lets a - same-principal caller pre-create a record at that deterministic id. -+ -+### Dispatching into another flow -+ -+An `internal` dispatcher may name a different flow — `flowKind` on the block. -+Nothing about the mechanism changes: one envelope, one door, one request -+record, the same session policies, the same handle back. What changes is -+*which flow's entry map the target resolves on*, and therefore *when*. -+ -+`defineFlow` resolves a same-flow address, because it holds that flow's maps. -+It cannot resolve a cross-flow one — the flow named is registered -+independently — so the walk skips it and the seam does the lookup instead, -+against the flows this process registered. The rule is unchanged, one keyed -+lookup with no fallback; only the moment moves, and so does the shape of a -+miss: `flow-not-found` for a flow this process does not have, `no-entry` for -+one that has no such entry, both reaching the sending block as -+`DispatchRefusedError`. Neither retries, queues, nor resolves the sender's own -+map. The seam's flow lookup is wired from the host's registry -+(`RequestHostConstructionInputs.resolveFlow`); a process without one refuses -+every cross-flow address as `flow-not-found`, which is what it can honestly -+say. -+ -+Two things about the child differ from a same-flow one, and both follow from -+the boundary being a **storage** boundary as much as a routing one: -+ -+- **It belongs to the addressed flow.** Its record carries that flow's -+ `flowKind` and its session-state defaults come from that flow's -+ `stateSchema`, not the sender's. `parentSessionId` still names the sender's -+ session. -+- **It roots its own lineage** instead of inheriting the sender's. A -+ `sharedToLineage` resource stores under `scopeType: "lineage"` at the lineage -+ id, with no flow anywhere in the key — so handing a cross-flow child the -+ sender's lineage would put two flows' declarations on one durable cell. The -+ registry validates exactly that hazard at user and org scope, where it can -+ see both schemas side by side; it cannot see it here. Data crosses in the -+ payload, which the entry's own schema validates, and that is the whole of the -+ channel. -+ -+The target flow kind also joins the child-key material, so one parent -+dispatching the same key to two flows gets a child for each rather than a -+`key-occupied` collision between two unrelated addresses. It is appended only -+for a cross-flow address, so same-flow children keep the ids they already -+derive. -+ -+Two consequences worth naming. **A cross-flow child is not a descendant for -+the verbs that authorise by descent** — `isDescendantSession` re-checks the flow -+kind at every hop, so `livenessOf` will not answer for one. And **addressing is -+by flow kind**: both flows must be registered in the same process, and the -+resolved instance's `flow.id` is stamped onto `metadata.dispatch.flowId` as -+provenance rather than being addressable. -+ -+**Replies work the same way across the boundary.** The recipient answers with -+its own `{ from: true }` dispatcher pointed at the sender's `flowKind` — the -+same three requests as within one flow. The stamp supplies the session id and -+the address supplies the flow; a delivery happens only when they agree, and a -+sender session on some other flow is `session-not-addressable`. -+ -+A `task` dispatcher takes no `flowKind`. Its rows settle against its board's -+ledger and the claim gate fronting a task entry is installed by the flow that -+declares that entry, so a cross-flow hand-off would put the ledger on one side -+of the boundary and the gate on the other. `dispatcher()` throws rather than -+ignoring the field. - - ## The claim gate and the fence ticket - diff --git a/.tmp-cross-flow-patches/05-createFlowState.ts.patch b/.tmp-cross-flow-patches/05-createFlowState.ts.patch deleted file mode 100644 index ce7bb418ae..0000000000 --- a/.tmp-cross-flow-patches/05-createFlowState.ts.patch +++ /dev/null @@ -1,15 +0,0 @@ ---- a/packages/engine/src/flowstate/createFlowState.ts -+++ b/packages/engine/src/flowstate/createFlowState.ts -@@ -936,6 +936,12 @@ - maxChildSessionListLimit: this.#options.maxChildSessionListLimit, - requestHost: { - staleThresholdMs, -+ // The seam's flow lookup, for a cross-flow dispatch address. Stamped -+ // here for the same reason `dispatchOperation` is installed below — -+ // this config is the one a colocated worker and the router both copy, -+ // so wiring it anywhere later leaves one of them unable to resolve a -+ // flow the process has plainly registered. -+ resolveFlow: (kind: string) => this.#registry.get(kind), - ...(this.#routerRequested ? { staleSweepIntervalMs } : {}) - } - }); diff --git a/.tmp-cross-flow-patches/06-defineFlow.ts.patch b/.tmp-cross-flow-patches/06-defineFlow.ts.patch deleted file mode 100644 index c2399cb198..0000000000 --- a/.tmp-cross-flow-patches/06-defineFlow.ts.patch +++ /dev/null @@ -1,29 +0,0 @@ ---- a/packages/core/src/flow/defineFlow.ts -+++ b/packages/core/src/flow/defineFlow.ts -@@ -617,6 +617,13 @@ - * address; caught at run time, a claimed row would be handed off to nothing and - * wait out its lease. - * -+ * The one address this walk cannot answer is a **cross-flow** one -+ * (`internal` with a `flowKind`): it names an entry on a flow registered -+ * independently of this one, and a `defineFlow` holding one flow's maps has -+ * nothing to look it up in. Those are skipped here and resolved by the seam, -+ * against the flows the running process registered — still one keyed lookup -+ * with no fallback, still a refusal by name, just one layer later. -+ * - * A task entry is declared as a plain block, and a `task` dispatch may only - * ever reach it through its board's gate — the row re-read, the claim verified, - * the task scope marked, the ticket re-minted. The board cannot install that -@@ -657,6 +664,12 @@ - const label = `${address.type}:"${address.target}"`; - - if (address.type === "internal") { -+ // A cross-flow address names an entry on a flow this `defineFlow` does -+ // not hold, so there is nothing here to resolve it against. Skipped -+ // rather than guessed: the seam resolves it against the flows the -+ // process actually registered and refuses by name — `flow-not-found` -+ // or `no-entry` — which is the same rule, checked where the answer is. -+ if (address.flowKind !== undefined) continue; - if (internal !== undefined && Object.hasOwn(internal, address.target)) continue; - throw new Error( - `Flow "${kind}" reaches block "${block.name}", which dispatches to ${label}, but the ` + diff --git a/.tmp-cross-flow-patches/07-README.md.patch b/.tmp-cross-flow-patches/07-README.md.patch deleted file mode 100644 index f657367aa3..0000000000 --- a/.tmp-cross-flow-patches/07-README.md.patch +++ /dev/null @@ -1,70 +0,0 @@ ---- a/packages/core/README.md -+++ b/packages/core/README.md -@@ -603,9 +603,10 @@ - | Field | What it does | - |---|---| - | `type` | `"internal"` sends this request's own authority; `"task"` sends a claim on a durable row and is meaningful only as a task board seat. | --| `target` | The entry name, resolved as `flow.internal.actions[target]` or `flow.task.actions[target]`. Checked when the flow is defined. | -+| `target` | The entry name, resolved as `flow.internal.actions[target]` or `flow.task.actions[target]`. Checked when the flow is defined, unless `flowKind` names another flow. | -+| `flowKind` | `internal` only. The **other flow** the entry lives on. Omit to address this flow's own entry. Checked at run time, not when the flow is defined — see [Dispatching to another flow](#dispatching-to-another-flow). | - | `inputSchema` | `internal` only. What the block accepts. Defaults to `z.unknown()`. | --| `session` | `internal`: `{ key: (input, ctx) => string }` derives a child of the running session; `{ id: (input, ctx) => string }` names an existing one. `task`: a `TaskSessionPolicy`, one of `"per-task"` (one child per row), `"per-worker"` (one child per seat), or `{ key: (task, ctx) => string }` read from the row's worker input. | -+| `session` | `internal`: `{ key: (input, ctx) => string }` derives a child of the running session; `{ id: (input, ctx) => string }` names an existing one; `{ from: true }` delivers into the seam-stamped sender (refuses `no-sender` when this request was not dispatched). `task`: a `TaskSessionPolicy`, one of `"per-task"` (one child per row), `"per-worker"` (one child per seat), or `{ key: (task, ctx) => string }` read from the row's worker input. | - | `payload` | `internal` only. `(input, ctx) => unknown`, the entry's input. Defaults to the input itself. Validated by the entry's own schema on arrival. | - | `transient` | Hide the block's trace from clients. Default `false`. | - -@@ -641,15 +642,51 @@ - - The same key from a different parent session, user, or tenant is a different child. A caller cannot address another user's child by key. The child's session record carries `parentSessionId`, `topic` (the key), and `coordinate` (`"internal:summarize"`). An `id` target must exist, belong to this flow kind, this principal, and this tenant, and not be bound to a different org. - --`defineFlow` checks every block it can reach (sequencer steps, rescue handlers, a generator's `tools`, the `blocks` a `forEach` / `forEachSideChain` factory declares, and the blocks behind `internal` and `task` entries) and throws when a dispatcher names an entry the flow does not declare, naming the block and the address. A target chosen from data is a `router` over declared dispatchers, not a dynamic string. -+`defineFlow` checks every block it can reach (sequencer steps, rescue handlers, a generator's `tools`, the `blocks` a `forEach` / `forEachSideChain` factory declares, and the blocks behind `internal` and `task` entries) and throws when a dispatcher names an entry the flow does not declare, naming the block and the address. A target chosen from data is a `router` over declared dispatchers, not a dynamic string. The one address it cannot check is a cross-flow one, which names an entry on a flow it does not hold. -+ -+### Dispatching to another flow -+ -+An `internal` dispatcher can name a different flow with `flowKind`. Everything else is the same: the dispatch is fire-and-forget, the session policy still decides where it runs, and the block still returns a `DispatchHandle`. -+ -+```ts -+const notifyBilling = dispatcher({ -+ name: "notify-billing", -+ type: "internal", -+ flowKind: "billing", // resolves on the billing flow -+ target: "charge", // billing's flow.internal.actions.charge -+ inputSchema: z.object({ orderId: z.string() }), -+ session: { key: (input) => input.orderId }, -+}); -+``` -+ -+The address is as declared as any other — a string on the block, not a value computed from data — but `defineFlow` holds one flow's entry maps and cannot resolve another's. That check moves to run time, against the flows the process has registered, and stays a refusal by name: `flow-not-found` when no such flow is registered, `no-entry` when the flow is registered and declares no such entry. Neither retries, queues, nor falls back to the sending flow's own map. -+ -+The `key` child belongs to the flow it was dispatched to: its session record carries that flow's `flowKind`, its session-state defaults come from that flow's schema, and it roots its own lineage rather than inheriting the sender's — a `sharedToLineage` resource is addressed by lineage with no flow in the key, so sharing one across flows would put two schemas on one durable cell. Data crosses in the payload, which the entry's own schema validates. Two flows addressed with the same key from the same parent get their own child each. -+ -+**Getting an answer back** is the same three-request shape it is within one flow: the recipient replies with its own `{ from: true }` dispatcher, pointed at the sender's flow. `{ from: true }` supplies the session id from the runtime's stamp and `flowKind` supplies the flow; a delivery happens only when they agree, and `session-not-addressable` names it when they do not. -+ -+```ts -+// declared on the billing flow -+const confirmToSender = dispatcher({ -+ name: "confirm-to-sender", -+ type: "internal", -+ flowKind: "orders", -+ target: "confirm", -+ inputSchema: z.object({ orderId: z.string() }), -+ session: { from: true }, -+}); -+``` -+ -+Cross-flow addressing resolves by flow **kind**, and both flows have to be registered in the same process — a flow served by some other host is `flow-not-found`, not a network hop. A `task` dispatcher takes no `flowKind` and throws if given one: its rows settle against its board's ledger, and the claim gate that fronts a task entry is installed by the flow that declares it. - - At run time a refused dispatch throws `DispatchRefusedError` (`code: "dispatch-refused"`), carrying `blockName`, `address`, `detail`, and `refused`: - - | `refused` | Meaning | - |---|---| --| `no-entry` | The flow declares no entry at `(type, target)`. | -+| `no-entry` | The addressed flow declares no entry at `(type, target)`. | -+| `flow-not-found` | A `flowKind` names a flow this process has not registered. | - | `session-not-found` | An `id` names a session that does not exist, or that belongs to another principal or another tenant. | --| `session-not-addressable` | An `id` names a session on another flow, or one bound to a different org. | -+| `session-not-addressable` | An `id` (or `{ from: true }`) names a session on a flow other than the one addressed, or one bound to a different org. | - | `key-occupied` | A `key` derived a child id already held by a record that is not this request's child. | - | `no-dispatch-operation` | This process executes requests but was not wired to dispatch one. | - | `dispatch-rejected` | The host refused before starting, such as a `reject` concurrency policy whose key is held. | diff --git a/.tmp-cross-flow-patches/08-createExecutionContext.ts.patch b/.tmp-cross-flow-patches/08-createExecutionContext.ts.patch deleted file mode 100644 index e158da7442..0000000000 --- a/.tmp-cross-flow-patches/08-createExecutionContext.ts.patch +++ /dev/null @@ -1,21 +0,0 @@ ---- a/packages/engine/src/context/createExecutionContext.ts -+++ b/packages/engine/src/context/createExecutionContext.ts -@@ -60,6 +60,7 @@ - import { DEFAULT_RUNTIME_LOGGER, logRuntimeEvent, summarizeForLog } from "../execution/logging"; - import { createRequestSideChainPool } from "../execution/request-side-chain-pool"; - import { createRequestHost } from "./create-request-host"; -+import { readDispatchStamp } from "../execution/dispatch-metadata"; - import { ensureSessionRecord } from "./ensure-session-record"; - import { resolveActionCore } from "../execution/resolve-action-core"; - import { isTraceObservabilityEnabled, errorDetailsWithCause } from "@flow-state-dev/core"; -@@ -758,8 +759,10 @@ - lineageId - }, - dispatchOperation: options.requestHost.dispatchOperation, -+ resolveFlow: options.requestHost.resolveFlow, - parentTask: options.requestHost.parentTask, - effectiveRuntimeConfig: options.effectiveRuntimeConfig, -+ dispatchStamp: readDispatchStamp(options.source, options.metadata), - liveness: { - heartbeatIntervalMs: flow.request?.heartbeatIntervalMs, - staleThresholdMs: options.requestHost.staleThresholdMs,