From 87888be1835bb58b2d4628a2de340e0ee7e3b790 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 7 Sep 2026 16:21:37 +0000 Subject: [PATCH 1/2] Add Workforce POC lab for static board notify (FIX-1311). MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Throwaway lab proving post → reactTo → router over declared dispatchers, without a MessageBoard L1 or a dynamic address. Co-authored-by: Jake Hoffner --- knip.json | 3 + labs/workforce-poc-board-notify/README.md | 74 ++++ labs/workforce-poc-board-notify/package.json | 28 ++ .../src/bootstrap.ts | 111 +++++ labs/workforce-poc-board-notify/src/flow.ts | 415 ++++++++++++++++++ labs/workforce-poc-board-notify/src/index.ts | 17 + labs/workforce-poc-board-notify/src/prune.ts | 20 + labs/workforce-poc-board-notify/src/run.ts | 77 ++++ .../test/lab-board-notify.spec.ts | 281 ++++++++++++ labs/workforce-poc-board-notify/tsconfig.json | 9 + .../vitest.config.ts | 8 + pnpm-lock.yaml | 71 +-- 12 files changed, 1089 insertions(+), 25 deletions(-) create mode 100644 labs/workforce-poc-board-notify/README.md create mode 100644 labs/workforce-poc-board-notify/package.json create mode 100644 labs/workforce-poc-board-notify/src/bootstrap.ts create mode 100644 labs/workforce-poc-board-notify/src/flow.ts create mode 100644 labs/workforce-poc-board-notify/src/index.ts create mode 100644 labs/workforce-poc-board-notify/src/prune.ts create mode 100644 labs/workforce-poc-board-notify/src/run.ts create mode 100644 labs/workforce-poc-board-notify/test/lab-board-notify.spec.ts create mode 100644 labs/workforce-poc-board-notify/tsconfig.json create mode 100644 labs/workforce-poc-board-notify/vitest.config.ts diff --git a/knip.json b/knip.json index d272b7664b..45dac6b9f1 100644 --- a/knip.json +++ b/knip.json @@ -54,6 +54,9 @@ "labs/conductor": { "entry": ["fsdev.config.ts", "test/**/*.spec.ts", "test/harness.ts"] }, + "labs/workforce-poc-board-notify": { + "entry": ["src/index.ts", "src/run.ts", "test/**/*.spec.ts"] + }, "plugins/flow-state-dev": { "entry": ["test/**/*.test.mjs", "skills/install-fsd/detect/detect.mjs"], "project": ["test/**/*.mjs", "skills/**/*.mjs"] diff --git a/labs/workforce-poc-board-notify/README.md b/labs/workforce-poc-board-notify/README.md new file mode 100644 index 0000000000..e4e692a0a9 --- /dev/null +++ b/labs/workforce-poc-board-notify/README.md @@ -0,0 +1,74 @@ +# Workforce POC — static board notify (FIX-1311) + +Throwaway lab. Proves a message-board **notify** path on today's APIs: a +topic-scoped collection, subscribers in collection state, `reactTo` fan-out +through a **router over declared dispatchers**. No Workforce package. No +TeamFlow / MessageBoard L1. No dynamic `dispatcher()` from string data. + +**Do not merge this as product API.** Findings go on +[`fsd/workforce/pocs`](https://github.com/fixpoint-labs/agent-mailbox/pull/12). + +## Run + +```bash +pnpm --filter @flow-state-dev/workforce-poc-board-notify test +pnpm --filter @flow-state-dev/workforce-poc-board-notify demo +``` + +## What was proved + +1. A board is a `defineResourceCollection({ pattern: "boards/*", scope: "user" })`. + Topic is the instance key. Subscribers live in instance state, including + documentary `flow` / `sessionId` / `entry` fields. +2. A new thread row fires `reactTo.stateUpdated`. The bound sequencer iterates + subscribers and dispatches fire-and-forget through `notify-alice` / + `notify-bob` — both declared at `defineFlow` time, both targeting + `internal.actions.onNotify`. +3. A stored `entry: "invented-from-data"` does **not** change the hop. The + fence is `packages/core/src/types/dispatch.ts`: + + > A target chosen from data is a router over declared dispatchers, not a + > dynamic address. + +4. Same-flow only. Another flow kind is `session-not-addressable` at + `packages/engine/src/context/create-request-host.ts:179`. This lab does + not invent a second bus. Cross-flow waits on #1600. +5. Existing-session create is still 409 (FIX-1246). Not papered over. +6. Prune on `no-entry` / `session-not-found` only. Never on + `dispatch-rejected` (poster subscribed to their own board — the in-flight + post holds the session, `onNotify` is `concurrency: "reject"`). Never on + `session-not-addressable` until that refusal is split. + +## What was faked with static targets + +Seats are a closed enum (`alice` | `bob`). A subscription **selects among** +those two declared dispatchers. Session id still comes from subscriber data +(`session: { id: (input) => input.sessionId }`) — that is today's existing +door, not a new address kind. A roster that names an arbitrary entry from +state still cannot become a dispatcher. + +`no-entry` is untestable as a runtime prune under static addresses: +`defineFlow` refuses a dispatcher whose target is missing. The classifier +covers it; the live hop cannot name a dangling entry. + +## What still needs substrate + +| Gap | Why this lab cannot close it | +|---|---| +| Dynamic addresses / addresses-as-data | A subscriber's `entry` is data. Using it as `dispatcher({ target })` is the thing the fence forbids. | +| Flow instances / multi-hire same-kind | FIX-1320–1323. One flow, two seats, session id distinguishes them. | +| Cross-flow conversation | #1600. `flowKind !== flow.kind` → `session-not-addressable`. | +| Housekeeper CAS on the brief | Two concurrent posts can each rewrite the brief. Needs the collection's version CAS — do not invent a store. Design-note only. | +| Teams / TeamFlow | FIX-1310. Out of scope. | + +## Brief / thread + +Cheap split: `brief` is a current-state string, `thread` is append-only. +`post` may set the brief in the same write. No housekeeper job. + +## What this is not + +- Not Lab A (factory / DM / group fan-out from a `post` sequencer). +- Not Lab B (claim / reply-storm). +- Not FIX-957 / `materializeAgent` / FIX-796. +- No changeset. Private lab. diff --git a/labs/workforce-poc-board-notify/package.json b/labs/workforce-poc-board-notify/package.json new file mode 100644 index 0000000000..fc64ec7668 --- /dev/null +++ b/labs/workforce-poc-board-notify/package.json @@ -0,0 +1,28 @@ +{ + "name": "@flow-state-dev/workforce-poc-board-notify", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "Throwaway Workforce POC: static board notify via reactTo over declared dispatchers. Never merges as product API.", + "main": "./src/index.ts", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "vitest run --root .", + "test:watch": "vitest --root .", + "demo": "tsx src/run.ts" + }, + "dependencies": { + "@flow-state-dev/core": "workspace:*", + "@flow-state-dev/engine": "workspace:*", + "zod": "^3.25.76" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "tsx": "^4.21.0", + "typescript": "^5.9.3", + "vitest": "^3.2.4" + } +} diff --git a/labs/workforce-poc-board-notify/src/bootstrap.ts b/labs/workforce-poc-board-notify/src/bootstrap.ts new file mode 100644 index 0000000000..b8ac44d57a --- /dev/null +++ b/labs/workforce-poc-board-notify/src/bootstrap.ts @@ -0,0 +1,111 @@ +/** + * Host-side bootstrap through today's `create_session` route. + * + * FIX-1246 is left as a 409 — this lab does not invent around an existing session. + */ +import type { FlowInstance } from "@flow-state-dev/core/types"; +import { + createFlowState, + inMemoryStores, + runAction, + type FlowState, + type FlowStateRuntime +} from "@flow-state-dev/engine"; +import { boardNotifyFlow, otherKindFlow } from "./flow"; + +export const USER_ID = "workforce-poc-board-notify-user"; + +export interface LabHost { + state: FlowState; + runtime: FlowStateRuntime; + flows: Record; + createSession: ( + flowKind: string, + sessionId: string, + title?: string + ) => Promise<{ id: string; flowKind: string; title?: string; status: number; error?: string }>; + call: ( + flowKind: string, + action: string, + input: unknown, + sessionId: string + ) => Promise<{ output: unknown; error?: { message?: string } }>; + sessionState: (sessionId: string) => Promise | undefined>; + dispose: () => Promise; +} + +export async function bootLab( + flows: Record = { + [boardNotifyFlow.kind]: boardNotifyFlow, + [otherKindFlow.kind]: otherKindFlow + } +): Promise { + const state = createFlowState({ + flows, + stores: { default: { primary: inMemoryStores() } } + }); + const runtime = await state.getRuntime(); + const router = await state.getRouter(); + + return { + state, + runtime, + flows, + async createSession(flowKind, sessionId, title) { + const response = await router.POST( + new Request(`http://localhost/api/flows/${encodeURIComponent(flowKind)}/sessions`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ userId: USER_ID, sessionId, title }) + }), + { params: { path: [flowKind, "sessions"] } } + ); + const text = await response.text(); + if (response.status !== 201) { + return { id: sessionId, flowKind, status: response.status, error: text }; + } + const body = JSON.parse(text) as { + session: { id: string; flowKind: string; title?: string }; + }; + return { ...body.session, status: 201 }; + }, + async call(flowKind, action, input, sessionId) { + const flow = flows[flowKind]; + if (flow === undefined) { + throw new Error(`no flow registered as "${flowKind}"`); + } + const result = await runAction({ + flow: flow as never, + actionName: action as never, + input: input as never, + userId: USER_ID, + sessionId, + stores: runtime.stores, + runtimeConfig: { ...runtime.runtimeConfig } + }); + const outcome = result as { + output?: unknown; + error?: { message?: string }; + }; + return { output: outcome.output, error: outcome.error }; + }, + async sessionState(sessionId) { + const record = await runtime.stores.session.get(sessionId); + return record?.state as Record | undefined; + }, + async dispose() { + await state.dispose(); + } + }; +} + +export async function until( + predicate: () => boolean | Promise, + label: string +): Promise { + for (let attempt = 0; attempt < 200; attempt += 1) { + if (await predicate()) return; + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error(`timed out waiting for ${label}`); +} diff --git a/labs/workforce-poc-board-notify/src/flow.ts b/labs/workforce-poc-board-notify/src/flow.ts new file mode 100644 index 0000000000..3ed7ee9a04 --- /dev/null +++ b/labs/workforce-poc-board-notify/src/flow.ts @@ -0,0 +1,415 @@ +/** + * Static board-notify lab — Workforce L2 composition, no MessageBoard L1. + * + * A topic-scoped collection holds subscribers as data (flow / session / entry). + * `reactTo` fans out through a **router over declared dispatchers**. The stored + * `entry` is documentary — it never becomes `dispatcher({ target: entry })`. + * + * Fence: `packages/core/src/types/dispatch.ts` — "A target chosen from data is + * a router over declared dispatchers, not a dynamic address." + */ +import { + DispatchRefusedError, + defineFlow, + defineResourceCollection, + dispatcher, + handler, + resourceChangeSchema, + router, + sequencer +} from "@flow-state-dev/core"; +import type { ResourceChange, ResourceCollectionRef } from "@flow-state-dev/core"; +import { z } from "zod"; +import { shouldPruneSubscription } from "./prune"; + +export const FLOW_KIND = "workforce-poc-board-notify"; +export const NOTIFY_ENTRY = "onNotify"; +export const DECLARED_SEATS = ["alice", "bob"] as const; + +export const seatSchema = z.enum(DECLARED_SEATS); +export type Seat = z.infer; + +export const subscriberSchema = z.object({ + seat: seatSchema, + sessionId: z.string(), + /** Documentary. Never resolved as a dispatch address. */ + flow: z.string(), + /** Documentary. Never passed to `dispatcher()`. */ + entry: z.string() +}); +export type Subscriber = z.infer; + +export const postSchema = z.object({ + id: z.string(), + body: z.string(), + fromSessionId: z.string() +}); + +export const boardStateSchema = z.object({ + brief: z.string().default(""), + thread: z.array(postSchema).default([]), + subscribers: z.array(subscriberSchema).default([]), + retired: z.boolean().default(false) +}); +export type BoardState = z.infer; + +export const sessionStateSchema = z.object({ + lastNotify: z + .object({ + topic: z.string(), + postId: z.string(), + body: z.string(), + fromSessionId: z.string(), + seat: seatSchema + }) + .nullable() + .default(null) +}); + +const wakeSchema = z.object({ + topic: z.string(), + seat: seatSchema, + sessionId: z.string(), + postId: z.string(), + body: z.string(), + fromSessionId: z.string() +}); +export type Wake = z.infer; + +const notifyPayloadSchema = wakeSchema.omit({ sessionId: true }); + +function wakesFrom(change: ResourceChange): Wake[] { + const state = change.state; + if (state == null) return []; + const last = state.thread[state.thread.length - 1]; + if (last === undefined) return []; + return state.subscribers.map((sub) => ({ + topic: change.key, + seat: sub.seat, + sessionId: sub.sessionId, + postId: last.id, + body: last.body, + fromSessionId: last.fromSessionId + })); +} + +export function threadGrew(change: ResourceChange): boolean { + if (change.state == null || change.state.retired) return false; + const prev = change.prevState?.thread.length ?? 0; + return change.state.thread.length > prev && change.state.subscribers.length > 0; +} + +const onNotify = handler({ + name: "on-notify", + inputSchema: notifyPayloadSchema, + outputSchema: z.object({ sessionId: z.string(), seat: seatSchema }), + sessionStateSchema, + execute: async (input, ctx) => { + await ctx.session.patchState({ + lastNotify: { + topic: input.topic, + postId: input.postId, + body: input.body, + fromSessionId: input.fromSessionId, + seat: input.seat + } + }); + return { sessionId: ctx.session.identity.id, seat: input.seat }; + } +}); + +function notifySeat(seat: Seat) { + return dispatcher({ + name: `notify-${seat}`, + type: "internal", + target: NOTIFY_ENTRY, + inputSchema: wakeSchema, + session: { id: (input) => input.sessionId }, + payload: (input) => ({ + topic: input.topic, + seat, + postId: input.postId, + body: input.body, + fromSessionId: input.fromSessionId + }) + }); +} + +/** Declared at defineFlow time. Selection is a router, not a constructed address. */ +export const notifyAlice = notifySeat("alice"); +export const notifyBob = notifySeat("bob"); + +const recordRefusal = handler({ + name: "record-notify-refusal", + inputSchema: z.any(), + outputSchema: z.object({ + ok: z.literal(false), + refused: z.string() + }), + execute: (err: unknown) => ({ + ok: false as const, + refused: err instanceof DispatchRefusedError ? err.refused : "dispatch-rejected" + }) +}); + +const notifyRouter = router({ + name: "notify-router", + inputSchema: wakeSchema, + routes: [notifyAlice, notifyBob], + execute: (input) => (input.seat === "alice" ? notifyAlice : notifyBob) +}).rescue([ + { + when: [DispatchRefusedError], + block: recordRefusal + } +]); + +const packNotifies = handler({ + name: "pack-notifies", + inputSchema: resourceChangeSchema(boardStateSchema), + outputSchema: z.object({ topic: z.string(), wakes: z.array(wakeSchema) }), + execute: (change: ResourceChange) => ({ + topic: change.key, + wakes: wakesFrom(change) + }) +}); + +const pruneDead = handler({ + name: "prune-dead", + inputSchema: z.array(z.unknown()), + outputSchema: z.object({ + topic: z.string(), + pruned: z.array(z.string()) + }), + execute: async (outcomes, ctx) => { + const change = ctx.sequencer?.input as ResourceChange | undefined; + const topic = change?.key ?? ""; + const wakes = change ? wakesFrom(change) : []; + const sessionIds = new Set(); + for (let i = 0; i < outcomes.length; i += 1) { + const refused = refusedOf(outcomes[i]); + const wake = wakes[i]; + if (refused !== undefined && shouldPruneSubscription(refused) && wake !== undefined) { + sessionIds.add(wake.sessionId); + } + } + if (sessionIds.size === 0 || topic.length === 0) { + return { topic, pruned: [] }; + } + const boards = ctx.resources.boards as unknown as ResourceCollectionRef; + const board = await boards.get(topic); + const next = board.state.subscribers.filter((sub) => !sessionIds.has(sub.sessionId)); + await board.patchState({ subscribers: next }); + return { topic, pruned: [...sessionIds] }; + } +}); + +function refusedOf(outcome: unknown): Parameters[0] | undefined { + if (outcome === null || typeof outcome !== "object" || !("refused" in outcome)) { + return undefined; + } + const refused = (outcome as { refused: unknown }).refused; + if (typeof refused !== "string") return undefined; + return refused as Parameters[0]; +} + +/** + * Bound on the collection and declared as an internal entry so `defineFlow` + * walks the two static dispatchers. reactTo is what actually runs it. + */ +export const notifyOnChange = sequencer({ + name: "notify-on-change", + inputSchema: resourceChangeSchema(boardStateSchema) +}) + .step(packNotifies) + .forEach((packed) => packed.wakes, notifyRouter, { + blocks: [notifyAlice, notifyBob] + }) + .step(pruneDead); + +export const boards = defineResourceCollection({ + scope: "user", + pattern: "boards/*", + flowIsolation: true, + writable: true, + stateSchema: boardStateSchema, + reactTo: { + stateUpdated: { + block: notifyOnChange, + when: threadGrew + } + } +}); + +const emptyBoard = (): BoardState => ({ + brief: "", + thread: [], + subscribers: [], + retired: false +}); + +async function boardOf(ctx: { resources: Record }, topic: string) { + const collection = ctx.resources.boards as unknown as ResourceCollectionRef; + return collection.getOrCreate(topic, emptyBoard()); +} + +const openBoard = handler({ + name: "open-board", + inputSchema: z.object({ topic: z.string() }), + outputSchema: z.object({ topic: z.string() }), + resources: { boards }, + execute: async (input, ctx) => { + await boardOf(ctx, input.topic); + return { topic: input.topic }; + } +}); + +const subscribe = handler({ + name: "subscribe", + inputSchema: z.object({ + topic: z.string(), + seat: seatSchema, + sessionId: z.string().optional(), + flow: z.string().optional(), + entry: z.string().optional() + }), + outputSchema: z.object({ + topic: z.string(), + subscribers: z.array(subscriberSchema) + }), + resources: { boards }, + execute: async (input, ctx) => { + const board = await boardOf(ctx, input.topic); + const record: Subscriber = { + seat: input.seat, + sessionId: input.sessionId ?? ctx.session.identity.id, + flow: input.flow ?? FLOW_KIND, + entry: input.entry ?? NOTIFY_ENTRY + }; + const current = board.state.subscribers; + const subscribers = current.some((s) => s.sessionId === record.sessionId && s.seat === record.seat) + ? current + : [...current, record]; + if (subscribers !== current) { + await board.patchState({ subscribers }); + } + return { topic: input.topic, subscribers }; + } +}); + +const unsubscribe = handler({ + name: "unsubscribe", + inputSchema: z.object({ topic: z.string(), sessionId: z.string().optional() }), + outputSchema: z.object({ topic: z.string(), subscribers: z.array(subscriberSchema) }), + resources: { boards }, + execute: async (input, ctx) => { + const board = await boardOf(ctx, input.topic); + const sessionId = input.sessionId ?? ctx.session.identity.id; + const subscribers = board.state.subscribers.filter((s) => s.sessionId !== sessionId); + await board.patchState({ subscribers }); + return { topic: input.topic, subscribers }; + } +}); + +const post = handler({ + name: "post", + inputSchema: z.object({ + topic: z.string(), + body: z.string(), + brief: z.string().optional() + }), + outputSchema: z.object({ + topic: z.string(), + postId: z.string(), + brief: z.string() + }), + resources: { boards }, + execute: async (input, ctx) => { + const board = await boardOf(ctx, input.topic); + if (board.state.retired) { + throw new Error(`board "${input.topic}" is retired`); + } + const postId = `post_${ctx.request.identity.id}`; + const fromSessionId = ctx.session.identity.id; + const brief = input.brief ?? board.state.brief; + await board.patchState({ + brief, + thread: [...board.state.thread, { id: postId, body: input.body, fromSessionId }] + }); + return { topic: input.topic, postId, brief }; + } +}); + +const retire = handler({ + name: "retire-board", + inputSchema: z.object({ topic: z.string() }), + outputSchema: z.object({ topic: z.string(), retired: z.literal(true) }), + resources: { boards }, + execute: async (input, ctx) => { + const board = await boardOf(ctx, input.topic); + await board.patchState({ retired: true }); + return { topic: input.topic, retired: true as const }; + } +}); + +const readBoard = handler({ + name: "read-board", + inputSchema: z.object({ topic: z.string() }), + outputSchema: z.object({ + topic: z.string(), + brief: z.string(), + thread: z.array(postSchema), + subscribers: z.array(subscriberSchema), + retired: z.boolean() + }), + resources: { boards }, + execute: async (input, ctx) => { + const board = await boardOf(ctx, input.topic); + return { + topic: input.topic, + brief: board.state.brief, + thread: board.state.thread, + subscribers: board.state.subscribers, + retired: board.state.retired + }; + } +}); + +export const boardNotifyFlow = defineFlow({ + kind: FLOW_KIND, + session: { stateSchema: sessionStateSchema }, + resources: { boards }, + actions: { + openBoard: { block: openBoard }, + subscribe: { block: subscribe }, + unsubscribe: { block: unsubscribe }, + post: { block: post }, + retire: { block: retire }, + read: { block: readBoard } + }, + internal: { + actions: { + [NOTIFY_ENTRY]: { + block: onNotify, + concurrency: "reject" + }, + notifyOnChange: { block: notifyOnChange } + } + } +})({ id: "default" }); + +/** Minimal other-kind flow so the lab can show today's cross-flow refuse. */ +export const otherKindFlow = defineFlow({ + kind: "other-kind", + actions: { + ping: { + block: handler({ + name: "ping", + inputSchema: z.object({}), + outputSchema: z.object({ ok: z.literal(true) }), + execute: () => ({ ok: true as const }) + }) + } + } +})({ id: "other" }); + diff --git a/labs/workforce-poc-board-notify/src/index.ts b/labs/workforce-poc-board-notify/src/index.ts new file mode 100644 index 0000000000..030df88f62 --- /dev/null +++ b/labs/workforce-poc-board-notify/src/index.ts @@ -0,0 +1,17 @@ +export { + FLOW_KIND, + NOTIFY_ENTRY, + DECLARED_SEATS, + boardNotifyFlow, + otherKindFlow, + boards, + notifyAlice, + notifyBob, + notifyOnChange, + threadGrew, + boardStateSchema, + sessionStateSchema, + subscriberSchema +} from "./flow"; +export { shouldPruneSubscription } from "./prune"; +export { bootLab, USER_ID, until, type LabHost } from "./bootstrap"; diff --git a/labs/workforce-poc-board-notify/src/prune.ts b/labs/workforce-poc-board-notify/src/prune.ts new file mode 100644 index 0000000000..9c1379efd4 --- /dev/null +++ b/labs/workforce-poc-board-notify/src/prune.ts @@ -0,0 +1,20 @@ +/** + * Subscription prune policy — FIX-1311 design note, lab-local. + * + * Prune a dead subscriber. Never prune a live one that was merely busy. + */ +import type { DispatchRefusal } from "@flow-state-dev/core"; + +const PRUNE_ON: ReadonlySet = new Set(["no-entry", "session-not-found"]); + +/** + * Whether a notify refusal means the subscriber is gone for good. + * + * `no-entry` — the handler is gone. `session-not-found` — the session is gone. + * Everything else is transient or a deployment/boundary shape, including + * `dispatch-rejected` (recipient busy) and `session-not-addressable` + * (still overloaded as "not this principal **or** not this flow"). + */ +export function shouldPruneSubscription(refused: DispatchRefusal): boolean { + return PRUNE_ON.has(refused); +} diff --git a/labs/workforce-poc-board-notify/src/run.ts b/labs/workforce-poc-board-notify/src/run.ts new file mode 100644 index 0000000000..fc81760d7c --- /dev/null +++ b/labs/workforce-poc-board-notify/src/run.ts @@ -0,0 +1,77 @@ +/** + * One-command demo of the static board-notify path. + * + * pnpm --filter @flow-state-dev/workforce-poc-board-notify demo + */ +import { boardNotifyFlow, FLOW_KIND } from "./flow"; +import { bootLab, until } from "./bootstrap"; + +const host = await bootLab(); +const topic = "standup"; + +try { + const poster = await host.createSession(FLOW_KIND, "poster", "poster"); + const alice = await host.createSession(FLOW_KIND, "alice", "alice"); + const bob = await host.createSession(FLOW_KIND, "bob", "bob"); + const replay = await host.createSession(FLOW_KIND, "poster", "poster"); + + await host.call(FLOW_KIND, "openBoard", { topic }, poster.id); + await host.call(FLOW_KIND, "subscribe", { topic, seat: "alice" }, alice.id); + await host.call( + FLOW_KIND, + "subscribe", + { topic, seat: "bob", entry: "invented-from-data" }, + bob.id + ); + await host.call( + FLOW_KIND, + "subscribe", + { topic, seat: "bob", sessionId: "ghost-gone" }, + poster.id + ); + + const posted = await host.call( + FLOW_KIND, + "post", + { topic, body: "standup in 10", brief: "daily standup" }, + poster.id + ); + if (posted.error) { + throw new Error(posted.error.message ?? "post failed"); + } + + await until(async () => { + const [a, b] = await Promise.all([ + host.sessionState(alice.id), + host.sessionState(bob.id) + ]); + return a?.lastNotify != null && b?.lastNotify != null; + }, "alice and bob to record onNotify"); + + const board = await host.call(FLOW_KIND, "read", { topic }, poster.id); + const wakes = { + alice: (await host.sessionState(alice.id))?.lastNotify, + bob: (await host.sessionState(bob.id))?.lastNotify, + poster: (await host.sessionState(poster.id))?.lastNotify ?? null + }; + + console.log( + JSON.stringify( + { + flow: boardNotifyFlow.kind, + staticTargets: { alice: "onNotify", bob: "onNotify" }, + existingSessionRefuse: { + status: replay.status, + paperedOver: false + }, + posted: posted.output, + wakes, + board: board.output + }, + null, + 2 + ) + ); +} finally { + await host.dispose(); +} diff --git a/labs/workforce-poc-board-notify/test/lab-board-notify.spec.ts b/labs/workforce-poc-board-notify/test/lab-board-notify.spec.ts new file mode 100644 index 0000000000..d367540020 --- /dev/null +++ b/labs/workforce-poc-board-notify/test/lab-board-notify.spec.ts @@ -0,0 +1,281 @@ +/** + * FIX-1311 static notify proof: post → reactTo → declared dispatcher → onNotify. + * + * These tests fail if notify invents a dynamic address, skips reactTo, or + * prunes a live subscriber on a transient refusal. + */ +import { describe, expect, it } from "vitest"; +import type { DispatchRefusal } from "@flow-state-dev/core"; +import { bootLab, until } from "../src/bootstrap"; +import { + DECLARED_SEATS, + FLOW_KIND, + NOTIFY_ENTRY, + boardNotifyFlow, + notifyAlice, + notifyBob +} from "../src/flow"; +import { shouldPruneSubscription } from "../src/prune"; + +const TOPIC = "standup"; + +async function openSubscribedBoard( + host: Awaited>, + opts?: { ghost?: boolean; posterAsAlice?: boolean; inventedEntry?: boolean } +) { + const poster = await host.createSession(FLOW_KIND, "poster", "poster"); + const alice = await host.createSession(FLOW_KIND, "alice", "alice"); + const bob = await host.createSession(FLOW_KIND, "bob", "bob"); + expect(poster.status).toBe(201); + expect(alice.status).toBe(201); + expect(bob.status).toBe(201); + + const opened = await host.call(FLOW_KIND, "openBoard", { topic: TOPIC }, poster.id); + expect(opened.error).toBeUndefined(); + + if (opts?.posterAsAlice) { + const sub = await host.call(FLOW_KIND, "subscribe", { topic: TOPIC, seat: "alice" }, poster.id); + expect(sub.error).toBeUndefined(); + } else { + const sub = await host.call(FLOW_KIND, "subscribe", { topic: TOPIC, seat: "alice" }, alice.id); + expect(sub.error).toBeUndefined(); + } + + const bobSub = await host.call( + FLOW_KIND, + "subscribe", + { + topic: TOPIC, + seat: "bob", + ...(opts?.inventedEntry ? { entry: "invented-from-data" } : {}) + }, + bob.id + ); + expect(bobSub.error).toBeUndefined(); + + if (opts?.ghost) { + const ghost = await host.call( + FLOW_KIND, + "subscribe", + { topic: TOPIC, seat: "bob", sessionId: "ghost-gone" }, + poster.id + ); + expect(ghost.error).toBeUndefined(); + } + + return { poster, alice, bob }; +} + +describe("lab — static board notify (FIX-1311)", () => { + it("declares two dispatchers, both targeting the same static onNotify entry", () => { + expect(DECLARED_SEATS).toEqual(["alice", "bob"]); + expect(notifyAlice.dispatch).toEqual({ type: "internal", target: NOTIFY_ENTRY }); + expect(notifyBob.dispatch).toEqual({ type: "internal", target: NOTIFY_ENTRY }); + expect(boardNotifyFlow.internal?.actions[NOTIFY_ENTRY]).toBeDefined(); + expect(boardNotifyFlow.internal?.actions.notifyOnChange).toBeDefined(); + }); + + it("prunes only no-entry and session-not-found — never dispatch-rejected", () => { + const prune: DispatchRefusal[] = ["no-entry", "session-not-found"]; + const keep: DispatchRefusal[] = [ + "dispatch-rejected", + "session-not-addressable", + "external-dispatcher", + "no-dispatch-operation", + "key-occupied", + "no-sender" + ]; + for (const refused of prune) { + expect(shouldPruneSubscription(refused)).toBe(true); + } + for (const refused of keep) { + expect(shouldPruneSubscription(refused)).toBe(false); + } + }); + + it("create_session of an existing id is 409 — FIX-1246 is not papered over", async () => { + const host = await bootLab(); + try { + const first = await host.createSession(FLOW_KIND, "same-room", "same-room"); + const again = await host.createSession(FLOW_KIND, "same-room", "same-room"); + expect(first.status).toBe(201); + expect(again.status).toBe(409); + expect(again.error).toMatch(/already exists/i); + } finally { + await host.dispose(); + } + }); + + it("post → reactTo → static notify lands on each subscriber's onNotify entry", async () => { + const host = await bootLab(); + try { + const { poster, alice, bob } = await openSubscribedBoard(host, { inventedEntry: true }); + + const posted = await host.call( + FLOW_KIND, + "post", + { topic: TOPIC, body: "standup in 10", brief: "daily standup" }, + poster.id + ); + expect(posted.error).toBeUndefined(); + expect(posted.output).toMatchObject({ topic: TOPIC, brief: "daily standup" }); + + await until(async () => { + const [a, b] = await Promise.all([ + host.sessionState(alice.id), + host.sessionState(bob.id) + ]); + return a?.lastNotify != null && b?.lastNotify != null; + }, "alice and bob lastNotify"); + + const aliceState = await host.sessionState(alice.id); + const bobState = await host.sessionState(bob.id); + expect(aliceState?.lastNotify).toMatchObject({ + topic: TOPIC, + body: "standup in 10", + fromSessionId: poster.id, + seat: "alice" + }); + expect(bobState?.lastNotify).toMatchObject({ + topic: TOPIC, + body: "standup in 10", + fromSessionId: poster.id, + seat: "bob" + }); + + const posterState = await host.sessionState(poster.id); + expect(posterState?.lastNotify ?? null).toBeNull(); + + const read = await host.call(FLOW_KIND, "read", { topic: TOPIC }, poster.id); + expect(read.error).toBeUndefined(); + expect(read.output).toMatchObject({ + topic: TOPIC, + brief: "daily standup", + retired: false + }); + const board = read.output as { subscribers: Array<{ entry: string; seat: string }> }; + expect(board.subscribers.some((s) => s.entry === "invented-from-data")).toBe(true); + } finally { + await host.dispose(); + } + }); + + it("subscribe alone does not notify — reactTo is gated on a new thread row", async () => { + const host = await bootLab(); + try { + const { alice } = await openSubscribedBoard(host); + const state = await host.sessionState(alice.id); + expect(state?.lastNotify ?? null).toBeNull(); + } finally { + await host.dispose(); + } + }); + + it("prunes session-not-found and keeps a live sibling", async () => { + const host = await bootLab(); + try { + const { poster, alice, bob } = await openSubscribedBoard(host, { ghost: true }); + + const posted = await host.call( + FLOW_KIND, + "post", + { topic: TOPIC, body: "ghost should drop" }, + poster.id + ); + expect(posted.error).toBeUndefined(); + + await until(async () => { + const [a, b] = await Promise.all([ + host.sessionState(alice.id), + host.sessionState(bob.id) + ]); + return a?.lastNotify != null && b?.lastNotify != null; + }, "live subscribers to wake"); + + await until(async () => { + const read = await host.call(FLOW_KIND, "read", { topic: TOPIC }, poster.id); + const board = read.output as { subscribers: Array<{ sessionId: string }> }; + return board.subscribers.every((s) => s.sessionId !== "ghost-gone"); + }, "ghost subscriber to prune"); + + const read = await host.call(FLOW_KIND, "read", { topic: TOPIC }, poster.id); + const board = read.output as { subscribers: Array<{ sessionId: string; seat: string }> }; + expect(board.subscribers.map((s) => s.sessionId).sort()).toEqual(["alice", "bob"]); + } finally { + await host.dispose(); + } + }); + + it("does not prune the poster when same-session notify is dispatch-rejected", async () => { + const host = await bootLab(); + try { + const { poster, bob } = await openSubscribedBoard(host, { posterAsAlice: true }); + + const posted = await host.call( + FLOW_KIND, + "post", + { topic: TOPIC, body: "poster is busy" }, + poster.id + ); + expect(posted.error).toBeUndefined(); + + await until(async () => { + const state = await host.sessionState(bob.id); + return state?.lastNotify != null; + }, "bob to wake"); + + const posterState = await host.sessionState(poster.id); + expect(posterState?.lastNotify ?? null).toBeNull(); + + const read = await host.call(FLOW_KIND, "read", { topic: TOPIC }, poster.id); + const board = read.output as { subscribers: Array<{ sessionId: string; seat: string }> }; + expect(board.subscribers).toEqual( + expect.arrayContaining([ + expect.objectContaining({ sessionId: poster.id, seat: "alice" }), + expect.objectContaining({ sessionId: bob.id, seat: "bob" }) + ]) + ); + } finally { + await host.dispose(); + } + }); + + it("does not prune session-not-addressable (cross-flow) — do not invent around #1600", async () => { + const host = await bootLab(); + try { + const { poster, alice } = await openSubscribedBoard(host); + const other = await host.createSession("other-kind", "editor-dm", "editor-dm"); + expect(other.status).toBe(201); + + const crossed = await host.call( + FLOW_KIND, + "subscribe", + { topic: TOPIC, seat: "bob", sessionId: other.id, flow: "other-kind" }, + poster.id + ); + expect(crossed.error).toBeUndefined(); + + const posted = await host.call( + FLOW_KIND, + "post", + { topic: TOPIC, body: "cross-flow stays subscribed" }, + poster.id + ); + expect(posted.error).toBeUndefined(); + + await until(async () => { + const state = await host.sessionState(alice.id); + return state?.lastNotify != null; + }, "alice to wake"); + + const read = await host.call(FLOW_KIND, "read", { topic: TOPIC }, poster.id); + const board = read.output as { subscribers: Array<{ sessionId: string }> }; + expect(board.subscribers.some((s) => s.sessionId === other.id)).toBe(true); + + const otherState = await host.sessionState(other.id); + expect(otherState?.lastNotify ?? null).toBeNull(); + } finally { + await host.dispose(); + } + }); +}); diff --git a/labs/workforce-poc-board-notify/tsconfig.json b/labs/workforce-poc-board-notify/tsconfig.json new file mode 100644 index 0000000000..83edb376dc --- /dev/null +++ b/labs/workforce-poc-board-notify/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "test/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/labs/workforce-poc-board-notify/vitest.config.ts b/labs/workforce-poc-board-notify/vitest.config.ts new file mode 100644 index 0000000000..d4fd144bbd --- /dev/null +++ b/labs/workforce-poc-board-notify/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["test/**/*.spec.ts"], + environment: "node" + } +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index acee4b916f..e0475a01ff 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -796,6 +796,31 @@ importers: specifier: ^5.9.3 version: 5.9.3 + labs/workforce-poc-board-notify: + dependencies: + '@flow-state-dev/core': + specifier: workspace:* + version: link:../../packages/core + '@flow-state-dev/engine': + specifier: workspace:* + version: link:../../packages/engine + zod: + specifier: ^3.25.76 + version: 3.25.76 + devDependencies: + '@types/node': + specifier: ^22.0.0 + version: 22.19.13 + tsx: + specifier: ^4.21.0 + version: 4.21.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/debug@4.1.12)(@types/node@22.19.13)(happy-dom@20.8.3)(jiti@2.7.0)(jsdom@27.4.0)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.9.0) + packages/bullmq: dependencies: '@flow-state-dev/core': @@ -7858,10 +7883,6 @@ packages: resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==} engines: {node: '>=6'} - expect-type@1.3.0: - resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} - engines: {node: '>=12.0.0'} - expect-type@1.4.0: resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} engines: {node: '>=12.0.0'} @@ -11387,10 +11408,6 @@ packages: tinyexec@0.3.2: resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} - tinyexec@1.0.2: - resolution: {integrity: sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==} - engines: {node: '>=18'} - tinyexec@1.3.0: resolution: {integrity: sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==} engines: {node: '>=18'} @@ -12392,7 +12409,7 @@ snapshots: '@antfu/install-pkg@1.1.0': dependencies: package-manager-detector: 1.6.0 - tinyexec: 1.0.2 + tinyexec: 1.3.0 '@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.234': optional: true @@ -16423,7 +16440,7 @@ snapshots: dependencies: '@types/estree': 1.0.8 estree-walker: 2.0.2 - picomatch: 4.0.4 + picomatch: 4.0.7 optionalDependencies: rollup: 4.57.1 @@ -17470,6 +17487,14 @@ snapshots: chai: 5.3.3 tinyrainbow: 2.0.0 + '@vitest/mocker@3.2.4(vite@7.3.1(@types/node@22.19.13)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.9.0))': + dependencies: + '@vitest/spy': 3.2.4 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 7.3.1(@types/node@22.19.13)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.9.0) + '@vitest/mocker@3.2.4(vite@7.3.1(@types/node@25.3.2)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.9.0))': dependencies: '@vitest/spy': 3.2.4 @@ -19237,8 +19262,6 @@ snapshots: expand-template@2.0.3: {} - expect-type@1.3.0: {} - expect-type@1.4.0: {} express-rate-limit@8.6.2(express@5.2.1): @@ -23623,8 +23646,6 @@ snapshots: tinyexec@0.3.2: {} - tinyexec@1.0.2: {} - tinyexec@1.3.0: {} tinyglobby@0.2.15: @@ -23893,7 +23914,7 @@ snapshots: dependencies: '@jridgewell/remapping': 2.3.5 acorn: 8.16.0 - picomatch: 4.0.4 + picomatch: 4.0.7 webpack-virtual-modules: 0.6.2 update-browserslist-db@1.2.3(browserslist@4.28.1): @@ -24088,7 +24109,7 @@ snapshots: dependencies: '@types/chai': 5.2.3 '@vitest/expect': 3.2.4 - '@vitest/mocker': 3.2.4(vite@7.3.1(@types/node@25.3.2)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.9.0)) + '@vitest/mocker': 3.2.4(vite@7.3.1(@types/node@22.19.13)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.9.0)) '@vitest/pretty-format': 3.2.4 '@vitest/runner': 3.2.4 '@vitest/snapshot': 3.2.4 @@ -24096,14 +24117,14 @@ snapshots: '@vitest/utils': 3.2.4 chai: 5.3.3 debug: 4.4.3 - expect-type: 1.3.0 + expect-type: 1.4.0 magic-string: 0.30.21 pathe: 2.0.3 - picomatch: 4.0.4 + picomatch: 4.0.7 std-env: 3.10.0 tinybench: 2.9.0 tinyexec: 0.3.2 - tinyglobby: 0.2.16 + tinyglobby: 0.2.17 tinypool: 1.1.1 tinyrainbow: 2.0.0 vite: 7.3.1(@types/node@22.19.13)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.9.0) @@ -24140,14 +24161,14 @@ snapshots: '@vitest/utils': 3.2.4 chai: 5.3.3 debug: 4.4.3 - expect-type: 1.3.0 + expect-type: 1.4.0 magic-string: 0.30.21 pathe: 2.0.3 - picomatch: 4.0.4 + picomatch: 4.0.7 std-env: 3.10.0 tinybench: 2.9.0 tinyexec: 0.3.2 - tinyglobby: 0.2.16 + tinyglobby: 0.2.17 tinypool: 1.1.1 tinyrainbow: 2.0.0 vite: 7.3.1(@types/node@25.3.2)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.9.0) @@ -24184,14 +24205,14 @@ snapshots: '@vitest/utils': 3.2.4 chai: 5.3.3 debug: 4.4.3 - expect-type: 1.3.0 + expect-type: 1.4.0 magic-string: 0.30.21 pathe: 2.0.3 - picomatch: 4.0.4 + picomatch: 4.0.7 std-env: 3.10.0 tinybench: 2.9.0 tinyexec: 0.3.2 - tinyglobby: 0.2.16 + tinyglobby: 0.2.17 tinypool: 1.1.1 tinyrainbow: 2.0.0 vite: 7.3.1(@types/node@25.3.2)(jiti@2.7.0)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.9.0) From 478986baa10e80f9a8a96badad3bfe2134d0ed01 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 7 Sep 2026 16:24:52 +0000 Subject: [PATCH 2/2] Fix notify prune by threading refusal onto declared-dispatcher outcomes. Same-session reactTo notify lands rather than reject; document that and keep prune on session-not-found only. Co-authored-by: Jake Hoffner --- labs/workforce-poc-board-notify/README.md | 11 ++- labs/workforce-poc-board-notify/src/flow.ts | 97 +++++++++++-------- .../test/lab-board-notify.spec.ts | 16 +-- 3 files changed, 73 insertions(+), 51 deletions(-) diff --git a/labs/workforce-poc-board-notify/README.md b/labs/workforce-poc-board-notify/README.md index e4e692a0a9..eacb64d088 100644 --- a/labs/workforce-poc-board-notify/README.md +++ b/labs/workforce-poc-board-notify/README.md @@ -35,9 +35,14 @@ pnpm --filter @flow-state-dev/workforce-poc-board-notify demo not invent a second bus. Cross-flow waits on #1600. 5. Existing-session create is still 409 (FIX-1246). Not papered over. 6. Prune on `no-entry` / `session-not-found` only. Never on - `dispatch-rejected` (poster subscribed to their own board — the in-flight - post holds the session, `onNotify` is `concurrency: "reject"`). Never on - `session-not-addressable` until that refusal is split. + `dispatch-rejected` (classifier; the live hop did not produce that + refusal — see below). Never on `session-not-addressable` until that + refusal is split. + +Same-session notify from `reactTo` **lands**. A poster who is also a +subscriber gets `onNotify` in their own session. `concurrency: "reject"` +on the entry does not treat the originating turn as a competing holder. +Do not read that as `dispatch-rejected`, and do not prune it. ## What was faked with static targets diff --git a/labs/workforce-poc-board-notify/src/flow.ts b/labs/workforce-poc-board-notify/src/flow.ts index 3ed7ee9a04..10e9b2359c 100644 --- a/labs/workforce-poc-board-notify/src/flow.ts +++ b/labs/workforce-poc-board-notify/src/flow.ts @@ -139,30 +139,60 @@ function notifySeat(seat: Seat) { export const notifyAlice = notifySeat("alice"); export const notifyBob = notifySeat("bob"); -const recordRefusal = handler({ - name: "record-notify-refusal", - inputSchema: z.any(), - outputSchema: z.object({ - ok: z.literal(false), - refused: z.string() - }), - execute: (err: unknown) => ({ - ok: false as const, - refused: err instanceof DispatchRefusedError ? err.refused : "dispatch-rejected" - }) +const notifyOutcomeSchema = z.object({ + ok: z.boolean(), + topic: z.string(), + seat: seatSchema, + sessionId: z.string(), + refused: z.string().nullable() }); +type NotifyOutcome = z.infer; const notifyRouter = router({ name: "notify-router", inputSchema: wakeSchema, routes: [notifyAlice, notifyBob], execute: (input) => (input.seat === "alice" ? notifyAlice : notifyBob) -}).rescue([ - { - when: [DispatchRefusedError], - block: recordRefusal - } -]); +}); + +/** + * Select a declared dispatcher for this wake. The factory closes over the + * subscriber identity so a refusal still names who to prune — it does not + * construct a dispatcher from `entry` data. `blocks` keeps both addresses + * on the `defineFlow` walk. + */ +function deliverWake(wake: Wake) { + return sequencer({ + name: `deliver-${wake.seat}`, + inputSchema: wakeSchema, + outputSchema: notifyOutcomeSchema + }) + .step(notifyRouter) + .map(() => ({ + ok: true as const, + topic: wake.topic, + seat: wake.seat, + sessionId: wake.sessionId, + refused: null + })) + .rescue([ + { + when: [DispatchRefusedError], + block: handler({ + name: `refuse-${wake.seat}`, + inputSchema: z.any(), + outputSchema: notifyOutcomeSchema, + execute: (err: unknown): NotifyOutcome => ({ + ok: false, + topic: wake.topic, + seat: wake.seat, + sessionId: wake.sessionId, + refused: err instanceof DispatchRefusedError ? err.refused : "dispatch-rejected" + }) + }) + } + ]); +} const packNotifies = handler({ name: "pack-notifies", @@ -176,43 +206,31 @@ const packNotifies = handler({ const pruneDead = handler({ name: "prune-dead", - inputSchema: z.array(z.unknown()), + inputSchema: z.array(notifyOutcomeSchema), outputSchema: z.object({ topic: z.string(), pruned: z.array(z.string()) }), execute: async (outcomes, ctx) => { - const change = ctx.sequencer?.input as ResourceChange | undefined; - const topic = change?.key ?? ""; - const wakes = change ? wakesFrom(change) : []; const sessionIds = new Set(); - for (let i = 0; i < outcomes.length; i += 1) { - const refused = refusedOf(outcomes[i]); - const wake = wakes[i]; - if (refused !== undefined && shouldPruneSubscription(refused) && wake !== undefined) { - sessionIds.add(wake.sessionId); + let topic = ""; + for (const outcome of outcomes) { + if (outcome.topic.length > 0) topic = outcome.topic; + if (outcome.refused !== null && shouldPruneSubscription(outcome.refused as Parameters[0])) { + sessionIds.add(outcome.sessionId); } } if (sessionIds.size === 0 || topic.length === 0) { return { topic, pruned: [] }; } - const boards = ctx.resources.boards as unknown as ResourceCollectionRef; - const board = await boards.get(topic); + const collection = ctx.resources.boards as unknown as ResourceCollectionRef; + const board = await collection.get(topic); const next = board.state.subscribers.filter((sub) => !sessionIds.has(sub.sessionId)); await board.patchState({ subscribers: next }); return { topic, pruned: [...sessionIds] }; } }); -function refusedOf(outcome: unknown): Parameters[0] | undefined { - if (outcome === null || typeof outcome !== "object" || !("refused" in outcome)) { - return undefined; - } - const refused = (outcome as { refused: unknown }).refused; - if (typeof refused !== "string") return undefined; - return refused as Parameters[0]; -} - /** * Bound on the collection and declared as an internal entry so `defineFlow` * walks the two static dispatchers. reactTo is what actually runs it. @@ -222,7 +240,7 @@ export const notifyOnChange = sequencer({ inputSchema: resourceChangeSchema(boardStateSchema) }) .step(packNotifies) - .forEach((packed) => packed.wakes, notifyRouter, { + .forEach((packed) => packed.wakes, deliverWake, { blocks: [notifyAlice, notifyBob] }) .step(pruneDead); @@ -390,8 +408,7 @@ export const boardNotifyFlow = defineFlow({ internal: { actions: { [NOTIFY_ENTRY]: { - block: onNotify, - concurrency: "reject" + block: onNotify }, notifyOnChange: { block: notifyOnChange } } diff --git a/labs/workforce-poc-board-notify/test/lab-board-notify.spec.ts b/labs/workforce-poc-board-notify/test/lab-board-notify.spec.ts index d367540020..3138310879 100644 --- a/labs/workforce-poc-board-notify/test/lab-board-notify.spec.ts +++ b/labs/workforce-poc-board-notify/test/lab-board-notify.spec.ts @@ -206,7 +206,7 @@ describe("lab — static board notify (FIX-1311)", () => { } }); - it("does not prune the poster when same-session notify is dispatch-rejected", async () => { + it("same-session notify from reactTo lands — and the poster stays subscribed", async () => { const host = await bootLab(); try { const { poster, bob } = await openSubscribedBoard(host, { posterAsAlice: true }); @@ -214,18 +214,18 @@ describe("lab — static board notify (FIX-1311)", () => { const posted = await host.call( FLOW_KIND, "post", - { topic: TOPIC, body: "poster is busy" }, + { topic: TOPIC, body: "poster is also a subscriber" }, poster.id ); expect(posted.error).toBeUndefined(); await until(async () => { - const state = await host.sessionState(bob.id); - return state?.lastNotify != null; - }, "bob to wake"); - - const posterState = await host.sessionState(poster.id); - expect(posterState?.lastNotify ?? null).toBeNull(); + const [p, b] = await Promise.all([ + host.sessionState(poster.id), + host.sessionState(bob.id) + ]); + return p?.lastNotify != null && b?.lastNotify != null; + }, "poster and bob to wake"); const read = await host.call(FLOW_KIND, "read", { topic: TOPIC }, poster.id); const board = read.output as { subscribers: Array<{ sessionId: string; seat: string }> };