diff --git a/.changeset/inventory-binder.md b/.changeset/inventory-binder.md new file mode 100644 index 0000000000..eb571a974a --- /dev/null +++ b/.changeset/inventory-binder.md @@ -0,0 +1,5 @@ +--- +"@flow-state-dev/workforce": patch +--- + +`openInventory` fills the live workforce inventory at boot: one row per hired seat, and one per open channel written by that channel itself from its own session state. `channelInstances({ inventory: true })` builds the built-in channel kind carrying the writer, and `inventoryWriterActions(kind)` puts the same two actions on a hand-rolled channel kind (FIX-1405). diff --git a/apps/docs/docs/workforce/capabilities-on-disk.md b/apps/docs/docs/workforce/capabilities-on-disk.md index 1b20beee74..844134cb57 100644 --- a/apps/docs/docs/workforce/capabilities-on-disk.md +++ b/apps/docs/docs/workforce/capabilities-on-disk.md @@ -1,6 +1,6 @@ --- title: Capabilities on disk -sidebar_position: 6 +sidebar_position: 7 sidebar_label: Capabilities on disk description: "Put a TypeScript capability in a team's resources/ folder, run one command, and let each worker's own file say which of its presets that worker wants." --- diff --git a/apps/docs/docs/workforce/documents-on-disk.md b/apps/docs/docs/workforce/documents-on-disk.md index 8bb92d7fb5..f9540c48f3 100644 --- a/apps/docs/docs/workforce/documents-on-disk.md +++ b/apps/docs/docs/workforce/documents-on-disk.md @@ -1,6 +1,6 @@ --- title: Documents on disk -sidebar_position: 5 +sidebar_position: 6 sidebar_label: Documents on disk description: "Write a team's shared documents as Markdown files, read the tree at startup, and install them as resources on a flow." --- diff --git a/apps/docs/docs/workforce/inventory.md b/apps/docs/docs/workforce/inventory.md new file mode 100644 index 0000000000..13bb7361d4 --- /dev/null +++ b/apps/docs/docs/workforce/inventory.md @@ -0,0 +1,259 @@ +--- +title: Live Inventory +sidebar_position: 5 +sidebar_label: Live Inventory +description: "What is actually open right now. The declared tree says what a workforce is meant to be; the inventory holds what is: one row per seat, one row per open channel, and one row per seat-in-channel." +--- + +# Live Inventory + +The tree tells you what a workforce is meant to be. A `WORKER.md` declares a seat. A `CHANNEL.md` declares a channel. Both are read once at boot. Neither answers what is open right now, which channels a seat is in, or whether a channel ever opened at all. A block cannot walk folders to find out. + +The inventory holds those answers as data: three org-scoped resource collections that a block reads the way it reads any other resource. + +| Collection | One row per | Key | +|------------|-------------|-----| +| Seats | registered seat | `inventory/seats/` | +| Channels | open channel | `inventory/channels/` | +| Memberships | seat-in-channel | `inventory/members//` | + +## When to use which source + +**Where the seat exists:** the tree (the `WORKER.md` folder). + +**Where the channel is declared:** the tree (the `CHANNEL.md` folder). + +**Which channels exist in this org right now:** the inventory. + +**Which seats is this channel open to:** the inventory's channel row, which holds `members`. + +**Which channels is this seat in:** the inventory's membership index. + +The two layers answer two different questions and join on one thing: the `id`. + +**Who may post to a channel:** the channel itself, checking its own session state. The `post` and `fileTask` blocks read `members` from the channel's session, not from the inventory. A caller asking whether a seat's post will be accepted asks the channel; the inventory's `members` is a copy for finding things, not the check. + +## Wiring the boot + +The inventory is written by actions that run inside flows, not by a standalone call. That means the rows are written at boot, after flows are registered and channels are open. + +```ts +import { + channelInstances, + hireWorkforce, + openChannels, + openInventory, +} from "@flow-state-dev/workforce"; + +const seats = hireWorkforce(roster.workers); +const instances = channelInstances(roster.channels, { inventory: true }); + +flowRegistry.registerMany([...seats, ...instances]); +// server starts here + +await openChannels(roster.channels, { + client: sessionClient, + userId: "u_boot", + orgId: "org_acme", +}); + +await openInventory( + { seats, channels: roster.channels }, + { + run, + seatWriter: { flowKind: "channel" }, + userId: "u_boot", + orgId: "org_acme", + } +); +``` + +The writer needs both halves: + +1. `channelInstances(roster.channels, { inventory: true })` builds the built-in kind carrying the registration actions and the three collections. +2. `openInventory(...)` runs those actions: once per channel, once for all seats. + +Leave both out and channels work without an inventory. Nothing is declared, nothing is written, and the three collection factories return collections whose keys resolve empty. + +### The action door + +`run` is your app's door into a flow. It takes the action request `openInventory` builds, runs it through your runtime, and rejects when the action fails: + +```ts +const run = async (request) => { + const result = await runAction({ + flow: byKind[request.flowKind], + actionName: request.action, + input: request.input, + userId: request.userId, + orgId: request.orgId, + sessionId: request.sessionId, + source: request.source, + stores: runtime.stores, + runtimeConfig: runtime.runtimeConfig, + }); + if (result?.error !== undefined) { + throw result.error instanceof Error ? result.error : new Error(String(result.error)); + } + return result; +}; +``` + +The rejection matters. A door that hands back a failed run as an ordinary value reports every channel registered while writing nothing. + +`source` matters too. The seat write is boot machinery, not something any caller can invoke — the request `openInventory` builds for it carries `source: "internal"`, and it only resolves when that reaches `runAction`. A door that drops it does not create a caller-reachable seat write; it makes the seat write fail closed, named in the result's `problems`. + +### Where the seat rows go + +Seat rows need a flow to run in, because a resource collection can only be written from inside a flow. Any flow carrying `inventoryWriterActions` will do. A channel kind built with `inventory: true` does, so `seatWriter: { flowKind: "channel" }` is the usual line. An app that has no channels, or whose channels run a kind of its own, names whichever flow carries the writer. + +## Reading the inventory + +Declare the same collections on any block. They return the same rows, because a collection is addressed by its pattern and scope, never by object identity. + +```ts +import { + defineChannelInventoryCollection, + defineMembershipIndexCollection, + defineSeatInventoryCollection, + membershipPrefix, +} from "@flow-state-dev/workforce"; +import { handler } from "@flow-state-dev/core"; +import { z } from "zod"; + +const seats = defineSeatInventoryCollection(); +const channels = defineChannelInventoryCollection(); +const memberships = defineMembershipIndexCollection(); + +const seatChannels = handler({ + name: "seat-channels", + inputSchema: z.object({ seatId: z.string() }), + outputSchema: z.object({ channelIds: z.array(z.string()) }), + resources: { memberships }, + execute: async (input, ctx) => { + const rows = await ctx.resources.memberships.list(membershipPrefix(input.seatId)); + return { channelIds: rows.map((row) => row.state.channelId) }; + }, +}); +``` + +`list()` hands back resource refs. The row is on `ref.state`. + +### What each row holds + +**Seat:** + +```ts +{ id: "engineering.lead", kind: "agent" } +``` + +**Channel:** + +```ts +{ + id: "engineering.standup", + kind: "channel", + members: ["engineering.lead", "engineering.analyst"], + openedAt: "2026-09-19T09:14:07.123Z" +} +``` + +**Membership:** + +```ts +{ seatId: "engineering.lead", channelId: "engineering.standup" } +``` + +`openedAt` is an ISO timestamp set the first time the channel registers and left alone after. `members` is what the channel's session holds, not what the roster declared. + +## Writing from your own kind + +A channel kind you wrote yourself gets rows when it carries the writer. `inventoryWriterActions(kind)` gives back its two blocks by action name — split them across `actions` and `internal.actions`, the way the built-in kind does. `registerChannelInInventory` is safe to leave public: it takes no input and derives its row from the channel's own already-open session state. `registerSeatsInInventory` is not — its whole input is the row data — so it belongs only in `internal.actions`, reachable solely by the trusted, direct `runAction({ source: "internal", ... })` call `openInventory` makes for it: + +```ts +import { defineFlow } from "@flow-state-dev/core"; +import { + channelSessionStateSchema, + inventoryWriterActions, +} from "@flow-state-dev/workforce"; + +const writer = inventoryWriterActions("briefing"); + +const briefingKind = defineFlow({ + kind: "briefing", + cardinality: "singleton", + session: { stateSchema: channelSessionStateSchema }, + actions: { + ...myActions, + registerChannelInInventory: writer.registerChannelInInventory, + }, + internal: { + actions: { registerSeatsInInventory: writer.registerSeatsInInventory }, + }, +}); +``` + +The string you pass `inventoryWriterActions` is the value that appears as `kind` on that channel's rows. Passing the wrong one is that kind's bug. + +A kind passed under `channelInstances`'s `kinds` option is yours to build. The `inventory: true` flag reaches the built-in only. + +## What is and is not written + +**What `openInventory` writes:** + +- One row per seat at `inventory/seats/`, carrying `{ id, kind }`. +- One row per channel at `inventory/channels/`, carrying `{ id, kind, members, openedAt }`. +- One row per member per channel at `inventory/members//`. + +**What the channel's `members` contains:** + +The seat ids its session holds, read by the channel itself. An edit to `members:` in a `CHANNEL.md` does not reach a channel that is already open, so it does not reach the row either. The inventory reports what the open channel holds, not what the file said when it was last read. + +**Running it twice:** + +Every write is an upsert keyed by the record's id. Running over the same roster writes the same rows. Nothing duplicates, and a channel that has been open since an earlier boot keeps its original `openedAt`. + +**Nothing is deleted:** + +A row stays where it is when a later roster no longer names the seat or the channel. There is no reconcile pass, no removal call. + +## What stops a write + +Both are wiring mistakes an app should fix at startup. + +**No `orgId`:** + +The inventory is org-scoped, so a write with no org lands where no flow can read it back. `openInventory` refuses and names what to pass. + +**Seats with no `seatWriter`:** + +A seat has no session of its own, so its row needs a flow to run in. `openInventory` refuses and names what to pass. + +## What lands in `problems` + +`openInventory` returns `{ seats, channels, problems }`. It collects failures rather than throwing, so one channel that cannot register is not an app with no inventory. + +A channel shows up in `problems` when: + +- Its session is not an open channel. +- Its kind declares no registration action. + +A seat write failure shows up once, naming every seat that could not be written. + +The rest of the roster is still attempted. Which of these is fatal is yours to decide. + +## Listing one seat's channels + +The membership index keys on the seat first, so a seat's channels are answerable by prefix. + +```ts +import { membershipPrefix } from "@flow-state-dev/workforce"; + +const rows = await ctx.resources.memberships.list(membershipPrefix(seatId)); +``` + +`membershipPrefix("engineering.lead")` is `"engineering.lead/"`. The trailing slash keeps `"engineering.lead"` from also matching `"engineering.leadership"`. + +**What the prefix does not buy:** + +Narrowing is not pushed into the store. The runtime fetches every membership row under the org before the prefix narrows it, so the cost grows with the org rather than with the seat. diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts index b701ab174a..d2576fb29a 100644 --- a/apps/docs/sidebars.ts +++ b/apps/docs/sidebars.ts @@ -232,6 +232,7 @@ const sidebars: SidebarsConfig = { "workforce/workers-on-disk", "workforce/built-in-worker", "workforce/channels", + "workforce/inventory", "workforce/documents-on-disk", "workforce/capabilities-on-disk", ], diff --git a/packages/workforce/README.md b/packages/workforce/README.md index e046387845..c68920602f 100644 --- a/packages/workforce/README.md +++ b/packages/workforce/README.md @@ -1069,53 +1069,135 @@ The inventory holds those answers as data: three org-scoped resource collections one row per open channel, and one row per seat-in-channel. They are ordinary collections, so a block reads them the way it reads any other resource. -**Nothing in the framework writes these rows yet.** Install the collections and your app is their -only writer. - | Factory | One row per | Fields | |---------|-------------|--------| | `defineSeatInventoryCollection()` | registered seat, at `inventory/seats/` | `id`, `kind` (the worker kind the seat was hired into) | | `defineChannelInventoryCollection()` | open channel, at `inventory/channels/` | `id`, `kind` (the channel kind that opened it), `members` (seat ids, `[]` when absent), `openedAt` (ISO string, or `null` when absent) | | `defineMembershipIndexCollection()` | seat-in-channel, at `inventory/members//` | `seatId`, `channelId` | +### Writing the inventory at boot + +The rows are written by `openInventory`, which runs after `openChannels`: + +```ts +import { + channelInstances, + hireWorkforce, + openChannels, + openInventory, +} from "@flow-state-dev/workforce"; + +const seats = hireWorkforce(roster.workers); +const instances = channelInstances(roster.channels, { inventory: true }); + +flowRegistry.registerMany([...seats, ...instances]); +// server starts here + +await openChannels(roster.channels, { client, userId: "u_boot", orgId: "org_acme" }); + +await openInventory( + { seats, channels: roster.channels }, + { + run, + seatWriter: { flowKind: "channel" }, + userId: "u_boot", + orgId: "org_acme", + } +); +``` + +The writer needs both halves. `channelInstances(roster.channels, { inventory: true })` builds the +built-in channel kind carrying the registration actions and the three collections. +`openInventory(...)` runs those actions: once per channel, once for all seats. + +Leave both out and channels work without an inventory. Nothing is declared, nothing is written. + +**What `openInventory` writes:** + +- One row per seat at `inventory/seats/`, carrying `{ id, kind }`. +- One row per channel at `inventory/channels/`, carrying `{ id, kind, members, openedAt }`. +- One row per member per channel at `inventory/members//`. + +**The `run` door.** `run` is your app's door into a flow: it takes the request `openInventory` +builds, runs it through your runtime, and rejects when the action fails. A door that hands back a +failed run as an ordinary value reports every channel registered while writing nothing. **It must +also forward `request.source` into `runAction`'s own `source` option** — +`runAction({ ..., source: request.source })` — because the seat write sets `source: "internal"` on +its request and needs that value carried through. A door that drops it does not become insecure, it +becomes unable to write seats at all: the seat write shows up named in `problems` instead. + +**Where the seat rows go.** Seat rows need a flow to run in, because a resource collection can only +be written from inside a flow. `seatWriter: { flowKind: "channel" }` names the built-in, which +carries the writer when built with `inventory: true`. Any flow that spreads `inventoryWriterActions` +will do. + +**`registerSeatsInInventory` is boot machinery, not a caller-addressed action.** Unlike channel +registration, which is public because its empty input and the channel's own already-open session +state make it harmless from any caller, the seat write has no session to derive from — its whole +input IS the row data. It lives only in the flow's `internal.actions` map, which a caller-addressed +HTTP or MCP request can never resolve into (`resolveEntry` reads one map per dispatch type with no +fallback); the only way in is the trusted, direct `runAction({ source: "internal", ... })` call +`openInventory`'s own request makes. A hand-rolled kind that spreads `inventoryWriterActions(kind)` +must make the same split itself — see that function's own doc comment for the shape. + +**What the channel rows hold.** `members` is the seat ids the channel's session holds, read by the +channel itself. An edit to `members:` in a `CHANNEL.md` does not reach a channel that is already +open, so it does not reach the row either. The `post` and `fileTask` blocks check membership against +the channel's session state, not the inventory; the row is a copy for finding things, not the check. + +**Running it twice.** Every write is an upsert keyed by the record's id. Nothing duplicates, and a +channel that has been open since an earlier boot keeps its original `openedAt`. + +**Nothing is deleted.** A row stays where it is when a later roster no longer names the seat or +channel. + +**What lands in `problems`.** `openInventory` returns `{ seats, channels, problems }`. A channel +whose session is not open, or whose kind declares no registration action, is named in `problems` and +the rest of the roster is still attempted. + +### Custom channel kinds + +A channel kind you wrote yourself gets rows when it spreads `inventoryWriterActions` into its +`actions`. The string it passes is the value that appears as `kind` on that channel's rows. + +```ts +defineFlow({ + kind: "briefing", + cardinality: "singleton", + session: { stateSchema: channelSessionStateSchema }, + actions: { ...myActions, ...inventoryWriterActions("briefing") }, +}); +``` + +A kind passed under `channelInstances`'s `kinds` option is yours to build. The `inventory: true` +flag reaches the built-in only. + +### Reading the inventory + Each factory takes no options. Install what it returns under any block's `resources` map: ```ts -import { handler } from "@flow-state-dev/core"; import { defineChannelInventoryCollection, defineMembershipIndexCollection, defineSeatInventoryCollection, - membershipKey, + membershipPrefix, } from "@flow-state-dev/workforce"; +import { handler } from "@flow-state-dev/core"; import { z } from "zod"; const seats = defineSeatInventoryCollection(); const channels = defineChannelInventoryCollection(); const memberships = defineMembershipIndexCollection(); -const recordChannelOpened = handler({ - name: "record-channel-opened", - inputSchema: z.object({ channelId: z.string(), members: z.array(z.string()) }), - outputSchema: z.object({ memberCount: z.number() }), - resources: { seats, channels, memberships }, +const seatChannels = handler({ + name: "seat-channels", + inputSchema: z.object({ seatId: z.string() }), + outputSchema: z.object({ channelIds: z.array(z.string()) }), + resources: { memberships }, execute: async (input, ctx) => { - await ctx.resources.channels.upsert(input.channelId, { - id: input.channelId, - kind: "channel", - members: input.members, - openedAt: new Date().toISOString(), - }); - - for (const seatId of input.members) { - await ctx.resources.seats.upsert(seatId, { id: seatId, kind: "agent" }); - await ctx.resources.memberships.upsert(membershipKey(seatId, input.channelId), { - seatId, - channelId: input.channelId, - }); - } - - return { memberCount: input.members.length }; + const rows = await ctx.resources.memberships.list(membershipPrefix(input.seatId)); + return { channelIds: rows.map((row) => row.state.channelId) }; }, }); ``` @@ -1123,7 +1205,7 @@ const recordChannelOpened = handler({ Keys are relative to each collection's own prefix, so `upsert("engineering.lead", row)` on the seat inventory lands at `inventory/seats/engineering.lead`. `list()` hands back resource refs, and the row itself is on `ref.state`. The membership index takes a two-segment key, which is what `membershipKey` -builds above; the next section covers it. +builds; the next section covers it. A row joins back to the declared record on the id and nothing else. The `id` on a seat row is the `id` the `WORKER.md` folder minted, and the `id` on a channel row is the `"."` @@ -1217,7 +1299,7 @@ membershipPrefix(""); | `SeatCapabilitySelection` | What a worker file's `capabilities:` key parses to — capability name to the presets that seat wants. Read by the built-in `agent` kind; validated at the hire. | | `defineChannelFlow(options?)` | Build a channel kind. `options.notify` is the per-member fan-out block. | | `channelFlow` | The built-in channel kind, seeded by `channelInstances` when you register none. | -| `channelInstances(manifests, { kinds? })` | Build time. One `FlowInstance` per distinct kind across the roster, the built-in seeded. Register these. | +| `channelInstances(manifests, { kinds?, inventory? })` | Build time. One `FlowInstance` per distinct kind across the roster, the built-in seeded. Pass `inventory: true` to install the registration actions and the three inventory collections on the built-in channel kind. Register these. | | `openChannels(manifests, { client, userId, orgId? })` | Runtime. One named session per record, carrying its members, charter and description, opened under `orgId` when one is given. Idempotent. | | `readChannelsDirectory(root)` | Read a `teams//channels//` tree into one `ChannelManifest` per channel. Ships from the `./loader` subpath (Node only). | | `ChannelManifest` | One channel record: `{ id, declared, body }`. | @@ -1237,6 +1319,13 @@ membershipPrefix(""); | `membershipPrefix(seatId)` | The prefix that lists one seat's memberships, trailing slash included, relative to the collection's prefix. Refuses the same ids `membershipKey` does. | | `SeatInventoryRow` / `ChannelInventoryRow` / `MembershipIndexRow` | One row of each of the three collections. | | `seatInventoryRowSchema` / `channelInventoryRowSchema` / `membershipIndexRowSchema` | The Zod schema behind each row type. Closed: an undeclared key is dropped on the way in. | +| `openInventory(roster, options)` | Write the inventory at boot: one row per seat, one row per channel, one row per membership. Takes `InventoryRoster` (the seats and channels to register) and `OpenInventoryOptions` (the `run` door, `seatWriter`, `userId`, `orgId`). Returns `{ seats, channels, problems }`. | +| `inventoryWriterActions(kind)` | The two blocks a custom channel kind installs to get inventory rows, keyed by action name. Split them: `registerChannelInInventory` into `actions` (public, safe — empty input), `registerSeatsInInventory` into `internal.actions` (its input is the row data, with nothing to check it against). The string is the `kind` value those rows carry. | +| `INVENTORY_REGISTER_CHANNEL` / `INVENTORY_REGISTER_SEATS` | The action names the writer runs: `"registerChannelInInventory"` and `"registerSeatsInInventory"`. | +| `INVENTORY_SEAT_WRITER_SESSION` | The session id the seat-registration action runs under when `seatWriter` names none: `"inventory-binder"`. | +| `InventoryRoster` / `InventorySeat` / `InventorySeatWriter` | What `openInventory` takes: the roster (`{ seats, channels }`), one seat (`{ id, kind }`), and which flow writes the seat rows (`{ flowKind }`). | +| `InventoryActionRequest` / `InventoryBinding` | What the `run` door receives (`{ action, input, userId, orgId, flowKind, sessionId, source? }` — `source` is `"internal"` on the seat request and must reach `runAction`), and what one boot of `openInventory` returns (`{ seats, channels, problems }`). | +| `OpenInventoryOptions` | The options `openInventory` takes: `run`, `seatWriter`, `userId`, `orgId`. | ## Error Semantics @@ -1274,6 +1363,9 @@ membershipPrefix(""); | `author-not-a-member` | A `post` claiming an `author` outside the channel's declared members. Per-request; nothing is written | | `external-dispatcher` | A flow-to-flow post on a host whose dispatcher hands work to an external queue. The public action route is unaffected | | Inventory id is not one path segment | `membershipKey` and `membershipPrefix` throw, naming the offending argument: an empty id, one containing `/` or `\`, or `.` and `..` | +| Inventory write with no org | `openInventory` throws before writing anything — the three collections are org-scoped | +| Seat inventory write with no seatWriter | `openInventory` throws when passed seats and no `seatWriter` — a seat has no session of its own, so its row needs a flow to run in | +| Channel or seat registration failed | Collected in `openInventory`'s `problems`: a channel whose session is not open, whose kind declares no registration action, or whose action failed; a seat write that failed. The rest of the roster is still attempted | ## Scripts diff --git a/packages/workforce/src/channel/channel-binder.ts b/packages/workforce/src/channel/channel-binder.ts index 783b8541b1..c2f61a0a22 100644 --- a/packages/workforce/src/channel/channel-binder.ts +++ b/packages/workforce/src/channel/channel-binder.ts @@ -39,6 +39,7 @@ import { CHANNEL_KIND, boundChannel, channelFlow, + defineChannelFlow, holdsBoards, type ChannelSessionState } from "./channel-flow"; @@ -90,6 +91,23 @@ export interface ChannelInstancesOptions { * the built-in. */ kinds?: Record; + + /** + * Build the **built-in** kind carrying the live inventory's writer half, so + * every channel it opens can publish its own row. + * + * Off by default: with this absent nothing is declared and nothing is + * written, and channels behave exactly as they did before the inventory + * existed. Turning it on here is half the wiring — `openInventory` is what + * actually runs the write, after `openChannels`. + * + * It reaches the built-in only. A kind passed under `kinds` is the caller's + * to build, and it carries the writer by spreading + * `inventoryWriterActions(itsOwnKindName)` into its own actions — the same + * way it already carries `cardinality: "singleton"`. There is nowhere to hand + * this to one: a custom kind is zero-arg by contract. + */ + inventory?: boolean; } export interface OpenChannelsOptions { @@ -191,8 +209,28 @@ function isAlreadyOpen(error: unknown): boolean { ); } -/** Records ordered by id, so one run's refusals read in a stable order. */ -function orderedById(records: readonly T[]): T[] { +/** + * The built-in kind holding the inventory writer, built at most once. + * + * Memoised rather than rebuilt per call for the same reason the board ledgers + * are: a kind is a declaration, and two declarations of one kind in one process + * are two objects the registry would have to tell apart. Lazy rather than a + * module-level `const`, so an app that never turns the inventory on never + * builds it. + */ +let inventoryChannelFlowMemo: ReturnType | undefined; +function inventoryChannelFlow(): ReturnType { + inventoryChannelFlowMemo ??= defineChannelFlow({ inventory: true }); + return inventoryChannelFlowMemo; +} + +/** + * Records ordered by id, so one run's refusals read in a stable order. + * + * Exported for the inventory binder, which walks the same records and owes the + * same stable order. Not re-exported from the package root. + */ +export function orderedById(records: readonly T[]): T[] { return [...records].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); } @@ -202,8 +240,14 @@ function orderedById(records: readonly T[]): T[] { * An omitted key selects the built-in — decision 1, and the reason the first * file in `channels/` carries no `flow:` line. A key that IS present and names * nothing registered is a misconfiguration and says so; it never falls back. + * + * Exported for the inventory binder, which addresses each channel's session on + * the kind that opened it and must read the record the same way `openChannels` + * did. A second derivation is a second answer to "which flow is this channel + * on", and the two would diverge silently. Not re-exported from the package + * root. */ -function kindOf(declared: Record): { kind: string } | { problem: string } { +export function kindOf(declared: Record): { kind: string } | { problem: string } { if (!Object.hasOwn(declared, "flow")) return { kind: CHANNEL_KIND }; const named = declared.flow; if (typeof named !== "string" || named.trim().length === 0) { @@ -408,9 +452,15 @@ export function channelInstances( options: ChannelInstancesOptions = {} ): FlowInstance[] { // The seed: the built-in fills the map only where the caller left the key - // free, so `kinds: { channel: mine }` replaces it wholesale. + // free, so `kinds: { channel: mine }` replaces it wholesale. With the + // inventory asked for, the seed is the same built-in rebuilt holding the + // writer — a second factory rather than a flag read at run time, because the + // collections have to be DECLARED on the flow and a declaration cannot be + // made per request. const kinds: Record = { - [CHANNEL_KIND]: channelFlow as unknown as ChannelKind, + [CHANNEL_KIND]: (options.inventory === true + ? inventoryChannelFlow() + : channelFlow) as unknown as ChannelKind, ...(options.kinds ?? {}) }; const available = Object.keys(kinds) diff --git a/packages/workforce/src/channel/channel-flow.ts b/packages/workforce/src/channel/channel-flow.ts index 021175dcd4..62b405c4cd 100644 --- a/packages/workforce/src/channel/channel-flow.ts +++ b/packages/workforce/src/channel/channel-flow.ts @@ -31,6 +31,13 @@ import { channelBoardNamesFor, resolveChannelBoard } from "./channel-board"; +import { + defineChannelInventoryCollection, + defineMembershipIndexCollection, + defineSeatInventoryCollection, + membershipKey, + seatInventoryRowSchema +} from "../inventory/collections"; /** The built-in kind's name, and so the built-in instance's address. */ export const CHANNEL_KIND = "channel"; @@ -585,6 +592,229 @@ const noteHandOffRefusal = handler({ }) }); +// --------------------------------------------------------------------------- +// The live inventory's writer half +// --------------------------------------------------------------------------- + +/** + * The action the boot binder dispatches into each open channel's OWN session, + * so the channel writes its own row. + * + * **Pinned.** `openInventory` names this string, and a channel kind a caller + * hand-rolled must declare an action under it — the same way it must declare + * `cardinality: "singleton"`. A kind that does not is a per-channel failure the + * binder names, never a channel silently missing from the inventory. + */ +export const INVENTORY_REGISTER_CHANNEL = "registerChannelInInventory"; + +/** + * The action the boot binder dispatches ONCE, carrying the roster's seats. + * + * **Pinned**, for the same reason. One run for the whole roster rather than one + * per seat: a seat holds no session, so there is no per-seat place this has to + * land, and the rows are a straight copy of what the binder already holds. + * + * Lives in `internal.actions`, never the public map — its whole input is the + * row data, with nothing to check it against. Reachable only by the binder's + * own direct, trusted `runAction({ source: "internal", ... })` call. + */ +export const INVENTORY_REGISTER_SEATS = "registerSeatsInInventory"; + +/** Nothing a caller supplies reaches the channel's row. */ +const registerChannelInputSchema = z.object({}).strict(); + +/** What a registration reports back: the row it wrote, so a caller can read it without a second read. */ +export const inventoryChannelRegisteredSchema = z.object({ + id: z.string(), + kind: z.string(), + members: z.array(z.string()) +}); + +/** The roster's seats, as the binder holds them. */ +const registerSeatsInputSchema = z + .object({ seats: z.array(seatInventoryRowSchema) }) + .strict(); + +/** What the seat write reports: how many rows landed. */ +export const inventorySeatsRegisteredSchema = z.object({ written: z.number() }); + +/** + * The two blocks that write the live inventory, built for one channel kind. + * + * Built per kind rather than once, because a channel row records **which kind + * minted it** and a block cannot read its own flow's kind: `ctx.flow` is + * narrowed to the create-time config bag and carries no name. So the kind is + * closed over here, at the one place that also writes `kind:` onto the flow. + * + * Both blocks refuse an org-less request by name. The inventory is org-scoped + * storage, so without an org there is nothing to write in — and the resource + * registry would report the collection as unregistered, which sends a reader to + * check a registration that is fine. + * + * @param kind The kind name the flow declaring these actions was built with. + * `defineChannelFlow` passes its own; a hand-rolled kind passes the same + * string it passed `defineFlow({ kind })`, and a row carrying the wrong one + * is that kind's bug in the same way a mismatched `cardinality` is. + * @returns Both entries, keyed by their action name. The blocks declare the + * collections they touch, so installing an entry installs its collection + * too. **Split them across `actions` and `internal.actions` — do not spread + * the whole return into `actions`.** `registerSeats`'s whole input is + * caller-supplied row data with nothing to check it against, so a public + * caller could write fabricated seat rows; `registerChannel` has no such + * risk (empty input, derives its row from the channel's own session state), + * so it is the one safe to leave public. `defineChannelFlow`'s own built-in + * kind makes exactly this split — read it there for the mechanics. + * + * @example + * const writer = inventoryWriterActions("briefing"); + * defineFlow({ + * kind: "briefing", + * cardinality: "singleton", + * session: { stateSchema: briefingState }, + * actions: { ...myActions, registerChannelInInventory: writer.registerChannelInInventory }, + * internal: { + * actions: { registerSeatsInInventory: writer.registerSeatsInInventory } + * } + * }); + */ +export function inventoryWriterActions(kind: string) { + // Fresh per call. Two collections declared from one factory share storage — + // a collection is addressed by its pattern and scope, never by object + // identity — so this costs nothing and keeps the declaration local to the + // flow that installs it. + const channels = defineChannelInventoryCollection(); + const memberships = defineMembershipIndexCollection(); + const seats = defineSeatInventoryCollection(); + + const registerChannel = handler({ + name: "channel-register-in-inventory", + inputSchema: registerChannelInputSchema, + outputSchema: inventoryChannelRegisteredSchema, + resources: { channels, memberships }, + execute: async (_input, ctx) => { + const channel = boundChannel(ctx.session.state); + if (channel === undefined) { + throw new ChannelPostRefusedError( + "channel-not-bound", + `session "${ctx.session.identity.id}" is not an open channel, so there is no ` + + `membership to publish. A channel's session is opened by \`openChannels\`, and the ` + + `inventory binder runs after it.` + ); + } + if (ctx.org === undefined) { + throw new Error( + `channel "${ctx.session.identity.id}" cannot register in the inventory: it is open ` + + `without an organization, and the inventory is org-scoped storage. Open the channel ` + + `with an \`orgId\` and it registers.` + ); + } + + const id = ctx.session.identity.id; + // The channel's OWN session state, and nothing else. The binder carries + // no members, deliberately: a roster's `members:` is what a file said + // when it was last read, and an edit to it never reaches a session that + // is already open. Copying it here would republish that file-time answer + // under a live name. + const members = [...channel.members]; + + // Every member's key is built up front, before anything is written. + // `membershipKey` throws on a member id that can never be one — and + // that failure is permanent, not flaky, so it must not land after some + // rows are already committed: a caller that retries a boot gets the + // same throw on the same member every time, and a run that had already + // written part of itself before hitting it would keep re-adding to a + // half-written state instead of leaving nothing behind. + const membershipKeys = members.map((seatId) => membershipKey(seatId, id)); + + // The membership rows go FIRST, and the channel row that names them + // goes last. Neither write is transactional with the other — a store + // failure partway through the loop below still leaves whatever landed + // before it — so the ordering is what stops the channel row from ever + // claiming a member the index does not have: the row is only written + // once every membership row it will name already exists. What it does + // not buy: a membership row from an EARLIER successful run can still + // outlive this run's channel row if this run's own loop fails partway + // through. That row is stale, not contradictory, and nothing here + // prunes stale rows in the first place (see `inventoryWriterActions`'s + // header). + for (let i = 0; i < members.length; i++) { + await ctx.resources.memberships.upsert(membershipKeys[i], { + seatId: members[i], + channelId: id + }); + } + + // `openedAt` is create-only, so a second boot does not restamp a channel + // that has been open since the first one. + await ctx.resources.channels.upsert( + id, + { id, kind, members }, + { openedAt: new Date().toISOString() } + ); + + return { id, kind, members }; + } + }); + + const registerSeats = handler({ + name: "inventory-register-seats", + inputSchema: registerSeatsInputSchema, + outputSchema: inventorySeatsRegisteredSchema, + resources: { seats }, + execute: async (input, ctx) => { + if (ctx.org === undefined) { + throw new Error( + "the seat rows cannot be written: this request carries no organization, and the " + + "inventory is org-scoped storage. Run the seat write under the same `orgId` the " + + "channels were opened with." + ); + } + + const problems: string[] = []; + let written = 0; + for (const row of input.seats) { + try { + await ctx.resources.seats.upsert(row.id, row); + written += 1; + } catch (error) { + problems.push( + `seat "${row.id}" — ${error instanceof Error ? error.message : String(error)}` + ); + } + } + + // Every row is attempted before anything is reported: one seat the store + // refuses is not an org with no seat inventory. The throw is what carries + // the failure back out — a boot door hands back an action's return value + // in a shape this package cannot read, so a `problems` field on the + // output would reach nobody. + if (problems.length > 0) { + throw new Error( + `${problems.length} of ${input.seats.length} seat rows could not be written:\n - ` + + problems.join("\n - ") + ); + } + return { written }; + } + }); + + return { + [INVENTORY_REGISTER_CHANNEL]: { + block: registerChannel, + description: + "Publish this channel's row and its membership rows into the org's live inventory, " + + "from the channel's own session state. Boot machinery: takes no input, and re-running " + + "it writes the same rows." + }, + [INVENTORY_REGISTER_SEATS]: { + block: registerSeats, + description: + "Write the org's seat rows into the live inventory. Boot machinery, called once by " + + "`openInventory` with the roster it was hired from." + } + }; +} + export interface DefineChannelFlowOptions { /** * The fan-out slot: a block run once per declared member per post, outside @@ -618,6 +848,20 @@ export interface DefineChannelFlowOptions { * name unambiguously (a board name carries no dot). */ boards?: readonly string[]; + + /** + * Carry the live inventory's writer half — the two actions + * {@link inventoryWriterActions} builds, and the collections they write. + * + * Absent by default, and absent means absent: no collection is declared, no + * action exists, and a channel behaves exactly as it did before the inventory + * existed. An entry that is only there to do nothing is worse than none, + * which is how the fan-out slot beside it works too. + * + * Supplied by `channelInstances({ inventory: true })` for the built-in, so an + * app turns the inventory on at one call rather than by rebuilding the kind. + */ + inventory?: boolean; } /** @@ -673,6 +917,13 @@ export function defineChannelFlow(options: DefineChannelFlowOptions = {}): Chann const fileTask = boardIds.length === 0 ? undefined : fileTaskFor(boardIds); const readBoard = boardIds.length === 0 ? undefined : readBoardFor(boardIds); + // Built on the FACTORY, never behind a `kind === "channel"` test inside the + // block: what the inventory promises is that EVERY open channel has a row, + // and a kind check in there would make that false for every kind but this + // one. What decides whether the rows are written is whether the app asked. + const inventoryActions = + options.inventory === true ? inventoryWriterActions(CHANNEL_KIND) : undefined; + // Declared ONLY when a slot was supplied. With no slot there is nothing to // deliver, so there is no entry to declare and no dispatch to make — rather // than a declared entry that exists to do nothing. @@ -784,7 +1035,20 @@ export function defineChannelFlow(options: DefineChannelFlowOptions = {}): Chann block: readBoard, description: "Read the rows on one of this channel's boards." } - }) + }), + // `registerChannel` only. It takes a closed, empty input and derives the + // row entirely from `ctx.session.state` — the channel's own, + // already-open state — so a caller cannot make it write anything but + // that channel's true members, and calling it early or twice is + // harmless. Public because the door that reaches it is the app's own + // action client at boot, and an internal dispatch resolves from a + // different map. + // + // `registerSeats` is deliberately NOT here — see `internal.actions` + // below for why. + ...(inventoryActions === undefined + ? {} + : { [INVENTORY_REGISTER_CHANNEL]: inventoryActions[INVENTORY_REGISTER_CHANNEL] }) }, internal: { actions: { @@ -801,6 +1065,24 @@ export function defineChannelFlow(options: DefineChannelFlowOptions = {}): Chann ...(fileTask === undefined || readBoard === undefined ? {} : { fileTask: { block: fileTask }, readBoard: { block: readBoard } }), + // `registerSeats` lives ONLY here, never in the public `actions` map + // above. Unlike `registerChannel`, it has no session state to derive + // from — a seat has no session — so its whole input IS the row data, + // with nothing in this package to check it against. Public + // reachability would let any principal that can reach this flow write + // fabricated `{ id, kind }` pairs into the org's seat inventory. + // `internal.actions` resolves from its own map (`resolveEntry`, + // `@flow-state-dev/engine`) that a caller-addressed dispatch can never + // reach — `dispatchTypeOf` maps every caller-facing transport source + // to `public`, never to `internal` — so the only way in is a direct, + // trusted `runAction({ source: "internal", ... })` call, which is + // exactly what `openInventory`'s `run` door makes for this one + // request (see `open-inventory.ts`). A hand-rolled kind that spreads + // `inventoryWriterActions(kind)` must do the same split itself — see + // that function's own doc comment. + ...(inventoryActions === undefined + ? {} + : { [INVENTORY_REGISTER_SEATS]: inventoryActions[INVENTORY_REGISTER_SEATS] }), ...(fanOut === undefined ? {} : { diff --git a/packages/workforce/src/channel/index.ts b/packages/workforce/src/channel/index.ts index 9d84a2dd65..dc2401d48f 100644 --- a/packages/workforce/src/channel/index.ts +++ b/packages/workforce/src/channel/index.ts @@ -15,6 +15,11 @@ export { CHANNEL_KIND, ChannelPostRefusedError, + INVENTORY_REGISTER_CHANNEL, + INVENTORY_REGISTER_SEATS, + inventoryChannelRegisteredSchema, + inventorySeatsRegisteredSchema, + inventoryWriterActions, channelFileTaskInputSchema, channelFileTaskOutputSchema, channelFlow, diff --git a/packages/workforce/src/inventory/collections.ts b/packages/workforce/src/inventory/collections.ts index 1823a896d6..c94d1a677b 100644 --- a/packages/workforce/src/inventory/collections.ts +++ b/packages/workforce/src/inventory/collections.ts @@ -50,9 +50,9 @@ import { z } from "zod"; */ export const seatInventoryRowSchema = z.object({ /** The seat's id — the same id the declared record carries. The join key. */ - id: z.string(), + id: z.string().min(1), /** The flow kind this seat was hired into, e.g. the built-in `"agent"`. */ - kind: z.string(), + kind: z.string().min(1), }); /** One row of the seat inventory. @see seatInventoryRowSchema */ diff --git a/packages/workforce/src/inventory/index.ts b/packages/workforce/src/inventory/index.ts index c23b3a11aa..03db162f11 100644 --- a/packages/workforce/src/inventory/index.ts +++ b/packages/workforce/src/inventory/index.ts @@ -2,10 +2,22 @@ * The live inventory: org-scoped rows for what is actually open. * * `collections.ts` owns the explanation — what each collection answers, why - * there are three, and what the membership index's key shape buys. This file - * only re-exports. + * there are three, and what the membership index's key shape buys. + * `open-inventory.ts` owns the other half: who writes each row, and why the + * two writers are split the way they are. This file only re-exports. */ +export { + INVENTORY_SEAT_WRITER_SESSION, + openInventory, + type InventoryActionRequest, + type InventoryBinding, + type InventoryRoster, + type InventorySeat, + type InventorySeatWriter, + type OpenInventoryOptions +} from "./open-inventory"; + export { channelInventoryRowSchema, defineChannelInventoryCollection, diff --git a/packages/workforce/src/inventory/open-inventory.ts b/packages/workforce/src/inventory/open-inventory.ts new file mode 100644 index 0000000000..c832de1986 --- /dev/null +++ b/packages/workforce/src/inventory/open-inventory.ts @@ -0,0 +1,304 @@ +/** + * `openInventory` — the boot binder that fills the live inventory. + * + * It runs after `openChannels` and writes nothing itself. Everything the + * inventory holds is written from inside a flow, because a resource collection + * has no door outside one: the session routes carry session state, and the + * resource routes carry a collection item's *content*, not its state. So the + * binder's whole job is to run two actions in the right places and to name what + * failed. + * + * **Two writers, split by where the live answer lives.** + * + * A **seat** has no session. What it is — its id and the kind it was hired into + * — is the roster the process was hired from, which the binder already holds, + * so the seat rows go out in ONE run carrying all of them. + * + * A **channel** has a session, and its `members` live there and nowhere else. + * So the binder does not write a channel's row at all: it runs + * {@link INVENTORY_REGISTER_CHANNEL} inside that channel's own session and the + * channel writes its own row from its own state. **The binder carries no member + * data**, and that is the point rather than a detail. A roster's `members:` is + * what a file said when it was last read; an edit to it does not reach a + * channel that is already open, so a binder copying it forward would publish a + * file-time answer under a live name. What the row buys is that the two + * disagreeing becomes *visible* instead of silent. + * + * **Nothing is ever deleted.** A row means *was registered in this org*, not + * *still declared*. A roster handed to one boot may be a partial one, and a + * binder that reconciled against it would drop the row of a live channel + * another process opened. A reader tolerates a row naming something it cannot + * reach; there is no undoing a row that should not have been removed. + */ + +import { kindOf, orderedById } from "../channel/channel-binder"; +import { + INVENTORY_REGISTER_CHANNEL, + INVENTORY_REGISTER_SEATS +} from "../channel/channel-flow"; +import type { ChannelManifest } from "../manifest"; + +/** + * One registered seat, as the binder needs it. + * + * Structurally typed, and satisfied by `hireWorkforce`'s own return value: a + * hired seat is a flow copy carrying exactly these two fields. Typed this + * loosely on purpose — what belongs in the inventory is the seats that + * actually exist, and a manifest the hire step refused never became one. + */ +export interface InventorySeat { + /** The seat's id, `"."` — the id its row is keyed by. */ + id: string; + /** The flow kind it was hired into. */ + kind: string; +} + +/** What the binder registers: the seats that were hired, and the channels that were opened. */ +export interface InventoryRoster { + /** The registered seats. Pass `hireWorkforce(...)`'s result directly. */ + seats: readonly InventorySeat[]; + /** The channel records — the same ones `channelInstances` registered and `openChannels` opened. */ + channels: readonly ChannelManifest[]; +} + +/** One action the binder asks the app's door to run. */ +export interface InventoryActionRequest { + /** The action's name — one of the two pinned inventory action names. */ + action: string; + /** The action's input. Empty for a channel registration. */ + input: unknown; + /** The user every run is made as — the same one the channels were opened for. */ + userId: string; + /** The org the rows are written in. Always present: the binder refuses without one. */ + orgId: string; + /** The flow kind to run on: the channel's own kind, or the seat writer's. */ + flowKind: string; + /** The session to run in: the channel's id for a channel, the seat writer's session otherwise. */ + sessionId: string; + /** + * `"internal"` for the seat write, absent for a channel registration. + * + * The seat-registration action lives only in the flow's `internal.actions` + * map, not its public one (see `inventoryWriterActions` in + * `channel-flow.ts`), because its whole input is caller-supplied row data + * with nothing to validate it against. `run` must forward this straight + * into `runAction`'s own `source` option — `runAction({ source: + * request.source, ... })` — so the seat write resolves from `internal.actions` + * instead of the public one. A door that drops this field on the floor + * makes the seat write unreachable rather than insecure: `resolveEntry` + * reads one map per dispatch type with no fallback, so a `run` that always + * dispatches as `"http"` gets `no-entry` for the seat write, never a + * public hit on it. + */ + source?: string; +} + +/** Where the seat rows are written. @see OpenInventoryOptions.seatWriter */ +export interface InventorySeatWriter { + /** A flow kind carrying {@link INVENTORY_REGISTER_SEATS}. */ + flowKind: string; + /** The session to run the write in. Defaults to {@link INVENTORY_SEAT_WRITER_SESSION}. */ + sessionId?: string; +} + +/** + * The session the seat write runs in when the caller names none. + * + * An ordinary session on the writer's flow, created on the first boot and + * reused after. It never collides with a channel: a channel's id is + * `"."` and always carries a dot. + */ +export const INVENTORY_SEAT_WRITER_SESSION = "inventory-binder"; + +export interface OpenInventoryOptions { + /** + * The action door — one call per open channel, plus one for the seats. + * + * Structurally typed and supplied by the app, for the same reason + * `openChannels` takes its session client that way: this package depends on + * no client package. It is a one-liner over whatever the app already uses to + * run an action, and it has to be the app's because the shipped action client + * is bound to one `flowKind` when it is created while channels may be + * several: + * + * ```ts + * const run = (req) => + * createClient({ flowKind: req.flowKind, userId: req.userId }) + * .sendAction(req.action, req.input, { sessionId: req.sessionId, orgId: req.orgId }); + * ``` + * + * **It must reject when the action fails.** A door that hands back a failed + * run as an ordinary value reports every channel registered and writes + * nothing, and the binder has no other way to tell: an action's return value + * arrives in whatever shape that door gives it, so the rejection is the only + * signal this package can read. + */ + run: (request: InventoryActionRequest) => Promise; + + /** + * Where the SEAT rows are written. + * + * A seat has no session of its own, and a collection can only be written from + * inside a running flow — so the seat rows need a flow to run in, and the + * binder cannot derive one. Every channel kind built with `inventory: true` + * carries the writer, and so does any flow of the app's own that spreads + * `inventoryWriterActions`. Naming it is one line, and it is the single thing + * about this call that is not already decided by the roster. + * + * Required when the roster carries seats, and refused by name when it is + * missing. A roster with no seats does not need one. + */ + seatWriter?: InventorySeatWriter; + + /** The user every run is made as — the same one `openChannels` opened the channels for. */ + userId: string; + + /** + * The org the rows are written in, and the same one the channels were opened + * under. + * + * Optional in this type only because the boot options beside it are; a run + * without one is refused. The inventory is org-scoped storage, so a write + * with no org goes somewhere no flow in the app can read back — the failure + * is an inventory that reads empty everywhere, which points at nothing. + */ + orgId?: string; +} + +/** What one boot wrote, and what it could not. */ +export interface InventoryBinding { + /** How many seat rows were written. */ + seats: number; + /** How many channels registered themselves. */ + channels: number; + /** + * What failed, named, in roster order. Never thrown: one channel whose kind + * cannot register is not an app with no inventory, and the caller decides + * which of these is fatal. + */ + problems: string[]; +} + +function messageOf(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** + * Fill the org's live inventory: one row per hired seat, and one per open + * channel written by that channel itself. + * + * Run it after `openChannels` — a channel that is not open yet has no session + * to register in, and the failure is named rather than silent. The seat half + * does not care about the order. + * + * Re-running over an unchanged roster is a no-op: every write is an upsert + * keyed by the record's own id, so nothing duplicates and nothing appends. A + * channel that has been open since an earlier boot keeps its original + * `openedAt`. + * + * @param roster The hired seats and the opened channel records. + * @param options `run`: the action door. `seatWriter`: the flow the seat rows + * are written through. `userId` / `orgId`: who and where. + * @returns What was written, and one named entry per failure. Nothing is + * retried. + * @throws If no `orgId` was given, or if the roster carries seats and no + * `seatWriter` was named. Both are wiring mistakes an app should not boot + * past — a run that continued would report success and write where nobody + * can read. + */ +export async function openInventory( + roster: InventoryRoster, + options: OpenInventoryOptions +): Promise { + const seats = orderedById(roster.seats); + const channels = orderedById(roster.channels); + + // Refused here rather than left to surface per row, and for the same reason + // `openChannels` refuses an org-less roster that declares boards: an + // org-scoped write with no org lands where no flow in this app resolves it, + // so every read comes back empty and points at the reader. + const orgId = options.orgId; + if (orgId === undefined) { + throw new Error( + `openInventory was given no \`orgId\`, but the inventory is org-scoped storage: ` + + `${seats.length} seat${seats.length === 1 ? "" : "s"} and ${channels.length} ` + + `channel${channels.length === 1 ? "" : "s"} would be written where no flow can read ` + + `them back. Pass the same \`orgId\` you passed \`openChannels\`.` + ); + } + + if (seats.length > 0 && options.seatWriter === undefined) { + throw new Error( + `openInventory was given ${seats.length} seat${seats.length === 1 ? "" : "s"} and no ` + + `\`seatWriter\`. A seat has no session, so its row has to be written from inside some ` + + `flow, and there is nothing in the roster that says which. Pass ` + + `\`seatWriter: { flowKind }\` naming a kind that carries the inventory writer — the ` + + `channel kind does when \`channelInstances\` was called with \`inventory: true\`.` + ); + } + + const problems: string[] = []; + let seatsWritten = 0; + + if (seats.length > 0) { + const writer = options.seatWriter!; + try { + await options.run({ + action: INVENTORY_REGISTER_SEATS, + // Id and kind only. A seat's row is the whole of what the inventory + // knows about it, and everything else on a record is the declared + // layer's to answer. + input: { seats: seats.map((seat) => ({ id: seat.id, kind: seat.kind })) }, + userId: options.userId, + orgId, + flowKind: writer.flowKind, + sessionId: writer.sessionId ?? INVENTORY_SEAT_WRITER_SESSION, + // The seat writer lives in `internal.actions` only — see + // `InventoryActionRequest.source`. + source: "internal" + }); + seatsWritten = seats.length; + } catch (error) { + // Collected, not thrown: an app whose channels all registered is not an + // app with no inventory, and the caller is the one that knows whether a + // seatless inventory is worth refusing to boot over. + problems.push(`the seat rows could not be written — ${messageOf(error)}`); + } + } + + let channelsWritten = 0; + for (const manifest of channels) { + const selected = kindOf(manifest.declared); + if ("problem" in selected) { + problems.push(`channel "${manifest.id}" — ${selected.problem}`); + continue; + } + + try { + await options.run({ + action: INVENTORY_REGISTER_CHANNEL, + // Empty, and that is the contract rather than an omission: the channel + // reads its members out of its own session state, so there is nothing + // for the binder to supply and nothing it could supply that would not + // be the file's answer wearing the live one's name. + input: {}, + userId: options.userId, + orgId, + flowKind: selected.kind, + sessionId: manifest.id + }); + channelsWritten += 1; + } catch (error) { + // The walk continues. The two ways to land here are a channel that is + // not open (so there is no membership to publish) and a kind that does + // not declare the registration action at all — a hand-rolled one that + // did not carry it. Both are named; neither is a channel quietly absent + // from the inventory. + problems.push( + `channel "${manifest.id}" could not register in the inventory — ${messageOf(error)}` + ); + } + } + + return { seats: seatsWritten, channels: channelsWritten, problems }; +} diff --git a/packages/workforce/test/inventory-binder.test.ts b/packages/workforce/test/inventory-binder.test.ts new file mode 100644 index 0000000000..6cdb585265 --- /dev/null +++ b/packages/workforce/test/inventory-binder.test.ts @@ -0,0 +1,712 @@ +/** + * The live inventory's two writers, on the real path: `openInventory` for the + * seat rows, and each channel for its own. + * + * `inventory-collections.test.ts` covers the floor these rows land on — org + * boundary, cross-flow sharing, key shape. This file covers who writes them and + * what they say, so every case here goes through a registered flow, a real + * session opened by `openChannels`, and a real action run. + * + * **Every assertion is paired with a control that would break it.** A row that + * exists is only evidence of a writer if the same roster, in the same process, + * produces no row when the writer is absent — so the off-state case runs the + * identical roster with the flag down, the custom-kind case runs a third kind + * that omits the registration, and the staleness case runs a roster that names + * different members from the ones the session holds. The reader is a flow that + * is not a channel and declares its own collection instances, so nothing here + * is green merely because the writer read back its own objects. + */ +import { describe, expect, it } from "vitest"; +import { defineFlow, handler } from "@flow-state-dev/core"; +import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; +import { z } from "zod"; +import { + CHANNEL_KIND, + INVENTORY_REGISTER_CHANNEL, + INVENTORY_REGISTER_SEATS, + INVENTORY_SEAT_WRITER_SESSION, + channelInstances, + defineChannelInventoryCollection, + defineMembershipIndexCollection, + defineSeatInventoryCollection, + inventoryWriterActions, + membershipPrefix, + openChannels, + openInventory, + type ChannelManifest, + type InventoryBinding, + type InventorySeat +} from "../src/index"; +import { channelSessionStateSchema } from "../src/index"; + +const USER_ID = "u_boot"; +const ORG_ID = "org_acme"; +const OTHER_ORG = "org_other"; + +/** The kind a hand-rolled channel runs on when a case needs a second one. */ +const BRIEFING_KIND = "briefing"; +/** A hand-rolled kind that deliberately does NOT carry the inventory writer. */ +const SILENT_KIND = "silent"; + +function record(id: string, declared: Record = {}): ChannelManifest { + return { id, declared: { members: ["eng.lead", "eng.coder"], ...declared }, body: "Charter." }; +} + +/** + * The reader: a flow that is **not** a channel, declaring its own instances of + * the three collections. + * + * Its own instances on purpose. A collection is addressed by its pattern and + * scope, and if that were not true this reader would come back empty — so + * calling the factories again here is what turns "the rows are shared" from a + * claim into a measurement. + */ +const seatsCollection = defineSeatInventoryCollection(); +const channelsCollection = defineChannelInventoryCollection(); +const membershipsCollection = defineMembershipIndexCollection(); + +const readInventory = handler({ + name: "read-inventory", + inputSchema: z.object({ membershipsOf: z.string().optional() }), + outputSchema: z.object({ + seats: z.array(z.unknown()), + channels: z.array(z.unknown()), + memberships: z.array(z.unknown()) + }), + resources: { + seats: seatsCollection, + channels: channelsCollection, + memberships: membershipsCollection + }, + execute: async (input: any, ctx: any) => { + const state = (ref: any): unknown => ref.state; + const memberships = + input.membershipsOf === undefined + ? await ctx.resources.memberships.list() + : await ctx.resources.memberships.list(membershipPrefix(input.membershipsOf)); + return { + seats: (await ctx.resources.seats.list()).map(state), + channels: (await ctx.resources.channels.list()).map(state), + memberships: memberships.map(state) + }; + } +}); + +const readerFlow = defineFlow({ + kind: "inventory-reader", + actions: { read: { block: readInventory } } +} as never); + +/** A hand-rolled channel kind, carrying the writer the way it carries the singleton contract. */ +function briefingKind() { + const flow = defineFlow({ + kind: BRIEFING_KIND, + cardinality: "singleton", + session: { stateSchema: channelSessionStateSchema }, + actions: { ...inventoryWriterActions(BRIEFING_KIND) } + } as never); + return Object.assign(() => (flow as any)(), { kind: BRIEFING_KIND }); +} + +/** + * The control kind: identical to {@link briefingKind} but for the one line that + * carries the registration. + * + * Its channel opens, holds members and behaves like any other — it simply has + * nowhere for the binder's run to land. That is what makes "the row is there" + * an assertion about the writer rather than about the roster. + */ +function silentKind() { + const noop = handler({ + name: "silent-noop", + inputSchema: z.object({}), + outputSchema: z.object({ ok: z.boolean() }), + execute: async () => ({ ok: true }) + }); + const flow = defineFlow({ + kind: SILENT_KIND, + cardinality: "singleton", + session: { stateSchema: channelSessionStateSchema }, + actions: { ping: { block: noop } } + } as never); + return Object.assign(() => (flow as any)(), { kind: SILENT_KIND }); +} + +type HostOptions = { + /** Turn the writer on for the built-in kind. */ + inventory?: boolean; + /** Extra channel kinds, by kind name. */ + kinds?: Record; + /** Channels `openChannels` opens. Defaults to the whole roster. */ + open?: ChannelManifest[]; + /** Shared storage, so a second boot reads what the first wrote. */ + adapter?: unknown; +}; + +/** + * Register the roster's kinds plus the reader, open the channels, and hand back + * the doors a case needs. + * + * `openInventory` is NOT called here. Several cases need it run alone, with a + * roster the channels were not opened from, so the binder stays the case's to + * invoke. + */ +async function host(roster: ChannelManifest[], options: HostOptions = {}) { + const instances = channelInstances(roster, { + ...(options.kinds === undefined ? {} : { kinds: options.kinds }), + ...(options.inventory === undefined ? {} : { inventory: options.inventory }) + }); + const byKind: Record = Object.fromEntries( + instances.map((instance) => [instance.kind, instance]) + ); + const reader = (readerFlow as any)(); + const state = createFlowState({ + flows: { ...byKind, [reader.kind]: reader }, + stores: { default: { primary: options.adapter ?? inMemoryStores() } } + } as never); + const runtime = await state.getRuntime(); + + await openChannels(options.open ?? roster, { + client: sessionApi(runtime.stores), + userId: USER_ID, + orgId: ORG_ID + }); + + /** + * The binder's action door, over this process's own runtime. + * + * It REJECTS on a failed run, which is the contract `openInventory`'s + * `run` states: the engine hands a refusal back as `{ error }` rather than + * throwing, and a door that passed that through as an ordinary value would + * report every channel registered while writing nothing. + */ + const run = async (request: { + action: string; + input: unknown; + userId: string; + orgId: string; + flowKind: string; + sessionId: string; + source?: string; + }): Promise => { + const flow = byKind[request.flowKind]; + if (flow === undefined) { + throw new Error(`no flow registered under kind "${request.flowKind}"`); + } + const result: any = await runAction({ + flow, + actionName: request.action, + input: request.input, + userId: request.userId, + orgId: request.orgId, + sessionId: request.sessionId, + source: request.source, + stores: runtime.stores, + runtimeConfig: { ...runtime.runtimeConfig } + } as never); + if (result?.error !== undefined) { + throw result.error instanceof Error ? result.error : new Error(String(result.error)); + } + return result; + }; + + return { + runtime, + run, + /** Read the inventory back through a flow that is not a channel. */ + read: async (opts: { orgId?: string; membershipsOf?: string } = {}) => { + const { membershipsOf, ...rest } = opts; + const result: any = await runAction({ + flow: reader, + actionName: "read", + input: membershipsOf === undefined ? {} : { membershipsOf }, + userId: USER_ID, + orgId: ORG_ID, + stores: runtime.stores, + runtimeConfig: { ...runtime.runtimeConfig }, + ...rest + } as never); + return (result.output ?? result) as { + seats: any[]; + channels: any[]; + memberships: any[]; + }; + }, + /** Every inventory key physically present in an org's storage. */ + keys: async (orgId: string = ORG_ID) => + Object.keys( + await runtime.stores.resourceState.getByPrefix("org", orgId, "inventory/") + ).sort(), + /** One stored row, straight out of org storage — never through the reader. */ + row: async (key: string) => + (await runtime.stores.resourceState.get("org", ORG_ID, key))?.state as + | Record + | undefined, + act: async (sessionId: string, actionName: string, input: unknown) => { + try { + return (await runAction({ + flow: byKind[CHANNEL_KIND], + actionName, + input, + userId: USER_ID, + orgId: ORG_ID, + sessionId, + stores: runtime.stores, + runtimeConfig: { ...runtime.runtimeConfig } + } as never)) as { output?: unknown; error?: unknown }; + } catch (error) { + return { error }; + } + }, + dispose: () => state.dispose() + }; +} + +/** `openChannels`'s session API over one runtime's stores. */ +function sessionApi(stores: any) { + return { + createSession: async (options: { + flowKind: string; + userId: string; + sessionId?: string; + orgId?: string; + description?: string; + state?: Record; + }): Promise => { + const id = String(options.sessionId); + if ((await stores.session.get(id)) !== undefined) { + throw Object.assign(new Error(`Session "${id}" already exists`), { status: 409 }); + } + const now = Date.now(); + await stores.session.set( + id, + { + id, + flowKind: options.flowKind, + flowId: options.flowKind, + userId: options.userId, + orgId: options.orgId, + state: options.state ?? {}, + lineageId: `lin_${id}`, + version: 0, + createdAt: now, + updatedAt: now, + journal: [] + } as never, + "absent" + ); + return { id }; + }, + getSession: async (sessionId: string) => { + const found = await stores.session.get(sessionId); + return { + flowKind: String(found?.flowKind), + flowId: found?.flowId, + userId: String(found?.userId), + orgId: (found as { orgId?: string } | undefined)?.orgId, + state: found?.state as Record | undefined + }; + }, + deleteSession: async (sessionId: string): Promise => { + await stores.session.delete(sessionId); + } + }; +} + +const SEATS: InventorySeat[] = [ + { id: "eng.lead", kind: "agent" }, + { id: "eng.coder", kind: "coder" } +]; + +/** The usual call: seats through the built-in kind, channels through their own. */ +function bind( + lab: Awaited>, + options: { + seats?: InventorySeat[]; + channels?: ChannelManifest[]; + orgId?: string | undefined; + seatWriterKind?: string; + } = {} +): Promise { + return openInventory( + { seats: options.seats ?? SEATS, channels: options.channels ?? [] }, + { + run: lab.run as never, + userId: USER_ID, + orgId: "orgId" in options ? options.orgId : ORG_ID, + seatWriter: { flowKind: options.seatWriterKind ?? CHANNEL_KIND } + } + ); +} + +describe("what one boot writes", () => { + it("gives every seat and every open channel a row, read back from a flow that is not a channel (BR-8, BR-14, BR-21)", async () => { + const roster = [record("eng.standup"), record("eng.retro", { members: ["eng.lead"] })]; + const lab = await host(roster, { inventory: true }); + try { + const result = await bind(lab, { channels: roster }); + expect(result.problems).toEqual([]); + expect(result).toMatchObject({ seats: 2, channels: 2 }); + + const rows = await lab.read(); + + expect(rows.seats.map((row) => row.id).sort()).toEqual(["eng.coder", "eng.lead"]); + expect(rows.seats.find((row) => row.id === "eng.coder")).toEqual({ + id: "eng.coder", + kind: "coder" + }); + + const channels = Object.fromEntries(rows.channels.map((row) => [row.id, row])); + expect(Object.keys(channels).sort()).toEqual(["eng.retro", "eng.standup"]); + expect(channels["eng.standup"]).toMatchObject({ + id: "eng.standup", + kind: CHANNEL_KIND, + members: ["eng.lead", "eng.coder"] + }); + expect(channels["eng.retro"].members).toEqual(["eng.lead"]); + // `openedAt` is written, not left at the schema's null default — the + // assertion is on it being a real timestamp, because a `null` here would + // still satisfy a `toHaveProperty` check. + expect(Date.parse(channels["eng.standup"].openedAt)).not.toBeNaN(); + } finally { + await lab.dispose(); + } + }); + + it("puts the rows under the pinned storage keys (BR-16)", async () => { + const roster = [record("eng.standup", { members: ["eng.lead"] })]; + const lab = await host(roster, { inventory: true }); + try { + await bind(lab, { channels: roster, seats: [{ id: "eng.lead", kind: "agent" }] }); + + // Read out of storage rather than through the collection, because what is + // being pinned is the key an already-persisted org would have to keep. + expect(await lab.keys()).toEqual([ + "inventory/channels/eng.standup", + "inventory/members/eng.lead/eng.standup", + "inventory/seats/eng.lead" + ]); + expect(await lab.row("inventory/seats/eng.lead")).toEqual({ + id: "eng.lead", + kind: "agent" + }); + } finally { + await lab.dispose(); + } + }); + + it("writes the membership index from the same read as the channel row, so the two agree (BR-17, BR-20)", async () => { + const roster = [ + record("eng.standup", { members: ["eng.lead", "eng.coder"] }), + record("eng.retro", { members: ["eng.lead"] }), + record("eng.allhands", { members: ["eng.leadership"] }) + ]; + const lab = await host(roster, { inventory: true }); + try { + await bind(lab, { + channels: roster, + seats: [...SEATS, { id: "eng.leadership", kind: "agent" }] + }); + + const mine = await lab.read({ membershipsOf: "eng.lead" }); + expect(mine.memberships.map((row) => row.channelId).sort()).toEqual([ + "eng.retro", + "eng.standup" + ]); + // "eng.leadership" is in the roster precisely so a prefix read without the + // segment boundary would drag its channel in here. + expect(mine.memberships.map((row) => row.channelId)).not.toContain("eng.allhands"); + + // The index is a projection, so it must say exactly what the rows say. A + // check on the index alone would pass against an index written from some + // other source entirely. + const all = await lab.read(); + const fromRows = all.channels + .filter((row) => (row.members as string[]).includes("eng.lead")) + .map((row) => row.id) + .sort(); + expect(fromRows).toEqual(mine.memberships.map((row) => row.channelId).sort()); + } finally { + await lab.dispose(); + } + }); +}); + +describe("what the binder refuses to carry", () => { + it("writes the members the open channel holds, never the ones the roster names (BR-10, BR-10a)", async () => { + // Opened with one roster, registered from another. Running `openInventory` + // ALONE is what makes this conclusive: with a whole boot in between, + // `openChannels` would be a second candidate writer of the row's members and + // a red result would not say which of the two carried them. + const opened = [record("eng.standup", { members: ["eng.lead", "eng.coder"] })]; + const lab = await host(opened, { inventory: true }); + try { + const edited = [record("eng.standup", { members: ["ops.oncall", "ops.sre"] })]; + await bind(lab, { channels: edited, seats: [] }); + + const rows = await lab.read(); + // The red state is this row holding ["ops.oncall", "ops.sre"] — exactly + // what a binder that copied the roster's `members:` forward would write. + expect(rows.channels).toHaveLength(1); + expect(rows.channels[0].members).toEqual(["eng.lead", "eng.coder"]); + + // And the index follows the row, not the roster, for the same reason. + expect(await lab.keys()).toEqual([ + "inventory/channels/eng.standup", + "inventory/members/eng.coder/eng.standup", + "inventory/members/eng.lead/eng.standup" + ]); + } finally { + await lab.dispose(); + } + }); + + it("refuses a run with no org rather than writing where nothing can read (BR-11)", async () => { + const roster = [record("eng.standup")]; + const lab = await host(roster, { inventory: true }); + try { + await expect(bind(lab, { channels: roster, orgId: undefined })).rejects.toThrow( + /no `orgId`/ + ); + + // The red state is a binder that carried on: it would report success and + // leave an inventory every flow reads back empty. Both halves are checked + // — nothing under any org, and the same call under an org does write. + expect(await lab.keys()).toEqual([]); + expect(await lab.keys(OTHER_ORG)).toEqual([]); + + await bind(lab, { channels: roster }); + expect((await lab.keys()).length).toBeGreaterThan(0); + } finally { + await lab.dispose(); + } + }); + + it("refuses seats with no seatWriter, naming what to pass", async () => { + const lab = await host([], { inventory: true }); + try { + await expect( + openInventory( + { seats: SEATS, channels: [] }, + { run: lab.run as never, userId: USER_ID, orgId: ORG_ID } + ) + ).rejects.toThrow(/seatWriter/); + expect(await lab.keys()).toEqual([]); + } finally { + await lab.dispose(); + } + }); +}); + +describe("running it twice", () => { + it("is a no-op over an unchanged roster, and keeps the rows a shrunken one drops (BR-9, BR-23)", async () => { + const adapter = inMemoryStores(); + const roster = [record("eng.standup"), record("eng.retro", { members: ["eng.lead"] })]; + + const first = await host(roster, { inventory: true, adapter }); + let openedAt: string; + try { + await bind(first, { channels: roster }); + const keys = await first.keys(); + expect(keys).toContain("inventory/channels/eng.retro"); + openedAt = (await first.row("inventory/channels/eng.standup"))!.openedAt as string; + + // Second run, same process, same roster: the red state is rows doubling. + await bind(first, { channels: roster }); + expect(await first.keys()).toEqual(keys); + } finally { + await first.dispose(); + } + + // A second boot over the SAME storage, from a roster that lost a channel and + // a seat. Nothing is reconciled: a binder that dropped what its roster no + // longer names would take a live channel's row with it. + const shrunk = [record("eng.standup")]; + const second = await host(shrunk, { inventory: true, adapter }); + try { + const result = await bind(second, { + channels: shrunk, + seats: [{ id: "eng.lead", kind: "agent" }] + }); + expect(result.problems).toEqual([]); + + const rows = await second.read(); + expect(rows.channels.map((row) => row.id).sort()).toEqual(["eng.retro", "eng.standup"]); + expect(rows.seats.map((row) => row.id).sort()).toEqual(["eng.coder", "eng.lead"]); + // The channel that was open before this boot keeps the moment it opened, + // rather than being restamped by a binder that has no idea when that was. + expect((await second.row("inventory/channels/eng.standup"))!.openedAt).toBe(openedAt); + } finally { + await second.dispose(); + } + }); +}); + +describe("an app that never turns the inventory on", () => { + it("declares nothing and writes nothing, and its channels behave as they did (BR-13)", async () => { + const roster = [record("eng.standup")]; + + // The control and the case are the same roster and the same code, one flag + // apart. Without it, there is no action to run, so the binder reports the + // channel by name and no row exists anywhere. + const off = await host(roster); + try { + const result = await bind(off, { channels: roster }); + expect(result.channels).toBe(0); + expect(result.problems).toHaveLength(2); + expect(result.problems.join("\n")).toContain("eng.standup"); + expect(await off.keys()).toEqual([]); + + // And the channel is otherwise exactly a channel: a post lands, a read + // comes back, nothing about it changed. + const posted = await off.act("eng.standup", "post", { body: "morning" }); + expect(posted.error).toBeUndefined(); + const read: any = await off.act("eng.standup", "read", {}); + expect(read.error).toBeUndefined(); + expect((read.output as any).members).toEqual(["eng.lead", "eng.coder"]); + expect((read.output as any).transcript).toHaveLength(1); + } finally { + await off.dispose(); + } + + const on = await host(roster, { inventory: true }); + try { + const result = await bind(on, { channels: roster }); + expect(result.problems).toEqual([]); + expect(await on.keys()).not.toEqual([]); + } finally { + await on.dispose(); + } + }); +}); + +describe("a custom channel kind", () => { + it("gets rows like the built-in's, and one that cannot register is named (BR-22, BR-12)", async () => { + const roster = [ + record("eng.standup"), + record("eng.brief", { flow: BRIEFING_KIND, members: ["eng.lead"] }), + record("eng.quiet", { flow: SILENT_KIND, members: ["eng.coder"] }) + ]; + const lab = await host(roster, { + inventory: true, + kinds: { [BRIEFING_KIND]: briefingKind(), [SILENT_KIND]: silentKind() } + }); + try { + const result = await bind(lab, { channels: roster }); + + const rows = await lab.read(); + const byId = Object.fromEntries(rows.channels.map((row) => [row.id, row])); + + // The built-in and the hand-rolled kind are both there, each carrying the + // kind that minted it. A write behind a `kind === "channel"` test would + // leave `eng.brief` out while every other assertion here still passed. + expect(byId["eng.standup"].kind).toBe(CHANNEL_KIND); + expect(byId["eng.brief"]).toMatchObject({ + id: "eng.brief", + kind: BRIEFING_KIND, + members: ["eng.lead"] + }); + + // The kind that carries no registration is a NAMED failure, not a silent + // gap — and the two that could register still did. + expect(byId["eng.quiet"]).toBeUndefined(); + expect(result.channels).toBe(2); + expect(result.problems).toHaveLength(1); + expect(result.problems[0]).toContain("eng.quiet"); + expect(result.problems[0]).toContain("could not register"); + } finally { + await lab.dispose(); + } + }); +}); + +describe("a channel nobody opened", () => { + it("is named rather than registered, and the open ones still are (BR-12)", async () => { + const roster = [record("eng.standup"), record("eng.ghost")]; + // Opened without `eng.ghost`, so its session has no channel in it. + const lab = await host(roster, { inventory: true, open: [record("eng.standup")] }); + try { + const result = await bind(lab, { channels: roster }); + + expect(result.channels).toBe(1); + expect(result.problems).toHaveLength(1); + expect(result.problems[0]).toContain("eng.ghost"); + expect(result.problems[0]).toContain("not an open channel"); + + const rows = await lab.read(); + expect(rows.channels.map((row) => row.id)).toEqual(["eng.standup"]); + } finally { + await lab.dispose(); + } + }); +}); + +describe("the registration action itself", () => { + it("takes no input at all, so nothing a caller supplies reaches the row", async () => { + const roster = [record("eng.standup")]; + const lab = await host(roster, { inventory: true }); + try { + const refused = await lab.act("eng.standup", INVENTORY_REGISTER_CHANNEL, { + members: ["ops.intruder"] + }); + // The schema is closed, so a caller cannot even name the field. This is + // the fence: there is no shape of input through which somebody else's + // membership could be published under this channel's id. + expect(refused.error).toBeDefined(); + expect(await lab.keys()).toEqual([]); + + const accepted = await lab.act("eng.standup", INVENTORY_REGISTER_CHANNEL, {}); + expect(accepted.error).toBeUndefined(); + expect((await lab.row("inventory/channels/eng.standup"))!.members).toEqual([ + "eng.lead", + "eng.coder" + ]); + } finally { + await lab.dispose(); + } + }); + + it("leaves nothing written when a member id cannot become a membership key, on every attempt", async () => { + // "bad/id" can never pass `membershipKey`'s one-path-segment rule, so this + // is not a flaky write — it fails the same way on every boot until the + // member id itself is fixed. + const roster = [record("eng.standup", { members: ["eng.lead", "bad/id"] })]; + const lab = await host(roster, { inventory: true, open: roster }); + try { + const first = await lab.act("eng.standup", INVENTORY_REGISTER_CHANNEL, {}); + expect(first.error).toBeDefined(); + // A channel row with no matching membership row would disagree with the + // index for as long as the process runs, since nothing here retries or + // prunes. So a permanently-failing member must leave nothing behind, + // not a channel row committed ahead of the membership it names. + expect(await lab.keys()).toEqual([]); + + const second = await lab.act("eng.standup", INVENTORY_REGISTER_CHANNEL, {}); + expect(second.error).toBeDefined(); + expect(await lab.keys()).toEqual([]); + } finally { + await lab.dispose(); + } + }); + + it("registerSeatsInInventory cannot be reached through the public door", async () => { + const roster = [record("eng.standup")]; + const lab = await host(roster, { inventory: true, open: roster }); + try { + // `lab.act` dispatches exactly the way a caller-addressed HTTP/MCP + // request would — no `source`, which resolves as `"http"` (public). + // Unlike `registerChannel`, this action's whole input is the row data, + // so a public hit on it would let a caller write any seat it chose. + const attempt = await lab.act(INVENTORY_SEAT_WRITER_SESSION, INVENTORY_REGISTER_SEATS, { + seats: [{ id: "attacker.fake", kind: "agent" }] + }); + expect(attempt.error).toBeDefined(); + expect(String((attempt.error as Error).message)).toContain( + `does not define action "${INVENTORY_REGISTER_SEATS}"` + ); + expect(await lab.row("inventory/seats/attacker.fake")).toBeUndefined(); + } finally { + await lab.dispose(); + } + }); +});