From 7db4d13374f211727996001502eb8c74b2b230d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 01:40:27 +0000 Subject: [PATCH 01/12] feat(core): resourceVisibility, a per-turn rule for what the model's resource tools reach (FIX-1788 P4 S8) A flow's optional resourceVisibility rule narrows every model-facing listing and lookup in core: the resource tools, search, the discover door's resource source, path and uri resolution. A hidden resource answers exactly as an unregistered one; a read-only one is read and not written. With no rule nothing changes. Generic: the rule names no worker (FIX-1788 D7, the epic's seventh Layer 1 mechanism). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- .changeset/flow-resource-visibility.md | 5 + packages/core/src/flow/defineFlow.ts | 3 + packages/core/src/index.ts | 1 + .../core/src/manifest/resources-source.ts | 10 +- .../core/src/tools/resource-content-tools.ts | 4 +- packages/core/src/tools/resource-tools.ts | 107 ++++++++++++------ packages/core/src/types/flow.ts | 12 ++ packages/core/src/types/index.ts | 1 + .../core/src/types/resource-visibility.ts | 40 +++++++ 9 files changed, 145 insertions(+), 38 deletions(-) create mode 100644 .changeset/flow-resource-visibility.md create mode 100644 packages/core/src/types/resource-visibility.ts diff --git a/.changeset/flow-resource-visibility.md b/.changeset/flow-resource-visibility.md new file mode 100644 index 0000000000..4553f5548f --- /dev/null +++ b/.changeset/flow-resource-visibility.md @@ -0,0 +1,5 @@ +--- +"@flow-state-dev/core": minor +--- + +`defineFlow` takes `resourceVisibility`, a per-turn rule for which of the flow's resources the model's resource tools reach. A resource it hides is absent from listing, search and the discovery door, and answers "not found" when named; a read-only one is read but not written. Omitted, nothing changes (FIX-1788). diff --git a/packages/core/src/flow/defineFlow.ts b/packages/core/src/flow/defineFlow.ts index de8ce7c12a..4b5a055453 100644 --- a/packages/core/src/flow/defineFlow.ts +++ b/packages/core/src/flow/defineFlow.ts @@ -189,6 +189,7 @@ function rejectRemovedClientData(value: object | undefined, flowKind: string, sc /** The definition-only options {@link rejectDefinitionOnlyOptions} refuses. */ const DEFINITION_ONLY_INSTANCE_OPTIONS = [ + "resourceVisibility", "webhooks", "schedules", "mcp", @@ -1473,6 +1474,7 @@ function normalizeFlowConfig( mcp, webhooks, schedules, + ...(definition.resourceVisibility !== undefined ? { resourceVisibility: definition.resourceVisibility } : {}), tokenCounter: options?.tokenCounter ?? definition.tokenCounter, costEstimator: options?.costEstimator ?? definition.costEstimator, isolateUserState, @@ -1558,6 +1560,7 @@ export function defineFlow< mcp: baseInstance.mcp, webhooks: baseInstance.webhooks, schedules: baseInstance.schedules, + ...(baseInstance.resourceVisibility !== undefined ? { resourceVisibility: baseInstance.resourceVisibility } : {}), tokenCounter: baseInstance.tokenCounter, costEstimator: baseInstance.costEstimator, isolateUserState: baseInstance.isolateUserState, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e1d5c6ce90..96222f3613 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -28,6 +28,7 @@ export { } from "./items/predicates"; // `ClientDataOf` covers both DefinedResource and DefinedResourceCollection — one import for either. export type { ClientDataOf, ContextOf, DefinedResource, ResourceContext, StateOf } from "./types/resource"; +export type { ResourceVisibility, ResourceVisibilityRule, ResourceVisibilityTarget } from "./types/resource-visibility"; export type { CollectionHookContext, DefinedResourceCollection, diff --git a/packages/core/src/manifest/resources-source.ts b/packages/core/src/manifest/resources-source.ts index 9dcf0d42b6..19c1c78e09 100644 --- a/packages/core/src/manifest/resources-source.ts +++ b/packages/core/src/manifest/resources-source.ts @@ -20,7 +20,7 @@ import type { ManifestEntry } from "@flow-state-dev/contracts"; import type { BlockContext } from "../types/block"; import type { ResourceRef } from "../types/resource"; -import { collectReadableProjectedCollections, collectReadableResources } from "../tools/resource-tools"; +import { collectReadableProjectedCollections, collectReadableResources, isLlmWritableNow } from "../tools/resource-tools"; import type { BlockManifestSource } from "./registry"; /** @@ -46,8 +46,10 @@ function purposeOf(ref: ResourceRef): string { * exists to remove. Collection instances carry their collection's config, so * the collection-level `writable` is read through this same expression. */ -function contractOf(ref: ResourceRef): string { - const mayWrite = ref.config?.llmWritable === true && ref.config?.writable !== false; +function contractOf(ref: ResourceRef, ctx: BlockContext): string { + // `isLlmWritableNow` also holds the flow's visibility rule: a resource it + // leaves read-only is advertised as read-only. + const mayWrite = isLlmWritableNow(ref, ctx) && ref.config?.writable !== false; return `Reachable by uri "${ref.uri}"; you may ${mayWrite ? "read and write" : "read"} its content.`; } @@ -67,7 +69,7 @@ export function resourcesManifestSource(): BlockManifestSource { id: ref.uri, kind: "resource", purpose: purposeOf(ref), - contract: contractOf(ref), + contract: contractOf(ref, ctx), }); } diff --git a/packages/core/src/tools/resource-content-tools.ts b/packages/core/src/tools/resource-content-tools.ts index 5c7bcef026..09ea264d43 100644 --- a/packages/core/src/tools/resource-content-tools.ts +++ b/packages/core/src/tools/resource-content-tools.ts @@ -13,7 +13,7 @@ import { z } from "zod"; import { handler } from "../blocks/handler"; -import { collectReadableResources, isLlmReadable, isLlmWritable, resolveResourceByUri } from "./resource-tools"; +import { collectReadableResources, isLlmReadable, isLlmWritableNow, resolveResourceByUri } from "./resource-tools"; /** * Tool block for reading rendered resource content, keyed by scope-qualified uri. @@ -62,7 +62,7 @@ export function writeResourceContentTool() { outputSchema: z.object({ uri: z.string(), ok: z.literal(true) }), execute: async (input, ctx) => { const ref = await resolveResourceByUri(input.uri, ctx); - if (ref === undefined || !isLlmWritable(ref)) { + if (ref === undefined || !isLlmWritableNow(ref, ctx)) { throw new Error(`Writable resource not found for uri: ${input.uri}`); } diff --git a/packages/core/src/tools/resource-tools.ts b/packages/core/src/tools/resource-tools.ts index 03dc62fe06..9a9640c90e 100644 --- a/packages/core/src/tools/resource-tools.ts +++ b/packages/core/src/tools/resource-tools.ts @@ -1,7 +1,8 @@ import { z } from "zod"; import type { BlockContext } from "../types/block"; -import type { ResourceRef } from "../types/resource"; +import type { AnyResourceRef, ResourceRef } from "../types/resource"; import type { ResourceCollectionRef } from "../types/resource-collection"; +import type { ResourceVisibility, ResourceVisibilityRule } from "../types/resource-visibility"; import { handler } from "../blocks/handler"; import { extractBareTopic, @@ -14,8 +15,42 @@ type CollectionEntry = { name: string; scope: string; ref: ResourceCollectionRef; + /** What this turn's visibility rule allows the model: never `"hidden"` here. */ + access: Exclude; }; +/** + * The flow's visibility rule, read off the running flow. `ctx.flow` is the + * flow instance at run time; the rule is definition-only, so every copy + * carries its definition's. + */ +function visibilityRuleOf(ctx: BlockContext): ResourceVisibilityRule | undefined { + return (ctx.flow as { resourceVisibility?: ResourceVisibilityRule } | undefined)?.resourceVisibility; +} + +/** + * Every registered resource the model may reach on this turn, with what it + * may do: the one place the flow's `resourceVisibility` rule is applied, so + * every listing and lookup below narrows the same way. A resource the rule + * hides is left out here, so it answers exactly like one that isn't + * registered. With no rule, every entry is `"visible"`. + */ +function reachableEntries(ctx: BlockContext): Array<{ entry: AnyResourceRef; access: Exclude }> { + const registry = ctx.resources; + if (registry === undefined) return []; + const rule = visibilityRuleOf(ctx); + if (rule === undefined) return registry.list().map((entry) => ({ entry, access: "visible" as const })); + const out: Array<{ entry: AnyResourceRef; access: Exclude }> = []; + // The registry's own keys are its accessor names; `get` and `list` are its methods. + for (const [name, entry] of Object.entries(registry as Record)) { + if (typeof entry !== "object" || entry === null) continue; + const ref = entry as AnyResourceRef; + const access = rule(ctx, { name, ref }); + if (access !== "hidden") out.push({ entry: ref, access }); + } + return out; +} + /** * True for a projected resource collection ref (FIX-858) — carries the * `projected: true` brand. Both `pattern`-bearing collection kinds (store-backed @@ -35,14 +70,11 @@ function isProjectedRef(entry: unknown): boolean { */ function collectCollections(ctx: BlockContext): CollectionEntry[] { const entries: CollectionEntry[] = []; - const registry = ctx.resources; - if (registry === undefined) return entries; - - for (const entry of registry.list()) { + for (const { entry, access } of reachableEntries(ctx)) { // ResourceCollectionRef has a `pattern` property that ResourceRef does not. if ("pattern" in entry && !isProjectedRef(entry)) { const nsRef = entry as unknown as ResourceCollectionRef; - entries.push({ name: nsRef.pattern, scope: nsRef.scope, ref: nsRef }); + entries.push({ name: nsRef.pattern, scope: nsRef.scope, ref: nsRef, access }); } } @@ -57,28 +89,25 @@ function collectCollections(ctx: BlockContext): CollectionEntry[] { */ export function collectProjectedCollections(ctx: BlockContext): CollectionEntry[] { const entries: CollectionEntry[] = []; - const registry = ctx.resources; - if (registry === undefined) return entries; - - for (const entry of registry.list()) { + for (const { entry, access } of reachableEntries(ctx)) { if ("pattern" in entry && isProjectedRef(entry)) { const nsRef = entry as unknown as ResourceCollectionRef; - entries.push({ name: nsRef.pattern, scope: nsRef.scope, ref: nsRef }); + entries.push({ name: nsRef.pattern, scope: nsRef.scope, ref: nsRef, access }); } } return entries; } +/** The static (single) resources the model may reach on this turn, with what it may do. */ +function reachableStatics(ctx: BlockContext): Array<{ ref: ResourceRef; access: Exclude }> { + return reachableEntries(ctx) + .filter(({ entry }) => !("pattern" in entry && "create" in entry) && !isProjectedRef(entry)) + .map(({ entry, access }) => ({ ref: entry as ResourceRef, access })); +} + function collectStaticResources(ctx: BlockContext): ResourceRef[] { - const registry = ctx.resources; - if (registry === undefined) return []; - return registry - .list() - .filter( - (entry: any): entry is ResourceRef => - !("pattern" in entry && "create" in entry) && !isProjectedRef(entry) - ); + return reachableStatics(ctx).map(({ ref }) => ref); } /** @@ -111,7 +140,7 @@ export function resourceTools() { ok: z.literal(true), }), execute: async (input, ctx) => { - const { nsRef, key } = resolvePathToCollection(input.path, ctx); + const { nsRef, key } = resolvePathToCollection(input.path, ctx, "write"); await nsRef.create(key, input.state as any); return { path: input.path, ok: true as const }; }, @@ -146,7 +175,7 @@ export function resourceTools() { ok: z.literal(true), }), execute: async (input, ctx) => { - const { nsRef, key } = resolvePathToCollection(input.path, ctx); + const { nsRef, key } = resolvePathToCollection(input.path, ctx, "write"); const handle = await nsRef.get(key); await handle.patchState(input.state as any); return { path: input.path, ok: true as const }; @@ -164,7 +193,7 @@ export function resourceTools() { ok: z.literal(true), }), execute: async (input, ctx) => { - const { nsRef, key } = resolvePathToCollection(input.path, ctx); + const { nsRef, key } = resolvePathToCollection(input.path, ctx, "write"); await nsRef.delete(key); return { path: input.path, ok: true as const }; }, @@ -189,14 +218,8 @@ export async function resolveResourceByPath( path: string, ctx: BlockContext, ): Promise | undefined> { - const registry = ctx.resources; - if (registry === undefined) return undefined; - - for (const entry of registry.list()) { - if (!("pattern" in entry && "create" in entry) && !isProjectedRef(entry)) { - const ref = entry as ResourceRef; - if (ref.path === path) return ref; - } + for (const ref of collectStaticResources(ctx)) { + if (ref.path === path) return ref; } const collections = collectCollections(ctx); @@ -230,6 +253,23 @@ export function isLlmWritable(ref: ResourceRef): boolean { return ref.config?.llmWritable === true; } +/** + * Whether the model may write `ref` on this turn: its own `llmWritable`, and + * the flow's visibility rule leaving it writable. `ref` is a static resource + * or a collection instance resolved through this module on this turn. + */ +export function isLlmWritableNow(ref: ResourceRef, ctx: BlockContext): boolean { + if (!isLlmWritable(ref)) return false; + if (visibilityRuleOf(ctx) === undefined) return true; + const own = reachableStatics(ctx).find((s) => s.ref === ref || s.ref.uri === ref.uri); + if (own !== undefined) return own.access === "visible"; + const slash = ref.uri.indexOf("/"); + const scope = ref.uri.slice(0, slash); + const path = ref.uri.slice(slash + 1); + const owner = collectCollections(ctx).find((ns) => ns.scope === scope && matchCollectionKey(ns, path) !== undefined); + return owner?.access === "visible"; +} + /** * Every `llmReadable` resource — static resources that opted in, plus the * instances of collections that opted in. Filters collections by their @@ -310,9 +350,12 @@ export async function resolveResourceByUri( function resolvePathToCollection( path: string, - ctx: BlockContext + ctx: BlockContext, + intent: "read" | "write" = "read" ): { nsRef: ResourceCollectionRef; key: string | Record } { - const collections = collectCollections(ctx); + // A collection the rule leaves read-only isn't a target for a write: the + // write answers as for a path no collection matches. + const collections = collectCollections(ctx).filter((ns) => intent === "read" || ns.access === "visible"); for (const ns of collections) { const key = matchCollectionKey(ns, path); diff --git a/packages/core/src/types/flow.ts b/packages/core/src/types/flow.ts index 14757c1b36..1b5bd5fda1 100644 --- a/packages/core/src/types/flow.ts +++ b/packages/core/src/types/flow.ts @@ -22,6 +22,7 @@ import type { TokenCounter } from "./tokens"; import type { JsonObject, JsonValue } from "../schema/common"; import type { VoiceConfig } from "./speech"; import type { SessionCreateCheck } from "./session-create"; +import type { ResourceVisibilityRule } from "./resource-visibility"; /** Legacy scope-keyed config alias preserved for type-internal usage. */ export type ScopeResourceConfig = ResourceConfig | ResourceCollectionConfig; @@ -597,6 +598,15 @@ export type FlowDefinition< */ schedules?: SchedulesConfig; + /** + * Which of the flow's resources the model's resource tools reach on each + * turn: listing, search, reading and writing through core's resource tools + * and the discovery door. Omitted, every resource is reachable as its own + * `llmReadable` and `llmWritable` flags allow. A resource the rule hides + * answers exactly like one that isn't registered. Definition-only. + */ + resourceVisibility?: ResourceVisibilityRule; + tokenCounter?: TokenCounter; costEstimator?: CostEstimator; @@ -733,6 +743,8 @@ export type FlowInstance< mcp?: McpConfig; webhooks?: WebhookConfig; schedules?: SchedulesConfig; + /** See {@link FlowDefinition.resourceVisibility}. */ + resourceVisibility?: ResourceVisibilityRule; tokenCounter?: TokenCounter; costEstimator?: CostEstimator; isolateUserState: boolean; diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index 4c186a0c98..0fe8f84e7b 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -248,6 +248,7 @@ export type { ResourceRegistry, StateOf } from "./resource"; +export type { ResourceVisibility, ResourceVisibilityRule, ResourceVisibilityTarget } from "./resource-visibility"; export type { CollectionHookContext, diff --git a/packages/core/src/types/resource-visibility.ts b/packages/core/src/types/resource-visibility.ts new file mode 100644 index 0000000000..cecd4e609a --- /dev/null +++ b/packages/core/src/types/resource-visibility.ts @@ -0,0 +1,40 @@ +/** + * A flow's per-turn rule for which of its resources the model's resource + * tools reach (`defineFlow({ resourceVisibility })`). + * + * The flow declares every resource it may ever need; the rule decides, on + * each turn, which of them the model can list, search, read and write + * through core's resource tools. It narrows only: a resource it calls + * `"visible"` is still subject to its own `llmReadable` and `llmWritable`. + * + * Block code that names a resource (`ctx.resources.handbook`) is the app's + * own and is not narrowed. + */ +import type { BlockContext } from "./block"; +import type { AnyResourceRef } from "./resource"; + +/** + * What the model's resource tools may do with one resource on this turn: + * + * - `"visible"`: everything its own flags allow; + * - `"read-only"`: list, search and read it, but not write it. A write is + * refused exactly as for a resource that isn't `llmWritable`; + * - `"hidden"`: nothing. It answers exactly like a resource that isn't + * registered: absent from every listing, and "not found" when named. + */ +export type ResourceVisibility = "visible" | "read-only" | "hidden"; + +/** One resource as the rule sees it: the key the flow registers it under, and its handle. */ +export type ResourceVisibilityTarget = { + /** The key in the flow's `resources` map (`ctx.resources[name]`). */ + readonly name: string; + /** The resource or collection's handle on this turn. */ + readonly ref: AnyResourceRef; +}; + +/** + * The rule. Called with the running block's context, on every listing and + * lookup, so it must be synchronous and cheap. Derive the answer from data + * the server wrote on this turn, never from the turn's input. + */ +export type ResourceVisibilityRule = (ctx: BlockContext, resource: ResourceVisibilityTarget) => ResourceVisibility; From 5902debba0ac808bc8e051cd435b1ca59bea2795 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 01:40:27 +0000 Subject: [PATCH 02/12] feat(engine): a dispatch refuses to adopt a child holding another readonly value (FIX-1788 P4 S11, BR-18b) A key-derived child that already exists with another value of a readonly session-state field than the dispatch names is refused key-occupied, naming the field, instead of running as the stored value. Covers the visibility rule end to end on the real engine too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- .../engine-adoption-refuses-readonly.md | 5 + .../engine/src/context/create-request-host.ts | 19 +- packages/engine/src/context/dispatch-run.ts | 27 +++ .../engine/test/resource-visibility.test.ts | 166 ++++++++++++++++++ packages/engine/test/session-birth.test.ts | 25 +++ 5 files changed, 241 insertions(+), 1 deletion(-) create mode 100644 .changeset/engine-adoption-refuses-readonly.md create mode 100644 packages/engine/test/resource-visibility.test.ts diff --git a/.changeset/engine-adoption-refuses-readonly.md b/.changeset/engine-adoption-refuses-readonly.md new file mode 100644 index 0000000000..c15aef7ebd --- /dev/null +++ b/.changeset/engine-adoption-refuses-readonly.md @@ -0,0 +1,5 @@ +--- +"@flow-state-dev/engine": minor +--- + +A dispatch that reaches a key-derived child session which already exists, asking for another value of one of its readonly session-state fields, is refused with `key-occupied`, naming the field, instead of adopting the session. Nothing is written and nothing runs there (FIX-1788). diff --git a/packages/engine/src/context/create-request-host.ts b/packages/engine/src/context/create-request-host.ts index 56692a183a..d5b31413fb 100644 --- a/packages/engine/src/context/create-request-host.ts +++ b/packages/engine/src/context/create-request-host.ts @@ -56,6 +56,7 @@ * is written * - the liveness gate refused → `livenessOf` is **absent from the bundle** */ +import { getReadonlyStateKeys } from "@flow-state-dev/core/helpers"; import type { DispatchOutcome, DispatchRefusal, @@ -76,7 +77,7 @@ import { resolveLineageId, resolveSessionStorageKey } from "../stores/scope-keys"; -import { deriveDispatchRunSessionId, evaluateAdoption } from "./dispatch-run"; +import { deriveDispatchRunSessionId, evaluateAdoption, readonlyStateMismatch } from "./dispatch-run"; import { ownsRecord } from "./record-owner"; import type { DispatchOperation } from "./dispatch-operation"; import { @@ -408,6 +409,22 @@ export function createRequestHost(inputs: RequestHostInputs): RequestHostBuild { : `the derived child key is held by a record whose ${verdict.mismatch} does not match this request` ); } + // The record was created with its own readonly state; adopting it for a + // dispatch that names another value would change a field nothing may + // change (a different worker, say). Refused by name rather than run as + // the record's value. + const differs = readonlyStateMismatch( + getReadonlyStateKeys(targetFlow.session?.stateSchema), + initialState, + current!.state as Readonly> | undefined + ); + if (differs !== undefined) { + return refuse( + "key-occupied", + `the derived child key is held by a session created with another value of readonly state field "${differs}"; ` + + `derive a key per value of "${differs}"` + ); + } return { ok: true, sessionId: childId, orgId: identity.orgId, adopted: true, delivery: "child" }; }; diff --git a/packages/engine/src/context/dispatch-run.ts b/packages/engine/src/context/dispatch-run.ts index d9b76874b3..33d10b6d1a 100644 --- a/packages/engine/src/context/dispatch-run.ts +++ b/packages/engine/src/context/dispatch-run.ts @@ -19,6 +19,7 @@ * an upgrade has to land on the session it started, not mint a second one * beside it. */ +import { deepEqual } from "@flow-state-dev/core/helpers"; import { createHash } from "node:crypto"; import type { FlowCardinality } from "@flow-state-dev/core/types"; import { framed } from "@flow-state-dev/core/types"; @@ -162,6 +163,32 @@ function sameOptional(a: string | undefined | null, b: string | undefined | null return left === right; } +/** + * The first readonly session-state field whose value the dispatch names and + * the record already holds differently, or `undefined` when none differs. + * + * Adopting such a record would run the dispatch in a session created with + * another value of a field nothing may change, so the caller refuses it. A + * field the dispatch doesn't name isn't compared: a dispatch that names no + * state adopts as it always has. + * + * @param readonlyFields The target flow's readonly session-state fields. + * @param requested The state the dispatch named for a new child. + * @param stored The adopted record's state. + */ +export function readonlyStateMismatch( + readonlyFields: readonly string[], + requested: Readonly> | undefined, + stored: Readonly> | undefined +): string | undefined { + if (requested === undefined) return undefined; + for (const field of readonlyFields) { + if (!Object.hasOwn(requested, field)) continue; + if (!deepEqual(requested[field], stored?.[field])) return field; + } + return undefined; +} + /** * Decide whether a record found at the derived key may be adopted. * diff --git a/packages/engine/test/resource-visibility.test.ts b/packages/engine/test/resource-visibility.test.ts new file mode 100644 index 0000000000..b144162fc6 --- /dev/null +++ b/packages/engine/test/resource-visibility.test.ts @@ -0,0 +1,166 @@ +/** + * A flow's `resourceVisibility` rule narrows what core's model-facing + * resource tools reach on a turn, on the real engine. + * + * Each tool is mounted as an action, the same block a model would call, and + * run with `runAction`. The rule here is fixed per flow, which is all core + * needs to prove: who the rule is computed from is the composing layer's. + * + * - a hidden document is absent from listing, search and the discovery + * door, and reading or writing it answers exactly as for a uri nothing + * registers; + * - a read-only one is listed and read, and a write is refused as for a + * resource that isn't writable; + * - an app's own tool built on core's lookup gets the same narrowing; + * - with no rule, nothing changes. + */ +import { + createManifestRegistry, + defineFlow, + defineResource, + defineResourceCollection, + discoveryTools, + handler, + readResourceContentTool, + resolveResourceByUri, + resourcesManifestSource, + resourceSearchTools, + resourceTools, + writeResourceContentTool, + type ResourceVisibilityRule +} from "@flow-state-dev/core"; +import type { FlowInstance } from "@flow-state-dev/core/types"; +import { z } from "zod"; +import { describe, expect, it } from "vitest"; +import { createFlowState, inMemoryStores, runAction } from "../src"; + +const ORG = "acme"; + +function document(ref: string) { + return defineResource({ + ref, + scope: "org", + stateSchema: z.object({}).passthrough(), + default: {}, + content: `# ${ref}\nthe ${ref} body`, + llmReadable: true, + llmWritable: true + }); +} + +const notes = defineResourceCollection({ + pattern: "notes/*", + scope: "org", + stateSchema: z.object({ text: z.string().default("") }), + llmReadable: true +}); + +/** handbook is read-only, payroll and the notes collection are hidden, ledger is visible. */ +const narrowing: ResourceVisibilityRule = (_ctx, { name }) => + name === "handbook" ? "read-only" : name === "payroll" || name === "notes" ? "hidden" : "visible"; + +/** An app's own tool: open a resource by uri through core's lookup and say what it found. */ +const peek = handler({ + name: "peek", + inputSchema: z.object({ uri: z.string() }), + execute: async ({ uri }, ctx) => { + const ref = await resolveResourceByUri(uri, ctx); + return { found: ref !== undefined }; + } +}); + +function boot(rule: ResourceVisibilityRule | undefined) { + const { globResources, grepResourceContent } = resourceSearchTools(); + const { createResource } = resourceTools(); + const discover = discoveryTools(createManifestRegistry([resourcesManifestSource()])).discover; + const flow = defineFlow({ + kind: "docs", + resources: { handbook: document("handbook"), payroll: document("payroll"), ledger: document("ledger"), notes }, + ...(rule !== undefined ? { resourceVisibility: rule } : {}), + actions: { + read: { inputSchema: z.object({ uri: z.string().optional() }), block: readResourceContentTool() }, + write: { inputSchema: z.object({ uri: z.string(), content: z.string() }), block: writeResourceContentTool() }, + glob: { inputSchema: z.object({}).passthrough(), block: globResources }, + grep: { inputSchema: z.object({ pattern: z.string() }).passthrough(), block: grepResourceContent }, + create: { inputSchema: z.object({ path: z.string() }), block: createResource }, + discover: { inputSchema: z.object({}).passthrough(), block: discover }, + peek: { inputSchema: z.object({ uri: z.string() }), block: peek } + } + }); + const instance = flow() as unknown as FlowInstance; + const state = createFlowState({ flows: { docs: instance }, stores: { default: { primary: inMemoryStores() } } }); + const call = async (actionName: string, input: unknown) => { + const runtime = await state.getRuntime(); + const result = await runAction({ + orgId: ORG, + flow: instance, + actionName, + input, + userId: "alice", + sessionId: "s1", + stores: runtime.stores, + runtimeConfig: { ...runtime.runtimeConfig } + }); + return { output: result.output as any, error: result.error === undefined ? undefined : String((result.error as Error).message ?? result.error) }; + }; + return { call, dispose: () => state.dispose() }; +} + +describe("resourceVisibility", () => { + it("hides a resource from listing, search, discovery, reading, writing and an app's own lookup, as if unregistered", async () => { + const { call, dispose } = await boot(narrowing); + try { + expect((await call("read", {})).output.uris).toEqual(["org/handbook", "org/ledger"]); + expect((await call("glob", {})).output.uris).toEqual(["org/handbook", "org/ledger"]); + const grep = (await call("grep", { pattern: "body" })).output.matches.map((m: { uri: string }) => m.uri); + expect([...new Set(grep)].sort()).toEqual(["org/handbook", "org/ledger"]); + const discovered = JSON.stringify((await call("discover", {})).output); + expect(discovered).toContain("org/ledger"); + expect(discovered).not.toContain("org/payroll"); + + // Named, the hidden one answers exactly as a uri nothing registers. + const hidden = await call("read", { uri: "org/payroll" }); + const missing = await call("read", { uri: "org/nothing" }); + expect(hidden.error).toBe(missing.error?.replace("org/nothing", "org/payroll")); + const hiddenWrite = await call("write", { uri: "org/payroll", content: "x" }); + const missingWrite = await call("write", { uri: "org/nothing", content: "x" }); + expect(hiddenWrite.error).toBe(missingWrite.error?.replace("org/nothing", "org/payroll")); + expect((await call("peek", { uri: "org/payroll" })).output).toEqual({ found: false }); + // A hidden collection takes no writes either, and says so as for a path nothing matches. + const hiddenCreate = await call("create", { path: "notes/a" }); + const missingCreate = await call("create", { path: "nowhere/a" }); + expect(hiddenCreate.error).toBe(missingCreate.error?.replace("nowhere/a", "notes/a")); + } finally { + await dispose(); + } + }); + + it("lets a read-only resource be read and refuses its write as for one that isn't writable", async () => { + const { call, dispose } = await boot(narrowing); + try { + expect((await call("read", { uri: "org/handbook" })).output.content).toContain("the handbook body"); + expect((await call("write", { uri: "org/handbook", content: "rewritten" })).error).toBe( + "Writable resource not found for uri: org/handbook" + ); + expect((await call("read", { uri: "org/handbook" })).output.content).toContain("the handbook body"); + // The visible one is written. + expect((await call("write", { uri: "org/ledger", content: "updated" })).error).toBeUndefined(); + expect((await call("read", { uri: "org/ledger" })).output.content).toBe("updated"); + } finally { + await dispose(); + } + }); + + it("changes nothing when the flow sets no rule", async () => { + const { call, dispose } = await boot(undefined); + try { + expect((await call("read", {})).output.uris).toEqual(["org/handbook", "org/ledger", "org/payroll"]); + expect((await call("read", { uri: "org/payroll" })).output.content).toContain("the payroll body"); + expect((await call("write", { uri: "org/handbook", content: "rewritten" })).error).toBeUndefined(); + expect((await call("peek", { uri: "org/payroll" })).output).toEqual({ found: true }); + expect((await call("create", { path: "notes/a" })).error).toBeUndefined(); + } finally { + await dispose(); + } + }); +}); diff --git a/packages/engine/test/session-birth.test.ts b/packages/engine/test/session-birth.test.ts index 3c58b95291..30d1c76a90 100644 --- a/packages/engine/test/session-birth.test.ts +++ b/packages/engine/test/session-birth.test.ts @@ -449,6 +449,31 @@ describe("a dispatch into a key-derived child", () => { expect(calls).toHaveLength(1); }); + it("refuses to adopt a child whose readonly state differs from what this dispatch names", async () => { + // Two workers, one key: adopting the first worker's child for the second + // would run the second as the first, which is a readonly field changing. + const { stores, flow, plain } = boot(); + await hold(stores, "alice", "researcher", "bound"); + await hold(stores, "alice", "editor", "bound"); + const send = (workerId: string) => + seam(stores, plain, flow)({ + type: "internal", action: "work", flowKind: "bound", session: { key: "shared", state: { workerId } }, payload: {}, from: "test" + }); + expect(await send("researcher")).toMatchObject({ ok: true, adopted: false }); + const second = await send("editor"); + expect(second).toMatchObject({ ok: false, refused: "key-occupied" }); + expect(JSON.stringify(second)).toContain("workerId"); + const children = await stores.session.list({ parentage: "all" }); + expect(children.map((child) => child.state.workerId)).toEqual(["researcher"]); + // The same worker again still adopts, and a dispatch that names no state adopts too. + expect(await send("researcher")).toMatchObject({ ok: true, adopted: true }); + expect( + await seam(stores, plain, flow)({ + type: "internal", action: "work", flowKind: "bound", session: { key: "shared" }, payload: {}, from: "test" + }) + ).toMatchObject({ ok: true, adopted: true }); + }); + it("refuses by name when the target refuses the child's state, and writes no child", async () => { const { stores, flow, plain } = boot(); const outcome = await seam(stores, plain, flow)({ From b255c6b58f7e0a49078d1d6a6c9047a139c72872 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 01:40:28 +0000 Subject: [PATCH 03/12] feat(workforce): one copy per worker flow; the per-worker hire, its roster and pins removed (FIX-1788 P4 S7 S8 S10 S11 S14) hireWorkforce(installation) registers one copy of each worker flow and the roster flow, and mints nothing per worker. agent on an installation loads its turn's worker in request.onStarted, keeps each worker's skills drawer apart, narrows each turn's model to the worker's document grants through the installation's resourceVisibility, refuses a turn whose input names a worker, and signs mailbox posts as the turn's worker. The mailbox wake keys each member's conversation by worker and the task lookup births each task's session naming its worker, for standard workers. workerFlow(...) builds a flow kept in its own file on its installation. Removed: the seat-hire capability and blocks, registerHiredSeat, the boot reload and repair, the hired-roster collections, seat addresses and listedSeatRows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- .changeset/workforce-one-copy-per-flow.md | 5 + packages/workforce/src/agent-worker-flow.ts | 142 ++- packages/workforce/src/browser.ts | 7 - packages/workforce/src/hire.ts | 62 +- packages/workforce/src/index.ts | 22 +- .../workforce/src/inventory/listed-seats.ts | 85 -- .../workforce/src/inventory/open-inventory.ts | 23 +- .../src/loader/read-declared-roster.ts | 2 +- .../workforce/src/loader/read-workforce.ts | 2 +- .../workforce/src/mailbox-post-capability.ts | 50 +- .../workforce/src/mailbox/mailbox-flow.ts | 132 +- .../workforce/src/mailbox/route-by-purpose.ts | 19 +- .../src/mailbox/wake-member-seats.ts | 67 +- packages/workforce/src/manifest-sources.ts | 39 +- packages/workforce/src/manifest.ts | 16 - packages/workforce/src/roster/address.ts | 104 -- packages/workforce/src/roster/check.ts | 112 -- packages/workforce/src/roster/collections.ts | 223 ---- packages/workforce/src/roster/incarnation.ts | 58 - packages/workforce/src/roster/index.ts | 65 - packages/workforce/src/roster/locate.ts | 91 -- .../src/roster/register-hired-seat.ts | 52 - packages/workforce/src/roster/reload.ts | 298 ----- packages/workforce/src/roster/remove.ts | 202 --- packages/workforce/src/roster/rows.ts | 286 ----- packages/workforce/src/seat-hire-blocks.ts | 1125 ----------------- .../workforce/src/seat-hire-capability.ts | 219 ---- packages/workforce/src/seat-hire-keys.ts | 44 - packages/workforce/src/seat-packages.ts | 18 +- packages/workforce/src/seat-references.ts | 4 +- packages/workforce/src/seat-resources.ts | 4 +- packages/workforce/src/worker-lookup.ts | 174 +-- packages/workforce/src/workers/index.ts | 9 + .../workforce/src/workers/installation.ts | 105 +- packages/workforce/src/workers/register.ts | 109 ++ .../workforce/src/workers/verified-worker.ts | 81 +- packages/workforce/src/workers/worker-flow.ts | 54 + .../workforce/src/workforce-capability.ts | 7 - .../test/agent-drawer-seeded-worker.test.ts | 4 +- .../test/agent-grants-per-turn.test.ts | 150 +++ .../test/agent-on-installation.test.ts | 114 ++ .../test/agent-resumed-turn-worker.test.ts | 120 ++ .../test/agent-routed-answer.test.ts | 6 +- .../workforce/test/agent-worker-flow.test.ts | 8 +- .../test/agent-worker-history.test.ts | 4 +- .../test/agent-worker-mailbox-post.test.ts | 4 +- .../test/agent-worker-memory.test.ts | 4 +- .../test/agent-worker-own-state.test.ts | 4 +- .../test/agent-worker-user-message.test.ts | 4 +- .../test/browser-subpath-safe.test.ts | 11 +- .../test/cross-org-collection-read.test.ts | 145 +-- .../test/custom-tools-catalog.test.ts | 4 +- .../workforce/test/custom-tools-seat.test.ts | 26 +- .../test/custom-worker-flow-data.test.ts | 114 ++ packages/workforce/test/hire-plane.test.ts | 286 ----- .../test/hire-required-settings.test.ts | 165 --- packages/workforce/test/hire.test.ts | 20 +- ...red-reference-read-only-in-devtool.test.ts | 4 +- .../workforce/test/inventory-binder.test.ts | 19 +- packages/workforce/test/listed-seats.test.ts | 102 -- .../test/mailbox-board-attendance.test.ts | 13 +- .../test/mailbox-board-tools.test.ts | 12 +- .../test/mailbox-post-capability.test.ts | 90 +- packages/workforce/test/mailbox-route.test.ts | 23 +- .../test/mailbox-routing-binder.test.ts | 4 +- .../workforce/test/manifest-sources.test.ts | 35 - packages/workforce/test/org-seats.test.ts | 50 +- .../test/owner-pin-gate-single-source.test.ts | 95 -- .../test/project-talk-template.test.ts | 6 +- .../workforce/test/read-workforce.test.ts | 4 +- .../test/references-convention.test.ts | 44 +- packages/workforce/test/roster-check.test.ts | 121 -- .../test/roster-owner-private.test.ts | 296 ----- packages/workforce/test/roster.test.ts | 654 ---------- .../workforce/test/seat-capabilities.test.ts | 6 +- .../workforce/test/seat-chosen-tools.test.ts | 36 +- .../workforce/test/seat-discovery.test.ts | 4 +- packages/workforce/test/seat-door.test.ts | 55 +- packages/workforce/test/seat-hire-ask.test.ts | 825 ------------ .../workforce/test/seat-hire-blocks.test.ts | 187 --- .../test/seat-hire-capability.test.ts | 440 ------- .../test/seat-hire-interleaving.test.ts | 545 -------- packages/workforce/test/seat-id.test.ts | 286 ----- packages/workforce/test/seat-packages.test.ts | 6 +- packages/workforce/test/seat-repair.test.ts | 1076 ---------------- .../workforce/test/seat-resources.test.ts | 22 +- packages/workforce/test/seat-skills.test.ts | 6 +- .../skills-resolve-from-principal.test.ts | 4 +- .../test/team-instructions-seam.test.ts | 14 +- .../workforce/test/wake-member-seats.test.ts | 107 +- packages/workforce/test/worker-config.test.ts | 6 +- .../test/worker-document-fence.test.ts | 4 +- .../test/worker-flow-registration.test.ts | 143 +-- .../test/worker-registration.test.ts | 122 ++ .../test/worker-task-hand-over.test.ts | 304 ++--- 95 files changed, 1624 insertions(+), 9456 deletions(-) create mode 100644 .changeset/workforce-one-copy-per-flow.md delete mode 100644 packages/workforce/src/inventory/listed-seats.ts delete mode 100644 packages/workforce/src/roster/address.ts delete mode 100644 packages/workforce/src/roster/check.ts delete mode 100644 packages/workforce/src/roster/collections.ts delete mode 100644 packages/workforce/src/roster/incarnation.ts delete mode 100644 packages/workforce/src/roster/index.ts delete mode 100644 packages/workforce/src/roster/locate.ts delete mode 100644 packages/workforce/src/roster/register-hired-seat.ts delete mode 100644 packages/workforce/src/roster/reload.ts delete mode 100644 packages/workforce/src/roster/remove.ts delete mode 100644 packages/workforce/src/roster/rows.ts delete mode 100644 packages/workforce/src/seat-hire-blocks.ts delete mode 100644 packages/workforce/src/seat-hire-capability.ts delete mode 100644 packages/workforce/src/seat-hire-keys.ts create mode 100644 packages/workforce/src/workers/register.ts create mode 100644 packages/workforce/src/workers/worker-flow.ts create mode 100644 packages/workforce/test/agent-grants-per-turn.test.ts create mode 100644 packages/workforce/test/agent-on-installation.test.ts create mode 100644 packages/workforce/test/agent-resumed-turn-worker.test.ts create mode 100644 packages/workforce/test/custom-worker-flow-data.test.ts delete mode 100644 packages/workforce/test/hire-plane.test.ts delete mode 100644 packages/workforce/test/hire-required-settings.test.ts delete mode 100644 packages/workforce/test/listed-seats.test.ts delete mode 100644 packages/workforce/test/owner-pin-gate-single-source.test.ts delete mode 100644 packages/workforce/test/roster-check.test.ts delete mode 100644 packages/workforce/test/roster-owner-private.test.ts delete mode 100644 packages/workforce/test/roster.test.ts delete mode 100644 packages/workforce/test/seat-hire-ask.test.ts delete mode 100644 packages/workforce/test/seat-hire-blocks.test.ts delete mode 100644 packages/workforce/test/seat-hire-capability.test.ts delete mode 100644 packages/workforce/test/seat-hire-interleaving.test.ts delete mode 100644 packages/workforce/test/seat-id.test.ts delete mode 100644 packages/workforce/test/seat-repair.test.ts create mode 100644 packages/workforce/test/worker-registration.test.ts diff --git a/.changeset/workforce-one-copy-per-flow.md b/.changeset/workforce-one-copy-per-flow.md new file mode 100644 index 0000000000..bedcadb8b9 --- /dev/null +++ b/.changeset/workforce-one-copy-per-flow.md @@ -0,0 +1,5 @@ +--- +"@flow-state-dev/workforce": minor +--- + +Every worker runs on one shared copy of the flow it names. `hireWorkforce(installation)` returns one copy of each worker flow and the roster flow (`workforce-roster`, with `hire`, `fork`, `edit` and `fire`), and mints nothing per worker and pins nothing. A worker flow declares `session: installation.session()` and loads its worker each turn; `workerFlow(...)` builds a flow in its own file on its installation, and `installation.resourceVisibility` narrows each turn's model to its worker's document grants. The built-in `agent` on an installation keeps each worker's skills apart, refuses a turn whose input names a worker, and signs its mailbox posts as the turn's worker. The mailbox wake and the task lookup open each session naming its worker, for standard workers only. Removed: `createSeatHireCapability`, `createSeatHireBlocks`, `registerHiredSeat`, `reloadHiredSeats`, the hired-roster collections and keys, `seatAddress`/`splitSeatAddress`, and `listedSeatRows` (FIX-1788). diff --git a/packages/workforce/src/agent-worker-flow.ts b/packages/workforce/src/agent-worker-flow.ts index 1fbd547f1b..efb55ee699 100644 --- a/packages/workforce/src/agent-worker-flow.ts +++ b/packages/workforce/src/agent-worker-flow.ts @@ -81,7 +81,7 @@ import type { ToolCatalog, UsesSlot } from "@flow-state-dev/core"; -import type { BlockContext } from "@flow-state-dev/core/types"; +import type { BlockContext, DeclaredResourceEntry, ResourceVisibilityRule, SessionConfig } from "@flow-state-dev/core/types"; import { activeSkillsArraySchema, createSkillActivator, @@ -102,8 +102,11 @@ import { import { ROUTED_TURN_STATE, answerRoutedPost, + mailboxPostCapability, routedTurnStateSchema, - seatIdConfigSchema + seatIdConfigSchema, + workerIdOfTurn, + workerMailboxPostCapability } from "./mailbox-post-capability"; import { SEAT_PACKAGES_KEY, SEAT_SKILLS_KEY, SEAT_TOOLS_KEY, oneNameMessage } from "./manifest"; import { @@ -118,6 +121,8 @@ import { } from "./seat-capabilities"; import { SEAT_DISCOVER_KEY } from "./seat-discovery"; import { seatSkillSchema, workerConfigSchema } from "./worker-config"; +import { seatConfigOf, verifiedWorkerOf } from "./workers/verified-worker"; +import type { WorkerInstallation } from "./workers/installation"; /** * The kind name the hire step resolves a record to when it names none, and the @@ -230,7 +235,7 @@ function packageCatalogCollisions( * kind registered under `agent` could hand over a config without the key. */ function seatSkillsOf(ctx: BlockContext): InitialSkill[] { - return (ctx.flow.config as Partial | undefined)?.seatSkills ?? []; + return (seatConfigOf(ctx) as Partial).seatSkills ?? []; } /** @@ -239,7 +244,7 @@ function seatSkillsOf(ctx: BlockContext): InitialSkill[] { * off, so anything other than an explicit `true` takes the plain arm. */ function activateToolOn(ctx: BlockContext): boolean { - return (ctx.flow.config as Partial | undefined)?.skills?.activateTool === true; + return (seatConfigOf(ctx) as Partial).skills?.activateTool === true; } /** What the app supplies. Everything else is a worker's own setting. */ @@ -303,13 +308,16 @@ export interface AgentWorkerFlowOptions { */ uses?: UsesSlot; /** - * Give each worker of this kind its own user-scoped storage, instead of one - * cell shared by every worker serving the same person. Default: false, - * matching the framework (BP-027). + * Key this flow's user-scoped storage by the flow copy's id, instead of one + * cell the person's other flows share. Default: false, matching the + * framework (BP-027). * - * Forwarded to the flow untouched. The key is the worker's id, so renaming - * a worker leaves its isolated data behind under the old name — and so does - * flipping this flag on a roster already in use. + * Forwarded to the flow untouched. On an installation every worker runs on + * the one `agent` copy, so its workers still share one cell per person; + * only the skills drawer is kept per worker. On a copy minted for one + * worker, the key is that worker's id, so renaming it leaves its isolated + * data behind under the old name — and so does flipping this flag on a + * roster already in use. * * All-or-nothing for the kind: a roster is either all-isolated or * all-shared, never a mix. Mixing would need each resource to carry its own @@ -349,6 +357,16 @@ export interface AgentWorkerFlowOptions { * Omitted, the kind's sequence is exactly what it is today. */ afterAnswer?: BlockDefinition; + /** + * Run workers as data: one copy of this flow for every worker, each + * session naming its worker when it is created (the installation's create + * check), and each turn loading that worker's configuration before + * anything reads it. The drawer is kept per worker. + * + * Omitted, the flow reads its settings off the copy, as a copy minted for + * one worker does. + */ + installation?: WorkerInstallation; } /** @@ -755,7 +773,13 @@ function catalogDeclaredResources( * @param options What only the app can supply — see {@link AgentWorkerFlowOptions}. * @returns A `defineFlow` result of kind `agent`, cardinality `collection`. */ -export function defineAgentWorkerFlow(options: AgentWorkerFlowOptions = {}) { +export function defineAgentWorkerFlow(given: AgentWorkerFlowOptions = {}) { + // A copy that runs every worker has no `seatId` of its own: its mailbox + // lines are signed by the worker each turn loads. + const options: AgentWorkerFlowOptions = + given.installation === undefined + ? given + : { ...given, uses: given.uses?.map((use) => (use === mailboxPostCapability ? workerMailboxPostCapability : use)) }; const catalog = mergeKindCatalog(options.uses, options.catalog); // Before anything is built from it. A catalog key that disagrees with its // block's own name would hand the model a tool no seat's `tools:` can @@ -770,6 +794,12 @@ export function defineAgentWorkerFlow(options: AgentWorkerFlowOptions = {}) { // declares a store is advertised with nothing behind it. const catalogResources = catalogDeclaredResources(catalog, seatCapabilityCatalog); const settings = settingsSchema({ ...options, catalog }, seatCapabilityCatalog); + /** + * The settings this turn runs with: the configuration of the worker the + * turn resolved, or the copy's own config on a copy minted for one worker. + */ + const turnConfig = (ctx: { readonly session: object; readonly flow?: { readonly config: unknown } }) => + seatConfigOf(ctx) as z.infer; const inputSchema = z.object({ message: z.string() }); /** * The answer's own input: the turn, and on a routed mailbox post the @@ -823,12 +853,19 @@ export function defineAgentWorkerFlow(options: AgentWorkerFlowOptions = {}) { // switched on re-seeds from the new key; the old rows are orphaned, not // lost — BP-030.) collectionConfig: { flowIsolation: true }, + // One drawer per worker on a copy the installation runs every worker on: + // the worker this turn's `resolveWorker` loaded and checked, never a value + // in session state (BP-031). On a copy minted for one worker the drawer + // is the copy's. + ...(options.installation !== undefined + ? { partitionBy: (ctx: BlockContext) => verifiedWorkerOf(ctx.session as object) } + : {}), // The second half of the `tools:` fence. A skill a seat merely HOLDS can // declare `agents:`, and the delegation surface would otherwise seat board // workers — separate generators the `tools:` mapping below never sees — // from the app's whole catalog. The fence is the seat's own list, so a // seat with `tools: []` reaches nothing, delegated or not. - toolSeatFence: (ctx) => (ctx.flow.config as Partial).tools ?? [] + toolSeatFence: (ctx) => (seatConfigOf(ctx) as Partial).tools ?? [] }); // Pinned by the contract (C5): the library plus a per-generator binding. @@ -895,7 +932,7 @@ export function defineAgentWorkerFlow(options: AgentWorkerFlowOptions = {}) { const seatCapabilities = (ctx: BlockContext) => resolveSeatCapabilities( seatCapabilityCatalog, - (ctx.flow.config as Partial | undefined)?.capabilities + (seatConfigOf(ctx) as Partial).capabilities ); const usesEntries = [ ...(options.uses ?? []), @@ -960,11 +997,11 @@ export function defineAgentWorkerFlow(options: AgentWorkerFlowOptions = {}) { // seat holds the package, so its text reads as part of what this seat is // told. The same caveat holds — order, not precedence. prompt: [ - (_input, ctx) => ctx.flow.config.teamInstructions, - (_input, ctx) => ctx.flow.config.instructions, - (_input, ctx) => packageInstructionsOf(ctx.flow.config[SEAT_PACKAGES_KEY]) + (_input, ctx) => turnConfig(ctx).teamInstructions, + (_input, ctx) => turnConfig(ctx).instructions, + (_input, ctx) => packageInstructionsOf(turnConfig(ctx)[SEAT_PACKAGES_KEY]) ], - model: (_input, ctx) => ctx.flow.config.model, + model: (_input, ctx) => turnConfig(ctx).model, // A routed mailbox post's lines before it, for this turn only: the // context slot reaches the model on its own call and is never stored, // so the lines are not kept in the conversation or sent on a later @@ -987,15 +1024,16 @@ export function defineAgentWorkerFlow(options: AgentWorkerFlowOptions = {}) { // package block the line names already resolved onto `seatTools` at the // hire, like a block in the seat's own folder. tools: async (_input, ctx): Promise => { - const listed = ctx.flow.config.tools; + const config = turnConfig(ctx); + const listed = config.tools; const named = listed === undefined ? [ - ...(await selectedPresetTools(seatCapabilityCatalog, ctx.flow.config.capabilities, ctx)), - ...(ctx.flow.config[SEAT_PACKAGES_KEY] ?? []).flatMap((held) => held.tools) + ...(await selectedPresetTools(seatCapabilityCatalog, config.capabilities, ctx)), + ...(config[SEAT_PACKAGES_KEY] ?? []).flatMap((held) => held.tools) ] : listed.map((toolName) => catalog[toolName] as GeneratorTool); - const own = ctx.flow.config[SEAT_TOOLS_KEY] as GeneratorTool[] | undefined; + const own = config[SEAT_TOOLS_KEY] as GeneratorTool[] | undefined; // Materialized only when the seat has both, which is the uncommon case. if (own === undefined || own.length === 0) return named; return named.length === 0 ? own : [...named, ...own]; @@ -1057,7 +1095,7 @@ export function defineAgentWorkerFlow(options: AgentWorkerFlowOptions = {}) { [ACTIVE_SKILLS_STATE.field]: activeSkillsArraySchema }), execute: async (_input, ctx) => { - const names = ctx.flow.config.skills.active; + const names = turnConfig(ctx).skills.active; // The cross-field refusal the mint could not carry — see the note there. assertHeldSkills(names, seatSkillsOf(ctx), appSkills); if (names.length === 0) return { added: 0 }; @@ -1095,9 +1133,31 @@ export function defineAgentWorkerFlow(options: AgentWorkerFlowOptions = {}) { } }); + const installation = options.installation; + /** + * The turn's worker, loaded before anything reads a setting: every read + * below goes through `turnConfig`, which returns this worker's + * configuration once it is loaded. It runs as the flow's request + * `onStarted`, which runs at the start of every run of a request, a resumed + * one included. A step of the turn would not: a resumed request injects a + * completed step's recorded output rather than running it again, so the + * worker would be loaded on the first run only, and a tool that waited for + * a person would be gone when the answer arrived. + */ + const resolveTurnWorker = handler({ + name: "agent-resolve-worker", + inputSchema: z.unknown(), + outputSchema: z.object({ worker: z.string().nullable() }), + ...(installation !== undefined ? { resources: { ...installation.resources } } : {}), + execute: async (_input, ctx) => { + if (installation === undefined) return { worker: null }; + return { worker: (await installation.resolveWorker(ctx, AGENT_KIND)).id }; + } + }); + const answered = sequencer({ name: "agent-run", inputSchema: turnInputSchema, flowConfigSchema: settings }) - .tapIf((_input, ctx) => ctx.flow.config.skills.enableLlmClassifier !== true, matcherWithoutClassifier) - .tapIf((_input, ctx) => ctx.flow.config.skills.enableLlmClassifier === true, matcherWithClassifier) + .tapIf((_input, ctx) => turnConfig(ctx).skills.enableLlmClassifier !== true, matcherWithoutClassifier) + .tapIf((_input, ctx) => turnConfig(ctx).skills.enableLlmClassifier === true, matcherWithClassifier) .tap(appendSeatDefaults) // Two arms rather than two `.stepIf`s: the answer is the sequencer's OUTPUT, // and a second conditional step would have to be typed against the first @@ -1170,7 +1230,8 @@ export function defineAgentWorkerFlow(options: AgentWorkerFlowOptions = {}) { z.object({ answeredAlready: z.literal(true) }) ]), requestStateSchema: routedTurnStateSchema, - flowConfigSchema: seatIdConfigSchema, + // A copy minted for one worker signs as its `seatId`, checked at the mint. + ...(options.installation === undefined ? { flowConfigSchema: seatIdConfigSchema } : {}), execute: async (reply: unknown, ctx) => { // Run only on a routed turn (the `tapIf` below), which is marked. const routed = ctx.request.state.mailboxRoutedPost!; @@ -1179,7 +1240,10 @@ export function defineAgentWorkerFlow(options: AgentWorkerFlowOptions = {}) { mailbox: routed.mailboxId, postId: routed.postId, body: reply, - author: ctx.flow.config.seatId, + author: + options.installation === undefined + ? String((ctx.flow.config as Record).seatId) + : workerIdOfTurn(ctx), ...(routed.answerToken === undefined ? {} : { token: routed.answerToken }) }; } @@ -1222,6 +1286,25 @@ export function defineAgentWorkerFlow(options: AgentWorkerFlowOptions = {}) { const taskTurn = sequencer({ name: "agent-task-turn", inputSchema: taskWorkerInputSchema }) .step((task: TaskWorkerInput) => ({ message: taskMessage(task) }), run); + // On an installation the copy declares every document a worker may be + // granted, and each turn's model reaches only its worker's: the + // installation's visibility rule reads the worker this turn loaded. Typed + // as the optional fields they fill, so the flow's type is one shape either + // way. + const bound: { + session?: SessionConfig; + resources?: Record; + resourceVisibility?: ResourceVisibilityRule; + request?: { onStarted: typeof resolveTurnWorker }; + } = + installation !== undefined + ? { + session: installation.session(), + resources: { ...installation.resources, ...installation.documents }, + resourceVisibility: installation.resourceVisibility, + request: { onStarted: resolveTurnWorker } + } + : {}; const flow = defineFlow({ kind: AGENT_KIND, // Required by contract C2. A plain singleton's seats mint and are then @@ -1232,9 +1315,14 @@ export function defineAgentWorkerFlow(options: AgentWorkerFlowOptions = {}) { // shared across the roster otherwise, which is the framework's default. isolateUserState: options.isolateUserState ?? false, configSchema: settings, + ...bound, // `userMessage` keeps the caller's message as their turn, so a seat's // conversation holds both sides and survives a reload. - actions: { run: { inputSchema, block: run, userMessage: (input) => input.message } }, + // On an installation copy the session names its worker, so a turn whose + // input names one (or carries any other key) is refused, not stripped. + actions: { + run: { inputSchema: installation !== undefined ? inputSchema.strict() : inputSchema, block: run, userMessage: (input) => input.message } + }, // A mailbox's notify block reaches a seat here: a dispatch resolves only // internal entries, so this is never caller-addressed. It runs `run`'s own // sequence, so a seat answers a post exactly as it answers a person; the diff --git a/packages/workforce/src/browser.ts b/packages/workforce/src/browser.ts index 1ca544f85f..b5c9eedf9e 100644 --- a/packages/workforce/src/browser.ts +++ b/packages/workforce/src/browser.ts @@ -12,13 +12,6 @@ * the workspace packages it reaches, and fails on any Node built-in. */ -export { - HIRED_ROSTER_BROWSER_PATTERN, - HIRED_ROSTER_RESOURCE, - SEAT_INVENTORY_RESOURCE -} from "./seat-hire-keys"; -export { seatAddress, splitSeatAddress } from "./roster/address"; -export { isHiredSeatRow, listedSeatRows } from "./inventory/listed-seats"; export { MAILBOX_POST_COMPONENT, mailboxTranscriptLineSchema, diff --git a/packages/workforce/src/hire.ts b/packages/workforce/src/hire.ts index c1552b90ec..e74aaaf1b5 100644 --- a/packages/workforce/src/hire.ts +++ b/packages/workforce/src/hire.ts @@ -29,7 +29,6 @@ import type { DeclaredResourceEntry, FlowInstance, FlowType, - InstanceOwnerPin, OrgConfig, RequestConfig, SessionConfig, @@ -73,6 +72,7 @@ import { import { heldPackageProblems, resolveHeldPackages } from "./seat-packages"; import { recordSeatDescription } from "./seat-description"; import { workerFlowProblems } from "./worker-flow-contract"; +import { isWorkerFlowBuilder, type WorkerFlowBuilder } from "./workers/worker-flow"; /** * The keys the factory itself reads. Everything else is the worker's settings. @@ -101,10 +101,11 @@ const RESERVED_KEYS = [ const builtInAgentWorkerFlow = defineAgentWorkerFlow() as unknown as AnyFlowType; /** - * One entry of {@link HireOptions.workerFlows}: a flow, or a flow and whether - * this app keeps it for declared workers. + * One entry of {@link HireOptions.workerFlows}: a flow, a flow and whether + * this app keeps it for declared workers, or a `workerFlow(...)` builder the + * installation builds on itself. */ -export type WorkerFlowEntry = AnyFlowType | { flow: AnyFlowType; standardOnly?: boolean }; +export type WorkerFlowEntry = AnyFlowType | { flow: AnyFlowType; standardOnly?: boolean } | WorkerFlowBuilder; /** One worker flow as a hire resolves a `flow:` against it. */ export type ResolvedWorkerFlow = { flow: AnyFlowType; standardOnly: boolean }; @@ -125,6 +126,12 @@ export function resolveWorkerFlows( const all: Record = { [AGENT_KIND]: builtInAgentWorkerFlow, ...workerFlows }; const resolved: Record = {}; for (const [name, entry] of Object.entries(all)) { + if (isWorkerFlowBuilder(entry)) { + throw new Error( + `Worker flow "${name}" is a workerFlow(...) builder, which is built on an installation: ` + + `pass it to createWorkerInstallation({ workerFlows }).` + ); + } resolved[name] = typeof entry === "function" ? { flow: entry, standardOnly: false } @@ -156,9 +163,10 @@ function contractProblemsOf(name: string, flow: AnyFlowType): readonly string[] /** * Refuse unless every worker flow meets the contract — every problem with - * every flow in one error, so an author fixes them in one pass. + * every flow in one error, so an author fixes them in one pass. Exported for + * `hireWorkforce` (`workers/register.ts`), not from the package root. */ -function checkWorkerFlows(flows: Record): void { +export function checkWorkerFlows(flows: Record): void { const refused: string[] = []; const problems: string[] = []; for (const name of Object.keys(flows).sort()) { @@ -416,13 +424,11 @@ function minter( id: string; config?: Record; resources?: DeclaredResources; - ownerPin?: InstanceOwnerPin; }) => FlowInstance { return flow as unknown as (options: { id: string; config?: Record; resources?: DeclaredResources; - ownerPin?: InstanceOwnerPin; }) => FlowInstance; } @@ -498,23 +504,24 @@ function resolveDeclaredTools( } /** - * Turn worker records into one configured flow copy each, ordered by id. + * Build the configured flow copy each worker record runs as, ordered by id, + * without registering any of them: what a worker's configuration is checked + * against when it is saved and on every turn (`createWorkerInstallation`). + * The installation's flows are registered once each, by `hireWorkforce`. * - * Every problem is a startup misconfiguration, so every problem throws — but - * they are collected first, so one run names all of them and an author fixes - * them in one pass. Nothing is returned partially: a refusal after a partial - * hire would not be a refusal. + * Every problem throws, but they are collected first, so one call names all + * of them. Nothing is returned partially. * * @param manifests The roster — from the loader, or hand-built. * @param options `workerFlows`: the worker flows the app defined. * Optional — the built-in `agent` flow is always available * underneath, and a flow passed under `agent` replaces it for * every seat. - * @returns One `FlowInstance` per record, ordered by id. Register these. + * @returns One `FlowInstance` per record, ordered by id. Not for registering. * @throws If a worker flow misses the contract (naming every problem with * every flow), or if any record cannot be hired (naming every bad worker). */ -export function hireWorkforce( +export function mintSeats( manifests: WorkerManifest[], options: HireOptions = {} ): FlowInstance[] { @@ -701,15 +708,6 @@ export function hireWorkforce( continue; } - // Standard-only, AFTER the default above: a worker naming no flow is an - // `agent` worker, and it is refused here when `agent` is kept. A hired - // worker is one with an owner pin — a runtime hire or a stored roster row, - // which a `WORKER.md` never sets — so every path that runs a worker meets - // this one check. - if (entry.standardOnly && manifest.ownerPin !== undefined) { - refuse(standardOnlyReason(kind, !Object.hasOwn(manifest.declared, "flow"))); - continue; - } const factory = entry.flow; // The seat's own skills, imposed on EVERY record — loaded or hand-built, @@ -732,7 +730,7 @@ export function hireWorkforce( // `hire` tool, the boot reload) carries it. A hired record's `id` is its // org-qualified address, so it brings the logical id a mailbox's // `members:` lists on `manifest.seatId`; a file record's `id` is that id. - settings[SEAT_ID_KEY] = manifest.seatId ?? manifest.id; + settings[SEAT_ID_KEY] = manifest.id; // The seat's TEAM-level instructions — and **only when the record carries // them**, which is the opposite of the line above and deliberately so. @@ -776,12 +774,10 @@ export function hireWorkforce( // The seat id it was hired as, not a hired seat's org-qualified address: // the same id the reference wall places the seat by. const { held, problems: heldProblems } = resolveHeldPackages( - manifest.seatId ?? manifest.id, + manifest.id, manifest.declared[PACKAGES_KEY], manifest.packages, - packageBlocks, - // Only an address carries the org to peel; a seat id never does. - manifest.seatId === undefined ? manifest.ownerPin?.orgId : undefined + packageBlocks ); const packageProblems = [...heldProblems, ...heldPackageProblems(held, registry)]; if (packageProblems.length > 0) { @@ -871,7 +867,7 @@ export function hireWorkforce( // Placed by the seat id, not the address: a runtime hire answers on an // org-qualified address (`acme.engineering.ada`), and its place in the // tree is the seat id it was hired as (`engineering.ada`). - const placedAs = manifest.seatId ?? manifest.id; + const placedAs = manifest.id; const wall = applyReferenceWall({ seatId: placedAs, declared: manifest.declared[SEAT_REFERENCES_KEY], @@ -899,7 +895,6 @@ export function hireWorkforce( const seat = minter(factory)({ id: manifest.id, config: settings, - ...(manifest.ownerPin !== undefined ? { ownerPin: manifest.ownerPin } : {}), ...(seatResources !== undefined ? { resources: seatResources } : {}) }); minting = false; @@ -990,7 +985,8 @@ export function hireWorkforce( } /** - * The unattended-board sentences `hireWorkforce` prints, as values. + * The unattended-board sentences `hireWorkforce` prints, as values, over the + * copies it registers. * * Hire does not attach boards. A caller that surfaces the same warning on a * tool result (the seat-hire capability) reads them here rather than @@ -1022,7 +1018,7 @@ export function unattendedBoardWarnings( const boardName = boardId.slice(mailboxId.length + 1); warnings.push( `[workforce] mailbox "${mailboxId}" holds board "${boardName}" (ledger "${boardId}"), ` + - `and no flow hired in this ` + + `and no flow registered in this ` + `call declares it. Rows filed there will sit pending until something drains them — ` + `declare the board on the seat that runs the work ` + `(\`resources: { [board.id]: board }\` with \`mailboxBoard("${mailboxId}", "${boardName}")\`), ` + diff --git a/packages/workforce/src/index.ts b/packages/workforce/src/index.ts index db6e77abc9..4d8e3f4fa6 100644 --- a/packages/workforce/src/index.ts +++ b/packages/workforce/src/index.ts @@ -56,32 +56,15 @@ export { AGENT_KIND, defineAgentWorkerFlow, type AgentWorkerFlowOptions } from "./agent-worker-flow"; export { definePersona, type PersonaResourceConfig, type PersonaCollectionConfig } from "./define-persona"; export { createWorkforceCapability, type WorkforceCapabilityOptions } from "./workforce-capability"; -export { - HIRED_ROSTER_PRIVATE_RESOURCE, - HIRED_ROSTER_RESOURCE, - SEAT_INVENTORY_RESOURCE -} from "./seat-hire-keys"; -export { - createSeatHireCapability, - createSeatHireBlocks, - hiredSeatOwnerPinFromRosterOwner, - registerHiredSeat, - SEAT_HIRE_CAPABILITY, - type HiredSeatOwnerPin, - type SeatHireAskData, - type SeatHireAskVerb, - type SeatHireBlocks, - type SeatHireCapabilityOptions, - type SeatHireToolOptions, -} from "./seat-hire-capability"; export { mailboxPostCapability, + workerMailboxPostCapability, MAILBOX_POST_CAPABILITY, POST_TO_MAILBOX_TOOL, postToMailboxInputSchema, type PostToMailboxInput, } from "./mailbox-post-capability"; -export { hireWorkforce, unattendedBoardWarnings, type HireOptions, type WorkerFlowEntry } from "./hire"; +export { unattendedBoardWarnings, type HireOptions, type WorkerFlowEntry } from "./hire"; export { workerFlowProblems } from "./worker-flow-contract"; export { sharedResource, writeShared, type SharedWriteContext, type WrittenBy } from "./shared-resource"; export { WORKER_TASK_ENTRY } from "./worker-task-entry"; @@ -143,6 +126,5 @@ export { export type { WorkerManifest, TeamManifest, ResourceDoc, PackageManifest } from "./manifest"; export * from "./mailbox"; export * from "./inventory"; -export * from "./roster"; export * from "./projects"; export * from "./workers"; diff --git a/packages/workforce/src/inventory/listed-seats.ts b/packages/workforce/src/inventory/listed-seats.ts deleted file mode 100644 index 0df8548ab9..0000000000 --- a/packages/workforce/src/inventory/listed-seats.ts +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Which seat inventory rows a team list shows: a hired seat's row only while - * a roster row of the same incarnation backs it, and a declared seat's row as - * it is. - * - * `fire` removes a hired seat's inventory row, so for a new fire there is - * nothing to hide. This is the read side of that change (BP-030): rows an - * earlier version's fire left behind, and the row a crash between fire's two - * deletes leaves, have no roster row, so they are not listed. Nothing here - * deletes anything; a reader that sweeps rows at start would race a hire in - * another process. - * - * A leaf (BP-019): its only import is the address helpers, so a browser panel - * takes it from `@flow-state-dev/workforce/browser` without the runtime. - */ - -import { seatAddress, splitSeatAddress } from "../roster/address"; - -/** - * Keep the inventory rows a team list should show. - * - * A row is a hired seat's when it says so (`hired: true`); it is listed only - * when a roster row at its address carries the same `incarnation`. The - * incarnation on the inventory row says which hire published it, not that - * the hire is still there: a fire that stopped after deleting the roster row - * leaves the inventory row as it was, and a seat hired again at the address - * carries a new one. A row that says `hired: false` is a declared seat's and - * is listed as it is, even when its team shares the organization's name. A - * row written before rows said where they came from (`hired` null or absent) - * is read by its id's shape: an address in `orgId` (`.`, or - * `.~.`) counts as hired. - * - * Rows from before incarnations: an inventory row that carries none (`null` - * or no field) matches only a roster row whose `incarnation` is `null`, and - * a `null` on only one side matches nothing. - * - * A user-owned hire's row (`.~.`) is backed only by its - * owner's own roster row, which is owner-private: only a reader that has it - * can pass it as `owned`. A browser reader cannot read the owner-private - * roster, so it lists no user-owned hire. - * - * @param orgId The organization the rows were read in. - * @param rows Seat inventory rows, as read, with their `hired` and `incarnation` fields when they carry them. - * @param roster The organization's roster rows a browser can read (their - * `seatId`s and `incarnation`s, `null` for a row from before them), or - * `undefined` when the roster did not load. With no roster, no org hire is listed: a seat the reader can't show - * is hired isn't shown as hired. - * @param owned The reader's own user-owned roster rows, read on the server as - * that user. Omitted, no user-owned hire is listed. - * @returns the rows to list, in the order given. - */ -export function listedSeatRows( - orgId: string, - rows: readonly T[], - roster: readonly { seatId: string; incarnation: string | null }[] | undefined, - owned: readonly { seatId: string; ownerUserId: string; incarnation: string | null }[] = [] -): T[] { - // The incarnation each backed address carries, at the address the canonical - // rules build. A roster row whose seat id they refuse (empty, or starting - // with `~`, the user-owned marker) backs nothing, so an org row can never - // stand in for a user-owned address. - const backing = new Map(); - const back = (seatId: string, ownerUserId: string | null, incarnation: string | null) => { - let address: string; - try { - address = seatAddress(orgId, seatId, ownerUserId); - } catch { - return; - } - backing.set(address, incarnation); - }; - for (const row of roster ?? []) back(row.seatId, null, row.incarnation); - for (const row of owned) back(row.seatId, row.ownerUserId, row.incarnation); - return rows.filter( - (row) => !isHiredSeatRow(orgId, row) || (backing.has(row.id) && backing.get(row.id) === (row.incarnation ?? null)) - ); -} - -/** - * Whether an inventory row is a runtime hire's: what the row says, or, for a - * row that predates `hired`, whether its id is an address in `orgId` (BP-030). - */ -export function isHiredSeatRow(orgId: string, row: { id: string; hired?: boolean | null }): boolean { - return row.hired == null ? splitSeatAddress(orgId, row.id) !== undefined : row.hired; -} diff --git a/packages/workforce/src/inventory/open-inventory.ts b/packages/workforce/src/inventory/open-inventory.ts index 26654dbedd..4187ec0e8f 100644 --- a/packages/workforce/src/inventory/open-inventory.ts +++ b/packages/workforce/src/inventory/open-inventory.ts @@ -45,7 +45,6 @@ import { } from "../mailbox/mailbox-flow"; import type { MailboxManifest } from "../manifest"; import { seatDoorOf } from "../seat-door"; -import { incarnationOf } from "../roster/incarnation"; /** * One registered seat, as the binder needs it. @@ -67,27 +66,11 @@ export interface InventorySeat { * by forgetting them: pass `{}` to say the seat has no door. */ actions: Readonly>; - /** - * The seat's settings, which `hireWorkforce` stamps with its `seatId`. A - * seat whose `seatId` differs from its `id` was hired at runtime (its id is - * an address); one whose `seatId` is its `id` was declared. The row's - * `hired` is read from this; omitted, the row says `null` (unknown). - */ - config?: unknown; -} - -/** `true` for a runtime hire, `false` for a declared seat, `null` when the seat doesn't say. */ -function hiredOf(seat: InventorySeat): boolean | null { - const seatId = - typeof seat.config === "object" && seat.config !== null - ? (seat.config as { readonly seatId?: unknown }).seatId - : undefined; - return typeof seatId === "string" ? seatId !== seat.id : null; } /** What the binder registers: the seats that were hired, and the mailboxes that were opened. */ export interface InventoryRoster { - /** The registered seats. Pass `hireWorkforce(...)`'s result directly. */ + /** The registered seats: `inventorySeats(installation)`, the standard workers with their flows' actions. */ seats: readonly InventorySeat[]; /** The mailbox records — the same ones `mailboxInstances` registered and `openMailboxes` opened. */ mailboxes: readonly MailboxManifest[]; @@ -325,8 +308,8 @@ export async function openInventory( id: seat.id, kind: seat.kind, door: seatDoorOf(seat).door, - hired: hiredOf(seat), - incarnation: incarnationOf(seat) ?? null, + hired: false, + incarnation: null, })), }, userId: options.userId, diff --git a/packages/workforce/src/loader/read-declared-roster.ts b/packages/workforce/src/loader/read-declared-roster.ts index e65957d0e9..67eb5bc51f 100644 --- a/packages/workforce/src/loader/read-declared-roster.ts +++ b/packages/workforce/src/loader/read-declared-roster.ts @@ -148,7 +148,7 @@ export interface DeclaredRoster { * // The refusal line is yours: this library does not decide what is fatal. * throw new Error(roster.problems.map((p) => `${p.layer} ${p.path}`).join(", ")); * } - * const seats = hireWorkforce(roster.workers); + * const flows = hireWorkforce(createWorkerInstallation({ standardWorkers: roster.workers })); */ export async function readDeclaredRoster(root: string): Promise { // Serially, not in parallel. The three share a root that either opens or diff --git a/packages/workforce/src/loader/read-workforce.ts b/packages/workforce/src/loader/read-workforce.ts index 820b06df92..3c15adb119 100644 --- a/packages/workforce/src/loader/read-workforce.ts +++ b/packages/workforce/src/loader/read-workforce.ts @@ -118,7 +118,7 @@ export interface ReadWorkforceResult { * if (errors.length > 0 || skillErrors.length > 0 || teamErrors.length > 0) { * throw new Error("short roster"); * } - * const seats = hireWorkforce(workers, { seatBlocks, packageBlocks }); + * const flows = hireWorkforce(createWorkerInstallation({ standardWorkers: workers, seatBlocks, packageBlocks })); */ export async function readWorkforce(root: string): Promise { const { workers, errors } = await readWorkforceDirectory(root); diff --git a/packages/workforce/src/mailbox-post-capability.ts b/packages/workforce/src/mailbox-post-capability.ts index c6c3514f75..1f33501809 100644 --- a/packages/workforce/src/mailbox-post-capability.ts +++ b/packages/workforce/src/mailbox-post-capability.ts @@ -5,7 +5,7 @@ * Compose it into a worker kind's `uses` and the kind's catalog gains one * tool, `post-to-mailbox`. That is a grant the kind offers, not one a seat * holds: a seat names the tool in its `tools:` before the model can call it, - * the same fence `createSeatHireCapability`'s `hire` sits behind. Posting is an + * the same fence the roster's `hire` sits behind as a tool. Posting is an * effect other people read, so it is never a control every seat holds. * * ## Who the line is from @@ -54,6 +54,7 @@ * before. */ +import { verifiedWorkerOf } from "./workers/verified-worker"; import { defineCapability, dispatcher, handler, sequencer } from "@flow-state-dev/core"; import type { DefinedCapability } from "@flow-state-dev/core"; import { z } from "zod"; @@ -115,6 +116,24 @@ export const routedTurnStateSchema = z.object({ [ROUTED_TURN_STATE]: routedTurnS */ export const seatIdConfigSchema = z.object({ [SEAT_ID_KEY]: z.string().min(1) }); +/** + * The worker a turn on a copy that runs every worker signs as: the one the + * turn loaded with `resolveWorker`. Refuses a turn that loaded none, since a + * line nobody signed can't be posted as a worker. + */ +export function workerIdOfTurn(ctx: { readonly session: object }): string { + const workerId = verifiedWorkerOf(ctx.session); + if (workerId === undefined) throw new Error("This turn loaded no worker, so it can't post as one."); + return workerId; +} + +/** + * Who a line is signed by: `copy`, the `seatId` of a copy minted for one + * worker, checked against the copy's config before the model is offered the + * tool; `worker`, the worker the turn loaded on a copy that runs every worker. + */ +type Signer = "copy" | "worker"; + /** What {@link postAsSeat} is handed: the tool's input, and the seat's name to post under. */ const postAsSeatInputSchema = z.object({ mailbox: z.string(), body: z.string(), author: z.string() }); @@ -192,7 +211,7 @@ export const answerRoutedPost = sequencer({ name: "answer-in-mailbox", inputSche type ToolLine = PostAsSeatInput & { postId?: string; token?: string; as: "answer" | "post" | "answered" }; /** The tool's line as the seat, and what it is against the turn's routed post. */ -const toolLine = handler({ +const toolLineFor = (signer: Signer) => handler({ name: "post-to-mailbox-line", inputSchema: postToMailboxInputSchema, outputSchema: postAsSeatInputSchema.extend({ @@ -201,9 +220,11 @@ const toolLine = handler({ as: z.enum(["answer", "post", "answered"]), }), requestStateSchema: routedTurnStateSchema, - flowConfigSchema: seatIdConfigSchema, + ...(signer === "copy" ? { flowConfigSchema: seatIdConfigSchema } : {}), execute: async (input: PostToMailboxInput, ctx): Promise => { - const line = { ...input, author: ctx.flow.config.seatId }; + const author = + signer === "copy" ? String((ctx.flow.config as Record)[SEAT_ID_KEY]) : workerIdOfTurn(ctx); + const line = { ...input, author }; const routed = ctx.request.state.mailboxRoutedPost; if (routed === undefined || routed.mailboxId !== input.mailbox) return { ...line, as: "post" }; if (routed.handed === true) return { ...line, as: "answered" }; @@ -231,7 +252,7 @@ const toAnswer = (line: ToolLine): AnswerAsSeatInput => ({ * a routed post whose answer the turn has handed over already, nothing and a * note saying so. */ -const postToMailbox = sequencer({ +const postToMailboxFor = (signer: Signer) => sequencer({ name: POST_TO_MAILBOX_TOOL, description: "Post a line to a mailbox you are a member of, under your own name. " + @@ -239,7 +260,7 @@ const postToMailbox = sequencer({ inputSchema: postToMailboxInputSchema, outputSchema: postToMailboxResultSchema, }) - .step(toolLine) + .step(toolLineFor(signer)) .stepIf((line: ToolLine) => line.as === "answer", toAnswer, answerRoutedPost) .stepIf((value: ToolLine | { sessionId: string }) => "as" in value && value.as === "post", toPost, postAsSeat) .map((value: { sessionId: string } | { mailbox: string }) => @@ -264,7 +285,22 @@ const postToMailbox = sequencer({ export const mailboxPostCapability: DefinedCapability = defineCapability({ name: MAILBOX_POST_CAPABILITY, presets: { - tools: { tools: [postToMailbox] }, + tools: { tools: [postToMailboxFor("copy")] }, + default: ["tools"], + }, +}); + +/** + * The same capability for a copy that runs every worker, which has no + * `seatId` of its own: each line is signed by the worker the turn loaded. + * `defineAgentWorkerFlow({ installation })` puts it in place of + * {@link mailboxPostCapability}; an app's own worker flow on an installation + * uses it directly. + */ +export const workerMailboxPostCapability: DefinedCapability = defineCapability({ + name: MAILBOX_POST_CAPABILITY, + presets: { + tools: { tools: [postToMailboxFor("worker")] }, default: ["tools"], }, }); diff --git a/packages/workforce/src/mailbox/mailbox-flow.ts b/packages/workforce/src/mailbox/mailbox-flow.ts index ad1cfb00d9..1271902ccc 100644 --- a/packages/workforce/src/mailbox/mailbox-flow.ts +++ b/packages/workforce/src/mailbox/mailbox-flow.ts @@ -44,10 +44,6 @@ import { resolveMailboxBoard } from "./mailbox-board"; import { emitMailboxPostLine, readMailboxPostLines } from "./mailbox-items"; -import { incarnationOfRow } from "../roster/incarnation"; -import { seatAddress, splitSeatAddress } from "../roster/address"; -import { defineHiredRosterCollection } from "../roster/collections"; -import { INVENTORY_RACE_ATTEMPTS, isWriteConflict } from "../roster/remove"; import { MAILBOX_POST_COMPONENT, mailboxTranscriptLineSchema, @@ -1019,122 +1015,12 @@ const retireMailboxesInputSchema = z.object({ ids: z.array(z.string().min(1)) }) /** What the retirement reports: how many mailbox rows it removed. */ export const inventoryMailboxesRetiredSchema = z.object({ retired: z.number() }); -/** The stored row is not one this boot may replace. */ -class NotTheBootsRow extends Error {} - -/** The stored row moved after the roster was read against it; read both again. */ -class RowMovedSinceRosterRead extends Error {} - -/** - * Whether a boot's row may replace the row stored at its address. - * - * A runtime hire's row (`hired: true`) is replaced by the same hire: a hired - * row carrying the same incarnation (`null` matching only `null`, a row from - * before incarnations). It is also replaced by the hire the roster holds at - * the address now (`rosterIncarnation`), because a row of another incarnation - * is then a hire the roster no longer has: what a fire that stopped between - * its two deletes leaves (FIX-1621). Without that, a replacement hire that - * stopped before publishing its own row could never publish it at a boot, - * and a team list would leave it out on every restart. A boot that read an - * older roster carries an incarnation the roster no longer holds, so it - * still replaces nothing of a newer hire's. - * - * A declared seat's row is replaced only by a declared row, and a boot's - * hired row never replaces it. A row from before `hired` existed is replaced - * by a declared row, and by a hired one as above. - * - * @param rosterIncarnation The incarnation of the roster row at the address, - * read in this attempt; `undefined` when there is none, or when the boot - * cannot read it (a user-owned seat's row is its owner's alone). - */ -function bootMayReplace( - stored: Record, - row: SeatInventoryRow, - rosterIncarnation: string | null | undefined -): boolean { - if (row.hired === true) { - if (stored.hired === false) return false; - const incarnation = row.incarnation ?? null; - return incarnationOfRow(stored) === incarnation || rosterIncarnation === incarnation; - } - return stored.hired !== true; -} - -/** - * The incarnation of the roster row at a hired seat's address, as stored now, - * for {@link bootMayReplace}. `undefined` when the address has no roster row, - * and for a user-owned address (`.~.`), whose roster row - * is owner-private and so not the boot's to read. - * - * As stored now, not as this request first read it: a fire and a replacement - * hire can both land between the two, and a boot judging by the older row - * would put a fired hire's row back over the replacement's. A row deleted - * since it was read throws `resource_deleted`, which the caller takes as - * "not the boot's to write". - */ -async function rosterIncarnationAt( - roster: ResourceCollectionRef, - orgId: string, - address: string -): Promise { - const seatId = splitSeatAddress(orgId, address); - if (seatId === undefined || seatAddress(orgId, seatId) !== address) return undefined; - const current = await roster.getOptional(seatId); - if (current === undefined) return undefined; - return readCommitted(current, (state) => incarnationOfRow(state as Record)); -} - /** - * Write one seat row from a boot's roster, only where it is still the boot's - * to write. - * - * The roster the boot read can be older than the store: during a rolling - * deploy another process may have fired the seat and hired a replacement, or - * dropped a declaration and hired the same address. So the row is created - * only where none was there when this action read the inventory, and - * otherwise replaced only while {@link bootMayReplace} holds. The check runs - * inside the version-checked write, so a row another writer put there since is - * checked again, against a roster read again for that attempt. A row removed - * after it was read is not written back. - * - * @returns whether the row landed. + * Write one seat row from a boot. A seat's row is its standard worker's, the + * same on every process, so a later boot's write replaces an earlier one's. */ -async function publishBootSeatRow( - seats: ResourceCollectionRef, - roster: ResourceCollectionRef, - orgId: string, - row: SeatInventoryRow -): Promise { - for (let attempt = 0; attempt < INVENTORY_RACE_ATTEMPTS; attempt += 1) { - const stored = await seats.getOptional(row.id); - try { - if (stored === undefined) { - await seats.create(row.id, row); - return true; - } - const rosterIncarnation = row.hired === true ? await rosterIncarnationAt(roster, orgId, row.id) : undefined; - const seen = incarnationOfRow(stored.state as Record); - await stored.updateState((current) => { - // The roster was read with `seen` stored. The write's own retry hands - // this a newer row without reading the roster again, so a row of - // another incarnation goes back round the loop for a fresh read of - // both rather than being judged by the older roster. - const now = incarnationOfRow(current); - if (rosterIncarnation !== undefined && now !== seen && now !== (row.incarnation ?? null)) { - throw new RowMovedSinceRosterRead(); - } - if (!bootMayReplace(current, row, rosterIncarnation)) throw new NotTheBootsRow(); - return row; - }); - return true; - } catch (error) { - if (error instanceof NotTheBootsRow) return false; - if (error instanceof RowMovedSinceRosterRead) continue; - if ((error as { code?: unknown }).code === "resource_deleted") return false; - if (!isWriteConflict(error)) throw error; - } - } - throw new Error("the row kept changing under this boot."); +async function publishBootSeatRow(seats: ResourceCollectionRef, row: SeatInventoryRow): Promise { + await seats.upsert(row.id, row); } /** @@ -1187,10 +1073,6 @@ export function inventoryWriterActions(kind: string) { const mailboxes = defineMailboxInventoryCollection(); const memberships = defineMembershipIndexCollection(); const seats = defineSeatInventoryCollection(); - // Read by the seat write only, to tell a fired hire's leftover row from a - // newer hire's (see `bootMayReplace`). Lazy, so the row is read when the - // write asks for it rather than when the request starts. - const roster = { ...defineHiredRosterCollection(), prefetchMode: "lazy" as const }; const registerMailbox = handler({ name: "mailbox-register-in-inventory", @@ -1266,7 +1148,7 @@ export function inventoryWriterActions(kind: string) { name: "inventory-register-seats", inputSchema: registerSeatsInputSchema, outputSchema: inventorySeatsRegisteredSchema, - resources: { seats, roster }, + resources: { seats }, execute: async (input, ctx) => { if (ctx.org === undefined) { throw new Error( @@ -1276,12 +1158,12 @@ export function inventoryWriterActions(kind: string) { ); } - const orgId = ctx.org.identity.orgId ?? ctx.org.identity.id; const problems: string[] = []; let written = 0; for (const row of input.seats) { try { - if (await publishBootSeatRow(ctx.resources.seats, ctx.resources.roster, orgId, row)) written += 1; + await publishBootSeatRow(ctx.resources.seats, row); + written += 1; } catch (error) { problems.push( `seat "${row.id}" — ${error instanceof Error ? error.message : String(error)}` diff --git a/packages/workforce/src/mailbox/route-by-purpose.ts b/packages/workforce/src/mailbox/route-by-purpose.ts index 06bafda30d..966a5b4906 100644 --- a/packages/workforce/src/mailbox/route-by-purpose.ts +++ b/packages/workforce/src/mailbox/route-by-purpose.ts @@ -42,6 +42,8 @@ import { choice, evaluator, handler, sequencer } from "@flow-state-dev/core"; import type { EvaluationModel, FlowInstance } from "@flow-state-dev/core/types"; import { z } from "zod"; import { seatDescription } from "../seat-description"; +import type { WorkerInstallation } from "../workers/installation"; +import { runsWorkersOf } from "../workers/register"; import { boundMailbox } from "./mailbox-flow"; import { emitMailboxRouteRecord } from "./mailbox-items"; import { @@ -67,6 +69,13 @@ export interface RouteByPurposeOptions { * fallback. */ model: string | EvaluationModel; + /** + * The installation whose worker flows run as one copy each: a member that + * is one of its standard workers is routed to by that worker's + * `description:`, on the copy of its flow. The same installation the wake + * is given. + */ + installation?: WorkerInstallation; } /** What the evaluator is asked. */ @@ -123,7 +132,13 @@ export function routeByPurpose(seats: readonly FlowInstance[], options: RouteByP "The package names no default." ); } - const hearing = hearingSeatsById(seats); + const hearing = hearingSeatsById(seats, options.installation); + /** A member's description: its standard worker's on a shared copy, else the minted seat's. */ + const describe = (member: string, seat: FlowInstance): string | undefined => { + if (options.installation === undefined || !runsWorkersOf(seat, options.installation)) return seatDescription(seat); + const described = options.installation.standardWorker(member)?.declared.description; + return typeof described === "string" && described.trim() !== "" ? described : undefined; + }; /** The members this caller can route to, the options, and whether the post's holder is one of them. */ const readCase = handler({ @@ -140,7 +155,7 @@ export function routeByPurpose(seats: readonly FlowInstance[], options: RouteByP const seat = reachableSeat(hearing.get(member) ?? [], ctx); if (seat === undefined) continue; reachable.push(member); - const description = seatDescription(seat); + const description = describe(member, seat); if (description !== undefined) options[member] = description; } const held = request.holder; diff --git a/packages/workforce/src/mailbox/wake-member-seats.ts b/packages/workforce/src/mailbox/wake-member-seats.ts index 079b67f7bd..947fd62a17 100644 --- a/packages/workforce/src/mailbox/wake-member-seats.ts +++ b/packages/workforce/src/mailbox/wake-member-seats.ts @@ -38,6 +38,10 @@ import type { BlockContext, BlockDefinition, FlowInstance } from "@flow-state-de import { z } from "zod"; import { SEAT_ID_KEY } from "../manifest"; import { WORKER_ID_STATE_KEY } from "../workers/keys"; +import { AGENT_KIND } from "../agent-worker-flow"; +import type { WorkerInstallation } from "../workers/installation"; +import { runsWorkersOf } from "../workers/register"; +import { standardWorkerFlow } from "../workers/standard-workers"; import { mailboxNotifyInputSchema, type MailboxNotifyInput } from "./mailbox-flow"; /** The internal entry a seat's kind declares to hear a mailbox's posts. */ @@ -51,6 +55,14 @@ export interface WakeMemberSeatsOptions { * gets. Never for a member the wake would have run. Silent when omitted. */ fallback?: BlockDefinition; + /** + * The installation whose worker flows run as one copy each. A copy passed + * in `seats` that declares this installation's session hears posts for + * every standard worker on its flow: a member naming that worker wakes it, + * in a conversation of its own, created naming the worker. A user's own + * worker isn't woken as a member. + */ + installation?: WorkerInstallation; } /** What a member gets when nothing is delivered to it. */ @@ -76,14 +88,25 @@ function seatIdOf(seat: FlowInstance): string { * The seats that can hear a post, grouped by the logical id a mailbox's * `members:` names them by. The wake's test of who can be woken, shared with * `routeByPurpose` so a route never offers a member the wake would not run. - * Not re-exported from the package root. + * A copy that runs an installation's workers hears posts for each standard + * worker on its flow, under that worker's id. Not re-exported from the + * package root. */ -export function hearingSeatsById(seats: readonly FlowInstance[]): Map { +export function hearingSeatsById( + seats: readonly FlowInstance[], + installation?: WorkerInstallation +): Map { const byId = new Map(); + const add = (id: string, seat: FlowInstance) => byId.set(id, [...(byId.get(id) ?? []), seat]); for (const seat of seats) { if (!hearsPosts(seat)) continue; - const seatId = seatIdOf(seat); - byId.set(seatId, [...(byId.get(seatId) ?? []), seat]); + if (installation !== undefined && runsWorkersOf(seat, installation)) { + for (const worker of installation!.standardWorkers()) { + if (standardWorkerFlow(worker, AGENT_KIND) === seat.kind) add(worker.id, seat); + } + continue; + } + add(seatIdOf(seat), seat); } return byId; } @@ -122,28 +145,36 @@ export function wakeMemberSeats( ): BlockDefinition { const fallback = options.fallback ?? silent; - // One dispatcher per seat that can hear a post, grouped by logical id. - const hearing = hearingSeatsById(seats); - const wakes = new Map>(); - for (const seat of [...hearing.values()].flat()) { + // One dispatcher per (seat, member) that can hear a post. A seat minted + // for one worker has one member; a copy that runs every worker of a flow + // has one per standard worker on it. + const hearing = hearingSeatsById(seats, options.installation); + const wakes = new Map>(); + const wakeKey = (seat: FlowInstance, member: string) => `${seat.id}\u0000${member}`; + for (const [member, group] of hearing) { + for (const seat of group) { + const shared = options.installation !== undefined && runsWorkersOf(seat, options.installation); + const worker = shared ? member : seatIdOf(seat); wakes.set( - seat, + wakeKey(seat, member), dispatcher({ - name: `wake-${seat.id}`, + name: shared ? `wake-${seat.id}-${member}` : `wake-${seat.id}`, flowKind: seat.id, action: MAILBOX_POST_ENTRY, inputSchema: mailboxNotifyInputSchema, - // One conversation per seat per mailbox, adopted on every post after the first. - // The worker is named when the conversation is created, from the seat - // this code chose, never the post's fields: a worker flow's create - // check confirms it (FIX-1788 BR-18). A conversation that exists keeps - // its own. + // One conversation per worker per mailbox, adopted on every post after + // the first. The worker is in the key as well as the state: on a copy + // several workers share, a key without it would hand the second + // worker the first one's conversation, which the engine refuses. The + // worker is named from the seat this code chose, never the post's + // fields, and a worker flow's create check confirms it (FIX-1788 BR-18). session: { - key: (post: MailboxNotifyInput) => `mailbox:${post.mailboxId}`, - state: { [WORKER_ID_STATE_KEY]: seatIdOf(seat) } + key: (post: MailboxNotifyInput) => `mailbox:${post.mailboxId}:${worker}`, + state: { [WORKER_ID_STATE_KEY]: worker } } }) ); + } } /** @@ -152,7 +183,7 @@ export function wakeMemberSeats( */ const wakeFor = (member: string, ctx: BlockContext): BlockDefinition | undefined => { const seat = reachableSeat(hearing.get(member) ?? [], ctx); - return seat === undefined ? undefined : wakes.get(seat); + return seat === undefined ? undefined : wakes.get(wakeKey(seat, member)); }; const routes = [...wakes.values(), silent]; diff --git a/packages/workforce/src/manifest-sources.ts b/packages/workforce/src/manifest-sources.ts index 50107be926..ac3a18f69a 100644 --- a/packages/workforce/src/manifest-sources.ts +++ b/packages/workforce/src/manifest-sources.ts @@ -53,7 +53,6 @@ import { resolveResourceCollection } from "@flow-state-dev/orchestration"; import { isTalkTemplate } from "./mailbox/mailbox-binder"; import type { MailboxManifest, WorkerManifest } from "./manifest"; import type { MailboxInventoryRow, SeatInventoryRow } from "./inventory/collections"; -import { hiredSeatManifestFromStored } from "./roster/rows"; /** * The declared half, as the sources need it — a structural subset of @@ -92,15 +91,6 @@ export interface WorkforceManifestSourceOptions { roster: DeclaredWorkforce; /** Where the live rows are mounted. A domain with no key gets no source. */ inventory: InventoryKeys; - /** - * Registry key for the durable hired roster (`defineHiredRosterCollection`). - * - * When named, a roster row with no file is the declared half for that seat - * — so Discover sees a runtime hire the same way it sees a file-declared - * one (FIX-1526). Omitted, only the boot-resolved file tree is declared, - * which is the ordinary state for an app that does not hire at runtime. - */ - hiredRoster?: string; } /** @@ -123,14 +113,6 @@ function purposeOf( return `The ${noun} "${id}". Its file declares no description.`; } -/** - * The org this discover call runs under, from the verified principal. - */ -function orgOf(ctx: BlockContext): string | undefined { - const orgId = ctx.org?.identity.orgId ?? ctx.org?.identity.id; - return typeof orgId === "string" && orgId.length > 0 ? orgId : undefined; -} - /** * List one collection's rows, or throw a message naming the key. * @@ -184,30 +166,13 @@ async function listRows( function seatsSource( roster: DeclaredWorkforce, key: string, - hiredRosterKey?: string, ): BlockManifestSource { const files = new Map(roster.workers.map((worker) => [worker.id, worker])); return { domain: "seats", origin: "createWorkforceCapability", entries: async (ctx: BlockContext): Promise => { - const declared = new Map(files); - if (hiredRosterKey !== undefined) { - const orgId = orgOf(ctx); - if (orgId !== undefined) { - for (const stored of await listRows(ctx, hiredRosterKey, "hired roster")) { - // One bad row is one skip, as in `reloadHiredSeats` — which names - // each skipped row in its `problems`. Discover skips silently: a - // row it cannot list is simply not a seat here. - const record = hiredSeatManifestFromStored(orgId, stored.state); - if ("problem" in record) continue; - if (!declared.has(record.manifest.id)) { - declared.set(record.manifest.id, record.manifest); - } - } - } - } - + const declared = files; const entries: ManifestEntry[] = []; for (const row of await listRows(ctx, key, "seats")) { // A row that lost its required fields reads back empty rather than @@ -298,7 +263,7 @@ export function workforceManifestSources( ): BlockManifestSource[] { const sources: BlockManifestSource[] = []; if (options.inventory.seats !== undefined) { - sources.push(seatsSource(options.roster, options.inventory.seats, options.hiredRoster)); + sources.push(seatsSource(options.roster, options.inventory.seats)); } if (options.inventory.mailboxes !== undefined) { sources.push(mailboxesSource(options.roster, options.inventory.mailboxes)); diff --git a/packages/workforce/src/manifest.ts b/packages/workforce/src/manifest.ts index d90d51cc42..fb22578440 100644 --- a/packages/workforce/src/manifest.ts +++ b/packages/workforce/src/manifest.ts @@ -11,7 +11,6 @@ */ import type { InitialSkill } from "@flow-state-dev/core"; -import type { InstanceOwnerPin } from "@flow-state-dev/core/types"; /** * One worker, as declared on disk or hand-built. Declared once, in this module; the loader @@ -83,21 +82,6 @@ export interface WorkerManifest { * libraries, only the ones its file names in `packages:`. */ packages?: PackageManifest[]; - /** - * Set by a hire row, never by a `WORKER.md`. Absent, the minted instance - * stays shared — a file-declared seat and a shared app flow. Present, the - * mint copies it onto the instance, and registration stores it as the pin. - * Not parsed from {@link WorkerManifest.id}. - */ - ownerPin?: InstanceOwnerPin; - /** - * The seat's logical id, as a mailbox's `members:` lists it: `"."` - * for a team seat, the bare `""` for an org seat. - * Set by a hire row, never by a `WORKER.md`. Absent, the hire uses - * {@link WorkerManifest.id}, which on a file record is that id. A hired - * record's `id` is its org-qualified address, so the row carries this. - */ - seatId?: string; } /** diff --git a/packages/workforce/src/roster/address.ts b/packages/workforce/src/roster/address.ts deleted file mode 100644 index 120435d3d3..0000000000 --- a/packages/workforce/src/roster/address.ts +++ /dev/null @@ -1,104 +0,0 @@ -/** - * A runtime-hired seat's address: built from an org and a seat id, and split - * back into the seat id. - * - * Split out of `rows.ts`, which re-exports both, so a browser panel can - * resolve an address without the roster's collection definitions (and through - * them the `@flow-state-dev/core` root). A leaf on purpose (BP-019): the only - * import is `@flow-state-dev/core/types` (kept free of Node built-ins by - * `test/browser-subpath-safe.test.ts`). - * `@flow-state-dev/workforce/browser` re-exports - * {@link splitSeatAddress} from here. - */ - -import { encodeUserSegment, isValidOrgId } from "@flow-state-dev/core/types"; - -/** - * The address a runtime-hired seat answers on. - * - * Org-visible: `.`. User-owned: `.~.`, with - * the user escaped. `ownerUserId` comes from the hire row. Nothing here - * reads a pin out of an address that was already built. - * - * Any org id the principal carries is accepted (`org_acme`, the framework's - * `__fsd_default_org__`). It is escaped the way the user segment is, by - * {@link orgSegment}, so the leading segment carries no `.` — which is what - * makes the join injective and therefore reversible by {@link splitSeatAddress}. - * An org already spelled in lowercase letters, digits and hyphens escapes to - * itself, so its addresses read as `.`. The seat id keeps its own - * shape: dotted for a team seat (`"."`), bare for an org seat - * (`""`). Only the leading segment has to be dot-free. - * - * @throws when the org id is empty, whitespace-only, or not well-formed - * Unicode (a lone UTF-16 surrogate; see `isValidOrgId`), or when the seat id - * is empty or starts with `~` (that marker is the user-owned form). - */ -export function seatAddress( - orgId: string, - seatId: string, - ownerUserId?: string | null, -): string { - const org = orgSegment(orgId); - if (seatId.length === 0) { - throw new Error("A seat id must not be empty — it is half of the seat's address"); - } - if (seatId.startsWith("~")) { - throw new Error( - `seat id "${seatId}" starts with "~", which marks a user-owned seat's address`, - ); - } - if (ownerUserId != null && ownerUserId.length > 0) { - return `${org}.~${encodeUserSegment(ownerUserId)}.${seatId}`; - } - return `${org}.${seatId}`; -} - -/** - * An org id as the leading segment of a seat's address: the user segment's - * escape, applied to the org. Not `validateSegment`: that rule is for names - * on disk (team, worker and mailbox folders), which an author chooses. A - * runtime org id comes from the principal, is opaque, and so is escaped - * rather than validated. Lowercase letters, digits and `-` pass through; - * every other character (`_`, `.`, `%`, upper case) is percent-encoded, so the - * result holds no `.` and two org ids never share one. - * - * @throws when the org id is empty, whitespace-only, or not well-formed - * Unicode (a lone UTF-16 surrogate), the ids `isValidOrgId` refuses. - */ -function orgSegment(orgId: string): string { - if (orgId.length === 0) { - throw new Error("An organization id must not be empty — it is the first half of a seat's address"); - } - // `isValidOrgId` refuses these at the principal; checked again here because - // the escape is injective only on well-formed strings (a lone surrogate - // encodes as U+FFFD, the same bytes as a real U+FFFD). - if (!isValidOrgId(orgId)) { - throw new Error(`Organization id ${JSON.stringify(orgId)} is not a usable organization id`); - } - return encodeUserSegment(orgId); -} - -/** - * The seat id inside an address this org owns, or `undefined` — including - * for an org id `seatAddress` would refuse. Never throws. - * - * One split at the first dot, which is correct only because the escaped org - * holds no dot. A user-owned address is `.~.`; the user - * segment is skipped and is not returned as an owner. The pin stays on the - * hire row. - */ -export function splitSeatAddress(orgId: string, address: string): string | undefined { - // No address is under an org id `seatAddress` refuses (empty, whitespace-only, - // a lone surrogate), so answer that rather than throwing. - if (!isValidOrgId(orgId)) return undefined; - const prefix = `${orgSegment(orgId)}.`; - if (!address.startsWith(prefix)) return undefined; - const rest = address.slice(prefix.length); - if (rest.startsWith("~")) { - const dot = rest.indexOf("."); - if (dot <= 1 || dot === rest.length - 1) return undefined; - const seatId = rest.slice(dot + 1); - return seatId.length > 0 ? seatId : undefined; - } - return rest.length > 0 ? rest : undefined; -} diff --git a/packages/workforce/src/roster/check.ts b/packages/workforce/src/roster/check.ts deleted file mode 100644 index beca393ddf..0000000000 --- a/packages/workforce/src/roster/check.ts +++ /dev/null @@ -1,112 +0,0 @@ -/** - * The one answer to "does this stored row become a seat, and if not, why?". - * - * The boot reload asks it of every row, and `brokenSeats` asks it on request. - * Two callers, one check: a second detector would drift from the start's own - * refusals, and then the list a person repairs from would not be the list the - * start skips. - * - * Three reasons, and they are a public surface (the chief of staff and the - * epic's closure read them by name): - * - * - `unreadable` — the row does not parse, is stamped for another - * organization, or cannot be an address. Retiring it is its only repair. - * - `kind-gone` — the row names a kind the app no longer carries. Decided - * before anything is minted, so a cut kind is never handed to the hire. - * - `refused` — the kind is carried, and the hire refuses the row (most - * often, settings the kind's schema no longer accepts; or a flow the - * app now keeps for declared workers, which a stored row, a - * hired worker, can't run on). - * - * The detail is the start's own wording, unchanged: the reload prints it after - * the organization and row, and `brokenSeats` hands it back as `detail`. - * - * Nothing here writes. A row that fails is left exactly as it is on disk. - */ - -import type { FlowInstance } from "@flow-state-dev/core/types"; -import { readDeclaredFlow } from "../declared-flow"; -import { AGENT_KIND } from "../agent-worker-flow"; -import { hireWorkforce, missingWorkerFlowRefusal, resolveWorkerFlows, type HireOptions } from "../hire"; -import type { HiredSeatRow } from "./collections"; -import { hiredSeatManifestFromStored, keyMismatch, parseHiredSeatRow } from "./rows"; -import { tagIncarnation } from "./incarnation"; - -/** Why a stored row does not become a seat. Pinned names; see the file header. */ -type BrokenSeatReason = "kind-gone" | "refused" | "unreadable"; - -/** One stored row, checked. */ -type HiredSeatRowCheck = - | { ok: true; row: HiredSeatRow; seat: FlowInstance } - | { - ok: false; - reason: BrokenSeatReason; - /** The start's own sentence for why the row was skipped. */ - detail: string; - /** The parsed row, when it parsed. Absent for an `unreadable` row that did not. */ - row?: HiredSeatRow; - }; - -function messageOf(error: unknown): string { - return error instanceof Error ? error.message : String(error); -} - - -/** - * Check one stored roster value, read under `orgId`, against the app's worker flows. - * - * @param orgId The organization whose cell the value was read from. - * @param stored The stored state, as the store returned it. - * @param workerFlows The app's worker flows, the same map the reload and the hire take. - * @param key The storage key the value was read under, when the caller has - * it. A row whose `seatId` is not the key's last segment is `unreadable`: - * routed by its envelope, a repair of it would act on whatever row the - * envelope's seat id names, and by its key, on an address the row disowns. - * @returns the seat it mints to, or the reason and detail it does not. Never throws. - */ -export function checkHiredSeatRow( - orgId: string, - stored: unknown, - workerFlows: HireOptions["workerFlows"], - key?: string -): HiredSeatRowCheck { - // The row is parsed for its fields, and the record is read through the same - // walk the reload uses (which parses again) so the two can't disagree on - // which rows count. One small row, read on demand; not worth a second walk. - const parsed = parseHiredSeatRow(stored); - if ("problem" in parsed) return { ok: false, reason: "unreadable", detail: parsed.problem }; - const row = parsed.row; - const mismatch = key === undefined ? undefined : keyMismatch(key, row.seatId); - if (mismatch !== undefined) return { ok: false, reason: "unreadable", detail: mismatch, row }; - const record = hiredSeatManifestFromStored(orgId, stored); - if ("problem" in record) return { ok: false, reason: "unreadable", detail: record.problem, row }; - - // The kind, resolved by the rule the hire itself uses, before any mint. - const declared = readDeclaredFlow(record.manifest.declared, AGENT_KIND); - if ("kind" in declared && !Object.hasOwn(resolveWorkerFlows(workerFlows), declared.kind)) { - return { - ok: false, - reason: "kind-gone", - detail: missingWorkerFlowRefusal(record.manifest.id, declared.kind, workerFlows), - row, - }; - } - - // One manifest per call: `hireWorkforce` refuses its whole batch over one - // bad record, so a batch would turn one stale row into no seats at all. - try { - // One record in, and a hire that did not throw returns one seat per record. - const seat = hireWorkforce([record.manifest], { workerFlows })[0]!; - // The seat carries the row's incarnation, so whoever registers it (the - // boot, a repair) can later tell it from another seat at the address. - tagIncarnation(seat, row.incarnation); - return { ok: true, row, seat }; - } catch (error) { - return { - ok: false, - reason: "refused", - detail: messageOf(error), - row, - }; - } -} diff --git a/packages/workforce/src/roster/collections.ts b/packages/workforce/src/roster/collections.ts deleted file mode 100644 index bf1485c7ba..0000000000 --- a/packages/workforce/src/roster/collections.ts +++ /dev/null @@ -1,223 +0,0 @@ -/** - * The hired roster — one org-scoped row per seat hired while the app was - * running, at `workforce/roster/*`. - * - * This is the durable half of a runtime hire. A `WORKER.md` file declares a - * seat and the boot reads it; a hire that happens after the boot has no file - * to be written into, so it is written here instead, and the next boot reads - * it back through the same door the hire went through. - * - * **Not the seat inventory, and deliberately beside it rather than inside it.** - * `inventory/seats/*` answers *was registered in this org*, and its boot binder - * never deletes a row — which is right for browsing and wrong for a roster, - * because firing a seat has to remove it. Two contracts, two collections; they - * join on the seat id and nothing else. A runtime hire writes both: the roster - * row is who was hired, the inventory row is *was registered here*. Fire - * (`removeHiredSeat`) deletes the roster row first, then the seat's inventory - * row; a row an earlier fire left in the inventory has no roster row, and a - * team list that joins the two (`listedSeatRows`) hides it. Discover joins - * file ∪ roster against inventory. - * - * These keys are a public surface on the same terms the inventory's are: - * moving the prefix breaks every deployment that has already hired. - */ - -import { defineResourceCollection } from "@flow-state-dev/core"; -import { z } from "zod"; -import { HIRED_ROSTER_BROWSER_PATTERN } from "../seat-hire-keys"; - -/** - * One hired seat, as it is stored. - * - * **The envelope is closed when read, kept whole when stored; `settings` is - * passthrough.** The envelope's keys are this package's to version, so this - * schema declares all of them and a parse (`parseHiredSeatRow`) hands back - * only those: logic never acts on a key it has no name for. But rows ARE - * read-modify-written — a re-hire replaces the row, and the fence a hire or - * re-hire runs before each side effect is itself a version-checked write — so - * the collections store through `storedHiredSeatRowSchema`, which passes - * unknown envelope keys through, and every rewrite starts from the stored row - * (`{ ...current, ... }`). A key a newer version added survives an older - * version's rewrite. - * - * `settings` is the opposite case and gets the opposite rule (BP-030). That - * bag belongs to the flow kind's own `configSchema`, which is free to grow - * keys this package has never heard of, so it is stored and handed back - * untouched. Typing it as a closed shape — or letting a strip run over it — - * would silently thin a seat's configuration on the first reload after a kind - * gained a setting, and the seat would come back running on defaults with - * nothing said. - * - * `seatId` and `flow` are required rather than defaulted, the same call the - * seat inventory makes for the same reason: a row that lost either is not a - * thinner row, it is a row that cannot be turned back into a seat, and a - * default of `""` would look structurally fine and mint nothing. - */ -export const hiredSeatRowSchema = z.object({ - /** - * The seat's id within its org — `"support.ada"` for a team seat - * (`"."`), or a bare `""` for a seat on no team; the org - * is NOT part of it. The address is - * built by joining the two, which is why the ORG is the segment that has to - * be dot-free (see `seatAddress`). - */ - seatId: z.string().min(1), - /** The flow kind this seat was hired into — what a `WORKER.md` spells `flow:`. */ - flow: z.string().min(1), - /** - * The settings bag handed to the kind, verbatim. Passthrough — see the - * schema's own note above. - */ - settings: z.record(z.unknown()).default({}), - /** - * The seat's instructions — what a file-declared seat carries in its - * Markdown body. Nullable with a `null` default (BP-023), so a reader - * `== null`-guards it rather than parsing `""`, and so a row written before - * a seat had instructions still reads. - */ - instructions: z.string().nullable().default(null), - /** - * The organization this hire belongs to. `null` — the default — is a row - * written before the field existed (BP-023, BP-030). A reload then binds - * the cell the row was stored in. A present value that disagrees with that - * cell is refused rather than stripped or re-bound. - */ - owningOrgId: z.string().nullable().default(null), - /** - * The user this hire belongs to. `null` means every member of the owning - * org may see it. A user-owned hire sets the caller. Independent of - * `owningOrgId`: matching one does not imply the other. - */ - ownerUserId: z.string().nullable().default(null), - /** - * Set while a `rehire` that wrote this row has not yet registered the seat - * and published its inventory row; cleared once it has. A re-hire run again - * finishes only a row that carries it, so a working seat is never taken for - * an unfinished repair. `null` — the default — on every other row, and on a - * row written before the field existed (BP-023, BP-030). Server-side only: - * not in the browser projection. - */ - pendingRepair: z.string().nullable().default(null), - /** - * The incarnation this row brought into being (see `incarnation.ts`): a - * fresh id on every hire and re-hire, stamped on the inventory row it - * publishes and the seat minted from it. `null` on a row written before the - * field (BP-023, BP-030), or by a writer that doesn't stamp one. - * Published to browsers by the org collection, beside `seatId`, `flow` and - * `instructions`, so a browser can join a roster row to its inventory row. - */ - incarnation: z.string().nullable().default(null), -}); - -/** One stored roster row. @see hiredSeatRowSchema */ -export type HiredSeatRow = z.infer; - -/** - * The roster collections' `stateSchema`: {@link hiredSeatRowSchema} with - * unknown envelope keys passed through, so a key a newer version stored is - * not dropped when this version rewrites the row. Browser reads are unaffected: - * the org collection's `expose` list names what a browser sees. - */ -const storedHiredSeatRowSchema = hiredSeatRowSchema.passthrough(); - -/** The collection's storage prefix, without its wildcard. Pinned; see the file header. */ -export const HIRED_ROSTER_PREFIX = "workforce/roster/"; - -// The org roster's browser pattern lives in the leaf `../seat-hire-keys` so -// the `./browser` entry can export it without this module's core import. -export { HIRED_ROSTER_BROWSER_PATTERN }; - -/** - * The pattern of a user-owned roster row. Two segments, no browser read. - * `defineHiredRosterPrivateCollection` declares it owner-private on its - * `owner` parameter, which is what keeps each row with the user it belongs to. - * Pinned; see the file header. - */ -export const HIRED_ROSTER_PRIVATE_PATTERN = "workforce/roster/[owner]/[seat]"; - -/** - * `flowIsolation: false`, spelled out rather than left to the flow-level flag, - * for exactly the reason the inventory spells it out: left undefined, an app - * that sets `isolateOrgState` for an unrelated reason would give the hiring - * flow a private roster, and every other flow — including the boot reload — - * would read empty with nothing at this layer saying why. - */ -const SHARED_ACROSS_FLOWS = false; - -/** - * The hired roster — one row per runtime-hired seat, at `workforce/roster/*`. - * - * Install it under the block that does the hiring. Org-scoped: every flow in - * the org reads the same rows, and a flow under a different `orgId` reads - * none, which is what makes two orgs able to hold a seat of the same name. - * - * Takes no options. The prefix, the scope and the sharing are the contract the - * boot reload joins against, not app settings. - * - * **Write a row with `create()`, never `upsert()` or `getOrCreate()`.** - * `create()` throws when the key already exists, and that throw *is* the - * refusal of a second hire of the same seat — including two arriving at once, - * with no lock and no check of your own. The seat inventory next door writes - * with `upsert`, so the wrong one is a single copy-paste away and it loses the - * refusal without any sign that it did. - * - * @example - * resources: { roster: defineHiredRosterCollection() } - */ -export function defineHiredRosterCollection() { - return defineResourceCollection({ - pattern: HIRED_ROSTER_BROWSER_PATTERN, - scope: "org", - flowIsolation: SHARED_ACROSS_FLOWS, - stateSchema: storedHiredSeatRowSchema, - // A browser may read these rows. Without it the collection-state route - // refuses every read with `403 State read not permitted`, and a roster - // panel has no way to name the org's seats — an action's return value has - // no path to the browser, so `readBoard`-style workarounds do not exist. - // - // What this opens is exactly the ORG's rows and no other org's, because - // the read resolves against the session's `orgId` and a session binds to - // its principal's org (`handleCreateSession` ignores `body.orgId` - // entirely). The axis is `scope`, not `flowIsolation`: an org-scoped - // resource is shared within the org by definition, so opening it to that - // org's own members reveals nothing they could not already be told. A - // USER-scoped collection would not get this — see - // `cross-org-collection-read.test.ts`, which fails if the boundary moves. - // - // `expose` rather than the identity default (BP-015), and `settings` is - // the key it leaves out. That bag is passthrough by contract — the flow - // kind's own `configSchema` owns it and is free to grow keys this package - // has never heard of, which is exactly the shape that should not be - // broadcast to every browser in the org. What a roster panel needs is who - // the seat is, not how it was configured. The other three are the seat's - // identity and are what "a user can see the workers in their org" means. - // `incarnation` is an opaque id the seat's inventory row publishes too; a - // team list matches the two by it (`listedSeatRows`). - client: { - state: { read: true }, - expose: ["seatId", "flow", "instructions", "incarnation"], - }, - }); -} - -/** - * The server-side writer for a user-owned roster row. - * - * Same store, nested key `~user/seat`. The browser collection's single - * segment does not match it, and this collection has no browser read. It is - * owner-private on `owner`: a row keyed `ownerSegment(userId)` there is - * served only to that user, in every process over the store, and no other - * collection reads or writes it. A block that holds the ref still only - * reaches the session user's own rows. Once a flow declaring it registers, - * the app refuses any other org-scoped collection whose pattern can reach - * those rows, such as `workforce/roster/**` or a copy of this pattern. - */ -export function defineHiredRosterPrivateCollection() { - return defineResourceCollection({ - pattern: HIRED_ROSTER_PRIVATE_PATTERN, - ownerPrivate: { param: "owner" }, - scope: "org", - flowIsolation: SHARED_ACROSS_FLOWS, - stateSchema: storedHiredSeatRowSchema, - }); -} diff --git a/packages/workforce/src/roster/incarnation.ts b/packages/workforce/src/roster/incarnation.ts deleted file mode 100644 index b56fd9b32a..0000000000 --- a/packages/workforce/src/roster/incarnation.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** - * A hired seat's incarnation: one id per roster-row write that brings a seat - * into being (a hire, a re-hire), stamped on that roster row, on the inventory - * row it publishes, and on the seat minted from it. - * - * It is what ties a side effect to the seat it belongs to. An address is - * reused: a seat fired and hired again answers on the same one, and a declared - * seat can sit at it too. So every side effect on an address lands only when - * its target still carries the incarnation of the call making it: a seat is - * unregistered only when the live one was minted from that incarnation, and - * an inventory row is written or deleted only while it carries it (or, for a - * write, while the call's own roster row is current). - * - * Rows written before incarnations have none (`null`, BP-030). `null` matches - * only `null`, on the one legacy path that names it: firing a roster row from - * before incarnations. A minted seat carries its incarnation in a process-local - * tag rather than in its settings, so no kind's settings schema has to admit - * it; the tag is set wherever a seat is minted from a row (`checkHiredSeatRow`, - * which the boot reload and the repair both read through, and the hire blocks). - */ - -const incarnations = new WeakMap(); - -/** A fresh incarnation id. */ -export function newIncarnation(): string { - return globalThis.crypto.randomUUID(); -} - -/** - * Record the row a minted seat came from: its incarnation, or `null` for a - * row from before incarnations. A seat never tagged (a declared one) was - * minted from no roster row at all. - */ -export function tagIncarnation(seat: object, incarnation: string | null): void { - incarnations.set(seat, incarnation); -} - -/** - * The incarnation a minted seat came from: a string, `null` when its row had - * none, `undefined` when it wasn't minted from a roster row. - */ -export function incarnationOf(seat: object): string | null | undefined { - return incarnations.get(seat); -} - -/** - * Whether `seat` was minted from a roster row carrying `incarnation`. A `null` - * incarnation matches only a seat minted from a row from before incarnations, - * never a declared seat. - */ -export function mintedFrom(seat: object, incarnation: string | null): boolean { - return incarnations.has(seat) && incarnations.get(seat) === incarnation; -} - -/** A stored row's incarnation; `null` when it has none, or predates the field (BP-030). */ -export function incarnationOfRow(state: Record): string | null { - return typeof state.incarnation === "string" ? state.incarnation : null; -} diff --git a/packages/workforce/src/roster/index.ts b/packages/workforce/src/roster/index.ts deleted file mode 100644 index 3b73f48557..0000000000 --- a/packages/workforce/src/roster/index.ts +++ /dev/null @@ -1,65 +0,0 @@ -/** - * The hired roster: the durable half of a seat hired while the app runs. - * - * `collections.ts` owns what is stored and why the write verb matters. - * `rows.ts` owns what a row means and what a hired seat is called. - * `reload.ts` owns reading the whole thing back at boot, and which failures - * stop that boot. `check.ts` owns the per-row answer the reload and - * `brokenSeats` share. `remove.ts` owns the one removal of a hired seat, and `locate.ts` - * which roster row a seat id names for the caller. - * This file only re-exports. - */ - -export { - HIRED_ROSTER_BROWSER_PATTERN, - HIRED_ROSTER_PREFIX, - HIRED_ROSTER_PRIVATE_PATTERN, - defineHiredRosterCollection, - defineHiredRosterPrivateCollection, - hiredSeatRowSchema, - type HiredSeatRow, -} from "./collections"; - -export { - encodeUserSegment, - hiredRosterStorageKey, - hiredSeatManifest, - hiredSeatOwnerPin, - hiredSeatRowFromManifest, - parseHiredSeatRow, - seatAddress, - splitSeatAddress, - toHiredSeatRow, - type RowProblem, -} from "./rows"; - -export { - hiredSeatOwnerPinFromRosterOwner, - registerHiredSeat, -} from "./register-hired-seat"; - -export { newIncarnation, tagIncarnation } from "./incarnation"; - -export { - resolveHiredSeatLocation, - type HiredSeatLocation, - type HiredSeatOwner, - type ResolveHiredSeatLocationOptions, -} from "./locate"; - -export { - removeHiredSeat, - type HiredSeatRelease, - type RemoveHiredSeatOptions, - type RemovedHiredSeat, -} from "./remove"; - -export { - DEFAULT_MAX_RELOAD_ORGS, - DEFAULT_ROSTER_READ_TIMEOUT_MS, - reloadHiredSeats, - type HiredRosterOrgReload, - type HiredRosterReload, - type HiredRosterStores, - type ReloadHiredSeatsOptions, -} from "./reload"; diff --git a/packages/workforce/src/roster/locate.ts b/packages/workforce/src/roster/locate.ts deleted file mode 100644 index 27dac84f32..0000000000 --- a/packages/workforce/src/roster/locate.ts +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Which roster row a seat id names for the caller: the one place that decides - * which row `fire` and `rehire` act on, and which an app's own fire reuses. - * - * A caller can hold two rows under one seat id: the organization's, and their - * own user-owned one on the owner-private roster. `owner` names which; without - * it, the only row under the id is the one, and two is a refusal rather than - * a guess. - */ - -import type { ResourceCollectionRef } from "@flow-state-dev/core/types"; -import { encodeUserSegment, seatAddress } from "./rows"; - -/** Whose roster row a seat id names: the organization's, or the caller's own. */ -export type HiredSeatOwner = "organization" | "me"; - -/** Where one seat's roster row is, and whose it is. */ -export interface HiredSeatLocation { - /** The roster collection holding the row. */ - roster: ResourceCollectionRef; - /** The row's key in that collection. */ - key: string | Record; - /** The member a user-owned row belongs to; `null` for an org row. */ - ownerUserId: string | null; -} - -/** What `resolveHiredSeatLocation` reads. */ -export interface ResolveHiredSeatLocationOptions { - seatId: string; - /** Which row. Omitted, the only row under the id. */ - owner?: HiredSeatOwner; - /** The organization's roster. */ - roster: ResourceCollectionRef; - /** The user-owned roster, when the flow mounts it. */ - privateRoster?: ResourceCollectionRef; - /** The caller, from the verified session. */ - userId?: string; - /** - * Required, so a fire can't leave it out by accident. A fire passes the - * organization and the seat inventory: when the caller has no user-owned - * row and names no owner, a hired inventory row at the caller's user-owned - * address (the one a fire leaves when it stops after deleting that row) - * keeps the seat the caller's, ahead of any org row, so the retry removes - * that row rather than firing an org seat that shares the id. `null` for a - * caller that acts only on a row that exists (a re-hire). - */ - leftoverAt: { orgId: string; inventory: ResourceCollectionRef } | null; -} - -/** - * Find a seat's roster row (present or not). - * - * `owner: "organization"` is the org's row. `owner: "me"` is the caller's own - * user-owned row, and is refused when there is no user-owned roster or no - * caller. Without `owner`: the caller's own row when only it exists, the org - * row when only it exists, and a refusal naming both when both do. - * - * @throws when `owner: "me"` has no user-owned roster to name, or when no - * `owner` is given and the caller has both rows under the seat id. - */ -export async function resolveHiredSeatLocation(options: ResolveHiredSeatLocationOptions): Promise { - const { seatId, owner, privateRoster, userId, leftoverAt } = options; - const org: HiredSeatLocation = { roster: options.roster, key: seatId, ownerUserId: null }; - if (owner === "organization") return org; - if (privateRoster === undefined || typeof userId !== "string" || userId.length === 0) { - if (owner === "me") { - throw new Error(`"${seatId}" can't be yours here: this flow keeps no user-owned roster for this caller.`); - } - return org; - } - const own: HiredSeatLocation = { - roster: privateRoster, - key: { owner: `~${encodeUserSegment(userId)}`, seat: seatId }, - ownerUserId: userId, - }; - if (owner === "me") return own; - if ((await privateRoster.getOptional(own.key)) !== undefined) { - if ((await org.roster.getOptional(org.key)) !== undefined) { - throw new Error( - `"${seatId}" names two seats: the organization's and yours. ` + - `Say which with owner: "organization" or owner: "me".` - ); - } - return own; - } - if (leftoverAt === null) return org; - // Probed before the org row: an org seat can share the seat id, and a retry - // that fell through to it would fire that seat instead. - const leftover = await leftoverAt.inventory.getOptional(seatAddress(leftoverAt.orgId, seatId, userId)); - return leftover?.state.hired === true ? own : org; -} diff --git a/packages/workforce/src/roster/register-hired-seat.ts b/packages/workforce/src/roster/register-hired-seat.ts deleted file mode 100644 index 96a8f72718..0000000000 --- a/packages/workforce/src/roster/register-hired-seat.ts +++ /dev/null @@ -1,52 +0,0 @@ -/** - * The hire writer's register door. - * - * Engine `register(flow, { pin })` still admits an unpinned instance, because - * app and kind flows stay shared. A hired seat is not one of those. This is - * the function a roster hire, a boot reload, and the seat-hire tools call, and - * it refuses before that register when the pin is missing. - * - * The callback receives the pin as its second argument. The writer wraps the - * engine door: `(seat, pin) => state.register(seat, { pin })`. - */ - -import type { FlowInstance, InstanceOwnerPin } from "@flow-state-dev/core/types"; - -/** - * Project a hire row's roster owner into the pin registration requires. - * - * @param owner The roster owner. `orgId` is required. `userId` is kept only - * when it is a non-empty string, so an org-visible row stays org-visible. - * @throws when `orgId` is missing or empty. An unpinned hired seat is refused - * rather than admitted as shared. - */ -export function hiredSeatOwnerPinFromRosterOwner(owner: { - orgId?: string | null; - userId?: string | null; -}): InstanceOwnerPin { - if (typeof owner.orgId !== "string" || owner.orgId.length === 0) { - throw new Error( - "A hired seat cannot be registered without an owner pin { orgId, userId? } derived from the hire row's roster owner.", - ); - } - return typeof owner.userId === "string" && owner.userId.length > 0 - ? { orgId: owner.orgId, userId: owner.userId } - : { orgId: owner.orgId }; -} - -/** - * Admit a hired seat only with a pin from its hire row's roster owner. - * - * @param register The writer's register. Called as `register(seat, pin)` and - * only after the pin is present. - * @param seat The minted instance. Its address is not read. - * @param pin The pin from the row. Omitted, or with no `orgId`, this throws - * and `register` is not called. - */ -export function registerHiredSeat( - register: (seat: FlowInstance, pin: InstanceOwnerPin) => void, - seat: FlowInstance, - pin: InstanceOwnerPin | undefined, -): void { - register(seat, hiredSeatOwnerPinFromRosterOwner(pin ?? {})); -} diff --git a/packages/workforce/src/roster/reload.ts b/packages/workforce/src/roster/reload.ts deleted file mode 100644 index 1b2393ebb5..0000000000 --- a/packages/workforce/src/roster/reload.ts +++ /dev/null @@ -1,298 +0,0 @@ -/** - * `reloadHiredSeats` — read a stored roster back at boot and turn it into - * seats. - * - * **Store-side only. It admits nothing.** It reads rows, translates them and - * hires them; registering the result is the caller's, one seat at a time. That - * split is not tidiness. A batch admission keeps the entries admitted before a - * refusal and ends the walk there, so the first refusable seat would take the - * rest of the roster down with it and the boot would fail — which is the - * degrade path broken by mechanism rather than by intent. Handing the seats - * back and letting the caller loop is what makes "one bad row is one missing - * seat" true. - * - * **Two failures stop the boot, and everything else degrades.** One rule, read - * from two sides: *fail fast on what THIS deploy got wrong; degrade on what a - * PAST deploy got wrong.* - * - * - A read the store will not complete, and a roster larger than the cap, - * both **reject**. Both are transient and inherited from the environment, - * so a boot that fails is retried and whatever is already serving keeps - * serving. Neither returns a partial result: a short roster served as if - * it were the whole one is the failure being avoided, and a cap that - * quietly truncated would be that failure with extra steps. - * - A row that disagrees with the code — a kind that is gone, settings the - * kind now refuses, a shape nothing can parse, an org or seat id that - * cannot be an address — is **skipped, named, and returned in - * `problems`**. No retry fixes any of those, so failing the - * boot over one would mean an app that can never start until somebody - * reaches the database, and the hostage is every other org's team. - * - * `{ seats, problems }` matches what `openInventory` returns, on purpose: one - * reader learns one word for the same idea, and the caller owns boot policy in - * both cases. `problems` is the part to handle rather than log — "the roster" - * and "what answers" are two numbers, and a warning in a log is not a report. - * - * Nothing here deletes or rewrites a row it could not use. - */ - -import { withTimeout } from "@flow-state-dev/core/helpers"; -import type { FlowInstance } from "@flow-state-dev/core/types"; -import type { HireOptions } from "../hire"; -import { checkHiredSeatRow } from "./check"; -import { HIRED_ROSTER_PREFIX } from "./collections"; - -/** - * The slice of a runtime's resource-state store this reads through. - * - * Structurally typed and satisfied by the engine's `StoreRegistry` directly, - * for the reason `openInventory` types its action door that way: this package - * does not depend on `@flow-state-dev/engine`, and growing a dependency on it - * to name one method would invert the layering for a type. - */ -export interface HiredRosterStores { - resourceState: { - /** - * Every live state entry in a scope whose key starts with `keyPrefix`. - * The engine's `ResourceStateStore.getByPrefix`. - */ - getByPrefix( - scopeType: string, - scopeId: string, - keyPrefix: string - ): Promise }>>; - }; -} - -/** - * Most organizations one boot will reload before it refuses. - * - * A bound on the boot rather than a statement about how many organizations an - * app may have: the reads run per organization, so this is what keeps a - * roster's growth from turning into a start-up that never concludes. An app - * past it raises the number deliberately, having decided the boot can afford - * the reads — which is a decision someone should make on purpose, and is the - * whole reason this refuses instead of truncating. - */ -export const DEFAULT_MAX_RELOAD_ORGS = 100; - -/** - * How long the whole roster read gets before the boot fails. - * - * Bounded rather than merely awaited, and the bound covers the SET rather than - * each read: a boot that hangs on a dead connection pool is worse for a - * platform to handle than one that exits, because nothing ever concludes and - * nothing is ever retried. Ten seconds is long enough for a cold pool to open - * and short enough that a platform's own start-up budget is not spent waiting. - */ -export const DEFAULT_ROSTER_READ_TIMEOUT_MS = 10_000; - -export interface ReloadHiredSeatsOptions { - /** The runtime's resolved stores — `(await flowstate.getRuntime()).stores`. */ - stores: HiredRosterStores; - - /** - * Which organizations to reload. - * - * Taken rather than discovered, because which organizations an app reloads - * is the app's policy and not one this package can make for it. There is no - * org-filtered read path to inherit, so a package that guessed the - * enumeration would be guessing for every app. - */ - orgIds: readonly string[]; - - /** - * The worker flows a stored `flow` may name — the SAME map passed to - * `hireWorkforce` for the file-declared roster. - * - * Passing a different map is how a reloaded seat ends up carrying a - * different tool catalog from its file-declared neighbours for no stated - * reason, so export the app's one map and hand it to both. - */ - workerFlows?: HireOptions["workerFlows"]; - - /** Most orgs to reload before refusing. @default {@link DEFAULT_MAX_RELOAD_ORGS} */ - maxOrgs?: number; - - /** The whole read's bound. @default {@link DEFAULT_ROSTER_READ_TIMEOUT_MS} */ - timeoutMs?: number; -} - -/** What one boot's reload produced, and what it could not. */ -export interface HiredRosterReload { - /** - * The seats that hired, ordered by address. Register them one at a time and - * fold any refusal into {@link HiredRosterReload.problems} — see this file's - * header for why this does not register them itself. - */ - seats: FlowInstance[]; - /** - * One named entry per row that did not become a seat, in the same dialect - * `openInventory` uses. Never thrown, and never empty-by-omission: a skip - * that reached only a log line is the degradation this is supposed to make - * honest. - */ - problems: string[]; - /** - * The same seats and problems, one entry per organization in `orgIds`, in - * that order. **Every organization is present**, with empty lists where it - * had nothing: a caller that publishes a report per organization has to - * rewrite the clean ones too, or last boot's problems stay standing where - * nobody overwrote them. - * - * Carries the seats as well as the problems because a seat can still be - * refused after this returns, at registration, and that refusal belongs to - * the organization the seat was hired for. The flat fields above are the - * union of these slices, unchanged. - */ - byOrg: HiredRosterOrgReload[]; -} - -/** One organization's share of a {@link HiredRosterReload}. */ -export interface HiredRosterOrgReload { - orgId: string; - /** This organization's seats, ordered by address. */ - seats: FlowInstance[]; - /** This organization's problems, in the dialect of the flat `problems`. */ - problems: string[]; -} - -/** - * Read each organization's stored roster and hire what it names. - * - * @param options `stores` / `orgIds`: where to read and for whom. `workerFlows`: the - * app's worker flows. `maxOrgs` / `timeoutMs`: the two bounds. - * @returns the hired seats and one named problem per row that could not - * become one. **The caller registers the seats.** - * @throws when there are more organizations than the cap, or when the read - * does not complete within its bound. Neither returns a partial roster. - */ -export async function reloadHiredSeats( - options: ReloadHiredSeatsOptions -): Promise { - const maxOrgs = options.maxOrgs ?? DEFAULT_MAX_RELOAD_ORGS; - const orgIds = options.orgIds; - - // Before the first read, so a refused boot has touched nothing. Refusing - // rather than slicing is the point — see the file header. - if (orgIds.length > maxOrgs) { - throw new Error( - `reloadHiredSeats was given ${orgIds.length} organizations and its cap is ${maxOrgs}. ` + - `Nothing was loaded: serving the first ${maxOrgs} would be a short roster that looks ` + - `like the whole one. Raise \`maxOrgs\` deliberately if the boot can afford the reads.` - ); - } - - // One bound over the WHOLE set rather than one per read. A per-read bound - // multiplies by the org count, so a roster of fifty organizations could - // legitimately spend fifty times the budget and still be "within bounds", - // which is not a bound on the boot at all. - // - // The map is created here and FILLED by the read, so the error factory can - // read it at the moment the bound expires. That is the whole of what makes - // BR-17's "naming the org and the store" satisfiable: the reads are - // sequential, so the first org missing from the map when the timer fires is - // exactly the one the boot is stuck on. A label built before the read - // starts can only ever name the count. The BOUND is unchanged — it still - // covers the whole set (D2); only the attribution is new. - const readsByOrg = new Map }>>(); - await withTimeout( - readEveryOrg(options.stores, orgIds, readsByOrg), - options.timeoutMs ?? DEFAULT_ROSTER_READ_TIMEOUT_MS, - "the hired roster read", - (label, timeoutMs) => new Error(stalledReadMessage(label, timeoutMs, orgIds, readsByOrg)) - ); - - const seats: FlowInstance[] = []; - const problems: string[] = []; - const byOrg: HiredRosterOrgReload[] = []; - - for (const [orgId, rowsByKey] of readsByOrg) { - const org: HiredRosterOrgReload = { orgId, seats: [], problems: [] }; - byOrg.push(org); - for (const key of Object.keys(rowsByKey).sort()) { - const stored = rowsByKey[key]!; - const where = `organization "${orgId}", row "${key}"`; - - // One shared check (`./check.ts`), the same one `brokenSeats` reads - // through, so the list a person repairs from is this list. A row it - // refuses is left on disk exactly as it is: a boot that repaired a row - // it did not understand would destroy the evidence of why it did not. - const checked = checkHiredSeatRow(orgId, stored.state, options.workerFlows, key); - if (checked.ok) { - org.seats.push(checked.seat); - } else { - org.problems.push(`${where} — ${checked.detail}`); - } - } - org.seats.sort((left, right) => left.id.localeCompare(right.id)); - seats.push(...org.seats); - problems.push(...org.problems); - } - - seats.sort((left, right) => left.id.localeCompare(right.id)); - return { seats, problems, byOrg }; -} - -/** - * Read every organization's roster prefix, into the caller's map. - * - * Sequential, and that is what {@link stalledReadMessage} reads it as: at any - * instant the orgs already in `byOrg` are done and the first one missing is - * the one in flight. **Parallelise this and that inference stops holding** — - * the bound would still be correct, but the timeout would name an arbitrary - * outstanding org rather than the stalled one, so the message would have to - * name the whole outstanding set instead. - * - * Fills the caller's map rather than returning a fresh one for the same - * reason: an error factory that only runs on timeout has to be able to see - * how far the read got, and a map that is only handed back on success is - * never handed back at all in that case. - * - * A read that REJECTS is not caught here: a store that will not answer is the - * fatal half of the rule, and swallowing it would report an organization as - * having an empty roster when nobody knows what it has. - */ -async function readEveryOrg( - stores: HiredRosterStores, - orgIds: readonly string[], - byOrg: Map }>> -): Promise { - for (const orgId of orgIds) { - byOrg.set(orgId, await stores.resourceState.getByPrefix("org", orgId, HIRED_ROSTER_PREFIX)); - } -} - -/** - * What the boot says when the roster read runs out of its bound (BR-17). - * - * Names the ORG and the STORE CALL, not just a count. A boot that fails with - * "the read for 40 organizations timed out" tells an operator to go looking - * through forty tenants; naming the one the read was on, and the exact store - * method it was waiting on, is the difference between a report and an alert. - * - * The `undefined` arm is not defensive padding for an impossible case: the - * timer and the final read settle in the same tick often enough that every - * org can be in the map when the factory runs, and a message claiming a - * stalled org that finished would be worse than one that says it could not - * attribute the stall. - */ -function stalledReadMessage( - label: string, - timeoutMs: number, - orgIds: readonly string[], - readSoFar: ReadonlyMap -): string { - const stalled = orgIds.find((orgId) => !readSoFar.has(orgId)); - const progress = `${readSoFar.size} of ${orgIds.length} organization${orgIds.length === 1 ? "" : "s"} had answered`; - const where = - stalled === undefined - ? "no organization was still outstanding when the bound expired" - : `it was reading organization "${stalled}" — ` + - `stores.resourceState.getByPrefix("org", "${stalled}", "${HIRED_ROSTER_PREFIX}") never answered`; - return ( - `${label} timed out after ${timeoutMs}ms: ${where}. ` + - `${progress}. Nothing was loaded — the bound covers the whole set, so a partial ` + - `roster is never served as the whole one.` - ); -} diff --git a/packages/workforce/src/roster/remove.ts b/packages/workforce/src/roster/remove.ts deleted file mode 100644 index 0295a1a5d3..0000000000 --- a/packages/workforce/src/roster/remove.ts +++ /dev/null @@ -1,202 +0,0 @@ -/** - * `removeHiredSeat` — the one removal of a hired seat. - * - * Firing a working seat and retiring one that no longer starts are the same - * fact: this organization no longer employs it. So there is one path, and - * every caller that removes a hired seat goes through it — `fire` on the - * seat-hire blocks, and an app's own admin action. One path means its crash - * and race cases are walked once. - * - * **The order is the contract.** The roster row goes first, because the roster - * is the fact: a leftover roster row would be a seat that still starts. Then - * the address is released, then the seat's inventory row (keyed by its - * address) goes. A crash between the two deletes leaves an inventory row with - * no roster row, which a team list that joins the two hides, and which the - * next call for the same seat removes, when the row says it was a runtime - * hire's (`hired: true`). - * - * What it never touches: a declared seat's inventory row (one whose address - * something else holds, or that doesn't say it was hired), the seat's - * sessions, state and resources, and mailbox membership rows. - */ - -import type { ResourceCollectionRef } from "@flow-state-dev/core/types"; -import { hiredSeatManifestFromStored, keyMismatch } from "./rows"; -import { incarnationOfRow } from "./incarnation"; - -/** How many times an inventory write or delete re-reads after losing a race. */ -export const INVENTORY_RACE_ATTEMPTS = 5; - -/** A store conflict: another writer moved or removed the row this call read. */ -export function isWriteConflict(error: unknown): boolean { - const code = (error as { code?: unknown } | undefined)?.code; - return code === "concurrent_modification" || code === "resource_deleted" || code === "resource_already_exists"; -} - -/** - * Delete the inventory row at `address` only while it is `incarnation`'s. - * - * The row must not be a declared seat's (`hired: false`), and must carry - * `incarnation`. `null` matches only a row that carries none either, which is - * the one legacy path: firing a roster row from before incarnations removes - * the row its older hire published. The delete is version-checked against the - * row checked; when another writer changed it in between, the store hands - * back the row that replaced it, which is checked again. Callers pass an - * incarnation whose roster row is gone, so a row carrying it is stale - * whenever it was written. Nothing here writes to a row it doesn't delete. - * - * @returns whether a row was deleted. - */ -export async function deleteOwnInventoryRow( - inventory: ResourceCollectionRef, - address: string, - incarnation: string | null -): Promise { - for (let attempt = 0; attempt < INVENTORY_RACE_ATTEMPTS; attempt += 1) { - const row = await inventory.getOptional(address); - if (row === undefined) return false; - if (row.state.hired === false || incarnationOfRow(row.state) !== incarnation) return false; - try { - await inventory.delete(address); - return true; - } catch (error) { - if (!isWriteConflict(error)) throw error; - } - } - return false; -} - -/** - * What releasing the address found: `released` when this call unregistered the - * seat, `not-held` when nothing held it here, `held-by-another` when something - * other than this row's seat holds it (so neither it nor its inventory row is - * touched). - */ -export type HiredSeatRelease = "released" | "not-held" | "held-by-another"; - -export interface RemoveHiredSeatOptions { - /** The organization the call runs under, from the principal. */ - orgId: string; - /** The roster collection that holds the row. */ - roster: ResourceCollectionRef; - /** The row's key in that collection. */ - key: string | Record; - /** The seat inventory, whose row for the seat's address is removed. */ - inventory: ResourceCollectionRef; - /** - * The address the caller expects the seat at. Used only when there is no - * roster row, to find a leftover inventory row; a readable row's own - * address is used otherwise. - */ - address: string; - /** - * Release the address, given the kind the row stored and the incarnation - * it carried (`null` on a row from before incarnations). - */ - release: (address: string, storedKind: string, incarnation: string | null) => HiredSeatRelease; - /** - * Whether something answers on an address right now. With no roster row, a - * held address is a seat this path does not own (a declared one), so its - * inventory row is left alone. - */ - isHeld: (address: string) => boolean; - /** - * The incarnation a person approved removing. Set, the row is removed only - * while it still carries it: a row that carries another (or none) is a - * replacement, and nothing is touched. Checked on the row this call read, - * with no await before the delete, and the delete is version-checked - * against that read, so a replacement written after it conflicts and is - * left too. Omitted, whatever row is there is removed. - */ - incarnation?: string | null; -} - -/** What the removal did. */ -export type RemovedHiredSeat = - /** The roster row was removed, then the address and the inventory row. */ - | { outcome: "removed"; address: string; storedKind: string; released: boolean } - /** The row could not be read; it was removed by its key, and nothing else was touched. */ - | { outcome: "unreadable"; problem: string } - /** No roster row, but a hired seat's inventory row was left at the address; it was removed. */ - | { outcome: "already-gone"; address: string } - /** Nothing of this seat's was found. The caller words the refusal. */ - | { outcome: "nothing"; address: string } - /** The row is no longer the approved incarnation's. Nothing was touched. */ - | { outcome: "replaced"; address: string }; - -/** - * Remove one hired seat: roster row, address, inventory row, in that order. - * - * @returns what was removed. Never throws over a missing seat; a store that - * refuses a write rejects. - */ -export async function removeHiredSeat(options: RemoveHiredSeatOptions): Promise { - const existing = await options.roster.getOptional(options.key); - - if (existing === undefined) { - // A crash between the two deletes leaves this. Removed only with positive - // evidence the row is a runtime hire's: nothing holds the address, and the - // row itself says `hired: true`. A declared seat's row can sit at the same - // address (a team named like the org), and a row that predates the field - // can't say; both are left, and a team list hides the second. - const leftover = await options.inventory.getOptional(options.address); - // Checked after the read, with no await before the delete is issued: a - // hire in this process registers its seat before it publishes, so a row - // a replacement hire published while the read was in flight is under a - // held address and is left. The delete is version-checked against the - // row read, so a row published after the read conflicts and is left too. - if (leftover === undefined || leftover.state.hired !== true || options.isHeld(options.address)) { - return { outcome: "nothing", address: options.address }; - } - try { - await options.inventory.delete(options.address); - } catch (error) { - if (isWriteConflict(error)) return { outcome: "nothing", address: options.address }; - throw error; - } - return { outcome: "already-gone", address: options.address }; - } - - // Read before the delete: a deleted ref reads as its schema defaults. - const incarnation = incarnationOfRow(existing.state); - const fenced = options.incarnation !== undefined; - if (fenced && (options.incarnation === null || incarnation !== options.incarnation)) { - return { outcome: "replaced", address: options.address }; - } - /** The roster delete; under the fence, a row that moved since the read is a replacement. */ - const deleteRow = async (): Promise => { - try { - await options.roster.delete(options.key); - return true; - } catch (error) { - if (fenced && isWriteConflict(error)) return false; - throw error; - } - }; - - const read = hiredSeatManifestFromStored(options.orgId, existing.state); - // A row whose seat id is not its key's names an address it isn't stored - // under: unreadable, like a row that does not parse. - const keySeat = typeof options.key === "string" ? options.key : options.key.seat; - const mismatch = - "problem" in read || keySeat === undefined ? undefined : keyMismatch(keySeat, String(existing.state.seatId)); - const record = mismatch === undefined ? read : { problem: mismatch }; - if ("problem" in record) { - // No address can be trusted from a row that does not read, so there is - // nothing to release and no inventory row that is provably its own. - if (!(await deleteRow())) return { outcome: "replaced", address: options.address }; - return { outcome: "unreadable", problem: record.problem }; - } - - const address = record.manifest.id; - const storedKind = String(existing.state.flow); - if (!(await deleteRow())) return { outcome: "replaced", address }; - const release = options.release(address, storedKind, incarnation); - if (release !== "held-by-another") { - // Only this incarnation's row, re-read: the roster row is gone, so a row - // carrying its incarnation is stale whenever it was written, and a seat - // hired again at the address since keeps its own. - await deleteOwnInventoryRow(options.inventory, address, incarnation); - } - return { outcome: "removed", address, storedKind, released: release === "released" }; -} diff --git a/packages/workforce/src/roster/rows.ts b/packages/workforce/src/roster/rows.ts deleted file mode 100644 index a1a6096d0d..0000000000 --- a/packages/workforce/src/roster/rows.ts +++ /dev/null @@ -1,286 +0,0 @@ -/** - * The one place a stored roster row becomes a hireable record and back, and - * the one place an org and a seat id become an address. - * - * Everything that turns storage into a seat goes through here so there is a - * single answer to two questions a reader will otherwise find answered twice: - * what a row means, and what a runtime-hired seat is called. - * - * **Nothing here throws over a bad stored row, and nothing here repairs one.** - * A row this version cannot read comes back as a reason. That is not - * politeness: a stored row was written by a past runtime against code that has - * since moved, so the boot that finds it must be able to skip it and serve, - * and a boot that rewrote data it did not understand would destroy the - * evidence of why it did not. The one thing that DOES throw is an address that - * cannot be built (an empty org id, or a seat id that is empty or starts with - * `~`) — see {@link seatAddress}. A reader walking stored rows calls - * {@link hiredSeatManifestFromStored}, which turns that throw into a reason - * too. - * - * The address pair lives in `./address.ts` and is re-exported here, so a - * browser can take it without this module's collections. Its only import is - * `@flow-state-dev/core/types`, which `test/browser-subpath-safe.test.ts` keeps - * free of Node built-ins. - */ - -import { encodeUserSegment, ownerSegment, type InstanceOwnerPin } from "@flow-state-dev/core/types"; -import type { WorkerManifest } from "../manifest"; -import { hiredSeatRowSchema, type HiredSeatRow } from "./collections"; -import { hiredSeatOwnerPinFromRosterOwner } from "./register-hired-seat"; -import { seatAddress, splitSeatAddress } from "./address"; - -export { encodeUserSegment, seatAddress, splitSeatAddress }; - -/** - * The stored envelope for one hire, built from what the hire supplied. - * - * `settings` is copied rather than referenced, so a caller that keeps mutating - * its own object after the hire does not retroactively change what was - * written. `instructions` normalizes whitespace-only to `null` — whitespace is - * not instructions, the same rule `hireWorkforce` applies to a file's body, - * and storing `""` would hand the kind a setting its schema can see. - */ -export function toHiredSeatRow(input: { - seatId: string; - flow: string; - settings?: Record; - instructions?: string | null; - /** - * The organization the row is written for. `null` — the default — is a - * legacy row; a reload binds the cell it was read from. - */ - owningOrgId?: string | null; - /** - * The user the hire belongs to, or `null` when every member of the owning - * org may see it. A user-owned row is stored under a nested key. - */ - ownerUserId?: string | null; - /** The incarnation this write brings into being; `null` — the default — stamps none. */ - incarnation?: string | null; -}): HiredSeatRow { - const instructions = - typeof input.instructions === "string" && input.instructions.trim().length > 0 - ? input.instructions - : null; - return { - seatId: input.seatId, - flow: input.flow, - settings: { ...(input.settings ?? {}) }, - instructions, - owningOrgId: input.owningOrgId ?? null, - ownerUserId: input.ownerUserId ?? null, - pendingRepair: null, - incarnation: input.incarnation ?? null, - }; -} - -/** - * The storage key for one row, relative to `workforce/roster/`. - * - * Org-visible rows stay one segment (`eng.lead`), which the browser - * collection lists. User-owned rows nest under `~/seat`, which - * that collection does not match. The user is escaped with the same encoding - * as the address, so a `/` in the id cannot extend another user's prefix. - * The address is not this key. - */ -export function hiredRosterStorageKey(row: { - seatId: string; - ownerUserId?: string | null; -}): string { - if (row.ownerUserId != null && row.ownerUserId.length > 0) { - return `${ownerSegment(row.ownerUserId)}/${row.seatId}`; - } - return row.seatId; -} - -/** - * The pin a row registers under. `userId` is omitted when the row is org-visible. - * - * Derived by the registration gate, {@link hiredSeatOwnerPinFromRosterOwner}, - * so a row and a direct registration get one answer. - * - * @throws when `orgId` is missing or empty. An unpinned hired seat is refused - * rather than admitted as shared. - */ -export function hiredSeatOwnerPin(orgId: string, row: HiredSeatRow): InstanceOwnerPin { - return hiredSeatOwnerPinFromRosterOwner({ orgId, userId: row.ownerUserId }); -} - -/** What a row could not be read as, when it could not be read. */ -export interface RowProblem { - /** One sentence naming what is wrong, for the boot report. */ - problem: string; -} - -/** - * Parse one stored value into a roster row. - * - * @returns the row, or a reason. Never throws, and never writes: a row that - * fails here is left exactly as it is on disk. - */ -export function parseHiredSeatRow(value: unknown): { row: HiredSeatRow } | RowProblem { - const parsed = hiredSeatRowSchema.safeParse(value); - if (!parsed.success) { - const issues = parsed.error.issues - .map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`) - .join("; "); - return { problem: `the stored row could not be read — ${issues}` }; - } - return { row: parsed.data }; -} - -/** - * Turn a stored row into the record `hireWorkforce` mints a seat from. - * - * The mapping, which is the whole of what a row means: - * - * - `id` is the seat's **address** (`.`), because that is the - * flow instance id it will be registered under. - * - `declared` is `{ ...settings, flow }` — the same shape a `WORKER.md`'s - * frontmatter produces, so a hired seat and a file-declared one reach the - * hire step through one path rather than two. The column wins over a - * same-named settings key; see the note in the body for why the order is - * load-bearing. - * - `body` is the instructions, which the hire step turns into the - * `instructions` setting exactly as it does for a file's Markdown body. - * - `seatId` is the row's own seat id, the logical id a mailbox's - * `members:` lists, which the hire step stamps as the seat's `seatId` - * setting. The address is not it. - * - * `skills` and `teamInstructions` are deliberately ABSENT rather than empty. On - * a manifest those two fields distinguish *nobody read any folders for this - * seat* from *the folders held nothing*, and a runtime hire is the first case: - * there are no folders. Setting them to `[]` would tell the kind its seat was - * read and found empty, which is a different and false claim. - * - * @returns the record, or a reason when the row's owning organization is - * not `orgId`. A row that predates the stamp binds `orgId` — the cell it - * was read from — rather than refusing. A bad ORG still throws, via - * {@link seatAddress}; a caller walking stored rows reads through - * {@link hiredSeatManifestFromStored}, which turns that throw into one row's - * reason, so one unaddressable row is one skip. - */ -export function hiredSeatManifest( - orgId: string, - row: HiredSeatRow -): { manifest: WorkerManifest } | RowProblem { - if (row.owningOrgId != null && row.owningOrgId !== orgId) { - return { - problem: - `the row is owned by organization "${row.owningOrgId}" and cannot be registered under "${orgId}"`, - }; - } - const owningOrgId = row.owningOrgId ?? orgId; - // `flow` is spread in as a declared key rather than handed over separately, - // so `hireWorkforce`'s own kind resolution and its own refusals are what - // decide it. A pre-check here would be a second gatekeeper with a second - // wording, and the one it duplicates is already the loud one. - // - // It goes in LAST, and that order is load-bearing. `settings` is a - // passthrough bag (see `collections.ts`), so a row can store its own - // `settings.flow`; spread the other way round it would overwrite the row's - // authoritative `flow` column, and nothing downstream would object — - // `settingsOf` strips `flow` as reserved before the kind ever validates the - // bag. The seat would mint and register as the bag's kind while the row - // said the column's kind forever, and the row is the only thing read again. - // What `hireWorkforce` decides is unchanged; what it decides FROM can no - // longer be shadowed by the row's own settings. - return { - manifest: { - id: seatAddress(owningOrgId, row.seatId, row.ownerUserId), - declared: { ...row.settings, flow: row.flow }, - body: row.instructions ?? "", - ownerPin: hiredSeatOwnerPin(owningOrgId, row), - seatId: row.seatId, - }, - }; -} - -/** - * A stored value, read under `orgId`, as the record a seat is minted from — - * or the one reason it cannot be. - * - * The per-row walk every reader of stored rows needs: parse, apply the - * owning-org fence, and build the address. The address throws when the seat id - * cannot be one (empty, or starting with `~`); here that throw is one row's - * reason, so a caller walking a roster - * skips it and keeps the rest. `reloadHiredSeats` and the seats manifest - * source both read through this, so they agree on which rows count. - * - * @returns the record, or a reason. Never throws. - */ -export function hiredSeatManifestFromStored( - orgId: string, - stored: unknown -): { manifest: WorkerManifest } | RowProblem { - const parsed = parseHiredSeatRow(stored); - if ("problem" in parsed) return parsed; - try { - return hiredSeatManifest(orgId, parsed.row); - } catch (error) { - // Only a bad org or seat id can throw in there today: the address - // (`seatAddress`), and the owner pin behind it (`hiredSeatOwnerPin`). A new - // throw added to `hiredSeatManifest` becomes a skipped row here, so make - // it a reason there instead if it is not about the address or the pin. - return { problem: error instanceof Error ? error.message : String(error) }; - } -} - -/** - * The reverse: recover the stored envelope from a record minted by - * {@link hiredSeatManifest}. - * - * Its reason for existing is the round-trip check, not a production caller — - * a row that cannot survive being read and written back is a row that will - * lose a seat's settings on some future reload, and the only way to know is to - * run it both ways. - * - * @returns the row, or a reason when the record does not belong to this org or - * names no kind. - */ -export function hiredSeatRowFromManifest( - orgId: string, - manifest: WorkerManifest -): { row: HiredSeatRow } | RowProblem { - const seatId = splitSeatAddress(orgId, manifest.id); - if (seatId === undefined) { - return { problem: `"${manifest.id}" is not an address in organization "${orgId}"` }; - } - const { flow, ...settings } = manifest.declared; - if (typeof flow !== "string" || flow.length === 0) { - return { problem: `"${manifest.id}" declares no flow kind` }; - } - const pin = manifest.ownerPin; - if (pin === undefined || pin.orgId !== orgId) { - return { - problem: - pin === undefined - ? `"${manifest.id}" declares no owning organization` - : `"${manifest.id}" is owned by organization "${pin.orgId}", not "${orgId}"`, - }; - } - return { - row: toHiredSeatRow({ - seatId, - flow, - settings, - instructions: manifest.body, - owningOrgId: pin.orgId, - ownerUserId: pin.userId ?? null, - }), - }; -} - -/** - * Why a row stored under `key` can't be taken as the seat it names, or - * `undefined` when the key's last segment is its `seatId`. - * - * @param key A roster storage key, with or without the roster prefix. - * @param seatId The `seatId` the row's envelope carries. - */ -export function keyMismatch(key: string, seatId: string): string | undefined { - const keySeat = key.split("/").pop()!; - return keySeat === seatId - ? undefined - : `the row is stored under "${keySeat}" but names the seat "${seatId}", so it can't be taken as either; fire "${keySeat}" to retire it`; -} diff --git a/packages/workforce/src/seat-hire-blocks.ts b/packages/workforce/src/seat-hire-blocks.ts deleted file mode 100644 index f4e1499794..0000000000 --- a/packages/workforce/src/seat-hire-blocks.ts +++ /dev/null @@ -1,1125 +0,0 @@ -/** - * `createSeatHireBlocks` — `hire`, `fire`, `brokenSeats` and `rehire` as - * blocks, with no model in front of them and no approval of their own. - * - * An action mounts any of the four directly, and nothing asks: the person - * calling the action already decided. `createSeatHireCapability` mounts all - * four as catalog tools and puts the ones a Lab names in `askBefore`, and - * `rehire` always, behind a person's approval. It reads each verb's checks and - * its write from {@link buildSeatHire}, so the tool and the block refuse the - * same things in the same words. - * - * Registration failure deletes the roster row written for that hire. The - * inventory write sits after that compensation. `fire` removes the roster row, - * then the address, then the seat's inventory row, through `removeHiredSeat`, - * the one removal every hired seat goes through. - * - * `brokenSeats` reads through the boot reload's own per-row check, so it names - * exactly the stored seats the start skips. `rehire` keeps a seat that no - * longer starts at its address, on a kind the caller names; it never picks one. - * - * User-owned seats: when the mounting flow has the user-owned roster under - * `HIRED_ROSTER_PRIVATE_RESOURCE`, `fire` and `rehire` take an `owner` - * (`"organization"` or `"me"`) naming which row they act on, and `brokenSeats` - * lists the caller's own user-owned rows beside the org's, each with its - * `owner`. Without `owner` they act on the only row under the seat id, and - * refuse when the caller has both. That collection serves a row only to the member it belongs to, so - * another member's user-owned seats are theirs to list and repair. - */ - -import { handler } from "@flow-state-dev/core"; -import type { JsonObject } from "@flow-state-dev/core"; -import { deepEqual } from "@flow-state-dev/core/helpers"; -import type { - BlockDefinition, - FlowInstance, - InstanceOwnerPin, - ResourceCollectionRef, - ResourceRef, -} from "@flow-state-dev/core/types"; -import type { BlockContext } from "@flow-state-dev/core/types"; -import { z } from "zod"; -import { - HIRED_ROSTER_PRIVATE_RESOURCE, - HIRED_ROSTER_RESOURCE, - SEAT_INVENTORY_RESOURCE, - SEAT_ADMIN_TOOLS, - SEAT_HIRE_CAPABILITY, -} from "./seat-hire-keys"; -import { seatDoorOf } from "./seat-door"; -import { hireWorkforce, KindRefusedHireError, unattendedBoardWarnings, type HireOptions } from "./hire"; -import { checkHiredSeatRow } from "./roster/check"; -import { HIRED_ROSTER_PREFIX, type HiredSeatRow } from "./roster/collections"; -import { hiredSeatOwnerPinFromRosterOwner, registerHiredSeat } from "./roster/register-hired-seat"; -import { deleteOwnInventoryRow, INVENTORY_RACE_ATTEMPTS, isWriteConflict, removeHiredSeat } from "./roster/remove"; -import { incarnationOfRow, mintedFrom, newIncarnation, tagIncarnation } from "./roster/incarnation"; -import { hiredSeatManifest, seatAddress, toHiredSeatRow } from "./roster/rows"; -import { resolveHiredSeatLocation, type HiredSeatLocation, type HiredSeatOwner } from "./roster/locate"; - -/** The registry keys live in a leaf module; re-exported here by name. */ -export { HIRED_ROSTER_PRIVATE_RESOURCE, HIRED_ROSTER_RESOURCE, SEAT_INVENTORY_RESOURCE }; - -/** - * The owner pin a hired-seat register must carry: another name for core's - * `InstanceOwnerPin`, `{ orgId, userId? }`. - * - * Derived from the hire row's roster owner, never from the address. `orgId` - * is the owning org. `userId` is present only when that row is user-owned. - */ -export type HiredSeatOwnerPin = InstanceOwnerPin; - -/** The one owner-pin gate lives with the roster; re-exported here by name. */ -export { hiredSeatOwnerPinFromRosterOwner, registerHiredSeat }; - -export interface SeatHireCapabilityOptions { - /** - * The flows a hire may name — the same map `hireWorkforce` takes. - * - * Closed over, not copied: a kind registered on this object after the - * factory runs is hireable. The built-in `agent` kind sits underneath, as - * it does for host hire. Every seat hired here is a hired worker (it carries an owner pin), so a flow the - * map keeps for declared workers (`{ flow, standardOnly: true }`) refuses it. - */ - workerFlows?: HireOptions["workerFlows"]; - /** - * Admit a minted seat at its address, with the owner pin from the hire - * row's roster owner. Hire refuses rather than call this without a pin. - * A hire that answers is a hire that was written down, so the roster row - * is created first; if this throws the row is deleted. - */ - register: (seat: FlowInstance, pin: HiredSeatOwnerPin) => void; - /** - * Release an address in this process. Fire deletes the roster row first; - * this is what makes the address stop resolving here. - */ - unregister: (id: string) => boolean; - /** - * The kind serving an address right now, if any. Used to refuse a second - * hire of a live seat before a row is written, the same pre-check host - * admin makes. Omitted, `create()` on the roster is still the duplicate - * refusal. - */ - kindAt?: (id: string) => string | undefined; - /** - * The seat serving an address right now, if any — the registry's own - * instance. Lets `rehire`, run again to finish a repair, count a seat the - * registry already holds as its own when that seat was minted from the - * repaired row (a restart registered it). Omitted, a retry that finds the - * address taken is refused, since nothing else can tell that seat from an - * unrelated one of the same kind. - */ - instanceAt?: (id: string) => FlowInstance | undefined; - /** - * Keep roster admin with the seats the app declares. When `true`, `hire` and - * `rehire` refuse settings that would give the new seat the roster tools: a - * `tools:` line naming `hire`, `fire`, `rehire` or `brokenSeats`, or a - * `capabilities:` pick of `seat-hire`. Default `false`: a hired seat may be - * given them like any other tool. - */ - refuseRosterAdmin?: boolean; - /** - * Kinds this tool may mint, as a subset of {@link SeatHireCapabilityOptions.workerFlows}. - * Omitted, every kind on the map (plus the built-in `agent`) is hireable. - */ - allowKinds?: readonly string[]; - /** - * Mailbox-board ledger ids, forwarded to `hireWorkforce` so an unattended - * board still warns. Hire does not attach boards; the warning is the - * honesty. - */ - mailboxBoards?: readonly string[]; -} - -const hireInput = z - .object({ - seatId: z.string().min(1), - flow: z.string().min(1), - settings: z - .record(z.unknown()) - .default({}) - .describe( - "The kind's own settings. Some kinds require one or more, such as the document a seat " + - "reads; your instructions name them and their values. The built-in `agent` kind needs none." - ), - instructions: z.string().optional(), - /** - * Accepted so a body that names an org is not an extra-key refusal, and - * ignored so a body that names another org changes nothing about which - * roster is written (BP-031). - */ - orgId: z.unknown().optional(), - }) - .strict(); - -const hireOutput = z.object({ - seatId: z.string(), - address: z.string(), - warning: z.string().optional(), -}); - -/** - * Whose roster row a seat id names: the organization's, or the caller's own - * user-owned one. `brokenSeats` reports it on each entry; `fire` and `rehire` - * take it, and need it when the caller has both rows under one seat id. - */ -const seatOwner = z.enum(["organization", "me"]); - -const fireInput = z - .object({ - seatId: z.string().min(1), - /** Which row to fire. Omitted, the only row under the id; refused when there are two. */ - owner: seatOwner.optional(), - orgId: z.unknown().optional(), - }) - .strict(); - -const fireOutput = z.object({ - seatId: z.string(), - /** Where the seat answered. `null` for a row that did not read, which has no address to trust. */ - address: z.string().nullable(), - released: z.boolean(), - /** - * Present when the roster row was already gone and only the seat's leftover - * inventory row was removed: a second call after a crash between the two - * deletes. Only a row marked `hired: true` is removed this way. - */ - alreadyGone: z.literal(true).optional(), -}); - -/** Ignores an org in the body, as every block here does (BP-031). */ -const brokenSeatsInput = z.object({ orgId: z.unknown().optional() }).strict(); - -const brokenSeatOutput = z.object({ - /** - * The id `fire` and `rehire` take. For an `unreadable` row, the row's key - * in the roster, which is what `fire` retires it by. - */ - seatId: z.string(), - /** The row's full storage key, as the boot report names it. */ - key: z.string(), - /** Whose row it is: what `fire` and `rehire` take as `owner` to reach this row. */ - owner: seatOwner, - /** The kind the row stored, or `null` when the row did not read. */ - kind: z.string().nullable(), - reason: z.enum(["kind-gone", "refused", "unreadable"]), - /** The start's own sentence for why the row is skipped. */ - detail: z.string(), -}); - -const brokenSeatsOutput = z.array(brokenSeatOutput); - -const rehireInput = z - .object({ - seatId: z.string().min(1), - flow: z.string().min(1), - /** Settings for the new kind. The old kind's are not carried over. */ - settings: z.record(z.unknown()).default({}), - /** Replaces the stored instructions. Omitted, the stored ones carry over. */ - instructions: z.string().optional(), - /** Which row to repair. Omitted, the only row under the id; refused when there are two. */ - owner: seatOwner.optional(), - orgId: z.unknown().optional(), - }) - .strict(); - -/** - * The org the call runs under, from the verified principal. - * - * `identity.orgId` first: `identity.id` is the storage key, which carries the - * flow when an app isolates its org state, and a roster keyed by that would - * be a different roster per flow. - */ -function orgOf(ctx: BlockContext): string { - const orgId = ctx.org?.identity.orgId ?? ctx.org?.identity.id; - if (typeof orgId !== "string" || orgId.length === 0) { - throw new Error( - "This request resolves no organization, and a roster is organization-scoped — " + - "there is nothing to write to." - ); - } - return orgId; -} - -function collectionOf(ctx: BlockContext, key: string): ResourceCollectionRef { - return ctx.resources[key] as unknown as ResourceCollectionRef; -} - -/** The user-owned roster, when the mounting flow has it. */ -function privateRosterOf(ctx: BlockContext): ResourceCollectionRef | undefined { - return ctx.resources[HIRED_ROSTER_PRIVATE_RESOURCE] as unknown as ResourceCollectionRef | undefined; -} - -/** - * Find a seat's roster row for this call: `resolveHiredSeatLocation` over this - * flow's two rosters and the session's user. - */ -function locateSeatRow( - ctx: BlockContext, - seatId: string, - owner: HiredSeatOwner | undefined, - leftoverAt: { orgId: string; inventory: ResourceCollectionRef } | null -): Promise { - return resolveHiredSeatLocation({ - seatId, - owner, - roster: collectionOf(ctx, HIRED_ROSTER_RESOURCE), - privateRoster: privateRosterOf(ctx), - userId: ctx.session.identity.userId, - leftoverAt, - }); -} - -/** A row's pending-repair marker; `null` when none, or on a row from before the field (BP-030). */ -function pendingRepairOf(state: JsonObject): string | null { - return typeof state.pendingRepair === "string" ? state.pendingRepair : null; -} - -/** - * Refuse settings that would hand the seat roster admin, whatever its kind: - * a `tools:` line naming a seat-hire tool, or a `capabilities:` pick of the - * seat-hire capability. Applied only under the `refuseRosterAdmin` option. - */ -function refuseRosterAdminIn(settings: Record | undefined, verb: string): void { - const tools = settings?.tools; - const named = Array.isArray(tools) ? tools.filter((name) => SEAT_ADMIN_TOOLS.includes(name as string)) : []; - const capabilities = settings?.capabilities; - const picked = - capabilities !== null && typeof capabilities === "object" && Object.hasOwn(capabilities, SEAT_HIRE_CAPABILITY); - if (named.length === 0 && !picked) return; - const what = named.length > 0 ? `the tools ${named.map((name) => `"${name}"`).join(", ")}` : `the "${SEAT_HIRE_CAPABILITY}" capability`; - throw new Error( - `This ${verb} asks for ${what}. This app keeps the roster tools with the seats it declares: ` + - `a seat this tool hires can't hire, fire or repair seats. Hire it without them.` - ); -} - -/** The row no longer carries this call's incarnation: another call replaced it. */ -class SeatMoved extends Error { - constructor(address: string) { - super(`"${address}" changed while this call was finishing it, most likely by another hire or repair of it. This call stopped.`); - } -} - -/** - * Refuse an approved change when the seat id now names a different row than - * the one the person was asked about: another hire under the same id, a - * different kind, or the other owner's seat. - * - * Only reached when a row is there to change. One with no incarnation (an - * older row, or one a writer stamped none on) is refused: a replacement - * written the same way would carry none either, and nothing else tells the - * two apart. - */ -function refuseIfReplaced(verb: string, address: string, approved: SeatHireChecked, now: SeatHireChecked): void { - if (approved.incarnation === null || now.incarnation === null) { - throw new Error( - `The seat "${address}" carries no incarnation on its roster row (it was written before incarnations, or ` + - `by a writer that stamps none), so this approval can't be tied to the seat you were asked about, and the ` + - `${verb} was not made.` - ); - } - if (approved.owner === now.owner && approved.incarnation === now.incarnation && (verb !== "fire" || approved.kind === now.kind)) { - return; - } - throw seatChanged(verb, address); -} - -/** The refusal for an approved change whose row is no longer the one approved. */ -function seatChanged(verb: string, address: string): Error { - return new Error( - `The seat "${address}" changed while you were asked: it is not the one you approved, so the ${verb} was not made. Ask again if it should be.` - ); -} - -/** - * The token an approved re-hire writes as its pending repair: minted once per - * tool call and kept on the request, like the check. So a recovery that finds - * the repair row it wrote knows the row as its own and finishes it, while a - * pending repair some other call wrote is still a replacement. - */ -async function repairTokenOnce(ctx: BlockContext): Promise { - const call = ctx._blockIdentity?.blockInstanceId; - if (ctx.runOnce === undefined || call === undefined) return newIncarnation(); - return await ctx.runOnce(`seat-hire-repair-token:${call}`, async () => newIncarnation()); -} - -/** - * The row an approved check found, as `owner` names it: so the change made on - * Approve reaches that row, and no other the seat id has come to name. - */ -function approvedOwner(approved: SeatHireChecked | undefined): HiredSeatOwner | undefined { - if (approved === undefined) return undefined; - return approved.owner === null ? "organization" : "me"; -} - -/** - * The call's own roster row failed its check: carried out of an inventory - * write, so it isn't read as that write's conflict. - */ -class FenceFailed extends Error { - constructor(readonly reason: unknown) { - super(reason instanceof Error ? reason.message : String(reason)); - } -} - -/** The address has a declared seat's inventory row, which no hire writes over. */ -class DeclaredRow extends Error { - constructor(address: string) { - super(`"${address}" has a declared seat's inventory row, which a hire does not write over.`); - } -} - -function asStored(row: HiredSeatRow): JsonObject { - return row as unknown as JsonObject; -} - -function listed(names: readonly string[]): string { - return names.length > 0 ? names.join(", ") : "(none)"; -} - -/** - * The seat-hire handlers, model-free. `createSeatHireCapability` mounts all - * four as catalog tools, with `rehire` (and any verb its `askBefore` names) - * behind a person's approval; mounted as actions, none of them asks. - */ -export interface SeatHireBlocks { - readonly hire: BlockDefinition; - /** Remove a hired seat: a working one, or one that no longer starts (retire). */ - readonly fire: BlockDefinition; - /** The organization's stored seats the start would skip, each with its reason. Writes nothing. */ - readonly brokenSeats: BlockDefinition; - /** Keep a seat that no longer starts at its address, on a kind the caller names. */ - readonly rehire: BlockDefinition; -} - -/** A verb's input and output, as its block declares them. */ -export type HireInput = z.infer; -export type HireOutput = z.infer; -export type FireInput = z.infer; -export type FireOutput = z.infer; -export type RehireInput = z.infer; - -/** - * One verb that changes the roster, split where an approval goes between. - * - * `check` meets every refusal the change would meet and writes nothing. - * `run` is the block's whole body, refusals included. - */ -export interface SeatHireVerb { - /** - * Refuse, writing nothing, if the change would fail now. - * - * @returns what the change concerns, for the ask to name and the approval - * to bind to: the kind a hire mints or a re-hire moves onto, the kind a - * fired row stored (`null` for a row that does not read), and the row. - */ - check(input: I, ctx: BlockContext): Promise; - /** - * Make the change. Given `approved`, the check a person approved, a fire or - * re-hire that now finds a different row under the seat id refuses - * instead of changing it. - */ - run(input: I, ctx: BlockContext, approved?: SeatHireChecked): Promise; -} - -/** What a verb's check found: the kind, and the roster row it found it on. */ -export interface SeatHireChecked { - kind: string | null; - /** The member a user-owned row belongs to; `null` for an org-visible row, and for a hire. */ - owner: string | null; - /** The row's incarnation; `null` when there is no row (a hire, a leftover inventory row). */ - incarnation: string | null; -} - -/** The three roster changes, each with its check. */ -export interface SeatHireVerbs { - readonly hire: SeatHireVerb; - readonly fire: SeatHireVerb; - readonly rehire: SeatHireVerb; -} - -/** - * Build `{ hire, fire, brokenSeats, rehire }`. - * - * @param options Kinds, register/unregister, and the optional allowlist. - * Org comes from the principal at the call, not from options. - */ -export function createSeatHireBlocks(options: SeatHireCapabilityOptions): SeatHireBlocks { - return buildSeatHire(options).blocks; -} - -/** - * The blocks and, under them, each verb's check and write. - * - * For `createSeatHireCapability`, whose gated tools check, ask, check again - * and write. Not exported from the package: an app mounts the blocks. - * - * @param options As {@link createSeatHireBlocks}. - */ -export function buildSeatHire(options: SeatHireCapabilityOptions): { - blocks: SeatHireBlocks; - verbs: SeatHireVerbs; -} { - const workerFlows = options.workerFlows ?? {}; - const allow = options.allowKinds === undefined ? undefined : new Set(options.allowKinds); - - const hireableKindNames = (): string[] => { - const names = new Set(["agent", ...Object.keys(workerFlows)]); - if (allow !== undefined) { - return [...names].filter((name) => allow.has(name)).sort(); - } - return [...names].sort(); - }; - - /** Refuse a kind this tool may not mint, or this app does not carry. Writes nothing. */ - const refuseUnhireableKind = (flow: string, verb: string): void => { - const available = hireableKindNames(); - if (allow !== undefined && !allow.has(flow)) { - throw new Error(`This seat may not ${verb} kind "${flow}". It may hire: ${listed(available)}.`); - } - if (!Object.hasOwn(workerFlows, flow) && flow !== "agent") { - throw new Error(`This app carries no flow kind "${flow}". It carries: ${listed(available)}.`); - } - }; - - /** - * Refuse an address a declared seat's inventory row sits at (a team named - * like the organization), even while nothing serves it. Writes nothing. - */ - const refuseDeclaredAddress = async (ctx: BlockContext, address: string): Promise => { - const row = await collectionOf(ctx, SEAT_INVENTORY_RESOURCE).getOptional(address); - if (row?.state.hired === false) { - throw new Error(`"${address}" is a seat declared in a worker file. Hire under another id.`); - } - }; - - /** Mint the seat a row describes, running the kind's settings schema. Writes nothing. */ - const mint = (orgId: string, row: HiredSeatRow, address: string): FlowInstance => { - const record = hiredSeatManifest(orgId, row); - // Type narrowing, not a second fence: the row was just stamped with this org. - if ("problem" in record) { - throw new Error(`"${address}" could not be hired: ${record.problem}.`); - } - const [seat] = hireWorkforce([record.manifest], { - workerFlows, - mailboxBoards: options.mailboxBoards, - }); - if (seat === undefined) { - throw new Error(`"${address}" could not be hired, and no reason was given.`); - } - tagIncarnation(seat, row.incarnation); - return seat; - }; - - /** - * Publish the seat's inventory row, and say what a person should know. - * - * Every write runs `fence` (the call's roster row is still current) after - * looking at the row it replaces, and lands only on that row: a create when - * there was none, otherwise a version-checked replace whose check runs inside - * the write, so a row another writer put there since is looked at, and - * fenced for, again. While the call's roster row is current, no other hire's - * row at the address can be live (one roster row per address), so the row - * replaced is this incarnation's or a stale one. A declared seat's row - * (`hired: false`) is never written over. - */ - const publish = async ( - ctx: BlockContext, - seat: FlowInstance, - flow: string, - address: string, - incarnation: string, - fence: () => Promise - ) => { - const door = seatDoorOf(seat); - const inventory = collectionOf(ctx, SEAT_INVENTORY_RESOURCE); - const next: JsonObject = { id: address, kind: flow, door: door.door, hired: true, incarnation }; - const create = async () => { - await fence(); - await inventory.create(address, next); - }; - let written = false; - for (let attempt = 0; attempt < INVENTORY_RACE_ATTEMPTS && !written; attempt += 1) { - try { - const row = await inventory.getOptional(address); - if (row === undefined) { - await create(); - } else { - try { - // The engine re-runs this against the row that won after any - // version conflict, so the check and the fence always precede - // the write that lands. - await row.updateState(async (current) => { - if (current.hired === false) throw new DeclaredRow(address); - await fence(); - return next; - }); - } catch (error) { - // Deleted since this call read it: write it fresh. - if (error instanceof FenceFailed || (error as { code?: unknown }).code !== "resource_deleted") throw error; - await create(); - } - } - written = true; - } catch (error) { - if (error instanceof FenceFailed || !isWriteConflict(error)) throw error; - } - } - if (!written) { - throw Object.assign(new Error(`"${address}"'s inventory row kept changing under this call.`), { - code: "concurrent_modification", - }); - } - // No door warning: the hire already refused a worker flow with none or two. - const warnings = unattendedBoardWarnings(options.mailboxBoards ?? [], [seat]); - return warnings.length > 0 ? { warning: warnings.join("\n") } : {}; - }; - - /** - * Register a seat. A `duplicate-id` refusal counts as registered only on a - * repair's retry (`own` set), and only when `instanceAt` shows the seat - * holding the address was minted from this incarnation's row — the one a - * restart registered. Any other holder, same kind or not, is a refusal. - * - * @returns whether this call registered it. - */ - const registerOnce = (seat: FlowInstance, pin: InstanceOwnerPin, own?: string): boolean => { - try { - registerHiredSeat(options.register, seat, pin); - return true; - } catch (error) { - const refused = error as { reason?: unknown; id?: unknown }; - if (own !== undefined && refused.reason === "duplicate-id" && refused.id === seat.id) { - const live = options.instanceAt?.(seat.id); - if (live !== undefined && live.kind === seat.kind && mintedFrom(live, own)) return false; - } - throw error; - } - }; - - /** - * The steps after a hire or re-hire wrote its roster row: register, publish - * the inventory row, and (for a re-hire) clear the row's pending-repair - * marker. Before each side effect the row is re-read from the store (a - * verified no-op write) and must still exist carrying `incarnation`. - * - * A conflict of any kind (the row was deleted, carries another incarnation, - * or another writer kept moving the inventory row) stops the call and takes - * back only what is still this incarnation's: the seat at the address when - * `instanceAt` shows it was minted from this incarnation, and the inventory - * row while it carries it. The other writer's seat, row and registration are - * left as they are. Without `instanceAt` the seat is left registered, since - * nothing can tell it from a seat hired again at the address. - */ - const settle = async ( - ctx: BlockContext, - ref: ResourceRef, - incarnation: string, - seat: FlowInstance, - pin: InstanceOwnerPin, - flow: string, - address: string, - step: { - /** A repair's retry: a registration of this incarnation's seat counts as done. */ - retry?: boolean; - /** Clear `pendingRepair` as the last write (a re-hire). */ - repair?: boolean; - /** - * Undo this call's roster write, only while the row is still this - * call's: when registration is refused, and when a declared seat's - * inventory row turned up at the address before the publish. - */ - undoRowWrite?: () => Promise; - } - ) => { - const stillOurs = (current: JsonObject) => { - if (incarnationOfRow(current) !== incarnation) throw new SeatMoved(address); - return current; - }; - const fence = async () => { - try { - await ref.updateState(stillOurs); - } catch (error) { - throw new FenceFailed(error); - } - }; - try { - await fence(); - try { - registerOnce(seat, pin, step.retry ? incarnation : undefined); - } catch (error) { - await step.undoRowWrite?.(); - throw error; - } - let warnings: { warning?: string }; - try { - warnings = await publish(ctx, seat, flow, address, incarnation, fence); - } catch (error) { - // A fire that removed the inventory row under this write removed the - // roster row first; that is the conflict below, not a failed write. - if (error instanceof FenceFailed || isWriteConflict(error)) throw error; - if (error instanceof DeclaredRow) { - // A boot wrote a declared seat's row here after this call checked - // the address (a rolling deploy whose old process still declares - // it). A hire never writes over one, so it takes back what it did: - // the seat it registered, then its roster row. The declared row and - // anything else at the address are left. - const live = options.instanceAt?.(address); - if (live !== undefined && mintedFrom(live, incarnation)) options.unregister(address); - await step.undoRowWrite?.(); - throw new Error( - `"${address}" was taken by a declared seat's inventory row while this call was finishing it, ` + - `and a hire does not write over a declared seat. This call took back its seat and its roster row.` - ); - } - await fence(); - if (!step.repair) throw error; - throw new Error( - `"${address}" was re-hired onto "${flow}" and is serving, but its inventory row could not be ` + - `written: ${error instanceof Error ? error.message : String(error)}. Run the same re-hire again to finish it.` - ); - } - await ref.updateState((current) => - step.repair && pendingRepairOf(current) === incarnation - ? { ...stillOurs(current), pendingRepair: null } - : stillOurs(current) - ); - return warnings; - } catch (thrown) { - const error = thrown instanceof FenceFailed ? thrown.reason : thrown; - if (!(error instanceof SeatMoved) && !isWriteConflict(error)) throw error; - // Checked and removed with no await between: the seat at the address - // is this incarnation's, or it is left. - const live = options.instanceAt?.(address); - if (live !== undefined && mintedFrom(live, incarnation)) options.unregister(address); - await deleteOwnInventoryRow(collectionOf(ctx, SEAT_INVENTORY_RESOURCE), address, incarnation); - throw new Error( - (error as { code?: unknown }).code === "resource_deleted" - ? `"${address}" was fired while this call was finishing it. Nothing of it was kept.` - : `"${address}" changed while this call was finishing it, most likely by another hire, fire or ` + - `repair of it. This call stopped and kept nothing of its own; the other one's seat was left as it is.` - ); - } - }; - - /** Every refusal a hire meets before it writes, and the seat it would mint. */ - const prepareHire = (input: HireInput, ctx: BlockContext) => { - const orgId = orgOf(ctx); - const address = seatAddress(orgId, input.seatId); - refuseUnhireableKind(input.flow, "hire"); - if (options.refuseRosterAdmin === true) refuseRosterAdminIn(input.settings, "hire"); - - const held = options.kindAt?.(address); - if (held !== undefined) { - throw new Error( - `"${address}" is already served by a flow of kind "${held}". Fire that seat first, or hire under another id.` - ); - } - // A declared seat is registered at its own id (`chief-of-staff`, - // `.`), so a hire that reused it would be a second seat - // answering to a declared seat's name. - const declared = options.kindAt?.(input.seatId); - if (declared !== undefined) { - throw new Error( - `"${input.seatId}" is the id of a seat this app declares (kind "${declared}"). Hire under another id.` - ); - } - - const incarnation = newIncarnation(); - const row = toHiredSeatRow({ - seatId: input.seatId, - flow: input.flow, - settings: input.settings, - instructions: input.instructions ?? null, - owningOrgId: orgId, - incarnation, - }); - // The kind's own refusal (typed at its source by `hireWorkforce`) writes - // nothing and the caller can correct it, so say so: a model reading only - // the boot-time sentence takes it as final. A framework refusal or any - // other mint fault keeps its own message. - let seat: FlowInstance; - try { - seat = mint(orgId, row, address); - } catch (error) { - if (!(error instanceof KindRefusedHireError)) throw error; - throw new Error( - `"${address}" was not hired, and nothing was written. Kind "${input.flow}" refused it: ` + - `${error.message}\n` + - `If that names a setting, call hire again with it in \`settings\`.` - ); - } - return { orgId, address, row, incarnation, seat }; - }; - - const hireVerb: SeatHireVerb = { - check: async (input, ctx) => { - const { address } = prepareHire(input, ctx); - // The write's own duplicate refusal is `create()`; asked before an - // approval, it has to be read. - if ((await collectionOf(ctx, HIRED_ROSTER_RESOURCE).getOptional(input.seatId)) !== undefined) { - throw new Error(`This organization already hired a seat "${input.seatId}". Fire it first, or hire under another id.`); - } - await refuseDeclaredAddress(ctx, address); - return { kind: input.flow, owner: null, incarnation: null }; - }, - run: async (input, ctx) => { - const { orgId, address, row, incarnation, seat } = prepareHire(input, ctx); - await refuseDeclaredAddress(ctx, address); - - const roster = collectionOf(ctx, HIRED_ROSTER_RESOURCE); - const written = await roster.create(input.seatId, asStored(row)); - - // Pin from the roster owner of the row just written — the org cell of - // this hire — not from `seat.id`. Address is a name the caller can type; - // it is not evidence of ownership (FIX-1529 / F2-PLAN). - const warnings = await settle(ctx, written, incarnation, seat, { orgId }, input.flow, address, { - undoRowWrite: async () => { - try { - // Only while the row is still this hire's; the delete is - // version-checked against the row read. - const current = await roster.getOptional(input.seatId); - if (current !== undefined && incarnationOfRow(current.state) === incarnation) { - await roster.delete(input.seatId); - } - } catch (cleanupError) { - console.error( - `[seat-hire] "${address}" was written and could not be registered, and its row could ` + - `not be removed either — the next boot will skip and name it: ${String(cleanupError)}` - ); - } - }, - }); - return { seatId: input.seatId, address, ...warnings }; - }, - }; - - /** The refusal for a fire that finds nothing of this organization's to remove. */ - const nothingToFire = (seatId: string, address: string): Error => { - const declared = options.kindAt?.(address) !== undefined ? address : options.kindAt?.(seatId) !== undefined ? seatId : undefined; - return new Error( - declared === undefined - ? `This organization hired no seat "${seatId}".` - : `"${declared}" was not hired through this tool — a seat declared in a worker file is ` + - `removed by editing its folder, not by firing it.` - ); - }; - - const fireVerb: SeatHireVerb = { - check: async (input, ctx) => { - const orgId = orgOf(ctx); - const inventory = collectionOf(ctx, SEAT_INVENTORY_RESOURCE); - const located = await locateSeatRow(ctx, input.seatId, input.owner, { orgId, inventory }); - const address = seatAddress(orgId, input.seatId, located.ownerUserId); - const existing = await located.roster.getOptional(located.key); - if (existing !== undefined) { - const checked = checkHiredSeatRow(orgId, existing.state, workerFlows); - return { kind: checked.row?.flow ?? null, owner: located.ownerUserId, incarnation: incarnationOfRow(existing.state) }; - } - // What `removeHiredSeat` does with no row: a hired seat's leftover - // inventory row (`hired: true`) at an address nothing holds is still - // removed; anything else is nothing, and is refused before anyone is asked. - if (options.kindAt?.(address) === undefined) { - const leftover = await inventory.getOptional(address); - if (leftover !== undefined && leftover.state.hired === true) { - return { kind: null, owner: located.ownerUserId, incarnation: null }; - } - } - throw nothingToFire(input.seatId, address); - }, - run: async (input, ctx, approved) => { - const orgId = orgOf(ctx); - const inventory = collectionOf(ctx, SEAT_INVENTORY_RESOURCE); - // After an approval, the row the person was asked about: its owner, - // even when the caller named none and the other roster has since gained - // a row under the same id. - const located = await locateSeatRow(ctx, input.seatId, input.owner ?? approvedOwner(approved), { orgId, inventory }); - if (approved !== undefined) { - const now = await located.roster.getOptional(located.key); - if (now !== undefined) { - const kind = checkHiredSeatRow(orgId, now.state, workerFlows).row?.flow ?? null; - refuseIfReplaced( - "fire", - seatAddress(orgId, input.seatId, located.ownerUserId), - approved, - { kind, owner: located.ownerUserId, incarnation: incarnationOfRow(now.state) } - ); - } - } - const removed = await removeHiredSeat({ - orgId, - roster: located.roster, - key: located.key, - inventory, - address: seatAddress(orgId, input.seatId, located.ownerUserId), - // After an approval, only the row the person approved: checked against - // the removal's own read and its version-checked delete, so a row - // fired and hired again since the check above is left alone. - ...(approved === undefined ? {} : { incarnation: approved.incarnation }), - isHeld: (address) => options.instanceAt?.(address) !== undefined || options.kindAt?.(address) !== undefined, - release: (address, storedKind, incarnation) => { - // With `instanceAt`, only the seat minted from this row is released: - // checked and removed with no await between. A `null` incarnation - // matches only a seat minted from a row from before incarnations, - // never a declared one. - if (options.instanceAt !== undefined) { - const live = options.instanceAt(address); - if (live === undefined) return "not-held"; - if (!mintedFrom(live, incarnation)) { - console.error( - `[seat-hire] removed the roster row for "${address}", but the address is held by a seat ` + - `that row didn't mint — leaving it registered.` - ); - return "held-by-another"; - } - return options.unregister(address) ? "released" : "not-held"; - } - // Without it, the kind is all there is to go on. - const liveKind = options.kindAt?.(address); - if (liveKind !== undefined && liveKind !== storedKind) { - console.error( - `[seat-hire] removed the roster row for "${address}" (kind "${storedKind}"), but the ` + - `address is held by a flow of kind "${liveKind}" — leaving it registered.` - ); - return "held-by-another"; - } - return options.unregister(address) ? "released" : "not-held"; - }, - }); - - switch (removed.outcome) { - case "removed": - return { seatId: input.seatId, address: removed.address, released: removed.released }; - case "unreadable": - return { seatId: input.seatId, address: null, released: false }; - case "already-gone": - return { seatId: input.seatId, address: removed.address, released: false, alreadyGone: true as const }; - case "nothing": - throw nothingToFire(input.seatId, removed.address); - case "replaced": - throw seatChanged("fire", removed.address); - } - }, - }; - - const brokenSeats = handler({ - name: "brokenSeats", - description: - "List this organization's stored seats that would not start, each with its reason " + - "(kind-gone, refused, unreadable), the caller's own user-owned seats included when the " + - "flow mounts that roster. Reads only.", - inputSchema: brokenSeatsInput, - outputSchema: brokenSeatsOutput, - execute: async (_input, ctx) => { - const orgId = orgOf(ctx); - // The org's rows, and the caller's own user-owned rows when the flow - // mounts that roster: the same rows the start reads for this member. - const owned = privateRosterOf(ctx); - const rows = [ - ...(await collectionOf(ctx, HIRED_ROSTER_RESOURCE).list()).map((ref) => ({ ref, owner: "organization" as const })), - ...(owned === undefined ? [] : await owned.list()).map((ref) => ({ ref, owner: "me" as const })), - ]; - const broken: Array> = []; - for (const { ref, owner } of rows) { - const checked = checkHiredSeatRow(orgId, ref.state, workerFlows, ref.path); - if (checked.ok) continue; - // The id `fire` takes: the key's last segment (`~/` for a - // user-owned row, which `fire` finds by the caller). - const relativeKey = ( - ref.path.startsWith(HIRED_ROSTER_PREFIX) ? ref.path.slice(HIRED_ROSTER_PREFIX.length) : ref.path - ).split("/").pop()!; - broken.push({ - seatId: checked.reason === "unreadable" ? relativeKey : (checked.row?.seatId ?? relativeKey), - key: ref.path, - owner, - kind: checked.row?.flow ?? null, - reason: checked.reason, - detail: checked.detail, - }); - } - return broken.sort((left, right) => left.key.localeCompare(right.key)); - }, - }); - - /** - * Every refusal a re-hire meets before it writes, and what it would do: write - * a new row (`finish: false`), or finish the unfinished re-hire the row's - * pending-repair marker names (`finish: true`). Writes nothing, so the - * capability can run it before asking and the write runs it again after. - */ - const prepareRehire = async ( - input: RehireInput, - ctx: BlockContext, - owner: HiredSeatOwner | undefined = input.owner, - ownToken?: string - ) => { - const orgId = orgOf(ctx); - // Re-hire acts only on a row that exists, so there is no leftover to find. - const located = await locateSeatRow(ctx, input.seatId, owner, null); - const address = seatAddress(orgId, input.seatId, located.ownerUserId); - const existing = await located.roster.getOptional(located.key); - if (existing === undefined) { - throw new Error(`This organization hired no seat "${input.seatId}".`); - } - - const before = existing.state as JsonObject; - const target = { kind: input.flow, owner: located.ownerUserId, incarnation: incarnationOfRow(before) }; - const checked = checkHiredSeatRow(orgId, before, workerFlows, input.seatId); - if (!checked.ok && (checked.reason === "unreadable" || checked.row === undefined)) { - throw new Error(`"${input.seatId}" is a row that can't be read (${checked.detail}). Fire it to retire it.`); - } - const old = checked.row!; - // The key the row was found under says whose it is; a stored owner that - // says otherwise is refused, not re-derived, since either could be the wrong one. - if ((old.ownerUserId ?? null) !== (located.ownerUserId ?? null)) { - throw new Error( - `"${input.seatId}"'s roster row says it belongs to ${old.ownerUserId === null ? "the whole org" : `user "${old.ownerUserId}"`}, ` + - `but it is stored as ${located.ownerUserId === null ? "the org's" : `user "${located.ownerUserId}"'s`}, so it was not re-hired. ` + - `Fire it to retire it.` - ); - } - const row = toHiredSeatRow({ - seatId: old.seatId, - flow: input.flow, - settings: input.settings, - instructions: input.instructions ?? old.instructions, - owningOrgId: orgId, - ownerUserId: old.ownerUserId, - }); - const pin = hiredSeatOwnerPinFromRosterOwner({ orgId, userId: old.ownerUserId }); - - if (checked.ok) { - // A seat the start serves is not repaired: a working seat changes kind - // by fire then hire. The one exception is a re-hire that wrote this - // row and didn't finish (the process died, or the inventory write - // failed), which the row says itself with its pending-repair marker. - // Only the same re-hire finishes it; a row with no marker (an older - // row included, BP-030) has no repair pending. - const token = old.pendingRepair; - if (token === null || old.incarnation !== token) { - throw new Error( - `"${address}" still starts on kind "${old.flow}". To change a working seat's kind, fire it and hire it again.` - ); - } - if (!deepEqual(row, { ...old, pendingRepair: null, incarnation: null })) { - throw new Error( - `"${address}" has an unfinished re-hire onto "${old.flow}". Run that same re-hire again to finish it.` - ); - } - refuseUnhireableKind(input.flow, "re-hire onto"); - // Finishing writes the seat out like any re-hire, so it meets the same - // refusal: a row left from before the app turned it on is not finished. - if (options.refuseRosterAdmin === true) refuseRosterAdminIn(input.settings, "re-hire"); - const live = options.kindAt?.(address); - if (live !== undefined && live !== input.flow) { - throw new Error(`"${address}" is already served by a flow of kind "${live}", so it can't be re-hired.`); - } - return { finish: true as const, target, address, existing, old, token, pin, seat: checked.seat }; - } - - // Everything that can refuse runs before the write. - refuseUnhireableKind(input.flow, "re-hire onto"); - if (options.refuseRosterAdmin === true) refuseRosterAdminIn(input.settings, "re-hire"); - const held = options.kindAt?.(address); - if (held !== undefined) { - throw new Error(`"${address}" is already served by a flow of kind "${held}", so it can't be re-hired.`); - } - await refuseDeclaredAddress(ctx, address); - const token = ownToken ?? newIncarnation(); - const seat = mint(orgId, { ...row, incarnation: token }, address); - return { finish: false as const, target, address, existing, before, old, row, token, pin, seat }; - }; - - const rehireVerb: SeatHireVerb = { - check: async (input, ctx) => (await prepareRehire(input, ctx)).target, - run: async (input, ctx, approved) => { - // An approved re-hire writes the token kept for this call, so a - // recovery after the row write finds a pending repair it knows as its - // own and finishes it. Any other row, a pending repair another call - // wrote included, is checked against what the person approved. - const ownToken = approved === undefined ? undefined : await repairTokenOnce(ctx); - const prepared = await prepareRehire(input, ctx, input.owner ?? approvedOwner(approved), ownToken); - const ours = prepared.finish && ownToken !== undefined && prepared.token === ownToken; - if (approved !== undefined && !ours) refuseIfReplaced("re-hire", prepared.address, approved, prepared.target); - if (prepared.finish) { - const { address, existing, old, token, pin, seat } = prepared; - const warnings = await settle(ctx, existing, token, seat, pin, input.flow, address, { - retry: true, - repair: true, - }); - return { seatId: old.seatId, address, ...warnings }; - } - const { address, existing, before, old, row, token, pin, seat } = prepared; - - // One version-checked write, marked as a repair in progress until the - // seat is registered and published. If the row moved since it was read - // (another repair landed, or it was retired), this one is refused rather - // than written over it. - await existing.updateState((current) => { - if (!deepEqual(current, before)) { - throw new Error( - `"${address}" changed while this re-hire was being made, most likely by another repair. Nothing was written.` - ); - } - // Onto the stored row, so a key a newer version wrote is kept. - return { ...current, ...asStored({ ...row, pendingRepair: token, incarnation: token }) }; - }); - - const warnings = await settle(ctx, existing, token, seat, pin, input.flow, address, { - repair: true, - undoRowWrite: async () => { - // Write the old row back, while it is still this repair's. - try { - await existing.updateState((current) => { - if (pendingRepairOf(current) !== token) throw new SeatMoved(address); - return before; - }); - } catch (restoreError) { - console.error( - `[seat-hire] "${address}" was re-hired onto "${input.flow}" and could not be registered, and its ` + - `old row could not be written back either — the next boot serves it on "${input.flow}", and the ` + - `same re-hire run again finishes it: ${String(restoreError)}` - ); - } - }, - }); - return { seatId: old.seatId, address, ...warnings }; - }, - }; - - const hire = handler({ - name: "hire", - description: - "Mint a seat of a kind this app already registered. Names the kind, a seat id, and in " + - "`settings` whatever that kind requires: a kind refuses a hire missing a required setting, " + - "naming it. Does not invent a kind, and does not attach boards.", - inputSchema: hireInput, - outputSchema: hireOutput, - execute: hireVerb.run, - }); - - const fire = handler({ - name: "fire", - description: - "Remove a runtime-hired seat: its roster row, its address in this process, and its " + - "inventory row. Also retires a stored seat that no longer starts.", - inputSchema: fireInput, - outputSchema: fireOutput, - execute: fireVerb.run, - }); - - const rehire = handler({ - name: "rehire", - description: - "Keep a stored seat that no longer starts (its kind is gone, or refuses its settings) at " + - "its address, on a kind this app carries. The caller names the kind; settings are the new kind's.", - inputSchema: rehireInput, - outputSchema: hireOutput, - execute: rehireVerb.run, - }); - - return { - blocks: { hire, fire, brokenSeats, rehire }, - verbs: { hire: hireVerb, fire: fireVerb, rehire: rehireVerb }, - }; -} diff --git a/packages/workforce/src/seat-hire-capability.ts b/packages/workforce/src/seat-hire-capability.ts deleted file mode 100644 index 46d8aa6e81..0000000000 --- a/packages/workforce/src/seat-hire-capability.ts +++ /dev/null @@ -1,219 +0,0 @@ -/** - * `createSeatHireCapability` — hire, fire and the two repairs as catalog - * tools on the existing mint. - * - * Compose it into a worker kind's `uses` and the kind's catalog gains `hire`, - * `fire`, `brokenSeats` and `rehire`. That is a grant the kind offers, not a - * grant a seat holds: a seat still names the tool in `tools:`, and an empty - * list stays empty (FIX-1393). The tools mint and retire seats of kinds this - * factory closed over, write the durable roster, write `inventory/seats/*` so - * Discover can see the new seat, and register the address. They do not invent - * a kind, and they do not attach boards. - * - * ## Which changes ask a person first - * - * `askBefore` names the verbs whose tool raises a stock `human_approval` - * before it writes: the tool checks the change would succeed, asks, checks - * again on Approve, then makes it. Deny changes nothing, and the model reads - * the denial as the tool's result. `rehire` always asks, whatever the list - * says, because a repair is the person's call. `brokenSeats` only reads, and - * never asks. Omitted, `hire` and `fire` are the blocks themselves, exactly as - * before the option existed. - * - * A verb that asks needs durable execution: the answer arrives later, through - * the engine's resume route, and a restart in between leaves the ask standing. - * In an app without it, the tool refuses by name and changes nothing. - * - * The blocks an action mounts directly (`createSeatHireBlocks`) never ask: the - * person calling that action already decided. - * - * ## Why this is a sibling of `createWorkforceCapability`, not a preset on it - * - * That capability's door is a control *because* composing it means "you may - * ask what is around you." Hire is a grant a seat must name. Different fence, - * different factory. - */ - -import { defineCapability, handler, SuspensionError, SuspensionRejectedError } from "@flow-state-dev/core"; -import type { DefinedCapability } from "@flow-state-dev/core"; -import type { BlockContext, BlockDefinition } from "@flow-state-dev/core/types"; -import type { ZodTypeAny } from "zod"; -import { defineHiredRosterCollection } from "./roster/collections"; -import { defineSeatInventoryCollection } from "./inventory/collections"; -import { HIRED_ROSTER_RESOURCE, SEAT_INVENTORY_RESOURCE } from "./seat-hire-keys"; -import { - buildSeatHire, - createSeatHireBlocks, - hiredSeatOwnerPinFromRosterOwner, - registerHiredSeat, - type HiredSeatOwnerPin, - type SeatHireBlocks, - type SeatHireCapabilityOptions, - type SeatHireChecked, - type SeatHireVerb, -} from "./seat-hire-blocks"; - -/** The capability name a worker file spells under `capabilities:`. */ -export { SEAT_HIRE_CAPABILITY } from "./seat-hire-keys"; -import { SEAT_HIRE_CAPABILITY } from "./seat-hire-keys"; - -/** Re-exported so existing imports of this module keep resolving. */ -export { - createSeatHireBlocks, - HIRED_ROSTER_RESOURCE, - SEAT_INVENTORY_RESOURCE, - hiredSeatOwnerPinFromRosterOwner, - registerHiredSeat, - type HiredSeatOwnerPin, - type SeatHireBlocks, - type SeatHireCapabilityOptions, -}; - -/** A roster change a Lab can put behind a person's approval. */ -export type SeatHireAskVerb = "hire" | "fire"; - -/** What a seat-hire approval carries in its `data`, for Inbox and the screens that read it. */ -export interface SeatHireAskData { - verb: SeatHireAskVerb | "rehire"; - seatId: string; - /** The kind hired or re-hired onto, the kind a fired seat stored, or `null` for a row that does not read. */ - kind: string | null; - /** The member whose own seat this is; `null` for an org-visible seat, and for a hire. */ - owner: string | null; - /** - * Which hire wrote the row the person is asked about; `null` when there is - * no row (a hire) or the row carries none. Approve changes that row only: a - * seat id that names another row by then is refused, and so is a row that - * carries none, since a replacement written the same way can't be told apart. - */ - incarnation: string | null; -} - -export interface SeatHireToolOptions extends SeatHireCapabilityOptions { - /** - * Which of `hire` and `fire` ask a person before they write. Default `[]`: - * neither asks. `rehire` is not controlled by this option: it always asks, - * so it needs durable execution whatever this says. - */ - askBefore?: readonly SeatHireAskVerb[]; -} - -const ASK_VERBS: readonly SeatHireAskVerb[] = ["hire", "fire"]; - -/** - * Build the seat-hire capability. - * - * @param options The worker flows, register/unregister, the optional allowlist / - * board ids, and `askBefore`. Org is never an option: it comes from the - * principal at the call. - * @returns A capability named `seat-hire`, contributing catalog `hire`, - * `fire`, `brokenSeats` and `rehire`, and installing the roster and - * seat-inventory collections. - * @throws when `askBefore` names a verb other than `hire` or `fire`. - */ -export function createSeatHireCapability(options: SeatHireToolOptions): DefinedCapability { - const askBefore = new Set(options.askBefore ?? []); - for (const verb of askBefore) { - if (!ASK_VERBS.includes(verb)) { - throw new Error(`askBefore names "${String(verb)}"; it takes ${ASK_VERBS.join(" and ")}.`); - } - } - const { blocks, verbs } = buildSeatHire(options); - - const hire = askBefore.has("hire") ? asking(blocks.hire, "hire", verbs.hire) : blocks.hire; - const fire = askBefore.has("fire") ? asking(blocks.fire, "fire", verbs.fire) : blocks.fire; - const rehire = asking(blocks.rehire, "rehire", verbs.rehire); - - return defineCapability({ - name: SEAT_HIRE_CAPABILITY, - resources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection(), - }, - presets: { - tools: { tools: [hire, fire, blocks.brokenSeats, rehire] }, - default: ["tools"], - }, - }); -} - -/** What the ask says, in Inbox's words. */ -function askMessage(data: SeatHireAskData): string { - const kind = data.kind === null ? "" : ` (kind "${data.kind}")`; - switch (data.verb) { - case "hire": - return `Hire seat "${data.seatId}"${kind}?`; - case "fire": - return `Fire seat "${data.seatId}"${kind}?`; - case "rehire": - return `Re-hire seat "${data.seatId}" onto${kind === "" ? " a new kind" : kind}?`; - } -} - -/** - * A verb's tool that asks first: check, ask, then make the change, whose own - * refusals are the check again. - * - * The runtime re-enters the tool from the top on Approve, and on a restart - * that picks up an approved request. What the first check found is kept on - * the request (`runOnce`), so the change made on Approve is bound to the row - * the person was asked about: if the seat id names another row by then (the - * seat was fired and hired again), the change is refused. The write runs its - * own refusals again too, so a change that has since stopped being possible - * is refused rather than made. A re-entry after the change landed meets its - * write's own refusal (a second hire of one id) or no-op (a fire of a seat - * already gone), so it is never made twice. - */ -function asking( - block: BlockDefinition, - verb: SeatHireAskData["verb"], - run: SeatHireVerb, -): BlockDefinition { - return handler({ - name: block.name, - description: `${block.description ?? ""} Waits for a person's approval first; a denial changes nothing.`.trim(), - inputSchema: block.inputSchema as ZodTypeAny, - outputSchema: block.outputSchema as ZodTypeAny, - execute: async (input: I, ctx: BlockContext) => { - const checked = await checkedOnce(run, input, ctx); - const data: SeatHireAskData = { verb, seatId: input.seatId, ...checked }; - const cannotAsk = (why: string) => - new Error(`"${block.name}" waits for a person's approval here, and this app can't ask for one: ${why} Nothing was changed.`); - if (ctx.suspend === undefined) throw cannotAsk("it runs without durable execution."); - try { - await ctx.suspend({ - reason: "human_approval", - message: askMessage(data), - data: { ...data }, - allow: ["approve", "reject"], - }); - } catch (error) { - // The ask itself, and a denial on resume, are control flow the runtime - // handles. Anything else is an app that cannot hold an ask. - if (error instanceof SuspensionError || error instanceof SuspensionRejectedError) throw error; - throw cannotAsk(error instanceof Error ? error.message : String(error)); - } - return await run.run(input, ctx, checked); - }, - }) as unknown as BlockDefinition; -} - -/** - * The verb's check as it ran before the ask: run once per tool call and kept - * on the request, so a re-entry after Approve, or after a restart, binds the - * change to what the person saw. A refusal is kept as its message and thrown - * fresh, because a rejecting `runOnce` would leave an unhandled rejection. - */ -async function checkedOnce(run: SeatHireVerb, input: I, ctx: BlockContext): Promise { - const call = ctx._blockIdentity?.blockInstanceId; - if (ctx.runOnce === undefined || call === undefined) return run.check(input, ctx); - const kept = await ctx.runOnce(`seat-hire-ask:${call}`, async () => { - try { - return { checked: await run.check(input, ctx) }; - } catch (error) { - return { refused: error instanceof Error ? error.message : String(error) }; - } - }); - if ("refused" in kept) throw new Error(kept.refused); - return kept.checked; -} diff --git a/packages/workforce/src/seat-hire-keys.ts b/packages/workforce/src/seat-hire-keys.ts deleted file mode 100644 index 93503ccd83..0000000000 --- a/packages/workforce/src/seat-hire-keys.ts +++ /dev/null @@ -1,44 +0,0 @@ -/** - * The two registry keys the seat-hire capability installs its collections - * under — the hired roster and the seat inventory — the key a flow mounts the - * user-owned roster under, and the org roster's collection pattern, which a - * panel finds the roster by. - * - * A leaf module on purpose (BP-019). The keys are what a browser panel needs - * to read a collection through the client, and they used to live in - * `seat-hire-blocks.ts` next to the handlers that use them. That module - * imports `hireWorkforce`, so a client component asking for one string pulled - * the whole hire runtime — and, through the skills library and the task board, - * `node:async_hooks` — into the browser bundle. Nothing here imports anything, - * so a panel gets the names and no runtime. - */ - -/** Registry key the capability installs the durable roster under. */ -export const HIRED_ROSTER_RESOURCE = "hiredRoster"; - -/** - * Registry key a flow mounts the user-owned roster - * (`defineHiredRosterPrivateCollection()`) under, for `fire`, `brokenSeats` - * and `rehire` to reach the caller's own user-owned seats. The capability does - * not install it; a flow that has none reaches org-visible seats only. - */ -export const HIRED_ROSTER_PRIVATE_RESOURCE = "hiredRosterPrivate"; - -/** Registry key the capability installs the seat inventory under. */ -export const SEAT_INVENTORY_RESOURCE = "seatInventory"; - -/** - * The pattern of the org roster, the collection a browser may read. One - * segment, so a nested `workforce/roster/~user/seat` key never matches it. - * Pinned; see `roster/collections.ts`'s header. - */ -export const HIRED_ROSTER_BROWSER_PATTERN = "workforce/roster/*"; - -/** The capability name a worker file spells under `capabilities:`. */ -export const SEAT_HIRE_CAPABILITY = "seat-hire"; - -/** - * The seat-hire capability's tool names. A seat a tool hires never carries - * them: roster admin stays with the seats the app declares. - */ -export const SEAT_ADMIN_TOOLS: readonly string[] = ["hire", "fire", "rehire", "brokenSeats"]; diff --git a/packages/workforce/src/seat-packages.ts b/packages/workforce/src/seat-packages.ts index d5f9c09d2c..a8c8855725 100644 --- a/packages/workforce/src/seat-packages.ts +++ b/packages/workforce/src/seat-packages.ts @@ -19,7 +19,6 @@ import { packageResourceMessage, type PackageManifest } from "./manifest"; -import { splitSeatAddress } from "./roster/address"; import { parseDeclaredSeatId } from "./seat-references"; /** One package a seat holds, with the blocks its address carries on the generated map. */ @@ -49,26 +48,17 @@ export interface HeldPackages { * worker-level entry must name this seat's worker and a team-level one its * team; any other is refused, and nothing is held. * @param packageBlocks The generated map, keyed by package address. - * @param orgId The organization a hired seat's address carries, passed only - * when `seatId` IS that address (a record with no `seatId`): peeling it off a - * bare seat id would misread a team named like the org. The org is peeled off with - * `splitSeatAddress`, so an org seat hired as `.` reads as the - * org seat it is. Without it, the declared id is the address's last two - * segments, which is right for every id the tree declares. */ export function resolveHeldPackages( seatId: string, declared: unknown, reach: readonly PackageManifest[] | undefined, - packageBlocks: Record>>, - orgId?: string + packageBlocks: Record>> ): HeldPackages { const problems: string[] = []; - // A hired record with no `seatId` passes its address and the org to peel off - // it. What remains is parsed whole, never cut down: `a.b.c` matches neither - // shape, and its last two segments would read as a seat on team `b`. - const declaredPart = (orgId === undefined ? undefined : splitSeatAddress(orgId, seatId)) ?? seatId; - const declaredId = parseDeclaredSeatId(declaredPart); + // Parsed whole, never cut down: `a.b.c` matches neither shape, and its + // last two segments would read as a seat on team `b`. + const declaredId = parseDeclaredSeatId(seatId); // With nothing in reach and no line, there is nothing to place: a hand-built // record keyed some other way is not this step's to refuse. if (declaredId === undefined && (reach ?? []).length === 0 && declared === undefined) { diff --git a/packages/workforce/src/seat-references.ts b/packages/workforce/src/seat-references.ts index 410dedbd33..f5ddc450e9 100644 --- a/packages/workforce/src/seat-references.ts +++ b/packages/workforce/src/seat-references.ts @@ -300,11 +300,11 @@ const unreachableSeatReferenceMessage = (ref: string, seatId: string): string => * the failure this convention exists to end. */ const referencesNotDeclaredMessage = (refs: readonly string[]): string => - `is hired onto a kind holding ${refs.length} reference(s) that hireWorkforce was not given: ` + + `runs on a flow holding ${refs.length} reference(s) its installation was not given: ` + `${refs.map((ref) => `"${ref}"`).join(", ")}. A reference's reach is derived from where its ` + `file sits, and that can only be worked out against the app's own catalog — so without it ` + `every seat would reach every team's references and nothing would say so. Pass the same map ` + - `you installed on the kind: \`hireWorkforce(workers, { references: referencesFromDocs(refs) })\`.`; + `you declared on the flow: \`createWorkerInstallation({ references: referencesFromDocs(refs) })\`.`; /** * The wording for a seat whose id names no place in the tree. diff --git a/packages/workforce/src/seat-resources.ts b/packages/workforce/src/seat-resources.ts index db9206ea4b..4022442f7b 100644 --- a/packages/workforce/src/seat-resources.ts +++ b/packages/workforce/src/seat-resources.ts @@ -167,8 +167,8 @@ const seatResourceRwOnUnwritableMessage = (ref: string): string => * lockout that reads like a roster full of typos. */ const seatResourcesWithoutCatalogMessage = (): string => - `declares \`${SEAT_RESOURCES_KEY}:\`, and hireWorkforce was given no documents to resolve it ` + - `against. Pass the app's documents — \`hireWorkforce(workers, { documents: ` + + `declares \`${SEAT_RESOURCES_KEY}:\`, and its installation was given no documents to resolve it ` + + `against. Pass the app's documents — \`createWorkerInstallation({ documents: ` + `resourcesFromDocs(documents) })\` — so a ref can be matched against what the app declared.`; /** diff --git a/packages/workforce/src/worker-lookup.ts b/packages/workforce/src/worker-lookup.ts index ec09a6534a..831f506fdb 100644 --- a/packages/workforce/src/worker-lookup.ts +++ b/packages/workforce/src/worker-lookup.ts @@ -2,47 +2,29 @@ * Which worker a name on a task means: the one lookup the hand-over, the * filing check and the wake all ask. * - * A task names its worker the way `discover` lists it — `eng.coder`, or the - * id a worker was hired under. The lookup answers with the flow id of the one - * worker holding that name for the running request: a worker the files - * declare, a worker hired for the organization, or one the running member - * hired for themselves. The organization comes from the run, and the member - * is the one who filed the task: the session owner when a door checks a name, - * and the filer the ledger stamped on the row (`task.createdBy`) at hand-over, - * whoever runs the drain. Neither comes from the task's own fields, so a name - * cannot reach another organization's worker or a teammate's own (BP-031). + * A task names its worker by id, as `discover` lists it (`eng.coder`). A task + * on a board is handed to a standard worker: one the installation's files + * declare, which every user has. The lookup answers with the flow it runs on, + * whose one registered copy runs it, and the hand-over opens the task's + * session naming the worker in its starting state, which the flow's create + * check confirms. A user's own worker isn't handed board tasks: the session + * would be created by whoever drains the board, who can't name another + * user's worker. * - * **It reads the host's live registry, not the list it booted with.** A hire - * registers its worker the moment it lands and a fire releases it, so a name - * resolves for a worker hired a moment ago and stops resolving the moment the - * worker is fired, with no restart and nothing to rebuild. - * - * A name two workers hold for one caller (the organization's and the caller's - * own) is refused as ambiguous, naming both. Never resolved by precedence: a - * task filed for one would silently run on the other. + * The lookup reads the installation, not a list it booted with, so a worker + * the files no longer declare stops resolving at the next boot. */ -import type { BlockContext, FlowInstance, TaskFlowTarget, TaskStateTarget } from "@flow-state-dev/core/types"; -import { seatAddress } from "./roster/address"; +import type { BlockContext, TaskFlowTarget, TaskStateTarget } from "@flow-state-dev/core/types"; +import { AGENT_KIND } from "./agent-worker-flow"; import { WORKER_TASK_ENTRY } from "./worker-task-entry"; +import type { WorkerInstallation } from "./workers/installation"; import { WORKER_ID_STATE_KEY } from "./workers/keys"; - +import { standardWorkerFlow } from "./workers/standard-workers"; export interface WorkerLookupOptions { - /** - * The flow registered at an id right now — the host registry's own getter - * (`(id) => runtime.registry.get(id)`), the same one the hire tool takes as - * `instanceAt`. Read on every lookup; never a copy. - */ - instanceAt: (id: string) => FlowInstance | undefined; - /** - * The ids of the workers the files declare, as `hireWorkforce` registered - * them. A declared worker is registered at its own id; this list is what - * tells it apart from any other flow registered at that id (a mailbox, say). - * Pass a getter when the lookup is built before the workers are hired; it - * is read on every lookup. - */ - declared: Iterable | (() => Iterable); + /** The installation whose standard workers a task can name. */ + installation: WorkerInstallation; } /** What the lookup answers for one name. */ @@ -50,43 +32,37 @@ export type WorkerLookupAnswer = | { found: true; flowId: string } | { found: false; - reason: "not-found" | "ambiguous"; + reason: "not-found"; /** One sentence naming the worker, for the refusal a door or a hand-over shows. */ message: string; } | { found: false; - /** The name means exactly one worker, but its kind declares no task entry. */ + /** The name means a worker, but its flow declares no task entry. */ reason: "takes-no-tasks"; - /** The one worker the name means, for a caller that wants it for something other than a task. */ + /** The flow the worker runs on, for a caller that wants it for something other than a task. */ flowId: string; message: string; }; -/** The lookup, and the two shapes the framework plugs it in as. */ +/** The lookup, and the shapes the framework plugs it in as. */ export interface WorkerLookup { - /** - * Which worker `name` means for the request `ctx` runs. - * - * @param member Whose own workers count. Defaults to the session owner, the - * filer when a door checks a name; pass `null` to count none. - */ - find(name: string, ctx: BlockContext, member?: string | null): WorkerLookupAnswer; + /** Which worker `name` means: the flow it runs on, or why there is none. */ + find(name: string, ctx?: BlockContext): WorkerLookupAnswer; /** * The per-task target for a list's fallback: - * `dispatcher({ action: "work", session: "per-task", flowKind: lookup.flowKind })`. - * A name nobody holds answers nothing, which refuses the hand-over - * `flow-not-found` naming it; an ambiguous name, or a worker whose kind - * takes no tasks, throws its own sentence. Either way the claim is still - * held, so the task fails through the list's ordinary error path. + * `dispatcher({ action: "work", session: "per-task", flowKind: lookup.flowKind, state: lookup.state })`. + * A name no worker holds answers nothing, which refuses the hand-over + * `flow-not-found` naming it; a worker whose flow takes no tasks throws its + * own sentence. Either way the claim is still held, so the task fails + * through the list's ordinary error path. */ flowKind: TaskFlowTarget; /** - * The per-task child state for a list's fallback, beside {@link flowKind}: - * `dispatcher({ ..., flowKind: lookup.flowKind, state: lookup.state })`. - * Names the worker the task names, so a worker flow's create check - * confirms it when the task's session is created (FIX-1788 BR-18). Read from - * the task the board hands over, never from its input. + * The per-task child state, beside {@link flowKind}: names the worker the + * task names, so the worker flow's create check confirms it when the task's + * session is created. Read from the task the board hands over, never from + * its input. */ state: TaskStateTarget; /** @@ -104,87 +80,42 @@ export interface WorkerLookup { } /** - * Build the worker lookup over the host's live registry. + * Build the worker lookup over an installation. * - * @param options The registry getter and the declared worker ids. - * @returns `find` for the filing check and the wake, `flowKind` for a list's fallback. + * @param options The installation. + * @returns `find` for the filing check and the wake, `flowKind` and `state` for a list's fallback. */ export function createWorkerLookup(options: WorkerLookupOptions): WorkerLookup { - const { instanceAt } = options; - const isDeclared = (id: string): boolean => { - const source = options.declared; - for (const declaredId of typeof source === "function" ? source() : source) { - if (declaredId === id) return true; - } - return false; - }; + const { installation } = options; - const find = (name: string, ctx: BlockContext, member?: string | null): WorkerLookupAnswer => { - // Read exactly as the hire tool reads them when it mints the address, so - // the address looked up is the one a hire registered: `identity.orgId` - // first (`identity.id` is the org's storage key, which can carry the flow), - // and the session owner as the member unless the caller names the filer. - const orgId = ctx.org?.identity.orgId ?? ctx.org?.identity.id; - const userId = member === undefined ? ctx.session.identity.userId : member ?? undefined; - - // Every worker this caller could mean by the name. The addresses carry the - // organization and the owner, so another organization's hire and a - // teammate's own are simply never asked about. - const held: Array<{ id: string; whose: string }> = []; - if (isDeclared(name) && instanceAt(name) !== undefined) { - held.push({ id: name, whose: "declared in the files" }); - } - if (typeof orgId === "string" && orgId.length > 0) { - const org = addressOrUndefined(orgId, name); - if (org !== undefined && instanceAt(org) !== undefined) { - held.push({ id: org, whose: "hired for the organization" }); - } - if (typeof userId === "string" && userId.length > 0) { - const own = addressOrUndefined(orgId, name, userId); - if (own !== undefined && instanceAt(own) !== undefined) { - held.push({ id: own, whose: "your own" }); - } - } - } - - if (held.length === 0) { + const find = (name: string): WorkerLookupAnswer => { + const worker = installation.standardWorker(name); + if (worker === undefined) { return { found: false, reason: "not-found", message: `No worker is named "${name}".` }; } - if (held.length > 1) { - return { - found: false, - reason: "ambiguous", - message: - `"${name}" names ${held.length} workers: ${held.map((h) => `one ${h.whose}`).join(" and ")}. ` + - `Fire or rename one of them so the name means one worker.`, - }; - } - const [only] = held; - const flow = instanceAt(only!.id)!; - if (!Object.prototype.hasOwnProperty.call(flow.task?.actions ?? {}, WORKER_TASK_ENTRY)) { + const flowId = standardWorkerFlow(worker, AGENT_KIND)!; + const flow = installation.workerFlows()[flowId]?.flow as { task?: { actions?: Record } } | undefined; + if (!Object.prototype.hasOwnProperty.call(flow?.task?.actions ?? {}, WORKER_TASK_ENTRY)) { return { found: false, reason: "takes-no-tasks", - flowId: only!.id, - message: `"${name}" takes no tasks: its kind "${flow.kind}" declares no \`${WORKER_TASK_ENTRY}\` task entry.`, + flowId, + message: `"${name}" takes no tasks: its flow "${flowId}" declares no \`${WORKER_TASK_ENTRY}\` task entry.` }; } - return { found: true, flowId: only!.id }; + return { found: true, flowId }; }; - // At hand-over the run is the drain's, so the member is the filer the - // ledger recorded, never the drainer: a teammate's drain must not route a - // task to the teammate's own worker. No recorded filer counts no own worker. - const flowKind: TaskFlowTarget = (task, ctx) => { - const answer = find(task.assignee, ctx, task.filedBy ?? null); + const flowKind: TaskFlowTarget = (task) => { + const answer = find(task.assignee); if (answer.found) return answer.flowId; if (answer.reason === "not-found") return undefined; throw new Error(`[workforce] task "${task.taskId}" could not be handed over: ${answer.message}`); }; - const filingCheck: WorkerLookup["filingCheck"] = (aliases = {}) => (name, listId, ctx) => { + const filingCheck: WorkerLookup["filingCheck"] = (aliases = {}) => (name, listId) => { if (Object.hasOwn(aliases, listId) && aliases[listId]!.includes(name)) return undefined; - const answer = find(name, ctx); + const answer = find(name); return answer.found ? undefined : answer.message; }; @@ -192,12 +123,3 @@ export function createWorkerLookup(options: WorkerLookupOptions): WorkerLookup { return { find, flowKind, state, filingCheck }; } - -/** A hired worker's address, or `undefined` for a name no address can carry. */ -function addressOrUndefined(orgId: string, name: string, userId?: string): string | undefined { - try { - return seatAddress(orgId, name, userId); - } catch { - return undefined; - } -} diff --git a/packages/workforce/src/workers/index.ts b/packages/workforce/src/workers/index.ts index 569955a665..2e759685eb 100644 --- a/packages/workforce/src/workers/index.ts +++ b/packages/workforce/src/workers/index.ts @@ -9,6 +9,11 @@ * - `createWorkerHireBlocks`: hire, fork, edit and fire, as writes to the * caller's roster. * - `defineWorkerRosterFlow`: the flow a client reads a roster through. + * - `hireWorkforce`: the copies to register, one per worker flow, and the + * roster flow. + * - `workerConfigOf`: the configuration of the worker a turn loaded. + * - `workerFlow`: a worker flow built on its installation, for a flow that + * lives in its own file. * - `createWorkforceClient`: find or start a session with a worker. Exported * from `./browser` only: it is an app's, and the server never calls it. */ @@ -34,9 +39,13 @@ export { verifiedWorkerOf, WorkerTurnRefusedError, type ResolvedWorker, + type WorkerGrants, type WorkerInstallation, type WorkerInstallationOptions, type WorkerTurnContext } from "./installation"; export { createWorkerHireBlocks, type WorkerHireBlocks } from "./hire-blocks"; export { defineWorkerRosterFlow } from "./roster-flow"; +export { hireWorkforce, inventorySeats, type HireWorkforceOptions } from "./register"; +export { workerConfigOf } from "./verified-worker"; +export { workerFlow, type WorkerFlowBuilder } from "./worker-flow"; diff --git a/packages/workforce/src/workers/installation.ts b/packages/workforce/src/workers/installation.ts index 38abc4f1cc..ce95dfed0b 100644 --- a/packages/workforce/src/workers/installation.ts +++ b/packages/workforce/src/workers/installation.ts @@ -27,23 +27,25 @@ import type { SessionCreateCheckInput, SessionCreateCheckResult } from "@flow-state-dev/core/types"; -import type { DeclaredResources } from "@flow-state-dev/core"; +import type { DeclaredResources, ResourceVisibilityRule } from "@flow-state-dev/core"; import { z } from "zod"; -import { AGENT_KIND } from "../agent-worker-flow"; +import { AGENT_KIND, defineAgentWorkerFlow } from "../agent-worker-flow"; import { hireRefusalReasons, - hireWorkforce, + mintSeats, resolveWorkerFlows, standardOnlyReason, type HireOptions, - type ResolvedWorkerFlow + type ResolvedWorkerFlow, + type WorkerFlowEntry } from "../hire"; +import { isWorkerFlowBuilder, type WorkerFlowBuilder } from "./worker-flow"; import type { PackageManifest, WorkerManifest } from "../manifest"; import { deriveWorkerSessionId, isDerivedWorkerSessionId } from "./derive-session-id"; import { STANDARD_WORKERS_RESOURCE, WORKERS_RESOURCE, WORKER_ID_STATE_KEY } from "./keys"; import { defineStandardWorkerCollection, standardWorkerFlow } from "./standard-workers"; import { defineWorkerCollection, parseWorkerRow, type WorkerRow } from "./worker-row"; -import { markVerifiedWorker } from "./verified-worker"; +import { grantedAccessOf, markVerifiedWorker, type GrantedAccess } from "./verified-worker"; export { verifiedWorkerOf } from "./verified-worker"; @@ -115,6 +117,25 @@ export interface ResolvedWorker { reaches(accessor: string): boolean; } +/** The two ways an installation's documents and references are handed to a worker flow. */ +export interface WorkerGrants { + /** + * Every document and reference a worker may be granted, by accessor. A + * worker flow whose model reaches documents declares them all in its + * `resources`, and sets {@link resourceVisibility} so each turn's model + * reaches only its worker's. + */ + readonly documents: DeclaredResources; + /** + * The flow's `resourceVisibility`: on each turn, a granted document is + * visible to the model's resource tools when the worker `resolveWorker` + * loaded on this turn reaches it, read-only when its grant is, and hidden + * otherwise, including on a turn that loaded no worker. Every other resource + * is visible. + */ + readonly resourceVisibility: ResourceVisibilityRule; +} + /** * Thrown when a turn can't run as the session's worker: it was fired, now * names another flow, names something the installation no longer registers, @@ -134,7 +155,7 @@ export class WorkerTurnRefusedError extends Error { } /** The installation's worker model. Build it once, at boot. */ -export interface WorkerInstallation { +export interface WorkerInstallation extends WorkerGrants { /** * The two worker collections: the user's own workers, and the standard * ones projected from the files. A worker flow spreads them into its @@ -165,7 +186,11 @@ export interface WorkerInstallation { /** * The worker this turn runs as, loaded now: the session's worker read from * the user's roster or the standard workers, with its configuration - * resolved. Call it at the start of every turn on a worker flow. + * resolved. Call it on every turn of a worker flow: in the flow's + * `request.onStarted`, which runs again when a request resumes, or in the + * block that reads the worker. Not in an earlier step of the turn: a + * resumed request reuses a finished step's recorded output without running + * it, so the worker it loaded is gone on the resumed run. * * @param ctx The block's context. The block must declare {@link resources}. * @param flowKind The running flow's kind. @@ -174,6 +199,8 @@ export interface WorkerInstallation { resolveWorker(ctx: WorkerTurnContext, flowKind: string): Promise; /** A standard worker by id, or `undefined`. */ standardWorker(id: string): WorkerManifest | undefined; + /** Every standard worker, by id order. */ + standardWorkers(): readonly WorkerManifest[]; /** The worker flows, resolved: each one's flow and whether it is kept for standard workers. */ workerFlows(): Record; /** @@ -184,6 +211,14 @@ export interface WorkerInstallation { * @returns The reasons it would be refused; empty when it would run. */ configurationProblems(id: string, row: WorkerRow): string[]; + /** + * Check every standard worker the same way, as its file declares it. Used by + * `hireWorkforce`, which refuses to register anything while one would be + * refused on its first turn. + * + * @returns Each refusal, prefixed with the worker's id; empty when every one would run. + */ + standardWorkerProblems(): string[]; } /** The settings a row hands its flow: its own settings, keyed as a `WORKER.md` frontmatter. */ @@ -213,8 +248,29 @@ export function createWorkerInstallation(options: WorkerInstallationOptions = {} standard.set(manifest.id, manifest); } - const workerFlowsOption = (): HireOptions["workerFlows"] => - typeof options.workerFlows === "function" ? options.workerFlows() : options.workerFlows; + // The built-in `agent`, bound to this installation, unless the app passes + // its own: built on first use, once, so every turn checks its workers + // against the one copy `hireWorkforce` registers. + let boundAgent: unknown; + // A `workerFlow(...)` builder, built on this installation once. + const built = new Map(); + const buildOf = (entry: WorkerFlowEntry): WorkerFlowEntry => { + if (!isWorkerFlowBuilder(entry)) return entry; + let flow = built.get(entry); + if (flow === undefined) { + flow = { flow: entry.build(installation) as never, standardOnly: entry.standardOnly }; + built.set(entry, flow); + } + return flow; + }; + const workerFlowsOption = (): HireOptions["workerFlows"] => { + const read = typeof options.workerFlows === "function" ? options.workerFlows() : options.workerFlows; + const given = + read === undefined ? undefined : Object.fromEntries(Object.entries(read).map(([kind, entry]) => [kind, buildOf(entry)])); + if (given !== undefined && Object.hasOwn(given, AGENT_KIND)) return given; + boundAgent ??= defineAgentWorkerFlow({ installation }); + return { [AGENT_KIND]: boundAgent as never, ...given }; + }; let resolvedFlows: Record | undefined; const workerFlows = (): Record => (resolvedFlows ??= resolveWorkerFlows(workerFlowsOption())); @@ -237,6 +293,9 @@ export function createWorkerInstallation(options: WorkerInstallationOptions = {} const sessionStateShape = { [WORKER_ID_STATE_KEY]: z.string().min(1).readonly() } as const; + /** Every resource a worker may be granted: the documents and the references. */ + const documents: DeclaredResources = Object.freeze({ ...(options.documents ?? {}), ...(options.references ?? {}) }); + /** * What `hireWorkforce` would refuse this worker for, or the instance it * would mint. Nothing is registered: the instance is read and dropped. @@ -250,7 +309,7 @@ export function createWorkerInstallation(options: WorkerInstallationOptions = {} manifest: WorkerManifest ): { ok: true; seat: FlowInstance } | { ok: false; problems: string[] } => { try { - const [seat] = hireWorkforce([manifest], { + const [seat] = mintSeats([manifest], { workerFlows: workerFlowsOption(), ...(options.seatBlocks !== undefined ? { seatBlocks: options.seatBlocks } : {}), ...(options.packageBlocks !== undefined ? { packageBlocks: options.packageBlocks } : {}), @@ -329,6 +388,12 @@ export function createWorkerInstallation(options: WorkerInstallationOptions = {} return minted.ok ? [] : minted.problems; }; + const standardWorkerProblems = (): string[] => + [...standard.values()].flatMap((manifest) => { + const minted = mint(manifest); + return minted.ok ? [] : minted.problems.map((problem) => `worker "${manifest.id}" — ${problem}`); + }); + const createCheck: SessionCreateCheck = async ( input: SessionCreateCheckInput ): Promise => { @@ -437,7 +502,15 @@ export function createWorkerInstallation(options: WorkerInstallationOptions = {} const seat = (minted as { seat: FlowInstance }).seat; const reached = (seat.resources ?? {}) as Record; - markVerifiedWorker(ctx.session as object, workerId); + // What the worker's grants let its model do with each grantable resource: + // the mint narrows a read-only grant by turning its write flags off. + const granted = new Map(); + for (const accessor of Object.keys(documents)) { + if (!Object.hasOwn(reached, accessor)) continue; + const entry = reached[accessor] as { llmWritable?: unknown; writable?: unknown }; + granted.set(accessor, entry.llmWritable === true && entry.writable !== false ? "visible" : "read-only"); + } + markVerifiedWorker(ctx.session as object, workerId, seat.config as Readonly>, granted); return { id: workerId, standard: worker.found === "standard", @@ -448,8 +521,11 @@ export function createWorkerInstallation(options: WorkerInstallationOptions = {} }; }; - return { + const installation: WorkerInstallation = { resources, + documents, + resourceVisibility: (ctx, { name }) => + Object.hasOwn(documents, name) ? (grantedAccessOf(ctx.session as object, name) ?? "hidden") : "visible", sessionStateShape, createCheck, session(extraShape) { @@ -460,7 +536,10 @@ export function createWorkerInstallation(options: WorkerInstallationOptions = {} }, resolveWorker, standardWorker: (id) => standard.get(id), + standardWorkers: () => [...standard.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)), workerFlows, - configurationProblems + configurationProblems, + standardWorkerProblems }; + return installation; } diff --git a/packages/workforce/src/workers/register.ts b/packages/workforce/src/workers/register.ts new file mode 100644 index 0000000000..8c003c2a8b --- /dev/null +++ b/packages/workforce/src/workers/register.ts @@ -0,0 +1,109 @@ +/** + * `hireWorkforce`: the flows an installation registers, one copy each. + * + * Every worker runs on one shared copy of the flow it names: the built-in + * `agent` and every flow the installation was given. A worker is data (a + * row its owner holds, or a standard worker from the files), so hiring one + * registers nothing, and nothing here mints a copy per worker or pins one to + * an owner. Beside the worker flows sits the roster flow, through which an + * app reads and writes a user's roster. + */ +import { firstInProcess } from "@flow-state-dev/core"; +import type { FlowInstance } from "@flow-state-dev/core/types"; +import { AGENT_KIND } from "../agent-worker-flow"; +import { checkWorkerFlows, unattendedBoardWarnings } from "../hire"; +import type { InventorySeat } from "../inventory/open-inventory"; +import { createWorkerHireBlocks } from "./hire-blocks"; +import type { WorkerInstallation } from "./installation"; +import { defineWorkerRosterFlow } from "./roster-flow"; +import { standardWorkerFlow } from "./standard-workers"; + +/** + * Whether `flow` runs this installation's workers: it declares the + * installation's session, whose create check names the session's worker. + */ +export function runsWorkersOf(flow: { readonly session?: unknown }, installation: WorkerInstallation): boolean { + return (flow.session as { createCheck?: unknown } | undefined)?.createCheck === installation.createCheck; +} + +/** What `hireWorkforce` takes beside the installation. */ +export interface HireWorkforceOptions { + /** + * The ledger ids of the boards the app's mailboxes declare + * (`mailboxBoardIds(mailboxes)`). A board no registered copy declares is + * named once per process in a warning: rows filed there sit pending until + * something drains them. + */ + mailboxBoards?: readonly string[]; +} + +/** + * The copies to register for `installation`: one per worker flow, at the + * flow's kind, and the roster flow with its `hire`, `fork`, `edit` and + * `fire` actions. Register every one. + * + * @throws When a worker flow misses the worker contract (a door, the + * configuration a worker is handed, shared resources through + * `sharedResource()`). Every problem with every flow is named, whatever + * the workers hold. + * @throws When a worker flow doesn't declare the installation's session + * (`session: installation.session()`): its sessions would run no checked + * worker. Every such flow is named. + * @throws When a standard worker would be refused on its first turn (a tool, + * a skill or a setting its flow won't take). Every such worker is named, + * and nothing is registered: a short roster that still runs is the failure. + */ +export function hireWorkforce(installation: WorkerInstallation, options: HireWorkforceOptions = {}): FlowInstance[] { + checkWorkerFlows(installation.workerFlows()); + const copies: FlowInstance[] = []; + const unbound: string[] = []; + for (const [kind, { flow }] of Object.entries(installation.workerFlows()).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) { + const copy = (flow as unknown as (options: { id: string }) => FlowInstance)({ id: kind }); + if (!runsWorkersOf(copy, installation)) unbound.push(kind); + copies.push(copy); + } + if (unbound.length > 0) { + throw new Error( + `hireWorkforce: worker flow${unbound.length === 1 ? "" : "s"} ${unbound.map((kind) => `"${kind}"`).join(", ")} ` + + `${unbound.length === 1 ? "doesn't" : "don't"} declare this installation's session, so ${unbound.length === 1 ? "its" : "their"} ` + + `sessions would run no checked worker. Declare \`session: installation.session()\` on each, and load the worker ` + + `with \`installation.resolveWorker\` on every turn (the flow's \`request.onStarted\` runs on a resumed one too).` + ); + } + const problems = installation.standardWorkerProblems(); + if (problems.length > 0) { + throw new Error( + `hireWorkforce: ${problems.length} standard worker problem(s); nothing was registered:\n` + + problems.map((problem) => ` - ${problem}`).join("\n") + ); + } + const { hire, fork, edit, fire } = createWorkerHireBlocks(installation); + const roster = defineWorkerRosterFlow(installation, { + hire: { inputSchema: hire.inputSchema, block: hire }, + fork: { inputSchema: fork.inputSchema, block: fork }, + edit: { inputSchema: edit.inputSchema, block: edit }, + fire: { inputSchema: fire.inputSchema, block: fire } + }); + copies.push(roster() as unknown as FlowInstance); + for (const boardId of options.mailboxBoards ?? []) { + for (const warning of unattendedBoardWarnings([boardId], copies)) { + if (firstInProcess(`workforce/unattended-board/${boardId}`)) console.warn(warning); + } + } + return copies; +} + +/** + * The installation's standard workers as `openInventory` takes seats: each + * worker's id, the flow it runs on, and that flow's actions, which its door is + * read from. The org's inventory lists these, the workers every member has; a + * user's own workers are theirs, on their roster. + */ +export function inventorySeats(installation: WorkerInstallation): InventorySeat[] { + const flows = installation.workerFlows(); + return installation.standardWorkers().map((worker) => { + const kind = standardWorkerFlow(worker, AGENT_KIND)!; + const actions = (flows[kind]?.flow as { actions?: Readonly> } | undefined)?.actions ?? {}; + return { id: worker.id, kind, actions }; + }); +} diff --git a/packages/workforce/src/workers/verified-worker.ts b/packages/workforce/src/workers/verified-worker.ts index 5bd7aa5ff3..0b9127303f 100644 --- a/packages/workforce/src/workers/verified-worker.ts +++ b/packages/workforce/src/workers/verified-worker.ts @@ -1,20 +1,47 @@ /** - * The worker each running request's turn was verified to run as, by the - * session handle its blocks share. A leaf module, so attribution - * (`writeShared`) reads it without importing the worker model. + * The worker each running request's turn was verified to run as, and that + * worker's configuration, by the session handle its blocks share. A leaf + * module, so attribution (`writeShared`) and the flows that read a worker's + * settings reach it without importing the worker model. */ -const verified = new WeakMap(); +/** What the worker's grants let its model do with one granted resource. */ +export type GrantedAccess = "visible" | "read-only"; + +type Verified = { + readonly workerId: string; + readonly config: Readonly>; + /** The documents and references the worker reaches, by accessor. */ + readonly granted: ReadonlyMap; +}; + +const verified = new WeakMap(); /** - * Record that this request's turn runs as `workerId`: the session's worker, - * as `resolveWorker` loaded and checked it. + * Record that this request's turn runs as `workerId`, with `config`: the + * session's worker, as `resolveWorker` loaded and checked it. * * @param session The block context's `session` handle, the same object for * every block of one request. */ -export function markVerifiedWorker(session: object, workerId: string): void { - verified.set(session, workerId); +export function markVerifiedWorker( + session: object, + workerId: string, + config: Readonly>, + granted: ReadonlyMap = new Map() +): void { + verified.set(session, { workerId, config, granted }); +} + +/** + * What the worker this request's turn was verified to run as may do with the + * granted resource under `accessor`, or `undefined` when it isn't granted it + * or no worker was resolved. + * + * @param session The block context's `session` handle. + */ +export function grantedAccessOf(session: object, accessor: string): GrantedAccess | undefined { + return verified.get(session)?.granted.get(accessor); } /** @@ -26,5 +53,41 @@ export function markVerifiedWorker(session: object, workerId: string): void { * @param session The block context's `session` handle. */ export function verifiedWorkerOf(session: object): string | undefined { - return verified.get(session); + return verified.get(session)?.workerId; +} + +/** + * The settings this turn runs with: the configuration of the worker the turn + * resolved, or, on a turn that resolved none, the flow copy's own + * `ctx.flow.config`. Synchronous: the worker was loaded at the start of the + * turn, so a prompt, a tool list or a step condition can read it. + * + * @param ctx Any block's context. + */ +export function seatConfigOf(ctx: { + readonly session: object; + readonly flow?: { readonly config: unknown }; +}): Readonly> { + return ( + verified.get(ctx.session)?.config ?? + ((ctx.flow?.config ?? {}) as Readonly>) + ); +} + +/** + * The configuration of the worker this turn loaded with `resolveWorker`, for a + * block of a worker flow that reads a setting after the turn's first step: + * the same value `resolveWorker` returned as `config`. Synchronous, so a + * prompt, a tool list or a step condition can read it. + * + * @param ctx Any block's context in the turn. + * @throws When the turn loaded no worker: call `installation.resolveWorker` + * in the flow's `request.onStarted`. + */ +export function workerConfigOf(ctx: { readonly session: object }): Readonly> { + const found = verified.get(ctx.session); + if (found === undefined) { + throw new Error("This turn loaded no worker: call installation.resolveWorker(ctx, flowKind) in the flow's request.onStarted."); + } + return found.config; } diff --git a/packages/workforce/src/workers/worker-flow.ts b/packages/workforce/src/workers/worker-flow.ts new file mode 100644 index 0000000000..c26a8d7485 --- /dev/null +++ b/packages/workforce/src/workers/worker-flow.ts @@ -0,0 +1,54 @@ +/** + * `workerFlow`: a worker flow built on the installation that runs its workers. + * + * A worker flow declares its installation's session and resources, so it is + * built with the installation in hand. An app that defines its flows beside + * the installation passes them in `workerFlows` already built. A flow that + * lives in its own file, under `workforce/flows/workers/` where `fsdev gen` + * finds it, has no installation to import, so its module exports a builder + * instead, and the installation builds it, once, with itself: + * + * ```ts + * // workforce/flows/workers/desk-clerk.ts + * export default workerFlow((installation) => + * defineFlow({ + * kind: "desk-clerk", + * session: installation.session(), + * resources: { ...installation.resources }, + * ... + * }) + * ); + * ``` + */ +import type { WorkerInstallation } from "./installation"; + +const BUILDER = Symbol.for("flow-state-dev/workforce/worker-flow"); + +/** A worker flow waiting for its installation. See {@link workerFlow}. */ +export interface WorkerFlowBuilder { + readonly [BUILDER]: true; + /** Builds the flow on the installation that runs its workers. Called once per installation. */ + readonly build: (installation: WorkerInstallation) => unknown; + /** Whether the app keeps the flow for the workers its files define. */ + readonly standardOnly: boolean; +} + +/** + * Declare a worker flow built on its installation. + * + * @param build Builds the flow (`defineFlow({ ..., session: installation.session() })`). + * @param options `standardOnly` keeps the flow for the workers the app's files define. + * @returns An entry for `createWorkerInstallation({ workerFlows })`, and for + * the `kinds` map `fsdev gen` writes. + */ +export function workerFlow( + build: (installation: WorkerInstallation) => unknown, + options: { standardOnly?: boolean } = {} +): WorkerFlowBuilder { + return { [BUILDER]: true, build, standardOnly: options.standardOnly === true }; +} + +/** Whether a `workerFlows` entry is a {@link workerFlow} builder. */ +export function isWorkerFlowBuilder(entry: unknown): entry is WorkerFlowBuilder { + return typeof entry === "object" && entry !== null && (entry as Record)[BUILDER] === true; +} diff --git a/packages/workforce/src/workforce-capability.ts b/packages/workforce/src/workforce-capability.ts index 594ffec615..6d13913a6f 100644 --- a/packages/workforce/src/workforce-capability.ts +++ b/packages/workforce/src/workforce-capability.ts @@ -68,12 +68,6 @@ export interface WorkforceCapabilityOptions { * fewer — an ordinary state, not an error. */ inventory: InventoryKeys; - /** - * Registry key for the durable hired roster. When set, Discover treats a - * roster row with no file as the declared half for that seat, so a runtime - * hire is visible on the same lookup Labs already use. - */ - hiredRoster?: string; /** * Other domains' sources to put behind the same door — `skillsManifestSource()` * from `@flow-state-dev/orchestration`, `resourcesManifestSource()` from @@ -127,7 +121,6 @@ export function createWorkforceCapability( ...workforceManifestSources({ roster: options.roster, inventory: options.inventory, - hiredRoster: options.hiredRoster, }), ...(options.sources ?? []), ]); diff --git a/packages/workforce/test/agent-drawer-seeded-worker.test.ts b/packages/workforce/test/agent-drawer-seeded-worker.test.ts index 3eff3ca906..5849c620ff 100644 --- a/packages/workforce/test/agent-drawer-seeded-worker.test.ts +++ b/packages/workforce/test/agent-drawer-seeded-worker.test.ts @@ -16,13 +16,13 @@ import { describe, expect, it } from "vitest"; import { DEFAULT_ORG_ID } from "@flow-state-dev/core"; import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; import { createMockModelResolver, mockGenerator } from "@flow-state-dev/testing"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; const ORG = DEFAULT_ORG_ID; const SKILL_MD = "---\nname: refunds\ndescription: How refunds work\n---\nRefunds take five days."; async function drawerKeys(workers: ReadonlyArray): Promise { - const [seat] = hireWorkforce([ + const [seat] = mintSeats([ { id: "support.otto", declared: {}, body: "You answer questions.", skills: [{ name: "refunds", skillMd: SKILL_MD }] } ]); const keys: string[] = []; diff --git a/packages/workforce/test/agent-grants-per-turn.test.ts b/packages/workforce/test/agent-grants-per-turn.test.ts new file mode 100644 index 0000000000..41428a047a --- /dev/null +++ b/packages/workforce/test/agent-grants-per-turn.test.ts @@ -0,0 +1,150 @@ +/** + * BR-24 on one shared `agent` copy: each worker's model reaches only the + * documents its grants name, on every turn, through core's own resource + * tools. + * + * One registered `agent` copy bound to an installation that declares two + * documents. Two standard workers of one user: one granted `handbook` + * read-only, one granted `ledger` read-write. A scripted model lists what it + * can read, then reads and writes both documents. Graded on what the tools + * handed the model back, and on a write actually landing. + */ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_ORG_ID, + defineResource, + readResourceContentTool, + writeResourceContentTool +} from "@flow-state-dev/core"; +import type { FlowInstance } from "@flow-state-dev/core/types"; +import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; +import { createMockModelResolver, type MockGeneratorInstance } from "@flow-state-dev/testing"; +import { z } from "zod"; +import { defineAgentWorkerFlow } from "../src/agent-worker-flow"; +import { createWorkerInstallation } from "../src/workers/installation"; + +function document(ref: string) { + return defineResource({ + ref, + scope: "org", + stateSchema: z.object({}).passthrough(), + default: {}, + content: `the ${ref} body`, + llmReadable: true, + llmWritable: true + }); +} + +const TOOLS = ["readResourceContent", "writeResourceContent"]; + +/** What the tool handed the model on each turn that called one. */ +type Seen = unknown[]; + +/** + * A turn `call ` gets one step calling that tool with that JSON, + * so the real tool runs; the step after records what it handed back and + * answers. A tool that refuses fails the turn, which the test reads instead. + */ +function scripted(seen: Seen): MockGeneratorInstance { + return { + name: "agent-answer", + calls: [], + reset: () => undefined, + next: (messages: Array<{ role: string; content: unknown }>, state: { toolResults: Array<{ result: unknown }> }) => { + if (state.toolResults.length > 0) { + seen.push(state.toolResults[0]!.result); + return { text: "done" }; + } + const turn = JSON.stringify([...messages].reverse().find((m) => m.role === "user")?.content ?? ""); + const call = /call (\w+) (\{.*\})/.exec(JSON.parse(turn) as string); + if (call === null) return { text: "nothing to call" }; + return { toolCalls: [{ toolCallId: `c${seen.length}`, toolName: call[1]!, args: JSON.parse(call[2]!) }] }; + } + } as unknown as MockGeneratorInstance; +} + +describe("agent's document grants on one copy for every worker (BR-24)", () => { + it("each worker's model lists, reads and writes exactly what its grants allow", async () => { + let flows: Record = {}; + const installation = createWorkerInstallation({ + standardWorkers: [ + { id: "desk.amy", declared: { tools: TOOLS, resources: ["handbook"] }, body: "You are Amy." }, + { id: "desk.bo", declared: { tools: TOOLS, resources: [{ ledger: "rw" }] }, body: "You are Bo." } + ], + documents: { handbook: document("handbook"), ledger: document("ledger") }, + workerFlows: () => flows as never + }); + const agent = defineAgentWorkerFlow({ + installation, + catalog: { readResourceContent: readResourceContentTool(), writeResourceContent: writeResourceContentTool() } + }); + flows = { agent }; + const copy = agent({ id: "agent" }) as unknown as FlowInstance; + const seen: Seen = []; + const state = createFlowState({ + flows: { agent: copy }, + stores: { default: { primary: inMemoryStores() } }, + modelResolver: createMockModelResolver({ generators: { "agent-answer": scripted(seen) }, policy: "allow" }) + }); + try { + const runtime = await state.getRuntime(); + const router = await state.getRouter(); + for (const worker of ["desk.amy", "desk.bo"]) { + const created = await router.POST( + new Request("http://localhost/api/flows/agent/sessions", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ userId: "alice", sessionId: `talk-${worker}`, state: { workerId: worker } }) + }), + { params: { path: ["agent", "sessions"] } } + ); + expect(created.status).toBe(201); + } + /** One turn as `worker` calling `tool`: what the tool handed back, or the turn's error. */ + const call = async (worker: string, tool: string, args: unknown) => { + const before = seen.length; + const turn = await runAction({ + orgId: DEFAULT_ORG_ID, + flow: copy, + actionName: "run", + input: { message: `call ${tool} ${JSON.stringify(args)}` }, + userId: "alice", + sessionId: `talk-${worker}`, + stores: runtime.stores, + runtimeConfig: { ...runtime.runtimeConfig } + }); + if (turn.error !== undefined) return { error: String((turn.error as Error).message) }; + return { result: seen.length > before ? seen[seen.length - 1] : undefined }; + }; + + // Each lists only its own grant. + expect(await call("desk.amy", "readResourceContent", {})).toEqual({ result: { uris: ["org/handbook"] } }); + expect(await call("desk.bo", "readResourceContent", {})).toEqual({ result: { uris: ["org/ledger"] } }); + // Amy reads the handbook and can't write it; the ledger isn't there for her. + expect(JSON.stringify(await call("desk.amy", "readResourceContent", { uri: "org/handbook" }))).toContain("the handbook body"); + expect((await call("desk.amy", "writeResourceContent", { uri: "org/handbook", content: "x" })).error).toContain( + "Writable resource not found for uri: org/handbook" + ); + expect((await call("desk.amy", "readResourceContent", { uri: "org/ledger" })).error).toContain( + "Readable resource not found for uri: org/ledger" + ); + // Bo writes the ledger and reads the write back; the handbook isn't there for him. + expect((await call("desk.bo", "writeResourceContent", { uri: "org/ledger", content: "written by Bo" })).error).toBeUndefined(); + expect(JSON.stringify(await call("desk.bo", "readResourceContent", { uri: "org/ledger" }))).toContain("written by Bo"); + expect((await call("desk.bo", "readResourceContent", { uri: "org/handbook" })).error).toContain( + "Readable resource not found for uri: org/handbook" + ); + } finally { + await state.dispose(); + } + }); +}); + +describe("the installation's resourceVisibility", () => { + it("hides every grantable document on a turn that loaded no worker, and leaves other resources alone", () => { + const installation = createWorkerInstallation({ documents: { handbook: document("handbook") } }); + const ctx = { session: {} } as never; + expect(installation.resourceVisibility(ctx, { name: "handbook", ref: {} as never })).toBe("hidden"); + expect(installation.resourceVisibility(ctx, { name: "audit-log", ref: {} as never })).toBe("visible"); + }); +}); diff --git a/packages/workforce/test/agent-on-installation.test.ts b/packages/workforce/test/agent-on-installation.test.ts new file mode 100644 index 0000000000..ce61782f32 --- /dev/null +++ b/packages/workforce/test/agent-on-installation.test.ts @@ -0,0 +1,114 @@ +/** + * The built-in `agent` run as one copy for every worker, bound to an + * installation. + * + * BR-23: it keeps each worker's skills drawer apart, even between two workers + * of one user. Two standard workers each carry a skill of their own, and the + * same user opens one session with each, created naming the worker. Graded on + * the store after real runs: every drawer write is recorded with the key it + * landed at, and each worker's skill must land in that worker's drawer only. + * + * The session names the worker, so a turn whose input names one is refused, + * not stripped and run. + */ +import { describe, expect, it } from "vitest"; +import { DEFAULT_ORG_ID } from "@flow-state-dev/core"; +import type { FlowInstance } from "@flow-state-dev/core/types"; +import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; +import { createMockModelResolver, mockGenerator } from "@flow-state-dev/testing"; +import { defineAgentWorkerFlow } from "../src/agent-worker-flow"; +import { createWorkerInstallation } from "../src/workers/installation"; + +const skillMd = (name: string) => `---\nname: ${name}\ndescription: ${name}\n---\nHow ${name} work.`; + +/** One `agent` copy running two standard workers, and every drawer key written on it. */ +async function boot() { + let flows: Record = {}; + const installation = createWorkerInstallation({ + standardWorkers: [ + { id: "desk.amy", declared: {}, body: "You are Amy.", skills: [{ name: "refunds", skillMd: skillMd("refunds") }] }, + { id: "desk.bo", declared: {}, body: "You are Bo.", skills: [{ name: "returns", skillMd: skillMd("returns") }] } + ], + workerFlows: () => flows as never + }); + const agent = defineAgentWorkerFlow({ installation }); + flows = { agent }; + const copy = agent({ id: "agent" }) as unknown as FlowInstance; + const drawerKeys: string[] = []; + const state = createFlowState({ + flows: { agent: copy }, + stores: { default: { primary: inMemoryStores() } }, + modelResolver: createMockModelResolver({ + generators: { + "agent-answer": mockGenerator({ name: "agent-answer", script: [{ when: () => true, then: { text: "ok" } }] }) + }, + policy: "allow" + }) + }); + const runtime = await state.getRuntime(); + const router = await state.getRouter(); + const store = runtime.stores.resourceState; + const set = store.set.bind(store); + store.set = ((scopeType: string, scopeId: string, key: string, ...rest: unknown[]) => { + if (key.startsWith("skills/")) drawerKeys.push(key); + return (set as (...args: unknown[]) => Promise)(scopeType, scopeId, key, ...rest); + }) as typeof store.set; + + /** One turn as `alice`, in a session created naming `worker`. */ + const turn = async (worker: string, input: unknown) => { + const sessionId = `conversation-${worker}`; + if ((await runtime.stores.session.get(sessionId)) == null) { + const created = await router.POST( + new Request("http://localhost/api/flows/agent/sessions", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ userId: "alice", sessionId, state: { workerId: worker } }) + }), + { params: { path: ["agent", "sessions"] } } + ); + expect(created.status).toBe(201); + } + return runAction({ + orgId: DEFAULT_ORG_ID, + flow: copy, + actionName: "run", + input, + userId: "alice", + sessionId, + stores: runtime.stores, + runtimeConfig: { ...runtime.runtimeConfig } + }); + }; + return { turn, drawerKeys, dispose: () => state.dispose() }; +} + +describe("agent on one copy for every worker", () => { + it("keeps each of one user's workers' skills in that worker's own drawer (BR-23)", async () => { + const { turn, drawerKeys, dispose } = await boot(); + try { + for (const worker of ["desk.amy", "desk.bo"]) { + expect((await turn(worker, { message: "what do you know?" })).error).toBeUndefined(); + } + } finally { + await dispose(); + } + const drawerOf = (skill: string) => + [...new Set(drawerKeys)] + .filter((key) => key.endsWith(`/${skill}/SKILL.md`)) + .map((key) => decodeURIComponent(key.split("/")[1]!)); + // Each skill is written once, into its own worker's drawer, and nowhere else. + expect(drawerOf("refunds")).toEqual(["desk.amy"]); + expect(drawerOf("returns")).toEqual(["desk.bo"]); + }); + + it("refuses a turn whose input names a worker, and runs the one beside it that doesn't", async () => { + const { turn, dispose } = await boot(); + try { + const named = await turn("desk.amy", { message: "answer as Bo", workerId: "desk.bo" }); + expect(String((named.error as { message?: unknown } | undefined)?.message)).toMatch(/workerId/); + expect((await turn("desk.amy", { message: "hello" })).error).toBeUndefined(); + } finally { + await dispose(); + } + }); +}); diff --git a/packages/workforce/test/agent-resumed-turn-worker.test.ts b/packages/workforce/test/agent-resumed-turn-worker.test.ts new file mode 100644 index 0000000000..23ae263bf7 --- /dev/null +++ b/packages/workforce/test/agent-resumed-turn-worker.test.ts @@ -0,0 +1,120 @@ +/** + * A turn on the shared `agent` copy that waits for a person runs as its + * worker again when the answer arrives. + * + * Every setting a turn reads comes from the worker the turn loaded. A resumed + * request injects a completed step's recorded output instead of running it + * again, so a worker loaded by a step of the turn would be loaded on the + * first run only: on resume the turn would read the copy's empty settings, + * and the tool that asked would be gone from the worker's tool set. The + * worker is loaded as the flow's request `onStarted`, which runs on every + * run of a request, the resumed one included. + */ +import { describe, expect, it } from "vitest"; +import { DEFAULT_ORG_ID, handler } from "@flow-state-dev/core"; +import type { FlowInstance, GeneratorModel, ModelResolver, SuspensionRecord } from "@flow-state-dev/core/types"; +import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; +import { z } from "zod"; +import { defineAgentWorkerFlow } from "../src/agent-worker-flow"; +import { createWorkerInstallation } from "../src/workers/installation"; + +/** A tool that waits for a person's approval, then says what it did. */ +const approveRefund = handler({ + name: "approveRefund", + description: "Refund an order, once a person approves it.", + inputSchema: z.object({ order: z.string() }), + outputSchema: z.object({ refunded: z.string() }), + execute: async (input, ctx) => { + await ctx.suspend!({ reason: "human_approval", message: `Refund ${input.order}?`, allow: ["approve", "reject"] }); + return { refunded: input.order }; + } +}); + +/** A model that calls `approveRefund` once, then answers. */ +function scripted(): ModelResolver { + let called = false; + const model: GeneratorModel = { + modelId: "test/step", + async generate() { + throw new Error("the owned tool loop calls generateStep"); + }, + async generateStep() { + if (called) return { text: "refunded", finishReason: "stop" }; + called = true; + return { + toolCalls: [{ toolCallId: "t1", toolName: "approveRefund", args: { order: "o-1" } }], + finishReason: "tool-calls" + }; + } + } as unknown as GeneratorModel; + return Object.assign(() => model, { resolveId: (id: string) => id }) as unknown as ModelResolver; +} + +describe("a resumed turn on the shared agent copy", () => { + it("runs as its worker again, so the tool that waited is still the worker's when the answer arrives", async () => { + let flows: Record = {}; + const installation = createWorkerInstallation({ + standardWorkers: [{ id: "desk.amy", declared: { tools: ["approveRefund"] }, body: "You are Amy." }], + workerFlows: () => flows as never + }); + const agent = defineAgentWorkerFlow({ installation, catalog: { approveRefund } }); + flows = { agent }; + const copy = agent({ id: "agent" }) as unknown as FlowInstance; + const state = createFlowState({ + flows: { agent: copy }, + stores: { default: { primary: inMemoryStores() } }, + durable: true, + modelResolver: scripted() + } as never); + try { + const runtime = await state.getRuntime(); + const router = await state.getRouter(); + const call = (method: "POST", path: string[], body: unknown) => + router[method]( + new Request(`http://localhost/api/flows/${path.join("/")}`, { + method, + headers: { "content-type": "application/json" }, + body: JSON.stringify(body) + }), + { params: { path } } + ); + + const sessionId = "conversation-amy"; + expect((await call("POST", ["agent", "sessions"], { userId: "alice", sessionId, state: { workerId: "desk.amy" } })).status).toBe(201); + const started = await runAction({ + orgId: DEFAULT_ORG_ID, + flow: copy, + actionName: "run", + input: { message: "refund o-1" }, + userId: "alice", + sessionId, + stores: runtime.stores, + runtimeConfig: { ...runtime.runtimeConfig } + }); + const requestId = started.requestId!; + expect((await runtime.stores.request.get(requestId))?.status).toBe("suspended"); + const [pending] = (await runtime.stores.suspensions.list({ status: "pending" })) as SuspensionRecord[]; + + const resumed = await call("POST", ["agent", "requests", requestId, "resume"], { + suspensionId: pending!.suspensionId, + action: "approve", + resumedBy: "alice" + }); + expect(resumed.status).toBe(202); + let status = "suspended"; + for (let i = 0; i < 200 && (status === "suspended" || status === "in_progress"); i += 1) { + await new Promise((resolve) => setTimeout(resolve, 25)); + status = String((await runtime.stores.request.get(requestId))?.status); + } + const record = (await runtime.stores.request.get(requestId)) as { items?: Array> }; + const failures = (record.items ?? []).filter((item) => item.type === "error").map((item) => item.message); + expect(failures).toEqual([]); + expect(status).toBe("completed"); + // The tool ran on Approve, as the worker's own. + const outputs = (record.items ?? []).filter((item) => item.type === "tool_output" && item.status === "completed"); + expect(outputs.map((item) => item.output)).toContainEqual({ refunded: "o-1" }); + } finally { + await state.dispose(); + } + }); +}); diff --git a/packages/workforce/test/agent-routed-answer.test.ts b/packages/workforce/test/agent-routed-answer.test.ts index 9303411b9c..1b5dbddd40 100644 --- a/packages/workforce/test/agent-routed-answer.test.ts +++ b/packages/workforce/test/agent-routed-answer.test.ts @@ -54,13 +54,13 @@ import { mailboxPostCapability, defineAgentWorkerFlow, defineMailboxFlow, - hireWorkforce, routeByPurpose, wakeMemberSeats, type MailboxManifest, type MailboxNotifyInput, - type WorkerManifest + type WorkerManifest, } from "../src/index"; +import { mintSeats } from "../src/hire"; import { MAILBOX_ANSWER_ACTION, mailboxAnswerInputSchema } from "../src/mailbox/mailbox-flow"; import { failLineWrite, postedLines } from "./mailbox-post-lines"; @@ -178,7 +178,7 @@ function answerFlow() { function host() { const agent = defineAgentWorkerFlow({ uses: [mailboxPostCapability] }); - const seats = hireWorkforce(workers(), { workerFlows: { agent } }); + const seats = mintSeats(workers(), { workerFlows: { agent } }); const [mailbox] = mailboxInstances(manifests, { kinds: { mailbox: defineMailboxFlow({ diff --git a/packages/workforce/test/agent-worker-flow.test.ts b/packages/workforce/test/agent-worker-flow.test.ts index 1d09eaf775..0e58350f7b 100644 --- a/packages/workforce/test/agent-worker-flow.test.ts +++ b/packages/workforce/test/agent-worker-flow.test.ts @@ -16,7 +16,7 @@ import type { FlowInstance, InitialSkill } from "@flow-state-dev/core/types"; import { createTestContext, mockGenerator } from "@flow-state-dev/testing"; import { executeBlock } from "@flow-state-dev/engine"; import { formatAllowedToolsIntentNote } from "@flow-state-dev/orchestration"; -import { hireWorkforce, type HireOptions } from "../src/hire"; +import { mintSeats, type HireOptions } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; import { workerConfigSchema } from "../src/worker-config"; import { AGENT_KIND, defineAgentWorkerFlow } from "../src/agent-worker-flow"; @@ -26,12 +26,12 @@ function record(over: Partial & { id: string }): WorkerManifest } function hire(manifests: WorkerManifest[], kinds: HireOptions["workerFlows"] = {}): FlowInstance[] { - return hireWorkforce(manifests, { workerFlows: kinds }); + return mintSeats(manifests, { workerFlows: kinds }); } function refusalOf(manifests: WorkerManifest[], kinds: HireOptions["workerFlows"] = {}): string { try { - hireWorkforce(manifests, { workerFlows: kinds }); + mintSeats(manifests, { workerFlows: kinds }); } catch (error) { return error instanceof Error ? error.message : String(error); } @@ -66,7 +66,7 @@ describe("the built-in agent kind", () => { // A roster of records that name no kind needs no `kinds` at all. it("hires with no options passed", () => { - const [seat] = hireWorkforce([record({ id: "engineering.lead", body: "You are the lead." })]); + const [seat] = mintSeats([record({ id: "engineering.lead", body: "You are the lead." })]); expect(seat!.kind).toBe(AGENT_KIND); }); diff --git a/packages/workforce/test/agent-worker-history.test.ts b/packages/workforce/test/agent-worker-history.test.ts index d27220ea67..0a18136955 100644 --- a/packages/workforce/test/agent-worker-history.test.ts +++ b/packages/workforce/test/agent-worker-history.test.ts @@ -28,7 +28,7 @@ import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engi import type { FlowStateRuntime } from "@flow-state-dev/engine"; import { createMockModelResolver, mockGenerator } from "@flow-state-dev/testing"; import { mailboxNotifyInputSchema, wakeMemberSeats, type MailboxNotifyInput } from "../src/index"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; const USER_ID = "u_person"; const SEAT = "support.devices"; @@ -64,7 +64,7 @@ function turnOf(messages: unknown): string | undefined { * post reaches the seat in the conversation a real mailbox would use. */ function boot() { - const [seat] = hireWorkforce([{ id: SEAT, declared: {}, body: "You answer device questions." }]); + const [seat] = mintSeats([{ id: SEAT, declared: {}, body: "You answer device questions." }]); const answer = mockGenerator({ name: "agent-answer", script: [ diff --git a/packages/workforce/test/agent-worker-mailbox-post.test.ts b/packages/workforce/test/agent-worker-mailbox-post.test.ts index 027b52757b..7d7bc29de9 100644 --- a/packages/workforce/test/agent-worker-mailbox-post.test.ts +++ b/packages/workforce/test/agent-worker-mailbox-post.test.ts @@ -25,7 +25,7 @@ import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engi import type { FlowStateRuntime } from "@flow-state-dev/engine"; import { createMockModelResolver, mockGenerator } from "@flow-state-dev/testing"; import { mailboxNotifyInputSchema, type MailboxNotifyInput } from "../src/index"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; const USER_ID = "u_mailbox"; const MAILBOX_SESSION = "support.desk"; @@ -50,7 +50,7 @@ function wakeFlow(seatId: string) { } function boot() { - const [seat] = hireWorkforce([{ id: "support.otto", declared: {}, body: "You answer questions." }]); + const [seat] = mintSeats([{ id: "support.otto", declared: {}, body: "You answer questions." }]); const heard: string[] = []; const sender = wakeFlow(seat!.id); const state = createFlowState({ diff --git a/packages/workforce/test/agent-worker-memory.test.ts b/packages/workforce/test/agent-worker-memory.test.ts index 13f2e83693..1e5075903c 100644 --- a/packages/workforce/test/agent-worker-memory.test.ts +++ b/packages/workforce/test/agent-worker-memory.test.ts @@ -33,7 +33,7 @@ import { executeBlock } from "@flow-state-dev/engine"; import { createTestContext, mockGenerator, testFlow } from "@flow-state-dev/testing"; import { system } from "@flow-state-dev/memory"; import { AGENT_KIND, defineAgentWorkerFlow } from "../src/agent-worker-flow"; -import { hireWorkforce, type HireOptions } from "../src/hire"; +import { mintSeats, type HireOptions } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; const USER_ID = "one-human"; @@ -44,7 +44,7 @@ function record(over: Partial & { id: string }): WorkerManifest } function hire(manifests: WorkerManifest[], kinds: HireOptions["workerFlows"] = {}): FlowInstance[] { - return hireWorkforce(manifests, { workerFlows: kinds }); + return mintSeats(manifests, { workerFlows: kinds }); } /** The write-side entry point — `createMemoryCapability` would be read-only. */ diff --git a/packages/workforce/test/agent-worker-own-state.test.ts b/packages/workforce/test/agent-worker-own-state.test.ts index 143024f4e3..23147c45f3 100644 --- a/packages/workforce/test/agent-worker-own-state.test.ts +++ b/packages/workforce/test/agent-worker-own-state.test.ts @@ -11,7 +11,7 @@ import { describe, expect, it } from "vitest"; import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; import { createMockModelResolver, mockGenerator } from "@flow-state-dev/testing"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; const ORG = "acme"; const SKILL_MD = "---\nname: refunds\ndescription: How refunds work\n---\nRefunds take five days."; @@ -19,7 +19,7 @@ const SKILL_MD = "---\nname: refunds\ndescription: How refunds work\n---\nRefund type Write = { scopeType: string; scopeId: string; key: string }; async function runAs(users: readonly string[]): Promise { - const [seat] = hireWorkforce([ + const [seat] = mintSeats([ { id: "support.otto", declared: {}, diff --git a/packages/workforce/test/agent-worker-user-message.test.ts b/packages/workforce/test/agent-worker-user-message.test.ts index 8ed2fe125e..803617336a 100644 --- a/packages/workforce/test/agent-worker-user-message.test.ts +++ b/packages/workforce/test/agent-worker-user-message.test.ts @@ -13,13 +13,13 @@ import { describe, expect, it } from "vitest"; import { DEFAULT_ORG_ID } from "@flow-state-dev/core"; import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; import { createMockModelResolver, mockGenerator } from "@flow-state-dev/testing"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; const USER_ID = "u_person"; describe("a message to an agent seat", () => { it("is kept in the seat's conversation as the caller's turn, ahead of the reply", async () => { - const [seat] = hireWorkforce([{ id: "support.otto", declared: {}, body: "You answer questions." }]); + const [seat] = mintSeats([{ id: "support.otto", declared: {}, body: "You answer questions." }]); const state = createFlowState({ flows: { [seat!.id]: seat! }, stores: { default: { primary: inMemoryStores() } }, diff --git a/packages/workforce/test/browser-subpath-safe.test.ts b/packages/workforce/test/browser-subpath-safe.test.ts index 406fec65c5..33aabad5fd 100644 --- a/packages/workforce/test/browser-subpath-safe.test.ts +++ b/packages/workforce/test/browser-subpath-safe.test.ts @@ -40,17 +40,14 @@ describe("@flow-state-dev/workforce/browser", () => { expect(published).toBe(await import("../src/browser")); }); - it("still exports the names the kitchen-sink panels import", async () => { + it("still exports the names an app's browser code imports", async () => { // The other direction: emptying the entry would pass the walk above. const entry = await import("@flow-state-dev/workforce/browser"); expect(entry.MAILBOX_POST_COMPONENT).toBe("mailbox-post"); - expect(entry.HIRED_ROSTER_RESOURCE).toBe("hiredRoster"); - expect(entry.HIRED_ROSTER_BROWSER_PATTERN).toBe("workforce/roster/*"); - expect(entry.SEAT_INVENTORY_RESOURCE).toBe("seatInventory"); - expect(typeof entry.splitSeatAddress).toBe("function"); - expect(typeof entry.listedSeatRows).toBe("function"); + expect(typeof entry.createWorkforceClient).toBe("function"); + expect(entry.ROSTER_FLOW_KIND).toBe("workforce-roster"); expect(typeof entry.mailboxTranscriptLineSchema.parse).toBe("function"); - // The eighth, the `MailboxTranscriptLine` type, is pinned in `browser-exports.test-d.ts`. + // The `MailboxTranscriptLine` type is pinned in `browser-exports.test-d.ts`. }); it("finds the Node built-in the package root reaches through the mailbox floor", () => { diff --git a/packages/workforce/test/cross-org-collection-read.test.ts b/packages/workforce/test/cross-org-collection-read.test.ts index e46f6ebc65..16825e4dac 100644 --- a/packages/workforce/test/cross-org-collection-read.test.ts +++ b/packages/workforce/test/cross-org-collection-read.test.ts @@ -56,7 +56,6 @@ import type { ResourceCollectionRef } from "@flow-state-dev/core/types"; import { z } from "zod"; import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; import { createMockModelResolver } from "@flow-state-dev/testing"; -import { defineHiredRosterCollection } from "../src/roster/collections"; import { mailboxBoard, MAILBOX_BOARD_CLIENT_FIELDS } from "../src/mailbox/mailbox-board"; import { mailboxBoardRowSchema } from "../src/mailbox/mailbox-flow"; import { @@ -67,30 +66,17 @@ import { openInventory, type MailboxManifest } from "../src/index"; -import { - createSeatHireBlocks, - HIRED_ROSTER_RESOURCE, - SEAT_INVENTORY_RESOURCE -} from "../src/seat-hire-blocks"; -/** - * Resource-map keys must be slash-free — they are one path segment in - * `/sessions/:id/resources/:ref`, so `workforce/roster` would 404 on - * segmentation. Distinct from the collection's `workforce/roster/*` PATTERN, - * which is a storage-key shape and may contain slashes. - */ -const ROSTER_REF = "roster"; const BOARD_REF = "eng.feature.triage"; const FLOW_KIND = "workforce-panels"; -const rosterCollection = defineHiredRosterCollection(); const boardLedger = mailboxBoard("eng.feature", "triage"); /** Execution internals a task envelope carries and a board card must never receive. */ const EXECUTION_INTERNALS = ["claimedBy", "leaseUntil", "retryLedger", "writeLog"] as const; /** - * Plants one roster row and one board row in whatever org the running session + * Plants one board row in whatever org the running session * is bound to. Deliberately an ACTION rather than a direct store write: the * rows have to land through the same org resolution the read uses, or the test * would be asserting against a fixture it placed by hand. @@ -102,16 +88,9 @@ const seed = handler({ name: "seed", inputSchema: z.object({ seatId: z.string(), goal: z.string() }), outputSchema: z.object({ ok: z.boolean() }), - resources: { [ROSTER_REF]: rosterCollection, [BOARD_REF]: boardLedger }, + resources: { [BOARD_REF]: boardLedger }, execute: async (input, ctx) => { - const roster = ctx.resources[ROSTER_REF] as ResourceCollectionRef>; const board = ctx.resources[BOARD_REF] as ResourceCollectionRef>; - await roster.create(input.seatId, { - seatId: input.seatId, - flow: "agent", - settings: { apiKey: "LEAKED-SETTINGS" }, - instructions: null - }); await board.create(`task-${input.seatId}`, { id: `task-${input.seatId}`, goal: input.goal, @@ -137,7 +116,7 @@ const seed = handler({ function panelFlow() { return defineFlow({ kind: FLOW_KIND, - resources: { [ROSTER_REF]: rosterCollection, [BOARD_REF]: boardLedger }, + resources: { [BOARD_REF]: boardLedger }, actions: { seed: { inputSchema: z.object({ seatId: z.string(), goal: z.string() }), block: seed } }, @@ -257,19 +236,17 @@ describe("FIX-1477 · the panel collections' client read", () => { expect(extra, "browser-only board fields the model's allowlist does not publish").toEqual([]); }); - it("both panel collections are org-scoped, which is what the opt-in rests on", () => { - const roster = rosterCollection as unknown as { scope?: string }; + it("the board collection is org-scoped, which is what the opt-in rests on", () => { const board = boardLedger as unknown as { scope?: string }; - expect(roster.scope, "the hired roster's scope").toBe("org"); expect(board.scope, "a mailbox board ledger's scope").toBe("org"); }); - it("an org's own member can read both collections at all", async () => { + it("an org's own member can read the board at all", async () => { const h = await buildHarness(); await plant(h, "org-a", "support.ada", "ship the thing"); const sessionId = await openSession(h, "org-a", "org-a"); - for (const ref of [ROSTER_REF, BOARD_REF]) { + for (const ref of [BOARD_REF]) { const { status, json } = await readCollection(h, sessionId, ref, "", { "x-verified-org": "org-a" }); @@ -294,23 +271,17 @@ describe("FIX-1477 · the panel collections' client read", () => { "x-organization": "org-b" }; - const roster = await readCollection(h, sessionId, ROSTER_REF, "?orgId=org-b", steer); const board = await readCollection(h, sessionId, BOARD_REF, "?orgId=org-b", steer); - expect(roster.status).toBe(200); expect(board.status).toBe(200); - const seatIds = roster.json.items.map((i: any) => i.clientData?.seatId); const goals = board.json.items.map((i: any) => i.clientData?.goal); - expect(seatIds, "the seats an org-a session may see").toEqual(["support.ada"]); - expect(seatIds).not.toContain("victim.bob"); expect(goals, "the tasks an org-a session may see").toEqual(["OWN-GOAL"]); expect(goals).not.toContain("VICTIM-GOAL"); // The same claim over the raw payload, so a shape change in `clientData` // cannot quietly turn the two assertions above into no-ops. - expect(JSON.stringify(roster.json)).not.toContain("victim"); expect(JSON.stringify(board.json)).not.toContain("VICTIM-GOAL"); }); @@ -357,25 +328,6 @@ describe("FIX-1477 · the panel collections' client read", () => { expect(card).not.toHaveProperty("claimedBy"); }); - it("a roster row carries no settings bag", async () => { - const h = await buildHarness(); - await plant(h, "org-a", "support.ada", "ship the thing"); - const sessionId = await openSession(h, "org-a", "org-a"); - - const roster = await readCollection(h, sessionId, ROSTER_REF, "", { - "x-verified-org": "org-a" - }); - - // `settings` is passthrough by contract — a flow kind's own config bag, - // free to grow keys this package has never heard of. - expect(roster.json.items[0].clientData).toEqual({ - seatId: "support.ada", - flow: "agent", - instructions: null, - incarnation: null - }); - expect(JSON.stringify(roster.json)).not.toContain("LEAKED-SETTINGS"); - }); }); // --------------------------------------------------------------------------- @@ -788,88 +740,3 @@ describe("FIX-1502 · the inventory collections' client read", () => { }); }); -describe("a fired seat leaves the browser's inventory read (FIX-1621 BR-9)", () => { - /** - * `fire` deletes the roster row, releases the address, then deletes the - * seat's inventory row, so the browser read lists the seat after the hire - * and not after the fire. This case used to assert the row stayed; it was - * flipped when fire started removing it, not relaxed. - */ - it("hire then fire through the seat-hire tools; the route lists the seat, then doesn't", async () => { - const registered = new Map(); - const { hire, fire } = createSeatHireBlocks({ - register: (seat) => { - registered.set(seat.id, seat); - }, - unregister: (id) => registered.delete(id) - }); - const flow = defineFlow({ - kind: "seat-hirer", - resources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection() - }, - actions: { - hire: { inputSchema: z.object({ seatId: z.string(), flow: z.string() }), block: hire }, - fire: { inputSchema: z.object({ seatId: z.string() }), block: fire } - }, - authentication: { resolvePrincipal: verifiedHeaderPrincipal((org) => `user-of-${org}`) } - } as never); - const state = createFlowState({ - flows: { "seat-hirer": flow as never }, - stores: { default: { primary: inMemoryStores() } }, - modelResolver: createMockModelResolver({}) - }); - const runtime = await state.getRuntime(); - const h = harnessOver(await state.getRouter()); - const org = { "x-verified-org": "org-a" }; - const created = await h.post(["seat-hirer", "sessions"], { userId: "user-of-org-a" }, org); - const sessionId = created.json.session?.id ?? created.json.id; - - const act = async (action: string, input: unknown): Promise => { - const posted = await h.post( - ["seat-hirer", sessionId, "actions", action], - { userId: "user-of-org-a", input }, - org - ); - expect(posted.status, JSON.stringify(posted.json)).toBe(202); - const requestId = posted.json.request.id; - for (let i = 0; i < 300; i++) { - const polled = await h.get(["seat-hirer", "requests", requestId, "status"], "", org); - const seen = polled.json?.status; - if (seen === "completed") return; - if (seen === "errored" || seen === "failed" || seen === "cancelled") { - throw new Error(`${action} ${seen}: ${JSON.stringify(polled.json)}`); - } - await new Promise((r) => setTimeout(r, 10)); - } - throw new Error(`${action} never reached a terminal status`); - }; - - // A hired seat's address is `.`. - const address = "org-a.eng.ada"; - await act("hire", { seatId: "eng.ada", flow: "agent" }); - expect([...registered.keys()], "the hire registered the seat").toEqual([address]); - expect( - Object.keys(await runtime.stores.resourceState.getByPrefix("org", "org-a", "workforce/roster/")), - "roster rows after the hire" - ).toEqual(["workforce/roster/eng.ada"]); - const hired = await readCollection(h, sessionId, SEAT_INVENTORY_RESOURCE, "", org); - expect(hired.status).toBe(200); - // The row a hire through the tools wrote carries the agent kind's door. - expect(hired.json.items.map((item: any) => item.clientData)).toEqual([ - { id: address, kind: "agent", door: "run", hired: true, incarnation: expect.any(String) } - ]); - await act("fire", { seatId: "eng.ada" }); - // The fire happened: the address is released and the roster row is gone. - expect(registered.has(address), "the fire released the seat").toBe(false); - expect( - Object.keys(await runtime.stores.resourceState.getByPrefix("org", "org-a", "workforce/roster/")), - "roster rows after the fire" - ).toEqual([]); - - const listed = await readCollection(h, sessionId, SEAT_INVENTORY_RESOURCE, "", org); - expect(listed.status).toBe(200); - expect(listed.json.items, "the fired seat's inventory row").toEqual([]); - }); -}); diff --git a/packages/workforce/test/custom-tools-catalog.test.ts b/packages/workforce/test/custom-tools-catalog.test.ts index 4af0833014..f142e0a48c 100644 --- a/packages/workforce/test/custom-tools-catalog.test.ts +++ b/packages/workforce/test/custom-tools-catalog.test.ts @@ -24,7 +24,7 @@ import { defineResource } from "@flow-state-dev/core/types"; import type { FlowInstance } from "@flow-state-dev/core/types"; import { createTestContext, mockGenerator } from "@flow-state-dev/testing"; import { executeBlock } from "@flow-state-dev/engine"; -import { hireWorkforce, type HireOptions } from "../src/hire"; +import { mintSeats, type HireOptions } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; import { AGENT_KIND, defineAgentWorkerFlow } from "../src/agent-worker-flow"; @@ -33,7 +33,7 @@ function record(over: Partial & { id: string }): WorkerManifest } function hire(manifests: WorkerManifest[], kinds: HireOptions["workerFlows"]): FlowInstance[] { - return hireWorkforce(manifests, { workerFlows: kinds }); + return mintSeats(manifests, { workerFlows: kinds }); } /** A model script that "calls" a tool by name. */ diff --git a/packages/workforce/test/custom-tools-seat.test.ts b/packages/workforce/test/custom-tools-seat.test.ts index f1314697df..b72a380fd4 100644 --- a/packages/workforce/test/custom-tools-seat.test.ts +++ b/packages/workforce/test/custom-tools-seat.test.ts @@ -20,7 +20,7 @@ import { defineResource } from "@flow-state-dev/core/types"; import type { BlockDefinition, FlowInstance } from "@flow-state-dev/core/types"; import { createTestContext, mockGenerator } from "@flow-state-dev/testing"; import { executeBlock } from "@flow-state-dev/engine"; -import { hireWorkforce, type HireOptions } from "../src/hire"; +import { mintSeats, type HireOptions } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; import { AGENT_KIND, defineAgentWorkerFlow } from "../src/agent-worker-flow"; @@ -30,7 +30,7 @@ function record(over: Partial & { id: string }): WorkerManifest function refusalOf(manifests: WorkerManifest[], options: HireOptions): string { try { - hireWorkforce(manifests, options); + mintSeats(manifests, options); } catch (error) { return error instanceof Error ? error.message : String(error); } @@ -82,7 +82,7 @@ async function runSeat(seat: FlowInstance, toolName: string) { describe("a seat's own blocks are registered, not granted", () => { it("lets a seat call a block from its own folder once its `tools:` names it", async () => { const check = countingBlock("check-inventory"); - const [seat] = hireWorkforce( + const [seat] = mintSeats( [record({ id: "support.clerk", declared: { tools: ["check-inventory"] }, body: "Clerk." })], { workerFlows: { [AGENT_KIND]: defineAgentWorkerFlow() }, @@ -104,7 +104,7 @@ describe("a seat's own blocks are registered, not granted", () => { // stays at zero here is the fence holding, not a broken harness. it("does NOT let a seat call a registered block its `tools:` never named", async () => { const check = countingBlock("check-inventory"); - const [seat] = hireWorkforce([record({ id: "support.quiet", body: "Quiet." })], { + const [seat] = mintSeats([record({ id: "support.quiet", body: "Quiet." })], { workerFlows: { [AGENT_KIND]: defineAgentWorkerFlow() }, seatBlocks: { "support.quiet": { "check-inventory": check } }, }); @@ -118,7 +118,7 @@ describe("a seat's own blocks are registered, not granted", () => { // "this seat reaches nothing", which must stay literally true. it("reaches nothing with an explicit empty `tools:` and a full folder", async () => { const check = countingBlock("check-inventory"); - const [seat] = hireWorkforce( + const [seat] = mintSeats( [record({ id: "support.empty", declared: { tools: [] }, body: "Empty." })], { workerFlows: { [AGENT_KIND]: defineAgentWorkerFlow() }, @@ -146,7 +146,7 @@ describe("a seat's own blocks are registered, not granted", () => { }) as BlockDefinition; calls["summarize-theirs"] = 0; - const [alpha] = hireWorkforce( + const [alpha] = mintSeats( [ record({ id: "support.alpha", declared: { tools: ["summarize"] }, body: "A." }), record({ id: "support.beta", declared: { tools: ["summarize"] }, body: "B." }), @@ -181,7 +181,7 @@ describe("a seat's own blocks are registered, not granted", () => { }) as BlockDefinition; calls["desk-note-app"] = 0; - const [seat] = hireWorkforce( + const [seat] = mintSeats( [record({ id: "support.desk", declared: { tools: ["desk-note"] }, body: "Desk." })], { workerFlows: { [AGENT_KIND]: defineAgentWorkerFlow({ catalog: { "desk-note": app } }) }, @@ -197,7 +197,7 @@ describe("a seat's own blocks are registered, not granted", () => { // A seat with no folder must behave exactly as it does today — including // keeping the catalog refusal it already has. it("changes nothing for a seat with no folder", () => { - const [seat] = hireWorkforce([record({ id: "support.plain", body: "Plain." })], { + const [seat] = mintSeats([record({ id: "support.plain", body: "Plain." })], { workerFlows: { [AGENT_KIND]: defineAgentWorkerFlow() }, }); expect(seat!.config).toMatchObject({ seatTools: [] }); @@ -241,7 +241,7 @@ describe("what a seat's own map is refused for", () => { // bare throw over any non-empty map. it("does not refuse when the key and the block's name agree", () => { expect(() => - hireWorkforce([record({ id: "support.clerk", body: "Clerk." })], { + mintSeats([record({ id: "support.clerk", body: "Clerk." })], { workerFlows: { [AGENT_KIND]: defineAgentWorkerFlow() }, seatBlocks: { "support.clerk": { "check-inventory": countingBlock("check-inventory") } }, }), @@ -309,7 +309,7 @@ describe("what a seat's own map is refused for", () => { const kind = defineAgentWorkerFlow({ uses: [defineCapability({ name: "shared-ledger", resources: { shared } })], }); - const [seat] = hireWorkforce( + const [seat] = mintSeats( [record({ id: "support.reader", declared: { tools: ["read-shared"] }, body: "Reader." })], { workerFlows: { [AGENT_KIND]: kind }, seatBlocks: { "support.reader": { "read-shared": reads } } }, ); @@ -330,7 +330,7 @@ describe("what a seat's own map is refused for", () => { // BP-035's second path: the option absent entirely must behave as before. it("hires with no `seatBlocks` option at all", () => { - const [seat] = hireWorkforce([record({ id: "support.plain", body: "Plain." })]); + const [seat] = mintSeats([record({ id: "support.plain", body: "Plain." })]); expect(seat!.config).toMatchObject({ seatTools: [] }); }); @@ -342,7 +342,7 @@ describe("what a seat's own map is refused for", () => { // actually being hired; entries addressed to anyone else are not this call's // business. it("hires a subset without objecting to map entries for the workers left out", () => { - const [seat] = hireWorkforce( + const [seat] = mintSeats( [record({ id: "support.clerk", declared: { tools: ["check-inventory"] }, body: "Clerk." })], { workerFlows: { [AGENT_KIND]: defineAgentWorkerFlow() }, @@ -395,7 +395,7 @@ describe("a colocated tool does not travel through delegation", () => { it("leaves only the catalog half in the bag's `tools`", () => { const own = countingBlock("check-inventory"); const app = countingBlock("desk-note"); - const [seat] = hireWorkforce( + const [seat] = mintSeats( [ record({ id: "support.clerk", diff --git a/packages/workforce/test/custom-worker-flow-data.test.ts b/packages/workforce/test/custom-worker-flow-data.test.ts new file mode 100644 index 0000000000..59debc6651 --- /dev/null +++ b/packages/workforce/test/custom-worker-flow-data.test.ts @@ -0,0 +1,114 @@ +/** + * Where a custom worker flow's data lives (D6), as the docs tell its author. + * + * One registered copy of a custom worker flow, two standard workers on it, + * and two users. What the flow keeps at user scope is shared by one user's + * workers and never reaches the other user. What it keys by the worker + * `resolveWorker` loaded stays with that worker. + */ +import { describe, expect, it } from "vitest"; +import { DEFAULT_ORG_ID, defineFlow, defineResource, defineResourceCollection, handler } from "@flow-state-dev/core"; +import type { FlowInstance } from "@flow-state-dev/core/types"; +import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; +import { z } from "zod"; +import { workerConfigSchema } from "../src/worker-config"; +import { createWorkerInstallation } from "../src/workers/installation"; + +/** One row per worker, in the user's scope: keyed by the worker, so kept per worker. */ +const workerNotes = defineResourceCollection({ + pattern: "worker-notes/*", + scope: "user", + stateSchema: z.object({ text: z.string().default("") }) +}); + +/** One row per user: every one of that user's workers on the flow reads it. */ +const userNotes = defineResource({ + ref: "user-notes", + scope: "user", + stateSchema: z.object({ text: z.string().default("") }), + default: { text: "" } +}); + +const input = z.object({ message: z.string() }); + +function host() { + let flows: Record = {}; + const installation = createWorkerInstallation({ + standardWorkers: [ + { id: "researcher", declared: { flow: "research" }, body: "Research." }, + { id: "scribe", declared: { flow: "research" }, body: "Take notes." } + ], + workerFlows: () => flows as never + }); + const door = handler({ + name: "research-run", + inputSchema: input, + resources: { workerNotes, userNotes, ...installation.resources }, + execute: async ({ message }, ctx) => { + const worker = await installation.resolveWorker(ctx, "research"); + if (message.startsWith("write:")) { + const text = message.slice("write:".length); + await ctx.resources.workerNotes.upsert(worker.id, { text }); + await ctx.resources.userNotes.setState({ text }); + } + const own = await ctx.resources.workerNotes.getOptional(worker.id); + return { mine: own?.state.text ?? null, user: ctx.resources.userNotes.state.text }; + } + }); + const research = defineFlow({ + kind: "research", + configSchema: workerConfigSchema(), + session: installation.session(), + resources: { ...installation.resources }, + actions: { run: { inputSchema: input, block: door, userMessage: (i: { message: string }) => i.message } } + }); + flows = { research }; + const copy = research() as unknown as FlowInstance; + return { copy, state: createFlowState({ flows: { research: copy }, stores: { default: { primary: inMemoryStores() } } }) }; +} + +describe("a custom worker flow's data (D6)", () => { + it("shares user-scoped data among one user's workers, never across users; a key by worker keeps it apart", async () => { + const { copy, state } = host(); + try { + const runtime = await state.getRuntime(); + const router = await state.getRouter(); + const turn = async (userId: string, worker: string, message: string) => { + const sessionId = `${userId}-${worker}`; + if ((await runtime.stores.session.get(sessionId)) == null) { + const created = await router.POST( + new Request("http://localhost/api/flows/research/sessions", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ userId, sessionId, state: { workerId: worker } }) + }), + { params: { path: ["research", "sessions"] } } + ); + expect(created.status).toBe(201); + } + const result = await runAction({ + orgId: DEFAULT_ORG_ID, + flow: copy, + actionName: "run", + input: { message }, + userId, + sessionId, + stores: runtime.stores, + runtimeConfig: { ...runtime.runtimeConfig } + }); + expect(result.error).toBeUndefined(); + return result.output as { mine: string | null; user: string }; + }; + + await turn("alice", "researcher", "write:the launch moved"); + // Alice's other worker on the flow reads her user-scoped row, not the researcher's own. + expect(await turn("alice", "scribe", "read")).toEqual({ mine: null, user: "the launch moved" }); + // The researcher reads both. + expect(await turn("alice", "researcher", "read")).toEqual({ mine: "the launch moved", user: "the launch moved" }); + // Bob, with the same worker, reads neither. + expect(await turn("bob", "researcher", "read")).toEqual({ mine: null, user: "" }); + } finally { + await state.dispose(); + } + }); +}); diff --git a/packages/workforce/test/hire-plane.test.ts b/packages/workforce/test/hire-plane.test.ts deleted file mode 100644 index 3e984ac4c5..0000000000 --- a/packages/workforce/test/hire-plane.test.ts +++ /dev/null @@ -1,286 +0,0 @@ -/** - * Hire-row pin for FIX-1529. - * - * The pin is `{ orgId, userId? }` from the row, never from the address. A - * legacy row binds the cell it was read from. A row that names another org - * is a problem and is not minted. A deep roster collection is refused once a - * registry holds the private writer, because the private sub-prefix only - * hides rows from the browser pattern. - */ -import { describe, expect, it } from "vitest"; -import { defineFlow, defineResourceCollection, handler } from "@flow-state-dev/core"; -import { createFlowRegistry } from "@flow-state-dev/engine"; -import { z } from "zod"; -import { - defineHiredRosterCollection, - defineHiredRosterPrivateCollection, - hiredRosterStorageKey, - hiredSeatManifest, - hiredSeatRowFromManifest, - registerHiredSeat, - reloadHiredSeats, - toHiredSeatRow, -} from "../src/roster"; -import { HIRED_ROSTER_BROWSER_PATTERN, HIRED_ROSTER_PRIVATE_PATTERN } from "../src"; -import type { FlowInstance, InstanceOwnerPin } from "@flow-state-dev/core/types"; -import { hireWorkforce } from "../src/hire"; -import { workerConfigSchema } from "../src/worker-config"; -import { workerDoor } from "./worker-door"; - -const work = handler({ - name: "desk-work", - inputSchema: z.object({ note: z.string() }), - outputSchema: z.object({ note: z.string() }), - execute: (input) => input, -}); - -const deskClerk = defineFlow({ - kind: "desk-clerk", - cardinality: "collection", - configSchema: workerConfigSchema(), - actions: { ...workerDoor, answer: { inputSchema: z.object({ note: z.string() }), block: work } }, -}); -const kinds = { "desk-clerk": deskClerk }; - -const ACME_PROMPT = "ACME-CONFIDENTIAL: you work on acme's roadmap"; - -describe("hire row pin", () => { - it("stamps owningOrgId and ownerUserId, and the mint carries that pin", () => { - const row = toHiredSeatRow({ - seatId: "research", - flow: "desk-clerk", - instructions: "ALICE-PRIVATE", - owningOrgId: "acme", - ownerUserId: "alice", - }); - expect(row.owningOrgId).toBe("acme"); - expect(row.ownerUserId).toBe("alice"); - expect(hiredRosterStorageKey(row)).toBe("~alice/research"); - expect( - hiredRosterStorageKey({ seatId: "research", ownerUserId: "bob/x" }) - ).toBe("~bob%2Fx/research"); - - const bound = hiredSeatManifest("acme", row); - if (!("manifest" in bound)) throw new Error(bound.problem); - expect(bound.manifest.id).toBe("acme.~alice.research"); - expect(bound.manifest.ownerPin).toEqual({ orgId: "acme", userId: "alice" }); - - const [seat] = hireWorkforce([bound.manifest], { workerFlows: kinds }); - expect(seat!.ownerPin).toEqual({ orgId: "acme", userId: "alice" }); - - const back = hiredSeatRowFromManifest("acme", bound.manifest); - if (!("row" in back)) throw new Error(back.problem); - expect(back.row.owningOrgId).toBe("acme"); - expect(back.row.ownerUserId).toBe("alice"); - }); - - it("E5 a row claiming another org is a named problem and is not registered", async () => { - const stores = { - resourceState: { - async getByPrefix() { - return { - "workforce/roster/eng.lead": { - state: { - seatId: "eng.lead", - flow: "desk-clerk", - settings: {}, - instructions: ACME_PROMPT, - owningOrgId: "globex", - }, - }, - }; - }, - }, - }; - const { seats, problems } = await reloadHiredSeats({ - stores, - orgIds: ["acme"], - workerFlows: kinds, - }); - expect(seats).toEqual([]); - expect(problems.join("\n")).toContain("globex"); - expect(problems.join("\n")).toContain("acme"); - expect(problems.join("\n")).not.toContain(ACME_PROMPT); - }); - - it("a legacy row binds the cell and stays org-visible", async () => { - const stores = { - resourceState: { - async getByPrefix() { - return { - "workforce/roster/eng.lead": { - state: { - seatId: "eng.lead", - flow: "desk-clerk", - settings: {}, - instructions: ACME_PROMPT, - }, - }, - }; - }, - }, - }; - const { seats, problems } = await reloadHiredSeats({ - stores, - orgIds: ["acme"], - workerFlows: kinds, - }); - expect(problems).toEqual([]); - expect(seats.map((seat) => seat.id)).toEqual(["acme.eng.lead"]); - expect(seats[0]!.ownerPin).toEqual({ orgId: "acme" }); - }); - - it("refuses a deep roster collection beside the private writer, and not in an app without it", () => { - const flowWith = (kind: string, resources: Record) => - defineFlow({ - kind, - resources: resources as never, - actions: { - ping: { - inputSchema: z.object({}), - block: handler({ - name: `${kind}-ping`, - inputSchema: z.object({}), - outputSchema: z.object({ ok: z.boolean() }), - execute: () => ({ ok: true }), - }), - }, - }, - })(); - expect(defineHiredRosterCollection().pattern).toBe("workforce/roster/*"); - expect(defineHiredRosterPrivateCollection().pattern).toBe("workforce/roster/[owner]/[seat]"); - expect(defineHiredRosterPrivateCollection().client?.state?.read).not.toBe(true); - - for (const pattern of [ - "workforce/roster/**", - "workforce/**", - "workforce/roster/[owner]/notes", - "workforce/roster/*/*", - ]) { - const deep = () => - defineResourceCollection({ pattern, scope: "org", stateSchema: z.object({}).passthrough() }); - - const withoutWriter = createFlowRegistry(); - withoutWriter.register(flowWith("deep", { deep: deep() })); - expect(withoutWriter.get("deep")).toBeDefined(); - - const armed = createFlowRegistry(); - armed.register(flowWith("hires", { roster: defineHiredRosterPrivateCollection() })); - expect(() => armed.register(flowWith("deep", { deep: deep() }))).toThrow( - `Collection pattern "${pattern}" can reach the rows of owner-private collection "workforce/roster/[owner]/[seat]".` - ); - expect(armed.get("deep")).toBeUndefined(); - } - }); - - it("exports the roster patterns from the package root, and declares each collection on its own", () => { - // The patterns are Workforce's, not the framework's. Their values are - // pinned in the case above. - expect(defineHiredRosterCollection().pattern).toBe(HIRED_ROSTER_BROWSER_PATTERN); - expect(defineHiredRosterPrivateCollection().pattern).toBe(HIRED_ROSTER_PRIVATE_PATTERN); - }); - - it("declares the private writer owner-private, and refuses a hand-built copy of its pattern beside it", () => { - expect(defineHiredRosterPrivateCollection().ownerPrivate).toEqual({ param: "owner" }); - const registry = createFlowRegistry(); - const ping = handler({ - name: "ping", - inputSchema: z.object({}), - outputSchema: z.object({ ok: z.boolean() }), - execute: () => ({ ok: true }), - }); - const writer = defineFlow({ - kind: "private-writer", - resources: { roster: defineHiredRosterPrivateCollection() }, - actions: { ping: { inputSchema: z.object({}), block: ping } }, - })(); - expect(() => registry.register(writer)).not.toThrow(); - - const copy = defineFlow({ - kind: "copied-writer", - resources: { - roster: defineResourceCollection({ - pattern: "workforce/roster/[owner]/[seat]", - scope: "org", - stateSchema: z.object({}), - }), - }, - actions: { ping: { inputSchema: z.object({}), block: ping } }, - })(); - expect(() => registry.register(copy)).toThrow( - 'Collection pattern "workforce/roster/[owner]/[seat]" can reach the rows of owner-private collection "workforce/roster/[owner]/[seat]".' - ); - }); - - it("gives alice and bob different addresses for the same seat id, and the pin stays the row", () => { - const alice = toHiredSeatRow({ - seatId: "research", - flow: "desk-clerk", - instructions: "ALICE-PRIVATE", - owningOrgId: "acme", - ownerUserId: "alice", - }); - const bob = toHiredSeatRow({ - seatId: "research", - flow: "desk-clerk", - instructions: "BOB-PRIVATE", - owningOrgId: "acme", - ownerUserId: "bob", - }); - const aliceBound = hiredSeatManifest("acme", alice); - const bobBound = hiredSeatManifest("acme", bob); - if (!("manifest" in aliceBound) || !("manifest" in bobBound)) { - throw new Error("expected both rows to mint"); - } - expect(aliceBound.manifest.id).toBe("acme.~alice.research"); - expect(bobBound.manifest.id).toBe("acme.~bob.research"); - expect(aliceBound.manifest.ownerPin).toEqual({ orgId: "acme", userId: "alice" }); - expect(bobBound.manifest.ownerPin).toEqual({ orgId: "acme", userId: "bob" }); - - const crafted = hiredSeatRowFromManifest("acme", { - id: "acme.~bob.research", - declared: { flow: "desk-clerk" }, - body: "from the row", - ownerPin: { orgId: "acme", userId: "alice" }, - }); - if (!("row" in crafted)) throw new Error(crafted.problem); - expect(crafted.row.seatId).toBe("research"); - expect(crafted.row.ownerUserId).toBe("alice"); - expect(() => - toHiredSeatRow({ seatId: "~alice.research", flow: "desk-clerk" }) - ).not.toThrow(); - expect(() => hiredSeatManifest("acme", toHiredSeatRow({ - seatId: "~alice.research", - flow: "desk-clerk", - }))).toThrow(/starts with "~"/); - }); -}); - -describe("registerHiredSeat", () => { - const seat = { id: "acme.x" } as FlowInstance; - - it("refuses a hired seat with no pin, and does not call register", () => { - const seen: InstanceOwnerPin[] = []; - const register = (_seat: FlowInstance, pin: InstanceOwnerPin) => { - seen.push(pin); - }; - expect(() => registerHiredSeat(register, seat, undefined)).toThrow(/owner pin/); - expect(() => registerHiredSeat(register, seat, { orgId: "" })).toThrow(/owner pin/); - expect(seen).toEqual([]); - }); - - it("registers with the pin from the row, and drops a blank user", () => { - const seen: InstanceOwnerPin[] = []; - const register = (_seat: FlowInstance, pin: InstanceOwnerPin) => { - seen.push(pin); - }; - registerHiredSeat(register, seat, { orgId: "globex" }); - registerHiredSeat(register, seat, { orgId: "globex", userId: "" }); - registerHiredSeat(register, seat, { orgId: "globex", userId: "alice" }); - expect(seen).toEqual([ - { orgId: "globex" }, - { orgId: "globex" }, - { orgId: "globex", userId: "alice" }, - ]); - }); -}); diff --git a/packages/workforce/test/hire-required-settings.test.ts b/packages/workforce/test/hire-required-settings.test.ts deleted file mode 100644 index 926f1865b8..0000000000 --- a/packages/workforce/test/hire-required-settings.test.ts +++ /dev/null @@ -1,165 +0,0 @@ -/** - * A model hiring a kind with required settings has to be able to get them - * right: on the first call from the tool it is shown, and on the second from - * the refusal it gets back. Deterministic — the model's side is the tool's - * description and input schema, and the error text a refused call returns. - * - * What would make each case fail: - * - the `hire` description and `settings` field saying nothing about - * required settings (the description used to name only "the kind and a - * seat id", which is how a model learns to leave `settings` out); - * - the mint refusal passed through as `hireWorkforce`'s boot-time sentence, - * which says neither that nothing was written nor that the call can be - * made again; - * - a refused hire leaving a roster row behind, which turns the corrected - * retry into "already hired"; - * - a mint fault that is not the kind's refusal dressed as one, which sends - * a model to retry a call no setting can fix. - */ -import { afterEach, describe, expect, it, vi } from "vitest"; -import { z } from "zod"; -import { defineFlow, handler } from "@flow-state-dev/core"; -import { executeBlock } from "@flow-state-dev/engine"; -import { createTestContext } from "@flow-state-dev/testing"; -import type { FlowInstance } from "@flow-state-dev/core/types"; -import { createSeatHireBlocks } from "../src/seat-hire-blocks"; -import { defineHiredRosterCollection } from "../src/roster/collections"; -import { defineSeatInventoryCollection } from "../src/inventory/collections"; -import { HIRED_ROSTER_RESOURCE, SEAT_INVENTORY_RESOURCE } from "../src/seat-hire-keys"; -import { workerConfigSchema } from "../src/worker-config"; -import { workerDoor } from "./worker-door"; - -// Lets one case make `hireWorkforce` mint nothing without throwing: a mint -// fault that is not the kind's refusal, which no real kind produces on demand. -const mintFault = vi.hoisted(() => ({ empty: false })); -vi.mock("../src/hire", async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - hireWorkforce: ((...args: Parameters) => - mintFault.empty ? [] : actual.hireWorkforce(...args)) as typeof actual.hireWorkforce, - }; -}); -afterEach(() => { - mintFault.empty = false; -}); - -const noop = handler({ - name: "noop", - inputSchema: z.object({}), - outputSchema: z.object({}), - execute: () => ({}), -}); - -/** A coder kind whose seats must name the document they read, as the DevForce Lab's does. */ -const coder = defineFlow({ - kind: "coder", - cardinality: "collection", - configSchema: workerConfigSchema().extend({ document: z.string().min(1) }), - actions: { ...workerDoor, run: { inputSchema: z.object({}), block: noop } }, -}); - -async function hireTool() { - const registered: FlowInstance[] = []; - const { hire } = createSeatHireBlocks({ - workerFlows: { coder } as never, - register: (seat) => { - registered.push(seat); - }, - unregister: () => true, - }); - const { ctx } = await createTestContext({ - orgId: "acme", - sessionId: "test-session", - declaredResources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection(), - }, - }); - const rosterIds = async () => - (await (ctx.resources as Record Promise> }>)[ - HIRED_ROSTER_RESOURCE - ]!.list()).map((row) => row.state.seatId); - return { hire, ctx, registered, rosterIds }; -} - -describe("the hire tool, as a model sees it, says settings may be required", () => { - it("names settings in the description and on the `settings` field", async () => { - const { hire } = await hireTool(); - expect(hire.description).toMatch(/settings/); - expect(hire.description).toMatch(/refuse/i); - const settings = (hire.inputSchema as z.AnyZodObject).shape.settings as z.ZodTypeAny; - expect(settings.description).toMatch(/require/i); - }); -}); - -describe("a hire missing a required setting comes back correctable", () => { - it("names the setting, says nothing was written, and the corrected call lands", async () => { - const { hire, ctx, registered, rosterIds } = await hireTool(); - - const refused = await executeBlock({ - block: hire, - input: { seatId: "coder-2", flow: "coder" }, - ctx, - }); - const message = refused.error?.message ?? ""; - expect(message).toMatch(/"document": Required/); - expect(message).toMatch(/nothing was written/i); - expect(message).toMatch(/call hire again/i); - expect(registered).toEqual([]); - expect(await rosterIds()).toEqual([]); - - const retried = await executeBlock({ - block: hire, - input: { seatId: "coder-2", flow: "coder", settings: { document: "teams/eng/feature-brief" } }, - ctx, - }); - expect(retried.error).toBeUndefined(); - expect(retried.output).toMatchObject({ seatId: "coder-2", address: "acme.coder-2" }); - expect(registered.map((seat) => (seat.config as { document?: string }).document)).toEqual([ - "teams/eng/feature-brief", - ]); - expect(await rosterIds()).toEqual(["coder-2"]); - }); -}); - -describe("a framework refusal is not dressed as the kind's", () => { - it("refuses a reserved `seatId` setting with the framework's message and no settings hint", async () => { - const { hire, ctx, registered, rosterIds } = await hireTool(); - - const refused = await executeBlock({ - block: hire, - input: { - seatId: "coder-4", - flow: "coder", - settings: { document: "teams/eng/feature-brief", seatId: "someone-else" }, - }, - ctx, - }); - const message = refused.error?.message ?? ""; - // The framework's own sentence for the reserved key, unframed. - expect(message).toMatch(/^hireWorkforce refused 1 of 1 worker/); - expect(message).toMatch(/declares `seatId:`, which is not a setting a worker declares/); - expect(message).not.toMatch(/call hire again|nothing was written/i); - expect(registered).toEqual([]); - expect(await rosterIds()).toEqual([]); - }); -}); - -describe("a mint fault that is not the kind's refusal keeps its own message", () => { - it("does not dress it as a correctable settings refusal", async () => { - const { hire, ctx, registered, rosterIds } = await hireTool(); - mintFault.empty = true; - - const refused = await executeBlock({ - block: hire, - input: { seatId: "coder-3", flow: "coder", settings: { document: "teams/eng/feature-brief" } }, - ctx, - }); - const message = refused.error?.message ?? ""; - expect(message).toBe(`"acme.coder-3" could not be hired, and no reason was given.`); - expect(message).not.toMatch(/call hire again|nothing was written/i); - expect(registered).toEqual([]); - expect(await rosterIds()).toEqual([]); - }); -}); diff --git a/packages/workforce/test/hire.test.ts b/packages/workforce/test/hire.test.ts index d332585949..81719e93bf 100644 --- a/packages/workforce/test/hire.test.ts +++ b/packages/workforce/test/hire.test.ts @@ -11,7 +11,7 @@ import { describe, expect, it } from "vitest"; import { z } from "zod"; import { defineFlow, handler } from "@flow-state-dev/core"; import type { FlowInstance } from "@flow-state-dev/core/types"; -import { hireWorkforce, type HireOptions } from "../src/hire"; +import { mintSeats, type HireOptions } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; import { workerConfigSchema } from "../src/worker-config"; import { workerDoor } from "./worker-door"; @@ -117,7 +117,7 @@ const intake = record({ }); function hireOne(manifest: WorkerManifest): FlowInstance { - const [seat] = hireWorkforce([manifest], { workerFlows: kinds }); + const [seat] = mintSeats([manifest], { workerFlows: kinds }); return seat!; } @@ -127,7 +127,7 @@ function refusalOf( ): string { let seats: FlowInstance[] | undefined; try { - seats = hireWorkforce(manifests, { workerFlows: withKinds }); + seats = mintSeats(manifests, { workerFlows: withKinds }); } catch (error) { expect(seats).toBeUndefined(); return error instanceof Error ? error.message : String(error); @@ -138,14 +138,14 @@ function refusalOf( describe("hireWorkforce", () => { // 1 it("mints one copy per record, carrying its own id, in id order", () => { - const seats = hireWorkforce([lead, intake], { workerFlows: kinds }); + const seats = mintSeats([lead, intake], { workerFlows: kinds }); expect(seats.map((s) => s.id)).toEqual(["engineering.intake", "engineering.lead"]); expect(seats.map((s) => s.kind)).toEqual(["intake", "custom-agent"]); }); // 2 it("gives each copy its own settings, frozen, with no trace of its sibling's", () => { - const seats = hireWorkforce([lead, intake], { workerFlows: kinds }); + const seats = mintSeats([lead, intake], { workerFlows: kinds }); const [thin, opinionated] = seats as [FlowInstance, FlowInstance]; expect(opinionated.config).toMatchObject({ @@ -285,7 +285,7 @@ describe("hireWorkforce", () => { let seats: FlowInstance[] | undefined; let message = ""; try { - seats = hireWorkforce([lead], { workerFlows: { ...kinds, "custom-agent": intakeFlow } }); + seats = mintSeats([lead], { workerFlows: { ...kinds, "custom-agent": intakeFlow } }); } catch (error) { message = error instanceof Error ? error.message : String(error); } @@ -361,7 +361,7 @@ describe("hireWorkforce", () => { it("builds nothing partially — one bad record takes the whole call", () => { let seats: FlowInstance[] | undefined; expect(() => { - seats = hireWorkforce([lead, intake, record({ id: "engineering.ghost", declared: { flow: " " } })], { + seats = mintSeats([lead, intake, record({ id: "engineering.ghost", declared: { flow: " " } })], { workerFlows: kinds }); }).toThrow(); @@ -377,7 +377,7 @@ describe("hireWorkforce", () => { // 12 it("returns an empty roster for empty input", () => { - expect(hireWorkforce([], { workerFlows: kinds })).toEqual([]); + expect(mintSeats([], { workerFlows: kinds })).toEqual([]); }); // 13 @@ -492,7 +492,7 @@ describe("hireWorkforce", () => { // It really does accept the bag — without this the test below would pass // for a kind that is genuinely missing the door. - const [ok] = hireWorkforce( + const [ok] = mintSeats( [record({ id: "engineering.ok", declared: { flow: "optional-no-default" }, body: "Work." })], { workerFlows: withKind } ); @@ -500,7 +500,7 @@ describe("hireWorkforce", () => { let message = ""; try { - hireWorkforce( + mintSeats( [ record({ id: "engineering.typo", diff --git a/packages/workforce/test/hired-reference-read-only-in-devtool.test.ts b/packages/workforce/test/hired-reference-read-only-in-devtool.test.ts index 6fd703fc8b..7e6b8f2f30 100644 --- a/packages/workforce/test/hired-reference-read-only-in-devtool.test.ts +++ b/packages/workforce/test/hired-reference-read-only-in-devtool.test.ts @@ -27,7 +27,7 @@ import { import { readDeclaredRoster } from "../src/loader/read-declared-roster"; import { referencesFromDocs } from "../src/references-from-docs"; import { resourcesFromDocs } from "../src/resources-from-docs"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; import { workerConfigSchema } from "../src/worker-config"; import { workerDoor } from "./worker-door"; @@ -117,7 +117,7 @@ async function devtoolResources(root: string): Promise { const documents = resourcesFromDocs(roster.documents); const references = referencesFromDocs(roster.references); - const [seat] = hireWorkforce( + const [seat] = mintSeats( [{ id: SEAT, declared: { flow: KIND, description: SEAT }, body: "" }], { workerFlows: { [KIND]: kindWith({ ...documents, ...references }) as never }, documents, references }, ); diff --git a/packages/workforce/test/inventory-binder.test.ts b/packages/workforce/test/inventory-binder.test.ts index 3b0dbe89fc..657bb7e2d9 100644 --- a/packages/workforce/test/inventory-binder.test.ts +++ b/packages/workforce/test/inventory-binder.test.ts @@ -378,21 +378,6 @@ function bind( } describe("what one boot writes", () => { - it("counts only the seat rows that landed: a row the boot may not replace is left and not counted", async () => { - // Another process hired `eng.lead`'s address after this boot read its - // roster: the boot's row for it is left, and the binding says one seat. - const lab = await host([record("eng.standup")], { inventory: true }); - try { - const hired ={ id: "eng.lead", kind: "agent", door: "userMessage", hired: true, incarnation: "i-live" }; - await lab.runtime.stores.resourceState.set("org", ORG_ID, "inventory/seats/eng.lead", hired as never, "any" as never); - const result = await bind(lab); - expect(result.problems).toEqual([]); - expect(result.seats).toBe(1); - expect((await lab.read()).seats.find((row) => row.id === "eng.lead")).toEqual(hired); - } finally { - await lab.dispose(); - } - }); it("gives every seat and every open mailbox a row, read back from a flow that is not a mailbox (BR-8, BR-14, BR-21)", async () => { const roster = [record("eng.standup"), record("eng.retro", { members: ["eng.lead"] })]; @@ -410,7 +395,7 @@ describe("what one boot writes", () => { id: "eng.coder", kind: "coder", door: null, - hired: null, + hired: false, incarnation: null }); @@ -448,7 +433,7 @@ describe("what one boot writes", () => { id: "eng.lead", kind: "agent", door: null, - hired: null, + hired: false, incarnation: null }); } finally { diff --git a/packages/workforce/test/listed-seats.test.ts b/packages/workforce/test/listed-seats.test.ts deleted file mode 100644 index e9dd1d2cda..0000000000 --- a/packages/workforce/test/listed-seats.test.ts +++ /dev/null @@ -1,102 +0,0 @@ -/** - * The team-list rule: a hired seat's inventory row is listed only while the - * roster backs it; a declared seat's row is listed as it is. - */ -import { describe, expect, it } from "vitest"; -import { listedSeatRows } from "../src/browser"; - -const declared = [ - { id: "eng.lead", kind: "agent", hired: false }, - { id: "chief-of-staff", kind: "agent", hired: false }, -]; - -describe("listedSeatRows", () => { - it("BR-22 · a hired seat's row with no roster row (as a crash between fire's deletes leaves it) is not listed", () => { - const rows = [ - ...declared, - { id: "acme.support.joe", kind: "desk-clerk", hired: true }, - { id: "acme.support.ada", kind: "agent", hired: true }, - ]; - const listed = listedSeatRows("acme", rows, [{ seatId: "support.ada", incarnation: null }]); - expect(listed.map((row) => row.id)).toEqual(["eng.lead", "chief-of-staff", "acme.support.ada"]); - }); - - it("BR-22 · a row from before rows said where they came from is read by its id: an earlier fire's leftover is not listed", () => { - // Today's fire left exactly this: `{ id, kind, door }`, no `hired`. - const rows = [{ id: "eng.lead", kind: "agent" }, { id: "acme.support.joe", kind: "desk-clerk" }]; - expect(listedSeatRows("acme", rows, []).map((row) => row.id)).toEqual(["eng.lead"]); - }); - - it("BR-23 · declared seats are listed as today, a dotless org seat included", () => { - expect(listedSeatRows("acme", declared, [])).toEqual(declared); - }); - - it("BR-23 · a declared team that shares the organization's name stays listed, with no roster row", () => { - // Org `acme`, declared team `acme`: `acme.support.ada` splits as an - // address in `acme`, and only the row's origin tells it from a hire. - const rows = [{ id: "acme.support.ada", kind: "agent", hired: false }]; - expect(listedSeatRows("acme", rows, [])).toEqual(rows); - expect(listedSeatRows("acme", rows, undefined)).toEqual(rows); - }); - - it("BR-24 · with no roster, no hired seat is listed and declared seats still are", () => { - const rows = [...declared, { id: "acme.support.ada", kind: "agent", hired: true }]; - expect(listedSeatRows("acme", rows, undefined).map((row) => row.id)).toEqual(["eng.lead", "chief-of-staff"]); - }); - - it("a user-owned hire's row is listed only while its owner's roster row carries the same incarnation", () => { - const rows = [...declared, { id: "acme.~u1.research", kind: "agent", hired: true, incarnation: "i-1" }]; - const live = [{ seatId: "research", ownerUserId: "u1", incarnation: "i-1" }]; - expect(listedSeatRows("acme", rows, [], live).map((row) => row.id)).toEqual(["eng.lead", "chief-of-staff", "acme.~u1.research"]); - // The owner's row is another hire's now: this inventory row isn't its. - expect(listedSeatRows("acme", rows, [], [{ ...live[0]!, incarnation: "i-2" }]).map((row) => row.id)).toEqual(["eng.lead", "chief-of-staff"]); - // Another member's row under the same seat id backs nothing at u1's address. - expect(listedSeatRows("acme", rows, [], [{ ...live[0]!, ownerUserId: "u2" }]).map((row) => row.id)).toEqual(["eng.lead", "chief-of-staff"]); - // Rows from before incarnations: none on both sides match; none on one side matches nothing. - const legacy = { id: "acme.~u1.old", kind: "agent", hired: true }; - expect(listedSeatRows("acme", [legacy], [], [{ seatId: "old", ownerUserId: "u1", incarnation: null }])).toEqual([legacy]); - expect(listedSeatRows("acme", [legacy], [], [{ seatId: "old", ownerUserId: "u1", incarnation: "i-1" }])).toEqual([]); - }); - - it("the row a fire leaves when it stops after deleting the owner's roster row is not listed, incarnation and all", () => { - // The crash state: the private roster row is gone, the inventory row is - // exactly what the hire published. Its incarnation says which hire - // published it, not that the hire is still there. - const rows = [...declared, { id: "acme.~u1.research", kind: "agent", hired: true, incarnation: "i-1" }]; - expect(listedSeatRows("acme", rows, [], []).map((row) => row.id)).toEqual(["eng.lead", "chief-of-staff"]); - // A reader that can't read the owner's roster (a browser) can't back it either. - expect(listedSeatRows("acme", rows, []).map((row) => row.id)).toEqual(["eng.lead", "chief-of-staff"]); - }); - - it("an org hire's row is listed only while the roster row at its address carries the same incarnation", () => { - const row = { id: "acme.support.ada", kind: "agent", hired: true, incarnation: "i-1" }; - expect(listedSeatRows("acme", [row], [{ seatId: "support.ada", incarnation: "i-1" }])).toEqual([row]); - // Fired and hired again at the address: the old hire's row isn't the new seat's. - expect(listedSeatRows("acme", [row], [{ seatId: "support.ada", incarnation: "i-2" }])).toEqual([]); - // A roster row from before incarnations backs only a row from before them. - expect(listedSeatRows("acme", [row], [{ seatId: "support.ada", incarnation: null }])).toEqual([]); - const legacy = { id: "acme.support.ada", kind: "agent", hired: true }; - expect(listedSeatRows("acme", [legacy], [{ seatId: "support.ada", incarnation: null }])).toEqual([legacy]); - expect(listedSeatRows("acme", [legacy], [{ seatId: "support.ada", incarnation: "i-2" }])).toEqual([]); - }); - - it("another organization's roster row backs nothing here, and a user-owned address is never backed by the org roster", () => { - const rows = [ - { id: "acme.support.ada", kind: "agent", hired: true }, - { id: "acme.~u1.support.ada", kind: "agent", hired: true }, - ]; - expect(listedSeatRows("globex", rows, [{ seatId: "support.ada", incarnation: null }])).toEqual([]); - expect(listedSeatRows("acme", rows, [{ seatId: "support.ada", incarnation: null }]).map((row) => row.id)).toEqual(["acme.support.ada"]); - }); - - it("a malformed org roster row backs nothing: a seat id shaped like a user-owned address doesn't back that user's row", () => { - // An unreadable org roster row whose seat id starts with `~` would, joined - // raw, spell a user-owned address and stand in for its owner's roster. - const rows = [{ id: "acme.~u1.old", kind: "agent", hired: true }]; - expect(listedSeatRows("acme", rows, [{ seatId: "~u1.old", incarnation: null }])).toEqual([]); - // And one malformed row doesn't take the rest of the list with it. - const ada = { id: "acme.support.ada", kind: "agent", hired: true }; - expect(listedSeatRows("acme", [ada], [{ seatId: "", incarnation: null }, { seatId: "support.ada", incarnation: null }])).toEqual([ada]); - expect(listedSeatRows("acme", [ada], [{ seatId: "support.ada", incarnation: null }], [{ seatId: "~x", ownerUserId: "u1", incarnation: null }])).toEqual([ada]); - }); -}); diff --git a/packages/workforce/test/mailbox-board-attendance.test.ts b/packages/workforce/test/mailbox-board-attendance.test.ts index ab3d9fedfc..e9b630578d 100644 --- a/packages/workforce/test/mailbox-board-attendance.test.ts +++ b/packages/workforce/test/mailbox-board-attendance.test.ts @@ -9,7 +9,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { z } from "zod"; import { __resetDeprecationWarningsForTests, defineFlow, handler } from "@flow-state-dev/core"; -import { mailboxBoard, hireWorkforce, workerConfigSchema } from "../src/index"; +import { mailboxBoard, workerConfigSchema } from "../src/index"; +import { mintSeats } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; import { workerDoor } from "./worker-door"; @@ -52,7 +53,7 @@ describe("a mailbox folder that was renamed", () => { // moved with it and the rows filed under the old id are still sitting at // the old key. Nothing migrates them and nothing refuses (BR-23) — the // seat below is the one that did not move. - hireWorkforce([seat("eng.coder")], { + mintSeats([seat("eng.coder")], { workerFlows: { coder: seatKindHolding(["eng.feature.triage"]) as never }, mailboxBoards: ["eng.renamed.triage"] }); @@ -76,7 +77,7 @@ describe("a mailbox board nobody declared", () => { it("warns at hire, names the mailbox and the id, and still hires", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); try { - const seats = hireWorkforce([seat("eng.coder")], { + const seats = mintSeats([seat("eng.coder")], { workerFlows: { coder: seatKindHolding(["eng.feature.triage"]) as never }, mailboxBoards: ["eng.feature.triage", "eng.feature.review"] }); @@ -103,7 +104,7 @@ describe("a mailbox board nobody declared", () => { it("says nothing when every board a roster minted is declared somewhere", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); try { - hireWorkforce([seat("eng.coder")], { + mintSeats([seat("eng.coder")], { workerFlows: { coder: seatKindHolding(["eng.feature.triage"]) as never }, mailboxBoards: ["eng.feature.triage"] }); @@ -122,7 +123,7 @@ describe("a mailbox board nobody declared", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); try { const hire = (mailboxBoards: string[]) => - hireWorkforce([seat("eng.coder")], { + mintSeats([seat("eng.coder")], { workerFlows: { coder: seatKindHolding(["eng.feature.triage"]) as never }, mailboxBoards }); @@ -147,7 +148,7 @@ describe("a mailbox board nobody declared", () => { // boards existed. const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); try { - hireWorkforce([seat("eng.coder")], { + mintSeats([seat("eng.coder")], { workerFlows: { coder: seatKindHolding([]) as never } }); expect(warn).not.toHaveBeenCalled(); diff --git a/packages/workforce/test/mailbox-board-tools.test.ts b/packages/workforce/test/mailbox-board-tools.test.ts index ed7337f13a..2515cdb42f 100644 --- a/packages/workforce/test/mailbox-board-tools.test.ts +++ b/packages/workforce/test/mailbox-board-tools.test.ts @@ -29,11 +29,11 @@ import { mailboxBoardTaskTools, mailboxInstances, defineAgentWorkerFlow, - hireWorkforce, openMailboxes, workerConfigSchema, - type MailboxManifest + type MailboxManifest, } from "../src/index"; +import { mintSeats } from "../src/hire"; // Package-internal: the board module's joins and resolvers are not public // surface, so a test reaches them where they live. import { resolveMailboxBoard } from "../src/mailbox/mailbox-board"; @@ -109,7 +109,7 @@ async function lab(script: Array>) { const [mailbox] = mailboxInstances(roster); const triage = mailboxBoard("eng.feature", "triage"); - const [seat] = hireWorkforce( + const [seat] = mintSeats( [{ id: "eng.coder", declared: { flow: AGENT_KIND, tools: [] }, body: "Coder." }], { workerFlows: { [AGENT_KIND]: defineAgentWorkerFlow({ uses: [mailboxBoardTaskTools(triage)] }) } } ); @@ -243,7 +243,7 @@ describe("a seat holding two boards", () => { // also the shape a fixed capability name and eight fixed tool names make // impossible: the capability collides at build, and the tools collide at // the generator's own uniqueness assert. - const [seat] = hireWorkforce( + const [seat] = mintSeats( [{ id: "eng.coder", declared: { flow: AGENT_KIND, tools: [] }, body: "Coder." }], { workerFlows: { @@ -334,7 +334,7 @@ describe("the seat's `tools:` fence", () => { // Both cases above already ran on a seat whose record says `tools: []`. // This one states the claim directly, on the hired seat, so a reader does // not have to infer it from a passing tool call. - const [seat] = hireWorkforce( + const [seat] = mintSeats( [{ id: "eng.fenced", declared: { flow: AGENT_KIND, tools: [] }, body: "Fenced." }], { workerFlows: { @@ -485,7 +485,7 @@ describe("a mailbox-board tool colocated in a seat's own folder", () => { let message = ""; try { - hireWorkforce([{ id: "eng.colo", declared: { flow: AGENT_KIND }, body: "Colo." }], { + mintSeats([{ id: "eng.colo", declared: { flow: AGENT_KIND }, body: "Colo." }], { workerFlows: { [AGENT_KIND]: defineAgentWorkerFlow() }, seatBlocks: { "eng.colo": { "file-triage": colocated } } }); diff --git a/packages/workforce/test/mailbox-post-capability.test.ts b/packages/workforce/test/mailbox-post-capability.test.ts index 00919678e2..6287ce5b23 100644 --- a/packages/workforce/test/mailbox-post-capability.test.ts +++ b/packages/workforce/test/mailbox-post-capability.test.ts @@ -39,13 +39,13 @@ import { mailboxPostCapability, defineAgentWorkerFlow, defineMailboxFlow, - hireWorkforce, wakeMemberSeats, workerConfigSchema, type WorkerManifest, } from "../src/index"; -import { hiredSeatManifest, toHiredSeatRow } from "../src/roster/rows"; +import { mintSeats } from "../src/hire"; import { postedLines } from "./mailbox-post-lines"; +import { createWorkerInstallation } from "../src/workers/installation"; const USER_ID = "devuser"; @@ -161,7 +161,7 @@ async function mailboxRequests(runtime: FlowStateRuntime, sessionId: string, cou describe("post-to-mailbox", () => { it("lands one line in a mailbox the seat belongs to, under the seat's own id (BR-1, BR-3)", async () => { - const [otto] = hireWorkforce([seat("support.otto")], { workerFlows: { agent } }); + const [otto] = mintSeats([seat("support.otto")], { workerFlows: { agent } }); const state = host([otto!]); try { const runtime = await state.getRuntime(); @@ -186,7 +186,7 @@ describe("post-to-mailbox", () => { }); it("wakes no co-member when the seat posts through the tool, and still wakes them on a public claim of that seat", async () => { - const [otto, iris] = hireWorkforce([seat("support.otto"), seat("support.iris", undefined)], { workerFlows: { agent } }); + const [otto, iris] = mintSeats([seat("support.otto"), seat("support.iris", undefined)], { workerFlows: { agent } }); const mailbox = defineMailboxFlow({ notify: wakeMemberSeats([otto!, iris!]) })(); const state = createFlowState({ flows: { [MAILBOX_KIND]: mailbox, [otto!.id]: otto!, [iris!.id]: iris! }, @@ -233,7 +233,7 @@ describe("post-to-mailbox", () => { }); it("refuses an author from the model, and any other key; nothing is posted (BR-4)", async () => { - const [otto] = hireWorkforce([seat("support.otto")], { workerFlows: { agent } }); + const [otto] = mintSeats([seat("support.otto")], { workerFlows: { agent } }); const state = host([otto!]); try { const runtime = await state.getRuntime(); @@ -253,7 +253,7 @@ describe("post-to-mailbox", () => { }); it("is refused by the mailbox when the seat is not a member; the turn completes and nothing is written (BR-5)", async () => { - const [otto] = hireWorkforce([seat("support.otto")], { workerFlows: { agent } }); + const [otto] = mintSeats([seat("support.otto")], { workerFlows: { agent } }); const state = host([otto!]); try { const runtime = await state.getRuntime(); @@ -273,7 +273,7 @@ describe("post-to-mailbox", () => { }); it("fails the call by name for an id nobody opened, and for a session of another kind; nothing is written (BR-6)", async () => { - const [otto] = hireWorkforce([seat("support.otto")], { workerFlows: { agent } }); + const [otto] = mintSeats([seat("support.otto")], { workerFlows: { agent } }); const state = host([otto!]); try { const runtime = await state.getRuntime(); @@ -293,7 +293,7 @@ describe("post-to-mailbox", () => { }); it("offers nothing to a seat whose tools: does not name it (BR-7)", async () => { - const [iris] = hireWorkforce([seat("support.iris", [])], { workerFlows: { agent } }); + const [iris] = mintSeats([seat("support.iris", [])], { workerFlows: { agent } }); const state = host([iris!]); try { const runtime = await state.getRuntime(); @@ -309,7 +309,7 @@ describe("post-to-mailbox", () => { }); it("refuses an empty body at the tool's input (BR-8)", async () => { - const [otto] = hireWorkforce([seat("support.otto")], { workerFlows: { agent } }); + const [otto] = mintSeats([seat("support.otto")], { workerFlows: { agent } }); const state = host([otto!]); try { const runtime = await state.getRuntime(); @@ -324,28 +324,6 @@ describe("post-to-mailbox", () => { } }); - it("posts a runtime-hired seat's line under its record id, not its address (BR-16)", async () => { - const hired = hiredSeatManifest( - "acme", - toHiredSeatRow({ seatId: "support.pat", flow: "agent", settings: { tools: [POST_TO_MAILBOX_TOOL] } }), - ); - if (!("manifest" in hired)) throw new Error(hired.problem); - const [pat] = hireWorkforce([hired.manifest], { workerFlows: { agent } }); - expect(pat!.id).not.toBe("support.pat"); - const state = host([pat!]); - try { - const runtime = await state.getRuntime(); - await bind(runtime.stores, "support.desk", ["support.otto", "support.pat"], MAILBOX_KIND, "acme"); - - const turn = await say(runtime, pat!, postTurn({ mailbox: "support.desk", body: "new here" }), "acme"); - expect(turn.error).toBeUndefined(); - await mailboxRequests(runtime, "support.desk", 1); - expect((await postedLines(runtime.stores, "support.desk")).map((l) => l.author)).toEqual(["support.pat"]); - } finally { - await state.dispose(); - } - }); - it("refuses a seat whose settings carry no seatId by name, at the mint, so it never posts as the principal (BR-17)", () => { // Minted straight off the kind, not hired: the one way to a seat with no `seatId`. expect(() => agent({ id: "support.otto", config: { tools: [POST_TO_MAILBOX_TOOL] } })).toThrow(/"seatId": Required/); @@ -385,8 +363,56 @@ describe("post-to-mailbox", () => { } }); + it("on one copy that runs every worker, lands the line under the worker the turn loaded (FIX-1788)", async () => { + let flows: Record = {}; + const installation = createWorkerInstallation({ + standardWorkers: [seat("support.otto"), seat("support.iris")], + workerFlows: () => flows as never, + }); + const shared = defineAgentWorkerFlow({ uses: [mailboxPostCapability], installation }); + flows = { agent: shared }; + const copy = shared({ id: "agent" }) as unknown as FlowInstance; + const state = host([copy]); + try { + const runtime = await state.getRuntime(); + const router = await state.getRouter(); + await bind(runtime.stores, "support.desk", ["support.otto", "support.iris"]); + for (const worker of ["support.iris", "support.otto"]) { + const sessionId = `talk-${worker}`; + const created = await router.POST( + new Request("http://localhost/api/flows/agent/sessions", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ userId: USER_ID, sessionId, state: { workerId: worker } }), + }), + { params: { path: ["agent", "sessions"] } }, + ); + expect(created.status).toBe(201); + const turn = await runAction({ + orgId: DEFAULT_ORG_ID, + flow: copy, + actionName: "run", + input: { message: postTurn({ mailbox: "support.desk", body: `from ${worker}` }) }, + userId: USER_ID, + sessionId, + stores: runtime.stores, + runtimeConfig: { ...runtime.runtimeConfig }, + }); + expect(turn.error).toBeUndefined(); + } + await mailboxRequests(runtime, "support.desk", 2); + const lines = await postedLines(runtime.stores, "support.desk"); + expect(lines.map((line) => [line.author, line.body]).sort()).toEqual([ + ["support.iris", "from support.iris"], + ["support.otto", "from support.otto"], + ]); + } finally { + await state.dispose(); + } + }); + it("fails the call naming the external dispatcher; nothing is written (BR-19)", async () => { - const [otto] = hireWorkforce([seat("support.otto")], { workerFlows: { agent } }); + const [otto] = mintSeats([seat("support.otto")], { workerFlows: { agent } }); const state = host([otto!], { external: true }); try { const runtime = await state.getRuntime(); diff --git a/packages/workforce/test/mailbox-route.test.ts b/packages/workforce/test/mailbox-route.test.ts index 3530e6b4e0..d9e1c648d4 100644 --- a/packages/workforce/test/mailbox-route.test.ts +++ b/packages/workforce/test/mailbox-route.test.ts @@ -53,7 +53,7 @@ import { type MailboxNotifyInput, type WorkerManifest } from "../src/index"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; import { failLineWrite, postedLines } from "./mailbox-post-lines"; import { workerDoor } from "./worker-door"; @@ -112,7 +112,6 @@ function workers(pinGeneralTo?: string, undescribed?: string): WorkerManifest[] id, declared: { flow: "listener", description }, body: "", - ...(id === "support.general" && pinGeneralTo !== undefined ? { ownerPin: { orgId: pinGeneralTo } } : {}) })), { id: "support.notes", declared: { flow: "note", description: "Takes notes." }, body: "" }, // A seat that hears posts and has no description, as a runtime hire reloads. @@ -156,7 +155,7 @@ function host( } = {} ) { const { heard, kinds } = listeningKinds(options.failOn); - const seats = hireWorkforce(workers(options.pinGeneralTo, options.undescribed), { workerFlows: kinds }); + const seats = mintSeats(workers(options.pinGeneralTo, options.undescribed), { workerFlows: kinds }); const route = scriptedRoute(); const [mailbox] = mailboxInstances(options.mailboxes ?? manifests(), { kinds: { @@ -751,24 +750,6 @@ describe("a person's post to a routed mailbox", () => { } }); - it("runs nobody when the caller cannot reach the fallback's seat, recorded as failed (BR-6)", async () => { - const { mailbox, state, heard } = host({ pinGeneralTo: "globex" }); - try { - const runtime = await state.getRuntime(); - await bind(runtime.stores, HELP, MEMBERS); - await post(runtime, mailbox, HELP, "who do I ask about a parking pass?"); - await settle(runtime, HELP, 1); - - expect(who(heard, "parking pass")).toEqual([]); - const record = await recordFor(runtime.stores, "parking pass"); - expect(record).toMatchObject({ by: "failed" }); - expect(record?.member).toBeUndefined(); - expect(record?.reason).toMatch(/the fallback "support\.general" has no seat this caller can reach/); - } finally { - await state.dispose(); - } - }); - it("runs nobody when the fallback is not a member of the mailbox as opened (BR-6)", async () => { const { mailbox, state, heard } = host(); try { diff --git a/packages/workforce/test/mailbox-routing-binder.test.ts b/packages/workforce/test/mailbox-routing-binder.test.ts index a7f84233e9..27b851ce31 100644 --- a/packages/workforce/test/mailbox-routing-binder.test.ts +++ b/packages/workforce/test/mailbox-routing-binder.test.ts @@ -28,7 +28,7 @@ import { workerConfigSchema, type MailboxManifest } from "../src/index"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; import { workerDoor } from "./worker-door"; /** A kind of the app's own that takes notes when asked and hears no posts. */ @@ -39,7 +39,7 @@ const note = defineFlow({ actions: { ...workerDoor, take: { block: handler({ name: "note-take", execute: () => ({}) }) } } } as never); -const seats = hireWorkforce( +const seats = mintSeats( [ { id: "support.devices", declared: { description: "Printers, laptops, phones and wifi." }, body: "Devices." }, { id: "support.general", declared: { description: "Anything that fits no one else." }, body: "General." }, diff --git a/packages/workforce/test/manifest-sources.test.ts b/packages/workforce/test/manifest-sources.test.ts index 62e42e8a12..06eaa03a61 100644 --- a/packages/workforce/test/manifest-sources.test.ts +++ b/packages/workforce/test/manifest-sources.test.ts @@ -113,23 +113,6 @@ describe("the seats source", () => { expect(entry!.purpose).toBe('The seat "a.b". Its file declares no description.'); }); - it("FIX-1526 · a roster row with no file is the declared half, so Discover lists a runtime hire", async () => { - const { seats } = sourcesOf(EMPTY, { seats: "seatRows" }, "hiredRows"); - const ctx = ctxWith( - { - seatRows: [{ id: "acme.eng.ada", kind: "agent" }], - hiredRows: [ - { seatId: "eng.ada", flow: "agent", settings: {}, instructions: "You take support tickets." }, - ], - }, - "acme", - ); - - const entries = await seats!.entries(ctx); - expect(entries.map((entry) => entry.id)).toEqual(["acme.eng.ada"]); - expect(entries[0]!.purpose).toBe("You take support tickets."); - }); - it("FIX-1526 · an inventory row whose roster row was fired is withheld", async () => { const { seats } = sourcesOf(EMPTY, { seats: "seatRows" }, "hiredRows"); const ctx = ctxWith( @@ -190,24 +173,6 @@ describe("the seats source", () => { expect((await seats!.entries(ctx)).map((entry) => entry.id)).toEqual(["eng.lead"]); }); - it("skips a roster row whose seat id cannot be an address, and lists its siblings", async () => { - // `~` marks a user-owned seat's address, so a stored seat id starting with - // it cannot be minted. Same failure as the dev-org row, one segment later. - const { seats } = sourcesOf(EMPTY, { seats: "seatRows" }, "hiredRows"); - const ctx = ctxWith( - { - seatRows: [{ id: "acme.eng.ada", kind: "agent" }], - hiredRows: [ - { seatId: "~eng.bo", flow: "agent", settings: {} }, - { seatId: "eng.ada", flow: "agent", settings: {}, instructions: "You take support tickets." }, - ], - }, - "acme", - ); - - expect((await seats!.entries(ctx)).map((entry) => entry.id)).toEqual(["acme.eng.ada"]); - }); - it("withholds a roster row stamped for another organization", async () => { // The owning-org fence: a row that says it belongs to acme is never minted // under the globex session it was read from. Both inventory rows exist, so diff --git a/packages/workforce/test/org-seats.test.ts b/packages/workforce/test/org-seats.test.ts index e9db9d84d6..a6d123242c 100644 --- a/packages/workforce/test/org-seats.test.ts +++ b/packages/workforce/test/org-seats.test.ts @@ -22,7 +22,7 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { z } from "zod"; import { handler } from "@flow-state-dev/core"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; import { readWorkforce, readWorkforceDirectory } from "../src/loader"; import { SEAT_PACKAGES_KEY, type PackageManifest } from "../src/manifest"; import { resolveHeldPackages } from "../src/seat-packages"; @@ -198,7 +198,7 @@ describe("an org seat reads the org level, then its own folder (BR-5)", () => { execute: () => ({ ok: true }), }); - const seats = hireWorkforce(workers, { + const seats = mintSeats(workers, { packageBlocks: { "org/workers/chief-of-staff/packages/roster": { "add-seat": tool } }, }); @@ -222,7 +222,7 @@ describe("an org seat reads the org level, then its own folder (BR-5)", () => { execute: () => ({ ok: true }), }); expect(() => - hireWorkforce(workers, { + mintSeats(workers, { packageBlocks: { "org/workers/chief-of-staff/packages/roster": { "add-seat": tool } }, }), ).toThrow(/worker "chief-of-staff"[\s\S]*org\/workers\/chief-of-staff\/packages\/roster/); @@ -301,27 +301,6 @@ describe("resolveHeldPackages reads an org seat's id through the parser", () => expect(problems.join("\n")).toContain(deploy.path); }); - it("reads a hired org seat's address . as that org seat when the org is known", () => { - // Two segments: without the org peeled, "acme.cos" reads as a seat of team "acme". - const { held, problems } = resolveHeldPackages("acme.cos", ["house"], [house, own], {}, "acme"); - expect(problems).toEqual([]); - expect(held.map((h) => h.manifest.path)).toEqual([own.path, house.path]); - // A user-owned address peels the same way. - expect(resolveHeldPackages("acme.~u_1.cos", ["house"], [house, own], {}, "acme").problems).toEqual([]); - // And a hired team seat keeps its team. - const lead = resolveHeldPackages("acme.eng.lead", ["deploy"], [deploy], {}, "acme"); - expect(lead.problems).toEqual([]); - expect(lead.held.map((h) => h.manifest.path)).toEqual([deploy.path]); - }); - - it("hires an org seat from a roster row with its own folder's package held", () => { - // The caller that has the org: the hire, reading the row's owner pin. - const [seat] = hireWorkforce( - [{ id: "acme.cos", seatId: "cos", declared: {}, body: "", packages: [own], ownerPin: { orgId: "acme" } }], - ); - expect(seat?.id).toBe("acme.cos"); - }); - it("refuses a team library with no owning team on its record, even when it names that package", () => { // A hand-built or widened record can drop the optional `team`. An org // seat has no team, so no team-level package is ever its own. @@ -338,29 +317,6 @@ describe("resolveHeldPackages reads an org seat's id through the parser", () => expect(problems.join("\n")).toContain("no team at all"); }); - it("holds a hired org seat's own package by the seat id it was hired as, not its org-qualified address", () => { - // `acme.research` read as a declared id is team `acme`, worker `research`; - // the seat was hired as `research`, an org seat, and the package is its own. - const mine = pkg("roster", "worker", "org/workers/research/packages/roster", { worker: "research" }); - const [seat] = hireWorkforce([ - { id: "acme.research", seatId: "research", declared: {}, body: "", packages: [mine], ownerPin: { orgId: "acme" } }, - ]); - expect(seat?.id).toBe("acme.research"); - const held = (seat!.config as Record>)[SEAT_PACKAGES_KEY]; - expect((held ?? []).map((entry) => entry.path)).toEqual([mine.path]); - }); - - it("keeps a hired seat on a team named like its org on that team, holding the team's package", () => { - // Seat id `acme.lead` in org `acme`: peeling the org off the seat id would - // read it as org seat `lead` and refuse the team library. - const library = pkg("deploy", "team", "teams/acme/packages/deploy", { team: "acme" }); - const [seat] = hireWorkforce([ - { id: "acme.acme.lead", seatId: "acme.lead", declared: { packages: ["deploy"] }, body: "", packages: [library], ownerPin: { orgId: "acme" } }, - ]); - const held = (seat!.config as Record>)[SEAT_PACKAGES_KEY]; - expect((held ?? []).map((entry) => entry.path)).toEqual([library.path]); - }); - it("refuses a seat id that matches neither declared shape, rather than reading its last two segments", () => { // `a.b.c` is no seat the loader can mint; cut to `b.c` it would read as // worker `c` on team `b` and hold team b's library. diff --git a/packages/workforce/test/owner-pin-gate-single-source.test.ts b/packages/workforce/test/owner-pin-gate-single-source.test.ts deleted file mode 100644 index 7a4431f1c2..0000000000 --- a/packages/workforce/test/owner-pin-gate-single-source.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Guard: the hired-seat owner-pin gate has exactly one implementation. - * - * The gate is what refuses to register a hired seat without an owner pin taken - * from its hire row. It is security-relevant, and it is reachable from several - * modules: the package root, the seat-hire capability, the hire blocks and the - * roster. If two of those held separate copies, an edit to one (a new guard, a - * reworded refusal, a wider pin) would pass every test while the other copy - * stayed as it was. Two checks back the single source: - * - * 1. Every module that exports `registerHiredSeat` or - * `hiredSeatOwnerPinFromRosterOwner` exports the same function object. - * This catches a second exported copy. - * 2. The gate's refusal sentence appears in exactly one source file, the - * roster module that owns the gate. This catches a private copy pasted in - * with its message. - * - * The roster's row-to-pin builder, `hiredSeatOwnerPin(orgId, row)`, gives a - * stored row the pin it registers under, so it must refuse exactly where the - * gate refuses. It is held to the gate's refusal sentence: with that sentence - * in one file, a builder that throws it is a builder that went through the gate. - */ -import { readdirSync, readFileSync } from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; -import { describe, expect, it } from "vitest"; -import * as root from "../src/index"; -import * as capability from "../src/seat-hire-capability"; -import * as blocks from "../src/seat-hire-blocks"; -import * as rosterBarrel from "../src/roster"; -import * as gate from "../src/roster/register-hired-seat"; -import { hiredSeatOwnerPin, toHiredSeatRow } from "../src/roster/rows"; - -const here = path.dirname(fileURLToPath(import.meta.url)); -const srcDir = path.resolve(here, "..", "src"); - -/** The start of the gate's refusal message; the gate's fingerprint in source. */ -const REFUSAL = "A hired seat cannot be registered without an owner pin"; - -/** Recursively collect every `.ts` file under a directory. */ -function collectSourceFiles(dir: string, acc: string[] = []): string[] { - for (const entry of readdirSync(dir, { withFileTypes: true })) { - const full = path.join(dir, entry.name); - if (entry.isDirectory()) collectSourceFiles(full, acc); - else if (entry.isFile() && entry.name.endsWith(".ts")) acc.push(full); - } - return acc; -} - -describe("the hired-seat owner-pin gate has one implementation", () => { - const exporters = { root, capability, blocks, rosterBarrel }; - - it.each(Object.entries(exporters))( - "%s exports the roster module's gate, not a copy", - (_name, mod) => { - expect(mod.registerHiredSeat).toBe(gate.registerHiredSeat); - expect(mod.hiredSeatOwnerPinFromRosterOwner).toBe(gate.hiredSeatOwnerPinFromRosterOwner); - }, - ); - - it("states the refusal in exactly one source file, the roster gate", () => { - const holders = collectSourceFiles(srcDir) - .filter((file) => readFileSync(file, "utf8").includes(REFUSAL)) - .map((file) => path.relative(srcDir, file)); - expect(holders).toEqual([path.join("roster", "register-hired-seat.ts")]); - }); -}); - -describe("the roster's row-to-pin builder goes through the gate", () => { - const orgVisible = toHiredSeatRow({ seatId: "eng.lead", flow: "desk-clerk" }); - const userOwned = toHiredSeatRow({ seatId: "eng.lead", flow: "desk-clerk", ownerUserId: "alice" }); - - // An unpinned hired seat would be admitted as shared. The builder is what - // hands a stored row its pin, so it must refuse the same empty or missing org - // the gate refuses, rather than return `{ orgId: "" }`. - it.each([ - ["an empty org", ""], - ["a missing org", undefined as unknown as string], - ["a null org", null as unknown as string], - ])("refuses %s with the gate's refusal", (_label, orgId) => { - expect(() => hiredSeatOwnerPin(orgId, orgVisible)).toThrow(REFUSAL); - expect(() => hiredSeatOwnerPin(orgId, userOwned)).toThrow(REFUSAL); - }); - - // The pins real rows register under do not move: an org-visible row stays - // visible to the whole org (no `userId` key at all), a user-owned row stays - // that user's. - it("gives an org-visible row { orgId } and a user-owned row { orgId, userId }, as before", () => { - expect(hiredSeatOwnerPin("acme", orgVisible)).toStrictEqual({ orgId: "acme" }); - expect(hiredSeatOwnerPin("acme", userOwned)).toStrictEqual({ orgId: "acme", userId: "alice" }); - expect(hiredSeatOwnerPin("acme", { ...orgVisible, ownerUserId: "" })).toStrictEqual({ - orgId: "acme", - }); - }); -}); diff --git a/packages/workforce/test/project-talk-template.test.ts b/packages/workforce/test/project-talk-template.test.ts index 7be1c896d3..4b306e3700 100644 --- a/packages/workforce/test/project-talk-template.test.ts +++ b/packages/workforce/test/project-talk-template.test.ts @@ -36,7 +36,6 @@ import { defineMailboxFlow, defineProjectBlocks, defineProjectsCollection, - hireWorkforce, openMailboxes, openInventory, wakeMemberSeats, @@ -44,8 +43,9 @@ import { type MailboxManifest, type MailboxNotifyInput, type ProjectRow, - type WorkerManifest + type WorkerManifest, } from "../src/index"; +import { mintSeats } from "../src/hire"; import { MAILBOX_ANSWER_ACTION } from "../src/mailbox/mailbox-flow"; import { forgetOrgTalkTemplate, forgetTalkTemplate, registeredTalkTemplate } from "../src/projects/talk-template"; import { roomLineKey } from "../src/projects/collections"; @@ -505,7 +505,7 @@ async function boot(options: { }) { const heard: Heard[] = []; const kept: { postId?: string; token?: string } = {}; - const seats = hireWorkforce((options.seats ?? ["eng.em", "ops.lead", "chief-of-staff"]).map(seatRecord), { + const seats = mintSeats((options.seats ?? ["eng.em", "ops.lead", "chief-of-staff"]).map(seatRecord), { workerFlows: { listener: listeningKind(heard, kept) as never } }); // Each boot stands for a fresh process: nothing declared or registered before it. diff --git a/packages/workforce/test/read-workforce.test.ts b/packages/workforce/test/read-workforce.test.ts index 7f0fb5c6a6..a3a9c5d0c9 100644 --- a/packages/workforce/test/read-workforce.test.ts +++ b/packages/workforce/test/read-workforce.test.ts @@ -13,7 +13,7 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { z } from "zod"; import { handler } from "@flow-state-dev/core"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; import { readWorkforce } from "../src/loader/read-workforce"; let root: string; @@ -168,7 +168,7 @@ describe("readWorkforce then hireWorkforce: a refused package in a worker's own execute: () => ({ ok: true }), }); expect(() => - hireWorkforce(workers, { + mintSeats(workers, { packageBlocks: { "teams/support/workers/clerk/packages/refunds": { "issue-refund": issueRefund } }, }), ).toThrow(/worker "support\.clerk"[\s\S]*teams\/support\/workers\/clerk\/packages\/refunds/); diff --git a/packages/workforce/test/references-convention.test.ts b/packages/workforce/test/references-convention.test.ts index 9689d203e8..3142ddf720 100644 --- a/packages/workforce/test/references-convention.test.ts +++ b/packages/workforce/test/references-convention.test.ts @@ -49,12 +49,11 @@ import { clearShadowedReferences, describeShadowedReferences, } from "../src/clear-shadowed-references"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; import { SEAT_REFERENCES_KEY, placeOfReference } from "../src/seat-references"; import { SEAT_RESOURCES_KEY } from "../src/seat-resources"; import { workerConfigSchema } from "../src/worker-config"; -import { hiredSeatManifest, toHiredSeatRow } from "../src/roster/rows"; import { workerDoor } from "./worker-door"; const ORG = "org_fix1467"; @@ -182,7 +181,7 @@ const handleFor = (ctx: { resources: { get(k: string): unknown } }, key: string) async function seatOn(root: string, seatRecord: WorkerManifest = seat(ENG_SEAT)) { const documents = resourcesFromDocs((await readResourcesDirectory(root)).documents); const references = referencesFromDocs((await readReferencesDirectory(root)).documents); - const hired = hireWorkforce([seatRecord], { + const hired = mintSeats([seatRecord], { workerFlows: { [KIND]: kindWith({ ...documents, ...references }) as never }, documents, references, @@ -372,7 +371,7 @@ describe("V2b · BR-19 — a row written BEFORE the move shadows the file", () = "org/resources/handbook.md": doc("The org handbook", "ORG HANDBOOK v1"), }); const documents = resourcesFromDocs((await readResourcesDirectory(root)).documents); - const before = hireWorkforce([seat(ENG_SEAT)], { + const before = mintSeats([seat(ENG_SEAT)], { workerFlows: { [KIND]: kindWith(documents) as never }, documents, }); @@ -630,7 +629,7 @@ describe("V4 · BR-14 — the mutable path is untouched", () => { "org/resources/coc.md": doc("Code of conduct", "coc seed"), }); const documents = resourcesFromDocs((await readResourcesDirectory(root)).documents); - const hired = hireWorkforce([seat(ENG_SEAT)], { + const hired = mintSeats([seat(ENG_SEAT)], { workerFlows: { [KIND]: kindWith(documents) as never }, documents, }); @@ -690,7 +689,7 @@ describe("BR-15 · a ref claimed by both slots is refused at both doors", () => content: "x", }); expect(() => - hireWorkforce([seat(ENG_SEAT)], { + mintSeats([seat(ENG_SEAT)], { workerFlows: { [KIND]: kindWith({ [ORG_HANDBOOK]: shared }) as never }, documents: { [ORG_HANDBOOK]: shared }, references: { [ORG_HANDBOOK]: shared }, @@ -744,7 +743,7 @@ describe("the wall places a reference by its minted ref, not by its accessor key // A single-segment alias of a TEAM document — the widening shape. companyHandbook: references[ENG_HANDBOOK]!, }; - const hired = hireWorkforce([seat(seatId)], { + const hired = mintSeats([seat(seatId)], { workerFlows: { [KIND]: kindWith({ ...documents, ...aliased }) as never }, documents, references: aliased, @@ -925,7 +924,7 @@ describe("the wall cannot be turned off by omission", () => { const root = await tree(); const documents = resourcesFromDocs((await readResourcesDirectory(root)).documents); const references = referencesFromDocs((await readReferencesDirectory(root)).documents); - return hireWorkforce([seatRecord], { + return mintSeats([seatRecord], { workerFlows: { [KIND]: kindWith({ ...documents, ...references }) as never }, documents, // `references` deliberately NOT passed. This is the whole case. @@ -950,7 +949,7 @@ describe("the wall cannot be turned off by omission", () => { Object.entries(all).filter(([ref]) => ref !== SALES_HANDBOOK), ); expect(() => - hireWorkforce([seat(ENG_SEAT)], { + mintSeats([seat(ENG_SEAT)], { workerFlows: { [KIND]: kindWith({ ...documents, ...all }) as never }, documents, references: partial, @@ -965,7 +964,7 @@ describe("the wall cannot be turned off by omission", () => { "teams/engineering/resources/scratch.md": doc("Scratch", "seed"), }); const documents = resourcesFromDocs((await readResourcesDirectory(root)).documents); - const hired = hireWorkforce([seat(ENG_SEAT)], { + const hired = mintSeats([seat(ENG_SEAT)], { workerFlows: { [KIND]: kindWith(documents) as never }, documents, }); @@ -1011,28 +1010,3 @@ describe("an org seat's own references/ reach that seat alone", () => { }); }); -describe("a runtime-hired seat on a kind with references", () => { - it("mints at its org-qualified address, and its wall is drawn from the seat id it was hired as", async () => { - // The hire row's address carries the organization (`acme.engineering.ada`); - // the place in the tree is the seat id (`engineering.ada`). - const bound = hiredSeatManifest("acme", toHiredSeatRow({ seatId: ENG_SEAT, flow: KIND, owningOrgId: "acme" })); - if ("problem" in bound) throw new Error(bound.problem); - expect(bound.manifest.id).toBe(`acme.${ENG_SEAT}`); - - const { seat: hired } = await seatOn(await tree(), bound.manifest); - expect(hired?.id).toBe(`acme.${ENG_SEAT}`); - // Under the organization the hire pinned it to. - const ctx = await createExecutionContext({ - flow: hired!, - actionName: "run", - requestId: "req_hired", - sessionId: "sess_hired", - userId: USER, - orgId: "acme", - stores: createInMemoryStores(), - }); - expect(await handleFor(ctx, ORG_HANDBOOK)!.readContent()).toBe("ORG HANDBOOK v1"); - expect(handleFor(ctx, ENG_HANDBOOK)).toBeDefined(); - expect(handleFor(ctx, SALES_HANDBOOK)).toBeUndefined(); - }); -}); diff --git a/packages/workforce/test/roster-check.test.ts b/packages/workforce/test/roster-check.test.ts deleted file mode 100644 index 00fc93effd..0000000000 --- a/packages/workforce/test/roster-check.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -/** - * The per-row check the boot reload and `brokenSeats` share. - * - * Each reason maps from the refusal the reload already made, and a row whose - * kind is gone is decided before anything is minted: the hire is never asked - * about a kind the app no longer carries. - */ -import { describe, expect, it, vi } from "vitest"; -import { z } from "zod"; -import { defineFlow, handler } from "@flow-state-dev/core"; -import { workerConfigSchema } from "../src/worker-config"; -import { toHiredSeatRow } from "../src/roster/rows"; -import { workerDoor } from "./worker-door"; - -const hires = vi.hoisted(() => ({ calls: [] as string[] })); - -vi.mock("../src/hire", async () => { - const actual = await vi.importActual("../src/hire"); - return { - ...actual, - hireWorkforce: (...args: Parameters) => { - hires.calls.push(...args[0].map((manifest) => manifest.id)); - return actual.hireWorkforce(...args); - }, - }; -}); - -const { checkHiredSeatRow } = await import("../src/roster/check"); -const { reloadHiredSeats } = await import("../src/roster/reload"); - -const noop = handler({ - name: "noop", - inputSchema: z.object({}), - outputSchema: z.object({}), - execute: () => ({}), -}); - -/** A kind whose settings require `queue`. */ -const desk = defineFlow({ - kind: "desk", - cardinality: "collection", - configSchema: workerConfigSchema().extend({ queue: z.string() }), - actions: { ...workerDoor, run: { inputSchema: z.object({}), block: noop } }, -}); - -const kinds = { desk }; - -function stored(over: Parameters[0]) { - return toHiredSeatRow({ owningOrgId: "acme", ...over }); -} - -describe("checkHiredSeatRow", () => { - it("a row that would start is a seat", () => { - const checked = checkHiredSeatRow("acme", stored({ seatId: "support.ada", flow: "desk", settings: { queue: "q" } }), kinds); - expect(checked.ok).toBe(true); - if (checked.ok) expect(checked.seat.id).toBe("acme.support.ada"); - }); - - it("kind-gone is decided before any mint, and names the kinds the app carries", () => { - hires.calls.length = 0; - const checked = checkHiredSeatRow("acme", stored({ seatId: "support.joe", flow: "desk-clerk" }), kinds); - expect(checked).toMatchObject({ ok: false, reason: "kind-gone", row: { seatId: "support.joe", flow: "desk-clerk" } }); - if (!checked.ok) expect(checked.detail).toContain('Worker flows passed: "agent", "desk"'); - expect(hires.calls, "the hire was asked about a cut kind").toEqual([]); - }); - - it("kind-gone's detail is the sentence the hire itself would throw", async () => { - const { hireWorkforce } = await vi.importActual("../src/hire"); - const checked = checkHiredSeatRow("acme", stored({ seatId: "support.joe", flow: "desk-clerk" }), kinds); - let thrown = ""; - try { - hireWorkforce( - [{ id: "acme.support.joe", declared: { flow: "desk-clerk" }, body: "", seatId: "support.joe" }], - { workerFlows: kinds }, - ); - } catch (error) { - thrown = (error as Error).message; - } - expect(thrown).not.toBe(""); - expect(checked.ok ? "" : checked.detail).toBe(thrown); - }); - - it("refused: the kind is carried and refuses the settings, with the kind's own refusal", () => { - const checked = checkHiredSeatRow("acme", stored({ seatId: "support.lin", flow: "desk" }), kinds); - expect(checked).toMatchObject({ ok: false, reason: "refused" }); - if (!checked.ok) expect(checked.detail).toMatch(/queue/); - }); - - it("unreadable: a row that doesn't parse, a row stamped for another org; any org id addresses", () => { - const shapeless = checkHiredSeatRow("acme", { seatId: "support.x" }, kinds); - expect(shapeless).toMatchObject({ ok: false, reason: "unreadable" }); - expect(shapeless.ok ? undefined : shapeless.row).toBeUndefined(); - - const foreign = checkHiredSeatRow("acme", stored({ seatId: "support.y", flow: "desk", owningOrgId: "globex" }), kinds); - expect(foreign).toMatchObject({ ok: false, reason: "unreadable" }); - if (!foreign.ok) expect(foreign.detail).toMatch(/cannot be registered under "acme"/); - - // An org id outside lowercase-hyphen is escaped into the address, not refused. - const spacedOrg = checkHiredSeatRow("Not An Org", stored({ seatId: "support.z", flow: "desk", settings: { queue: "q" }, owningOrgId: null }), kinds); - expect(spacedOrg).toMatchObject({ ok: true }); - }); - - it("the reload names each skipped row with the check's detail, unchanged", async () => { - const rows: Record }> = { - "workforce/roster/support.joe": { state: stored({ seatId: "support.joe", flow: "desk-clerk" }) }, - "workforce/roster/support.lin": { state: stored({ seatId: "support.lin", flow: "desk" }) }, - "workforce/roster/support.ada": { state: stored({ seatId: "support.ada", flow: "desk", settings: { queue: "q" } }) }, - }; - const reload = await reloadHiredSeats({ - stores: { resourceState: { getByPrefix: async () => rows } }, - orgIds: ["acme"], - workerFlows: kinds, - }); - expect(reload.seats.map((seat) => seat.id)).toEqual(["acme.support.ada"]); - const expected = ["support.joe", "support.lin"].map((seatId) => { - const checked = checkHiredSeatRow("acme", rows[`workforce/roster/${seatId}`]!.state, kinds); - return `organization "acme", row "workforce/roster/${seatId}" — ${checked.ok ? "" : checked.detail}`; - }); - expect(reload.problems).toEqual(expected); - }); -}); diff --git a/packages/workforce/test/roster-owner-private.test.ts b/packages/workforce/test/roster-owner-private.test.ts deleted file mode 100644 index 1c833357ec..0000000000 --- a/packages/workforce/test/roster-owner-private.test.ts +++ /dev/null @@ -1,296 +0,0 @@ -/** - * The private roster is an owner-private collection. - * - * `defineHiredRosterPrivateCollection()` declares `ownerPrivate` on `owner`, - * so Engine's generic fences keep each user-owned row with its owner. This - * file holds the roster-shaped cases: which patterns a Workforce app is - * refused (the characterization corpus the change was designed against), - * rows stored before the change reading back unmigrated, and an app that - * never installs Workforce paying nothing for it. - */ -import { describe, expect, it } from "vitest"; -import { z } from "zod"; -import { defineFlow, defineResourceCollection, handler, ownerSegment } from "@flow-state-dev/core"; -import type { FlowInstance, ResourceCollectionRef } from "@flow-state-dev/core/types"; -import { createFlowRegistry, createFlowState, inMemoryStores } from "@flow-state-dev/engine"; -import { createMockModelResolver } from "@flow-state-dev/testing"; -import { defineHiredRosterPrivateCollection } from "../src/roster"; - -const PRIVATE = "workforce/roster/[owner]/[seat]"; - -const overlap = (pattern: string): string => - `Collection pattern "${pattern}" can reach the rows of owner-private collection "${PRIVATE}". ` + - `Only that collection reads or writes them, each for the user it belongs to.`; - -/** - * pattern → the complete refusal at the roster's `org` scope once the private - * roster is registered, or `null` when admitted. The first twelve are the - * characterization corpus: on the parent commit an app without Workforce was - * refused the first eight at registration. The last is the hire-plane goal's - * wide pattern. - */ -const CORPUS: ReadonlyArray = [ - ["workforce/roster/[owner]/notes", overlap("workforce/roster/[owner]/notes")], - ["workforce/roster/**", overlap("workforce/roster/**")], - ["workforce/**", overlap("workforce/**")], - [PRIVATE, overlap(PRIVATE)], - ["**", overlap("**")], - ["[tenant]/**", overlap("[tenant]/**")], - ["[a]/[b]/[c]/[d]", overlap("[a]/[b]/[c]/[d]")], - ["*/**", overlap("*/**")], - ["workforce/roster/*", null], - ["files/**", null], - ["[tenant]/notes/[id]", null], - ["[a]/[b]/[c]", null], - ["workforce/[area]/[owner]/[seat]", overlap("workforce/[area]/[owner]/[seat]")], -]; - -let n = 0; -/** A flow whose resources are set after definition, so registration is measured on its own. */ -function flowWith(kind: string, resources: Record): FlowInstance { - n += 1; - const flow = defineFlow({ - kind, - actions: { - ping: { - inputSchema: z.object({}), - block: handler({ - name: `ping-${n}`, - inputSchema: z.object({}), - outputSchema: z.object({ ok: z.boolean() }), - execute: () => ({ ok: true }), - }), - }, - }, - })(); - (flow as { resources: unknown }).resources = resources; - return flow; -} - -const overlapping = (kind: string, pattern: string, scope = "org") => flowWith(kind, { wide: { pattern, scope } }); - -function refusal(run: () => void): string | null { - try { - run(); - return null; - } catch (error) { - return (error as Error).message; - } -} - -describe("the roster corpus · an app without the private roster", () => { - it.each(CORPUS)("defines and registers %s", (pattern) => { - expect(() => - defineResourceCollection({ pattern, scope: "org", stateSchema: z.object({}).passthrough() }) - ).not.toThrow(); - const registry = createFlowRegistry(); - registry.register(overlapping(`app-${n}`, pattern)); - expect(registry.list()).toHaveLength(1); - }); -}); - -describe("the roster corpus · beside the private roster", () => { - it.each(CORPUS)("private roster first, then %s: the complete message, or admitted", (pattern, message) => { - const registry = createFlowRegistry(); - registry.register(flowWith("hires", { roster: defineHiredRosterPrivateCollection() })); - expect(refusal(() => registry.register(overlapping("late", pattern)))).toBe(message); - expect(registry.get("late") !== undefined).toBe(message === null); - }); - - it.each(CORPUS.filter(([, message]) => message !== null))( - "%s first, then the private roster: refused, naming the earlier flow, and nothing changes", - (pattern, message) => { - const registry = createFlowRegistry(); - registry.register(overlapping("early", pattern)); - expect(refusal(() => registry.register(flowWith("hires", { roster: defineHiredRosterPrivateCollection() })))).toBe( - `${message} Flow "early" declares it and is already registered.` - ); - expect(registry.list().map((flow) => flow.id)).toEqual(["early"]); - } - ); - - it("admits the private roster on several flows, and a collection in another scope whatever its pattern", () => { - const registry = createFlowRegistry(); - registry.register(flowWith("hires-a", { roster: defineHiredRosterPrivateCollection() })); - registry.register(flowWith("hires-b", { roster: defineHiredRosterPrivateCollection() })); - registry.register(overlapping("session-wide", "[tenant]/**", "session")); - expect(registry.list().map((flow) => flow.id)).toEqual(["hires-a", "hires-b", "session-wide"]); - }); -}); - -const verified = { - resolvePrincipal: (context: { request?: Request }) => { - const userId = context.request?.headers.get("x-verified-user"); - const orgId = context.request?.headers.get("x-verified-org"); - return userId && orgId ? { userId, orgId } : null; - }, -}; - -/** Boot `flows` over `stores`; `run` posts one action for `user` in org acme and waits for `probes/`. */ -async function boot(flows: Record, stores: ReturnType) { - const state = createFlowState({ - flows: flows as never, - resolvePrincipal: verified.resolvePrincipal, - stores: { default: { primary: stores } }, - modelResolver: createMockModelResolver({}), - }); - const router = (await state.getRouter()) as Record< - string, - (request: Request, ctx: { params: { path: string[] } }) => Promise - >; - const runtime = await state.getRuntime(); - const call = async (user: string, path: string[], body: unknown) => { - const response = await router.POST!( - new Request(`http://test/api/flows/${path.join("/")}`, { - method: "POST", - headers: { "content-type": "application/json", "x-verified-user": user, "x-verified-org": "acme" }, - body: JSON.stringify(body), - }), - { params: { path } } - ); - return { status: response.status, json: await response.json() }; - }; - const run = async (flow: string, user: string, action: string, tag: string) => { - const opened = await call(user, [flow, "sessions"], { userId: user }); - expect(opened.status).toBe(201); - const posted = await call(user, [flow, opened.json.session.id, "actions", action], { userId: user, input: { tag } }); - expect(posted.status).toBe(202); - let row: { state?: { seen?: string } } | undefined; - for (let i = 0; i < 200 && row === undefined; i++) { - row = await runtime.stores.resourceState.get("org", "acme", `probes/${tag}`); - if (row === undefined) await new Promise((resolve) => setTimeout(resolve, 5)); - } - return JSON.parse(row!.state!.seen!); - }; - return { run }; -} - -const tagInput = z.object({ tag: z.string() }); -const probes = defineResourceCollection({ pattern: "probes/*", scope: "org", stateSchema: z.object({ seen: z.string() }) }); - -async function plant(stores: ReturnType, rows: Record) { - const primary = await stores.resolve(["primary"]); - for (const [key, state] of Object.entries(rows)) { - await primary.resourceState!.set("org", "acme", key, state as never, "any"); - } -} - -describe("rows stored before the private roster was owner-private", () => { - it("read back for their owner through the private roster, a seat id beginning ~ included", async () => { - const roster = defineHiredRosterPrivateCollection(); - const row = (seatId: string, instructions: string) => ({ - seatId, - flow: "desk-clerk", - settings: {}, - instructions, - owningOrgId: "acme", - ownerUserId: "alice", - }); - const read = handler({ - name: "read-roster", - inputSchema: tagInput, - outputSchema: z.object({ ok: z.boolean() }), - resources: { roster, probes }, - execute: async (input, ctx) => { - const handle = ctx.resources.roster as unknown as ResourceCollectionRef; - const owner = ownerSegment(ctx.session.identity.userId!); - const seen = { - list: (await handle.list()).map((entry) => entry.path).sort(), - research: (await handle.getOptional({ owner, seat: "research" }))?.state.instructions ?? null, - tilde: (await handle.getOptional({ owner, seat: "~research" }))?.state.instructions ?? null, - }; - await (ctx.resources.probes as unknown as ResourceCollectionRef).create(input.tag, { seen: JSON.stringify(seen) }); - return { ok: true }; - }, - }); - const stores = inMemoryStores(); - await plant(stores, { - "workforce/roster/~alice/research": row("research", "ALICE-RESEARCH"), - "workforce/roster/~alice/~research": row("~research", "ALICE-TILDE"), - }); - const app = await boot( - { - hires: defineFlow({ - kind: "hires", - resources: { roster, probes }, - actions: { read: { inputSchema: tagInput, block: read } }, - authentication: verified, - })(), - }, - stores - ); - - expect(await app.run("hires", "alice", "read", "alice")).toEqual({ - list: ["workforce/roster/~alice/research", "workforce/roster/~alice/~research"], - research: "ALICE-RESEARCH", - tilde: "ALICE-TILDE", - }); - expect(await app.run("hires", "bob", "read", "bob")).toEqual({ list: [], research: null, tilde: null }); - }); -}); - -/** - * An app that never installs Workforce, end to end through `createFlowState` - * and the HTTP router. It declares collections whose patterns reach the - * roster's user-owned rows, writes and lists through them, and starts. The - * store already holds another member's user-owned row, as a store shared with - * a Workforce app would; the app's lists never show it. The same flow beside - * the private roster refuses to start. No model call is involved. - */ -describe("an app without Workforce", () => { - const notesSchema = z.object({ text: z.string() }).passthrough(); - const resources = { - tenantNotes: defineResourceCollection({ - pattern: "[tenant]/**", - scope: "org", - flowIsolation: false, - stateSchema: notesSchema, - }), - rosterNotes: defineResourceCollection({ - pattern: "workforce/roster/[owner]/notes", - scope: "org", - flowIsolation: false, - stateSchema: notesSchema, - }), - probes, - }; - const writeAndList = handler({ - name: "write-and-list", - inputSchema: tagInput, - outputSchema: z.object({ ok: z.boolean() }), - resources, - execute: async (input, ctx) => { - const tenant = ctx.resources.tenantNotes as unknown as ResourceCollectionRef; - const roster = ctx.resources.rosterNotes as unknown as ResourceCollectionRef; - await tenant.create({ tenant: "acme" }, { text: "tenant note" }); - await roster.create({ owner: "team" }, { text: "team note" }); - const paths = [...(await tenant.list()), ...(await roster.list())].map((entry) => entry.path).sort(); - await (ctx.resources.probes as unknown as ResourceCollectionRef).create(input.tag, { seen: JSON.stringify(paths) }); - return { ok: true }; - }, - }); - const app = () => - defineFlow({ - kind: "app", - resources, - actions: { write: { inputSchema: tagInput, block: writeAndList } }, - authentication: verified, - })(); - - it("starts, writes and lists through roster-shaped patterns, and never lists a user-owned row", async () => { - const stores = inMemoryStores(); - await plant(stores, { - "workforce/roster/~alice/research": { text: "ALICE-PRIVATE" }, - "workforce/roster/~alice/notes": { text: "ALICE-PRIVATE" }, - }); - const started = await boot({ app: app() }, stores); - // `[tenant]/**` is parameterized, so the matcher reads its `**` as a - // literal segment: the note it creates is stored at `acme/**`. - expect(await started.run("app", "bob", "write", "bob")).toEqual(["acme/**", "workforce/roster/team/notes"]); - }); - - it("the same flow beside the private roster refuses to start", async () => { - const hires = flowWith("hires", { roster: defineHiredRosterPrivateCollection() }); - await expect(boot({ hires, app: app() }, inMemoryStores())).rejects.toThrow(overlap("[tenant]/**")); - }); -}); diff --git a/packages/workforce/test/roster.test.ts b/packages/workforce/test/roster.test.ts deleted file mode 100644 index cedbc643db..0000000000 --- a/packages/workforce/test/roster.test.ts +++ /dev/null @@ -1,654 +0,0 @@ -/** - * The hired roster: what a row means (V3, V4) and what a boot does with a - * whole one (V5, V6, V7). - * - * Each case below states what would make it fail, because a check whose red - * state nobody produced is not evidence. The six that were actually produced - * and reverted before this file was trusted: - * - * V3 — spread the row as `{ flow: row.flow, ...row.settings }`: a row - * storing its own `settings.flow` mints and registers THAT kind while - * the row says its own kind forever, and the round trip writes the - * shadow back over the column. - * V3 — give `settings` a closed shape instead of a passthrough record: the - * unknown-key assertion fails and a seat comes back on defaults. - * V4 — pass the org into `seatAddress` unescaped: both hires succeed and - * mint the SAME address, so the second silently rebinds the first. - * V5 — hire the roster in one `hireWorkforce` call instead of per row: the - * stale row's throw takes the good row with it, so `seats` is empty - * and `problems` never names anything. This is the degrade path - * broken by mechanism, and it is the check that catches it. - * V6 — swap `withTimeout` for a bare await: the reload hangs instead of - * rejecting, and the assertion on elapsed time is what tells a hang - * from a failure. - * V6 — build the timeout label before the read instead of from the progress - * map: the message reads "the hired roster read for 3 organizations - * timed out", naming a count where BR-17 asks for the org and the - * store. - * V7 — slice `orgIds` to the cap instead of refusing: the "nothing was - * read" assertion fails. - */ -import { describe, expect, it, vi } from "vitest"; -import { z } from "zod"; -import { defineFlow, handler } from "@flow-state-dev/core"; -import { DEFAULT_ORG_ID } from "@flow-state-dev/core/types"; -import { - DEFAULT_ROSTER_READ_TIMEOUT_MS, - HIRED_ROSTER_PREFIX, - hiredSeatManifest, - hiredSeatRowFromManifest, - parseHiredSeatRow, - reloadHiredSeats, - seatAddress, - splitSeatAddress, - toHiredSeatRow, - type HiredRosterStores, -} from "../src/roster"; -import { hireWorkforce } from "../src/hire"; -import { workerConfigSchema } from "../src/worker-config"; -import { workerDoor } from "./worker-door"; - -const inputSchema = z.object({ note: z.string() }); - -const work = handler({ - name: "desk-work", - inputSchema, - outputSchema: z.object({ note: z.string() }), - execute: (input) => input, -}); - -/** - * A kind that composes the seat contract and adds one setting of its own. - * It accepts `desk` and refuses anything else, which is what makes the - * "settings the kind now refuses" case below a real refusal rather than a - * silently dropped key. - */ -const deskClerk = defineFlow({ - kind: "desk-clerk", - cardinality: "collection", - configSchema: workerConfigSchema().extend({ desk: z.string().default("front") }), - actions: { ...workerDoor, answer: { inputSchema, block: work } }, -}); - -const kinds = { "desk-clerk": deskClerk }; - -/** A store stub holding exactly the rows a case names. */ -function storeHolding( - rowsByOrg: Record> -): HiredRosterStores & { reads: string[] } { - const reads: string[] = []; - return { - reads, - resourceState: { - async getByPrefix(_scopeType: string, scopeId: string, keyPrefix: string) { - reads.push(scopeId); - const rows = rowsByOrg[scopeId] ?? {}; - return Object.fromEntries( - Object.entries(rows).map(([seatId, state]) => [ - `${keyPrefix}${seatId}`, - { state: state as Record }, - ]) - ); - }, - }, - }; -} - -describe("V3 · a row round-trips to a record and back", () => { - it("carries a settings key this version has never heard of, in both directions", () => { - // The BP-030 case: `settings` belongs to the KIND's schema, which is free - // to grow keys this package does not know. A strip here would thin a - // seat's configuration on the first reload after the kind gained a - // setting, and the seat would come back on defaults with nothing said. - const stored = { - seatId: "support.ada", - flow: "desk-clerk", - settings: { desk: "back", aSettingFromTheFuture: { nested: [1, 2] } }, - instructions: "You work the back desk.", - }; - - const parsed = parseHiredSeatRow(stored); - expect("row" in parsed).toBe(true); - if (!("row" in parsed)) return; - - const record = hiredSeatManifest("acme", parsed.row); - expect("manifest" in record).toBe(true); - if (!("manifest" in record)) return; - - expect(record.manifest.id).toBe("acme.support.ada"); - expect(record.manifest.declared).toEqual({ - flow: "desk-clerk", - desk: "back", - aSettingFromTheFuture: { nested: [1, 2] }, - }); - expect(record.manifest.body).toBe("You work the back desk."); - - const back = hiredSeatRowFromManifest("acme", record.manifest); - expect("row" in back).toBe(true); - if (!("row" in back)) return; - expect(back.row).toEqual({ - ...parsed.row, - owningOrgId: "acme", - ownerUserId: null, - }); - }); - - it("returns a reason for a row missing a required field, and never throws", () => { - const parsed = parseHiredSeatRow({ seatId: "support.ada" }); - expect("problem" in parsed).toBe(true); - if (!("problem" in parsed)) return; - expect(parsed.problem).toContain("flow"); - }); - - it("leaves absent skills and team instructions ABSENT, not empty", () => { - // Empty would tell the kind its folders were read and held nothing. A - // runtime hire has no folders, which is a different and true claim. - const row = toHiredSeatRow({ seatId: "support.ada", flow: "desk-clerk" }); - const record = hiredSeatManifest("acme", row); - if (!("manifest" in record)) throw new Error("expected a manifest"); - expect(Object.hasOwn(record.manifest, "skills")).toBe(false); - expect(Object.hasOwn(record.manifest, "teamInstructions")).toBe(false); - }); - - it("normalizes whitespace-only instructions to null", () => { - expect(toHiredSeatRow({ seatId: "a.b", flow: "k", instructions: " \n " }).instructions).toBe( - null - ); - }); - - it("does not let a `flow` inside `settings` shadow the row's own column", async () => { - // `settings` is a passthrough record, so `settings.flow` is storable, and - // `settingsOf` strips `flow` as reserved BEFORE the kind validates the - // bag — so nothing downstream ever objects. With the spread the other way - // round (`{ flow: row.flow, ...row.settings }`) this row mints and - // registers an `agent` while the row says `desk-clerk` forever: the - // roster's authoritative column and the running seat disagree, and only - // the row is ever read again. - // - // Red state: restore `declared: { flow: row.flow, ...row.settings }` in - // `hiredSeatManifest` and both assertions below flip to "agent". - const row = { - seatId: "support.ada", - flow: "desk-clerk", - settings: { flow: "agent", desk: "back" }, - instructions: null, - }; - const parsed = parseHiredSeatRow(row); - if (!("row" in parsed)) throw new Error("expected a row"); - - const record = hiredSeatManifest("acme", parsed.row); - if (!("manifest" in record)) throw new Error("expected a manifest"); - expect(record.manifest.declared.flow).toBe("desk-clerk"); - - // …and the seat that actually mints is the row's kind, not the bag's. - const [seat] = hireWorkforce([record.manifest], { workerFlows: kinds }); - expect(seat!.kind).toBe("desk-clerk"); - expect(seat!.id).toBe("acme.support.ada"); - }); - - it("drops a shadowing `settings.flow` on the way back, rather than restoring it", () => { - // The round trip is NOT byte-identical for such a row, and that is the - // intended loss: `hiredSeatRowFromManifest` destructures the single - // `flow` key out of `declared`, and after the fix above that key holds - // the row's authoritative kind. What comes back is the row with the - // shadow removed — the same seat, minus a key that could only ever have - // lied. Every row without a `settings.flow` still round-trips exactly, - // which is the case the V3 round-trip above pins. - const row = toHiredSeatRow({ - seatId: "support.ada", - flow: "desk-clerk", - settings: { flow: "agent", desk: "back" }, - }); - const record = hiredSeatManifest("acme", row); - if (!("manifest" in record)) throw new Error("expected a manifest"); - const back = hiredSeatRowFromManifest("acme", record.manifest); - if (!("row" in back)) throw new Error("expected a row"); - - expect(back.row.flow).toBe("desk-clerk"); - expect(back.row.settings).toEqual({ desk: "back" }); - }); -}); - -describe("V4 · the org segment is what makes the address unambiguous", () => { - it("cannot let org `acme` + `support.ada` and org `acme.support` + `ada` coexist", () => { - // Both would spell `acme.support.ada` if the org went in as written. The - // org is escaped like the user segment, so its dot can't reach the - // address and the two land apart. Pass the org through raw and the second - // expectation fails: both hires mint one address and the second silently - // rebinds the first. - expect(seatAddress("acme", "support.ada")).toBe("acme.support.ada"); - expect(seatAddress("acme.support", "ada")).toBe("acme%2Esupport.ada"); - expect(seatAddress("acme", "research", "alice")).toBe("acme.~alice.research"); - expect(seatAddress("acme", "research", "alice@acme.com")).toBe("acme.~alice%40acme%2Ecom.research"); - expect(() => seatAddress("acme", "~research", "alice")).toThrow(/starts with "~"/); - }); - - it("addresses any org the principal carries, and splits back under it alone", () => { - expect(seatAddress("org_pentest_lab", "helper")).toBe("org%5Fpentest%5Flab.helper"); - expect(seatAddress(DEFAULT_ORG_ID, "lead")).toBe("%5F%5Ffsd%5Fdefault%5Forg%5F%5F.lead"); - expect(splitSeatAddress("org_pentest_lab", "org%5Fpentest%5Flab.helper")).toBe("helper"); - expect(splitSeatAddress("acme.support", "acme%2Esupport.ada")).toBe("ada"); - // An org never reads another's address, even one its raw spelling prefixes. - expect(splitSeatAddress("acme", "acme%2Esupport.ada")).toBeUndefined(); - expect(splitSeatAddress("acme.support", "acme.support.ada")).toBeUndefined(); - }); - - it("refuses an org id with a lone surrogate, which would share U+FFFD's address", () => { - // The escape goes through UTF-8, where a lone surrogate becomes U+FFFD. - // Admit it and these two orgs would answer on one address. - expect(seatAddress("�", "ada")).toBe("%EF%BF%BD.ada"); - expect(() => seatAddress("\uD800", "ada")).toThrow(/not a usable organization id/); - expect(() => seatAddress("acme\uDC00", "ada")).toThrow(/not a usable organization id/); - // A well-formed pair is an ordinary character. - expect(seatAddress("😀", "ada")).toBe("%F0%9F%98%80.ada"); - }); - - it("finds no seat, rather than throwing, under an org id seatAddress refuses", () => { - // `splitSeatAddress` is a lookup: an address is never under such an org. - for (const orgId of ["", " ", "\uD800", "acme\uDC00"]) { - expect(() => splitSeatAddress(orgId, "%EF%BF%BD.ada")).not.toThrow(); - expect(splitSeatAddress(orgId, "%EF%BF%BD.ada")).toBeUndefined(); - expect(splitSeatAddress(orgId, "%20%20%20.ada")).toBeUndefined(); - } - }); - - it("refuses an empty org id", () => { - expect(() => seatAddress("", "support.ada")).toThrow(/organization id must not be empty/); - expect(splitSeatAddress("", ".ada")).toBeUndefined(); - }); - - it("refuses an empty seat id", () => { - expect(() => seatAddress("acme", "")).toThrow(/seat id/); - }); -}); - -describe("V5 · a boot reload skips what it cannot use and serves the rest", () => { - it("hires the good row and names the other two, with distinct reasons", async () => { - const stores = storeHolding({ - acme: { - "support.ada": { - seatId: "support.ada", - flow: "desk-clerk", - settings: { desk: "front" }, - instructions: "Front desk.", - }, - // The kind was deleted from the code since this row was written. - "support.bo": { seatId: "support.bo", flow: "kind-that-is-gone", settings: {} }, - // Nothing can parse this one. - "support.cy": { seatId: "support.cy" }, - }, - }); - - const { seats, problems } = await reloadHiredSeats({ stores, orgIds: ["acme"], workerFlows: kinds }); - - expect(seats.map((seat) => seat.id)).toEqual(["acme.support.ada"]); - expect(seats[0]!.config).toMatchObject({ desk: "front", instructions: "Front desk." }); - - expect(problems).toHaveLength(2); - // Distinct reasons, not two copies of one generic sentence — a reader has - // to be able to tell "put the kind back" from "this row is corrupt". - const [missingKind, unreadable] = problems.sort(); - expect(missingKind).toContain("support.bo"); - expect(missingKind).toContain("kind-that-is-gone"); - expect(unreadable).toContain("support.cy"); - expect(unreadable).toContain("could not be read"); - // Every problem names where it came from, or the boot report points at - // nothing when more than one org is loaded. - for (const problem of problems) expect(problem).toContain('organization "acme"'); - }); - - it("skips a row whose settings the kind now refuses, on the same terms", async () => { - // The batch-hire shape cannot do this: `hireWorkforce` throws for the - // WHOLE roster when one record's settings fail the kind's schema, so a - // pre-check on the kind name would not have caught it either. - const stores = storeHolding({ - acme: { - "support.ada": { seatId: "support.ada", flow: "desk-clerk", settings: { desk: "front" } }, - "support.bo": { - seatId: "support.bo", - flow: "desk-clerk", - settings: { aSettingTheKindDropped: true }, - }, - }, - }); - - const { seats, problems } = await reloadHiredSeats({ stores, orgIds: ["acme"], workerFlows: kinds }); - - expect(seats.map((seat) => seat.id)).toEqual(["acme.support.ada"]); - expect(problems).toHaveLength(1); - expect(problems[0]).toContain("support.bo"); - }); - - it("registers nothing for an org with no rows, and reports no problem", async () => { - const stores = storeHolding({ acme: {} }); - const { seats, problems } = await reloadHiredSeats({ stores, orgIds: ["acme"], workerFlows: kinds }); - expect(seats).toEqual([]); - expect(problems).toEqual([]); - }); - - it("keeps two orgs' seats of the same name apart", async () => { - const row = { seatId: "support.ada", flow: "desk-clerk", settings: {} }; - const stores = storeHolding({ - acme: { "support.ada": { ...row, settings: { desk: "acme-front" } } }, - bravo: { "support.ada": { ...row, settings: { desk: "bravo-front" } } }, - }); - - const { seats, problems } = await reloadHiredSeats({ - stores, - orgIds: ["acme", "bravo"], - workerFlows: kinds, - }); - - expect(problems).toEqual([]); - expect(seats.map((seat) => seat.id)).toEqual(["acme.support.ada", "bravo.support.ada"]); - expect(seats[0]!.config).toMatchObject({ desk: "acme-front" }); - expect(seats[1]!.config).toMatchObject({ desk: "bravo-front" }); - }); - - it("serves the default org's rows, and skips only a row it cannot address", async () => { - // An app with no principal resolver runs as DEFAULT_ORG_ID, and a runtime - // hire there comes back at boot like any other org's. A seat id carrying - // the user-owned `~` marker can never become a seat, but it must cost only - // itself: the boot still hands back every other row, and names this one - // rather than dropping it. - const stores = storeHolding({ - acme: { - "support.ada": { seatId: "support.ada", flow: "desk-clerk", settings: {} }, - "~support.bo": { seatId: "~support.bo", flow: "desk-clerk", settings: {} }, - }, - [DEFAULT_ORG_ID]: { - lead: { - seatId: "lead", - flow: "desk-clerk", - settings: {}, - owningOrgId: DEFAULT_ORG_ID, - }, - }, - }); - - const { seats, problems } = await reloadHiredSeats({ - stores, - orgIds: [DEFAULT_ORG_ID, "acme"], - workerFlows: kinds, - }); - - expect(seats.map((seat) => seat.id)).toEqual([seatAddress(DEFAULT_ORG_ID, "lead"), "acme.support.ada"]); - expect(problems).toHaveLength(1); - expect(problems[0]).toContain('organization "acme", row "workforce/roster/~support.bo"'); - expect(problems[0]).toContain('starts with "~"'); - }); - - it("still refuses a row stamped for another org, even when that org is not addressable", async () => { - // The owning-org fence runs before the address is built, so a row that - // claims a different org is refused as a mismatch — never minted under - // the cell it was read from, and never re-bound to make it addressable. - const stores = storeHolding({ - acme: { - lead: { seatId: "lead", flow: "desk-clerk", settings: {}, owningOrgId: DEFAULT_ORG_ID }, - }, - [DEFAULT_ORG_ID]: { - lead: { seatId: "lead", flow: "desk-clerk", settings: {}, owningOrgId: "acme" }, - }, - }); - - const { seats, problems } = await reloadHiredSeats({ - stores, - orgIds: ["acme", DEFAULT_ORG_ID], - workerFlows: kinds, - }); - - expect(seats).toEqual([]); - expect(problems).toHaveLength(2); - for (const problem of problems) expect(problem).toContain("cannot be registered under"); - }); - - it("reads the pinned storage prefix", async () => { - // The prefix is a public surface: moving it strands every roster already - // written. Asserted so a rename has to be a deliberate edit here too. - const seen: string[] = []; - const stores: HiredRosterStores = { - resourceState: { - async getByPrefix(_scope: string, _id: string, keyPrefix: string) { - seen.push(keyPrefix); - return {}; - }, - }, - }; - await reloadHiredSeats({ stores, orgIds: ["acme"], workerFlows: kinds }); - expect(seen).toEqual(["workforce/roster/"]); - expect(HIRED_ROSTER_PREFIX).toBe("workforce/roster/"); - }); -}); - -describe("the reload, partitioned by organization", () => { - // A caller that publishes the report per organization needs each org's slice - // from the reload itself. The flat `problems` names the org only inside its - // prose, and re-deriving structure from prose is the wrong way round. - const good = { seatId: "support.ada", flow: "desk-clerk", settings: {} }; - const stores = () => - storeHolding({ - acme: { - "support.ada": good, - "support.bo": { seatId: "support.bo", flow: "kind-that-is-gone", settings: {} }, - }, - beta: { "support.ada": good }, - quiet: {}, - }); - - it("returns one entry per organization it was given, in that order, empty ones included", async () => { - const { byOrg } = await reloadHiredSeats({ - stores: stores(), - orgIds: ["acme", "beta", "quiet"], - workerFlows: kinds, - }); - - // An org with nothing to report still gets an entry. Leaving it out is how - // a report written on the last boot stays standing when nobody rewrites it. - expect(byOrg.map((org) => org.orgId)).toEqual(["acme", "beta", "quiet"]); - expect(byOrg[2]).toEqual({ orgId: "quiet", seats: [], problems: [] }); - }); - - it("files each seat and each problem under its own organization only", async () => { - const { byOrg, seats, problems } = await reloadHiredSeats({ - stores: stores(), - orgIds: ["acme", "beta", "quiet"], - workerFlows: kinds, - }); - const [acme, beta] = byOrg; - - expect(acme!.seats.map((seat) => seat.id)).toEqual(["acme.support.ada"]); - expect(acme!.problems).toHaveLength(1); - expect(acme!.problems[0]).toContain("support.bo"); - - expect(beta!.seats.map((seat) => seat.id)).toEqual(["beta.support.ada"]); - expect(beta!.problems).toEqual([]); - - // The flat fields are unchanged: the union of the slices. - expect(seats.map((seat) => seat.id)).toEqual(["acme.support.ada", "beta.support.ada"]); - expect(problems).toEqual(acme!.problems); - }); - - it("files a row stamped for another organization under the org whose cell held it", async () => { - // Refused by the owning-org fence, not by the kind — a different reason - // from the case above, and it has to land in the same slice. A report - // published per organization would otherwise never show it. - const { byOrg, problems } = await reloadHiredSeats({ - stores: storeHolding({ - acme: { stray: { seatId: "stray", flow: "desk-clerk", settings: {}, owningOrgId: "globex" } }, - }), - orgIds: ["acme"], - workerFlows: kinds, - }); - - expect(byOrg[0]!.problems).toHaveLength(1); - expect(byOrg[0]!.problems[0]).toContain('organization "acme", row "workforce/roster/stray"'); - expect(byOrg[0]!.problems[0]).toContain("cannot be registered under"); - expect(problems).toEqual(byOrg[0]!.problems); - }); -}); - -describe("a row read under an empty organization id", () => { - // The owner pin refuses an empty org, and so does the address. On the boot - // reload either refusal must stay one row's named skip: a throw that escaped - // would take every other organization's seats down with it. - it("is reported and skipped, and the other organizations still load", async () => { - const good = { seatId: "support.ada", flow: "desk-clerk", settings: {} }; - const { seats, problems, byOrg } = await reloadHiredSeats({ - stores: storeHolding({ - "": { - legacy: { seatId: "legacy", flow: "desk-clerk", settings: {} }, - stamped: { seatId: "stamped", flow: "desk-clerk", settings: {}, owningOrgId: "" }, - }, - acme: { "support.ada": good }, - }), - orgIds: ["", "acme"], - workerFlows: kinds, - }); - - expect(seats.map((seat) => seat.id)).toEqual(["acme.support.ada"]); - expect(seats[0]!.ownerPin).toStrictEqual({ orgId: "acme" }); - expect(byOrg[0]!.seats).toEqual([]); - expect(byOrg[0]!.problems).toHaveLength(2); - expect(byOrg[0]!.problems[0]).toContain('organization "", row "workforce/roster/legacy"'); - expect(byOrg[0]!.problems[1]).toContain('organization "", row "workforce/roster/stamped"'); - expect(byOrg[1]!.problems).toEqual([]); - expect(problems).toEqual(byOrg[0]!.problems); - }); -}); - -describe("V6 · a store that never answers fails the boot inside its bound", () => { - it("rejects, returns no partial result, and does so well within the test's own budget", async () => { - vi.useFakeTimers(); - try { - const stores: HiredRosterStores = { - resourceState: { - // Never settles. A bare await here hangs the boot for ever, which is - // the outcome the bound exists to convert into an exit. - getByPrefix: () => new Promise(() => {}), - }, - }; - - const reload = reloadHiredSeats({ - stores, - orgIds: ["acme"], - workerFlows: kinds, - timeoutMs: 250, - }); - // Attached before the timers advance, so the rejection is never - // unhandled. - const settled = expect(reload).rejects.toThrow(/timed out/i); - - // The clock is driven rather than waited on: a check that merely waited - // could not tell "rejected at its bound" from "the suite's own timeout - // killed a hang", and those are the two outcomes it has to separate. - await vi.advanceTimersByTimeAsync(260); - await settled; - } finally { - vi.useRealTimers(); - } - }); - - it("names the org it stalled on and the store call, not just the count (BR-17)", async () => { - // BR-17 asks for "an error naming the org and the store". A count tells an - // operator to go looking through every tenant; the org plus the exact - // store method is the difference between a report and an alert. - // - // Satisfiable because `readEveryOrg` is sequential: `bravo` is the second - // of three and never answers, so at the bound it is exactly the first org - // missing from the progress map. `charlie` is here so the case cannot - // pass by naming "the last org" — the stall is in the MIDDLE. - // - // Red state: label the `withTimeout` call `the hired roster read for N - // organizations` and drop the error factory, and every assertion below - // fails on a message that names only the count. - vi.useFakeTimers(); - try { - const stores: HiredRosterStores = { - resourceState: { - getByPrefix: (_scope: string, scopeId: string) => - scopeId === "bravo" - ? new Promise }>>(() => {}) - : Promise.resolve({}), - }, - }; - - const reload = reloadHiredSeats({ - stores, - orgIds: ["acme", "bravo", "charlie"], - workerFlows: kinds, - timeoutMs: 250, - }); - const settled = expect(reload).rejects.toThrow(/timed out/i); - await vi.advanceTimersByTimeAsync(260); - await settled; - - // Re-run for the message itself; the assertions are what BR-17 buys. - const again = reloadHiredSeats({ - stores, - orgIds: ["acme", "bravo", "charlie"], - workerFlows: kinds, - timeoutMs: 250, - }); - const captured = again.catch((error: unknown) => - error instanceof Error ? error.message : String(error) - ); - await vi.advanceTimersByTimeAsync(260); - const message = await captured; - - expect(message).toContain('organization "bravo"'); - expect(message).toContain("stores.resourceState.getByPrefix"); - expect(message).toContain(HIRED_ROSTER_PREFIX); - // Not the org that answered, and not the one never reached. - expect(message).not.toContain('"acme"'); - expect(message).not.toContain('"charlie"'); - // The whole-set bound (D2) is still what is being reported. - expect(message).toContain("1 of 3 organizations had answered"); - } finally { - vi.useRealTimers(); - } - }); - - it("lets a read that rejects outright fail the boot rather than reporting an empty org", async () => { - const stores: HiredRosterStores = { - resourceState: { - getByPrefix: () => Promise.reject(new Error("connection pool is closed")), - }, - }; - await expect(reloadHiredSeats({ stores, orgIds: ["acme"], workerFlows: kinds })).rejects.toThrow( - /connection pool is closed/ - ); - }); - - it("bounds the whole set rather than each read", () => { - // A per-read bound multiplies by the org count, so fifty orgs could spend - // fifty budgets and still be "within bounds" — which bounds nothing. - expect(DEFAULT_ROSTER_READ_TIMEOUT_MS).toBeGreaterThan(0); - }); -}); - -describe("V7 · more orgs than the cap refuses rather than truncating", () => { - it("names the count and the cap, and reads nothing at all", async () => { - const stores = storeHolding({ a: {}, b: {}, c: {} }); - - await expect( - reloadHiredSeats({ stores, orgIds: ["a", "b", "c"], workerFlows: kinds, maxOrgs: 2 }) - ).rejects.toThrow(/3 organizations and its cap is 2/); - - // The assertion the slicing implementation fails: a truncating reload - // would have read the first two and looked healthy doing it. - expect(stores.reads).toEqual([]); - }); - - it("admits exactly the cap", async () => { - const stores = storeHolding({ a: {}, b: {} }); - const { seats, problems } = await reloadHiredSeats({ - stores, - orgIds: ["a", "b"], - workerFlows: kinds, - maxOrgs: 2, - }); - expect(seats).toEqual([]); - expect(problems).toEqual([]); - expect(stores.reads).toEqual(["a", "b"]); - }); -}); diff --git a/packages/workforce/test/seat-capabilities.test.ts b/packages/workforce/test/seat-capabilities.test.ts index e4969f0d66..927d60c42f 100644 --- a/packages/workforce/test/seat-capabilities.test.ts +++ b/packages/workforce/test/seat-capabilities.test.ts @@ -19,7 +19,7 @@ import type { FlowInstance } from "@flow-state-dev/core"; import { executeBlock } from "@flow-state-dev/engine"; import { createTestContext, mockGenerator } from "@flow-state-dev/testing"; import { AGENT_KIND, defineAgentWorkerFlow } from "../src/agent-worker-flow"; -import { hireWorkforce, type HireOptions } from "../src/hire"; +import { mintSeats, type HireOptions } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; // Markers, not prose: each appears in exactly one preset on one capability, so @@ -141,7 +141,7 @@ function hire( manifests: WorkerManifest[], kinds: HireOptions["workerFlows"] = {} ): (id: string) => FlowInstance { - const seats = hireWorkforce(manifests, { workerFlows: kinds }); + const seats = mintSeats(manifests, { workerFlows: kinds }); return (id) => { const seat = seats.find((candidate) => candidate.id === id); if (!seat) throw new Error(`no seat "${id}" in [${seats.map((s) => s.id).join(", ")}]`); @@ -151,7 +151,7 @@ function hire( function refusalOf(manifests: WorkerManifest[], kinds: HireOptions["workerFlows"] = {}): string { try { - hireWorkforce(manifests, { workerFlows: kinds }); + mintSeats(manifests, { workerFlows: kinds }); } catch (error) { return error instanceof Error ? error.message : String(error); } diff --git a/packages/workforce/test/seat-chosen-tools.test.ts b/packages/workforce/test/seat-chosen-tools.test.ts index 052c198dc5..1b820b1292 100644 --- a/packages/workforce/test/seat-chosen-tools.test.ts +++ b/packages/workforce/test/seat-chosen-tools.test.ts @@ -19,9 +19,8 @@ import type { FlowInstance } from "@flow-state-dev/core/types"; import { executeBlock } from "@flow-state-dev/engine"; import { createTestContext, mockGenerator } from "@flow-state-dev/testing"; import { AGENT_KIND, defineAgentWorkerFlow } from "../src/agent-worker-flow"; -import { hireWorkforce, type HireOptions } from "../src/hire"; +import { mintSeats, type HireOptions } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; -import { hiredSeatManifestFromStored, hiredSeatRowFromManifest, toHiredSeatRow } from "../src/roster/rows"; /** A named tool that does nothing; the checks read whether it was OFFERED. */ function tool(name: string) { @@ -90,7 +89,7 @@ function hire( kinds: HireOptions["workerFlows"], seatBlocks?: HireOptions["seatBlocks"] ): (id: string) => FlowInstance { - const seats = hireWorkforce(manifests, { workerFlows: kinds, ...(seatBlocks ? { seatBlocks } : {}) }); + const seats = mintSeats(manifests, { workerFlows: kinds, ...(seatBlocks ? { seatBlocks } : {}) }); return (id) => { const seat = seats.find((candidate) => candidate.id === id); if (!seat) throw new Error(`no seat "${id}" in [${seats.map((s) => s.id).join(", ")}]`); @@ -318,35 +317,6 @@ describe("omitted and empty stay apart after the schema", () => { // A stored row is read the way a file is. Round-tripped through JSON, as // storage does, so a key written as `undefined` could not survive by accident. - it("reads a stored row with no `tools:` as omitted, and a stored `tools: []` as a withhold (BR-8)", async () => { - const stored = (settings: Record, seatId: string) => - JSON.parse( - JSON.stringify( - toHiredSeatRow({ seatId, flow: AGENT_KIND, settings, owningOrgId: "acme" }) - ) - ) as unknown; - const manifestOf = (value: unknown): WorkerManifest => { - const read = hiredSeatManifestFromStored("acme", value); - if ("problem" in read) throw new Error(read.problem); - return read.manifest; - }; - - const open = manifestOf(stored({ capabilities: { fieldwork: ["survey"] } }, "eng.open")); - const shut = manifestOf( - stored({ tools: [], capabilities: { fieldwork: ["survey"] } }, "eng.shut") - ); - - // Written back, the omitted line is still omitted. - const again = hiredSeatRowFromManifest("acme", open); - if ("problem" in again) throw new Error(again.problem); - expect(again.row.settings).not.toHaveProperty("tools"); - - const seat = hire([open, shut], { - [AGENT_KIND]: defineAgentWorkerFlow({ uses: [fieldwork] }) - }); - expect(await offered(seat("acme.eng.open"), "acme")).toEqual(["lookup"]); - expect(await offered(seat("acme.eng.shut"), "acme")).toEqual([]); - }); }); describe("chosen tools that cannot all be granted are refused at the hire", () => { @@ -363,7 +333,7 @@ describe("chosen tools that cannot all be granted are refused at the hire", () = let message = ""; try { - hireWorkforce( + mintSeats( [ record({ id, diff --git a/packages/workforce/test/seat-discovery.test.ts b/packages/workforce/test/seat-discovery.test.ts index 0dc28ebbdf..834221ce42 100644 --- a/packages/workforce/test/seat-discovery.test.ts +++ b/packages/workforce/test/seat-discovery.test.ts @@ -21,7 +21,7 @@ import { executeBlock } from "@flow-state-dev/engine"; import { createTestContext, runForTest } from "@flow-state-dev/testing"; import { createWorkforceCapability } from "../src/workforce-capability"; import { defineAgentWorkerFlow } from "../src/agent-worker-flow"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; /** @@ -151,7 +151,7 @@ describe("the `discover:` worker-file key", () => { function hire(manifests: WorkerManifest[]) { const kind = defineAgentWorkerFlow({ uses: [capabilityWithThreeDomains()] }); - return hireWorkforce(manifests, { workerFlows: { agent: kind as never } }); + return mintSeats(manifests, { workerFlows: { agent: kind as never } }); } it("carries a seat's list onto its settings", () => { diff --git a/packages/workforce/test/seat-door.test.ts b/packages/workforce/test/seat-door.test.ts index 8d24dac71a..3f07c62c05 100644 --- a/packages/workforce/test/seat-door.test.ts +++ b/packages/workforce/test/seat-door.test.ts @@ -12,13 +12,11 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { z } from "zod"; import { defineFlow, handler } from "@flow-state-dev/core"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; import { openInventory } from "../src/inventory/open-inventory"; import type { WorkerManifest } from "../src/manifest"; import { seatDoorOf } from "../src/seat-door"; import { workerConfigSchema } from "../src/worker-config"; -import { checkHiredSeatRow } from "../src/roster/check"; -import { toHiredSeatRow } from "../src/roster/rows"; const message = z.object({ message: z.string() }); const echo = handler({ name: "door-echo", inputSchema: message, outputSchema: message, execute: (i) => i }); @@ -80,18 +78,18 @@ function refusalOf(run: () => unknown): string { describe("a seat's door (BR-1, BR-2)", () => { it("is the built-in agent kind's `run`", () => { - const [seat] = hireWorkforce([record("eng.lead")], { workerFlows: kinds }); + const [seat] = mintSeats([record("eng.lead")], { workerFlows: kinds }); expect(seat!.kind).toBe("agent"); expect(seatDoorOf(seat!)).toEqual({ door: "run" }); }); it("is the one public action a kind declares for a person's message", () => { - const [seat] = hireWorkforce([record("eng.desk", "desk")], { workerFlows: kinds }); + const [seat] = mintSeats([record("eng.desk", "desk")], { workerFlows: kinds }); expect(seatDoorOf(seat!)).toEqual({ door: "ask" }); }); it("refuses a kind with no door when it is registered, and hires nothing", () => { - const message = refusalOf(() => hireWorkforce([record("eng.quiet", "quiet")], { workerFlows: { quiet: quietKind } })); + const message = refusalOf(() => mintSeats([record("eng.quiet", "quiet")], { workerFlows: { quiet: quietKind } })); expect(message).toContain('worker flow "quiet" has no door'); expect(message).toContain("nothing was hired"); }); @@ -99,14 +97,14 @@ describe("a seat's door (BR-1, BR-2)", () => { it("refuses a kind with two doors when it is registered, naming both, and prints no warning", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); const message = refusalOf(() => - hireWorkforce([record("eng.chatty", "two-door")], { workerFlows: { "two-door": twoDoorKind } }), + mintSeats([record("eng.chatty", "two-door")], { workerFlows: { "two-door": twoDoorKind } }), ); expect(message).toContain('worker flow "two-door" has 2 doors ("message", "say")'); expect(warn).not.toHaveBeenCalled(); }); it("is written on the seat's inventory row at boot", async () => { - const seats = hireWorkforce([record("eng.lead"), record("eng.desk", "desk")], { + const seats = mintSeats([record("eng.lead"), record("eng.desk", "desk")], { workerFlows: kinds, }); const sent: unknown[] = []; @@ -130,44 +128,3 @@ describe("a seat's door (BR-1, BR-2)", () => { }); }); -describe("a seat's origin on its inventory row", () => { - it("is `hired: true` for a seat whose id is its address, and `false` for a declared one, even one named like the org", async () => { - // A team-list reader tells the two apart by this, not by the id's shape: - // `org.lead` below is a declared team `org` in organization `org`. - const seats = hireWorkforce( - [{ ...record("org.support.ada"), seatId: "support.ada" }, record("org.lead")], - { workerFlows: kinds }, - ); - const sent: Array<{ seats: Array<{ id: string; hired: boolean | null }> }> = []; - await openInventory( - { seats, mailboxes: [] }, - { - run: async (request) => void sent.push(request.input as (typeof sent)[number]), - userId: "u", - orgId: "org", - seatWriter: { flowKind: "mailbox" }, - }, - ); - expect(sent[0]!.seats.map((row) => [row.id, row.hired])).toEqual([ - ["org.lead", false], - ["org.support.ada", true], - ]); - }); - - it("keeps a hired seat's incarnation when the boot rewrites its row, so a user-owned hire stays listed after a restart", async () => { - const row = toHiredSeatRow({ seatId: "research", flow: "agent", owningOrgId: "org", ownerUserId: "u1", incarnation: "i-9" }); - const checked = checkHiredSeatRow("org", row, kinds); - if (!checked.ok) throw new Error(checked.detail); - const sent: Array<{ seats: Array<{ id: string; incarnation: string | null }> }> = []; - await openInventory( - { seats: [checked.seat], mailboxes: [] }, - { - run: async (request) => void sent.push(request.input as (typeof sent)[number]), - userId: "u", - orgId: "org", - seatWriter: { flowKind: "mailbox" }, - }, - ); - expect(sent[0]!.seats.map((seat) => [seat.id, seat.incarnation])).toEqual([["org.~u1.research", "i-9"]]); - }); -}); diff --git a/packages/workforce/test/seat-hire-ask.test.ts b/packages/workforce/test/seat-hire-ask.test.ts deleted file mode 100644 index de9095c438..0000000000 --- a/packages/workforce/test/seat-hire-ask.test.ts +++ /dev/null @@ -1,825 +0,0 @@ -/** - * Seat-hire tools that ask a person first (`askBefore`), run where a model - * runs them: an agent seat's own turn, under durable execution, answered - * through the same continuation Inbox's Approve and Deny reach. - * - * Graded on the stores and the live registry, never on the model's words. A - * "restart" is a second boot over the same stores: a new registry, a new - * capability, the hired roster reloaded, nothing carried over in memory. - * - * Rules (`specs/issues/FIX-1719/BUSINESS-RULES.md`): BR-8 a hire with `fire` - * listed asks nothing · BR-9 a kind outside `allowKinds` is refused · BR-10 - * fire asks and changes nothing yet · BR-11 Approve removes the seat · BR-12 - * Deny changes nothing · BR-13 a restart between the ask and the answer keeps - * the ask · BR-14 a declared seat is refused with no ask · BR-15 `hire` listed - * asks · BR-16 no durable execution refuses by name · BR-18 `rehire` always - * asks · BR-20 a hire reusing a declared seat's id is refused. Plus the approve - * crash promise: a process that dies between the approval and the write, then - * restarts, makes the change exactly once. - */ -import { mkdtempSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { afterAll, describe, expect, it } from "vitest"; -import { createSQLiteStores, type SQLiteStoreRegistry } from "@flow-state-dev/store-sqlite"; -import type { - FlowInstance, - GeneratorModel, - GeneratorModelCallOptions, - GeneratorModelResult, - ModelResolver, - SuspensionRecord, -} from "@flow-state-dev/core/types"; -import { - continueRequest, - createCheckpointDurabilityProvider, - createFlowRegistry, - runAction, - type StoreRegistry, -} from "@flow-state-dev/engine"; -import { createSeatHireCapability, type SeatHireAskVerb } from "../src/seat-hire-capability"; -import { defineAgentWorkerFlow } from "../src/agent-worker-flow"; -import { hireWorkforce, type HireOptions } from "../src/hire"; -import { reloadHiredSeats } from "../src/roster/reload"; -import { HIRED_ROSTER_PREFIX } from "../src/roster/collections"; -import { toHiredSeatRow } from "../src/roster/rows"; - -/** - * A SQLite file per test, because a restart has to find what the first process - * wrote, items included: the in-memory request store keeps a run's items only - * once the run ends, so a process that dies mid-run would leave it nothing. - */ -const opened: SQLiteStoreRegistry[] = []; -afterAll(() => { - for (const stores of opened) stores.close(); -}); -type LabStores = SQLiteStoreRegistry & { file: string }; -function freshStores(): LabStores { - const file = join(mkdtempSync(join(tmpdir(), "seat-hire-ask-")), "lab.db"); - return reopen({ file }); -} -/** A second connection to the same file: the next process's view. */ -function reopen(stores: { file: string }): LabStores { - const next = Object.assign(createSQLiteStores({ filename: stores.file }), { file: stores.file }); - opened.push(next); - return next; -} - -const ORG = "acme"; -const USER = "u_person"; -const COS = "chief-of-staff"; -const HELPER = "helper"; -const HELPER_ADDRESS = `${ORG}.${HELPER}`; -const COS_TOOLS = ["hire", "fire", "rehire", "brokenSeats"]; - -type Step = (options: GeneratorModelCallOptions) => GeneratorModelResult; - -/** - * A step-capable model that plays `script` in order; `seen` counts the calls. - * `streaming` offers only `streamStep`, as a real provider's model is driven. - */ -function stepModel(script: Step[], streaming = false) { - const seen: GeneratorModelCallOptions[] = []; - const next = (options: GeneratorModelCallOptions): GeneratorModelResult => { - seen.push(options); - const entry = script[seen.length - 1]; - if (entry === undefined) throw new Error(`no script entry for step ${seen.length - 1}`); - return entry(options); - }; - const model: GeneratorModel = streaming - ? { - modelId: "test/stream-step", - async generate() { - throw new Error("the owned tool loop calls streamStep"); - }, - async *streamStep(options) { - const result = next(options); - if (result.text) yield { type: "text_delta", textDelta: result.text }; - yield { type: "finish", finishReason: result.finishReason ?? "stop", fullResult: result } as never; - }, - } - : { - modelId: "test/step", - async generate() { - throw new Error("the owned tool loop calls generateStep"); - }, - async generateStep(options) { - return next(options); - }, - }; - const resolver = Object.assign(() => model, { resolveId: (id: string) => id }) as unknown as ModelResolver; - return { resolver, seen }; -} - -const call = (toolName: string, args: Record, id = "c1"): Step => () => ({ - toolCalls: [{ toolCallId: id, toolName, args }], - finishReason: "tool-calls", -}); -const say = (text: string): Step => () => ({ text, finishReason: "stop" }); - -/** The tool results the model was handed on its last call, as text. */ -function lastToolResults(seen: GeneratorModelCallOptions[]): string { - const messages = seen.at(-1)?.messages ?? []; - return JSON.stringify((messages as Array<{ role?: string }>).filter((m) => m.role === "tool")); -} - -interface BootOptions { - askBefore?: readonly SeatHireAskVerb[]; - durable?: boolean; - /** Stores this process sees; a fault-injecting view of the shared ones. */ - view?: StoreRegistry; - /** How many stored rows the boot is expected to skip. Default none. */ - reloadProblems?: number; - /** Drive the model through `streamStep`, as a real provider's is. */ - streaming?: boolean; - /** Turn on the capability's `refuseRosterAdmin` setting. */ - refuseRosterAdmin?: boolean; - /** Hand the capability `instanceAt`, as a Lab does, so a retried re-hire counts a seat its row minted as its own. */ - instanceAt?: boolean; -} - -/** - * One process: the kinds, the capability, a registry holding the declared - * chief of staff and every stored hire, and a model playing `script`. - */ -async function boot(stores: StoreRegistry, script: Step[], options: BootOptions = {}) { - const seen = stepModel(script, options.streaming); - const registry = createFlowRegistry(); - const released: string[] = []; - const kinds: NonNullable = {}; - const seatHire = createSeatHireCapability({ - workerFlows: kinds, - register: (seat, pin) => registry.register(seat, { pin }), - unregister: (id) => { - released.push(id); - return registry.unregister(id); - }, - kindAt: (id) => registry.get(id)?.kind, - allowKinds: ["agent"], - ...(options.askBefore === undefined ? {} : { askBefore: options.askBefore }), - ...(options.refuseRosterAdmin === undefined ? {} : { refuseRosterAdmin: options.refuseRosterAdmin }), - ...(options.instanceAt === true ? { instanceAt: (id: string) => registry.get(id) } : {}), - }); - kinds.agent = defineAgentWorkerFlow({ uses: [seatHire] }); - - const [cos] = hireWorkforce( - [{ id: COS, declared: { tools: COS_TOOLS }, body: "You are the chief of staff." }], - { workerFlows: kinds }, - ); - registry.register(cos!); - const reload = await reloadHiredSeats({ stores, orgIds: [ORG], workerFlows: kinds }); - expect(reload.problems).toHaveLength(options.reloadProblems ?? 0); - for (const seat of reload.seats) { - registry.register(seat, { pin: (seat as { ownerPin?: { orgId: string } }).ownerPin ?? { orgId: ORG } }); - } - - const view = options.view ?? stores; - const durabilityProvider = - options.durable === false - ? undefined - : createCheckpointDurabilityProvider({ - checkpoints: view.checkpoints, - suspensions: view.suspensions, - leases: view.leases, - }); - const runtimeConfig = { modelResolver: seen.resolver, ...(durabilityProvider === undefined ? {} : { durabilityProvider }) }; - - /** Ask the chief of staff something; the script decides what it does. */ - const ask = async (message: string) => { - const result = await runAction({ - orgId: ORG, - flow: registry.get(COS) as FlowInstance, - actionName: "run", - input: { message }, - userId: USER, - stores: view, - runtimeConfig, - } as never); - return { requestId: result.requestId!, status: (await view.request.get(result.requestId!))?.status }; - }; - - /** Answer the pending ask as Inbox does, and run the request on. */ - const answer = async (requestId: string, action: "approve" | "reject") => { - const [pending] = await pendingAsks(view); - expect(pending).toBeDefined(); - await durabilityProvider!.suspend({ - ...pending!, - status: action === "approve" ? "approved" : "rejected", - resolvedAt: Date.now(), - }); - return continueRequest({ - requestId, - stores: view, - flowRegistry: registry, - resumeContext: { suspensionId: pending!.suspensionId, action, resumedBy: USER }, - runtimeConfig, - } as never); - }; - - /** Pick up a request a dead process left, as crash recovery does. */ - const recover = async (requestId: string) => { - const record = await view.request.get(requestId); - await view.request.set(requestId, { ...record!, status: "interrupted", interruptedAt: Date.now() } as never, "any"); - const { finished } = await continueRequest({ requestId, stores: view, flowRegistry: registry, runtimeConfig } as never); - await finished; - return (await view.request.get(requestId))?.status; - }; - - return { registry, released, seen: seen.seen, ask, answer, recover }; -} - -async function pendingAsks(stores: StoreRegistry): Promise { - return (await stores.suspensions.list({ status: "pending" })) as SuspensionRecord[]; -} - -/** The org's stored roster rows, by seat id. */ -async function rosterRows(stores: StoreRegistry): Promise { - const rows = await stores.resourceState.getByPrefix("org", ORG, HIRED_ROSTER_PREFIX); - return Object.entries(rows) - .filter(([, record]) => (record as { deleted?: boolean; state?: unknown }).state != null) - .map(([key]) => key.slice(HIRED_ROSTER_PREFIX.length)); -} - -/** The org's seat inventory rows, by address. */ -async function inventoryRows(stores: StoreRegistry): Promise { - const rows = await stores.resourceState.getByPrefix("org", ORG, "inventory/seats/"); - return Object.entries(rows) - .filter(([, record]) => (record as { state?: unknown }).state != null) - .map(([key]) => key.slice("inventory/seats/".length)); -} - -/** Hire the helper with nothing asked, as the Lab's policy says. */ -async function withHelperHired(stores: StoreRegistry) { - const lab = await boot(stores, [call("hire", { seatId: HELPER, flow: "agent" }), say("hired")], { askBefore: ["fire"] }); - const hired = await lab.ask("we need a helper"); - expect(hired.status).toBe("completed"); - return lab; -} - -describe("a hire, with only fire asking first (BR-8)", () => { - it("lands at once: roster row, inventory row, a registered address, and no ask", async () => { - const stores = freshStores(); - const lab = await withHelperHired(stores); - expect(await pendingAsks(stores)).toEqual([]); - expect(await rosterRows(stores)).toEqual([HELPER]); - expect(await inventoryRows(stores)).toContain(HELPER_ADDRESS); - expect(lab.registry.get(HELPER_ADDRESS)?.kind).toBe("agent"); - }); - - it("refuses a kind outside allowKinds, writing nothing (BR-9)", async () => { - const stores = freshStores(); - const lab = await boot(stores, [call("hire", { seatId: HELPER, flow: "coder" }), say("could not")], { askBefore: ["fire"] }); - expect((await lab.ask("hire a coder")).status).toBe("completed"); - expect(lastToolResults(lab.seen)).toContain("may not hire kind"); - expect(await rosterRows(stores)).toEqual([]); - }); - - it("refuses a seat id a declared seat holds, before any row is written (BR-20)", async () => { - const stores = freshStores(); - const lab = await boot(stores, [call("hire", { seatId: COS, flow: "agent" }), say("could not")], { askBefore: ["fire"] }); - expect((await lab.ask("hire another chief of staff")).status).toBe("completed"); - expect(lastToolResults(lab.seen)).toContain(`is the id of a seat this app declares`); - expect(await rosterRows(stores)).toEqual([]); - expect(await pendingAsks(stores)).toEqual([]); - }); -}); - -describe("roster admin, when the app keeps it with the seats it declares", () => { - it("with refuseRosterAdmin, refuses a hire whose settings grant the roster tools, by a tools line or by picking the seat-hire capability", async () => { - // An app that keeps hiring with its chief of staff: a seat it hires can't - // be handed the same tools, whatever the kind. - const stores = freshStores(); - const lab = await boot( - stores, - [ - call("hire", { seatId: "deputy", flow: "agent", settings: { tools: ["hire", "fire"] } }, "h1"), - call("hire", { seatId: "deputy2", flow: "agent", settings: { capabilities: { "seat-hire": ["tools"] } } }, "h2"), - say("done"), - ], - { refuseRosterAdmin: true }, - ); - expect((await lab.ask("hire two deputies who can hire")).status).toBe("completed"); - const results = lastToolResults(lab.seen); - expect(results.match(/keeps the roster tools with the seats it declares/g)).toHaveLength(2); - expect(await rosterRows(stores)).toEqual([]); - }); - - it("without it, a hired seat may be given the roster tools like any other tool", async () => { - // The refusal is a setting an app opts into, not a rule of the tool: - // left off, a hire that names `hire` goes through. - const stores = freshStores(); - const lab = await boot(stores, [ - call("hire", { seatId: "deputy", flow: "agent", settings: { tools: ["hire"] } }, "h1"), - say("done"), - ]); - expect((await lab.ask("hire a deputy who can hire")).status).toBe("completed"); - expect(lastToolResults(lab.seen)).not.toMatch(/roster tools/); - expect(await rosterRows(stores)).toEqual(["deputy"]); - }); - - it("with refuseRosterAdmin, refuses to finish a pending re-hire whose settings grant the roster tools", async () => { - // What a re-hire left when it died after its roster write, from before - // the app turned the refusal on: a row onto `agent` holding `hire`. - const stores = freshStores(); - const key = `${HIRED_ROSTER_PREFIX}${HELPER}`; - const token = "inc-pending"; - const row = { - ...toHiredSeatRow({ seatId: HELPER, flow: "agent", settings: { tools: ["hire"] }, owningOrgId: ORG }), - incarnation: token, - pendingRepair: token, - }; - await stores.resourceState.set("org", ORG, key, row as never, "any"); - const lab = await boot( - stores, - [call("rehire", { seatId: HELPER, flow: "agent", settings: { tools: ["hire"] } }), say("done")], - { refuseRosterAdmin: true }, - ); - expect((await lab.ask("finish the helper's re-hire")).status).toBe("completed"); - - expect(await pendingAsks(stores)).toEqual([]); - expect(lastToolResults(lab.seen)).toContain("keeps the roster tools with the seats it declares"); - expect((await stores.resourceState.get("org", ORG, key))?.state).toMatchObject({ pendingRepair: token }); - expect(await inventoryRows(stores)).not.toContain(HELPER_ADDRESS); - }); -}); - -describe("a fire, with fire asking first", () => { - it("raises one human_approval naming the verb, the seat and its kind, and changes nothing yet (BR-10)", async () => { - const stores = freshStores(); - await withHelperHired(stores); - const lab = await boot(stores, [call("fire", { seatId: HELPER })], { askBefore: ["fire"] }); - const fired = await lab.ask("let the helper go"); - expect(fired.status).toBe("suspended"); - - const [pending] = await pendingAsks(stores); - expect(pending?.reason).toBe("human_approval"); - const stored = (await stores.resourceState.get("org", ORG, `${HIRED_ROSTER_PREFIX}${HELPER}`))?.state as - | { incarnation?: unknown } - | undefined; - expect(typeof stored?.incarnation).toBe("string"); - expect(pending?.data).toEqual({ verb: "fire", seatId: HELPER, kind: "agent", owner: null, incarnation: stored?.incarnation }); - expect(await rosterRows(stores)).toEqual([HELPER]); - expect(lab.registry.get(HELPER_ADDRESS)).toBeDefined(); - expect(lab.released).toEqual([]); - }); - - it("raises the same ask when the model streams, as a real provider's does", async () => { - const stores = freshStores(); - await withHelperHired(stores); - const lab = await boot(stores, [call("fire", { seatId: HELPER }), say("waiting")], { askBefore: ["fire"], streaming: true }); - expect((await lab.ask("let the helper go")).status).toBe("suspended"); - expect((await pendingAsks(stores))[0]?.data).toEqual({ verb: "fire", seatId: HELPER, kind: "agent", owner: null, incarnation: expect.any(String) }); - expect(await rosterRows(stores)).toEqual([HELPER]); - }); - - it("on Approve removes the roster row, the address and the inventory row (BR-11)", async () => { - const stores = freshStores(); - await withHelperHired(stores); - const lab = await boot(stores, [call("fire", { seatId: HELPER }), say("done")], { askBefore: ["fire"] }); - const { requestId } = await lab.ask("let the helper go"); - const { finished } = await lab.answer(requestId, "approve"); - await finished; - - expect((await stores.request.get(requestId))?.status).toBe("completed"); - expect(await rosterRows(stores)).toEqual([]); - expect(await inventoryRows(stores)).not.toContain(HELPER_ADDRESS); - expect(lab.registry.get(HELPER_ADDRESS)).toBeUndefined(); - expect(lab.released).toEqual([HELPER_ADDRESS]); - // And a restart brings nothing back. - const after = await boot(stores, []); - expect(after.registry.get(HELPER_ADDRESS)).toBeUndefined(); - }); - - it("carries the owner a fire names through the ask to the fire it makes, and refuses one this flow can't reach unasked", async () => { - const stores = freshStores(); - await withHelperHired(stores); - // The chief of staff mounts the organization's roster only: a seat of - // the caller's own is refused before anyone is asked. - const mine = await boot(stores, [call("fire", { seatId: HELPER, owner: "me" }), say("no")], { askBefore: ["fire"] }); - expect((await mine.ask("let my helper go")).status).toBe("completed"); - expect(lastToolResults(mine.seen)).toContain("user-owned roster"); - expect(await pendingAsks(stores)).toEqual([]); - - const lab = await boot(stores, [call("fire", { seatId: HELPER, owner: "organization" }), say("done")], { askBefore: ["fire"] }); - const { requestId } = await lab.ask("let the helper go"); - expect((await pendingAsks(stores))[0]?.data).toMatchObject({ verb: "fire", seatId: HELPER, owner: null }); - const { finished } = await lab.answer(requestId, "approve"); - await finished; - expect(await rosterRows(stores)).toEqual([]); - expect(lab.released).toEqual([HELPER_ADDRESS]); - }); - - it("on Approve leaves alone a seat hired under the same id while the person was asked", async () => { - const stores = freshStores(); - await withHelperHired(stores); - const asked = await boot(stores, [call("fire", { seatId: HELPER }), say("done")], { askBefore: ["fire"] }); - const { requestId } = await asked.ask("let the helper go"); - - // Meanwhile, through a door that doesn't ask: the helper is fired and a - // new one hired under the same id. - const meanwhile = await boot(stores, [ - call("fire", { seatId: HELPER }, "f1"), - call("hire", { seatId: HELPER, flow: "agent", instructions: "The new helper." }, "h1"), - say("replaced"), - ]); - expect((await meanwhile.ask("replace the helper")).status).toBe("completed"); - const replacement = await stores.resourceState.get("org", ORG, `${HIRED_ROSTER_PREFIX}${HELPER}`); - - const { finished } = await asked.answer(requestId, "approve"); - await finished; - expect((await stores.request.get(requestId))?.status).toBe("completed"); - - expect(lastToolResults(asked.seen)).toContain("changed while you were asked"); - expect(await rosterRows(stores)).toEqual([HELPER]); - expect(await stores.resourceState.get("org", ORG, `${HIRED_ROSTER_PREFIX}${HELPER}`)).toEqual(replacement); - expect(await inventoryRows(stores)).toContain(HELPER_ADDRESS); - }); - - it("on Deny changes nothing, and the model is told (BR-12)", async () => { - const stores = freshStores(); - await withHelperHired(stores); - const lab = await boot(stores, [call("fire", { seatId: HELPER }), say("kept")], { askBefore: ["fire"] }); - const { requestId } = await lab.ask("let the helper go"); - const { finished } = await lab.answer(requestId, "reject"); - await finished; - - expect((await stores.request.get(requestId))?.status).toBe("completed"); - expect(lastToolResults(lab.seen)).toContain("denied"); - expect(await rosterRows(stores)).toEqual([HELPER]); - expect(lab.released).toEqual([]); - const after = await boot(stores, []); - expect(after.registry.get(HELPER_ADDRESS)?.kind).toBe("agent"); - }); - - it("keeps the ask across a restart, and Approve after it removes the seat (BR-13)", async () => { - const stores = freshStores(); - await withHelperHired(stores); - const before = await boot(stores, [call("fire", { seatId: HELPER })], { askBefore: ["fire"] }); - const { requestId } = await before.ask("let the helper go"); - - // The process is gone. A new one boots over the same file. - const next = reopen(stores); - const after = await boot(next, [say("done")], { askBefore: ["fire"] }); - expect(await pendingAsks(next)).toHaveLength(1); - expect(after.registry.get(HELPER_ADDRESS)?.kind).toBe("agent"); - - const { finished } = await after.answer(requestId, "approve"); - await finished; - expect(await rosterRows(next)).toEqual([]); - expect(after.registry.get(HELPER_ADDRESS)).toBeUndefined(); - expect(after.released).toEqual([HELPER_ADDRESS]); - }); - - it("refuses the chief of staff itself with no ask (BR-14)", async () => { - const stores = freshStores(); - const lab = await boot(stores, [call("fire", { seatId: COS }), say("no")], { askBefore: ["fire"] }); - expect((await lab.ask("fire yourself")).status).toBe("completed"); - expect(lastToolResults(lab.seen)).toContain("removed by editing its folder"); - expect(await pendingAsks(stores)).toEqual([]); - expect(lab.registry.get(COS)).toBeDefined(); - }); - - it("on Approve refuses a seat whose row carries no incarnation, so a replacement written the same way isn't fired unasked", async () => { - // A writer that stamps no incarnation (an older row, or `toHiredSeatRow`'s - // default) can fire and replace the seat while the person is asked; with - // no stamp on either row, nothing tells the replacement from the original. - const stores = freshStores(); - const key = `${HIRED_ROSTER_PREFIX}${HELPER}`; - await stores.resourceState.set("org", ORG, key, toHiredSeatRow({ seatId: HELPER, flow: "agent", owningOrgId: ORG }) as never, "any"); - const asked = await boot(stores, [call("fire", { seatId: HELPER }), say("done")], { askBefore: ["fire"] }); - const { requestId } = await asked.ask("let the helper go"); - expect((await pendingAsks(stores))[0]?.data).toMatchObject({ verb: "fire", seatId: HELPER, incarnation: null }); - - const replacement = toHiredSeatRow({ seatId: HELPER, flow: "agent", owningOrgId: ORG, instructions: "The new helper." }); - await stores.resourceState.set("org", ORG, key, replacement as never, "any"); - - const { finished } = await asked.answer(requestId, "approve"); - await finished; - expect(lastToolResults(asked.seen)).toContain("carries no incarnation"); - expect(await rosterRows(stores)).toEqual([HELPER]); - expect((await stores.resourceState.get("org", ORG, key))?.state).toEqual(replacement); - expect(asked.released).toEqual([]); - }); - - it("on Approve refuses a re-hire of a row with no incarnation, even when a different-kind row replaced it", async () => { - const stores = freshStores(); - const key = `${HIRED_ROSTER_PREFIX}${HELPER}`; - await stores.resourceState.set("org", ORG, key, toHiredSeatRow({ seatId: HELPER, flow: "retired-kind", owningOrgId: ORG }) as never, "any"); - const asked = await boot(stores, [call("rehire", { seatId: HELPER, flow: "agent" }), say("done")], { reloadProblems: 1 }); - const { requestId } = await asked.ask("put the helper back on the agent kind"); - - const replacement = toHiredSeatRow({ seatId: HELPER, flow: "another-retired-kind", owningOrgId: ORG }); - await stores.resourceState.set("org", ORG, key, replacement as never, "any"); - - const { finished } = await asked.answer(requestId, "approve"); - await finished; - expect(lastToolResults(asked.seen)).toContain("carries no incarnation"); - expect((await stores.resourceState.get("org", ORG, key))?.state).toEqual(replacement); - expect(asked.registry.get(`${ORG}.${HELPER}`)).toBeUndefined(); - }); - - it("asks before clearing a hired seat's leftover inventory row, and refuses one that never said it was hired", async () => { - // A crash between fire's two deletes leaves a `hired: true` inventory row - // with no roster row; fire still clears it, so the ask is still owed. A - // row with no `hired` mark is nothing fire removes, so nobody is asked. - const leftover = async (stores: StoreRegistry, hired: boolean) => - stores.resourceState.set( - "org", - ORG, - `inventory/seats/${HELPER_ADDRESS}`, - { id: HELPER_ADDRESS, kind: "agent", door: null, ...(hired ? { hired: true } : {}) } as never, - "any", - ); - - const marked = freshStores(); - await leftover(marked, true); - const asked = await boot(marked, [call("fire", { seatId: HELPER })], { askBefore: ["fire"] }); - expect((await asked.ask("clear the helper")).status).toBe("suspended"); - expect((await pendingAsks(marked))[0]?.data).toEqual({ verb: "fire", seatId: HELPER, kind: null, owner: null, incarnation: null }); - - const unmarked = freshStores(); - await leftover(unmarked, false); - const refused = await boot(unmarked, [call("fire", { seatId: HELPER }), say("no")], { askBefore: ["fire"] }); - expect((await refused.ask("clear the helper")).status).toBe("completed"); - expect(lastToolResults(refused.seen)).toContain("This organization hired no seat"); - expect(await pendingAsks(unmarked)).toEqual([]); - expect(await inventoryRows(unmarked)).toContain(HELPER_ADDRESS); - }); -}); - -describe("the approve crash promise", () => { - /** - * A view of `stores` that, once armed, never answers a roster write: the - * process dies at the moment the change would land. - */ - function dyingAtRosterWrite(stores: StoreRegistry) { - const state = { armed: false, held: 0 }; - const resourceState = new Proxy(stores.resourceState, { - get(target, prop, receiver) { - const value = Reflect.get(target, prop, receiver); - if (typeof value !== "function") return value; - return (...args: unknown[]) => { - const writes = prop === "set" || prop === "delete"; - if (state.armed && writes && typeof args[2] === "string" && args[2].startsWith(HIRED_ROSTER_PREFIX)) { - state.held += 1; - return new Promise(() => {}); - } - return value.apply(target, args); - }; - }, - }); - return { view: { ...stores, resourceState } as StoreRegistry, state }; - } - - it("dies between Approve and the fire, restarts, and fires exactly once", async () => { - const stores = freshStores(); - await withHelperHired(stores); - const { view, state } = dyingAtRosterWrite(stores); - const doomed = await boot(stores, [call("fire", { seatId: HELPER }), say("never reached")], { askBefore: ["fire"], view }); - const { requestId } = await doomed.ask("let the helper go"); - expect((await stores.request.get(requestId))?.status).toBe("suspended"); - - state.armed = true; - void (await doomed.answer(requestId, "approve")).finished; - for (let i = 0; i < 200 && state.held === 0; i++) await new Promise((r) => setTimeout(r, 5)); - expect(state.held).toBe(1); - // Approved, and nothing changed: the process died before the write landed. - expect(await rosterRows(stores)).toEqual([HELPER]); - expect(doomed.released).toEqual([]); - - const next = reopen(stores); - const restarted = await boot(next, [say("done")], { askBefore: ["fire"] }); - expect(restarted.registry.get(HELPER_ADDRESS)?.kind).toBe("agent"); - expect(await restarted.recover(requestId)).toBe("completed"); - - expect(await rosterRows(next)).toEqual([]); - expect(await inventoryRows(next)).not.toContain(HELPER_ADDRESS); - expect(restarted.released).toEqual([HELPER_ADDRESS]); - // No second ask was raised for the approved change. - expect(await pendingAsks(next)).toEqual([]); - }); - - it("dies after the fire landed and before the turn ended, restarts, and does not fire again", async () => { - const stores = freshStores(); - await withHelperHired(stores); - let died = false; - const doomed = await boot( - stores, - [ - call("fire", { seatId: HELPER }), - () => { - died = true; - return new Promise(() => {}) as never; - }, - ], - { askBefore: ["fire"] }, - ); - const { requestId } = await doomed.ask("let the helper go"); - void (await doomed.answer(requestId, "approve")).finished; - for (let i = 0; i < 200 && !died; i++) await new Promise((r) => setTimeout(r, 5)); - expect(died).toBe(true); - expect(await rosterRows(stores)).toEqual([]); - expect(doomed.released).toEqual([HELPER_ADDRESS]); - - const next = reopen(stores); - const restarted = await boot(next, [say("done")], { askBefore: ["fire"] }); - expect(await restarted.recover(requestId)).toBe("completed"); - expect(await rosterRows(next)).toEqual([]); - // The fire is not made a second time, and the model was handed its first result, not a refusal. - expect(restarted.released).toEqual([]); - expect(lastToolResults(restarted.seen)).toContain(HELPER_ADDRESS); - expect(lastToolResults(restarted.seen)).not.toContain("hired no seat"); - }); -}); - -describe("what asks, and where it can't", () => { - it("asks before a hire when the Lab lists hire, and Approve then hires (BR-15)", async () => { - const stores = freshStores(); - const lab = await boot(stores, [call("hire", { seatId: HELPER, flow: "agent" }), say("hired")], { askBefore: ["hire", "fire"] }); - const { requestId, status } = await lab.ask("we need a helper"); - expect(status).toBe("suspended"); - expect((await pendingAsks(stores))[0]?.data).toEqual({ verb: "hire", seatId: HELPER, kind: "agent", owner: null, incarnation: null }); - expect(await rosterRows(stores)).toEqual([]); - - await (await lab.answer(requestId, "approve")).finished; - expect(await rosterRows(stores)).toEqual([HELPER]); - expect(lab.registry.get(HELPER_ADDRESS)?.kind).toBe("agent"); - }); - - it("refuses a listed verb by name without durable execution, changing nothing (BR-16)", async () => { - const stores = freshStores(); - await withHelperHired(stores); - const lab = await boot(stores, [call("fire", { seatId: HELPER }), say("could not")], { askBefore: ["fire"], durable: false }); - expect((await lab.ask("let the helper go")).status).toBe("completed"); - expect(lastToolResults(lab.seen)).toContain(`\\"fire\\" waits for a person's approval here, and this app can't ask for one`); - expect(await rosterRows(stores)).toEqual([HELPER]); - expect(lab.released).toEqual([]); - }); - - it("asks before a re-hire even with askBefore empty (BR-18)", async () => { - const stores = freshStores(); - // A stored seat whose kind this app no longer carries. - await stores.resourceState.set( - "org", - ORG, - `${HIRED_ROSTER_PREFIX}${HELPER}`, - toHiredSeatRow({ seatId: HELPER, flow: "retired-kind", owningOrgId: ORG }) as never, - "any", - ); - const lab = await boot(stores, [call("rehire", { seatId: HELPER, flow: "agent" })], { askBefore: [], reloadProblems: 1 }); - expect((await lab.ask("put the helper back on the agent kind")).status).toBe("suspended"); - expect((await pendingAsks(stores))[0]?.data).toEqual({ verb: "rehire", seatId: HELPER, kind: "agent", owner: null, incarnation: null }); - }); - - it("asks nothing with askBefore omitted: a fire lands at once, as before the option", async () => { - const stores = freshStores(); - await withHelperHired(stores); - const lab = await boot(stores, [call("fire", { seatId: HELPER }), say("done")]); - expect((await lab.ask("let the helper go")).status).toBe("completed"); - expect(await pendingAsks(stores)).toEqual([]); - expect(await rosterRows(stores)).toEqual([]); - }); - - it("refuses an askBefore entry it does not know", () => { - expect(() => - createSeatHireCapability({ register: () => {}, unregister: () => true, askBefore: ["rehire" as never] }), - ).toThrow(/askBefore names "rehire"/); - }); -}); - -describe("an approved fire stays fenced to the approved row", () => { - /** - * A view of `stores` that, once armed, runs `meanwhile` right after the - * `at`-th load of the roster, as another request in the same - * process would between two awaits. The read still answers what it found. - */ - function interleavingAt(stores: StoreRegistry, at: number, meanwhile: () => Promise) { - const state = { armed: false, reads: 0, ran: false }; - const resourceState = new Proxy(stores.resourceState, { - get(target, prop, receiver) { - const value = Reflect.get(target, prop, receiver); - if (typeof value !== "function") return value; - return async (...args: unknown[]) => { - const result = await value.apply(target, args); - // The context loads the roster through one prefix read and serves - // the check and the removal from it. - if (state.armed && prop === "getByPrefix" && args[2] === HIRED_ROSTER_PREFIX) { - state.reads += 1; - if (state.reads === at && !state.ran) { - state.ran = true; - await meanwhile(); - } - } - return result; - }; - }, - }); - return { view: { ...stores, resourceState } as StoreRegistry, state }; - } - - it("leaves alone a replacement hired between the approval's check and the removal", async () => { - const stores = freshStores(); - await withHelperHired(stores); - const key = `${HIRED_ROSTER_PREFIX}${HELPER}`; - const original = (await stores.resourceState.get("org", ORG, key))!.state as Record; - // The replacement another request writes: fired and hired again under the same id. - const replacement = { ...original, incarnation: "replacement-incarnation", instructions: "The new helper." }; - const { view, state } = interleavingAt(stores, 1, async () => { - await stores.resourceState.set("org", ORG, key, replacement as never, "any"); - }); - const asked = await boot(stores, [call("fire", { seatId: HELPER }), say("done")], { askBefore: ["fire"], view }); - const { requestId } = await asked.ask("let the helper go"); - - state.armed = true; - const { finished } = await asked.answer(requestId, "approve"); - await finished; - expect(state.ran).toBe(true); - - // The replacement keeps its row, the address and its inventory row, and - // the model is told the seat changed, not handed a store error. - expect((await stores.resourceState.get("org", ORG, key))?.state).toEqual(replacement); - expect(await inventoryRows(stores)).toContain(HELPER_ADDRESS); - expect(asked.released).toEqual([]); - expect(lastToolResults(asked.seen)).toContain("changed while you were asked"); - }); -}); - -describe("an approved re-hire that dies part-way", () => { - /** A view of `stores` that, once armed, never answers an inventory write. */ - function dyingAtInventoryWrite(stores: StoreRegistry) { - const state = { armed: false, held: 0 }; - const resourceState = new Proxy(stores.resourceState, { - get(target, prop, receiver) { - const value = Reflect.get(target, prop, receiver); - if (typeof value !== "function") return value; - return (...args: unknown[]) => { - const writes = prop === "set" || prop === "delete"; - if (state.armed && writes && typeof args[2] === "string" && args[2].startsWith("inventory/seats/")) { - state.held += 1; - return new Promise(() => {}); - } - return value.apply(target, args); - }; - }, - }); - return { view: { ...stores, resourceState } as StoreRegistry, state }; - } - - it("finishes on recovery: the pending repair is this approval's own, so it completes rather than being refused", async () => { - const stores = freshStores(); - const key = `${HIRED_ROSTER_PREFIX}${HELPER}`; - await stores.resourceState.set( - "org", - ORG, - key, - { ...toHiredSeatRow({ seatId: HELPER, flow: "retired-kind", owningOrgId: ORG }), incarnation: "old-incarnation" } as never, - "any", - ); - const { view, state } = dyingAtInventoryWrite(stores); - const doomed = await boot(stores, [call("rehire", { seatId: HELPER, flow: "agent" }), say("never reached")], { - reloadProblems: 1, - view, - instanceAt: true, - }); - const { requestId } = await doomed.ask("put the helper back on the agent kind"); - expect((await stores.request.get(requestId))?.status).toBe("suspended"); - - // Approved; the process dies after the repair row is written, before the inventory row is. - state.armed = true; - void (await doomed.answer(requestId, "approve")).finished; - for (let i = 0; i < 200 && state.held === 0; i++) await new Promise((r) => setTimeout(r, 5)); - expect(state.held).toBe(1); - expect((await stores.resourceState.get("org", ORG, key))?.state).toMatchObject({ flow: "agent", pendingRepair: expect.any(String) }); - - const next = reopen(stores); - // The restart serves the repaired row; the recovery finishes the repair onto that seat. - const restarted = await boot(next, [say("done")], { instanceAt: true }); - expect(await restarted.recover(requestId)).toBe("completed"); - - expect(lastToolResults(restarted.seen)).not.toContain("changed while you were asked"); - expect((await next.resourceState.get("org", ORG, key))?.state).toMatchObject({ flow: "agent", pendingRepair: null }); - expect(await inventoryRows(next)).toContain(HELPER_ADDRESS); - expect(restarted.registry.get(HELPER_ADDRESS)?.kind).toBe("agent"); - }); -}); - -describe("a re-hire of a row whose stored owner disagrees with where it is stored", () => { - it("is refused before anyone is asked, and the row is left as it was", async () => { - const stores = freshStores(); - const key = `${HIRED_ROSTER_PREFIX}${HELPER}`; - // Stored under the org roster's key, but saying it belongs to one user. - const row = { - ...toHiredSeatRow({ seatId: HELPER, flow: "retired-kind", owningOrgId: ORG, ownerUserId: "u_someone" }), - incarnation: "old-incarnation", - }; - await stores.resourceState.set("org", ORG, key, row as never, "any"); - const asked = await boot(stores, [call("rehire", { seatId: HELPER, flow: "agent" }), say("done")], { reloadProblems: 1 }); - const { status } = await asked.ask("put the helper back on the agent kind"); - - expect(status).toBe("completed"); - expect(await pendingAsks(stores)).toEqual([]); - expect(lastToolResults(asked.seen)).toContain("u_someone"); - expect((await stores.resourceState.get("org", ORG, key))?.state).toEqual(row); - expect(await inventoryRows(stores)).not.toContain(HELPER_ADDRESS); - }); -}); diff --git a/packages/workforce/test/seat-hire-blocks.test.ts b/packages/workforce/test/seat-hire-blocks.test.ts deleted file mode 100644 index 67a4711f49..0000000000 --- a/packages/workforce/test/seat-hire-blocks.test.ts +++ /dev/null @@ -1,187 +0,0 @@ -/** - * Fences the unedited capability suite cannot see: the capability's tools are - * the handlers this factory returned, `create()` refuses a second hire when - * `kindAt` is omitted, and a thrown `register` deletes the roster row before - * inventory is written. - */ -import { describe, expect, it, vi } from "vitest"; -import { resolveActivePresets } from "@flow-state-dev/core/capability"; -import { executeBlock } from "@flow-state-dev/engine"; -import { createTestContext } from "@flow-state-dev/testing"; -import type { SeatHireCapabilityOptions } from "../src/seat-hire-blocks"; -import { defineHiredRosterCollection } from "../src/roster/collections"; -import { defineSeatInventoryCollection } from "../src/inventory/collections"; -import { seatAddress, splitSeatAddress } from "../src/roster/address"; -import { DEFAULT_ORG_ID } from "@flow-state-dev/core/types"; - -const captured = vi.hoisted(() => ({ - hire: undefined as unknown, - fire: undefined as unknown, - brokenSeats: undefined as unknown, - rehire: undefined as unknown, -})); - -vi.mock("../src/seat-hire-blocks", async () => { - const actual = await vi.importActual( - "../src/seat-hire-blocks", - ); - return { - ...actual, - buildSeatHire: (options: Parameters[0]) => { - const real = actual.buildSeatHire(options); - Object.assign(captured, real.blocks); - return real; - }, - }; -}); - -const { createSeatHireCapability, HIRED_ROSTER_RESOURCE, SEAT_INVENTORY_RESOURCE } = await import( - "../src/seat-hire-capability" -); - -function presetTools(cap: Parameters[0]): unknown[] { - return resolveActivePresets(cap).flatMap(({ preset }) => - Array.isArray(preset.tools) ? preset.tools : [], - ); -} - -async function hireAgainst( - register: SeatHireCapabilityOptions["register"] = () => {}, - orgId = "acme", -) { - const { createSeatHireBlocks } = await import("../src/seat-hire-blocks"); - const { hire } = createSeatHireBlocks({ - register, - unregister: () => true, - }); - const runtime = await createTestContext({ - orgId, - sessionId: "test-session", - declaredResources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection(), - }, - }); - return { hire, ctx: runtime.ctx }; -} - -async function listedIds(ctx: { resources: object }, key: string, field: string): Promise { - const resources = ctx.resources as Record< - string, - { list: () => Promise }>> } - >; - const rows = await resources[key]!.list(); - return rows - .map((row) => row.state?.[field]) - .filter((value): value is string => typeof value === "string"); -} - -describe("the capability mounts the factory's blocks", () => { - it("with askBefore omitted, puts that call's hire, fire and brokenSeats in the preset as they are", () => { - const cap = createSeatHireCapability({ - register: () => {}, - unregister: () => true, - }); - const tools = presetTools(cap) as Array<{ name: string }>; - expect(tools.map((tool) => tool.name)).toEqual(["hire", "fire", "brokenSeats", "rehire"]); - expect(tools[0]).toBe(captured.hire); - expect(tools[1]).toBe(captured.fire); - expect(tools[2]).toBe(captured.brokenSeats); - // rehire always asks, so the tool is never the bare block. - expect(tools[3]).not.toBe(captured.rehire); - }); - - it("wraps only the verbs askBefore names", () => { - const cap = createSeatHireCapability({ - register: () => {}, - unregister: () => true, - askBefore: ["fire"], - }); - const tools = presetTools(cap); - expect(tools[0]).toBe(captured.hire); - expect(tools[1]).not.toBe(captured.fire); - }); -}); - -describe("two hires of one id, kindAt omitted, leave one roster row", () => { - it("arriving in sequence: the second is refused by create() throwing", async () => { - const { hire, ctx } = await hireAgainst(); - - const first = await executeBlock({ - block: hire, - input: { seatId: "eng.ada", flow: "agent" }, - ctx, - }); - expect(first.error).toBeUndefined(); - - const second = await executeBlock({ - block: hire, - input: { seatId: "eng.ada", flow: "agent" }, - ctx, - }); - expect(second.error).toBeDefined(); - - expect(await listedIds(ctx, HIRED_ROSTER_RESOURCE, "seatId")).toEqual(["eng.ada"]); - }); - - it("arriving at once: exactly one succeeds, and one roster row is left", async () => { - const { hire, ctx } = await hireAgainst(); - - const [a, b] = await Promise.allSettled([ - executeBlock({ block: hire, input: { seatId: "eng.ada", flow: "agent" }, ctx }), - executeBlock({ block: hire, input: { seatId: "eng.ada", flow: "agent" }, ctx }), - ]); - - const errors = [a, b].filter( - (settled) => settled.status === "fulfilled" && settled.value.error !== undefined, - ); - expect(errors).toHaveLength(1); - expect(await listedIds(ctx, HIRED_ROSTER_RESOURCE, "seatId")).toEqual(["eng.ada"]); - }); -}); - -describe("register throwing leaves no roster row and no inventory row", () => { - it("cleans up the roster row it just wrote, and never reaches the inventory write", async () => { - const { hire, ctx } = await hireAgainst(() => { - throw new Error("registration refused"); - }); - - const result = await executeBlock({ - block: hire, - input: { seatId: "eng.ada", flow: "agent" }, - ctx, - }); - - expect(result.error?.message).toMatch(/registration refused/); - expect(await listedIds(ctx, HIRED_ROSTER_RESOURCE, "seatId")).toEqual([]); - expect(await listedIds(ctx, SEAT_INVENTORY_RESOURCE, "id")).toEqual([]); - }); -}); - -describe("an org id that is not a lowercase-hyphen segment can hire", () => { - // The framework's own default org, and the `org_…` ids auth providers hand - // out. Put the segment check back in `seatAddress` and every hire here is - // refused with "Organization id … must be lowercase letters". - for (const orgId of ["org_pentest_lab", DEFAULT_ORG_ID, "Org_2NfXq"]) { - it(`hires under "${orgId}", at an address that splits back to the seat id`, async () => { - const registered: string[] = []; - const { hire, ctx } = await hireAgainst((seat) => { - registered.push(seat.id); - }, orgId); - - const result = await executeBlock({ - block: hire, - input: { seatId: "helper", flow: "agent" }, - ctx, - }); - - expect(result.error).toBeUndefined(); - const address = (result.output as { address: string }).address; - expect(address).toBe(seatAddress(orgId, "helper")); - expect(registered).toEqual([address]); - expect(splitSeatAddress(orgId, address)).toBe("helper"); - expect(await listedIds(ctx, HIRED_ROSTER_RESOURCE, "seatId")).toEqual(["helper"]); - expect(await listedIds(ctx, SEAT_INVENTORY_RESOURCE, "id")).toEqual([address]); - }); - } -}); diff --git a/packages/workforce/test/seat-hire-capability.test.ts b/packages/workforce/test/seat-hire-capability.test.ts deleted file mode 100644 index f98e01b145..0000000000 --- a/packages/workforce/test/seat-hire-capability.test.ts +++ /dev/null @@ -1,440 +0,0 @@ -/** - * Seat-hire capability — hire and fire as catalog tools on the existing mint. - * - * Graded on what a seat can actually call and what Discover then lists, not - * on the factory's return type. Empty `tools:` staying empty is the fence - * (BR-1). Naming `hire` after the kind installed the capability is the grant - * (BR-2). A hire nobody can find is theater (BR-10). - */ -import { describe, expect, it } from "vitest"; -import { - createSeatHireCapability, - HIRED_ROSTER_RESOURCE, - SEAT_INVENTORY_RESOURCE, - registerHiredSeat, - type HiredSeatOwnerPin, -} from "../src/seat-hire-capability"; -import { createWorkforceCapability } from "../src/workforce-capability"; -import { workforceManifestSources } from "../src/manifest-sources"; -import { defineAgentWorkerFlow } from "../src/agent-worker-flow"; -import { hireWorkforce, type HireOptions } from "../src/hire"; -import { parseHiredSeatRow } from "../src/roster/rows"; -import type { WorkerManifest } from "../src/manifest"; -import type { FlowInstance } from "@flow-state-dev/core"; -import { executeBlock } from "@flow-state-dev/engine"; -import { createTestContext, mockGenerator } from "@flow-state-dev/testing"; - -function record(over: Partial & { id: string }): WorkerManifest { - return { declared: {}, body: "", ...over }; -} - -function liveRoster() { - const held = new Map(); - return { - register: (seat: FlowInstance) => { - if (held.has(seat.id)) { - throw new Error(`"${seat.id}" is already registered`); - } - held.set(seat.id, seat); - }, - unregister: (id: string) => held.delete(id), - kindAt: (id: string) => held.get(id)?.kind, - has: (id: string) => held.has(id), - }; -} - -type ToolCall = { toolCallId: string; toolName: string; args: Record }; - -async function runSeat( - seat: FlowInstance, - script: Array<{ toolCalls: ToolCall[] } | { text: string }>, - orgId = "acme", -) { - const runtime = await createTestContext({ - flow: { ...seat, cardinality: "singleton" }, - orgId, - org: { state: {} }, - sessionId: "test-session", - sequencerName: seat.actions.run!.block.name, - declaredResources: seat.actions.run!.block.declaredResources, - generators: { - "agent-answer": mockGenerator({ - name: "agent-answer", - script: script as never, - }), - }, - }); - const result = await executeBlock({ - block: seat.actions.run!.block, - input: { message: "run the named tools" }, - ctx: runtime.ctx, - }); - return { result, ctx: runtime.ctx }; -} - -function callTool(toolName: string, args: Record = {}, id = "call-1"): ToolCall { - return { toolCallId: id, toolName, args }; -} - -function collectionOf(ctx: { resources: Record Promise> }> }, key: string) { - return ctx.resources[key]; -} - -async function listedIds( - ctx: { resources: Record Promise }>> }> }, - key: string, - field: string, -): Promise { - const rows = await collectionOf(ctx, key).list(); - return rows - .map((row) => row.state?.[field]) - .filter((value): value is string => typeof value === "string"); -} - -function hireReturn(items: unknown[]): { seatId?: string; address?: string; warning?: string } | undefined { - const visit = (value: unknown): { seatId?: string; address?: string; warning?: string } | undefined => { - if (value === null || typeof value !== "object") return undefined; - const record = value as Record; - if (typeof record.seatId === "string" && typeof record.address === "string") { - return record as { seatId?: string; address?: string; warning?: string }; - } - for (const nested of Object.values(record)) { - const found = visit(nested); - if (found !== undefined) return found; - } - return undefined; - }; - for (const item of items) { - const found = visit(item); - if (found !== undefined) return found; - } - return undefined; -} - -async function discoverSeatIds(ctx: never, hiredRoster = HIRED_ROSTER_RESOURCE): Promise { - const [source] = workforceManifestSources({ - roster: { workers: [], mailboxes: [] }, - inventory: { seats: SEAT_INVENTORY_RESOURCE }, - hiredRoster, - }); - const entries = await source!.entries(ctx); - return entries.map((entry) => entry.id); -} - -function kindWithHire( - live: ReturnType, - over: Partial[0]> = {}, -) { - const kinds: NonNullable = {}; - const seatHire = createSeatHireCapability({ - workerFlows: kinds, - register: live.register, - unregister: live.unregister, - kindAt: live.kindAt, - ...over, - }); - kinds.agent = defineAgentWorkerFlow({ uses: [seatHire] }); - return { kinds, seatHire }; -} - -describe("the tools fence on seat-hire", () => { - it("BR-1 · a seat whose tools: is empty cannot call hire even when its kind installed the capability", async () => { - let hireCalls = 0; - const live = liveRoster(); - const { kinds } = kindWithHire(live, { - register: (seat) => { - hireCalls += 1; - live.register(seat); - }, - }); - - const [manager] = hireWorkforce( - [record({ id: "eng.manager", body: "Expands the roster." })], - { workerFlows: kinds }, - ); - - const { result } = await runSeat(manager!, [ - { toolCalls: [callTool("hire", { seatId: "eng.ada", flow: "agent", instructions: "You take support tickets." })] }, - { text: "done" }, - ]); - - expect(result.error).toBeUndefined(); - expect(hireCalls).toBe(0); - expect(live.has("acme.eng.ada")).toBe(false); - }); - - it("BR-2 · a seat that names hire in tools: mints, writes the roster, and returns { seatId, address }", async () => { - const live = liveRoster(); - const { kinds } = kindWithHire(live); - - const [manager] = hireWorkforce( - [record({ id: "eng.manager", declared: { tools: ["hire"] }, body: "Expands the roster." })], - { workerFlows: kinds }, - ); - - const { result, ctx } = await runSeat(manager!, [ - { - toolCalls: [ - callTool("hire", { - seatId: "eng.ada", - flow: "agent", - instructions: "You take support tickets.", - }), - ], - }, - { text: "done" }, - ]); - - expect(result.error).toBeUndefined(); - expect(live.has("acme.eng.ada")).toBe(true); - expect(live.kindAt("acme.eng.ada")).toBe("agent"); - expect(await listedIds(ctx, HIRED_ROSTER_RESOURCE, "seatId")).toEqual(["eng.ada"]); - expect(await listedIds(ctx, SEAT_INVENTORY_RESOURCE, "id")).toEqual(["acme.eng.ada"]); - - expect(hireReturn(result.items)).toMatchObject({ seatId: "eng.ada", address: "acme.eng.ada" }); - }); - - it("refuses a kind this app never registered, and writes nothing", async () => { - const live = liveRoster(); - const { kinds } = kindWithHire(live); - - const [manager] = hireWorkforce( - [record({ id: "eng.manager", declared: { tools: ["hire"] }, body: "Expands the roster." })], - { workerFlows: kinds }, - ); - - const { result, ctx } = await runSeat(manager!, [ - { toolCalls: [callTool("hire", { seatId: "eng.ada", flow: "invented-kind" })] }, - { text: "done" }, - ]); - - expect(result.error?.message).toMatch(/invented-kind/); - expect(live.has("acme.eng.ada")).toBe(false); - expect(await listedIds(ctx, HIRED_ROSTER_RESOURCE, "seatId")).toEqual([]); - expect(await listedIds(ctx, SEAT_INVENTORY_RESOURCE, "id")).toEqual([]); - }); - - it("refuses the same seat id twice", async () => { - const live = liveRoster(); - const { kinds } = kindWithHire(live); - - const [manager] = hireWorkforce( - [record({ id: "eng.manager", declared: { tools: ["hire"] }, body: "Expands the roster." })], - { workerFlows: kinds }, - ); - - const { result, ctx } = await runSeat(manager!, [ - { toolCalls: [callTool("hire", { seatId: "eng.ada", flow: "agent" }, "call-1")] }, - { toolCalls: [callTool("hire", { seatId: "eng.ada", flow: "agent" }, "call-2")] }, - { text: "done" }, - ]); - - expect(result.error?.message).toMatch(/already served/); - expect(live.has("acme.eng.ada")).toBe(true); - expect(await listedIds(ctx, HIRED_ROSTER_RESOURCE, "seatId")).toEqual(["eng.ada"]); - }); - - it("does not let a seat name hire when its kind never installed the capability", () => { - expect(() => - hireWorkforce( - [record({ id: "eng.manager", declared: { tools: ["hire"] }, body: "No grant." })], - { workerFlows: { agent: defineAgentWorkerFlow() } }, - ), - ).toThrow(/hire/); - }); - - it("ignores a caller-supplied orgId and writes the principal's roster", async () => { - const live = liveRoster(); - const { kinds } = kindWithHire(live); - - const [manager] = hireWorkforce( - [record({ id: "eng.manager", declared: { tools: ["hire"] }, body: "Expands the roster." })], - { workerFlows: kinds }, - ); - - const { ctx } = await runSeat(manager!, [ - { - toolCalls: [ - callTool("hire", { seatId: "eng.ada", flow: "agent", orgId: "other-org" }), - ], - }, - { text: "done" }, - ]); - - expect(live.has("acme.eng.ada")).toBe(true); - expect(live.has("other-org.eng.ada")).toBe(false); - expect(await listedIds(ctx, HIRED_ROSTER_RESOURCE, "seatId")).toEqual(["eng.ada"]); - expect(await listedIds(ctx, SEAT_INVENTORY_RESOURCE, "id")).toEqual(["acme.eng.ada"]); - const [stored] = await collectionOf(ctx as never, HIRED_ROSTER_RESOURCE).list(); - const parsed = parseHiredSeatRow(stored?.state); - if ("problem" in parsed) throw new Error(parsed.problem); - expect(parsed.row.owningOrgId).toBe("acme"); - expect(parsed.row.ownerUserId).toBeNull(); - }); -}); - -describe("fire", () => { - it("removes the roster row, releases the address, and removes the inventory row", async () => { - const live = liveRoster(); - const { kinds } = kindWithHire(live); - - const [manager] = hireWorkforce( - [record({ id: "eng.manager", declared: { tools: ["hire", "fire"] }, body: "Expands the roster." })], - { workerFlows: kinds }, - ); - - const { ctx } = await runSeat(manager!, [ - { toolCalls: [callTool("hire", { seatId: "eng.ada", flow: "agent" }, "h1")] }, - { toolCalls: [callTool("fire", { seatId: "eng.ada" }, "f1")] }, - { text: "done" }, - ]); - - expect(live.has("acme.eng.ada")).toBe(false); - expect(await listedIds(ctx, HIRED_ROSTER_RESOURCE, "seatId")).toEqual([]); - expect(await listedIds(ctx, SEAT_INVENTORY_RESOURCE, "id")).toEqual([]); - }); - - it("refuses to fire a seat that was declared in a worker file, not hired through this tool", async () => { - const live = liveRoster(); - const { kinds } = kindWithHire(live); - - const seats = hireWorkforce( - [ - record({ id: "eng.manager", declared: { tools: ["fire"] }, body: "Expands the roster." }), - record({ id: "acme.eng.file", body: "Declared on disk." }), - ], - { workerFlows: kinds }, - ); - const manager = seats.find((seat) => seat.id === "eng.manager"); - const fileSeat = seats.find((seat) => seat.id === "acme.eng.file"); - live.register(fileSeat!); - - const { result } = await runSeat(manager!, [ - { toolCalls: [callTool("fire", { seatId: "eng.file" })] }, - { text: "done" }, - ]); - - expect(live.has("acme.eng.file")).toBe(true); - expect(result.error?.message).toMatch(/worker file|folder/); - }); -}); - -describe("Discover sees a runtime hire", () => { - function kindThatCanHireAndDiscover(live: ReturnType) { - const kinds: NonNullable = {}; - const seatHire = createSeatHireCapability({ - workerFlows: kinds, - register: live.register, - unregister: live.unregister, - kindAt: live.kindAt, - }); - const workforce = createWorkforceCapability({ - roster: { workers: [], mailboxes: [] }, - inventory: { seats: SEAT_INVENTORY_RESOURCE }, - hiredRoster: HIRED_ROSTER_RESOURCE, - }); - kinds.agent = defineAgentWorkerFlow({ uses: [seatHire, workforce] }); - return kinds; - } - - it("BR-10 · hire then discover lists the new seat", async () => { - const live = liveRoster(); - const kinds = kindThatCanHireAndDiscover(live); - const [manager] = hireWorkforce( - [record({ id: "eng.manager", declared: { tools: ["hire"] }, body: "Expands the roster." })], - { workerFlows: kinds }, - ); - - const { result, ctx } = await runSeat(manager!, [ - { - toolCalls: [ - callTool("hire", { - seatId: "eng.ada", - flow: "agent", - instructions: "You take support tickets.", - }), - ], - }, - { text: "done" }, - ]); - - expect(result.error).toBeUndefined(); - expect(await discoverSeatIds(ctx as never)).toEqual(["acme.eng.ada"]); - }); - - it("fire removes the seat from Discover and from the inventory", async () => { - const live = liveRoster(); - const kinds = kindThatCanHireAndDiscover(live); - const [manager] = hireWorkforce( - [record({ id: "eng.manager", declared: { tools: ["hire", "fire"] }, body: "Expands the roster." })], - { workerFlows: kinds }, - ); - - const { ctx } = await runSeat(manager!, [ - { toolCalls: [callTool("hire", { seatId: "eng.ada", flow: "agent" }, "h1")] }, - { toolCalls: [callTool("fire", { seatId: "eng.ada" }, "f1")] }, - { text: "done" }, - ]); - - expect(await listedIds(ctx, HIRED_ROSTER_RESOURCE, "seatId")).toEqual([]); - expect(await listedIds(ctx, SEAT_INVENTORY_RESOURCE, "id")).toEqual([]); - expect(await discoverSeatIds(ctx as never)).toEqual([]); - }); -}); - -describe("FIX-1529 owner pin", () => { - it("refuses registering a hired seat without an owner pin from the hire row", async () => { - const calls: Array<{ id: string; pin: HiredSeatOwnerPin }> = []; - const seat = { id: "acme.eng.ada", kind: "agent" } as FlowInstance; - - expect(() => - registerHiredSeat((registered, pin) => { - calls.push({ id: registered.id, pin }); - }, seat, undefined), - ).toThrow(/owner pin/); - expect(calls).toEqual([]); - - const pins: HiredSeatOwnerPin[] = []; - const live = liveRoster(); - const { kinds } = kindWithHire(live, { - register: (hired, pin) => { - pins.push(pin); - live.register(hired); - }, - }); - const [manager] = hireWorkforce( - [record({ id: "eng.manager", declared: { tools: ["hire"] }, body: "Expands the roster." })], - { workerFlows: kinds }, - ); - const { result } = await runSeat(manager!, [ - { toolCalls: [callTool("hire", { seatId: "eng.ada", flow: "agent" })] }, - { text: "done" }, - ]); - - expect(result.error).toBeUndefined(); - expect(pins).toEqual([{ orgId: "acme" }]); - expect(pins[0]?.orgId).not.toBe("eng"); - }); -}); - -describe("unattended boards stay a warning", () => { - it("hires without attaching a board and names the unattended ledger", async () => { - const live = liveRoster(); - const { kinds } = kindWithHire(live, { mailboxBoards: ["eng.standup.triage"] }); - - const [manager] = hireWorkforce( - [record({ id: "eng.manager", declared: { tools: ["hire"] }, body: "Expands the roster." })], - { workerFlows: kinds }, - ); - - const { result } = await runSeat(manager!, [ - { toolCalls: [callTool("hire", { seatId: "eng.ada", flow: "agent" })] }, - { text: "done" }, - ]); - - const payload = hireReturn(result.items); - expect(payload?.address).toBe("acme.eng.ada"); - expect(payload?.warning).toMatch(/eng\.standup/); - expect(payload?.warning).toMatch(/triage/); - }); -}); diff --git a/packages/workforce/test/seat-hire-interleaving.test.ts b/packages/workforce/test/seat-hire-interleaving.test.ts deleted file mode 100644 index c985e1c564..0000000000 --- a/packages/workforce/test/seat-hire-interleaving.test.ts +++ /dev/null @@ -1,545 +0,0 @@ -/** - * Hire, fire and rehire, interleaved at every store call. - * - * One operation (the primary) runs while a store wrapper stops it before each - * of its store calls in turn; at the chosen stops a competing operation (a - * fire, a replacement hire) runs to completion, then the primary carries on. - * Every combination of stops is run. Whatever the order, the end state has to - * agree with itself: the roster row, the seat registered at the address and - * the seat's inventory row all carry the same incarnation, or are absent, and - * a declared seat's row is never touched. - * - * One state is allowed by name, because no read the engine offers a block - * can rule it out: a fire whose two collection snapshots were taken on either - * side of a hire's publish deletes that hire's roster row and seat but can't - * see its inventory row. What is left is an inventory row whose roster row is - * gone and whose seat isn't registered. That is accepted only if the team list - * leaves it out and the next fire of the seat removes it; anything else fails. - */ -import { describe, expect, it } from "vitest"; -import { z } from "zod"; -import { defineFlow, handler } from "@flow-state-dev/core"; -import type { FlowInstance } from "@flow-state-dev/core/types"; -import { createFlowState, FlowIdentityConflictError, inMemoryStores, runAction } from "@flow-state-dev/engine"; -import { createSeatHireBlocks, HIRED_ROSTER_RESOURCE, SEAT_INVENTORY_RESOURCE } from "../src/seat-hire-blocks"; -import type { SeatHireCapabilityOptions } from "../src/seat-hire-blocks"; -import { defineHiredRosterCollection } from "../src/roster/collections"; -import { defineSeatInventoryCollection } from "../src/inventory/collections"; -import { INVENTORY_REGISTER_SEATS, inventoryWriterActions } from "../src/mailbox/mailbox-flow"; -import { incarnationOf } from "../src/roster/incarnation"; -import { listedSeatRows } from "../src/inventory/listed-seats"; -import { toHiredSeatRow } from "../src/roster/rows"; -import { workerConfigSchema } from "../src/worker-config"; -import { workerDoor } from "./worker-door"; - -const ROSTER = "workforce/roster/"; -const SEATS = "inventory/seats/"; - -const noop = handler({ - name: "noop", - inputSchema: z.object({}), - outputSchema: z.object({}), - execute: () => ({}), -}); - -const desk = defineFlow({ - kind: "desk", - cardinality: "collection", - configSchema: workerConfigSchema().extend({ queue: z.string() }), - actions: { ...workerDoor, run: { inputSchema: z.object({}), block: noop } }, -}); - -type Rows = (prefix: string) => Promise>>; -/** - * `input` may be read from the world just before the operation runs (a boot - * carries the roster as it read it), and never during an interleaving. - */ -type Op = { - action: "hire" | "fire" | "rehire" | "boot"; - input: Record | ((rows: Rows) => Promise>); - label: string; -}; -type Outcome = { label: string; error?: string }; - -/** - * One app, one store, a live registry, and a store wrapper that can stop the - * primary. `lazyInventory` loads the seat inventory on first read instead of - * at action start, so a read of it is a store call a competitor can precede. - */ -async function world(options: { lazyInventory?: boolean } = {}) { - const held = new Map(); - const blocks = createSeatHireBlocks({ - workerFlows: { desk }, - register: (seat: FlowInstance) => { - const existing = held.get(seat.id); - if (existing !== undefined) { - throw new FlowIdentityConflictError({ reason: "duplicate-id", kind: seat.kind, id: seat.id, existingKind: existing.kind }); - } - held.set(seat.id, seat); - }, - unregister: (id: string) => held.delete(id), - kindAt: (id: string) => held.get(id)?.kind, - instanceAt: (id: string) => held.get(id), - } as SeatHireCapabilityOptions); - const ops = defineFlow({ - kind: "ops", - resources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: options.lazyInventory - ? { ...defineSeatInventoryCollection(), prefetchMode: "lazy" } - : defineSeatInventoryCollection(), - }, - actions: { - hire: { block: blocks.hire }, - fire: { block: blocks.fire }, - rehire: { block: blocks.rehire }, - }, - } as never)(); - // The inventory write `openInventory` runs at boot, with the seats the boot - // read, on the mailbox kind that carries it. - const booter = defineFlow({ - kind: "booter", - actions: { boot: inventoryWriterActions("booter")[INVENTORY_REGISTER_SEATS] }, - } as never)(); - const state = createFlowState({ flows: { ops: ops as never }, stores: { default: { primary: inMemoryStores() } } }); - const runtime = await state.getRuntime(); - const stores = runtime.stores; - - // The stop: before each store call the primary makes, run whatever is due. - let primaryRunning = false; - let inCompetitor = false; - let calls = 0; - let due: Array<{ at: number; run: () => Promise }> = []; - const store = stores.resourceState as unknown as Record Promise>; - for (const name of ["get", "set", "delete", "getAll", "getByPrefix"]) { - const real = store[name]!.bind(store); - store[name] = async (...args: unknown[]) => { - if (primaryRunning && !inCompetitor) { - while (due.length > 0 && due[0]!.at <= calls) { - const next = due.shift()!; - inCompetitor = true; - try { - await next.run(); - } finally { - inCompetitor = false; - } - } - calls += 1; - } - return real(...args); - }; - } - - let n = 0; - const run = async (op: Op): Promise => { - n += 1; - const result = (await runAction({ - flow: op.action === "boot" ? booter : ops, - actionName: op.action, - input: typeof op.input === "function" ? await op.input(rows) : op.input, - userId: "u1", - orgId: "acme", - sessionId: `s-${n}`, - stores, - runtimeConfig: { ...runtime.runtimeConfig }, - } as never)) as { error?: { message: string } }; - return { label: op.label, error: result.error?.message }; - }; - - /** - * Run `primary`, running `competitors[i]` before the primary's store call - * number `stops[i]` (a stop past its last call runs after it finishes). - * Returns every outcome and how many store calls the primary made. - */ - const interleave = async (primary: Op, competitors: Op[], stops: number[]) => { - const outcomes: Outcome[] = []; - due = competitors.map((op, i) => ({ at: stops[i]!, run: async () => void outcomes.push(await run(op)) })); - const resolved: Op = typeof primary.input === "function" ? { ...primary, input: await primary.input(rows) } : primary; - calls = 0; - primaryRunning = true; - const own = await run(resolved).finally(() => { - primaryRunning = false; - }); - for (const rest of due.splice(0)) await rest.run(); - return { outcomes: [own, ...outcomes], calls }; - }; - - async function rows(prefix: string): Promise>> { - return Object.fromEntries( - Object.entries(await stores.resourceState.getByPrefix("org", "acme", prefix)).map(([key, value]) => [ - key.slice(prefix.length), - (value as { state: Record }).state, - ]), - ); - } - const seed = (key: string, value: Record) => - stores.resourceState.set("org", "acme", key, value as never, "any" as never); - - return { held, run, interleave, rows, seed }; -} - -type World = Awaited>; - -/** - * The end state agrees with itself at `seatId`'s address: a registered seat - * was minted from the roster row there, a hired inventory row carries that - * row's incarnation, a roster row with an incarnation is served and listed, - * and `untouched` rows are exactly as seeded. - */ -async function expectConsistent( - w: World, - seatId: string, - untouched: Record>, - story: string -): Promise { - const address = `acme.${seatId}`; - const roster = (await w.rows(ROSTER))[seatId]; - const inventory = (await w.rows(SEATS))[address]; - const live = w.held.get(address); - const rowIncarnation = (roster?.incarnation ?? null) as string | null; - const facts = JSON.stringify({ roster, inventory, live: live === undefined ? null : { kind: live.kind, incarnation: incarnationOf(live) } }); - - if (live !== undefined) { - expect(roster, `${story}: a seat is registered with no roster row — ${facts}`).toBeDefined(); - expect(incarnationOf(live), `${story}: the registered seat is another incarnation's — ${facts}`).toBe(rowIncarnation); - } - if (inventory !== undefined && typeof inventory.incarnation === "string" && roster === undefined && live === undefined) { - // The named window: hidden from the team list, and the next fire removes it. - expect(listedSeatRows("acme", [inventory as { id: string; hired: boolean }], []), `${story}: a stale row is listed — ${facts}`).toEqual([]); - expect((await w.run({ action: "fire", input: { seatId }, label: "next fire" })).error, `${story}: the next fire failed — ${facts}`).toBeUndefined(); - expect((await w.rows(SEATS))[address], `${story}: the next fire left the stale row — ${facts}`).toBeUndefined(); - return true; - } - if (inventory !== undefined && typeof inventory.incarnation === "string") { - expect(rowIncarnation, `${story}: the inventory row is another incarnation's — ${facts}`).toBe(inventory.incarnation); - } - if (rowIncarnation !== null) { - expect(live, `${story}: a roster row's seat isn't registered — ${facts}`).toBeDefined(); - expect(inventory?.incarnation, `${story}: a roster row's seat has no inventory row — ${facts}`).toBe(rowIncarnation); - } - for (const [key, value] of Object.entries(untouched)) { - const now = key.startsWith(SEATS) ? (await w.rows(SEATS))[key.slice(SEATS.length)] : (await w.rows(ROSTER))[key.slice(ROSTER.length)]; - if (now !== undefined) expect(now, `${story}: ${key} was written over — ${facts}`).toEqual(value); - } - return false; -} - -/** Every way to place `count` competitors, in order, before the primary's calls 0..calls. */ -function placements(count: number, calls: number): number[][] { - if (count === 0) return [[]]; - const out: number[][] = []; - const place = (from: number, left: number, acc: number[]) => { - if (left === 0) return void out.push(acc); - for (let at = from; at <= calls; at += 1) place(at, left - 1, [...acc, at]); - }; - place(0, count, []); - return out; -} - -/** - * Run one scenario at every placement of its competitors and check each end - * state. `setup` seeds a fresh world; the primary's call count comes from a - * run with no competitors. - */ -async function everyInterleaving( - scenario: string, - setup: (w: World) => Promise>>, - primary: Op, - competitors: Op[], - seatId: string, - options: { lazyInventory?: boolean } = {} -) { - const dry = await world(options); - await setup(dry); - const { calls } = await dry.interleave(primary, [], []); - expect(calls).toBeGreaterThan(0); - const runs = placements(competitors.length, calls); - const windows: string[] = []; - for (const stops of runs) { - const w = await world(options); - const untouched = await setup(w); - const { outcomes } = await w.interleave(primary, competitors, stops); - const story = `${scenario}, stops ${JSON.stringify(stops)}: ${outcomes.map((o) => `${o.label} ${o.error === undefined ? "ok" : `refused (${o.error.slice(0, 60)})`}`).join("; ")}`; - if (await expectConsistent(w, seatId, untouched, story)) windows.push(story); - } - return { runs: runs.length, windows }; -} - -const hireAda = (queue: string, label: string): Op => ({ action: "hire", input: { seatId: "support.ada", flow: "desk", settings: { queue } }, label }); -const fireAda: Op = { action: "fire", input: { seatId: "support.ada" }, label: "fire" }; - -describe("hire, fire and rehire interleaved at every store call", () => { - it("a hire, with a fire and then a replacement hire landing at any two of its store calls", async () => { - const { runs, windows } = await everyInterleaving("hire | fire, replacement hire", async () => ({}), hireAda("first", "hire"), [fireAda, hireAda("second", "replacement")], "support.ada"); - expect(runs).toBeGreaterThan(10); - // The named window is never reached here: every end state is fully consistent. - expect(windows).toEqual([]); - }, 120_000); - - it("a fire, with a replacement hire landing at any of its store calls", async () => { - const { runs, windows } = await everyInterleaving( - "fire | replacement hire", - async (w) => { - expect((await w.run(hireAda("first", "setup"))).error).toBeUndefined(); - return {}; - }, - fireAda, - [hireAda("second", "replacement")], - "support.ada" - ); - expect(runs).toBeGreaterThan(3); - // The named window is never reached here: every end state is fully consistent. - expect(windows).toEqual([]); - }, 120_000); - - it("a re-hire of a seat whose kind was cut, with a fire and then a replacement hire landing at any two of its store calls", async () => { - const { runs, windows } = await everyInterleaving( - "rehire | fire, replacement hire", - async (w) => { - await w.seed(`${ROSTER}support.joe`, toHiredSeatRow({ seatId: "support.joe", flow: "desk-clerk", owningOrgId: "acme" }) as never); - await w.seed(`${SEATS}acme.support.joe`, { id: "acme.support.joe", kind: "desk-clerk", door: "run", hired: true, incarnation: null }); - return {}; - }, - { action: "rehire", input: { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }, label: "rehire" }, - [ - { action: "fire", input: { seatId: "support.joe" }, label: "fire" }, - { action: "hire", input: { seatId: "support.joe", flow: "desk", settings: { queue: "second" } }, label: "replacement" }, - ], - "support.joe" - ); - expect(runs).toBeGreaterThan(10); - // The named window is never reached here: every end state is fully consistent. - expect(windows).toEqual([]); - }, 120_000); - - it("a fire's retry with no roster row left (only its leftover inventory row), with a replacement hire landing at any of its store calls", async () => { - // What a fire that stopped between its two deletes leaves: no roster row, - // nothing registered, and the old hire's inventory row. - const { runs, windows } = await everyInterleaving( - "fire retry | replacement hire", - async (w) => { - await w.seed(`${SEATS}acme.support.ada`, { id: "acme.support.ada", kind: "desk", door: "run", hired: true, incarnation: "i-fired" }); - return {}; - }, - fireAda, - [hireAda("second", "replacement")], - "support.ada" - ); - expect(runs).toBeGreaterThan(2); - // The leftover path itself never reaches the named window; only the - // placement where the replacement finishes before fire reads anything, - // so fire takes the roster path, can. - expect(windows.every((story) => story.includes("stops [0]"))).toBe(true); - }, 120_000); - - it("the same, with the inventory read when fire first asks for it rather than at action start", async () => { - // The read is then a store call after fire saw no roster row, so a - // replacement hire can finish in between and its row be the one read. - const { runs, windows } = await everyInterleaving( - "fire retry (lazy inventory) | replacement hire", - async (w) => { - await w.seed(`${SEATS}acme.support.ada`, { id: "acme.support.ada", kind: "desk", door: "run", hired: true, incarnation: "i-fired" }); - return {}; - }, - fireAda, - [hireAda("second", "replacement")], - "support.ada", - { lazyInventory: true } - ); - expect(runs).toBeGreaterThan(2); - expect(windows.every((story) => story.includes("stops [0]"))).toBe(true); - }, 120_000); - - it("fire of a row from before incarnations, with a declared seat's row at the same address: the declared row is never touched", async () => { - // A team named like the organization declares `acme.support.ada`; a - // roster row from before incarnations names the same address. - const declared = { id: "acme.support.ada", kind: "desk", door: "run", hired: false, incarnation: null }; - const { runs, windows } = await everyInterleaving( - "fire (legacy row) | replacement hire", - async (w) => { - await w.seed(`${ROSTER}support.ada`, toHiredSeatRow({ seatId: "support.ada", flow: "desk", settings: { queue: "q" }, owningOrgId: "acme" }) as never); - await w.seed(`${SEATS}acme.support.ada`, declared); - return { [`${SEATS}acme.support.ada`]: declared }; - }, - fireAda, - [hireAda("second", "replacement")], - "support.ada" - ); - expect(runs).toBeGreaterThan(3); - // The named window is never reached here: every end state is fully consistent. - expect(windows).toEqual([]); - // And on its own: fire removes the roster row and leaves the declared row. - const w = await world(); - await w.seed(`${ROSTER}support.ada`, toHiredSeatRow({ seatId: "support.ada", flow: "desk", settings: { queue: "q" }, owningOrgId: "acme" }) as never); - await w.seed(`${SEATS}acme.support.ada`, declared); - expect((await w.run(fireAda)).error).toBeUndefined(); - expect(await w.rows(ROSTER)).toEqual({}); - expect((await w.rows(SEATS))["acme.support.ada"]).toEqual(declared); - }, 120_000); - - it("a boot carrying the roster it read before a fire and a replacement hire, with those landing at any two of its store calls", async () => { - // Another process booted and read the roster while the first hire was - // current; the fire and the replacement hire land around its inventory - // write. The replacement's row must survive the boot's stale one. - const { runs, windows } = await everyInterleaving( - "boot (stale roster) | fire, replacement hire", - async (w) => { - expect((await w.run(hireAda("first", "setup"))).error).toBeUndefined(); - return {}; - }, - { - action: "boot", - input: async (rows) => ({ - seats: [{ id: "acme.support.ada", kind: "desk", door: "run", hired: true, incarnation: (await rows(ROSTER))["support.ada"]!.incarnation }], - }), - label: "boot", - }, - [fireAda, hireAda("second", "replacement")], - "support.ada" - ); - expect(runs).toBeGreaterThan(2); - // The named window is never reached here: a row the fire removed after - // the boot read it is not written back. - expect(windows).toEqual([]); - }, 120_000); - - it("a boot carrying a declared seat at an address, with a runtime hire of that address landing at any of its store calls", async () => { - // A rolling deploy: the old process read a declaration the new one has - // dropped, and the new one hired the same address. The boot's declared - // row must not replace the hire's. - const { runs, windows } = await everyInterleaving( - "boot (stale declared row) | hire", - async () => ({}), - { - action: "boot", - input: { seats: [{ id: "acme.support.ada", kind: "desk", door: "run", hired: false, incarnation: null }] }, - label: "boot", - }, - [hireAda("first", "hire")], - "support.ada" - ); - expect(runs).toBeGreaterThan(1); - // The named window is never reached here: every end state is fully consistent. - expect(windows).toEqual([]); - }, 120_000); - - it("a hire, with a boot carrying a stale declared seat at its address landing at any of its store calls", async () => { - // The other side of the same race: the boot read no row and creates its - // declared one while the hire is between its checks and its publish. The - // hire can't write over a declared row, so it has to take back what it - // did, not stay serving with no row of its own. - const declared = { id: "acme.support.ada", kind: "desk", door: "run", hired: false, incarnation: null }; - const { runs, windows } = await everyInterleaving( - "hire | boot (stale declared row)", - async () => ({}), - hireAda("first", "hire"), - [{ action: "boot", input: { seats: [declared] }, label: "boot" }], - "support.ada" - ); - expect(runs).toBeGreaterThan(2); - // The named window is never reached here: every end state is fully consistent. - expect(windows).toEqual([]); - }, 120_000); - - it("a re-hire, with a boot carrying a stale declared seat at its address landing at any of its store calls", async () => { - // The seat's old inventory row is gone (a pre-field fire left none), so - // the boot reads no row and creates its declared one mid re-hire. - const declared = { id: "acme.support.joe", kind: "desk", door: "run", hired: false, incarnation: null }; - const legacy = toHiredSeatRow({ seatId: "support.joe", flow: "desk-clerk", owningOrgId: "acme" }); - const { runs, windows } = await everyInterleaving( - "rehire | boot (stale declared row)", - async (w) => { - await w.seed(`${ROSTER}support.joe`, legacy as never); - return {}; - }, - { action: "rehire", input: { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }, label: "rehire" }, - [{ action: "boot", input: { seats: [declared] }, label: "boot" }], - "support.joe" - ); - expect(runs).toBeGreaterThan(2); - // The named window is never reached here: every end state is fully consistent. - expect(windows).toEqual([]); - }, 120_000); -}); - -/** - * Two crashes in a row leave a hired seat's address with an inventory row - * from a hire the roster no longer has: a fire of A stopped after deleting - * A's roster row and before deleting A's inventory row, then the replacement - * hire B stopped after writing its roster row and before publishing its - * inventory row. Every boot after that reloads B. Its row has to land, or B - * is never listed (the team list wants the roster's incarnation on the - * inventory row) however many times the app restarts. - */ -describe("a boot over the row a fire left behind", () => { - const staleA = { id: "acme.support.ada", kind: "desk", door: "run", hired: true, incarnation: "i-A" }; - const rosterRow = (incarnation: string) => - toHiredSeatRow({ seatId: "support.ada", flow: "desk", settings: { queue: "q" }, owningOrgId: "acme", incarnation }); - const boot = (incarnation: string, label = "boot"): Op => ({ - action: "boot", - input: { seats: [{ id: "acme.support.ada", kind: "desk", door: "run", hired: true, incarnation }] }, - label, - }); - - it("replaces it with the hire the roster holds, so that hire is listed", async () => { - const w = await world(); - await w.seed(`${ROSTER}support.ada`, rosterRow("i-B") as never); - await w.seed(`${SEATS}acme.support.ada`, staleA); - - for (const label of ["first boot", "second boot"]) { - expect((await w.run(boot("i-B", label))).error).toBeUndefined(); - const row = (await w.rows(SEATS))["acme.support.ada"]; - expect(row, label).toMatchObject({ hired: true, incarnation: "i-B" }); - expect( - listedSeatRows("acme", [row as { id: string; hired: boolean; incarnation: string }], [{ seatId: "support.ada", incarnation: "i-B" }]), - label - ).toHaveLength(1); - } - }); - - it("leaves it to a later hire: a boot carrying a hire the roster no longer holds writes nothing", async () => { - // The roster has moved on to C, which has not published yet. A boot that - // read B before that must not put B's row there. - const w = await world(); - await w.seed(`${ROSTER}support.ada`, rosterRow("i-C") as never); - await w.seed(`${SEATS}acme.support.ada`, staleA); - - expect((await w.run(boot("i-B"))).error).toBeUndefined(); - expect((await w.rows(SEATS))["acme.support.ada"]).toEqual(staleA); - }); - - it("never replaces a newer hire's published row", async () => { - const w = await world(); - const published = { ...staleA, incarnation: "i-C" }; - await w.seed(`${ROSTER}support.ada`, rosterRow("i-C") as never); - await w.seed(`${SEATS}acme.support.ada`, published); - - expect((await w.run(boot("i-B"))).error).toBeUndefined(); - expect((await w.rows(SEATS))["acme.support.ada"]).toEqual(published); - }); - - it("with a fire and a replacement hire landing at any two of its store calls", async () => { - const { runs, windows } = await everyInterleaving( - "boot (roster's hire, stale row) | fire, replacement hire", - async (w) => { - expect((await w.run(hireAda("first", "setup"))).error).toBeUndefined(); - // Then the two crashes: the first hire's inventory row is replaced by - // a fired hire's leftover, which is what the boot finds. - await w.seed(`${SEATS}acme.support.ada`, staleA); - return {}; - }, - { - action: "boot", - input: async (rows) => ({ - seats: [{ id: "acme.support.ada", kind: "desk", door: "run", hired: true, incarnation: (await rows(ROSTER))["support.ada"]!.incarnation }], - }), - label: "boot", - }, - [fireAda, hireAda("second", "replacement")], - "support.ada" - ); - expect(runs).toBeGreaterThan(2); - expect(windows).toEqual([]); - }, 120_000); -}); - diff --git a/packages/workforce/test/seat-id.test.ts b/packages/workforce/test/seat-id.test.ts deleted file mode 100644 index c58848bdf7..0000000000 --- a/packages/workforce/test/seat-id.test.ts +++ /dev/null @@ -1,286 +0,0 @@ -/** - * `seatId` — every hired seat knows its own id. - * - * A block inside a seat cannot see which seat it runs in: core keeps the flow's - * id off the block context. The seat's settings are the one per-seat fact a - * block can read, and only the hire step writes them, so the hire step stamps - * the record's id there, on every record, from every mint path. - * - * Why it matters: a seat that files onto a board or posts to a mailbox signs - * with this value. A seat hired without it would file unattributed; a record - * that could author it could sign as any other seat. - */ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { describe, expect, it } from "vitest"; -import { z } from "zod"; -import { defineFlow, handler } from "@flow-state-dev/core"; -import type { FlowInstance } from "@flow-state-dev/core/types"; -import { DEFAULT_ORG_ID } from "@flow-state-dev/core"; -import { createFlowState, executeBlock, inMemoryStores, runAction } from "@flow-state-dev/engine"; -import type { StoreRegistry } from "@flow-state-dev/engine"; -import { createTestContext } from "@flow-state-dev/testing"; -import { mailboxInstances, openMailboxes, type MailboxManifest } from "../src/index"; -import { hireWorkforce } from "../src/hire"; -import { readWorkforceDirectory } from "../src/loader/read-workforce-directory"; -import type { WorkerManifest } from "../src/manifest"; -import { SEAT_ID_KEY } from "../src/manifest"; -import { reloadHiredSeats } from "../src/roster"; -import { defineHiredRosterCollection } from "../src/roster/collections"; -import { defineSeatInventoryCollection } from "../src/inventory/collections"; -import { createSeatHireBlocks } from "../src/seat-hire-blocks"; -import { HIRED_ROSTER_RESOURCE, SEAT_INVENTORY_RESOURCE } from "../src/seat-hire-capability"; -import { workerConfigSchema } from "../src/worker-config"; -import { postedLines } from "./mailbox-post-lines"; -import { workerDoor } from "./worker-door"; - -const inputSchema = z.object({ note: z.string() }); -const work = handler({ - name: "clerk-work", - inputSchema, - outputSchema: inputSchema, - execute: (input) => input, -}); - -const deskClerk = defineFlow({ - kind: "desk-clerk", - cardinality: "collection", - configSchema: workerConfigSchema().extend({ desk: z.string().default("front") }), - actions: { ...workerDoor, answer: { inputSchema, block: work } }, -}); -const kinds = { "desk-clerk": deskClerk }; - -function record(id: string, declared: Record = {}): WorkerManifest { - return { id, declared: { flow: "desk-clerk", ...declared }, body: "" }; -} - -function refusalOf(manifests: WorkerManifest[]): string { - try { - hireWorkforce(manifests, { workerFlows: kinds }); - } catch (error) { - return error instanceof Error ? error.message : String(error); - } - throw new Error("expected a refusal"); -} - -describe("every hired seat carries its own id as `seatId`", () => { - it("is the contract key, spelled once", () => { - expect(SEAT_ID_KEY).toBe("seatId"); - expect(Object.keys(workerConfigSchema().shape)).toContain(SEAT_ID_KEY); - }); - - it("from files: each seat's `seatId` is its own record id, not a sibling's", () => { - const seats = hireWorkforce([record("support.ada"), record("support.grace")], { workerFlows: kinds }); - expect(seats.map((seat) => [seat.id, seat.config[SEAT_ID_KEY]])).toEqual([ - ["support.ada", "support.ada"], - ["support.grace", "support.grace"], - ]); - }); - - it("from the runtime `hire` tool: the seat it registers carries its record id", async () => { - const registered: FlowInstance[] = []; - const { hire } = createSeatHireBlocks({ - workerFlows: kinds, - register: (seat) => { - registered.push(seat); - }, - unregister: () => true, - }); - const { ctx } = await createTestContext({ - orgId: "acme", - sessionId: "test-session", - declaredResources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection(), - }, - }); - - const result = await executeBlock({ - block: hire, - input: { seatId: "support.otto", flow: "desk-clerk" }, - ctx, - }); - expect(result.error).toBeUndefined(); - // Registered at its org-qualified address, signing with the id a - // mailbox's `members:` lists. - expect(registered.map((seat) => [seat.id, seat.config[SEAT_ID_KEY]])).toEqual([ - ["acme.support.otto", "support.otto"], - ]); - }); - - it("from the boot reload: a stored row written before the key existed still gets it", async () => { - const stores = { - resourceState: { - async getByPrefix() { - return { - "workforce/roster/support.ada": { - state: { seatId: "support.ada", flow: "desk-clerk", settings: { desk: "front" } }, - }, - }; - }, - }, - }; - const { seats, problems } = await reloadHiredSeats({ stores, orgIds: ["acme"], workerFlows: kinds }); - expect(problems).toEqual([]); - expect(seats.map((seat) => [seat.id, seat.config[SEAT_ID_KEY]])).toEqual([ - ["acme.support.ada", "support.ada"], - ]); - }); -}); - -/** `openMailboxes`'s session API over a test's own stores. */ -function sessionApi(stores: StoreRegistry) { - return { - createSession: async (options: { flowKind: string; userId: string; sessionId?: string; orgId?: string; state?: Record }) => { - const id = String(options.sessionId); - const now = Date.now(); - await stores.session.set( - id, - { - id, - flowKind: options.flowKind, - flowId: options.flowKind, - userId: options.userId, - orgId: options.orgId ?? DEFAULT_ORG_ID, - 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) => { - await stores.session.delete(sessionId); - }, - }; -} - -describe("a runtime-hired seat signs as the member its mailbox lists", () => { - /** - * The reason the key exists: a mailbox checks an author against its - * `members:`, which name seats by their logical id. A runtime-hired seat is - * registered at its org-qualified address, and a `seatId` taken from that - * address would be refused as `author-not-a-member`. - */ - it("posts to a mailbox that lists it, signed with its `seatId`", async () => { - const registered: FlowInstance[] = []; - const { hire } = createSeatHireBlocks({ - workerFlows: kinds, - register: (seat) => { - registered.push(seat); - }, - unregister: () => true, - }); - const { ctx } = await createTestContext({ - orgId: "acme", - sessionId: "test-session", - declaredResources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection(), - }, - }); - const hired = await executeBlock({ block: hire, input: { seatId: "support.otto", flow: "desk-clerk" }, ctx }); - expect(hired.error).toBeUndefined(); - const author = registered[0]!.config[SEAT_ID_KEY]; - - const roster: MailboxManifest[] = [ - { id: "support.desk", declared: { members: ["support.ada", "support.otto"] }, body: "Charter." }, - ]; - const [mailbox] = mailboxInstances(roster); - const state = createFlowState({ - flows: { [mailbox!.kind]: mailbox! }, - stores: { default: { primary: inMemoryStores() } }, - } as never); - try { - const runtime = await state.getRuntime(); - await openMailboxes(roster, { client: sessionApi(runtime.stores), userId: "u_seat" }); - const posted = (await runAction({ - flow: mailbox!, - actionName: "post", - input: { body: "on it", author }, - userId: "u_seat", - orgId: DEFAULT_ORG_ID, - sessionId: "support.desk", - stores: runtime.stores, - runtimeConfig: { ...runtime.runtimeConfig }, - } as never)) as { error?: unknown }; - - expect(String(posted.error ?? "")).not.toContain("author-not-a-member"); - expect(posted.error).toBeUndefined(); - expect((await postedLines(runtime.stores, "support.desk")).map((line) => line.author)).toEqual([ - "support.otto", - ]); - } finally { - await state.dispose(); - } - }); -}); - -describe("a record may not author `seatId`", () => { - it("is refused by name at the hire, even though every composed kind declares the key", () => { - // Control: the same record without the key hires. - expect(hireWorkforce([record("support.ada")], { workerFlows: kinds })).toHaveLength(1); - - const message = refusalOf([record("support.ada", { seatId: "support.grace" })]); - expect(message).toContain('worker "support.ada"'); - expect(message).toContain("`seatId:`"); - expect(message).toContain("not a setting a worker declares"); - }); - - it("is refused by name at the loader", async () => { - const root = mkdtempSync(join(tmpdir(), "fsd-seat-id-")); - const file = join(root, "teams/support/workers/ada/WORKER.md"); - mkdirSync(join(file, ".."), { recursive: true }); - writeFileSync( - file, - "---\ndescription: The front desk.\nflow: desk-clerk\nseatId: support.grace\n---\nBody.\n", - ); - const { workers, errors } = await readWorkforceDirectory(root); - rmSync(root, { recursive: true, force: true }); - expect(workers).toEqual([]); - expect(errors.map((e) => e.path)).toEqual(["teams/support/workers/ada"]); - expect(errors[0]!.error.message).toContain("`seatId:`"); - expect(errors[0]!.error.message).toContain("not a setting a worker declares"); - }); -}); - -describe("a hand-written kind schema that omits `seatId`", () => { - it("refuses when the flow is registered, naming the key", () => { - const handWritten = defineFlow({ - kind: "hand-written", - cardinality: "collection", - configSchema: z.object({ - instructions: z.string().optional(), - teamInstructions: z.string().optional(), - seatSkills: z.array(z.any()).optional(), - seatTools: z.array(z.any()).optional(), - seatPackages: z.array(z.any()).optional(), - }), - actions: { answer: { inputSchema, block: work } }, - }); - let message = ""; - try { - hireWorkforce([{ id: "support.ada", declared: { flow: "hand-written" }, body: "" }], { - workerFlows: { "hand-written": handWritten as never }, - }); - } catch (error) { - message = error instanceof Error ? error.message : String(error); - } - expect(message).toContain('worker flow "hand-written" doesn\'t accept `seatId`'); - }); -}); diff --git a/packages/workforce/test/seat-packages.test.ts b/packages/workforce/test/seat-packages.test.ts index d305b7b70a..aabeba7d23 100644 --- a/packages/workforce/test/seat-packages.test.ts +++ b/packages/workforce/test/seat-packages.test.ts @@ -21,7 +21,7 @@ import type { FlowInstance } from "@flow-state-dev/core/types"; import { executeBlock } from "@flow-state-dev/engine"; import { createTestContext } from "@flow-state-dev/testing"; import { AGENT_KIND, defineAgentWorkerFlow } from "../src/agent-worker-flow"; -import { hireWorkforce, type HireOptions } from "../src/hire"; +import { mintSeats, type HireOptions } from "../src/hire"; import { resolveHeldPackages } from "../src/seat-packages"; import { SEAT_PACKAGES_KEY, type PackageManifest, type WorkerManifest } from "../src/manifest"; import { workerConfigSchema } from "../src/worker-config"; @@ -96,7 +96,7 @@ function hire( manifests: WorkerManifest[], options: Omit & { packageBlocks?: HireOptions["packageBlocks"] } = {} ): (id: string) => FlowInstance { - const seats = hireWorkforce(manifests, { packageBlocks, ...options }); + const seats = mintSeats(manifests, { packageBlocks, ...options }); return (id) => { const seat = seats.find((candidate) => candidate.id === id); if (!seat) throw new Error(`no seat "${id}" in [${seats.map((s) => s.id).join(", ")}]`); @@ -106,7 +106,7 @@ function hire( function refusal(manifests: WorkerManifest[], options: HireOptions = {}): string { try { - hireWorkforce(manifests, { packageBlocks, ...options }); + mintSeats(manifests, { packageBlocks, ...options }); } catch (error) { return error instanceof Error ? error.message : String(error); } diff --git a/packages/workforce/test/seat-repair.test.ts b/packages/workforce/test/seat-repair.test.ts deleted file mode 100644 index 7362e430a7..0000000000 --- a/packages/workforce/test/seat-repair.test.ts +++ /dev/null @@ -1,1076 +0,0 @@ -/** - * Repairing a stored seat that no longer starts: `brokenSeats`, retire through - * `fire`, and `rehire`, run as actions over a real runtime and graded on what - * the store holds afterwards, not on what a block returned. - * - * The app under test carried `desk-clerk` when its seats were hired and has - * since cut it; `desk` is still carried, and its settings now require a - * `queue`. - */ -import { afterEach, describe, expect, it, vi } from "vitest"; -import { z } from "zod"; -import { defineFlow, handler } from "@flow-state-dev/core"; -import type { FlowInstance } from "@flow-state-dev/core/types"; -import { createFlowState, FlowIdentityConflictError, inMemoryStores, runAction } from "@flow-state-dev/engine"; -import { - buildSeatHire, - createSeatHireBlocks, - HIRED_ROSTER_PRIVATE_RESOURCE, - HIRED_ROSTER_RESOURCE, - SEAT_INVENTORY_RESOURCE, -} from "../src/seat-hire-blocks"; -import type { SeatHireCapabilityOptions, SeatHireChecked } from "../src/seat-hire-blocks"; -import { defineHiredRosterCollection, defineHiredRosterPrivateCollection } from "../src/roster/collections"; -import { defineSeatInventoryCollection } from "../src/inventory/collections"; -import { reloadHiredSeats } from "../src/roster/reload"; -import { encodeUserSegment, toHiredSeatRow } from "../src/roster/rows"; -import { listedSeatRows } from "../src/inventory/listed-seats"; -import { workerConfigSchema } from "../src/worker-config"; -import { workerDoor } from "./worker-door"; - -const ROSTER = "workforce/roster/"; -const SEATS = "inventory/seats/"; - -const noop = handler({ - name: "noop", - inputSchema: z.object({}), - outputSchema: z.object({}), - execute: () => ({}), -}); - -const desk = defineFlow({ - kind: "desk", - cardinality: "collection", - configSchema: workerConfigSchema().extend({ queue: z.string() }), - actions: { ...workerDoor, run: { inputSchema: z.object({}), block: noop } }, -}); - -/** The kinds the app carries now. `desk-clerk` is gone. */ -const kinds = { desk }; - -function liveRegistry() { - const held = new Map(); - return { - held, - // Refuses a taken address the way the engine's registry does. - register: (seat: FlowInstance) => { - const existing = held.get(seat.id); - if (existing !== undefined) { - throw new FlowIdentityConflictError({ reason: "duplicate-id", kind: seat.kind, id: seat.id, existingKind: existing.kind }); - } - held.set(seat.id, seat); - }, - unregister: (id: string) => held.delete(id), - kindAt: (id: string) => held.get(id)?.kind, - }; -} - -async function harness(over: Partial = {}, mount: { userOwned?: boolean } = {}) { - const live = liveRegistry(); - const blocks = createSeatHireBlocks({ - workerFlows: kinds, - register: live.register, - unregister: live.unregister, - kindAt: live.kindAt, - instanceAt: (id: string) => live.held.get(id), - ...over, - } as SeatHireCapabilityOptions); - const ops = defineFlow({ - kind: "ops", - resources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection(), - ...(mount.userOwned ? { [HIRED_ROSTER_PRIVATE_RESOURCE]: defineHiredRosterPrivateCollection() } : {}), - }, - actions: { - hire: { block: blocks.hire }, - fire: { block: blocks.fire }, - brokenSeats: { block: blocks.brokenSeats }, - rehire: { block: blocks.rehire }, - }, - } as never)(); - const state = createFlowState({ flows: { ops: ops as never }, stores: { default: { primary: inMemoryStores() } } }); - const runtime = await state.getRuntime(); - const stores = runtime.stores; - let n = 0; - - const run = async (action: string, input: unknown, orgId = "acme", userId = "u1") => { - n += 1; - const result = (await runAction({ - flow: ops, - actionName: action, - input, - userId, - orgId, - sessionId: `s-${n}`, - stores, - runtimeConfig: { ...runtime.runtimeConfig }, - } as never)) as { output?: any; error?: { message: string } }; - return result; - }; - - const seed = async (key: string, state: Record, orgId = "acme") => { - await stores.resourceState.set("org", orgId, `${ROSTER}${key}`, state as never, "any" as never); - }; - /** `hired` as the row says it; omitted, the row predates the field. */ - const seedInventory = async (address: string, kind: string, orgId = "acme", hired?: boolean) => { - const state = { id: address, kind, door: "run", ...(hired === undefined ? {} : { hired }) }; - await stores.resourceState.set("org", orgId, `${SEATS}${address}`, state as never, "any" as never); - }; - const rows = async (prefix: string, orgId = "acme") => - Object.fromEntries( - Object.entries(await stores.resourceState.getByPrefix("org", orgId, prefix)).map(([key, value]) => [ - key.slice(prefix.length), - (value as { state: Record }).state, - ]), - ); - const versions = async (prefix: string, orgId = "acme") => - Object.fromEntries( - Object.entries(await stores.resourceState.getByPrefix("org", orgId, prefix)).map(([key, value]) => [ - key, - (value as { version: number }).version, - ]), - ); - const reload = (orgIds = ["acme"]) => reloadHiredSeats({ stores, orgIds, workerFlows: kinds }); - - /** Every org row as it stands: what a process that died now leaves on disk. */ - const snapshot = async (orgId = "acme") => - Object.fromEntries( - Object.entries(await stores.resourceState.getByPrefix("org", orgId, "")).map(([key, value]) => [ - key, - (value as { state: Record }).state, - ]), - ); - /** Load a dead process's rows, then boot: register every seat the start serves. */ - const restartFrom = async (rows: Record>, orgId = "acme") => { - for (const [key, state] of Object.entries(rows)) { - await stores.resourceState.set("org", orgId, key, state as never, "any" as never); - } - const started = await reload([orgId]); - for (const seat of started.seats) live.register(seat); - return started; - }; - /** Make the next write of a seat inventory row reject, as a store that is briefly down would. */ - const failNextInventoryWrite = () => { - const set = stores.resourceState.set.bind(stores.resourceState); - const spy = vi.spyOn(stores.resourceState, "set").mockImplementation(async (...args) => { - if (String(args[2]).startsWith(SEATS)) { - spy.mockRestore(); - throw new Error("the store is unavailable"); - } - return set(...args); - }); - }; - - return { live, run, seed, seedInventory, rows, versions, reload, snapshot, restartFrom, failNextInventoryWrite, stores }; -} - -afterEach(() => vi.restoreAllMocks()); - -const row = (over: Parameters[0]) => - toHiredSeatRow({ owningOrgId: "acme", ...over }) as unknown as Record; - -/** Three stored seats after `desk-clerk` was cut, one healthy, and their inventory rows. */ -async function cutKindStore(h: Awaited>) { - await h.seed("support.joe", row({ seatId: "support.joe", flow: "desk-clerk", instructions: "Answer the desk." })); - await h.seed("support.lin", row({ seatId: "support.lin", flow: "desk" })); - await h.seed("support.ada", row({ seatId: "support.ada", flow: "desk", settings: { queue: "billing" } })); - await h.seed("support.bad", { seatId: "support.bad" }); - for (const [seatId, kind] of [["support.joe", "desk-clerk"], ["support.lin", "desk"], ["support.ada", "desk"]] as const) { - await h.seedInventory(`acme.${seatId}`, kind); - } -} - -/** - * Re-hire `support.joe` in a process that dies right after the roster write - * (registration throws), and return the store as that process left it: - * captured after the write and before the write-back a dead process never runs. - */ -async function diedAfterRehireWrite(input: Record) { - let dead: Record> | undefined; - const first = await harness({ - register: () => { - throw new Error("process died"); - }, - }); - await cutKindStore(first); - const realSet = first.stores.resourceState.set.bind(first.stores.resourceState); - let writes = 0; - vi.spyOn(first.stores.resourceState, "set").mockImplementation(async (...args) => { - const result = await realSet(...args); - if (String(args[2]) === `${ROSTER}support.joe` && ++writes === 1) dead = await first.snapshot(); - return result; - }); - expect((await first.run("rehire", input)).error?.message).toMatch(/process died/); - vi.restoreAllMocks(); - return dead!; -} - -describe("brokenSeats", () => { - it("BR-1 to BR-4 · lists each stored seat the start skips, with its reason; not the one that starts", async () => { - const h = await harness(); - await cutKindStore(h); - const listed = await h.run("brokenSeats", {}); - expect(listed.error).toBeUndefined(); - const out = listed.output as Array>; - expect(out.map((entry) => [entry.seatId, entry.reason, entry.kind])).toEqual([ - ["support.bad", "unreadable", null], - ["support.joe", "kind-gone", "desk-clerk"], - ["support.lin", "refused", "desk"], - ]); - expect(out[0]!.key).toBe("workforce/roster/support.bad"); - expect(String(out[1]!.detail)).toContain('Worker flows passed: "agent", "desk"'); - expect(String(out[2]!.detail)).toMatch(/queue/); - }); - - it("BR-5 · names the same rows with the same detail as the start, over the same rows", async () => { - const h = await harness(); - await cutKindStore(h); - const listed = (await h.run("brokenSeats", {})).output as Array<{ key: string; detail: string }>; - const started = await h.reload(); - expect(new Set(listed.map((entry) => `organization "acme", row "${entry.key}" — ${entry.detail}`))).toEqual( - new Set(started.problems), - ); - expect(started.seats.map((seat) => seat.id)).toEqual(["acme.support.ada"]); - }); - - it("BR-6 · reads the principal's organization only; an org in the body changes nothing", async () => { - const h = await harness(); - await cutKindStore(h); - await h.seed("ops.kim", toHiredSeatRow({ seatId: "ops.kim", flow: "desk-clerk", owningOrgId: "globex" }) as never, "globex"); - const asAcme = (await h.run("brokenSeats", { orgId: "globex" })).output as Array<{ seatId: string }>; - expect(asAcme.map((entry) => entry.seatId)).not.toContain("ops.kim"); - const asGlobex = (await h.run("brokenSeats", {}, "globex")).output as Array<{ seatId: string }>; - expect(asGlobex.map((entry) => entry.seatId)).toEqual(["ops.kim"]); - }); - - it("BR-7 · writes nothing", async () => { - const h = await harness(); - await cutKindStore(h); - const before = { roster: await h.versions(ROSTER), seats: await h.versions(SEATS) }; - await h.run("brokenSeats", {}); - expect({ roster: await h.versions(ROSTER), seats: await h.versions(SEATS) }).toEqual(before); - }); -}); - -describe("one hire's side effects never touch another's", () => { - it("a hire that lands while an older fire is finishing keeps its inventory row; the fire still succeeds", async () => { - const h = await harness(); - expect((await h.run("hire", { seatId: "support.ada", flow: "desk", settings: { queue: "old" } })).error).toBeUndefined(); - - // When the fire is about to delete the inventory row (its roster row and - // address already gone), a replacement hire of the same seat lands. - const realDelete = h.stores.resourceState.delete.bind(h.stores.resourceState); - let replaced: Promise<{ error?: unknown }> | undefined; - vi.spyOn(h.stores.resourceState, "delete").mockImplementation(async (...args) => { - if (replaced === undefined && String(args[2]) === `${SEATS}acme.support.ada`) { - replaced = Promise.resolve({}); - replaced = h.run("hire", { seatId: "support.ada", flow: "desk", settings: { queue: "new" } }) as Promise<{ error?: unknown }>; - expect((await replaced).error).toBeUndefined(); - } - return realDelete(...args); - }); - const fired = await h.run("fire", { seatId: "support.ada" }); - vi.restoreAllMocks(); - expect(replaced).toBeDefined(); - expect((await h.rows(ROSTER))["support.ada"]).toMatchObject({ settings: { queue: "new" } }); - expect((await h.rows(SEATS))["acme.support.ada"]).toMatchObject({ kind: "desk", hired: true }); - expect(h.live.held.has("acme.support.ada")).toBe(true); - expect(fired.error).toBeUndefined(); - }); - - it("a fire that lands while a hire is publishing leaves no inventory row behind", async () => { - const h = await harness(); - const realSet = h.stores.resourceState.set.bind(h.stores.resourceState); - let fired: Promise<{ error?: unknown }> | undefined; - vi.spyOn(h.stores.resourceState, "set").mockImplementation(async (...args) => { - if (fired === undefined && String(args[2]) === `${SEATS}acme.support.ada`) { - fired = Promise.resolve({}); - fired = h.run("fire", { seatId: "support.ada" }) as Promise<{ error?: unknown }>; - expect((await fired).error).toBeUndefined(); - } - return realSet(...args); - }); - const hired = await h.run("hire", { seatId: "support.ada", flow: "desk", settings: { queue: "q" } }); - vi.restoreAllMocks(); - expect(fired).toBeDefined(); - expect(h.live.held.has("acme.support.ada")).toBe(false); - expect(await h.rows(ROSTER)).toEqual({}); - expect(await h.rows(SEATS)).toEqual({}); - expect(hired.error?.message).toMatch(/fired/); - }); - - it("fire leaves registered a same-kind seat at the address that this row didn't mint", async () => { - const h = await harness(); - expect((await h.run("hire", { seatId: "support.ada", flow: "desk", settings: { queue: "q" } })).error).toBeUndefined(); - // Since then the address came to be served by a seat the row didn't mint - // (a declared one, here put there by hand). - const stranger = { id: "acme.support.ada", kind: "desk" } as FlowInstance; - h.live.held.set("acme.support.ada", stranger); - const fired = await h.run("fire", { seatId: "support.ada" }); - expect(fired.error).toBeUndefined(); - expect(fired.output).toMatchObject({ released: false }); - expect(h.live.held.get("acme.support.ada")).toBe(stranger); - expect(await h.rows(ROSTER)).toEqual({}); - }); - - it("rehire with no `kindAt`: a same-kind seat already at the address that isn't this seat is refused, and the old row comes back", async () => { - const h = await harness({ kindAt: undefined }); - await cutKindStore(h); - const stranger = { id: "acme.support.joe", kind: "desk" } as FlowInstance; - h.live.held.set("acme.support.joe", stranger); // a declared seat, not from the roster - const before = (await h.rows(ROSTER))["support.joe"]; - const result = await h.run("rehire", { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }); - expect(h.live.held.get("acme.support.joe")).toBe(stranger); - expect((await h.rows(SEATS))["acme.support.joe"]).toMatchObject({ kind: "desk-clerk" }); - expect((await h.rows(ROSTER))["support.joe"]).toEqual(before); - expect(result.error?.message).toMatch(/already registered/); - }); - - it("an unfinished repair's retry: a same-kind seat at the address that this row didn't register is refused", async () => { - const input = { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }; - const dead = await diedAfterRehireWrite(input); - const h = await harness({ kindAt: undefined }); - for (const [key, state] of Object.entries(dead)) { - await h.stores.resourceState.set("org", "acme", key, state as never, "any" as never); - } - const stranger = { id: "acme.support.joe", kind: "desk" } as FlowInstance; - h.live.held.set("acme.support.joe", stranger); // not the seat the marked row would start - const result = await h.run("rehire", input); - expect(h.live.held.get("acme.support.joe")).toBe(stranger); - expect((await h.rows(SEATS))["acme.support.joe"]).toMatchObject({ kind: "desk-clerk" }); - expect((await h.rows(ROSTER))["support.joe"]).toMatchObject({ pendingRepair: expect.any(String) }); - expect(result.error?.message).toMatch(/already registered/); - }); -}); - -describe("retire is fire", () => { - it("BR-8 · a listed seat is retired: roster row then inventory row, nothing released, the next start names nothing for it", async () => { - const h = await harness(); - await cutKindStore(h); - const fired = await h.run("fire", { seatId: "support.joe" }); - expect(fired.error).toBeUndefined(); - expect(fired.output).toEqual({ seatId: "support.joe", address: "acme.support.joe", released: false }); - expect(Object.keys(await h.rows(ROSTER))).not.toContain("support.joe"); - expect(Object.keys(await h.rows(SEATS))).not.toContain("acme.support.joe"); - expect((await h.reload()).problems.join("\n")).not.toContain("support.joe"); - }); - - it("BR-9 · a working hired seat: roster row, address released, inventory row", async () => { - const h = await harness(); - const hired = await h.run("hire", { seatId: "support.ada", flow: "desk", settings: { queue: "q" } }); - expect(hired.error).toBeUndefined(); - expect(Object.keys(await h.rows(SEATS))).toEqual(["acme.support.ada"]); - const fired = await h.run("fire", { seatId: "support.ada" }); - expect(fired.output).toEqual({ seatId: "support.ada", address: "acme.support.ada", released: true }); - expect(h.live.held.has("acme.support.ada")).toBe(false); - expect(await h.rows(ROSTER)).toEqual({}); - expect(await h.rows(SEATS)).toEqual({}); - }); - - it("BR-10 · a crash between the two deletes: the next fire removes the leftover row and says it was already gone", async () => { - let crash = true; - const h = await harness({ - unregister: () => { - if (crash) throw new Error("process died between the deletes"); - return false; - }, - }); - await h.run("hire", { seatId: "support.ada", flow: "desk", settings: { queue: "q" } }); - const first = await h.run("fire", { seatId: "support.ada" }); - expect(first.error?.message).toMatch(/process died/); - expect(await h.rows(ROSTER)).toEqual({}); - expect(Object.keys(await h.rows(SEATS))).toEqual(["acme.support.ada"]); - - crash = false; - h.live.held.clear(); // the restart: nothing holds the address - const second = await h.run("fire", { seatId: "support.ada" }); - expect(second.error).toBeUndefined(); - expect(second.output).toEqual({ seatId: "support.ada", address: "acme.support.ada", released: false, alreadyGone: true }); - expect(await h.rows(SEATS)).toEqual({}); - }); - - it("BR-10 · a leftover row at an address something holds is not removed; the declared-seat refusal stands", async () => { - const h = await harness(); - await h.seedInventory("acme.lead", "desk"); - h.live.held.set("acme.lead", { id: "acme.lead", kind: "desk" } as FlowInstance); - const fired = await h.run("fire", { seatId: "lead" }); - expect(fired.error?.message).toMatch(/worker file|folder/); - expect(Object.keys(await h.rows(SEATS))).toEqual(["acme.lead"]); - }); - - it("BR-11 · with no `kindAt`, a declared worker's inventory row at the fired address is left alone and the fire refused", async () => { - // Org `acme`, declared worker `acme.lead`: `fire({ seatId: "lead" })` - // computes the same address. Without `kindAt` nothing says it is held, so - // only the row's own origin keeps fire off it. - const h = await harness({ kindAt: undefined }); - await h.seedInventory("acme.lead", "desk", "acme", false); - await h.seedInventory("acme.old", "desk"); // written before rows said where they came from - for (const seatId of ["lead", "old"]) { - const fired = await h.run("fire", { seatId }); - expect(fired.error?.message).toMatch(new RegExp(`hired no seat "${seatId}"`)); - } - expect(Object.keys(await h.rows(SEATS)).sort()).toEqual(["acme.lead", "acme.old"]); - }); - - it("BR-11 · a seat this org never hired is refused, as today", async () => { - const h = await harness(); - const fired = await h.run("fire", { seatId: "support.nobody" }); - expect(fired.error?.message).toMatch(/hired no seat "support.nobody"/); - }); - - it("BR-12 · an unreadable row is deleted by its key, and nothing else is touched", async () => { - const h = await harness(); - await cutKindStore(h); - const seatsBefore = await h.rows(SEATS); - const fired = await h.run("fire", { seatId: "support.bad" }); - expect(fired.output).toEqual({ seatId: "support.bad", address: null, released: false }); - expect(Object.keys(await h.rows(ROSTER)).sort()).toEqual(["support.ada", "support.joe", "support.lin"]); - expect(await h.rows(SEATS)).toEqual(seatsBefore); - }); -}); - -describe("a row stored under a key that isn't its seat id", () => { - /** `legacy-key` holds an envelope naming `support.lin`, a working seat stored under its own key. */ - async function mismatchedStore(h: Awaited>) { - await h.seed("legacy-key", row({ seatId: "support.lin", flow: "desk-clerk" })); - await h.seed("support.lin", row({ seatId: "support.lin", flow: "desk", settings: { queue: "q" } })); - await h.seedInventory("acme.support.lin", "desk"); - const started = await h.reload(); - for (const seat of started.seats) h.live.register(seat); - return started; - } - - it("is listed as unreadable under its storage key, as the start names it", async () => { - const h = await harness(); - const started = await mismatchedStore(h); - const listed = await h.run("brokenSeats", {}); - expect(listed.output).toEqual([ - expect.objectContaining({ seatId: "legacy-key", key: `${ROSTER}legacy-key`, reason: "unreadable" }), - ]); - expect(started.problems.join("\n")).toMatch(/legacy-key.*support\.lin/); - }); - - it("fire by that key removes only that row; the seat its envelope names keeps its row, address and inventory row", async () => { - const h = await harness(); - await mismatchedStore(h); - const fired = await h.run("fire", { seatId: "legacy-key" }); - expect(fired.error).toBeUndefined(); - expect(fired.output).toEqual({ seatId: "legacy-key", address: null, released: false }); - expect(Object.keys(await h.rows(ROSTER))).toEqual(["support.lin"]); - expect(h.live.held.has("acme.support.lin")).toBe(true); - expect(Object.keys(await h.rows(SEATS))).toEqual(["acme.support.lin"]); - }); - - it("rehire by that key is refused, and nothing changes", async () => { - const h = await harness(); - await mismatchedStore(h); - const before = await h.snapshot(); - const rehired = await h.run("rehire", { seatId: "legacy-key", flow: "desk", settings: { queue: "q" } }); - expect(rehired.error?.message).toMatch(/can't be read/); - expect(await h.snapshot()).toEqual(before); - }); -}); - -describe("a user-owned seat whose kind was cut", () => { - const OWNED = `~${encodeUserSegment("u1")}/research`; - const ownedRow = (flow: string) => row({ seatId: "research", flow, ownerUserId: "u1", instructions: "Read." }); - - it("the start and brokenSeats name it alike for its owner; another member's list leaves it out", async () => { - const h = await harness({}, { userOwned: true }); - await cutKindStore(h); - await h.seed(OWNED, ownedRow("desk-clerk")); - const listed = (await h.run("brokenSeats", {})).output as Array<{ seatId: string; key: string; detail: string }>; - const started = await h.reload(); - expect(listed.find((entry) => entry.key === `${ROSTER}${OWNED}`)).toMatchObject({ seatId: "research", owner: "me" }); - expect(listed.find((entry) => entry.key === `${ROSTER}support.joe`)).toMatchObject({ owner: "organization" }); - expect(new Set(listed.map((entry) => `organization "acme", row "${entry.key}" — ${entry.detail}`))).toEqual( - new Set(started.problems), - ); - // The user-owned roster serves a row only to its member. - const others = (await h.run("brokenSeats", {}, "acme", "u2")).output as Array<{ key: string }>; - expect(others.map((entry) => entry.key)).not.toContain(`${ROSTER}${OWNED}`); - }); - - it("rehire keeps it user-owned at its address, and the next start serves it", async () => { - const h = await harness({}, { userOwned: true }); - await h.seed(OWNED, ownedRow("desk-clerk")); - const rehired = await h.run("rehire", { seatId: "research", flow: "desk", settings: { queue: "q" } }); - expect(rehired.error).toBeUndefined(); - expect(rehired.output).toEqual({ seatId: "research", address: "acme.~u1.research" }); - expect(h.live.kindAt("acme.~u1.research")).toBe("desk"); - expect((await h.rows(ROSTER))[OWNED]).toMatchObject({ flow: "desk", ownerUserId: "u1", instructions: "Read." }); - expect((await h.rows(SEATS))["acme.~u1.research"]).toMatchObject({ kind: "desk", hired: true }); - const started = await h.reload(); - expect(started.problems).toEqual([]); - expect(started.seats.map((seat) => seat.id)).toEqual(["acme.~u1.research"]); - }); - - it("fire dies after its user-owned roster row is gone: the retry keeps it the caller's and removes the leftover inventory row", async () => { - let crash = true; - const h = await harness( - { - unregister: () => { - if (crash) throw new Error("process died between the deletes"); - return false; - }, - }, - { userOwned: true }, - ); - await h.seed(OWNED, ownedRow("desk-clerk")); - await h.run("rehire", { seatId: "research", flow: "desk", settings: { queue: "q" } }); - expect((await h.rows(SEATS))["acme.~u1.research"]).toMatchObject({ hired: true }); - - const first = await h.run("fire", { seatId: "research" }); - expect(first.error?.message).toMatch(/process died/); - expect(await h.rows(ROSTER)).toEqual({}); - expect(Object.keys(await h.rows(SEATS))).toEqual(["acme.~u1.research"]); - // The leftover still carries the incarnation its hire stamped; with the - // owner's roster row gone, the team list doesn't show it. - const leftover = Object.values(await h.rows(SEATS)) as Array<{ id: string; hired: boolean; incarnation: string | null }>; - expect(leftover[0]!.incarnation).toEqual(expect.any(String)); - expect(listedSeatRows("acme", leftover, [], [])).toEqual([]); - - crash = false; - h.live.held.clear(); // the restart: nothing holds the address - const second = await h.run("fire", { seatId: "research" }); - expect(second.error).toBeUndefined(); - expect(second.output).toEqual({ seatId: "research", address: "acme.~u1.research", released: false, alreadyGone: true }); - expect(await h.rows(SEATS)).toEqual({}); - }); - - it("the same retry when an org-wide seat shares the seat id: the caller's leftover goes, and the org seat is untouched", async () => { - let crash = true; - const h = await harness( - { - unregister: (id: string) => { - if (crash) throw new Error("process died between the deletes"); - return h.live.held.delete(id); - }, - }, - { userOwned: true }, - ); - await h.seed(OWNED, ownedRow("desk-clerk")); - await h.run("rehire", { seatId: "research", flow: "desk", settings: { queue: "q" } }); - crash = false; - const org = await h.run("hire", { seatId: "research", flow: "desk", settings: { queue: "org" } }); - expect(org.error).toBeUndefined(); - crash = true; - - // Two rows under the id, so the first fire names its own. - const first = await h.run("fire", { seatId: "research", owner: "me" }); - expect(first.error?.message).toMatch(/process died/); - expect(Object.keys(await h.rows(ROSTER))).toEqual(["research"]); - - crash = false; - h.live.held.delete("acme.~u1.research"); // the restart: the user-owned seat is not served - const second = await h.run("fire", { seatId: "research" }); - expect(second.error).toBeUndefined(); - expect(second.output).toEqual({ seatId: "research", address: "acme.~u1.research", released: false, alreadyGone: true }); - expect(Object.keys(await h.rows(ROSTER))).toEqual(["research"]); - expect(Object.keys(await h.rows(SEATS))).toEqual(["acme.research"]); - expect(h.live.held.has("acme.research")).toBe(true); - }); - - /** u1 holds a user-owned `research` and the org holds one too, both healthy. */ - async function twoUnderOneId() { - const h = await harness({}, { userOwned: true }); - await h.seed(OWNED, ownedRow("desk-clerk")); - expect((await h.run("rehire", { seatId: "research", owner: "me", flow: "desk", settings: { queue: "mine" } })).error).toBeUndefined(); - expect((await h.run("hire", { seatId: "research", flow: "desk", settings: { queue: "org" } })).error).toBeUndefined(); - return h; - } - - it("fire and rehire with no owner refuse when the caller has both rows under the seat id, and name the two", async () => { - const h = await twoUnderOneId(); - const before = await h.snapshot(); - for (const [action, input] of [ - ["fire", { seatId: "research" }], - ["rehire", { seatId: "research", flow: "desk", settings: { queue: "x" } }], - ] as const) { - const refused = await h.run(action, input); - expect(refused.error?.message).toMatch(/"research" names two seats: the organization's and yours.*owner: "organization" or owner: "me"/); - } - expect(await h.snapshot()).toEqual(before); - expect([...h.live.held.keys()].sort()).toEqual(["acme.research", "acme.~u1.research"]); - }); - - it("owner picks the row: \"organization\" fires the org seat and leaves the caller's own", async () => { - const h = await twoUnderOneId(); - const fired = await h.run("fire", { seatId: "research", owner: "organization" }); - expect(fired.output).toEqual({ seatId: "research", address: "acme.research", released: true }); - expect(Object.keys(await h.rows(ROSTER))).toEqual([OWNED]); - expect(Object.keys(await h.rows(SEATS))).toEqual(["acme.~u1.research"]); - expect([...h.live.held.keys()]).toEqual(["acme.~u1.research"]); - }); - - it("owner picks the row: \"me\" fires the caller's own and leaves the org seat", async () => { - const h = await twoUnderOneId(); - const fired = await h.run("fire", { seatId: "research", owner: "me" }); - expect(fired.output).toEqual({ seatId: "research", address: "acme.~u1.research", released: true }); - expect(Object.keys(await h.rows(ROSTER))).toEqual(["research"]); - expect(Object.keys(await h.rows(SEATS))).toEqual(["acme.research"]); - expect([...h.live.held.keys()]).toEqual(["acme.research"]); - }); - - it("a broken org seat beside a healthy user-owned one: the owner brokenSeats reports is the row rehire repairs", async () => { - const h = await harness({}, { userOwned: true }); - await h.seed("research", row({ seatId: "research", flow: "desk-clerk" })); - await h.seed(OWNED, ownedRow("desk-clerk")); - expect((await h.run("rehire", { seatId: "research", owner: "me", flow: "desk", settings: { queue: "mine" } })).error).toBeUndefined(); - const listed = (await h.run("brokenSeats", {})).output as Array<{ seatId: string; owner: "organization" | "me" }>; - expect(listed.map((entry) => [entry.seatId, entry.owner])).toEqual([["research", "organization"]]); - const rehired = await h.run("rehire", { seatId: listed[0]!.seatId, owner: listed[0]!.owner, flow: "desk", settings: { queue: "org" } }); - expect(rehired.output).toEqual({ seatId: "research", address: "acme.research" }); - const roster = await h.rows(ROSTER); - expect(roster.research).toMatchObject({ flow: "desk", settings: { queue: "org" }, ownerUserId: null }); - expect(roster[OWNED]).toMatchObject({ flow: "desk", settings: { queue: "mine" }, ownerUserId: "u1" }); - }); - - it("owner \"me\" on a flow with no user-owned roster is refused, not read as the org's row", async () => { - const h = await harness(); - await cutKindStore(h); - const fired = await h.run("fire", { seatId: "support.joe", owner: "me" }); - expect(fired.error?.message).toMatch(/no user-owned roster/); - expect(Object.keys(await h.rows(ROSTER))).toContain("support.joe"); - }); - - it("fire retires it: its row goes, and the next start names nothing", async () => { - const h = await harness({}, { userOwned: true }); - await h.seed(OWNED, ownedRow("desk-clerk")); - const fired = await h.run("fire", { seatId: "research" }); - expect(fired.error).toBeUndefined(); - expect(fired.output).toEqual({ seatId: "research", address: "acme.~u1.research", released: false }); - expect(await h.rows(ROSTER)).toEqual({}); - expect((await h.reload()).problems).toEqual([]); - }); -}); - -describe("rehire", () => { - it("BR-14 · a kind-gone seat keeps its id and address on the named kind; instructions carry, settings are the new kind's", async () => { - const h = await harness(); - await cutKindStore(h); - const rehired = await h.run("rehire", { seatId: "support.joe", flow: "desk", settings: { queue: "front" } }); - expect(rehired.error).toBeUndefined(); - expect(rehired.output).toEqual({ seatId: "support.joe", address: "acme.support.joe" }); - expect(h.live.kindAt("acme.support.joe")).toBe("desk"); - expect((await h.rows(ROSTER))["support.joe"]).toMatchObject({ - seatId: "support.joe", - flow: "desk", - settings: { queue: "front" }, - instructions: "Answer the desk.", - }); - expect((await h.rows(SEATS))["acme.support.joe"]).toMatchObject({ kind: "desk" }); - const started = await h.reload(); - expect(started.seats.map((seat) => [seat.id, seat.kind])).toContainEqual(["acme.support.joe", "desk"]); - }); - - it("a field this version doesn't know, written by a newer one, survives the re-hire and the retry that finishes it", async () => { - // A mixed-version deployment: a newer worker stored a roster field this - // version has no name for. Re-hire rewrites the row; the field is not its - // to drop. - const h = await harness({ - register: () => { - throw new Error("process died"); - }, - }); - await cutKindStore(h); - await h.seed("support.joe", { ...row({ seatId: "support.joe", flow: "desk-clerk" }), addedLater: { tier: "gold" } }); - const input = { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }; - const realSet = h.stores.resourceState.set.bind(h.stores.resourceState); - let dead: Record> | undefined; - vi.spyOn(h.stores.resourceState, "set").mockImplementation(async (...args) => { - const result = await realSet(...args); - if (String(args[2]) === `${ROSTER}support.joe` && dead === undefined) dead = await h.snapshot(); - return result; - }); - expect((await h.run("rehire", input)).error?.message).toMatch(/process died/); - vi.restoreAllMocks(); - expect(dead![`${ROSTER}support.joe`]).toMatchObject({ flow: "desk", addedLater: { tier: "gold" } }); - - const after = await harness(); - await after.restartFrom(dead!); - expect((await after.run("rehire", input)).error).toBeUndefined(); - expect((await after.rows(ROSTER))["support.joe"]).toMatchObject({ flow: "desk", pendingRepair: null, addedLater: { tier: "gold" } }); - }); - - it("BR-14 · a refused seat is re-hired with settings the kind accepts, and new instructions replace the old", async () => { - const h = await harness(); - await cutKindStore(h); - const rehired = await h.run("rehire", { seatId: "support.lin", flow: "desk", settings: { queue: "q" }, instructions: "New." }); - expect(rehired.error).toBeUndefined(); - expect((await h.rows(ROSTER))["support.lin"]).toMatchObject({ flow: "desk", instructions: "New." }); - }); - - it("BR-15 · a kind not carried, outside allowKinds, or refusing the settings is refused before anything is written", async () => { - const h = await harness({ allowKinds: ["desk"] }); - await cutKindStore(h); - const before = await h.versions(ROSTER); - const cases = [ - [{ seatId: "support.joe", flow: "desk-clerk" }, /may not re-hire onto kind "desk-clerk"/], - [{ seatId: "support.joe", flow: "agent" }, /may not re-hire onto kind "agent"/], - [{ seatId: "support.joe", flow: "desk" }, /queue/], - ] as const; - for (const [input, refusal] of cases) { - const result = await h.run("rehire", input); - expect(result.error?.message).toMatch(refusal); - } - const unallowed = await harness(); - await cutKindStore(unallowed); - expect((await unallowed.run("rehire", { seatId: "support.joe", flow: "desk-clerk" })).error?.message).toMatch( - /carries no flow kind "desk-clerk"/, - ); - expect(await h.versions(ROSTER)).toEqual(before); - expect(((await h.run("brokenSeats", {})).output as Array<{ seatId: string }>).map((e) => e.seatId)).toContain("support.joe"); - }); - - it("BR-16 · registration fails after the write: the old row is written back, the seat stays listed, the error is named", async () => { - const h = await harness({ - register: () => { - throw new Error("the registry refused the address"); - }, - }); - await cutKindStore(h); - const before = (await h.rows(ROSTER))["support.joe"]; - const result = await h.run("rehire", { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }); - expect(result.error?.message).toMatch(/registry refused/); - expect((await h.rows(ROSTER))["support.joe"]).toEqual(before); - expect((await h.rows(SEATS))["acme.support.joe"]).toMatchObject({ kind: "desk-clerk" }); - const listed = (await h.run("brokenSeats", {})).output as Array<{ seatId: string; reason: string }>; - expect(listed).toContainEqual(expect.objectContaining({ seatId: "support.joe", reason: "kind-gone" })); - }); - - it("BR-17 · the process dies after the write and before registration: the next start serves the seat on its new kind", async () => { - let atDeath: ReturnType | undefined; - const h = await harness({ - register: () => { - // What a fresh process would read had this one died here. - atDeath = h.reload(); - throw new Error("process died"); - }, - }); - await cutKindStore(h); - await h.run("rehire", { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }); - const started = await atDeath!; - expect(started.seats.map((seat) => [seat.id, seat.kind])).toContainEqual(["acme.support.joe", "desk"]); - expect(started.problems.join("\n")).not.toContain("support.joe"); - }); - - it("BR-17 · the process dies after the write: the same re-hire run after the restart finishes the inventory row and clears the pending repair", async () => { - const input = { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }; - const dead = await diedAfterRehireWrite(input); - expect(dead[`${ROSTER}support.joe`]).toMatchObject({ flow: "desk", pendingRepair: expect.any(String) }); - - const h = await harness(); - const started = await h.restartFrom(dead); - expect(started.seats.map((seat) => [seat.id, seat.kind])).toContainEqual(["acme.support.joe", "desk"]); - expect((await h.rows(SEATS))["acme.support.joe"]).toMatchObject({ kind: "desk-clerk" }); - - const again = await h.run("rehire", input); - expect(again.error).toBeUndefined(); - expect(again.output).toEqual({ seatId: "support.joe", address: "acme.support.joe" }); - expect((await h.rows(SEATS))["acme.support.joe"]).toMatchObject({ kind: "desk", hired: true }); - expect((await h.rows(ROSTER))["support.joe"]).toMatchObject({ flow: "desk", settings: { queue: "q" }, pendingRepair: null }); - // Finished: the same call now meets a working seat with nothing pending. - expect((await h.run("rehire", input)).error?.message).toMatch(/still starts/); - }); - - it("an unfinished repair finishes with no `kindAt`: the seat the restart registered counts as registered", async () => { - const input = { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }; - const dead = await diedAfterRehireWrite(input); - const h = await harness({ kindAt: undefined }); - await h.restartFrom(dead); - const again = await h.run("rehire", input); - expect(again.error).toBeUndefined(); - expect(h.live.held.get("acme.support.joe")?.kind).toBe("desk"); - expect((await h.rows(SEATS))["acme.support.joe"]).toMatchObject({ kind: "desk", hired: true }); - expect((await h.rows(ROSTER))["support.joe"]).toMatchObject({ pendingRepair: null }); - }); - - /** - * The inventory after a fire took back an unfinished repair: the repair - * published nothing, so the row at the address is still the one the seat had - * before it (written before incarnations), untouched. Fire removes only the - * fired incarnation's row; this one carries none, and no roster row backs it, - * so a team list leaves it out. (A real restart rewrites it with the - * incarnation of the seat it serves, which fire then removes.) - */ - async function expectOnlyTheOldRowLeft(h: Awaited>) { - const seats = await h.rows(SEATS); - expect(seats["acme.support.joe"]).toEqual({ id: "acme.support.joe", kind: "desk-clerk", door: "run" }); - const listed = listedSeatRows("acme", Object.values(seats) as Array<{ id: string; hired?: boolean | null }>, []); - expect(listed.map((row) => row.id)).not.toContain("acme.support.joe"); - } - - it("fire lands after an unfinished repair's retry loaded its row: the retry neither registers nor publishes it", async () => { - const input = { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }; - const dead = await diedAfterRehireWrite(input); - const h = await harness(); - await h.restartFrom(dead); - - // The retry loads the roster when it starts; run `fire` to completion - // right after, so the retry works from a row the store no longer holds. - const realLoad = h.stores.resourceState.getByPrefix.bind(h.stores.resourceState); - let fired: Promise<{ error?: unknown }> | undefined; - vi.spyOn(h.stores.resourceState, "getByPrefix").mockImplementation(async (...args) => { - const loaded = await realLoad(...args); - if (fired === undefined && String(args[2]).startsWith(ROSTER)) { - fired = Promise.resolve({}); - fired = h.run("fire", { seatId: "support.joe" }) as Promise<{ error?: unknown }>; - expect((await fired).error).toBeUndefined(); - } - return loaded; - }); - const again = await h.run("rehire", input); - vi.restoreAllMocks(); - expect(fired).toBeDefined(); - expect(h.live.held.has("acme.support.joe")).toBe(false); - expect(again.error?.message).toMatch(/fired/); - expect(await h.rows(ROSTER)).not.toHaveProperty("support.joe"); - await expectOnlyTheOldRowLeft(h); - }); - - it("fire lands during the retry's first check of its row: what the retry registered is taken back", async () => { - const input = { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }; - const dead = await diedAfterRehireWrite(input); - const h = await harness(); - await h.restartFrom(dead); - - // Run `fire` to completion during the retry's first store read of the row, - // which then answers with the row as it was: the retry registers, and its - // next check finds the row gone. - const realGet = h.stores.resourceState.get.bind(h.stores.resourceState); - let fired: Promise | undefined; - vi.spyOn(h.stores.resourceState, "get").mockImplementation(async (...args) => { - const result = await realGet(...args); - if (fired === undefined && String(args[2]) === `${ROSTER}support.joe`) { - fired = Promise.resolve(); // the fire's own reads pass through - fired = h.run("fire", { seatId: "support.joe" }); - expect(((await fired) as { error?: unknown }).error).toBeUndefined(); - } - return result; - }); - const again = await h.run("rehire", input); - vi.restoreAllMocks(); - expect(fired).toBeDefined(); - expect(again.error?.message).toMatch(/fired/); - expect(h.live.held.has("acme.support.joe")).toBe(false); - expect(await h.rows(ROSTER)).not.toHaveProperty("support.joe"); - await expectOnlyTheOldRowLeft(h); - }); - - it("the inventory write fails after the seat is re-hired: the error says so, and the same re-hire run again finishes it", async () => { - const h = await harness(); - await cutKindStore(h); - const input = { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }; - h.failNextInventoryWrite(); - const first = await h.run("rehire", input); - expect(first.error?.message).toMatch(/is serving, but its inventory row could not be written.*store is unavailable.*same re-hire again/s); - expect(h.live.kindAt("acme.support.joe")).toBe("desk"); - expect((await h.rows(SEATS))["acme.support.joe"]).toMatchObject({ kind: "desk-clerk" }); - - const again = await h.run("rehire", input); - expect(again.error).toBeUndefined(); - expect((await h.rows(SEATS))["acme.support.joe"]).toMatchObject({ kind: "desk", hired: true }); - // A different re-hire of the now-working seat is still refused (BR-18). - expect((await h.run("rehire", { ...input, settings: { queue: "other" } })).error?.message).toMatch(/still starts/); - }); - - it("fire lands just before an unfinished repair's retry writes the inventory row: the retry takes it back, leaving no seat and no inventory row", async () => { - const input = { seatId: "support.joe", flow: "desk", settings: { queue: "q" } }; - const dead = await diedAfterRehireWrite(input); - const h = await harness(); - await h.restartFrom(dead); - - // Run `fire` to completion when the retry is about to write the seat's - // inventory row, then let that write land. - const realSet = h.stores.resourceState.set.bind(h.stores.resourceState); - let fired: Promise<{ error?: unknown }> | undefined; - vi.spyOn(h.stores.resourceState, "set").mockImplementation(async (...args) => { - if (fired === undefined && String(args[2]) === `${SEATS}acme.support.joe`) { - fired = Promise.resolve({}); - fired = h.run("fire", { seatId: "support.joe" }) as Promise<{ error?: unknown }>; - expect((await fired).error).toBeUndefined(); - } - return realSet(...args); - }); - const again = await h.run("rehire", input); - vi.restoreAllMocks(); - expect(fired).toBeDefined(); - expect(again.error?.message).toMatch(/fired/); - expect(h.live.held.has("acme.support.joe")).toBe(false); - expect(await h.rows(ROSTER)).not.toHaveProperty("support.joe"); - // The retry replaced the old row while its roster row was current, then - // took its own row back: nothing is left at the address. - expect(await h.rows(SEATS)).not.toHaveProperty("acme.support.joe"); - }); - - it("BR-18 · a working seat re-hired with its own kind and settings is refused, on a row from before repairs were marked", async () => { - const h = await harness(); - // No `pendingRepair` key at all: a row written before the field (BP-030). - await h.seed("support.ada", { - seatId: "support.ada", - flow: "desk", - settings: { queue: "billing" }, - instructions: null, - owningOrgId: "acme", - ownerUserId: null, - }); - const before = await h.versions(ROSTER); - const result = await h.run("rehire", { seatId: "support.ada", flow: "desk", settings: { queue: "billing" } }); - expect(result.error?.message).toMatch(/still starts/); - expect(await h.versions(ROSTER)).toEqual(before); - expect(h.live.held.has("acme.support.ada")).toBe(false); - expect(await h.rows(SEATS)).toEqual({}); - }); - - it("BR-18 · a seat that would start, and an unreadable row, are refused", async () => { - const h = await harness(); - await cutKindStore(h); - const working = await h.run("rehire", { seatId: "support.ada", flow: "desk", settings: { queue: "x" } }); - expect(working.error?.message).toMatch(/still starts.*fire it and hire it again/); - const unreadable = await h.run("rehire", { seatId: "support.bad", flow: "desk", settings: { queue: "x" } }); - expect(unreadable.error?.message).toMatch(/can't be read.*Fire it to retire it/); - }); - - it("BR-19 · two repairs of one seat at once: one lands, the other is refused naming the seat", async () => { - const h = await harness(); - await cutKindStore(h); - const [a, b] = await Promise.all([ - h.run("rehire", { seatId: "support.joe", flow: "desk", settings: { queue: "a" } }), - h.run("rehire", { seatId: "support.joe", flow: "desk", settings: { queue: "b" } }), - ]); - const errors = [a, b].filter((result) => result.error !== undefined); - expect(errors).toHaveLength(1); - expect(errors[0]!.error!.message).toMatch(/acme\.support\.joe/); - const landed = a.error === undefined ? "a" : "b"; - expect((await h.rows(ROSTER))["support.joe"]).toMatchObject({ settings: { queue: landed } }); - }); - - it("BR-19 · a re-hire racing a retire never resurrects the row", async () => { - const h = await harness(); - await cutKindStore(h); - await Promise.all([ - h.run("rehire", { seatId: "support.joe", flow: "desk", settings: { queue: "a" } }), - h.run("fire", { seatId: "support.joe" }), - ]); - const roster = await h.rows(ROSTER); - const seats = await h.rows(SEATS); - // Whichever landed second, the seat is either retired or re-hired, never half of each. - if (roster["support.joe"] === undefined) { - expect(h.live.held.has("acme.support.joe")).toBe(false); - } else { - expect(roster["support.joe"]).toMatchObject({ flow: "desk" }); - expect(seats["acme.support.joe"]).toMatchObject({ kind: "desk" }); - } - }); -}); - -describe("a broken org seat and the caller's own seat under one id", () => { - const OWNED = `~${encodeUserSegment("u1")}/research`; - - it("brokenSeats names whose row it is, and rehire with that owner repairs the org row, leaving the caller's alone", async () => { - const h = await harness({}, { userOwned: true }); - await h.seed("research", row({ seatId: "research", flow: "desk-clerk" })); - await h.seed(OWNED, row({ seatId: "research", flow: "desk", settings: { queue: "mine" }, ownerUserId: "u1" })); - const mine = (await h.rows(ROSTER))[OWNED]; - - const listed = (await h.run("brokenSeats", {})).output as Array<{ seatId: string; owner: string }>; - expect(listed).toEqual([expect.objectContaining({ seatId: "research", owner: "organization" })]); - - // Without the owner, two rows under the id is a refusal, not a guess. - expect((await h.run("rehire", { seatId: "research", flow: "desk", settings: { queue: "q" } })).error?.message).toMatch( - /names two seats/ - ); - - const rehired = await h.run("rehire", { seatId: "research", flow: "desk", settings: { queue: "q" }, owner: "organization" }); - expect(rehired.error).toBeUndefined(); - expect(rehired.output).toEqual({ seatId: "research", address: "acme.research" }); - expect((await h.rows(ROSTER))["research"]).toMatchObject({ flow: "desk", ownerUserId: null }); - expect((await h.rows(ROSTER))[OWNED]).toEqual(mine); - }); - - it("brokenSeats calls the caller's own broken row theirs, and rehire with owner \"me\" reaches it", async () => { - const h = await harness({}, { userOwned: true }); - await h.seed(OWNED, row({ seatId: "research", flow: "desk-clerk", ownerUserId: "u1" })); - const listed = (await h.run("brokenSeats", {})).output as Array<{ seatId: string; owner: string }>; - expect(listed).toEqual([expect.objectContaining({ seatId: "research", owner: "me" })]); - const rehired = await h.run("rehire", { seatId: "research", flow: "desk", settings: { queue: "q" }, owner: "me" }); - expect(rehired.output).toEqual({ seatId: "research", address: "acme.~u1.research" }); - }); -}); - -describe("an approved fire, when the caller gains a seat of their own under the id while asked", () => { - it("fires the organization's row the person approved, and leaves the caller's new one alone", async () => { - const live = liveRegistry(); - const { verbs } = buildSeatHire({ - workerFlows: kinds, - register: live.register, - unregister: live.unregister, - kindAt: live.kindAt, - instanceAt: (id: string) => live.held.get(id), - } as SeatHireCapabilityOptions); - const OWNED = `~${encodeUserSegment("u1")}/research`; - // The check and the fire made on Approve run in two requests, as they do - // around a suspension; the caller's own row appears in between. - let checked: SeatHireChecked | undefined; - const check = handler({ - name: "check", - inputSchema: z.object({ seatId: z.string() }), - outputSchema: z.unknown(), - execute: async (input, ctx) => { - checked = await verbs.fire.check(input, ctx); - return {}; - }, - }); - const fire = handler({ - name: "fire", - inputSchema: z.object({ seatId: z.string(), approved: z.boolean() }), - outputSchema: z.unknown(), - execute: async ({ approved, ...input }, ctx) => verbs.fire.run(input, ctx, approved ? checked : undefined), - }); - const ops = defineFlow({ - kind: "ops", - resources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection(), - [HIRED_ROSTER_PRIVATE_RESOURCE]: defineHiredRosterPrivateCollection(), - }, - actions: { check: { block: check }, fire: { block: fire } }, - } as never)(); - const state = createFlowState({ flows: { ops: ops as never }, stores: { default: { primary: inMemoryStores() } } }); - const runtime = await state.getRuntime(); - const stores = runtime.stores; - const seed = (key: string, value: Record) => - stores.resourceState.set("org", "acme", `${ROSTER}${key}`, value as never, "any" as never); - let n = 0; - const run = async (actionName: string, input: unknown) => { - n += 1; - return (await runAction({ - flow: ops, - actionName, - input, - userId: "u1", - orgId: "acme", - sessionId: `s-${n}`, - stores, - runtimeConfig: { ...runtime.runtimeConfig }, - } as never)) as { output?: unknown; error?: { message: string } }; - }; - - await seed("research", row({ seatId: "research", flow: "desk", settings: { queue: "org" }, incarnation: "inc-org" })); - expect((await run("check", { seatId: "research" })).error).toBeUndefined(); - expect(checked).toEqual({ kind: "desk", owner: null, incarnation: "inc-org" }); - await seed(OWNED, row({ seatId: "research", flow: "desk", settings: { queue: "mine" }, ownerUserId: "u1" })); - - // Unbound to an approval, two rows under the id is a refusal: what the - // approved owner is there to get past. - expect((await run("fire", { seatId: "research", approved: false })).error?.message).toMatch(/names two seats/); - - const fired = await run("fire", { seatId: "research", approved: true }); - expect(fired.error).toBeUndefined(); - expect(fired.output).toMatchObject({ seatId: "research", address: "acme.research" }); - const left = Object.keys(await stores.resourceState.getByPrefix("org", "acme", ROSTER)).map((key) => key.slice(ROSTER.length)); - expect(left).toEqual([OWNED]); - }); -}); diff --git a/packages/workforce/test/seat-resources.test.ts b/packages/workforce/test/seat-resources.test.ts index c6768f49c1..1f572b22d5 100644 --- a/packages/workforce/test/seat-resources.test.ts +++ b/packages/workforce/test/seat-resources.test.ts @@ -35,7 +35,7 @@ import { import type { FlowInstance } from "@flow-state-dev/core/types"; import { createExecutionContext, createInMemoryStores } from "@flow-state-dev/engine"; import { runForTest } from "@flow-state-dev/testing"; -import { hireWorkforce, type HireOptions } from "../src/hire"; +import { mintSeats, type HireOptions } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; import { SEAT_RESOURCES_KEY, @@ -152,7 +152,7 @@ function seat(id: string, declared: Record = {}): WorkerManifes } function hire(manifests: WorkerManifest[], options: Partial = {}): FlowInstance[] { - return hireWorkforce(manifests, { + return mintSeats(manifests, { workerFlows: { [DESK_KIND]: deskFlow as never }, documents: CATALOG, ...options @@ -389,7 +389,7 @@ describe("V5 · the second path — a seat that declares nothing is untouched (B }); it("hires with no `documents` passed at all, the way every caller before this did", () => { - const seats = hireWorkforce([seat("eng.unrestricted")], { workerFlows: { [DESK_KIND]: deskFlow as never } }); + const seats = mintSeats([seat("eng.unrestricted")], { workerFlows: { [DESK_KIND]: deskFlow as never } }); expect(seats).toHaveLength(1); expect([...seats[0]!.flowLevelResourceKeys].sort()).toEqual( @@ -418,7 +418,7 @@ describe("V6 · the kind's own machinery is never what a grant governs (BR-7, BR // install the document at flow level, where it wins the merge — a seat file // repointing its kind's wiring. expect(() => - hireWorkforce( + mintSeats( [ { id: "eng.lead", @@ -434,7 +434,7 @@ describe("V6 · the kind's own machinery is never what a grant governs (BR-7, BR it("the same kind hires a seat whose grant does NOT collide, and keeps the block's resource", async () => { // The control. Without it the refusal above is equally consistent with this // kind being unhireable for some reason that has nothing to do with the ref. - const seats = hireWorkforce( + const seats = mintSeats( [ { id: "eng.lead", @@ -514,7 +514,7 @@ describe("V8 · a grant never widens, and never resolves against nothing", () => actions: { ...workerDoor, run: { inputSchema: z.object({}), block: work } } }); const hireFiltered = (refs: unknown) => - hireWorkforce( + mintSeats( [{ id: "eng.lead", declared: { flow: "filtered-desk", description: "d", [SEAT_RESOURCES_KEY]: refs }, body: "" }], { workerFlows: { "filtered-desk": filteredFlow as never }, documents: CATALOG } ); @@ -527,7 +527,7 @@ describe("V8 · a grant never widens, and never resolves against nothing", () => it("a seat declaring `resources:` with no documents supplied refuses, naming what is missing (BR-18)", () => { expect(() => - hireWorkforce([seat("eng.lead", { [SEAT_RESOURCES_KEY]: [HANDBOOK] })], { + mintSeats([seat("eng.lead", { [SEAT_RESOURCES_KEY]: [HANDBOOK] })], { workerFlows: { [DESK_KIND]: deskFlow as never } }) ).toThrow(/no documents to resolve it against/); @@ -570,7 +570,7 @@ describe("V9 · the narrowing is checked on the seat that was BUILT", () => { }); const hireRestoring = (refs: unknown) => - hireWorkforce( + mintSeats( [{ id: "eng.lead", declared: { flow: "restoring-desk", description: "d", [SEAT_RESOURCES_KEY]: refs }, body: "" }], { workerFlows: { "restoring-desk": restoringFlow as never }, documents: CATALOG } ); @@ -617,7 +617,7 @@ describe("V9 · the narrowing is checked on the seat that was BUILT", () => { actions: { ...workerDoor, run: { inputSchema: z.object({}), block: work } } }); - const [lead] = hireWorkforce( + const [lead] = mintSeats( [{ id: "eng.lead", declared: { flow: "aliased-desk", description: "d", [SEAT_RESOURCES_KEY]: [] }, body: "" }], { workerFlows: { "aliased-desk": aliasedFlow as never }, documents: CATALOG } ); @@ -643,7 +643,7 @@ describe("a document's ref must hold that document on the kind", () => { actions: { ...workerDoor, run: { inputSchema: z.object({}), block: work } } }); const hireImpostor = (refs: unknown) => - hireWorkforce( + mintSeats( [{ id: "eng.lead", declared: { flow: "impostor-desk", description: "d", [SEAT_RESOURCES_KEY]: refs }, body: "" }], { workerFlows: { "impostor-desk": impostorFlow as never }, documents: CATALOG } ); @@ -662,7 +662,7 @@ describe("a document's ref must hold that document on the kind", () => { resources: { [HANDBOOK]: CATALOG[HANDBOOK]!, [PAYROLL]: CATALOG[PAYROLL]!, "audit-log": auditLog } as DeclaredResources, actions: { ...workerDoor, run: { inputSchema: z.object({}), block: work } } }); - const [lead] = hireWorkforce( + const [lead] = mintSeats( [{ id: "eng.lead", declared: { flow: "honest-desk", description: "d", [SEAT_RESOURCES_KEY]: [HANDBOOK] }, body: "" }], { workerFlows: { "honest-desk": honestFlow as never }, documents: CATALOG } ); diff --git a/packages/workforce/test/seat-skills.test.ts b/packages/workforce/test/seat-skills.test.ts index f64b4d1e51..b28ad71518 100644 --- a/packages/workforce/test/seat-skills.test.ts +++ b/packages/workforce/test/seat-skills.test.ts @@ -16,7 +16,7 @@ import { defineFlow, handler } from "@flow-state-dev/core"; import type { FlowInstance, InitialSkill } from "@flow-state-dev/core/types"; import { createTestContext, mockGenerator } from "@flow-state-dev/testing"; import { executeBlock } from "@flow-state-dev/engine"; -import { hireWorkforce, type HireOptions } from "../src/hire"; +import { mintSeats, type HireOptions } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; import { AGENT_KIND, defineAgentWorkerFlow } from "../src/agent-worker-flow"; import { workerConfigSchema } from "../src/worker-config"; @@ -31,12 +31,12 @@ function record(over: Partial & { id: string }): WorkerManifest } function hire(manifests: WorkerManifest[], kinds: HireOptions["workerFlows"] = {}): FlowInstance[] { - return hireWorkforce(manifests, { workerFlows: kinds }); + return mintSeats(manifests, { workerFlows: kinds }); } function refusalOf(manifests: WorkerManifest[], kinds: HireOptions["workerFlows"] = {}): string { try { - hireWorkforce(manifests, { workerFlows: kinds }); + mintSeats(manifests, { workerFlows: kinds }); } catch (error) { return error instanceof Error ? error.message : String(error); } diff --git a/packages/workforce/test/skills-resolve-from-principal.test.ts b/packages/workforce/test/skills-resolve-from-principal.test.ts index e1637eb2e4..5a76f181ed 100644 --- a/packages/workforce/test/skills-resolve-from-principal.test.ts +++ b/packages/workforce/test/skills-resolve-from-principal.test.ts @@ -14,7 +14,7 @@ import { DEFAULT_ORG_ID } from "@flow-state-dev/core"; import type { FlowInstance, InitialSkill, ResolvePrincipalFn } from "@flow-state-dev/core/types"; import { createFlowState, inMemoryStores } from "@flow-state-dev/engine"; import { createMockModelResolver, mockGenerator } from "@flow-state-dev/testing"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; import { AGENT_KIND, defineAgentWorkerFlow } from "../src/agent-worker-flow"; import type { WorkerManifest } from "../src/manifest"; @@ -100,7 +100,7 @@ async function ask(seat: FlowInstance, sessionId: string): Promise { function hireSeat(authentication?: FlowInstance["authentication"]): FlowInstance { const kind = defineAgentWorkerFlow(); - const [seat] = hireWorkforce([record()], { workerFlows: { [AGENT_KIND]: kind } }); + const [seat] = mintSeats([record()], { workerFlows: { [AGENT_KIND]: kind } }); if (authentication !== undefined) { Object.assign(seat!, { authentication }); } diff --git a/packages/workforce/test/team-instructions-seam.test.ts b/packages/workforce/test/team-instructions-seam.test.ts index cd7eac2547..abe970ca33 100644 --- a/packages/workforce/test/team-instructions-seam.test.ts +++ b/packages/workforce/test/team-instructions-seam.test.ts @@ -29,7 +29,7 @@ import type { FlowInstance } from "@flow-state-dev/core/types"; import { createInMemoryStores } from "@flow-state-dev/engine"; import { mockGenerator, testFlow } from "@flow-state-dev/testing"; import { z } from "zod"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; import { readTeamsDirectory } from "../src/loader/read-teams-directory"; import { readWorkforce } from "../src/loader/read-workforce"; import { readWorkforceDirectory } from "../src/loader/read-workforce-directory"; @@ -79,7 +79,7 @@ const record = (over: Partial = {}): WorkerManifest => ({ const refusalOf = (roster: WorkerManifest[]): string => { try { - hireWorkforce(roster); + mintSeats(roster); return ""; } catch (error) { return error instanceof Error ? error.message : String(error); @@ -163,14 +163,14 @@ describe("three doors, one constant", () => { * having it is worth having for both, as its own change. */ it("does not refuse the record FIELD, which is the loader's own channel", () => { - const [seat] = hireWorkforce([record({ teamInstructions: "Built by hand, not read." })]); + const [seat] = mintSeats([record({ teamInstructions: "Built by hand, not read." })]); expect((seat!.config as Record)[TEAM_INSTRUCTIONS_KEY]).toBe( "Built by hand, not read.", ); // The sibling field behaves the same way, which is what makes the line // above a convention rather than an oversight in this one key. - const [withSkills] = hireWorkforce([ + const [withSkills] = mintSeats([ record({ id: "engineering.scribe", skills: [{ name: "hand-built", skillMd: "---\n---\n" }] }), ]); expect( @@ -225,7 +225,7 @@ describe("the prompt seam", () => { * green for a seam that never wired the helper to the prompt slot at all. */ async function systemPromptOf(manifest: WorkerManifest): Promise { - const [seat] = hireWorkforce([manifest]); + const [seat] = mintSeats([manifest]); const answer = mockGenerator({ name: "agent-answer", script: [{ text: "noted" }] }); const stores = createInMemoryStores(); const sessionId = "seam-session"; @@ -345,7 +345,7 @@ describe("a kind that ignores the layer", () => { }, }); - const seats = hireWorkforce( + const seats = mintSeats( [ record({ id: "engineering.lead", @@ -388,7 +388,7 @@ describe("end to end, from files", () => { const { workers, teamErrors } = await readWorkforce(root); expect(teamErrors).toEqual([]); - const seats = hireWorkforce(workers); + const seats = mintSeats(workers); const config = (id: string) => seats.find((seat) => seat.id === id)!.config as Record; diff --git a/packages/workforce/test/wake-member-seats.test.ts b/packages/workforce/test/wake-member-seats.test.ts index d9e6df9143..0f2c949c78 100644 --- a/packages/workforce/test/wake-member-seats.test.ts +++ b/packages/workforce/test/wake-member-seats.test.ts @@ -47,13 +47,13 @@ import { mailboxNotifyInputSchema, defineAgentWorkerFlow, defineMailboxFlow, - hireWorkforce, wakeMemberSeats, workerConfigSchema, type MailboxNotifyInput, - type WorkerManifest + type WorkerManifest, } from "../src/index"; -import { hiredSeatManifest, toHiredSeatRow } from "../src/roster/rows"; +import { mintSeats } from "../src/hire"; +import { createWorkerInstallation } from "../src/workers/installation"; import { workerDoor } from "./worker-door"; const USER_ID = "u_wake"; @@ -125,13 +125,6 @@ function worker(id: string, flow?: string): WorkerManifest { return { id, declared: flow === undefined ? {} : { flow }, body: "" }; } -/** A seat minted from a stored roster row, as the boot reload does: at `.`. */ -function reloaded(orgId: string, seatId: string, flow: string, ownerUserId?: string): WorkerManifest { - const bound = hiredSeatManifest(orgId, toHiredSeatRow({ seatId, flow, ownerUserId })); - if (!("manifest" in bound)) throw new Error(bound.problem); - return bound.manifest; -} - /** A fallback that records each member it ran for, and on which post. */ function recordingFallback() { const ran: string[] = []; @@ -268,10 +261,49 @@ function bySeat(heard: Heard[]): Record { return out; } +describe("wakeMemberSeats · workers on one shared copy (FIX-1788)", () => { + it("wakes two workers on one agent copy, each in a conversation of its own, created naming its worker", async () => { + let flows: Record = {}; + const installation = createWorkerInstallation({ + standardWorkers: [ + { id: "desk.amy", declared: {}, body: "You are Amy." }, + { id: "desk.bo", declared: {}, body: "You are Bo." } + ], + workerFlows: () => flows as never + }); + const agent = defineAgentWorkerFlow({ installation }); + flows = { agent }; + const copy = agent({ id: "agent" }) as unknown as FlowInstance; + const { mailbox, state } = host([copy], wakeMemberSeats([copy], { installation })); + try { + const runtime = await state.getRuntime(); + await bind(runtime.stores, "desk.front", ["desk.amy", "desk.bo"]); + await post(runtime, mailbox, "desk.front", "first"); + await settle(runtime, "desk.front", 1); + await post(runtime, mailbox, "desk.front", "second"); + await settle(runtime, "desk.front", 2); + + const conversations = (await runtime.stores.session.list({ flowId: "agent", parentage: "all" })).filter( + (s) => s.parentSessionId === "desk.front" + ); + // Two workers, two conversations, each created naming its own worker. + expect(conversations.map((s) => s.state.workerId).sort()).toEqual(["desk.amy", "desk.bo"]); + expect(new Set(conversations.map((s) => s.id)).size).toBe(2); + // Each heard both posts in its own conversation, and every run completed. + for (const conversation of conversations) { + const requests = await runtime.stores.request.list({ sessionId: conversation.id, withItems: true }); + expect(requests.map((r) => r.status)).toEqual(["completed", "completed"]); + } + } finally { + await state.dispose(); + } + }); +}); + describe("wakeMemberSeats · who a post wakes", () => { it("runs each declaring member once per post, one conversation per seat, and nobody else (BR-1, BR-2, BR-6, BR-8, BR-9, BR-12)", async () => { const { heard, map } = kinds(); - const seats = hireWorkforce( + const seats = mintSeats( [worker("desk.amy"), worker("desk.ivy", "listener"), worker("desk.oz", "listener"), worker("desk.ned", "note"), worker("desk.idle", "listener")], { workerFlows: map } ); @@ -317,7 +349,7 @@ describe("wakeMemberSeats · who a post wakes", () => { it("wakes hearing members when a public post claims a hire address as author", async () => { const { heard, map } = kinds(); - const seats = hireWorkforce( + const seats = mintSeats( [worker("desk.amy"), worker("desk.ivy", "listener"), worker("desk.oz", "listener"), worker("desk.ned", "note")], { workerFlows: map } ); @@ -342,7 +374,7 @@ describe("wakeMemberSeats · who a post wakes", () => { it("wakes hearing members when a dispatched post claims a hire address as author", async () => { const { heard, map } = kinds(); - const seats = hireWorkforce( + const seats = mintSeats( [worker("desk.amy"), worker("desk.ivy", "listener"), worker("desk.oz", "listener"), worker("desk.ned", "note")], { workerFlows: map } ); @@ -366,7 +398,7 @@ describe("wakeMemberSeats · who a post wakes", () => { it("wakes nobody when the post arrives on the seat post action; the fallback stays with members that could not wake", async () => { const { heard, map } = kinds(); - const seats = hireWorkforce( + const seats = mintSeats( [worker("desk.amy"), worker("desk.ivy", "listener"), worker("desk.oz", "listener"), worker("desk.ned", "note")], { workerFlows: map } ); @@ -401,7 +433,7 @@ describe("wakeMemberSeats · who a post wakes", () => { it("gives a member with no seat the fallback, and everyone the fallback when no seats are passed (BR-4, BR-15)", async () => { const { heard, map } = kinds(); - const seats = hireWorkforce([worker("desk.ivy", "listener")], { workerFlows: map }); + const seats = mintSeats([worker("desk.ivy", "listener")], { workerFlows: map }); const fallback = recordingFallback(); const { mailbox, state } = host([], wakeMemberSeats([], { fallback: fallback.block }), seats); try { @@ -420,51 +452,10 @@ describe("wakeMemberSeats · who a post wakes", () => { }); describe("wakeMemberSeats · where a woken seat runs", () => { - it("wakes a seat the boot reload minted at ., by its logical id, in the post's organization (BR-5)", async () => { - const { heard, map } = kinds(); - const seats = hireWorkforce([reloaded("acme", "desk.rex", "listener"), reloaded("globex", "desk.rex", "listener")], { - workerFlows: map - }); - expect(seats.map((s) => s.id).sort()).toEqual(["acme.desk.rex", "globex.desk.rex"]); - const { mailbox, state } = host(seats, wakeMemberSeats(seats)); - try { - const runtime = await state.getRuntime(); - await bind(runtime.stores, "desk.front", ["desk.rex"], "acme"); - await post(runtime, mailbox, "desk.front", "for acme", { orgId: "acme" }); - await settle(runtime, "desk.front", 1); - - expect(heard.map((h) => `${h.seat}|${h.body}`)).toEqual(["acme.desk.rex|for acme"]); - } finally { - await state.dispose(); - } - }); - - it("wakes the caller's own seat when users of one organization each own a seat of that id (BR-5)", async () => { - const { heard, map } = kinds(); - // Another user's seat first, so a pick by organization alone takes the wrong one. - const seats = hireWorkforce( - [reloaded("acme", "desk.rex", "listener", "u_other"), reloaded("acme", "desk.rex", "listener", USER_ID)], - { workerFlows: map } - ); - const fallback = recordingFallback(); - const { mailbox, state } = host(seats, wakeMemberSeats(seats, { fallback: fallback.block })); - try { - const runtime = await state.getRuntime(); - await bind(runtime.stores, "desk.front", ["desk.rex"], "acme"); - await post(runtime, mailbox, "desk.front", "for me", { orgId: "acme" }); - await settle(runtime, "desk.front", 1); - - const mine = seats.find((s) => s.ownerPin?.userId === USER_ID)!.id; - expect(heard.map((h) => `${h.seat}|${h.body}`)).toEqual([`${mine}|for me`]); - expect(fallback.ran).toEqual([]); - } finally { - await state.dispose(); - } - }); it("keeps one conversation per mailbox for a seat in two mailboxes (BR-10)", async () => { const { heard, map } = kinds(); - const seats = hireWorkforce([worker("desk.ivy", "listener")], { workerFlows: map }); + const seats = mintSeats([worker("desk.ivy", "listener")], { workerFlows: map }); const { mailbox, state } = host(seats, wakeMemberSeats(seats)); try { const runtime = await state.getRuntime(); @@ -487,7 +478,7 @@ describe("wakeMemberSeats · where a woken seat runs", () => { it("fails one member's delivery when its entry refuses the post, and still runs the others (BR-7)", async () => { const { heard, map } = kinds(); - const seats = hireWorkforce([worker("desk.pip", "picky"), worker("desk.ivy", "listener")], { workerFlows: map }); + const seats = mintSeats([worker("desk.pip", "picky"), worker("desk.ivy", "listener")], { workerFlows: map }); const { mailbox, state } = host(seats, wakeMemberSeats(seats)); try { const runtime = await state.getRuntime(); diff --git a/packages/workforce/test/worker-config.test.ts b/packages/workforce/test/worker-config.test.ts index 305a5ae34d..00c2c46cad 100644 --- a/packages/workforce/test/worker-config.test.ts +++ b/packages/workforce/test/worker-config.test.ts @@ -11,7 +11,7 @@ import { describe, expect, it } from "vitest"; import { z } from "zod"; import { defineFlow, handler } from "@flow-state-dev/core"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; import { INSTRUCTIONS_KEY, SEAT_SKILLS_KEY, SEAT_TOOLS_KEY, TEAM_INSTRUCTIONS_KEY } from "../src/manifest"; import { workerConfigSchema, type WorkerConfig } from "../src/worker-config"; @@ -32,7 +32,7 @@ function record(over: Partial & { id: string }): WorkerManifest function refusalOf(manifests: WorkerManifest[], kinds: Record): string { try { - hireWorkforce(manifests, { workerFlows: kinds }); + mintSeats(manifests, { workerFlows: kinds }); } catch (error) { return error instanceof Error ? error.message : String(error); } @@ -109,7 +109,7 @@ describe("workerConfigSchema — what composing it buys a kind", () => { const kinds = { "contract-triage": triage, "contract-triage-strict": strictTriage } as never; it("hires a seat and hands it both its own setting and the contract's", () => { - const [seat] = hireWorkforce( + const [seat] = mintSeats( [record({ id: "support.desk", declared: { flow: "contract-triage", desk: "mezzanine" } })], { workerFlows: kinds } ); diff --git a/packages/workforce/test/worker-document-fence.test.ts b/packages/workforce/test/worker-document-fence.test.ts index 3874afd728..b6f8665b57 100644 --- a/packages/workforce/test/worker-document-fence.test.ts +++ b/packages/workforce/test/worker-document-fence.test.ts @@ -32,7 +32,7 @@ import { z } from "zod"; import { defineFlow, handler } from "@flow-state-dev/core"; import { createExecutionContext, createInMemoryStores, toBareStates } from "@flow-state-dev/engine"; import { readResourcesDirectory } from "../src/loader"; -import { hireWorkforce } from "../src/hire"; +import { mintSeats } from "../src/hire"; import { workerConfigSchema } from "../src/worker-config"; import { resourcesFromDocs } from "../src/resources-from-docs"; import { DERIVED_RESOURCE_KEYS, type WorkerManifest } from "../src/manifest"; @@ -128,7 +128,7 @@ async function hireTwoSeatsOver(root: string) { // The production factory, not a hand-built pair of instances: what makes the // fence work is that `hireWorkforce` mints one flow INSTANCE ID per seat, and // a hand-built pair would be assuming exactly the thing under test. - const seats = hireWorkforce(manifests, { workerFlows: { recon: reconFlow } }); + const seats = mintSeats(manifests, { workerFlows: { recon: reconFlow } }); expect(seats.map((s) => s.id)).toEqual([ALICE, BOB]); // Both seats really carry the documents. Without this, a roster hired into diff --git a/packages/workforce/test/worker-flow-registration.test.ts b/packages/workforce/test/worker-flow-registration.test.ts index 27c093cd94..1b2dd87e3b 100644 --- a/packages/workforce/test/worker-flow-registration.test.ts +++ b/packages/workforce/test/worker-flow-registration.test.ts @@ -13,16 +13,9 @@ import { z } from "zod"; import { defineFlow, defineResourceCollection, handler } from "@flow-state-dev/core"; import { createInMemoryStores, executeBlock } from "@flow-state-dev/engine"; import { createTestContext } from "@flow-state-dev/testing"; -import { defineSeatInventoryCollection } from "../src/inventory/collections"; -import { defineHiredRosterCollection } from "../src/roster/collections"; -import { createSeatHireBlocks, HIRED_ROSTER_RESOURCE, SEAT_INVENTORY_RESOURCE } from "../src/seat-hire-blocks"; import { defineAgentWorkerFlow } from "../src/agent-worker-flow"; -import { hireWorkforce, type HireOptions } from "../src/hire"; +import { mintSeats, type HireOptions } from "../src/hire"; import type { WorkerManifest } from "../src/manifest"; -import { checkHiredSeatRow } from "../src/roster/check"; -import { HIRED_ROSTER_PREFIX } from "../src/roster/collections"; -import { reloadHiredSeats } from "../src/roster/reload"; -import { toHiredSeatRow } from "../src/roster/rows"; import { workerConfigSchema } from "../src/worker-config"; const message = z.object({ message: z.string() }); @@ -54,17 +47,6 @@ function standard(id: string, flow?: string): WorkerManifest { return { id, declared: flow === undefined ? {} : { flow }, body: "" }; } -/** A hired worker: a runtime hire or a stored row, so it carries an owner pin. */ -function own(id: string, flow?: string): WorkerManifest { - return { - id: `acme.~bob.${id}`, - declared: flow === undefined ? {} : { flow }, - body: "", - seatId: id, - ownerPin: { orgId: "acme", userId: "bob" } - }; -} - function refusalOf(run: () => unknown): string { try { run(); @@ -78,7 +60,7 @@ describe("registering worker flows (V2)", () => { it("BR-7 · refuses every broken flow in one error, and hires nothing", () => { let seats: unknown; const message = refusalOf(() => { - seats = hireWorkforce([standard("support.ada"), standard("support.tri", "triage")], { + seats = mintSeats([standard("support.ada"), standard("support.tri", "triage")], { workerFlows: { triage, doorless, numbered } }); }); @@ -91,14 +73,14 @@ describe("registering worker flows (V2)", () => { }); it("refuses a broken flow before any worker, an empty roster included", () => { - expect(refusalOf(() => hireWorkforce([], { workerFlows: { doorless } }))).toContain('"doorless"'); + expect(refusalOf(() => mintSeats([], { workerFlows: { doorless } }))).toContain('"doorless"'); }); it("V7 · no worker flow hires with no door or two", () => { - expect(refusalOf(() => hireWorkforce([standard("support.d", "doorless")], { workerFlows: { doorless } }))).toContain( + expect(refusalOf(() => mintSeats([standard("support.d", "doorless")], { workerFlows: { doorless } }))).toContain( "no door" ); - const two = refusalOf(() => hireWorkforce([standard("support.t", "two-doors")], { workerFlows: { "two-doors": twoDoors } })); + const two = refusalOf(() => mintSeats([standard("support.t", "two-doors")], { workerFlows: { "two-doors": twoDoors } })); expect(two).toContain('"ask"'); expect(two).toContain('"say"'); }); @@ -109,18 +91,18 @@ describe("registering worker flows (V2)", () => { board: defineResourceCollection({ pattern: "board/*", scope: "org", stateSchema: z.object({ text: z.string() }) }) } }); - const seats = hireWorkforce([standard("ops.keeper", "org-keeper")], { workerFlows: { "org-keeper": orgKeeper } }); + const seats = mintSeats([standard("ops.keeper", "org-keeper")], { workerFlows: { "org-keeper": orgKeeper } }); expect(seats.map((seat) => seat.kind)).toEqual(["org-keeper"]); }); it("BR-10 · with no flows of its own, the app registers the built-in agent, which passes", () => { - expect(hireWorkforce([standard("support.ada")]).map((seat) => seat.kind)).toEqual(["agent"]); - expect(hireWorkforce([standard("support.ada")], { workerFlows: {} }).map((seat) => seat.kind)).toEqual(["agent"]); + expect(mintSeats([standard("support.ada")]).map((seat) => seat.kind)).toEqual(["agent"]); + expect(mintSeats([standard("support.ada")], { workerFlows: {} }).map((seat) => seat.kind)).toEqual(["agent"]); }); it("BR-9 · registers the built-in agent with mailbox task lists, with no warning", () => { const agent = defineAgentWorkerFlow({ taskLists: ["front-desk.queue"] }); - const seats = hireWorkforce([standard("support.ada")], { workerFlows: { agent } as never }); + const seats = mintSeats([standard("support.ada")], { workerFlows: { agent } as never }); expect(seats.map((seat) => seat.kind)).toEqual(["agent"]); }); }); @@ -129,114 +111,11 @@ describe("which workers may run on a flow (V3)", () => { const kept: HireOptions["workerFlows"] = { triage, coordinator: { flow: coordinator, standardOnly: true } }; it("BR-11 · a worker naming a registered flow runs on it", () => { - expect(hireWorkforce([standard("support.tri", "triage")], { workerFlows: kept }).map((s) => s.kind)).toEqual([ + expect(mintSeats([standard("support.tri", "triage")], { workerFlows: kept }).map((s) => s.kind)).toEqual([ "triage" ]); }); - it("BR-14 · refuses a hired worker naming a standard-only flow, and a declared worker on it runs", () => { - const message = refusalOf(() => hireWorkforce([own("coord", "coordinator")], { workerFlows: kept })); - expect(message).toContain('"coordinator"'); - expect(message).toContain("declared workers"); - const seats = hireWorkforce([standard("ops.coord", "coordinator")], { workerFlows: kept }); - expect(seats.map((seat) => seat.kind)).toEqual(["coordinator"]); - }); - - it("a hired worker runs on a flow that isn't kept", () => { - expect(hireWorkforce([own("tri", "triage")], { workerFlows: kept }).map((s) => s.kind)).toEqual(["triage"]); - }); - - it("BR-13 · a worker naming no flow is an agent worker, and standard-only is checked after that default", () => { - const agentKept: HireOptions["workerFlows"] = { agent: { flow: defineAgentWorkerFlow() as never, standardOnly: true } }; - const message = refusalOf(() => hireWorkforce([own("helper")], { workerFlows: agentKept })); - expect(message).toContain('"agent"'); - expect(message).toContain("declared workers"); - // Named directly, the same refusal. - expect(refusalOf(() => hireWorkforce([own("helper", "agent")], { workerFlows: agentKept }))).toContain( - "declared workers" - ); - // A declared worker naming no flow still runs on it. - expect(hireWorkforce([standard("support.ada")], { workerFlows: agentKept }).map((s) => s.kind)).toEqual(["agent"]); - }); - - it("BR-16 · a replacement agent passes the same checks, and keeps the app's flag", () => { - const replacement = workerFlow("agent"); - const replaced: HireOptions["workerFlows"] = { agent: { flow: replacement, standardOnly: true } }; - expect(refusalOf(() => hireWorkforce([own("helper")], { workerFlows: replaced }))).toContain("declared workers"); - const seats = hireWorkforce([standard("support.ada")], { workerFlows: replaced }); - expect(seats[0]!.kind).toBe("agent"); - expect(seats[0]!.actions).toHaveProperty("run"); - - const brokenReplacement = workerFlow("agent", { actions: { run: { inputSchema: note, block: work } } }); - expect(refusalOf(() => hireWorkforce([standard("support.ada")], { workerFlows: { agent: brokenReplacement } }))).toContain( - 'worker flow "agent" has no door' - ); - }); -}); - -describe("a runtime hire on a standard-only flow (S3, every path)", () => { - it("BR-14 · refuses a hired worker's hire, writes no roster row, and registers nothing", async () => { - const registered: string[] = []; - const { hire } = createSeatHireBlocks({ - workerFlows: { coordinator: { flow: coordinator, standardOnly: true } }, - register: (seat) => void registered.push(seat.id), - unregister: () => true - }); - const { ctx } = await createTestContext({ - orgId: "acme", - sessionId: "hire-session", - declaredResources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection() - } - }); - const result = await executeBlock({ block: hire, input: { seatId: "coord", flow: "coordinator" }, ctx }); - expect(String(result.error?.message ?? result.error)).toContain("declared workers"); - const roster = await (ctx.resources as Record }>)[HIRED_ROSTER_RESOURCE]!.list(); - expect(roster).toEqual([]); - expect(registered).toEqual([]); - - // The same tool hires onto a flow that isn't kept. - const { hire: open } = createSeatHireBlocks({ - workerFlows: { triage }, - register: (seat) => void registered.push(seat.id), - unregister: () => true - }); - expect((await executeBlock({ block: open, input: { seatId: "tri", flow: "triage" }, ctx })).error).toBeUndefined(); - expect(registered).toEqual(["acme.tri"]); - }); -}); - -describe("a stored worker on a flow that became standard-only (V4)", () => { - const row = toHiredSeatRow({ seatId: "coord", flow: "coordinator", owningOrgId: "acme", ownerUserId: "bob" }); - - it("BR-15 · is reported refused with the standard-only sentence", () => { - const checked = checkHiredSeatRow("acme", row, { coordinator: { flow: coordinator, standardOnly: true } }); - expect(checked.ok).toBe(false); - if (!checked.ok) { - expect(checked.reason).toBe("refused"); - expect(checked.detail).toContain("declared workers"); - } - // The same row runs once the mark is removed. - expect(checkHiredSeatRow("acme", row, { coordinator }).ok).toBe(true); - }); - - it("BR-15 · is skipped at boot and left byte-identical on disk", async () => { - const stores = createInMemoryStores(); - const key = `${HIRED_ROSTER_PREFIX}coord`; - await stores.resourceState.set("org", "acme", key, row as never, "any" as never); - const before = JSON.stringify(await stores.resourceState.get("org", "acme", key)); - - const reload = await reloadHiredSeats({ - stores, - orgIds: ["acme"], - workerFlows: { coordinator: { flow: coordinator, standardOnly: true } } - }); - expect(reload.seats).toEqual([]); - expect(reload.problems).toHaveLength(1); - expect(JSON.stringify(reload.problems[0])).toContain("declared workers"); - expect(JSON.stringify(await stores.resourceState.get("org", "acme", key))).toBe(before); - }); }); describe("a block requirement the registration check can't reach", () => { @@ -258,7 +137,7 @@ describe("a block requirement the registration check can't reach", () => { it("is refused when a worker is hired on the flow, naming the block, and nothing is hired", () => { let seats: unknown; const refusal = refusalOf(() => { - seats = hireWorkforce([{ id: "support.front", declared: { flow: "desk", desk: "front" }, body: "" }], { + seats = mintSeats([{ id: "support.front", declared: { flow: "desk", desk: "front" }, body: "" }], { workerFlows: { desk } }); }); diff --git a/packages/workforce/test/worker-registration.test.ts b/packages/workforce/test/worker-registration.test.ts new file mode 100644 index 0000000000..6b3a48dc79 --- /dev/null +++ b/packages/workforce/test/worker-registration.test.ts @@ -0,0 +1,122 @@ +/** + * `hireWorkforce`: one copy per worker flow, and the roster flow (BR-26, V9). + * + * Workers are data, so hiring the installation registers the same copies + * however many workers it holds: one per flow, at the flow's kind, none per + * worker and none pinned to an owner. A flow that doesn't declare the + * installation's session is refused by name, since its sessions would run no + * checked worker. + */ +import { describe, expect, it } from "vitest"; +import { defineFlow, handler } from "@flow-state-dev/core"; +import { createFlowRegistry } from "@flow-state-dev/engine"; +import { z } from "zod"; +import { createWorkerInstallation, hireWorkforce, ROSTER_FLOW_KIND, workerFlow, type WorkerInstallation } from "../src/index"; +import { workerConfigSchema } from "../src/worker-config"; + +const door = z.object({ message: z.string() }); + +function researchFlow(installation: WorkerInstallation | undefined) { + return defineFlow({ + kind: "research", + configSchema: workerConfigSchema(), + ...(installation !== undefined ? { session: installation.session(), resources: { ...installation.resources } } : {}), + actions: { + run: { + inputSchema: door, + userMessage: (input: { message: string }) => input.message, + block: handler({ name: "research-run", inputSchema: door, execute: (input) => input }) + } + } + }); +} + +function installation(workers: number, bound = true) { + let flows: Record = {}; + const made = createWorkerInstallation({ + standardWorkers: Array.from({ length: workers }, (_, i) => ({ + id: `desk.w${i}`, + declared: i % 2 === 0 ? {} : { flow: "research" }, + body: `Worker ${i}.` + })), + workerFlows: () => flows as never + }); + flows = { research: researchFlow(bound ? made : undefined) }; + return made; +} + +describe("hireWorkforce", () => { + it("registers one copy per flow and the roster flow, the same for two workers as for forty, with no pin", () => { + for (const count of [2, 40]) { + const registry = createFlowRegistry(); + for (const copy of hireWorkforce(installation(count))) registry.register(copy); + expect(registry.list().map((flow) => flow.id).sort()).toEqual(["agent", "research", ROSTER_FLOW_KIND]); + expect(registry.list().map((flow) => registry.pinOf(flow.id))).toEqual([undefined, undefined, undefined]); + } + }); + + it("registers the built-in agent bound to the installation when the app passes none", () => { + const made = installation(2); + const agent = hireWorkforce(made).find((copy) => copy.id === "agent")!; + expect((agent.session as { createCheck?: unknown } | undefined)?.createCheck).toBe(made.createCheck); + }); + + it("refuses a worker flow that doesn't declare the installation's session, naming it", () => { + expect(() => hireWorkforce(installation(2, false))).toThrow( + /worker flow "research" doesn't declare this installation's session/ + ); + }); + + it("registers nothing while a standard worker would be refused on its first turn, naming it", () => { + // A short roster that still runs is the failure: the one worker's unknown + // tool refuses the whole installation, by the worker's id and the tool. + let flows: Record = {}; + const made = createWorkerInstallation({ + standardWorkers: [ + { id: "desk.ok", declared: {}, body: "Fine." }, + { id: "desk.typo", declared: { tools: ["no-such-tool"] }, body: "Names a tool nothing registers." } + ], + workerFlows: () => flows as never + }); + flows = { research: researchFlow(made) }; + expect(() => hireWorkforce(made)).toThrow(/nothing was registered[\s\S]*worker "desk\.typo"[\s\S]*no-such-tool/); + expect(made.standardWorkerProblems()).toHaveLength(1); + }); + + it("refuses a worker flow that misses the contract, even with no worker on it, naming it", () => { + let flows: Record = {}; + const made = createWorkerInstallation({ + standardWorkers: [{ id: "desk.ok", declared: { flow: "research" }, body: "Fine." }], + workerFlows: () => flows as never + }); + const doorless = defineFlow({ + kind: "doorless", + configSchema: workerConfigSchema(), + session: made.session(), + resources: { ...made.resources }, + actions: { work: { inputSchema: door, block: handler({ name: "doorless-work", inputSchema: door, execute: (input) => input }) } } + }); + flows = { research: researchFlow(made), doorless }; + expect(() => hireWorkforce(made)).toThrow(/refused 1 worker flow \("doorless"\); nothing was hired[\s\S]*no door/); + }); + + it("builds a workerFlow(...) entry on its installation, once, and registers it like any flow", () => { + // A flow in its own file has no installation to import: its module + // exports a builder, and the installation builds it with itself. + const builds: WorkerInstallation[] = []; + const research = workerFlow((installation) => { + builds.push(installation); + return researchFlow(installation); + }); + const made = createWorkerInstallation({ + standardWorkers: [{ id: "desk.r", declared: { flow: "research" }, body: "Research." }], + workerFlows: { research } + }); + const copies = hireWorkforce(made); + expect(copies.map((copy) => copy.id).sort()).toEqual(["agent", "research", ROSTER_FLOW_KIND]); + const copy = copies.find((c) => c.id === "research")!; + expect((copy.session as { createCheck?: unknown } | undefined)?.createCheck).toBe(made.createCheck); + expect(made.workerFlows().research!.flow).toBe(made.workerFlows().research!.flow); + expect(builds).toEqual([made]); + }); +}); diff --git a/packages/workforce/test/worker-task-hand-over.test.ts b/packages/workforce/test/worker-task-hand-over.test.ts index affb152ca0..5a48911136 100644 --- a/packages/workforce/test/worker-task-hand-over.test.ts +++ b/packages/workforce/test/worker-task-hand-over.test.ts @@ -1,17 +1,16 @@ /** * A task names a worker, and the list hands it to that worker. * - * Two halves. The lookup on its own, over a registry this test holds, so each - * rule about who a name reaches is one assertion: a declared worker, one hired - * for the organization, one a member hired for themselves, nobody, two at - * once, one in another organization, one whose kind takes no tasks, a hire - * made after start, a fired worker. + * Two halves. The lookup on its own, over an installation, so each rule about + * who a name reaches is one assertion: a standard worker, nobody, a user's + * own worker, one whose flow takes no tasks. * * Then the whole path on a real host: a mailbox with one task list that no - * worker kind was wired to, a coordinator board over it whose fallback asks - * the lookup, and `agent` workers whose kind takes tasks from the mailbox's - * lists. A task filed for a worker hired after start runs on that worker's - * own flow, as one turn holding the task's goal, and settles with the answer. + * worker flow was wired to, a coordinator board over it whose fallback asks + * the lookup, and the one `agent` copy taking tasks from the mailbox's lists. + * A task filed for a worker runs on the shared copy, in a session of its own + * created naming the worker, as one turn holding the task's goal, and settles + * with the answer. */ import { describe, expect, it } from "vitest"; import { DEFAULT_ORG_ID, defineFlow, dispatcher, handler } from "@flow-state-dev/core"; @@ -22,17 +21,16 @@ import { taskBoard } from "@flow-state-dev/orchestration/task-board"; import { createMockModelResolver, mockGenerator } from "@flow-state-dev/testing"; import { z } from "zod"; import { + createWorkerInstallation, createWorkerLookup, defineAgentWorkerFlow, defineMailboxFlow, hireWorkforce, - hiredSeatManifest, mailboxBoard, mailboxInstances, openMailboxes, - seatAddress, - toHiredSeatRow, type MailboxManifest, + type WorkerInstallation, type WorkerLookup } from "../src/index"; import { workerConfigSchema } from "../src/worker-config"; @@ -40,156 +38,78 @@ import { workerDoor } from "./worker-door"; const ORG = DEFAULT_ORG_ID; const USER_ID = "u_coordinator"; - -function run(orgId: string | undefined, userId?: string): BlockContext { - return { - ...(orgId === undefined ? {} : { org: { identity: { orgId } } }), - // The member is the session's owner, as the hire tool reads it. - session: { identity: userId === undefined ? {} : { userId } } - } as unknown as BlockContext; -} - -/** A flow kind with no task door: an app's own worker kind that takes no tasks. */ -const deskClerk = defineFlow({ - kind: "desk-clerk", - cardinality: "collection", - configSchema: workerConfigSchema(), - actions: { ...workerDoor, - answer: { - inputSchema: z.object({ note: z.string() }), - block: handler({ - name: "desk-answer", +const ctx = {} as BlockContext; + +/** An app's own worker flow with no task entry, bound to `installation`. */ +function deskClerk(installation: WorkerInstallation) { + return defineFlow({ + kind: "desk-clerk", + configSchema: workerConfigSchema(), + session: installation.session(), + resources: { ...installation.resources }, + actions: { + ...workerDoor, + answer: { inputSchema: z.object({ note: z.string() }), - outputSchema: z.object({ note: z.string() }), - execute: (input) => input - }) + block: handler({ + name: "desk-answer", + inputSchema: z.object({ note: z.string() }), + outputSchema: z.object({ note: z.string() }), + execute: (input) => input + }) + } } - } -}); - -describe("which worker a name on a task means", () => { - const list = mailboxBoard("ops.desk", "work"); - const kinds = { - agent: defineAgentWorkerFlow({ taskLists: [list.id] }), - "desk-clerk": deskClerk - } as never; - - /** A registry this test holds, standing in for the host's. */ - function registry() { - const flows = new Map(); - const add = (seat: FlowInstance) => flows.set(seat.id, seat); - const hire = (orgId: string, seatId: string, flow = "agent", ownerUserId: string | null = null) => { - const bound = hiredSeatManifest( - orgId, - toHiredSeatRow({ seatId, flow, instructions: "Hired.", owningOrgId: orgId, ownerUserId }) - ); - if (!("manifest" in bound)) throw new Error(bound.problem); - const [seat] = hireWorkforce([bound.manifest], { workerFlows: kinds }); - add(seat!); - return seat!; - }; - const [declared] = hireWorkforce([{ id: "eng.auditor", declared: {}, body: "You audit." }], { workerFlows: kinds }); - add(declared!); - const lookup = createWorkerLookup({ instanceAt: (id) => flows.get(id), declared: ["eng.auditor"] }); - return { flows, hire, lookup }; - } - - it("finds a worker the files declare, by its name", () => { - const { lookup } = registry(); - expect(lookup.find("eng.auditor", run(ORG))).toEqual({ found: true, flowId: "eng.auditor" }); - }); - - it("finds a worker hired after the lookup was built, and loses it when it is fired", () => { - const { flows, hire, lookup } = registry(); - expect(lookup.find("frontend", run("acme")).found).toBe(false); - const seat = hire("acme", "frontend"); - expect(lookup.find("frontend", run("acme"))).toEqual({ found: true, flowId: seat.id }); - expect(seat.id).toBe(seatAddress("acme", "frontend")); - flows.delete(seat.id); - const fired = lookup.find("frontend", run("acme")); - expect(fired).toMatchObject({ found: false, reason: "not-found" }); - }); - - it("finds a member's own worker for that member only", () => { - const { hire, lookup } = registry(); - const own = hire("acme", "scout", "agent", "alice"); - expect(lookup.find("scout", run("acme", "alice"))).toEqual({ found: true, flowId: own.id }); - expect(lookup.find("scout", run("acme", "bob"))).toMatchObject({ found: false, reason: "not-found" }); }); +} - it("hands a task to the filer's own worker, whoever runs the drain", async () => { - // BR-7: the member is the one who filed the task. Bob draining the list - // must reach Alice's worker for her task, and never his own of that name. - const { hire, lookup } = registry(); - const alices = hire("acme", "scout", "agent", "alice"); - hire("acme", "scout", "agent", "bob"); - const drainedByBob = run("acme", "bob"); - expect(await lookup.flowKind({ assignee: "scout", taskId: "t1", input: {}, filedBy: "alice" }, drainedByBob)).toBe( - alices.id - ); - // No filer on record: no member's own worker counts. - expect(await lookup.flowKind({ assignee: "scout", taskId: "t2", input: {} }, drainedByBob)).toBeUndefined(); +/** An installation whose `agent` takes tasks from `listId`, with an auditor on it and a clerk on `desk-clerk`. */ +function installationFor(listId: string) { + let flows: Record = {}; + const installation = createWorkerInstallation({ + standardWorkers: [ + { id: "eng.auditor", declared: {}, body: "You audit." }, + { id: "ops.clerk", declared: { flow: "desk-clerk" }, body: "You file." } + ], + workerFlows: () => flows as never }); + flows = { agent: defineAgentWorkerFlow({ installation, taskLists: [listId] }), "desk-clerk": deskClerk(installation) }; + return installation; +} - it("does not reach another organization's worker", () => { - const { hire, lookup } = registry(); - hire("acme", "frontend"); - expect(lookup.find("frontend", run("globex"))).toMatchObject({ found: false, reason: "not-found" }); - }); +describe("which worker a name on a task means", () => { + const list = mailboxBoard("ops.desk", "work"); + const lookup = createWorkerLookup({ installation: installationFor(list.id) }); - it("refuses a name held by the organization's worker and the caller's own, naming both", () => { - const { hire, lookup } = registry(); - hire("acme", "frontend"); - hire("acme", "frontend", "agent", "alice"); - const answer = lookup.find("frontend", run("acme", "alice")); - expect(answer).toMatchObject({ found: false, reason: "ambiguous" }); - expect(!answer.found && answer.message).toMatch(/hired for the organization and one your own/); - // A teammate sees only the organization's. - expect(lookup.find("frontend", run("acme", "bob")).found).toBe(true); + it("finds a standard worker by its id, on the flow it runs on", () => { + expect(lookup.find("eng.auditor", ctx)).toEqual({ found: true, flowId: "agent" }); }); - it("refuses a worker whose kind takes no tasks", () => { - const { hire, lookup } = registry(); - const clerk = hire("acme", "clerk", "desk-clerk"); - const answer = lookup.find("clerk", run("acme")); - // Still says which worker the name means: only taking tasks is refused. - expect(answer).toMatchObject({ found: false, reason: "takes-no-tasks", flowId: clerk.id }); - expect(!answer.found && answer.message).toMatch(/"clerk" takes no tasks: its kind "desk-clerk"/); + it("finds no worker for a name the files don't declare, a user's own worker's included", () => { + expect(lookup.find("frontend", ctx)).toMatchObject({ found: false, reason: "not-found" }); }); - it("reads the declared list on every lookup when given a getter", () => { - const flows = new Map(); - const declaredIds: string[] = []; - const lookup = createWorkerLookup({ instanceAt: (id) => flows.get(id), declared: () => declaredIds }); - const [declared] = hireWorkforce([{ id: "eng.auditor", declared: {}, body: "You audit." }], { workerFlows: kinds }); - flows.set(declared!.id, declared!); - expect(lookup.find("eng.auditor", run("acme")).found).toBe(false); - // Declared after the lookup was built, as a host that hires later does. - declaredIds.push("eng.auditor"); - expect(lookup.find("eng.auditor", run("acme"))).toEqual({ found: true, flowId: "eng.auditor" }); + it("refuses a worker whose flow takes no tasks, still saying which flow it runs on", () => { + const answer = lookup.find("ops.clerk", ctx); + expect(answer).toMatchObject({ found: false, reason: "takes-no-tasks", flowId: "desk-clerk" }); + expect(!answer.found && answer.message).toMatch(/"ops.clerk" takes no tasks: its flow "desk-clerk"/); }); - it("does not take a flow registered at a name the files never declared for a worker", () => { - const flows = new Map([["ops.desk", deskClerk({ id: "ops.desk" })]]); - const lookup = createWorkerLookup({ instanceAt: (id) => flows.get(id), declared: [] }); - expect(lookup.find("ops.desk", run(ORG)).found).toBe(false); + it("names the task's worker in the child session's starting state", async () => { + expect(await lookup.state({ assignee: "eng.auditor", taskId: "t1", input: {} }, ctx)).toEqual({ workerId: "eng.auditor" }); }); it("lets a list's own seat names through the filing check without asking", () => { - const { lookup } = registry(); const check = lookup.filingCheck({ [list.id]: ["coder"] }); - expect(check("coder", list.id, run(ORG))).toBeUndefined(); - expect(check("coder", "other.list", run(ORG))).toMatch(/No worker is named "coder"/); - expect(check("eng.auditor", list.id, run(ORG))).toBeUndefined(); + expect(check("coder", list.id, ctx)).toBeUndefined(); + expect(check("coder", "other.list", ctx)).toMatch(/No worker is named "coder"/); + expect(check("eng.auditor", list.id, ctx)).toBeUndefined(); }); - it("refuses a hand-over to a worker whose kind takes no tasks, or two at once, by name", async () => { - const { hire, lookup } = registry(); - hire("acme", "clerk", "desk-clerk"); + it("refuses a hand-over to a worker whose flow takes no tasks, and hands nobody's over to nothing", async () => { await expect( - Promise.resolve().then(() => lookup.flowKind({ assignee: "clerk", taskId: "t1", input: {} }, run("acme"))) - ).rejects.toThrow(/task "t1" could not be handed over: "clerk" takes no tasks/); - expect(await lookup.flowKind({ assignee: "nobody", taskId: "t2", input: {} }, run("acme"))).toBeUndefined(); + Promise.resolve().then(() => lookup.flowKind({ assignee: "ops.clerk", taskId: "t1", input: {} }, ctx)) + ).rejects.toThrow(/task "t1" could not be handed over: "ops.clerk" takes no tasks/); + expect(await lookup.flowKind({ assignee: "nobody", taskId: "t2", input: {} }, ctx)).toBeUndefined(); }); }); @@ -201,18 +121,13 @@ describe("a task filed for a worker by name, on a real host", () => { const list = mailboxBoard(mailboxId, "work"); async function host() { - let lookup: WorkerLookup | undefined; const answered: string[] = []; const heard: string[] = []; - const agent = defineAgentWorkerFlow({ taskLists: [list.id] }); - const kinds = { agent } as never; - const [auditor] = hireWorkforce([{ id: "eng.auditor", declared: {}, body: "You audit." }], { workerFlows: kinds }); + const installation = installationFor(list.id); + const lookup: WorkerLookup = createWorkerLookup({ installation }); + const copies = hireWorkforce(installation); const [mailbox] = mailboxInstances(roster, { - kinds: { - mailbox: defineMailboxFlow({ - checkAssignee: (name, listId, ctx) => lookup!.filingCheck()(name, listId, ctx) - }) as never - } + kinds: { mailbox: defineMailboxFlow({ checkAssignee: lookup.filingCheck() }) as never } }); // The coordinator's board over the list: no seat of its own, and a @@ -226,16 +141,20 @@ describe("a task filed for a worker by name, on a real host", () => { name: "desk-hand-over", action: "work", session: "per-task", - flowKind: (task, ctx) => lookup!.flowKind(task, ctx) + flowKind: lookup.flowKind, + state: lookup.state }) }); - const coordinator = defineFlow({ - kind: "desk-coordinator", - actions: { drain: { block: board.drain } } - })({ id: "desk-coordinator" }); + const coordinator = defineFlow({ kind: "desk-coordinator", actions: { drain: { block: board.drain } } })({ + id: "desk-coordinator" + }); const state = createFlowState({ - flows: { [mailbox!.kind]: mailbox!, [auditor!.id]: auditor!, [coordinator.id]: coordinator }, + flows: { + [mailbox!.kind]: mailbox!, + [coordinator.id]: coordinator, + ...Object.fromEntries(copies.map((copy) => [copy.id, copy])) + }, stores: { default: { primary: inMemoryStores() } }, modelResolver: createMockModelResolver({ generators: { @@ -260,7 +179,6 @@ describe("a task filed for a worker by name, on a real host", () => { }) }); const runtime: FlowStateRuntime = await state.getRuntime(); - lookup = createWorkerLookup({ instanceAt: (id) => runtime.registry.get(id), declared: [auditor!.id] }); await openMailboxes(roster, { client: sessionApi(runtime), userId: USER_ID }); const act = (flow: FlowInstance, sessionId: string, actionName: string, input: unknown) => @@ -275,24 +193,11 @@ describe("a task filed for a worker by name, on a real host", () => { runtimeConfig: { ...runtime.runtimeConfig } } as never) as Promise<{ output?: any; error?: any }>; - const hire = (seatId: string) => { - const bound = hiredSeatManifest( - ORG, - toHiredSeatRow({ seatId, flow: "agent", instructions: "Hired.", owningOrgId: ORG, ownerUserId: null }) - ); - if (!("manifest" in bound)) throw new Error(bound.problem); - const [seat] = hireWorkforce([bound.manifest], { workerFlows: kinds }); - state.register(seat!, { pin: { orgId: ORG } }); - return seat!; - }; - return { state, runtime, answered, heard, - hire, - fire: (id: string) => state.unregister(id), file: (assignee: string, goal: string, extra: Record = {}) => act(mailbox!, mailboxId, "fileTask", { board: "work", goal, assignee, ...extra }), drain: () => act(coordinator, "s_coordinator", "drain", {}), @@ -326,32 +231,18 @@ describe("a task filed for a worker by name, on a real host", () => { } }); - it("refuses at filing a name nobody holds, then hands a task to a worker hired after start", async () => { + it("refuses at filing a name no worker holds, and files nothing", async () => { const h = await host(); try { const refused = await h.file("frontend", "GOAL-abc123 audit the licenses"); expect(String(refused.error?.message)).toMatch(/unknown-assignee: No worker is named "frontend"/); expect(await h.listed()).toEqual([]); - - const seat = h.hire("frontend"); - const filed = await h.file("frontend", "GOAL-abc123 audit the licenses"); - expect(filed.error).toBeUndefined(); - const taskId = filed.output.taskId as string; - - expect((await h.drain()).error).toBeUndefined(); - await until(async () => (await h.row(taskId))?.status === "completed", "the hire to settle the task"); - const row = (await h.row(taskId))!; - expect(row.output).toBe("answered"); - expect(h.answered).toEqual(["abc123"]); - // It ran on the hire's own flow, linked from the row. - const linked = await h.runtime.stores.session.get(row.run.sessionId); - expect(linked?.flowId ?? linked?.flowKind).toBe(seat.id); } finally { await h.state.dispose(); } }); - it("hands a declared worker a task on a list no code wired it to, each task in its own session", async () => { + it("hands a worker a task on a list no code wired it to: the shared copy, each task in its own session naming the worker", async () => { const h = await host(); try { const one = (await h.file("eng.auditor", "GOAL-one1 first")).output.taskId as string; @@ -362,45 +253,16 @@ describe("a task filed for a worker by name, on a real host", () => { } const [a, b] = [(await h.row(one))!, (await h.row(two))!]; expect(a.run.sessionId).not.toBe(b.run.sessionId); + for (const row of [a, b]) { + const linked = await h.runtime.stores.session.get(row.run.sessionId); + expect(linked?.flowId ?? linked?.flowKind).toBe("agent"); + expect((linked?.state as { workerId?: string }).workerId).toBe("eng.auditor"); + } expect(h.answered.sort()).toEqual(["one1", "two2"]); } finally { await h.state.dispose(); } }); - - it("gives an open task to the worker re-hired under the same name", async () => { - const h = await host(); - try { - const first = h.hire("frontend"); - const taskId = (await h.file("frontend", "GOAL-rehired audit")).output.taskId as string; - h.fire(first.id); - const second = h.hire("frontend"); - expect((await h.drain()).error).toBeUndefined(); - await until(async () => (await h.row(taskId))?.status === "completed", "the re-hire to settle the task"); - const row = (await h.row(taskId))!; - const linked = await h.runtime.stores.session.get(row.run.sessionId); - expect(linked?.flowId).toBe(second.id); - expect(h.answered).toEqual(["rehired"]); - } finally { - await h.state.dispose(); - } - }); - - it("fails a task whose worker was fired after it was filed, naming the worker", async () => { - const h = await host(); - try { - const seat = h.hire("frontend"); - const taskId = (await h.file("frontend", "GOAL-gone audit")).output.taskId as string; - h.fire(seat.id); - await h.drain(); - const row = (await h.row(taskId))!; - expect(row.status).toBe("errored"); - expect(row.error).toMatch(/flow-not-found.*assignee "frontend"/); - expect(h.answered).toEqual([]); - } finally { - await h.state.dispose(); - } - }); }); /** `openMailboxes`'s session API over the runtime's own stores. */ From 5d4306af9f0fe99e3f1d172244a12a8d1f9edb0e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 01:40:28 +0000 Subject: [PATCH 04/12] feat(shift-manager): Roster lists the person's own workers; conversations name their worker (FIX-1788 P4 S12 S15) Roster reads the signed-in person's roster through createWorkforceClient (useWorkforce) beside the standard workers. A seat's conversation is the person's newest session on its flow naming the worker, opened naming it before the first line. The DevTeam Lab, its fixtures and tests run one copy per worker flow, with hire and fire as the chief of staff's tools over the person's roster. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- .changeset/shift-manager-workers-as-data.md | 5 + packages/shift-manager/README.md | 18 +- .../src/components/Conversation.tsx | 8 +- .../shift-manager/src/lib/conversation.ts | 64 ++- packages/shift-manager/src/lib/derive.ts | 35 +- packages/shift-manager/src/lib/reads.ts | 163 ++------ packages/shift-manager/src/lib/workforce.ts | 35 ++ .../src/surfaces/ChiefOfStaff.tsx | 4 +- .../shift-manager/src/surfaces/JumpTo.tsx | 2 +- .../shift-manager/src/surfaces/Roster.tsx | 105 ++++- .../shift-manager/src/surfaces/Sidebar.tsx | 5 - .../shift-manager/teams/devteam/README.md | 10 +- packages/shift-manager/teams/devteam/ask.mts | 68 +++- .../shift-manager/teams/devteam/board.mts | 38 +- packages/shift-manager/teams/devteam/host.mts | 374 ++++++++++-------- .../shift-manager/teams/devteam/notify.mts | 38 +- .../shift-manager/teams/devteam/phase.mts | 33 +- .../teams/devteam/seat-config.mts | 118 +++--- .../devteam/workforce/flows/workers/coder.mts | 42 +- .../devteam/workforce/flows/workers/em.mts | 41 +- .../org/workers/chief-of-staff/WORKER.md | 29 +- .../shift-manager/test/chief-of-staff.test.ts | 56 ++- packages/shift-manager/test/columns.test.ts | 4 +- .../shift-manager/test/conversation.test.tsx | 36 +- .../test/devforce-lab-hired-boot.test.ts | 311 --------------- .../test/devteam-hired-restart.test.ts | 82 ---- .../test/devteam-repository-ask.test.ts | 40 +- .../test/fixtures/ask-lab/asker.mts | 15 +- .../test/fixtures/ask-lab/lab.mts | 29 +- .../test/fixtures/multi-seat-collab/host.mts | 56 ++- .../workforce/flows/workers/planner.mts | 10 +- .../workforce/flows/workers/worker.mts | 36 +- .../test/fixtures/run-lab/lab.mts | 74 +++- packages/shift-manager/test/projects.test.tsx | 7 +- packages/shift-manager/test/reads.test.ts | 14 +- .../shift-manager/test/roster-screen.test.tsx | 47 ++- packages/shift-manager/test/roster.test.ts | 30 +- packages/shift-manager/test/run.test.ts | 6 +- .../shift-manager/test/shell-lines.test.ts | 2 +- packages/shift-manager/test/shell.test.tsx | 44 ++- .../shift-manager/test/teams-roster.test.ts | 138 ++----- .../shift-manager/test/turn-routes.test.ts | 16 +- packages/shift-manager/test/workforce.test.ts | 84 ++++ 43 files changed, 1194 insertions(+), 1178 deletions(-) create mode 100644 .changeset/shift-manager-workers-as-data.md create mode 100644 packages/shift-manager/src/lib/workforce.ts delete mode 100644 packages/shift-manager/test/devforce-lab-hired-boot.test.ts delete mode 100644 packages/shift-manager/test/devteam-hired-restart.test.ts create mode 100644 packages/shift-manager/test/workforce.test.ts diff --git a/.changeset/shift-manager-workers-as-data.md b/.changeset/shift-manager-workers-as-data.md new file mode 100644 index 0000000000..4cdfad643d --- /dev/null +++ b/.changeset/shift-manager-workers-as-data.md @@ -0,0 +1,5 @@ +--- +"@flow-state-dev/shift-manager": minor +--- + +Roster lists the signed-in person's own workers beside the Lab's standard ones, read through Workforce's roster flow, and the chief of staff's conversation is a session of its flow that names the worker. A Lab registers the flows `hireWorkforce(installation)` returns (FIX-1788). diff --git a/packages/shift-manager/README.md b/packages/shift-manager/README.md index 286e85d322..cdbb6f37e1 100644 --- a/packages/shift-manager/README.md +++ b/packages/shift-manager/README.md @@ -121,11 +121,11 @@ A Lab with no resolver runs in the framework's development organization, `DEFAUL 2. Call `openInventory` once `openMailboxes` has returned, under the organization your resolver names. ```ts -// `roster` is the tree read with `readDeclaredRoster`, `hired` the seats -// `hireWorkforce` returned, and `client` the session client `openMailboxes` takes. +// `roster` is the tree read with `readDeclaredRoster`, `installation` the one built on its +// workers, and `client` the session client `openMailboxes` takes. await openMailboxes(roster.mailboxes, { client, userId: "u_lab" }); const opened = await openInventory( - { seats: hired.map((seat) => ({ id: seat.id, kind: seat.kind })), mailboxes: roster.mailboxes }, + { seats: inventorySeats(installation), mailboxes: roster.mailboxes }, { run, seatWriter: { flowKind: "mailbox" }, userId: "u_lab", orgId: "org_lab" }, ); if (opened.problems.length > 0) throw new Error(opened.problems.join("; ")); @@ -194,7 +194,7 @@ A Lab with no chief of staff needs nothing in its config. Every screen works, an ## What you see - **Shift Coordinator.** Where Shift Manager opens: a summary of the shift, and your conversation with the Lab's chief of staff. See [Shift Coordinator](#shift-coordinator). -- **Sidebar.** The organization, Jump to (⌘K), Shift Coordinator, Inbox and Tasks with their counts (Inbox's count is highlighted while anything waits on you), Roster with how many workers are on shift and on call, PROJECTS (each project with its workstreams, then No project), and TEAMS: one row per team in the Lab's seat inventory, with how many of its workers are on shift and a square for each worker. A workstream under PROJECTS shows a yellow square while one of its workers' asks waits on you, otherwise a blue one while one of its tasks runs. Organization-level workers, such as a chief of staff, sit in one Staff row at the top. A worker hired while the Lab runs is listed only while the organization's roster has its row, so a fired worker leaves the list even if its inventory row is still there. When no flow the person uses lets Shift Manager read the roster, hired workers aren't listed and TEAMS says how many were left out. Hover a square for the worker and its status. Click a team to open Roster for that team. The footer repeats the on-shift and on-call counts, followed by your initials. +- **Sidebar.** The organization, Jump to (⌘K), Shift Coordinator, Inbox and Tasks with their counts (Inbox's count is highlighted while anything waits on you), Roster with how many workers are on shift and on call, PROJECTS (each project with its workstreams, then No project), and TEAMS: one row per team in the Lab's seat inventory, with how many of its workers are on shift and a square for each worker. A workstream under PROJECTS shows a yellow square while one of its workers' asks waits on you, otherwise a blue one while one of its tasks runs. Organization-level workers, such as a chief of staff, sit in one Staff row at the top. TEAMS lists the Lab's standard workers; your own workers are on Roster. Hover a square for the worker and its status. Click a team to open Roster for that team. The footer repeats the on-shift and on-call counts, followed by your initials. - **Jump to (⌘K).** Finds Shift Coordinator, workstreams, seats, tasks and the Lab's [readable documents](#what-a-labs-config-provides). A seat opens Roster. A document opens read-only. - **Inbox.** Every approval or question a seat is waiting on you for, oldest first. You answer it on its card, and can reply to the worker under it. An ask from a run the Lab started by itself, such as a seat woken by a mailbox post, is shown without buttons, and its card says why: the Lab never reopens those runs from outside. Under the ask, *From the session* lists the last three tool calls the worker made before it asked. Replies you send appear below that list once the worker's session has stored them. - **Tasks.** Every row on every attached board that isn't done, grouped by state, worker or workstream. Each row shows its id and, while it runs, how long it has been running. Queued tasks, blocked ones included, stay hidden until you turn on the Queued toggle, which shows how many there are. @@ -208,7 +208,7 @@ A post appears in the transcript only once the mailbox has kept it. Until then t **Talking to a worker.** Start a line with `@` and a worker's name to send it to that worker's task in this workstream instead of the mailbox. If it has several, the composer asks which. If it has none, Send is off and says so. In a task, the composer sends to that task's run. From Inbox, the reply box sends to the worker that asked, if its kind takes messages. A worker whose kind takes no message gets a reply box that says so. -A running coding run stops where it is and carries on in the same session with your message. Each message box names the worker it sends to. In Shift Coordinator and Inbox, as soon as the worker's session holds your line, the line leaves the box and shows in the conversation, and the composer says it's waiting on the reply. It says *delivered* once the worker's turn on it ends. If the send fails after the line left the box, the line is put back. A conversation that's scrolled to its end keeps the latest turn in view as lines arrive. If the worker stops on an ask of its own, as a chief of staff does before it fires or retires a seat, the line is still delivered: the composer says so and points you at Inbox, where the ask now waits, and offers no Retry. If it stops to wait on something other than you, the composer says it's waiting, again with no Retry. If the worker refuses it, your draft stays and its reason is shown. If the line never reached the Lab, Retry sends it again. If it may have arrived but Shift Manager can't confirm it, the draft stays and there's no Retry, so it isn't sent twice. A finished task takes no message. +A running coding run stops where it is and carries on in the same session with your message. Each message box names the worker it sends to. In Shift Coordinator and Inbox, as soon as the worker's session holds your line, the line leaves the box and shows in the conversation, and the composer says it's waiting on the reply. It says *delivered* once the worker's turn on it ends. If the send fails after the line left the box, the line is put back. A conversation that's scrolled to its end keeps the latest turn in view as lines arrive. If the worker stops on an ask of its own, as a chief of staff does before it fires a worker, the line is still delivered: the composer says so and points you at Inbox, where the ask now waits, and offers no Retry. If it stops to wait on something other than you, the composer says it's waiting, again with no Retry. If the worker refuses it, your draft stays and its reason is shown. If the line never reached the Lab, Retry sends it again. If it may have arrived but Shift Manager can't confirm it, the draft stays and there's no Retry, so it isn't sent twice. A finished task takes no message. To make your own worker kind take messages, give it one public action that declares `userMessage` and takes `{ message }`. Shift Manager sends lines there, using the `door` on the seat's inventory row. @@ -220,7 +220,7 @@ Shift Manager opens here, at `/` or `/cos`. The top of the screen is Shift Manager's own summary of the shift: how many asks wait on you, each one with the same Approve and Reject you'd get in Inbox, and how many runs are going across how many workstreams. The numbers are the ones Inbox and Tasks show. -Below it is your conversation with the Lab's chief-of-staff seat. A line goes through the seat's door, like any other line you send to a worker. The message box names who you're sending to, Shift Coordinator. The reply is what the seat wrote in that session, with the time it was written. While the seat works on a line you sent from this tab, a blue square says so under the conversation and on the sidebar's Shift Coordinator entry. Once you send a line, the conversation follows: each new turn scrolls into view, until you scroll up to read earlier ones. Come back later and the same conversation is there. +Below it is your conversation with the Lab's chief-of-staff worker: your newest session on its flow that names it. A first line opens that session, naming the worker, before the line goes through the flow's door, like any other line you send to a worker. The message box names who you're sending to, Shift Coordinator. The reply is what the seat wrote in that session, with the time it was written. While the seat works on a line you sent from this tab, a blue square says so under the conversation and on the sidebar's Shift Coordinator entry. Once you send a line, the conversation follows: each new turn scrolls into view, until you scroll up to read earlier ones. Come back later and the same conversation is there. Above the message box sit suggested lines you can click to fill the box: `Who's on call?`, and `What's blocking #?`. The workstream named is one with an ask waiting on you, or, if none has one, one with a task running. Nothing goes out until you send it. @@ -284,17 +284,17 @@ A board that hands work off keeps a running task on the worker it was given to, ## Roster -Roster shows every worker the Lab's seat inventory lists, in three groups: +Roster shows the signed-in person's workers: the standard workers the Lab's seat inventory lists, and their own, hired or forked, which no one else sees (marked YOURS). Their own are read through Workforce's client (`createWorkforceClient(...).roster()`), so the Lab has to register the roster flow `hireWorkforce` returns. Each worker is in one of three groups: - **On shift**: it holds a task that is running. - **On call**: nothing of its is running, but it is waiting on you, either on a task it parked for you or on an ask in Inbox. - **Off shift**: neither. A worker with only queued tasks is off shift until it claims one. -Each worker shows its team and kind, how many slots it has in use (one square per task it holds), the tasks it holds, and what it is waiting on. Click a task to open it. The counts at the top are for the workers shown. +Each worker shows its team and the flow it runs on, how many slots it has in use (one square per task it holds), the tasks it holds, and what it is waiting on. Click a task to open it. The counts at the top are for the workers shown. The same status appears in the sidebar and in a workstream's panel, so a worker reads the same everywhere. If the Lab's asks didn't load, each of those places marks its status *partial*: a worker waiting on you only through an ask would read off shift. -Roster is read with the rest of the screen, when Shift Manager starts, on Retry, after you answer an ask, and after each message the chief of staff takes (so a hire, or a project it starts for you, shows up at once). It says when it was read. It doesn't refresh on its own. +Roster is read with the rest of the screen, when Shift Manager starts, on Retry, after you answer an ask, and after each message the chief of staff takes (so a hire, a fire, or a project it starts for you, shows up at once). It says when it was read. It doesn't refresh on its own. Slots count what a worker holds now. Nothing in a Lab limits how many tasks a worker takes, so Roster shows no capacity and no free slots. diff --git a/packages/shift-manager/src/components/Conversation.tsx b/packages/shift-manager/src/components/Conversation.tsx index 8e2c8be055..d3d66832c3 100644 --- a/packages/shift-manager/src/components/Conversation.tsx +++ b/packages/shift-manager/src/components/Conversation.tsx @@ -25,7 +25,7 @@ import { SessionItemsProvider } from "./flow-state/session-items-context"; import { shiftManagerRenderers, ToolLineGroup } from "./ToolLine"; import { SectionFailure } from "./ui"; import { TurnComposer } from "./TurnComposer"; -import { useSeatConversation } from "../lib/conversation"; +import { openConversation, useSeatConversation } from "../lib/conversation"; import { useFollowLatest } from "../lib/follow"; import { useLab } from "../lib/lab-data"; import type { Seat } from "../lib/reads"; @@ -114,7 +114,7 @@ export function Conversation({ // Nothing is sent into a conversation the screen hasn't read, or to a seat with no door. const blocked = - seat.door === null + seat.door === null || seat.kind === null ? `${seat.id} ${gaps.turn.noDoor}` : failure !== undefined ? "The conversation didn't load, so nothing can be sent until it does." @@ -137,7 +137,9 @@ export function Conversation({ const settled = startWork?.(); feed.follow(); try { - const sent = await sendTurn(clients, { sessionId: target, flowId: seat.id, door: seat.door! }, message, { + // A first line opens its session naming the seat's worker before the door's request runs in it. + if (sessionId === null) await openConversation(clients, { id: seat.id, kind: seat.kind! }, target); + const sent = await sendTurn(clients, { sessionId: target, flowId: seat.kind!, door: seat.door! }, message, { onHeld: () => { // The session holds the line: read it back now, so it is drawn while the reply is in flight. conversation.open(target); diff --git a/packages/shift-manager/src/lib/conversation.ts b/packages/shift-manager/src/lib/conversation.ts index a0f82cb19a..f488b1c5e1 100644 --- a/packages/shift-manager/src/lib/conversation.ts +++ b/packages/shift-manager/src/lib/conversation.ts @@ -1,32 +1,35 @@ /** * One person's conversation with one seat, read from the seat's session. * - * The session is the newest direct one the snapshot lists for the seat, or the - * one a first line just opened, until the snapshot lists it (BR-14). Its items - * are read when the view opens and after each line, never on the snapshot's - * refresh. Nothing is sent into a conversation the screen hasn't read; one a - * line opened here holds nothing the person hasn't seen. + * The session is the newest direct one the snapshot lists on the seat's flow + * naming the seat's worker, or the one a first line just opened, until the + * snapshot lists it (BR-14). Its items are read when the view opens and after + * each line, never on the snapshot's refresh. Nothing is sent into a + * conversation the screen hasn't read; one a line opened here holds nothing + * the person hasn't seen. * * Used by ``; a view that wants a conversation with a seat draws * that component, and calls this only to build its own. */ import { useCallback, useEffect, useRef, useState } from "react"; -import type { SessionSummary } from "@flow-state-dev/client"; +import { ClientHttpError, type SessionSummary } from "@flow-state-dev/client"; +import { WORKER_ID_STATE_KEY } from "@flow-state-dev/workforce/browser"; +import type { LabClients } from "./connection"; import { newSessionId } from "./ids"; import { useLab } from "./lab-data"; -import { describeFailure, type Failure, type Seat } from "./reads"; +import { describeFailure, workerOf, type Failure, type Seat } from "./reads"; import { readSessionItems, RunReadError, type SessionItems } from "./run"; /** - * The id of the person's conversation with the seat `seatId`: their newest - * session on that seat's flow with no parent session, or `null` when they have - * none. A store that nulls absent keys hands back `null` for a parent, so the - * guard is `== null`. + * The id of the person's conversation with `seat`: their newest session on + * the seat's flow that names the seat's worker and has no parent session, or + * `null` when they have none. A store that nulls absent keys hands back + * `null` for a parent, so the guard is `== null`. */ -export function conversationSession(sessions: readonly SessionSummary[], seatId: string): string | null { +export function conversationSession(sessions: readonly SessionSummary[], seat: Pick): string | null { let newest: SessionSummary | undefined; for (const session of sessions) { - if (session.flowId !== seatId || session.parentSessionId != null) continue; + if (session.flowKind !== seat.kind || workerOf(session) !== seat.id || session.parentSessionId != null) continue; if (newest === undefined || session.createdAt > newest.createdAt) newest = session; } return newest?.id ?? null; @@ -37,20 +40,43 @@ export function conversationSession(sessions: readonly SessionSummary[], seatId: * here, until the listing holds it; from then on the newest direct session * the listing names, which may be one started elsewhere. */ -export function currentConversation(sessions: readonly SessionSummary[], seatId: string, opened: string | null): string | null { +export function currentConversation( + sessions: readonly SessionSummary[], + seat: Pick, + opened: string | null, +): string | null { if (opened !== null && !sessions.some((session) => session.id === opened)) return opened; - return conversationSession(sessions, seatId); + return conversationSession(sessions, seat); } /** - * A fresh session id for a new conversation ({@link newSessionId}). The Lab's - * answer to an action sent with no session doesn't name the session it opened, - * so a first line goes to an id minted here, and the door's request opens it. + * A fresh session id for a new conversation ({@link newSessionId}). A worker's + * session names its worker from the moment it is created, so a first line goes + * to an id minted here, opened by {@link openConversation} before the door's + * request runs in it. */ export function newConversationId(): string { return newSessionId("conv", "_"); } +/** + * Open `sessionId` on the seat's flow, naming the seat's worker in its + * starting state. A session a failed earlier attempt already opened under that + * id is the one the line goes to, so a conflict is not an error. + */ +export async function openConversation(clients: LabClients, seat: { id: string; kind: string }, sessionId: string): Promise { + try { + await clients.sessions.createSession({ + flowKind: seat.kind, + userId: clients.userId, + sessionId, + state: { [WORKER_ID_STATE_KEY]: seat.id }, + }); + } catch (error) { + if (!(error instanceof ClientHttpError && error.status === 409)) throw error; + } +} + export interface SeatConversation { /** The conversation's session, or `null` before a first line. */ sessionId: string | null; @@ -72,7 +98,7 @@ export interface SeatConversation { export function useSeatConversation(seat: Seat, sessions: readonly SessionSummary[]): SeatConversation { const { clients } = useLab(); const [opened, setOpened] = useState(null); - const sessionId = currentConversation(sessions, seat.id, opened); + const sessionId = currentConversation(sessions, seat, opened); // The id a first line goes to, kept across a failed send so a retry lands in // the same session if the Lab already opened it. const fresh = useRef(null); diff --git a/packages/shift-manager/src/lib/derive.ts b/packages/shift-manager/src/lib/derive.ts index 82eb24cc85..b680108e9d 100644 --- a/packages/shift-manager/src/lib/derive.ts +++ b/packages/shift-manager/src/lib/derive.ts @@ -2,7 +2,6 @@ * What the screens compute from one snapshot, kept out of the components so * every surface computes it the same way. */ -import { splitSeatAddress } from "@flow-state-dev/workforce/browser"; import { columnFor, isDone, readStatus } from "./columns"; import { STAFF_TEAM, @@ -39,11 +38,10 @@ export type Roster = { seats: readonly Seat[]; workstreams: readonly Workstream[ * to, not a seat address: a board may name `` for the seat * `.`. So, in order: * - * 1. a seat whose id, or whose logical seat id (a hired seat's `` - * inside its `.` address), is the assignee; + * 1. the seat whose id is the assignee; * 2. the one seat whose own name is the assignee; * 3. when that name belongs to seats in more than one team, the one of them - * that is a member of the row's mailbox, by either id. + * that is a member of the row's mailbox. * * Still more than one, or none, is no seat: a row is never shown against * several seats, or against a guess. Which seat actually claimed the row is @@ -52,12 +50,12 @@ export type Roster = { seats: readonly Seat[]; workstreams: readonly Workstream[ */ export function seatFor(roster: Roster, row: BoardRow): Seat | undefined { if (row.assignee === null) return undefined; - const exact = roster.seats.find((seat) => seat.id === row.assignee || seat.seatId === row.assignee); + const exact = roster.seats.find((seat) => seat.id === row.assignee); if (exact !== undefined) return exact; const named = roster.seats.filter((seat) => seat.name === row.assignee); if (named.length <= 1) return named[0]; const members = new Set(roster.workstreams.find((w) => w.id === row.mailboxId)?.members ?? []); - const inMailbox = named.filter((seat) => members.has(seat.id) || members.has(seat.seatId)); + const inMailbox = named.filter((seat) => members.has(seat.id)); return inMailbox.length === 1 ? inMailbox[0] : undefined; } @@ -172,12 +170,13 @@ export function workstreamsOf(ask: Ask, workstreams: readonly Workstream[]): Wor } /** - * The door of the flow that owns a session: the seat inventory row whose id is - * that flow's id names it. `null` when no seat row matches or its kind takes - * no message. + * The door of the flow that owns a session: the seat inventory rows of the + * workers on that flow name it, since a worker flow is registered at its kind. + * Every worker on one flow shares its door. `null` when no seat row is on the + * flow, or its kind takes no message. */ export function doorOf(seats: readonly Seat[], flowId: string): string | null { - return seats.find((seat) => seat.id === flowId)?.door ?? null; + return seats.find((seat) => seat.kind === flowId)?.door ?? null; } /** @@ -350,17 +349,13 @@ const CHIEF_OF_STAFF = "chief-of-staff"; export type ChiefOfStaff = { kind: "one"; seat: Seat } | { kind: "none" } | { kind: "several"; seats: Seat[] }; /** - * The chief of staff among the inventory's seats (D2): the seats whose name, - * once an Ops-hired seat's `.` address is split off, is exactly - * `chief-of-staff`. That is an org seat (`chief-of-staff`), a team's worker - * (`.chief-of-staff`), or either hired at runtime under the org. One is - * the chief of staff; two or more are a state, never a guess. + * The chief of staff among the inventory's seats (D2): the seats whose name is + * exactly `chief-of-staff`. That is an org seat (`chief-of-staff`) or a + * team's worker (`.chief-of-staff`). One is the chief of staff; two or + * more are a state, never a guess. */ -export function chiefOfStaffOf(seats: readonly Seat[], orgId: string): ChiefOfStaff { - const found = seats.filter((seat) => { - const seatId = splitSeatAddress(orgId, seat.id) ?? seat.id; - return seatId.slice(seatId.indexOf(".") + 1) === CHIEF_OF_STAFF; - }); +export function chiefOfStaffOf(seats: readonly Seat[]): ChiefOfStaff { + const found = seats.filter((seat) => seat.id.slice(seat.id.indexOf(".") + 1) === CHIEF_OF_STAFF); if (found.length === 0) return { kind: "none" }; return found.length === 1 ? { kind: "one", seat: found[0]! } : { kind: "several", seats: found }; } diff --git a/packages/shift-manager/src/lib/reads.ts b/packages/shift-manager/src/lib/reads.ts index c73a23408b..cd4b43f354 100644 --- a/packages/shift-manager/src/lib/reads.ts +++ b/packages/shift-manager/src/lib/reads.ts @@ -56,28 +56,32 @@ import { ClientHttpError, type ResourceManifest, type SessionSummary } from "@fl import type { OutputItem, SuspensionItem } from "@flow-state-dev/core/items"; import type { ResumeAction } from "@flow-state-dev/core/types"; import { deriveSuspensions, suspensionShape } from "@flow-state-dev/react"; -import { - HIRED_ROSTER_BROWSER_PATTERN, - isHiredSeatRow, - listedSeatRows, - splitSeatAddress -} from "@flow-state-dev/workforce/browser"; +import { WORKER_ID_STATE_KEY } from "@flow-state-dev/workforce/browser"; import type { LabClients } from "./connection"; /** Why a read did not load. */ export type Failure = { message: string; httpStatus?: number }; +/** + * The worker a session runs, as its state names it (`workerId`), or `null` + * when it names none. + */ +export function workerOf(session: SessionSummary): string | null { + return text(field((session as { state?: unknown }).state, WORKER_ID_STATE_KEY)); +} + /** One section's outcome: its value, or why it has none. */ export type Section = { ok: true; value: T } | { ok: false; failure: Failure }; -/** A seat, as the seat inventory registers it. */ +/** A seat, as the seat inventory registers it: one worker. */ export type Seat = { /** - * The seat's address, which is also its flow instance id: `.`, - * a bare name for an org seat, or `.` for a hired one. + * The worker's id: `.`, or a bare name for an org seat. Boards + * and mailboxes name the seat by it, and its sessions carry it as their + * `workerId`. */ id: string; - /** The kind the seat was hired from; `null` on a row that has none. */ + /** The worker flow the worker runs on, which is also that flow's copy id; `null` on a row that has none. */ kind: string | null; /** * The action that takes a person's message into this seat's sessions, as @@ -85,17 +89,6 @@ export type Seat = { * written before doors were published. */ door: string | null; - /** - * Whether the row says the seat was hired at runtime (`true`) or declared - * (`false`); `null` on a row written before rows said, which is then read - * by its id's shape. - */ - hired: boolean | null; - /** - * The id boards and mailboxes name the seat by: for a hired seat the - * `` inside its `.` address, otherwise `id` itself. - */ - seatId: string; /** The team it sits under, or {@link STAFF_TEAM} for an org seat (see {@link toSeat}). */ team: string; name: string; @@ -250,17 +243,9 @@ export type DeclaredResource = { ref: string; sessionId: string }; /** The organization's seats and workstreams, as the inventory registers them. */ export type Inventory = { - /** - * The seats a team list shows: a hired seat only while the organization's - * roster backs it (Workforce's `listedSeatRows`), every declared seat as registered. - */ + /** Every seat the inventory registers. */ seats: Seat[]; workstreams: Workstream[]; - /** - * Set when hired seats were left out because the roster couldn't be read: - * says how many and why. Absent when the roster loaded, or nothing was left out. - */ - rosterUnread?: string; }; /** Everything one refresh read. */ @@ -308,9 +293,6 @@ export const ROOM_KIND = "mailbox"; */ const PROJECT_PATTERNS = { projects: "projects/*" } as const; -/** The organization's hired roster, by its published key pattern. */ -const ROSTER_PATTERN = HIRED_ROSTER_BROWSER_PATTERN; - /** Rows per collection page: the collection route's maximum. */ const PAGE_SIZE = 200; /** A guard against a server that pages forever; the shipped panel readers use the same bound. */ @@ -380,29 +362,19 @@ function time(value: unknown): number | null { export const STAFF_TEAM = "Staff"; /** - * A seat inventory row, grouped by its address (FIX-1719's seat contract): + * A seat inventory row, grouped by its worker id: * - * - `.`, a seat hired at runtime into this organization (a - * user-owned one too), is split the way Workforce splits it and grouped by - * the seat id it holds; * - `.` sits under its team: a team id carries no dot, so the team * is everything before the first one; * - an id with no dot is an org seat, and sits in {@link STAFF_TEAM}. - * - * Which of the first two a row is comes from the row's own `hired` field, so - * a declared team that shares the organization's name stays a team. A row - * written before the field existed is read by its id's shape. */ -export function toSeat(row: unknown, orgId: string): Seat | undefined { +export function toSeat(row: unknown): Seat | undefined { const id = text(field(row, "id")); if (id === null) return undefined; - const flag = field(row, "hired"); - const hired = typeof flag === "boolean" ? flag : null; - const address = (isHiredSeatRow(orgId, { id, hired }) ? splitSeatAddress(orgId, id) : undefined) ?? id; - const dot = address.indexOf("."); - const team = dot > 0 ? address.slice(0, dot) : STAFF_TEAM; - const name = dot > 0 ? address.slice(dot + 1) : address; - return { id, kind: text(field(row, "kind")), door: text(field(row, "door")), hired, seatId: address, team, name }; + const dot = id.indexOf("."); + const team = dot > 0 ? id.slice(0, dot) : STAFF_TEAM; + const name = dot > 0 ? id.slice(dot + 1) : id; + return { id, kind: text(field(row, "kind")), door: text(field(row, "door")), team, name }; } /** A mailbox inventory row. A row written before `members` existed reads as none (BP-030). */ @@ -579,52 +551,8 @@ export function createLabReader(clients: LabClients): LabReader { const readBoard = async (mailboxId: string, boardRef: string): Promise => (await readCollection(mailboxId, boardRef)).map((row) => toBoardRow(boardRef, mailboxId, row.topic, row.clientData)); - /** - * The organization's hired roster (its seat ids), through the first listed - * flow that declares it. A failure, or no listed flow declaring it, is the - * section's failure: the caller then lists no hired seat. - */ - const readRoster = async ( - byKind: ReadonlyMap, - ): Promise>> => { - try { - for (const [kind, sessionId] of byKind) { - const manifest = await manifestFor(kind, sessionId); - const ref = manifest.resources.find( - (r) => r.kind === "collection" && r.pattern === ROSTER_PATTERN && r.client.state?.read === true, - )?.ref; - if (ref === undefined) continue; - const rows = await readCollection(sessionId, ref); - return { - ok: true, - value: rows.flatMap((row) => { - const seatId = text(field(row.clientData, "seatId")); - return seatId === null ? [] : [{ seatId, incarnation: text(field(row.clientData, "incarnation")) }]; - }), - }; - } - } catch (error) { - return { ok: false, failure: describeFailure(error) }; - } - return { ok: false, failure: { message: "None of this person's sessions is on a flow that declares the roster." } }; - }; - - /** - * The sessions the roster may be read through: the top-level ones by kind - * first, then a kind seen only on a dispatch child. The roster is org-scoped, - * so any session of the org reads the same rows, and a viewer whose only - * session on a roster-declaring flow is a child still has one. - */ - const rosterCarriers = (sessions: SessionSummary[], topLevel: ReadonlyMap) => { - const byKind = new Map(topLevel); - for (const session of sessions) { - if (!byKind.has(session.flowKind)) byKind.set(session.flowKind, session.id); - } - return byKind; - }; - /** Find the inventory through the first listed session whose flow declares it. */ - const readInventory = async (sessions: SessionSummary[], orgId: string): Promise> => { + const readInventory = async (sessions: SessionSummary[]): Promise> => { const byKind = new Map(); for (const session of sessions) { if (session.parentSessionId == null && !byKind.has(session.flowKind)) byKind.set(session.flowKind, session.id); @@ -647,32 +575,11 @@ export function createLabReader(clients: LabClients): LabReader { readCollection(sessionId, seatsRef), readCollection(sessionId, mailboxesRef), ]); - // Each seat beside the incarnation its row carries, which the - // team-list rule matches against the roster row's. - const rows = seatRows.flatMap((r) => { - const seat = toSeat(r.clientData, orgId); - return seat === undefined - ? [] - : [{ id: seat.id, hired: seat.hired, incarnation: text(field(r.clientData, "incarnation")), seat }]; - }); - const registered = rows.map((row) => row.seat); - // A hired seat is listed only while the roster backs it: Workforce's - // team-list rule, applied once here so every screen draws the same list. - // The roster is read only when a hired seat's row is there to check. - const anyHired = registered.some((seat) => isHiredSeatRow(orgId, seat)); - const roster = anyHired ? await readRoster(rosterCarriers(sessions, byKind)) : ({ ok: true, value: [] } as const); - const seats = listedSeatRows(orgId, rows, roster.ok ? roster.value : undefined).map((row) => row.seat); - const hiddenForNoRoster = registered.length - seats.length; - const rosterUnread = - roster.ok || hiddenForNoRoster === 0 - ? null - : `${hiddenForNoRoster} hired seat${hiddenForNoRoster === 1 ? " isn't" : "s aren't"} listed: the roster didn't load, so Shift Manager can't show ${hiddenForNoRoster === 1 ? "it's" : "they're"} still hired. ${roster.failure.message}`; + const seats = seatRows.map((r) => toSeat(r.clientData)).filter((seat): seat is Seat => seat !== undefined); const workstreams = mailboxRows .map((r) => toWorkstream(r.clientData)) .filter((w): w is Workstream => w !== undefined); - // Empty means nothing registered, not nothing listed: hired seats the - // roster can't vouch for are a listed inventory with `rosterUnread`. - if (registered.length === 0 && workstreams.length === 0) { + if (seats.length === 0 && workstreams.length === 0) { return { ok: false, failure: { @@ -681,7 +588,7 @@ export function createLabReader(clients: LabClients): LabReader { }, }; } - return { ok: true, value: { seats, workstreams, ...(rosterUnread === null ? {} : { rosterUnread }) } }; + return { ok: true, value: { seats, workstreams } }; } catch (error) { return { ok: false, failure: describeFailure(error) }; } @@ -890,7 +797,7 @@ export function createLabReader(clients: LabClients): LabReader { } if (typeof orgId !== "string" || orgId.length === 0) return { refused: { message: noOrganization(clients.userId, "their session records none") } }; - const inventory = await readInventory(sessions, orgId); + const inventory = await readInventory(sessions); const [boardEntries, asks, resources, projects] = await Promise.all([ inventory.ok @@ -902,17 +809,17 @@ export function createLabReader(clients: LabClients): LabReader { if (!inventory.ok) { return { ok: false, failure: { message: `Asks are read from seat sessions, and the seat inventory did not load. ${inventory.failure.message}` } }; } + // A seat's sessions are on its worker flow, and name the worker in + // their state. One on a seat's flow that names none is still read: its + // asks are shown, unattributed. const seatIds = new Set(inventory.value.seats.map((s) => s.id)); const seatKinds = new Set(inventory.value.seats.map((s) => s.kind).filter((k): k is string => k !== null)); - const seatSessions = sessions.flatMap((s): Array<{ session: SessionSummary; seatId: string | null }> => - s.flowId != null - ? seatIds.has(s.flowId) - ? [{ session: s, seatId: s.flowId }] - : [] - : seatKinds.has(s.flowKind) - ? [{ session: s, seatId: null }] - : [], - ); + const seatSessions = sessions.flatMap((s): Array<{ session: SessionSummary; seatId: string | null }> => { + if (!seatKinds.has(s.flowKind)) return []; + const workerId = workerOf(s); + if (workerId === null) return [{ session: s, seatId: null }]; + return seatIds.has(workerId) ? [{ session: s, seatId: workerId }] : []; + }); try { const found = await inBatches(seatSessions, ASK_READ_BATCH, ({ session, seatId }) => readAsks(session, seatId)); return { ok: true, value: found.flat().sort((a, b) => a.since - b.since) }; diff --git a/packages/shift-manager/src/lib/workforce.ts b/packages/shift-manager/src/lib/workforce.ts new file mode 100644 index 0000000000..0b8063207b --- /dev/null +++ b/packages/shift-manager/src/lib/workforce.ts @@ -0,0 +1,35 @@ +/** + * The person's workers, through Workforce's client: their roster (their own + * workers and the standard ones, each naming the flow it runs on) and their + * sessions with each worker, found or started with `ensureWorkerSession`. + * + * The client is built from the Lab connection every other read uses, so it + * acts as the same person and carries the same credential on every request. + * + * `useWorkforce` lives in Shift Manager, not in a package: `@flow-state-dev/react` + * may import only `contracts`, `core` and `client`, and `@flow-state-dev/workforce` + * may not import `react`, so neither package can hold a hook over + * `createWorkforceClient`. An app builds the same client with `useMemo`. + */ +import { useMemo } from "react"; +import { createWorkforceClient, type WorkforceClient } from "@flow-state-dev/workforce/browser"; +import type { LabClients } from "./connection"; +import { useLab } from "./lab-data"; + +/** A workforce client for the Lab connection `clients` reads as. */ +export function workforceClientFor(clients: LabClients): WorkforceClient { + return createWorkforceClient({ + userId: clients.userId, + ...(clients.baseUrl === undefined ? {} : { baseUrl: clients.baseUrl }), + fetcher: clients.fetcher, + }); +} + +/** + * The workforce client for the Lab this page reads, one per connection. + * Throws outside a `LabProvider`. + */ +export function useWorkforce(): WorkforceClient { + const { clients } = useLab(); + return useMemo(() => workforceClientFor(clients), [clients]); +} diff --git a/packages/shift-manager/src/surfaces/ChiefOfStaff.tsx b/packages/shift-manager/src/surfaces/ChiefOfStaff.tsx index c2b88b7bd1..dd3c21957d 100644 --- a/packages/shift-manager/src/surfaces/ChiefOfStaff.tsx +++ b/packages/shift-manager/src/surfaces/ChiefOfStaff.tsx @@ -65,7 +65,7 @@ function Header({ snapshot }: { snapshot: LoadedSnapshot }) { let watching: string | null = null; if (snapshot.inventory.ok) { const { seats, workstreams } = snapshot.inventory.value; - const cos = chiefOfStaffOf(seats, snapshot.orgId); + const cos = chiefOfStaffOf(seats); status = cos.kind === "one" ? seatStates(snapshot).seats.get(cos.seat.id)?.status : undefined; watching = `watching ${plural(workstreams.length, "stream", "streams")} and ${plural(seats.length, "worker", "workers")}`; } @@ -187,7 +187,7 @@ function ChiefOfStaffConversation({ snapshot, gaps, lead }: { snapshot: LoadedSn ); } - const cos = chiefOfStaffOf(snapshot.inventory.value.seats, snapshot.orgId); + const cos = chiefOfStaffOf(snapshot.inventory.value.seats); if (cos.kind === "none") { return ( diff --git a/packages/shift-manager/src/surfaces/JumpTo.tsx b/packages/shift-manager/src/surfaces/JumpTo.tsx index d92397c8c8..cc22b2116d 100644 --- a/packages/shift-manager/src/surfaces/JumpTo.tsx +++ b/packages/shift-manager/src/surfaces/JumpTo.tsx @@ -61,7 +61,7 @@ export function JumpTo({ snapshot, gaps, onClose }: { snapshot: LoadedSnapshot; const message = query.slice(MESSAGE_PREFIX.length).trim(); if (message === "") return; if (!snapshot.inventory.ok) return setSendFailure("The Lab's seats didn't load, so there is no one to send this to."); - const cos = chiefOfStaffOf(snapshot.inventory.value.seats, snapshot.orgId); + const cos = chiefOfStaffOf(snapshot.inventory.value.seats); if (cos.kind !== "one") return setSendFailure("There isn't exactly one Shift Coordinator to send this to."); if (cos.seat.door === null) return setSendFailure(`${cos.seat.id} ${gaps.turn.noDoor}`); handToChiefOfStaff(message); diff --git a/packages/shift-manager/src/surfaces/Roster.tsx b/packages/shift-manager/src/surfaces/Roster.tsx index 36518022e6..029c00921c 100644 --- a/packages/shift-manager/src/surfaces/Roster.tsx +++ b/packages/shift-manager/src/surfaces/Roster.tsx @@ -1,6 +1,10 @@ /** - * Roster: every worker in the seat inventory, grouped on shift, on call and - * off shift, for all teams or one (`/roster[?team=]`). + * Roster: every worker the person has, grouped on shift, on call and off + * shift, for all teams or one (`/roster[?team=]`). The workers are the + * person's roster, read through Workforce's client: their own workers and the + * standard ones, each on the flow it names. A standard worker's row is the + * seat inventory's. The roster is read again with every snapshot, so a worker + * hired or fired on a turn shows on the next read. * * Every status, slot and count is read from the one `seatStates` result over * the snapshot, the same one the sidebar and the workstream panel draw, so a @@ -11,12 +15,15 @@ * with what its status means, and ON CALL FOR as boxed tags, a task or an ask * waiting on you tagged WAITING on the highlighter. */ -import { useSyncExternalStore } from "react"; +import { useEffect, useState, useSyncExternalStore } from "react"; +import type { RosterEntry } from "@flow-state-dev/workforce/browser"; import { PartialMark, ScreenTitle, SectionFailure, ShiftMark } from "../components/ui"; import { pickedTeam, seatStates, SHIFT_STATUSES, shiftCounts, teamsOf, type LoadedSnapshot, type SeatState, type ShiftStatus } from "../lib/derive"; import { readStatus } from "../lib/columns"; import { themeLabel, type ThemeLook } from "../lib/theme"; import { useLab } from "../lib/lab-data"; +import { describeFailure, STAFF_TEAM, type Failure, type Seat } from "../lib/reads"; +import { useWorkforce } from "../lib/workforce"; import { navigate } from "../lib/routes"; import type { Gaps } from "../gaps"; @@ -61,7 +68,59 @@ function useLookName(look: ThemeLook | undefined): string | null { return theme === undefined ? null : themeLabel(theme); } -function WorkerRow({ state, gaps }: { state: SeatState; gaps: Gaps }) { +/** + * The person's roster, read through Workforce's client with every snapshot: + * `undefined` until the first read lands. + */ +function useRoster(readAt: number): { entries: RosterEntry[] } | { failure: Failure } | undefined { + const workforce = useWorkforce(); + const [read, setRead] = useState<{ entries: RosterEntry[] } | { failure: Failure } | undefined>(undefined); + useEffect(() => { + let closed = false; + workforce + .roster() + .then((entries) => { + if (!closed) setRead({ entries }); + }) + .catch((error: unknown) => { + if (!closed) setRead({ failure: describeFailure(error) }); + }); + return () => { + closed = true; + }; + }, [workforce, readAt]); + return read; +} + +/** + * The person's own workers as rows beside the inventory's: each on the flow + * it names, with that flow's door, grouped by its id the way an inventory + * row is. + */ +function ownSeats(entries: readonly RosterEntry[], inventory: readonly Seat[]): Seat[] { + return entries + .filter((entry) => !entry.standard && !inventory.some((seat) => seat.id === entry.id)) + .map((entry) => { + const dot = entry.id.indexOf("."); + return { + id: entry.id, + kind: entry.flow, + door: inventory.find((seat) => seat.kind === entry.flow)?.door ?? null, + team: dot > 0 ? entry.id.slice(0, dot) : STAFF_TEAM, + name: dot > 0 ? entry.id.slice(dot + 1) : entry.id, + }; + }); +} + +/** A standard worker the roster lists and the inventory hasn't registered, as a row. */ +function standardSeats(entries: readonly RosterEntry[], inventory: readonly Seat[]): Seat[] { + return ownSeats( + entries.filter((entry) => entry.standard).map((entry) => ({ ...entry, standard: false })), + inventory, + ); +} + +function WorkerRow({ state, gaps, own }: { state: SeatState; gaps: Gaps; own: boolean }) { const { seat, status, held, asks } = state; const parked = held.filter((row) => readStatus(row.status) === "parked"); return ( @@ -70,11 +129,17 @@ function WorkerRow({ state, gaps }: { state: SeatState; gaps: Gaps }) { data-testid="roster-worker" data-seat-id={seat.id} data-status={status} + data-own={own ? "true" : "false"} >

{seat.name} {seat.team} + {own ? ( + + YOURS + + ) : null}

{seat.kind ?? "unknown kind"} @@ -150,16 +215,30 @@ export function RosterView({ }) { const { refresh } = useLab(); const lookName = useLookName(look); - if (!snapshot.inventory.ok) { + const roster = useRoster(snapshot.readAt); + const entries = roster !== undefined && "entries" in roster ? roster.entries : []; + const inventorySeats = snapshot.inventory.ok ? snapshot.inventory.value.seats : []; + const own = ownSeats(entries, inventorySeats); + // With the inventory unread, the standard workers the roster lists are still the person's. + const extra = snapshot.inventory.ok ? own : [...standardSeats(entries, inventorySeats), ...own]; + if (!snapshot.inventory.ok && extra.length === 0) { return (

void refresh()} testId="roster-inventory-failure" />
); } - const seats = snapshot.inventory.value.seats; + const seats = [...inventorySeats, ...extra]; + const withOwn: LoadedSnapshot = { + ...snapshot, + inventory: { + ok: true, + value: { ...(snapshot.inventory.ok ? snapshot.inventory.value : { workstreams: [] }), seats }, + }, + }; + const ownIds = new Set(own.map((seat) => seat.id)); const team = pickedTeam(seats, asked); - const states = seatStates(snapshot); + const states = seatStates(withOwn); const shown = [...states.seats.values()].filter((s) => team === null || s.seat.team === team); const counts = shiftCounts(states, team ?? undefined); const unread = Object.entries(snapshot.boards).flatMap(([workstreamId, boards]) => (boards.ok ? [] : [{ workstreamId, failure: boards.failure }])); @@ -207,6 +286,16 @@ export function RosterView({ ON CALL FOR
+ {snapshot.inventory.ok ? null : ( +
+ void refresh()} testId="roster-inventory-failure" /> +
+ )} + {roster !== undefined && "failure" in roster ? ( +

+ Your own workers didn't load: {roster.failure.message} +

+ ) : null} {snapshot.asks.ok ? null : (
void refresh()} testId="roster-asks-failure" /> @@ -234,7 +323,7 @@ export function RosterView({
    {group.map((state) => ( - + ))}
diff --git a/packages/shift-manager/src/surfaces/Sidebar.tsx b/packages/shift-manager/src/surfaces/Sidebar.tsx index d5af774fad..cea9bed8ec 100644 --- a/packages/shift-manager/src/surfaces/Sidebar.tsx +++ b/packages/shift-manager/src/surfaces/Sidebar.tsx @@ -370,11 +370,6 @@ export function Sidebar({ route, gaps, onJump, look }: { route: Route; gaps: Gap TEAMS
- {loaded?.inventory.ok && loaded.inventory.value.rosterUnread !== undefined ? ( -

- {loaded.inventory.value.rosterUnread} -

- ) : null} {loaded === undefined ? null : loaded.inventory.ok ? ( teamsOf(loaded.inventory.value.seats).map(({ team, seats }) => ( - ) : null, - // An open seat shows its kind, what it handles and its instructions - // under its row, and why its last "New conversation" failed, if it did. - leafDetail: (leaf: FlowNavigatorLeafState) => - isSeatKind(leaf.kind) ? ( - <> - {seatCreateError?.address === leaf.address && ( -

- Could not start a conversation: {seatCreateError.message} -

- )} - {panelSessionId === undefined || panelOrgId === undefined ? ( -

Loading…

- ) : ( - - )} - ) : null, + leafDetail: () => null, }), - [ - handleNewSession, - handleNewSeatConversation, - seatCreateError, - flow.isLoading, - panelSessionId, - panelOrgId, - resourceClient, - ] + [handleNewSession, flow.isLoading] ); const handleSelectedModelChange = useCallback( @@ -579,7 +515,8 @@ function KitchenSinkApp({ e2eSessionId, pickedLive }: { e2eSessionId: string | n const teamPanel = ( .`, and the row is - * keyed by that `seatId`. A seat declared in a worker file has no row. A seat a - * user hired for themselves, at `.~.`, has a row the rail - * may not read, and its `seatId` can equal an org-visible seat's; splitting its - * address would open the other seat's row. Both are handed over with no topic, - * so the detail says their instructions are not published and reads nothing. - * - * What a declared seat handles is its `WORKER.md`'s `description:`, which the - * shell carries by address (`SEAT_DESCRIPTIONS`). A seat with none draws none. - */ -import { SeatDetail, type PanelItemSource } from "@flow-state-dev/react"; -import { HIRED_ROSTER_RESOURCE, seatAddress, splitSeatAddress } from "@flow-state-dev/workforce/browser"; - -import { SEAT_DESCRIPTIONS } from "@/lib/workforce-shell"; - -export interface SeatPaneProps { - /** The rail's session: the instructions are read through it. */ - sessionId: string; - /** The organization that session is bound to, from its own record. */ - orgId: string; - /** The seat's kind, from the navigator row. */ - kind: string; - /** The seat's flow address, from the navigator row. */ - address: string; - /** The host's resource client, so the read carries the host's transport. Stable. */ - resourceClient: PanelItemSource; -} - -/** The roster topic of a seat hired into the whole organization; `undefined` for any other seat. */ -function publicRosterTopic(orgId: string, address: string): string | undefined { - const seatId = splitSeatAddress(orgId, address); - // A user-owned address splits to its seat id too; only the org-visible one rebuilds to itself. - return seatId !== undefined && seatAddress(orgId, seatId) === address ? seatId : undefined; -} - -export function SeatPane({ sessionId, orgId, kind, address, resourceClient }: SeatPaneProps) { - const description = (SEAT_DESCRIPTIONS as Record)[address]; - return ( -
- {description !== undefined && ( -

- {description} -

- )} - -
- ); -} diff --git a/apps/kitchen-sink/components/team-panel.tsx b/apps/kitchen-sink/components/team-panel.tsx index 47d5f8e791..36eb916ef2 100644 --- a/apps/kitchen-sink/components/team-panel.tsx +++ b/apps/kitchen-sink/components/team-panel.tsx @@ -1,43 +1,32 @@ "use client"; /** - * The shell's right panel: the organization's roster and the boards, whatever - * mode the app is in. + * The right-hand panel: the person's workers, and the mailbox's boards. * - * Layout only. The roster and the board lists are `@flow-state-dev/react` - * components; this places them, themes them, and supplies the roster's - * skipped-seat list, which the boot publishes and the roster cannot read for - * itself. + * The workers are the person's roster: the specialists the app's files + * declare, which everyone has, and any worker the person hired or forked, + * each with the flow it runs on. "Talk" opens the person's conversation with + * that worker, or starts one, through Workforce's client. * - * The roster reads through the assistant's session. Each board reads through - * its own mailbox's session, whose flow declares it, so a board is drawn before - * any assistant conversation exists and, when `live`, follows that mailbox's - * stream: a case the mailbox files shows without a reload. + * Each board reads through its own mailbox's session. */ import { useEffect, useState, type CSSProperties, type ReactNode } from "react"; import type { ClientFetch } from "@flow-state-dev/client"; -import { BoardList, Roster, type PanelRowSource } from "@flow-state-dev/react"; -import { HIRED_ROSTER_RESOURCE } from "@flow-state-dev/workforce/browser"; +import { BoardList, type PanelRowSource } from "@flow-state-dev/react"; +import type { RosterEntry, WorkforceClient } from "@flow-state-dev/workforce/browser"; -import { - ROSTER_BOOT_REPORT_REF, - SHELL_BOARDS, - problemsFromBootReport, -} from "@/lib/workforce-shell"; +import { SHELL_BOARDS } from "@/lib/workforce-shell"; -/** The panels' custom properties, set to this app's tokens. */ const PANEL_THEME = { "--fsd-panel-fg": "var(--color-foreground)", "--fsd-panel-muted-fg": "var(--color-muted-foreground)", } as CSSProperties; export interface TeamPanelProps { - /** - * The session the roster and the boot report read through. Its flow must - * declare both; `undefined` while the session is still being created. The - * boards do not wait for it. - */ - sessionId: string | undefined; + /** The person's workforce client. Pass a stable one: the roster is read again only when it changes. */ + workforce: WorkforceClient; + /** Open the person's conversation with a worker. */ + onTalk: (worker: RosterEntry) => Promise; /** The host's resource client. Pass a stable one — the panels fence on it. */ resourceClient: PanelRowSource; /** @@ -51,31 +40,13 @@ export interface TeamPanelProps { top?: ReactNode; } -export function TeamPanel({ sessionId, resourceClient, fetcher, live = false, top }: TeamPanelProps) { - const report = useRosterBootReport(resourceClient, sessionId); +export function TeamPanel({ workforce, onTalk, resourceClient, fetcher, live = false, top }: TeamPanelProps) { return (
{top}
-

Roster

- {report.error !== null && ( -

- {report.error}{" "} - -

- )} - {sessionId === undefined ? ( -

Loading…

- ) : ( - - )} +

Workers

+
{SHELL_BOARDS.map((board) => (
@@ -97,47 +68,80 @@ export function TeamPanel({ sessionId, resourceClient, fetcher, live = false, to ); } -/** An empty board, in the desk's words. */ function noCasesYet() { return

No cases filed here yet.

; } -/** - * What the last boot could not bring back into this organization's roster. - * - * Read through the same client the roster reads through. A read that fails is - * reported beside the roster with a retry, and not as a skipped seat: a roster - * shown without its skipped seats looks complete when it is not, and one with - * an invented skipped seat miscounts. - */ -function useRosterBootReport( - source: PanelRowSource, - sessionId: string | undefined, -): { problems: readonly string[]; error: string | null; retry: () => void } { - const [problems, setProblems] = useState([]); +/** The person's roster, each worker with its flow, what it handles, and "Talk". */ +function WorkerRoster({ workforce, onTalk }: { workforce: WorkforceClient; onTalk: (worker: RosterEntry) => Promise }) { + const roster = useRoster(workforce); + const [talkError, setTalkError] = useState<{ id: string; message: string } | null>(null); + if (roster.error !== null) { + return ( +

+ The roster could not be read: {roster.error}{" "} + +

+ ); + } + if (roster.workers === undefined) return

Loading…

; + return ( +
    + {roster.workers.map((worker) => ( +
  • +
    + {worker.id} + {worker.flow} + +
    + {worker.description !== null &&

    {worker.description}

    } + {talkError?.id === worker.id && ( +

    + Could not open a conversation: {talkError.message} +

    + )} +
  • + ))} +
+ ); +} + +function useRoster(workforce: WorkforceClient): { + workers: readonly RosterEntry[] | undefined; + error: string | null; + retry: () => void; +} { + const [workers, setWorkers] = useState(undefined); const [error, setError] = useState(null); const [attempt, setAttempt] = useState(0); useEffect(() => { - setProblems([]); setError(null); - if (sessionId === undefined) return; let current = true; - source - .listCollectionItems(sessionId, ROSTER_BOOT_REPORT_REF) - .then((page) => { - if (current) setProblems(problemsFromBootReport(page.items)); + workforce + .roster() + .then((entries) => { + if (current) setWorkers(entries); }) .catch((reason: unknown) => { - if (!current) return; - setError( - `The list of seats the last start skipped could not be read: ${ - reason instanceof Error ? reason.message : String(reason) - }`, - ); + if (current) setError(reason instanceof Error ? reason.message : String(reason)); }); return () => { current = false; }; - }, [source, sessionId, attempt]); - return { problems, error, retry: () => setAttempt((n) => n + 1) }; + }, [workforce, attempt]); + return { workers, error, retry: () => setAttempt((n) => n + 1) }; } diff --git a/apps/kitchen-sink/flows/chat-agent/flow.ts b/apps/kitchen-sink/flows/chat-agent/flow.ts index 7b626c1f5d..f3445daa56 100644 --- a/apps/kitchen-sink/flows/chat-agent/flow.ts +++ b/apps/kitchen-sink/flows/chat-agent/flow.ts @@ -29,7 +29,6 @@ import { approvalGate } from "./approval-gate"; import { askQuestion, collectForm, chooseOption } from "./human-input"; import { mem } from "./run/cognition"; import { bashCap } from "./shared/capabilities/features"; -import { workforcePanelResources } from "./shared/workforce-panels"; import { coalesceThinkingStyle, modeSchema, @@ -145,11 +144,8 @@ const chatAgentFlow = defineFlow({ // FIX-435: resources live in a single flat flow.resources map; their // intrinsic scope routes them to the right storage layer. - // `workforcePanelResources`: the roster and the boot report the shell's - // right panel reads through this flow's session. resources: { ...(mem.userResources ?? {}), - ...workforcePanelResources, }, // Tear down the bash sandbox at request end. Required when the bash diff --git a/apps/kitchen-sink/flows/chat-agent/shared/workforce-panels.ts b/apps/kitchen-sink/flows/chat-agent/shared/workforce-panels.ts deleted file mode 100644 index 6c342cd21f..0000000000 --- a/apps/kitchen-sink/flows/chat-agent/shared/workforce-panels.ts +++ /dev/null @@ -1,44 +0,0 @@ -/** - * The collections the shell's right panel reads, declared on the shell's flow. - * - * A panel read resolves its ref against the reading session's own flow, so the - * shell can only show the roster if `chat-agent` declares it. Each one is - * org-scoped, so a chat-agent session reads its own organization's rows and no - * other's. The boards are not here: each is read through its own mailbox's - * session, whose flow already declares it. - * - * - `HIRED_ROSTER_RESOURCE` — the hired roster, from the same factory the - * admin flow and the boot reload use, so there is one declaration of that - * contract. Declared under the package's key, not a name of this app's, - * because the operator's hire (`flows/workforce-admin/`) writes the roster - * there; a second key for the same collection would be refused as a - * resource collision. - * - `rosterBootReport` — what the last boot could not bring back, one row per - * organization. The boot writes it (`lib/roster-reload-report.ts`); nothing - * in this flow does. The key and the row's schema are declared in - * `lib/` (`workforce-shell.ts` and `roster-boot-report-schema.ts`), since - * the boot writer must reach them without importing this flow module. - */ -import { defineResourceCollection } from "@flow-state-dev/core"; -import { defineHiredRosterCollection, HIRED_ROSTER_RESOURCE } from "@flow-state-dev/workforce"; - -import { rosterBootReportSchema } from "@/lib/roster-boot-report-schema"; -import { ROSTER_BOOT_REPORT_PREFIX, ROSTER_BOOT_REPORT_REF } from "@/lib/workforce-shell"; - -/** - * Org-scoped and shared across flows: the boot writes it with no flow at all, - * so a flow-isolated key would be one the boot cannot address. - */ -export const rosterBootReportCollection = defineResourceCollection({ - pattern: `${ROSTER_BOOT_REPORT_PREFIX}*`, - scope: "org", - flowIsolation: false, - stateSchema: rosterBootReportSchema, - client: { state: { read: true }, expose: ["problems"] }, -}); - -/** Spread into the shell flow's `resources`. */ -export const workforcePanelResources = { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [ROSTER_BOOT_REPORT_REF]: rosterBootReportCollection, -}; diff --git a/apps/kitchen-sink/flows/workforce-admin/flow.ts b/apps/kitchen-sink/flows/workforce-admin/flow.ts deleted file mode 100644 index 0b791e705c..0000000000 --- a/apps/kitchen-sink/flows/workforce-admin/flow.ts +++ /dev/null @@ -1,385 +0,0 @@ -/** - * workforce-admin — hire a seat while the app is running, and fire one. - * - * The reference HTTP path for a durable hire, and **only** that: the seat-facing - * hire a worker reaches through its own tools is FIX-1480's and composes this - * roster rather than standing up a second one. Nothing here is the API a Lab - * copies. - * - * **The shape of a hire, and why it is in this order.** - * - * 1 refuse anything this deploy can decide is wrong — no org, an org that is - * not a legal address segment, a kind this app does not carry, an address - * something already holds. Nothing has been written at this point. - * 2 MINT the seat. `hireWorkforce` runs the kind's own settings schema, so a - * setting the kind refuses is refused here — still before any row exists, - * which is what BR-9's "no row, no registration" requires. Minting is not - * registering; nothing is reachable yet. - * 3 WRITE the row, with `create()`. Its already-exists throw IS the refusal - * of a duplicate hire, including two arriving at once. Never `upsert()`. - * 4 REGISTER. A hire that answers is a hire that was written down, so the - * row goes first. - * 5 if registration fails, DELETE the row this call created, then report the - * registration failure. A hire that failed leaves nothing behind. - * - * **One seat per call.** There is no batch form, deliberately: a batch cannot - * honour "a refused hire changes nothing" without atomic admission nobody here - * needs. - * - * **What a fire does not do.** It removes the row, the address and any - * inventory row, through Workforce's one removal of a hired seat. It cancels - * nothing — a run already going finishes and its items are persisted — and it - * deletes no sessions, state or resources. Those are a separate, irreversible - * operation. And it is durable immediately but process-wide only at the next - * boot: a sibling process serving the seat keeps serving it until it restarts. - * That window is the same one a hire has, and it is documented rather than - * closed, because closing it needs cross-process invalidation — a subsystem, - * not a line. - */ - -import { defineFlow, handler } from "@flow-state-dev/core"; -import type { JsonObject } from "@flow-state-dev/core"; -import type { ResourceCollectionRef } from "@flow-state-dev/core/types"; -import { - defineHiredRosterCollection, - defineHiredRosterPrivateCollection, - defineSeatInventoryCollection, - encodeUserSegment, - hiredSeatManifest, - hireWorkforce, - newIncarnation, - removeHiredSeat, - resolveHiredSeatLocation, - seatAddress, - tagIncarnation, - toHiredSeatRow, - type HiredSeatRelease, - type HiredSeatRow, -} from "@flow-state-dev/workforce"; -import { z } from "zod"; - -import { workforceRegistrar } from "@/lib/workforce-registrar"; -import { adminPrincipalResolver } from "@/lib/workforce-admin-auth"; -import { kitchenSinkKinds } from "@/workforce/hire"; - -const roster = defineHiredRosterCollection(); -/** User-owned rows. No browser read; the single-segment roster does not list them. */ -const rosterPrivate = defineHiredRosterPrivateCollection(); -/** The org's seat inventory, so `fire` removes a fired seat's row through the shared removal. */ -const seatInventory = defineSeatInventoryCollection(); - -/** The kinds a hire may name, and the sentence that lists them in a refusal. */ -const KIND_NAMES = Object.keys(kitchenSinkKinds).sort(); - -const hireInput = z.object({ - /** The seat's id within the organization — `"support.ada"`. */ - seatId: z.string().min(1), - /** The flow kind to hire it into. */ - flow: z.string().min(1), - /** The settings bag handed to that kind. */ - settings: z.record(z.unknown()).default({}), - /** The seat's instructions. */ - instructions: z.string().optional(), -}); - -const hireOutput = z.object({ - /** The address the seat now answers on. */ - address: z.string(), - /** The organization it was hired into — from the credential, never the body. */ - orgId: z.string(), -}); - -const fireInput = z.object({ - seatId: z.string().min(1), - /** - * Which row: a legacy org row, or the caller's own user-owned one. Omitted, - * the only row under the id; refused when the caller has both. - */ - owner: z.enum(["organization", "me"]).optional(), -}); - -const fireOutput = z.object({ - address: z.string(), - orgId: z.string(), - /** Whether an address stopped answering in THIS process. */ - released: z.boolean(), -}); - -/** - * The org the call runs under, from the verified principal. - * - * `ctx.org` exists because the resolver returned one. There is no unscoped - * roster to fall back to, so a call without one is refused rather than written - * somewhere no flow can read. - */ -function orgOf(ctx: { org?: { identity: { id: string; orgId?: string } } }): string { - // `identity.orgId` first: `identity.id` is the storage key, which carries the - // flow when an app isolates its org state, and a roster keyed by that would - // be a different roster per flow. - const orgId = ctx.org?.identity.orgId ?? ctx.org?.identity.id; - if (typeof orgId !== "string" || orgId.length === 0) { - throw new Error( - "This admin credential resolves no organization, and a roster is organization-scoped — " + - "there is nothing to write to." - ); - } - return orgId; -} - -/** - * The roster collection, through `ctx.resources`' loose typing. - * - * Typed at the storage shape rather than at `HiredSeatRow`: the row's - * `settings` is an open bag, which is deliberately wider than `JsonObject`'s - * recursive value type. The schema on the collection is what validates a row; - * this cast only names the accessor. - */ -function rosterOf(ctx: { resources: Record }): ResourceCollectionRef { - return ctx.resources.roster as unknown as ResourceCollectionRef; -} - -function privateRosterOf(ctx: { resources: Record }): ResourceCollectionRef { - return ctx.resources.rosterPrivate as unknown as ResourceCollectionRef; -} - -function inventoryOf(ctx: { resources: Record }): ResourceCollectionRef { - return ctx.resources.seatInventory as unknown as ResourceCollectionRef; -} - -function userOf(ctx: { session: { identity: { userId?: string } } }): string { - const userId = ctx.session.identity.userId; - if (typeof userId !== "string" || userId.length === 0) { - throw new Error("This admin credential resolves no user, and a hire is user-owned."); - } - return userId; -} - -/** A row on its way into storage. See {@link rosterOf} for why this is a cast. */ -function asStored(row: HiredSeatRow): JsonObject { - return row as unknown as JsonObject; -} - -const hire = handler({ - name: "workforce-admin-hire", - inputSchema: hireInput, - outputSchema: hireOutput, - execute: async (input, ctx) => { - const orgId = orgOf(ctx); - - // Refuses a dotted, empty or over-long org before anything else looks at - // it: without this, `acme` + `support.ada` and `acme.support` + `ada` spell - // one address and the second hire silently rebinds the first. - const userId = userOf(ctx); - // User-owned seats carry the user in the address, so two members can hire - // the same seat id without sharing one address. The pin is the row, below. - const address = seatAddress(orgId, input.seatId, userId); - - if (!Object.hasOwn(kitchenSinkKinds, input.flow)) { - throw new Error( - `This app carries no flow kind "${input.flow}". It carries: ${KIND_NAMES.join(", ")}.` - ); - } - - // Before the row is written, and naming what holds it. `register` would - // also refuse a duplicate, but only after a row existed — which would make - // every refused hire depend on the compensating delete working. - const held = workforceRegistrar.kindAt(address); - if (held !== undefined) { - throw new Error( - `"${address}" is already served by a flow of kind "${held}". Fire that seat first, or hire under another id.` - ); - } - - const row = toHiredSeatRow({ - seatId: input.seatId, - flow: input.flow, - settings: input.settings, - instructions: input.instructions ?? null, - owningOrgId: orgId, - ownerUserId: userId, - // A fresh one per hire, so a fire of this seat can tell its rows from a - // replacement's at the same address. - incarnation: newIncarnation(), - }); - - // Minted from exactly what will be stored, not from the request — so a - // seat that hires is a seat the stored row can rebuild at the next boot. - // This is also where the kind's own settings schema runs, which is why it - // happens before anything is written. A row whose owning org disagrees - // with this cell comes back as a reason and is not written. - const record = hiredSeatManifest(orgId, row); - if ("problem" in record) { - throw new Error(record.problem); - } - const [seat] = hireWorkforce([record.manifest], { workerFlows: kitchenSinkKinds }); - if (seat === undefined) { - throw new Error(`"${address}" could not be hired, and no reason was given.`); - } - // The seat carries the row's incarnation, as a boot's reload tags it. - tagIncarnation(seat, row.incarnation); - - // User-owned, so the key is nested. The browser roster is single-segment - // and does not list it. `create`, never `upsert`: the already-exists throw - // IS the duplicate refusal, and it survives a second hire arriving at the - // same moment. - const owner = `~${encodeUserSegment(userId)}`; - await privateRosterOf(ctx).create( - { owner, seat: input.seatId }, - asStored(row) - ); - - try { - // `registerFromRoster`, not `register`: this records that the address is - // held by an instance THIS app minted from a roster row, which is what - // `fire` checks before releasing it (BR-28). - workforceRegistrar.registerFromRoster(seat, { - pin: record.manifest.ownerPin, - }); - } catch (error) { - // The row this call created, removed — a hire that failed leaves nothing - // behind. If the delete also fails, the stranded row is skipped and named - // at the next boot rather than failing it, and the caller still hears - // about the registration failure rather than about the cleanup. - try { - await privateRosterOf(ctx).delete({ owner: `~${encodeUserSegment(userId)}`, seat: input.seatId }); - } catch (cleanupError) { - console.error( - `[workforce-admin] "${address}" was written and could not be registered, and its row could ` + - `not be removed either — the next boot will skip and name it: ${String(cleanupError)}` - ); - } - throw error; - } - - ctx.emit.message(`Hired ${address} as ${input.flow}.`); - return { address, orgId }; - }, -}); - -const fire = handler({ - name: "workforce-admin-fire", - inputSchema: fireInput, - outputSchema: fireOutput, - execute: async (input, ctx) => { - const orgId = orgOf(ctx); - const userId = userOf(ctx); - - // Org-scoped, so another organization's seat is not reachable by fire even - // by exact id. A file-declared seat has no row here either, which is the - // same refusal reached from the other side — its folder is where it is - // removed. User-owned rows live on the private collection; a legacy - // org-visible row is still the flat key. Workforce decides which row the - // seat id names, the same way its own `fire` does. - const located = await resolveHiredSeatLocation({ - seatId: input.seatId, - owner: input.owner, - roster: rosterOf(ctx), - privateRoster: privateRosterOf(ctx), - userId, - // A retry after a fire that died past the caller's own row stays theirs. - leftoverAt: { orgId, inventory: inventoryOf(ctx) }, - }); - // A user-owned row answers on `.~.`. A legacy flat row, - // and a file-declared seat, stay on `.`. - const address = seatAddress(orgId, input.seatId, located.ownerUserId); - - // Workforce's one removal of a hired seat: roster row, then the address, - // then the seat's inventory row. This app's hire writes no inventory row, - // so there is usually none to remove; going through the shared path keeps - // that true if it starts to. - const removed = await removeHiredSeat({ - orgId, - roster: located.roster, - key: located.key, - inventory: inventoryOf(ctx), - address, - isHeld: (at) => workforceRegistrar.kindAt(at) !== undefined, - release: (at, storedKind) => releaseIfMintedHere(at, storedKind), - }); - - switch (removed.outcome) { - case "nothing": - throw new Error( - workforceRegistrar.kindAt(address) === undefined - ? `This organization hired no seat "${input.seatId}".` - : `"${address}" was not hired through this action — a seat declared in \`workforce/teams/\` is ` + - `removed by editing its folder, not by firing it.` - ); - case "unreadable": - ctx.emit.message(`Removed the unreadable roster row "${input.seatId}".`); - return { address, orgId, released: false }; - case "already-gone": - ctx.emit.message(`${address} was already fired; removed its leftover inventory row.`); - return { address, orgId, released: false }; - case "removed": - ctx.emit.message(`Fired ${removed.address}.`); - return { address: removed.address, orgId, released: removed.released }; - } - }, -}); - -/** - * Release `address` only when it is held by the instance this app minted from - * the row being removed. Called by the shared removal between its two deletes. - */ -function releaseIfMintedHere(address: string, storedKind: string): HiredSeatRelease { - // Released ONLY when the address is held by the instance this row minted - // (BR-28). **Two clauses, because neither subsumes the other**, and each - // fails a case the other admits: - // - // - PROVENANCE (`isFromRoster`) is what BR-28 is actually written in - // terms of. Kind equality alone is a weaker proxy: a seat declared in - // `workforce/teams/` at this address carrying the row's OWN kind - // passes it, and firing would unregister a file-declared seat — - // contradicting the refusal in `fire`, which promises such a - // seat is removed by editing its folder. Reachable: hire a seat, later - // add a folder declaring one at the same address with the same kind, - // restart. The file seat registers first, the reload's duplicate is - // skipped and named (BR-21), and the row survives. - // - KIND still matters because a mark can go STALE. Provenance records - // that this app registered the address; it cannot see the address - // being re-taken by a different instance afterwards. When the kinds - // disagree, whatever is there now is not what the mark refers to. - // - // `kindAt` gates both, and only when something is actually there: an - // address nothing holds is the ordinary stranded-row cleanup (a sibling - // process's registration, or a compensating delete that failed), which - // falls through to `released: false` with nothing to report. - const liveKind = workforceRegistrar.kindAt(address); - const mintedHere = workforceRegistrar.isFromRoster(address); - if (liveKind !== undefined && (!mintedHere || liveKind !== storedKind)) { - console.error( - `[workforce-admin] removed the roster row for "${address}" (kind "${storedKind}"), but the ` + - `address is held by a flow of kind "${liveKind}" that ` + - (mintedHere - ? "no longer matches the stored kind" - : "this app did not register from that row") + - " — leaving it registered." - ); - return "held-by-another"; - } - - return workforceRegistrar.unregister(address) ? "released" : "not-held"; -} - -/** - * The admin flow. Its resolver is its own, and `fsdev.config.ts` registers this - * flow **only** when a credential is configured — see `lib/workforce-admin-auth.ts`. - */ -const workforceAdminFlow = defineFlow({ - kind: "workforce-admin", - requireUser: true, - authentication: { - resolvePrincipal: adminPrincipalResolver(), - requireUser: true, - }, - resources: { roster, rosterPrivate, seatInventory }, - actions: { - hire: { inputSchema: hireInput, block: hire }, - fire: { inputSchema: fireInput, block: fire }, - }, -}); - -const flow = workforceAdminFlow(); - -export default flow; diff --git a/apps/kitchen-sink/fsdev.config.ts b/apps/kitchen-sink/fsdev.config.ts index 61671a8490..47d73765ab 100644 --- a/apps/kitchen-sink/fsdev.config.ts +++ b/apps/kitchen-sink/fsdev.config.ts @@ -19,15 +19,11 @@ import { after } from "next/server"; import path from "node:path"; import { createGateway } from "@ai-sdk/gateway"; import { createFlowState, inMemoryStores, filesystemStores, type FlowState } from "@flow-state-dev/engine"; -import type { FlowInstance } from "@flow-state-dev/core/types"; import { createSessionClient } from "@flow-state-dev/client"; import { OpenAIVoiceProvider } from "@flow-state-dev/voice-openai"; import { vercelPostgresStores } from "@flow-state-dev/vercel/store"; import { createScheduledTransportAdapter } from "@flow-state-dev/scheduled"; import { setScheduleIndexImpl } from "@/lib/schedule-index"; -import { setWorkforceRegistrarImpl, workforceRegistrar } from "@/lib/workforce-registrar"; -import { admitReloadedSeats } from "@/lib/roster-reload-report"; -import { adminCredentialConfigured } from "@/lib/workforce-admin-auth"; import { KITCHEN_SINK_ORG_ID, KITCHEN_SINK_USER_ID, @@ -38,14 +34,12 @@ import { createKitchenSinkTestModelResolver } from "@/test/mock-flowstate"; import chatAgentFlow from "@/flows/chat-agent/flow"; import richTextComponentFlow from "@/flows/rich-text-component/flow"; import weeklyDigestFlow from "@/flows/weekly-digest/flow"; -import workforceAdminFlow from "@/flows/workforce-admin/flow"; -import { hireKitchenSinkWorkforce, kitchenSinkKinds } from "@/workforce/hire"; +import { buildKitchenSinkWorkforce } from "@/workforce/hire"; import { describePreRenameMarks, findPreRenameMarks, mergeSeatFlows, openMailboxes, - reloadHiredSeats, } from "@flow-state-dev/workforce"; import { bullmqWorker } from "@flow-state-dev/bullmq"; @@ -75,48 +69,33 @@ const pgStores = vercelPostgresStores(); // the pool, leaving the proxy a no-op — matching in-memory's lack of scheduling). setScheduleIndexImpl(pgStores.scheduleIndex); -// The team under `workforce/`, hired before the runtime is assembled. +// The team under `workforce/`, built before the runtime is assembled. // -// Hiring is async because a seat's configuration lives in its own `WORKER.md`: -// the roster is read from files rather than written here, which is the whole -// point of the demonstration. `createFlowState({ flows })` takes a resolved -// map, so the two are reconciled by awaiting at module scope rather than by -// registering into a running FlowState: +// Async because a worker's configuration lives in its own `WORKER.md`: the +// roster is read from files rather than written here, which is the whole point +// of the demonstration. `createFlowState({ flows })` takes a resolved map, so +// the two are reconciled by awaiting at module scope: what this app serves is +// still the single `flows` map below, and the registry's duplicate-id and +// cross-flow schema checks still run at construction. // -// - One declaration stays one declaration. What this app serves is still the -// single `flows` map below, and the registry's duplicate-id and cross-flow -// schema checks still run at construction — a bad seat fails the boot -// instead of the first request that happens to address it. -// - An async boot is also the half a durable roster needs: reloading -// previously hired seats out of the store on the next boot is another -// await on this line. Adding a seat to an *already running* app is a -// different question, with ordering and in-flight-request consequences -// this app cannot answer by itself, and is left to FIX-1475. +// The workers are data. Their copies are one per worker flow, the same +// however many workers there are, so a worker a user hires or forks through +// the roster flow runs at once, on every process, with nothing registered and +// nothing to reload at the next boot. // // Both the Next.js route handlers and the `fsdev` CLI import this module, so -// both serve the same seats from the same files. -const workforce = await hireKitchenSinkWorkforce(); +// both serve the same workers from the same files. +const workforce = await buildKitchenSinkWorkforce(); -// A folder the loader could not read is a seat this app does not have. Report -// it once at boot rather than letting the roster come up quietly short. +// A folder the loader could not read is a worker this app does not have. +// Report it once at boot rather than letting the roster come up quietly short. for (const failedPath of workforce.errors) { console.error(`[workforce] could not read ${failedPath}`); } -// The admin path is registered ONLY when a credential is configured, which is -// what makes it fail closed: a default deployment has no `workforce-admin` -// address at all, rather than one standing behind a check somebody could get -// wrong. The module is imported either way — importing it registers nothing. -const adminFlows: Record> = adminCredentialConfigured() - ? { workforceAdmin: workforceAdminFlow } - : {}; - // One instance per mailbox KIND the tree selected, never one per mailbox — a // mailbox kind is a singleton, so its address is its kind and every mailbox is -// a named session on it. Seats go the other way, one entry per -// seat, because a seat kind is a `collection` and every seat is its own -// addressable copy. Both lines follow the kind's declared cardinality; neither -// is this app choosing a convention. +// a named session on it. // // These replace the hand-registered built-in this app used to carry: only the binder hands a kind the ledgers a roster minted, so // an instance built by hand answers no board call however many `boards:` lines @@ -125,10 +104,11 @@ const mailboxFlows = Object.fromEntries( workforce.mailboxFlows.map((instance) => [instance.id, instance]) ); -// Seats are addressed by their own ids (`support.devices`, `support.general`, …), -// which is what a caller puts on the URL and what `fsdev run` takes. An org -// seat's id is its bare folder name, so `mergeSeatFlows` refuses one that is -// already a flow's id rather than letting it replace that flow. +// The workforce's copies are addressed by their flow's kind (`agent`, and +// `workforce-roster` for the roster flow). A session with a worker is a session +// on its flow's copy, created naming the worker. `mergeSeatFlows` refuses a +// copy at an id a flow of this app already holds rather than letting it +// replace that flow. const flowstate = createFlowState({ flows: mergeSeatFlows( { @@ -136,9 +116,8 @@ const flowstate = createFlowState({ chatAgent: chatAgentFlow, richTextComponent: richTextComponentFlow, weeklyDigest: weeklyDigestFlow, - ...adminFlows, }, - workforce.seats + workforce.copies ), models: { default: DEFAULT_KITCHEN_SINK_MODEL, @@ -225,133 +204,23 @@ const flowstate = createFlowState({ worker: bullmqDispatch ? bullmq : undefined, adapters: [createScheduledTransportAdapter()], // Who every caller is, for every flow that brings no resolver of its own: - // the assistant's flow, every seat, every mailbox. One organization and one - // user, both constants, read from nothing on the request - // (`lib/kitchen-sink-principal.ts`). `workforce-admin` and `weekly-digest` - // keep their own. + // the assistant's flow, the workforce's copies, every mailbox. One + // organization and one user, both constants, read from nothing on the + // request (`lib/kitchen-sink-principal.ts`). `weekly-digest` keeps its own. resolvePrincipal: resolveKitchenSinkPrincipal, onError: (error, ctx) => { console.error(`[flowstate] ${ctx.method} ${ctx.path}:`, error.message); }, }); -// --------------------------------------------------------------------------- -// The durable half: seats hired while a PREVIOUS run of this app was serving. -// -// After `createFlowState`, not beside the file hire above, because the stores -// only exist once the FlowState does. Awaited at module scope for the reason -// the file hire is: both the Next route handlers and the `fsdev` CLI import -// this module, so finishing here is what guarantees no request arrives -// mid-reload and sees a roster that is half-loaded. -// -// Seats are admitted ONE AT A TIME. A batch keeps the earlier entries when a -// later one is refused and ends there, so one refusable row would take the rest -// of the roster with it and fail the boot — which is the degrade rule broken by -// mechanism rather than by intent. -// -// The cost this accepts, stated rather than hidden: resolving the runtime here -// opens the store pool at module load instead of on the first request. A -// durable roster cannot be served without reading it before the first request, -// so the eager open is the price of the feature rather than an oversight. -// --------------------------------------------------------------------------- const runtime = await flowstate.getRuntime(); -// Install the admission door behind the proxy the admin flow imports. Before -// the reload, so the two go through one seam rather than two. -setWorkforceRegistrarImpl({ - register: (flow) => flowstate.register(flow), - unregister: (id) => flowstate.unregister(id), - // From the runtime's registry because `FlowState` publishes no read of what - // holds an address — `meta.flowKeys` answers which ids, not which kinds. - // Recorded as a follow-up rather than quietly normalised. - kindAt: (id) => runtime.registry.get(id)?.kind, -}); - -/** - * What the boot brought back, and what it could not. - * - * The log lines below print it. The browser does not read this: the shell's - * roster panel reads the per-organization report `admitReloadedSeats` writes. - * - * `reportErrors` is kept apart from `problems`: a report that failed to write - * describes a seat that *was* admitted, so it must never inflate the "stored - * seat(s) could not be brought back" count below. - */ -export const hiredRosterReload: { seats: string[]; problems: string[]; reportErrors: string[] } = { - seats: [], - problems: [], - reportErrors: [], -}; - -{ - // The app names which organizations to reload — the framework cannot, because - // there is no org-filtered read path to inherit. Here that is every org this - // deployment has a record for; `orgId` rather than `id`, since the record's - // id is a storage key that carries the flow when org state is isolated. - // Deliberately every stored org, not just the ones with a configured admin - // credential: a hired seat should keep running after its org's token is - // rotated out of `WORKFORCE_ADMIN_TOKENS`, since firing it is a separate act - // from revoking who can hire and fire. - const orgIds = [ - ...new Set((await runtime.stores.org.list()).map((record) => record.orgId)), - ].sort(); - - const reload = await reloadHiredSeats({ - stores: runtime.stores, - orgIds, - workerFlows: kitchenSinkKinds, - }); - hiredRosterReload.problems.push(...reload.problems); - - // One organization at a time, so a refusal is filed under the organization - // the seat was hired for. Each organization's report is written to its own - // scope, which is where the shell's roster panel reads it. Refusals also go - // into the flat list above, which is what the log lines below print. - const admitted = await admitReloadedSeats({ - reload, - stores: runtime.stores, - // Through the registrar, not `flowstate.register`: these seats came from - // roster rows, and that provenance is what `fire` checks before it - // releases an address (BR-28). Registering them directly would leave - // every reloaded seat unfireable after a restart. - admit: (seat) => - workforceRegistrar.registerFromRoster( - seat, - seat.ownerPin !== undefined ? { pin: seat.ownerPin } : undefined - ), - }); - hiredRosterReload.seats.push(...admitted.seats); - hiredRosterReload.problems.push(...admitted.problems); - hiredRosterReload.reportErrors.push(...admitted.reportErrors); - - if (hiredRosterReload.seats.length > 0) { - console.log( - `[workforce] reloaded ${hiredRosterReload.seats.length} hired seat(s): ${hiredRosterReload.seats.join(", ")}`, - ); - } - for (const problem of hiredRosterReload.problems) { - console.error(`[workforce] skipped a hired seat — ${problem}`); - } - if (hiredRosterReload.problems.length > 0) { - console.error( - `[workforce] ${hiredRosterReload.problems.length} stored seat(s) could not be brought back; ` + - `the rest of the roster is serving`, - ); - } - // A report-write failure is not a skipped seat — the seat above is running. - // Only the roster panel's picture of it, for that one organization, is - // stale until the next boot. - for (const reportError of hiredRosterReload.reportErrors) { - console.error(`[workforce] a roster boot report could not be written — ${reportError}`); - } -} - // --------------------------------------------------------------------------- // The mailboxes the tree declared, opened. // -// After `createFlowState`, not beside the file hire above, because opening a +// After `createFlowState`, not beside the workforce build above, because opening a // mailbox is a session create and there is no session route until the -// FlowState exists. Awaited at module scope for the reason the hire is: both +// FlowState exists. Awaited at module scope for the reason the build is: both // the Next route handlers and the `fsdev` CLI import this module, so finishing // here is what guarantees no request arrives before the mailboxes are open. // diff --git a/apps/kitchen-sink/lib/mailbox-landing-control.ts b/apps/kitchen-sink/lib/mailbox-landing-control.ts index e4758368cf..55c00f8e19 100644 --- a/apps/kitchen-sink/lib/mailbox-landing-control.ts +++ b/apps/kitchen-sink/lib/mailbox-landing-control.ts @@ -24,9 +24,16 @@ * can never reach a deployed build. The published kind has no switch that * stops a routed answer landing, and must not. */ -import { defineFlow, generator, type BlockDefinition, type DefinedCapability } from "@flow-state-dev/core"; +import { defineFlow, generator, handler, sequencer, type BlockDefinition, type DefinedCapability } from "@flow-state-dev/core"; import { resolveActivePresets } from "@flow-state-dev/core/capability"; -import { AGENT_KIND, mailboxNotifyInputSchema, workerConfigSchema, type MailboxNotifyInput } from "@flow-state-dev/workforce"; +import { + AGENT_KIND, + mailboxNotifyInputSchema, + workerConfigOf, + workerConfigSchema, + type MailboxNotifyInput, + type WorkerInstallation, +} from "@flow-state-dev/workforce"; import { z } from "zod"; import { goalControl } from "./goal-control"; @@ -53,19 +60,26 @@ function grantedTools(capability: DefinedCapability): Record>, mailboxPost: DefinedCapability) { +export function mailboxLandingControl( + catalog: Record>, + mailboxPost: DefinedCapability, + installation: WorkerInstallation, +) { if (goalControl() !== "no-landing") return undefined; const kindCatalog = { ...grantedTools(mailboxPost), ...catalog }; const settings = workerConfigSchema().extend({ tools: z.array(z.string()).optional() }); type Settings = z.infer; - const tools = (_input: unknown, ctx: { flow: { config: unknown } }): BlockDefinition[] => - ((ctx.flow.config as Settings).tools ?? []) + const config = (ctx: { session: object }) => workerConfigOf(ctx) as Settings; + const tools = (_input: unknown, ctx: { session: object }): BlockDefinition[] => + (config(ctx).tools ?? []) .filter((name) => kindCatalog[name] !== undefined) .map((name) => kindCatalog[name]!); const prompt = [ - (_input: unknown, ctx: { flow: { config: unknown } }) => (ctx.flow.config as Settings).teamInstructions, - (_input: unknown, ctx: { flow: { config: unknown } }) => (ctx.flow.config as Settings).instructions, + (_input: unknown, ctx: { session: object }) => config(ctx).teamInstructions, + (_input: unknown, ctx: { session: object }) => config(ctx).instructions, ]; const answerPost = generator({ name: "agent-answer", @@ -93,19 +107,40 @@ export function mailboxLandingControl(catalog: Record input.message, tools, }); + // The turn's worker, loaded before the answer reads its settings. + const resolve = (inputSchema: T) => + handler({ + name: "agent-resolve-worker", + inputSchema, + resources: { ...installation.resources }, + execute: async (_input, ctx) => { + await installation.resolveWorker(ctx, AGENT_KIND); + }, + }); + const turnInput = z.object({ message: z.string() }); return defineFlow({ kind: AGENT_KIND, cardinality: "collection", configSchema: settings, + session: installation.session(), + resources: { ...installation.resources }, actions: { run: { - inputSchema: z.object({ message: z.string() }), - block: answerTurn, + inputSchema: turnInput.strict(), + block: sequencer({ name: "agent-run", inputSchema: turnInput }).tap(resolve(turnInput)).step(answerTurn), userMessage: (input: { message: string }) => input.message, }, }, internal: { - actions: { onMailboxPost: { inputSchema: mailboxNotifyInputSchema, block: answerPost, userMessage: heard } }, + actions: { + onMailboxPost: { + inputSchema: mailboxNotifyInputSchema, + block: sequencer({ name: "agent-heard-post", inputSchema: mailboxNotifyInputSchema }) + .tap(resolve(mailboxNotifyInputSchema)) + .step(answerPost), + userMessage: heard, + }, + }, }, } as never); } diff --git a/apps/kitchen-sink/lib/roster-boot-report-schema.ts b/apps/kitchen-sink/lib/roster-boot-report-schema.ts deleted file mode 100644 index 88720e892a..0000000000 --- a/apps/kitchen-sink/lib/roster-boot-report-schema.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * The shape of the boot's skipped-seat report. - * - * A leaf module like `lib/workforce-shell.ts`, but not folded into it: that - * module's contract is zero imports, and this schema needs zod. Both the boot - * writer (`lib/roster-reload-report.ts`) and the shell's flow - * (`flows/chat-agent/shared/workforce-panels.ts`) import it from here, so - * there is one declaration of what a report row holds. - */ -import { z } from "zod"; - -/** What the report holds: the problems the roster panel shows beside the seats. */ -export const rosterBootReportSchema = z.object({ - problems: z.array(z.string()), -}); - -export type RosterBootReport = z.infer; diff --git a/apps/kitchen-sink/lib/roster-reload-report.ts b/apps/kitchen-sink/lib/roster-reload-report.ts deleted file mode 100644 index 540996d7cf..0000000000 --- a/apps/kitchen-sink/lib/roster-reload-report.ts +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Admit the seats a boot reload brought back, and publish what each - * organization could not get back. - * - * The roster panel shows two numbers: the seats that answer, and the seats - * that were skipped. Skipped seats never became roster rows, so the panel can - * only get them from something the boot writes. This writes one report row - * per organization, into that organization's own scope, where the shell's - * flow declares it readable. - * - * A seat can be skipped in two places, and both go into the report: - * - * - by the reload, which could not turn a stored row into a seat. Those - * arrive in the reload's per-organization slices. - * - by the registry, which refused a seat the reload did build. Those happen - * here, and are filed under the organization the seat was hired for. - * - * Every organization the reload covered is written, including the clean ones. - * A clean organization gets an empty list, so last boot's problems do not stay - * on screen after they are fixed. - * - * A report that cannot be written does not stop the boot, and is not a skipped - * seat: the seat it describes was admitted and is running, only the panel's - * picture of it failed to save. It is returned separately, as a - * `reportErrors` entry for the boot's log, and the remaining organizations - * are admitted and written as usual. - */ -import type { FlowInstance } from "@flow-state-dev/core/types"; -import type { HiredRosterReload } from "@flow-state-dev/workforce"; - -import type { RosterBootReport } from "@/lib/roster-boot-report-schema"; -import { ROSTER_BOOT_REPORT_KEY } from "@/lib/workforce-shell"; - -/** The one store write this needs. Satisfied by the engine's `StoreRegistry`. */ -export interface RosterReportStores { - resourceState: { - set( - scopeType: "org", - scopeId: string, - resourceKey: string, - state: RosterBootReport, - expectedVersion: "any", - ): Promise; - }; -} - -export interface AdmitReloadedSeatsOptions { - reload: HiredRosterReload; - /** Admit one seat. Throwing refuses that seat and no other. */ - admit: (seat: FlowInstance) => void; - stores: RosterReportStores; -} - -export interface AdmittedSeats { - /** Ids of the seats that were admitted. */ - seats: string[]; - /** - * One entry per seat the registry refused, as ` — `. Every - * one of these is a seat that did not come back, so the boot's "N stored - * seat(s) could not be brought back" count is drawn from this list alone. - */ - problems: string[]; - /** - * One entry per organization whose report could not be written, as - * `organization "" — its boot report could not be written: `. - * Kept apart from `problems`: the seat itself was admitted, only the - * panel's picture of it failed to save, so this must never be counted as a - * skipped seat. - */ - reportErrors: string[]; -} - -/** - * Admit every reloaded seat, one at a time, and write each organization's - * report. - * - * @returns What was admitted and what was refused, across every organization, - * for the boot's own log. The reload's own problems are not repeated here. - */ -export async function admitReloadedSeats( - options: AdmitReloadedSeatsOptions, -): Promise { - const admitted: AdmittedSeats = { seats: [], problems: [], reportErrors: [] }; - - for (const org of options.reload.byOrg) { - const problems = [...org.problems]; - for (const seat of org.seats) { - try { - options.admit(seat); - admitted.seats.push(seat.id); - } catch (error) { - // One seat the registry refuses is one seat that cannot run, not a - // reason for the app to fail to start. - const refusal = `${seat.id} — ${error instanceof Error ? error.message : String(error)}`; - problems.push(refusal); - admitted.problems.push(refusal); - } - } - try { - await options.stores.resourceState.set( - "org", - org.orgId, - ROSTER_BOOT_REPORT_KEY, - { problems }, - "any", - ); - } catch (error) { - admitted.reportErrors.push( - `organization "${org.orgId}" — its boot report could not be written: ${ - error instanceof Error ? error.message : String(error) - }`, - ); - } - } - - return admitted; -} diff --git a/apps/kitchen-sink/lib/workforce-admin-auth.ts b/apps/kitchen-sink/lib/workforce-admin-auth.ts deleted file mode 100644 index b8e93b9310..0000000000 --- a/apps/kitchen-sink/lib/workforce-admin-auth.ts +++ /dev/null @@ -1,223 +0,0 @@ -/** - * The admin credential for `workforce-admin`, and the organization it names. - * - * **Why this flow carries a resolver of its own.** The framework's stock - * resolver, `defaultBodyUserIdPrincipalResolver`, reads `userId` *and `orgId`* - * straight out of the request body. That is fine for a demonstration flow whose - * whole state is the caller's own. It is not fine for `hire` and `fire`, which - * write durable state belonging to an organization: under the stock resolver - * "the organization comes from the resolved principal" is true and means - * nothing, because the caller supplied it. Any caller could hire into any - * organization. This is BP-031, and closing it is a resolver rather than a - * check inside the action — the action never sees an unverified org at all. - * - * **Fail-closed.** With no credential configured, `adminPrincipalResolver()` - * returns `undefined` and `fsdev.config.ts` does not register the admin flow at - * all. A default deployment therefore has no hire path to reach, rather than - * one guarded by a check somebody could get wrong. - * - * Configure it as `WORKFORCE_ADMIN_TOKENS="kitchen-sink:[,kitchen-sink:…]"`. - * - * **Every token must name {@link KITCHEN_SINK_ORG_ID}.** This app runs as one - * organization (`lib/kitchen-sink-principal.ts`): its assistant, its seats and - * its mailboxes all resolve to it, and so does every seat hired through them. A - * token bound anywhere else would administer a roster nothing in this app - * reads, and its `fire` would miss every seat the app hired. So an entry naming - * another organization is refused when the credentials are read, and the - * refusal is logged, the same fail-closed way a shared token is. - */ - -import { timingSafeEqual } from "node:crypto"; -import { extractBearerToken, PrincipalResolutionError } from "@flow-state-dev/engine"; -import type { FlowInstance, InstanceOwnerPin, ResolvePrincipalFn } from "@flow-state-dev/core/types"; - -import { KITCHEN_SINK_ORG_ID } from "@/lib/kitchen-sink-principal"; - -/** The env var holding `:` pairs. */ -export const ADMIN_TOKENS_ENV = "WORKFORCE_ADMIN_TOKENS"; - -/** - * The user every admin action runs as. - * - * A fixed machine identity rather than something off the request: the admin - * credential authenticates an operator, not an end user, and the runtime still - * needs a `userId` to key its request records by. Nothing user-scoped is read - * or written by either action. - */ -export const ADMIN_USER_ID = "workforce-admin"; - -/** - * Parse `WORKFORCE_ADMIN_TOKENS` into token → org. Malformed entries are - * skipped, and so is every entry naming an organization other than - * {@link KITCHEN_SINK_ORG_ID} (see the file header). - * - * **A token naming more than one organization drops ALL of its bindings**, - * later one and earlier one alike. `Map#set` would keep the last write and - * discard the first silently, which turns a copy-paste in an env var into a - * cross-tenant authorization decision made by config order: with - * `acme:secret,bravo:secret`, acme's own admin credential resolves the BRAVO - * organization and hires into it. Dropping the later binding alone would still - * leave acme's operator holding a credential bravo also knows. - * - * Failing closed here has a second effect worth knowing rather than - * discovering: {@link adminCredentialConfigured} reads this map, so a config - * whose ONLY token collides leaves the admin flow unregistered altogether — - * no hire path at all, rather than one pointing at the wrong tenant. - * - * The same organization listed twice under one token is not a collision: it is - * one binding written twice, and it resolves. - * - * **The collision check runs before the organization check**, over every - * well-formed entry. With `kitchen-sink:shared,bravo:shared`, somebody was - * handed `shared` believing it administers bravo; checking the organization - * first would drop bravo's entry and leave that credential administering - * kitchen-sink. Both go. - */ -function configuredTokens(): Map { - const raw = process.env[ADMIN_TOKENS_ENV]; - const byToken = new Map(); - if (typeof raw !== "string" || raw.trim().length === 0) return byToken; - - const orgsByToken = new Map>(); - for (const entry of raw.split(",")) { - const trimmed = entry.trim(); - if (trimmed.length === 0) continue; - // Split at the FIRST colon: an org id can never contain one (it is a - // single address segment), and a token might. - const at = trimmed.indexOf(":"); - if (at <= 0 || at === trimmed.length - 1) { - console.error( - `[workforce-admin] ignoring a malformed ${ADMIN_TOKENS_ENV} entry — expected ":"` - ); - continue; - } - const token = trimmed.slice(at + 1); - const orgs = orgsByToken.get(token); - if (orgs === undefined) orgsByToken.set(token, new Set([trimmed.slice(0, at)])); - else orgs.add(trimmed.slice(0, at)); - } - - for (const [token, orgs] of orgsByToken) { - if (orgs.size > 1) { - // The organizations, never the token — this line goes to a log. - console.error( - `[workforce-admin] one ${ADMIN_TOKENS_ENV} token is shared by ${orgs.size} organizations ` + - `(${[...orgs].join(", ")}) — dropping every binding for it, because which organization it ` + - `resolves would otherwise depend on the order they are written in. Give each organization ` + - `its own token.` - ); - continue; - } - const orgId = [...orgs][0]!; - if (orgId !== KITCHEN_SINK_ORG_ID) { - // The organization, never the token. - console.error( - `[workforce-admin] refusing a ${ADMIN_TOKENS_ENV} entry that names organization "${orgId}" — ` + - `this app runs as "${KITCHEN_SINK_ORG_ID}" only, so a token bound elsewhere would ` + - `administer seats nothing here reads. Bind it to "${KITCHEN_SINK_ORG_ID}".` - ); - continue; - } - byToken.set(token, orgId); - } - return byToken; -} - -/** Whether any admin credential is configured. Decides whether the flow exists at all. */ -export function adminCredentialConfigured(): boolean { - return configuredTokens().size > 0; -} - -/** Constant-time compare that does not leak length through an early return. */ -function matches(given: string, expected: string): boolean { - const a = Buffer.from(given, "utf8"); - const b = Buffer.from(expected, "utf8"); - return a.length === b.length && timingSafeEqual(a, b); -} - -/** - * The resolver for `workforce-admin`, or `undefined` when nothing is - * configured — in which case the flow is not registered. - * - * The returned principal's `orgId` is the one the credential is bound to. The - * request body is never consulted for it, which is the whole point: a hire - * whose body names another organization still writes to `kitchen-sink`. - * - * Read once, at module scope, rather than per request: a credential that could - * change between two requests of one process would make "which org am I" a - * question with two answers in one boot. - */ -export function adminPrincipalResolver(): ResolvePrincipalFn | undefined { - const byToken = configuredTokens(); - if (byToken.size === 0) return undefined; - - return (context) => { - const header = context.request?.headers?.get("authorization") ?? null; - const token = extractBearerToken(header); - if (token === null) { - throw new PrincipalResolutionError( - "workforce-admin requires an admin credential: send `Authorization: Bearer `.", - { status: 401 } - ); - } - // Every candidate is compared, and the loop is not broken early, so the - // time taken does not depend on which entry matched. - let orgId: string | undefined; - for (const [expected, org] of byToken) { - if (matches(token, expected)) orgId = org; - } - if (orgId === undefined) { - throw new PrincipalResolutionError("Invalid workforce-admin credential.", { - status: 401, - }); - } - return { userId: ADMIN_USER_ID, orgId }; - }; -} - -/** - * A seat the admin credential hired, resolving its callers with that - * credential. - * - * `workforce-admin` pins its seat to the organization the credential resolved - * and to {@link ADMIN_USER_ID}, and every request to the seat is checked - * against that pin. So the seat has to resolve its callers the same way. With - * no resolver of its own it falls to the framework default, which names the - * default organization, and the pin refuses even the operator who just hired it. - * - * **Only a seat pinned to {@link ADMIN_USER_ID}.** A seat hired from inside the - * app, by a seat's `hire` tool, is pinned to the organization alone: any member - * of it may open the seat, the way they open any other. Giving that seat the - * admin resolver would demand the operator's token from every visitor. So the - * decision is read from the pin, which the hire set on the server, and never - * from anything on a request (BP-031). - * - * **On the seat instance, and nowhere wider.** A host-level resolver would put - * every open flow in this app (`chat-agent`, the mailboxes, the file-declared - * seats) behind the admin token. A resolver on the kind would do the same to - * the file-declared seats of that kind, which run unpinned for `devuser`. The - * instance is the one place that covers exactly the pinned seats. - * - * The pin is untouched: this only decides who the caller IS, from the verified - * token. Whether that caller may reach the seat is still the pin's call, so - * another organization's credential is refused as before. - * - * Returned unchanged when the pin names no user or another user, when no - * credential is configured — nothing can resolve the pinned organization, so - * the pin refuses everyone — and when the seat's kind names a resolver of its - * own, which is that kind's decision to make. - */ -export function withAdminAuthentication( - seat: FlowInstance, - pin: InstanceOwnerPin, - resolvePrincipal: ResolvePrincipalFn | undefined -): FlowInstance { - if ( - pin.userId !== ADMIN_USER_ID || - resolvePrincipal === undefined || - seat.authentication?.resolvePrincipal !== undefined - ) { - return seat; - } - return { ...seat, authentication: { ...seat.authentication, resolvePrincipal } }; -} diff --git a/apps/kitchen-sink/lib/workforce-registrar.ts b/apps/kitchen-sink/lib/workforce-registrar.ts deleted file mode 100644 index 483f4d4c0c..0000000000 --- a/apps/kitchen-sink/lib/workforce-registrar.ts +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Standalone workforce-registrar proxy. - * - * Sits in its own module for the same reason `lib/schedule-index.ts` does, and - * it is the same shape: it breaks a cyclic import. `fsdev.config.ts` builds the - * FlowState and installs the real implementation here; - * `flows/workforce-admin/flow.ts` imports the proxy so its `hire` and `fire` - * actions can admit and release an address. The admin flow cannot import the - * config, because the config is what registers the admin flow. - * - * **The default throws rather than no-opping**, which is the one place this - * differs from the schedule index. A no-op schedule index means no row is - * mirrored, which the collection documents. A no-op registrar would mean a hire - * that wrote its durable row, registered nothing, and reported success — a seat - * that exists in storage, answers nowhere, and appears out of nothing at the - * next boot. Failing loudly turns a wiring mistake into a refused hire with a - * named cause, and the compensating delete then removes the row it wrote. - */ - -import type { FlowInstance, InstanceOwnerPin } from "@flow-state-dev/core/types"; -import { registerHiredSeat } from "@flow-state-dev/workforce"; - -import { adminPrincipalResolver, withAdminAuthentication } from "./workforce-admin-auth"; - -/** - * The resolver a seat `workforce-admin` hired answers with — the admin flow's own, - * read from the same env at the same point in the boot, so the seat resolves - * a caller exactly as the hire that pinned it did. `undefined` when no admin - * credential is configured. - */ -const hiredSeatResolver = adminPrincipalResolver(); - -/** - * **Provenance lives here, not in the installed door.** `fire` may release only - * an address this app registered *from a roster row* (BR-28). Nothing on a - * `FlowInstance` says where it came from — a seat minted from a row and one - * declared in `workforce/teams/` are the same shape and can carry the same - * kind — so the only place that answer exists is the call site that did the - * registering, and the only way to keep it is to record it there. - * - * It is module state beside `impl` rather than part of the door, because it is - * a fact about THIS app's roster path and not about whichever admission door - * is installed. Installing a door resets it: a new door is a new app, and a - * mark carried over from the last one would claim provenance for a - * registration that never happened. - */ -const fromRoster = new Set(); - -/** What the app installs: the FlowState's admission door, plus one read. */ -export interface WorkforceRegistrar { - /** Admit one instance. Throws exactly as `FlowState.register` does. */ - register(flow: FlowInstance, options?: { pin?: InstanceOwnerPin }): void; - /** Release one address. `false` when nothing held it. */ - unregister(id: string): boolean; - /** - * The kind of whatever currently holds an address, or `undefined`. - * - * Needed by `fire`, which must release an address **only** when the live - * instance is the one this org's row minted. There is no public read of the - * registry on `FlowState` today — `meta.flowKeys` answers *which ids* but not - * *what kind* — so the config supplies this from `getRuntime().registry`. - * That gap is recorded as a follow-up rather than worked around quietly. - */ - kindAt(id: string): string | undefined; -} - -/** - * The proxy's own surface: the door, plus the two provenance operations that - * belong to this app rather than to the door. - */ -export interface WorkforceRosterRegistrar extends WorkforceRegistrar { - /** - * Admit one instance minted from a roster row, and record that this app did - * so. The two call sites are `hire` and the boot reload in `fsdev.config.ts` - * — a seat that reaches the registry any other way is not this app's to - * release. - * - * Marked only after the door accepts. A registration that threw (a duplicate - * address, say, which is exactly what a file-declared seat holding the same - * address produces at boot) left nothing registered, so claiming provenance - * for it would hand `fire` someone else's instance. - */ - registerFromRoster(flow: FlowInstance, options?: { pin?: InstanceOwnerPin }): void; - /** - * Whether this app registered the address from a roster row — what BR-28 - * actually asks, rather than the kind-equality proxy that answers `true` for - * any file-declared seat that happens to share the row's kind. - */ - isFromRoster(id: string): boolean; -} - -function notInstalled(): never { - throw new Error( - "The workforce registrar has not been installed. `fsdev.config.ts` installs it " + - "immediately after `createFlowState`, before anything can serve a request — so " + - "reaching this means the admin flow was registered by some other assembly. " + - "A hire cannot be honoured without it: the row would be written and no seat would answer." - ); -} - -let impl: WorkforceRegistrar = { - register: notInstalled, - unregister: notInstalled, - kindAt: notInstalled, -}; - -/** Install the backing implementation. Called once by `fsdev.config.ts`. */ -export function setWorkforceRegistrarImpl(next: WorkforceRegistrar): void { - impl = next; - fromRoster.clear(); -} - -/** - * Stable proxy whose methods delegate to the installed implementation. - * Safe to import from anywhere at module-init time. - */ -export const workforceRegistrar: WorkforceRosterRegistrar = { - register: (flow, options) => impl.register(flow, options), - unregister: (id: string) => { - // The mark goes whether or not anything was holding the address: once an - // address is released, this app is no longer the reason something is - // there, and a mark that outlived its registration would let `fire` - // release whatever took the address next. - fromRoster.delete(id); - return impl.unregister(id); - }, - kindAt: (id: string) => impl.kindAt(id), - registerFromRoster: (flow, options) => { - // A roster hire with no pin — neither the argument nor the pin the row - // stamped onto the instance — refuses here, before the address is marked. - // App and kind flows do not come through this door, so they stay shared. - // - // A seat `workforce-admin` hired is pinned to the admin user, so it - // resolves its callers with the admin credential: without it the seat - // hears every request as the default organization and its own pin refuses - // the operator who hired it. A seat hired in-app is pinned to the - // organization alone and keeps the resolver every other flow uses, so a - // visitor opens it with no token. The pin decides, not the request. - registerHiredSeat( - (seat, pin) => impl.register(withAdminAuthentication(seat, pin, hiredSeatResolver), { pin }), - flow, - options?.pin ?? flow.ownerPin, - ); - fromRoster.add(flow.id); - }, - isFromRoster: (id: string) => fromRoster.has(id), -}; diff --git a/apps/kitchen-sink/lib/workforce-shell.ts b/apps/kitchen-sink/lib/workforce-shell.ts index 0243221d2d..e0d8683547 100644 --- a/apps/kitchen-sink/lib/workforce-shell.ts +++ b/apps/kitchen-sink/lib/workforce-shell.ts @@ -1,25 +1,23 @@ /** * The names the shell and its flow agree on — which kinds the rail groups, - * what each declared seat handles, and which collections the right panel reads. + * what a worker's composer sends, and which boards the right panel reads. * * A leaf module on purpose (BP-019): the page is a client bundle and the flow * is server code, and both import these. Nothing here imports anything, so the * page gets the names without pulling the flow into the browser. * - * The hired roster's key is not here. It is the workforce package's own - * `HIRED_ROSTER_RESOURCE`, because the operator's hire runs the package's - * sequence, which writes the roster under that key; the flow imports it from - * the package root, and the panels from `@flow-state-dev/workforce/browser`, - * because the root is server code (`test/client-imports.test.ts`). + * The workers themselves are not here: the right panel reads the person's + * roster through Workforce's client (`@flow-state-dev/workforce/browser`), + * which answers with each worker's flow and description. * - * The kind names, seat descriptions and board ids are written down rather than - * derived, because the only place that knows them at run time is the - * server-side tree under `workforce/`, which a browser cannot read. - * `test/workforce-shell.test.ts` holds them to that tree and fails when a - * kind, a seat's description or a board changes there and not here. + * The kind names and board ids are written down rather than derived, because + * the only place that knows them at run time is the server-side tree under + * `workforce/`, which a browser cannot read. `test/workforce-shell.test.ts` + * holds them to that tree and fails when a kind or a board changes there and + * not here. */ -/** The flow the stream talks to, and the one whose session the roster reads through. */ +/** The flow the stream talks to. */ export const SHELL_FLOW_KIND = "chat-agent"; /** @@ -42,23 +40,12 @@ export function isMailboxKind(kind: string): boolean { export const SHELL_MAILBOXES = [{ id: "support.help", kind: "mailbox" }] as const; /** - * The seat kinds: the built-in `agent`, plus every kind under - * `workforce/flows/workers/`, of which this app has none. + * The worker flows: the built-in `agent`, plus every flow under + * `workforce/flows/workers/`, of which this app has none. Each runs as one + * copy, holding every worker's conversations on it. */ export const SEAT_KINDS = ["agent"] as const; -/** - * What each declared seat handles: its `WORKER.md`'s `description:`, by the - * seat's address. The route reads the same line to pick who answers a post, so - * the rail shows a person what the route reads. - */ -export const SEAT_DESCRIPTIONS = { - "support.devices": "Printers, laptops, phones, wifi and anything else with a power button.", - "support.accounts": "Sign-in, passwords, billing, refunds and subscriptions.", - "support.fsd": "Questions about building apps with the flow-state-dev framework.", - "support.general": "Anything that fits none of the other specialists.", -} as const; - /** * What a seat's composer sends: the one action its kind answers a person with, * and that action's one input field. A kind with nothing to answer with says @@ -104,20 +91,6 @@ export function defaultConversation !(session.tags?.includes(LEGACY_SEAT_HIRES_TAG) ?? false)); } -/** The key the shell's flow declares the boot's skipped-seat report under. */ -export const ROSTER_BOOT_REPORT_REF = "rosterBootReport"; - -/** Storage prefix of the boot report. One row per organization lives under it. */ -export const ROSTER_BOOT_REPORT_PREFIX = "kitchen-sink/roster-boot-report/"; - -/** - * The one row a boot writes into each organization it reloaded. A plain - * string, not the row's schema — the schema needs zod, which would give this - * leaf module an import, so it lives in `lib/roster-boot-report-schema.ts` - * instead, where both the boot writer and the flow can reach it. - */ -export const ROSTER_BOOT_REPORT_KEY = `${ROSTER_BOOT_REPORT_PREFIX}latest`; - /** * The boards the right panel draws, one per `boards:` entry in the tree's * `MAILBOX.md` files. @@ -129,28 +102,3 @@ export const ROSTER_BOOT_REPORT_KEY = `${ROSTER_BOOT_REPORT_PREFIX}latest`; export const SHELL_BOARDS = [ { mailboxId: "support.help", board: "escalations", ref: "support.help.escalations" }, ] as const; - -/** - * The skipped-seat lines in a page of boot-report rows. - * - * One row per organization is written, and a session reads only its own - * organization's, so in practice this is one row's list. A row whose shape is - * not a list of strings contributes nothing rather than failing the panel. - * - * This reads `clientData` with a cast rather than the row's zod schema - * (`lib/roster-boot-report-schema.ts`): that schema needs zod, and this - * module's contract (above) is that nothing here imports anything, so the - * page keeps getting these names without pulling anything else into the - * browser. The shape checked below — `problems` an array, non-string entries - * dropped — mirrors what that schema would enforce. - */ -export function problemsFromBootReport( - items: readonly { readonly clientData?: unknown }[], -): string[] { - return items.flatMap((item) => { - const report = item.clientData as { problems?: unknown } | undefined; - return Array.isArray(report?.problems) - ? report.problems.filter((line): line is string => typeof line === "string") - : []; - }); -} diff --git a/apps/kitchen-sink/test/escalate.test.ts b/apps/kitchen-sink/test/escalate.test.ts index d11df02391..7972ff1f0d 100644 --- a/apps/kitchen-sink/test/escalate.test.ts +++ b/apps/kitchen-sink/test/escalate.test.ts @@ -25,8 +25,8 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import type { FlowState } from "@flow-state-dev/engine"; import { runAction } from "@flow-state-dev/engine"; -import { createResourceClient, createSessionClient } from "@flow-state-dev/client"; import type { FlowInstance } from "@flow-state-dev/core/types"; +import { createResourceClient, createSessionClient } from "@flow-state-dev/client"; // Each case boots the whole app afresh, and the first import is cold. vi.setConfig({ testTimeout: 30_000 }); @@ -83,16 +83,17 @@ function textOf(item: Item): string { return item.text ?? JSON.stringify(item); } -/** Send a message the way the seat composer does, and wait for the run to finish. */ -async function ask(app: App, seat: string, message: string) { - const session = await app.sessions.createSession({ flowKind: seat, userId: "devuser" }); +/** Send a message to a worker the way the panel's composer does, and wait for the run to finish. */ +async function ask(app: App, worker: string, message: string) { + // A conversation with a worker is a session on its flow's one copy, created naming the worker. + const session = await app.sessions.createSession({ flowKind: "agent", userId: "devuser", state: { workerId: worker } }); const res = await app.router.POST( - new Request(`http://localhost/api/flows/${seat}/actions/run`, { + new Request(`http://localhost/api/flows/agent/actions/run`, { method: "POST", headers: { "content-type": "application/json", accept: "text/event-stream" }, body: JSON.stringify({ userId: "devuser", sessionId: session.id, input: { message } }), }), - { params: { path: [seat, "actions", "run"] } }, + { params: { path: ["agent", "actions", "run"] } }, ); const stream = await res.text(); const snapshot = await app.sessions.getSessionState(session.id, { includeItems: true }); @@ -164,15 +165,25 @@ describe("V3 · a specialist files what needs a person", () => { ]); }); - it("files nothing for a seat that is not a member of support.help, and says so", async () => { + it("files nothing for a worker that is not a member of support.help, and says so", async () => { const app = await bootApp(); - const { kitchenSinkKinds } = await import("@/workforce/hire"); - const { hireWorkforce } = await import("@flow-state-dev/workforce"); - const [outsider] = hireWorkforce( - [{ id: "support.bo", declared: { tools: ["escalate"] }, body: "Answer questions." }], - { workerFlows: kitchenSinkKinds }, + // The person hires a worker of their own, holding the tool, through the roster flow. + const roster = await app.sessions.createSession({ flowKind: "workforce-roster", userId: "devuser" }); + const hired = await app.router.POST( + new Request(`http://localhost/api/flows/workforce-roster/actions/hire`, { + method: "POST", + headers: { "content-type": "application/json", accept: "text/event-stream" }, + body: JSON.stringify({ + userId: "devuser", + sessionId: roster.id, + input: { id: "support.bo", instructions: "Answer questions.", settings: { tools: ["escalate"] } }, + }), + }), + { params: { path: ["workforce-roster", "actions", "hire"] } }, ); - app.flowstate.register(outsider as FlowInstance); + expect(hired.status).toBe(200); + const stream = await hired.text(); + expect(stream, "the hire's own answer").not.toMatch(/"status":"failed"|refused/); const mark = token(); const ran = await ask(app, "support.bo", `[scenario:needs-a-person] ${mark} escalate me`); @@ -199,8 +210,12 @@ describe("V3 · a specialist files what needs a person", () => { it("says filing is unavailable past an external dispatcher, and files nothing (BR-11)", async () => { const app = await bootApp(); const runtime = await app.flowstate.getRuntime(); - const seat = runtime.registry.get("support.devices") as FlowInstance; - const session = await app.sessions.createSession({ flowKind: "support.devices", userId: "devuser" }); + const seat = runtime.registry.get("agent") as FlowInstance; + const session = await app.sessions.createSession({ + flowKind: "agent", + userId: "devuser", + state: { workerId: "support.devices" }, + }); const mark = token(); const ran = await runAction({ diff --git a/apps/kitchen-sink/test/goal-control.test.ts b/apps/kitchen-sink/test/goal-control.test.ts index eeebc9249d..70495e799c 100644 --- a/apps/kitchen-sink/test/goal-control.test.ts +++ b/apps/kitchen-sink/test/goal-control.test.ts @@ -16,7 +16,7 @@ import { join, relative, sep } from "node:path"; import { fileURLToPath } from "node:url"; import { afterEach, describe, expect, it, vi } from "vitest"; import { handler } from "@flow-state-dev/core"; -import { mailboxPostCapability, type MailboxManifest } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, mailboxPostCapability, type MailboxManifest } from "@flow-state-dev/workforce"; import { z } from "zod"; import { goalControl, pageGoalControl } from "@/lib/goal-control"; @@ -87,7 +87,7 @@ describe("V4 · every control is read through the gate, and only in this app (BR const routed = [{ id: "support.help", declared: { routing: { fallback: "support.general" } } }] as unknown as MailboxManifest[]; const controls: Array<[name: string, apply: () => Promise<{ swapped: boolean }>]> = [ - ["no-landing", async () => ({ swapped: (await import("@/lib/mailbox-landing-control")).mailboxLandingControl(catalog, mailboxPostCapability) !== undefined })], + ["no-landing", async () => ({ swapped: (await import("@/lib/mailbox-landing-control")).mailboxLandingControl(catalog, mailboxPostCapability, createWorkerInstallation()) !== undefined })], ["no-filing", async () => ({ swapped: (await import("@/lib/escalate-control")).escalateControl(catalog) !== undefined })], ["no-route", async () => ({ swapped: (await import("@/lib/mailbox-route-control")).withMailboxRouteControl(routed) !== routed })], ["name-only-notify", async () => ({ swapped: (await import("@/lib/mailbox-wake-control")).withMailboxWakeControl(wake) !== wake })], diff --git a/apps/kitchen-sink/test/hired-seat-auth.test.ts b/apps/kitchen-sink/test/hired-seat-auth.test.ts deleted file mode 100644 index d7403d697b..0000000000 --- a/apps/kitchen-sink/test/hired-seat-auth.test.ts +++ /dev/null @@ -1,299 +0,0 @@ -/** - * A seat hired over `workforce-admin` answers the credential that hired it — - * over HTTP, through the router this app serves, the way a caller reaches it. - * - * The hire pins the seat to the organization (and the user) the admin - * credential resolved. Every later request to the seat is checked against that - * pin, so the seat is only reachable if the request resolves the same principal. - * With no resolver of its own the seat fell to the framework default, which - * names the default organization — and the pin refused even the operator who - * had just hired it. - * - * Red state, produced before the green was trusted: drop the - * `withAdminAuthentication` call from `registerFromRoster` in - * `lib/workforce-registrar.ts`. The three "hiring credential" cases go red - * (`404 Unknown flow` on the open, the run, and the run after a restart); the - * refusals stay green, because they were refused before the fix too. - * - * The catalog and listing legs lean on the engine resolving each instance's - * caller with that instance's own resolver. Revert `flowsForCaller` in the - * engine's `routes/http-handlers.ts` to the host resolver alone and only "is - * listed in the catalog" goes red. Drop the `ownResolverVerdict` calls from - * the engine's session listing and only the two "session listing" cases for - * the hiring credential go red. - * - * Every admin token names `kitchen-sink`, the one organization this app runs - * as (`lib/workforce-admin-auth.ts`). A token naming any other organization is - * refused when the credentials are read, so the "another organization" case - * below is that token being refused at the seat, not a pin miss. - */ -import { afterAll, describe, expect, it, vi } from "vitest"; -import type { FlowInstance } from "@flow-state-dev/core/types"; -import { createFlowState, inMemoryStores } from "@flow-state-dev/engine"; -import { createMockModelResolver } from "@flow-state-dev/testing"; -import { reloadHiredSeats, seatAddress } from "@flow-state-dev/workforce"; - -// Before any import below evaluates: the admin flow and the registrar each read -// the credential once, at module scope, exactly as they do at boot. -const previousTokens = vi.hoisted(() => { - const previous = process.env.WORKFORCE_ADMIN_TOKENS; - process.env.WORKFORCE_ADMIN_TOKENS = "kitchen-sink:tok-ks,elsewhere:tok-elsewhere"; - return previous; -}); - -import { ADMIN_USER_ID } from "../lib/workforce-admin-auth"; -import { setWorkforceRegistrarImpl, workforceRegistrar } from "../lib/workforce-registrar"; -import workforceAdminFlow from "../flows/workforce-admin/flow"; -import { kitchenSinkKinds } from "../workforce/hire"; -import { KITCHEN_SINK_ORG_ID, resolveKitchenSinkPrincipal } from "../lib/kitchen-sink-principal"; - -/** The configured kitchen-sink admin token. */ -const TOKEN = "tok-ks"; -/** A token whose entry named another organization, refused when the credentials were read. */ -const OTHER_ORG_TOKEN = "tok-elsewhere"; -const SEAT = seatAddress(KITCHEN_SINK_ORG_ID, "support.bo", ADMIN_USER_ID); - -type Router = { - GET: (request: Request, ctx: { params: { path: string[] } }) => Promise; - POST: (request: Request, ctx: { params: { path: string[] } }) => Promise; -}; - -/** - * The app's runtime as `fsdev.config.ts` assembles the parts this needs: the - * admin flow registered, and the registrar installed over the FlowState's own - * door, so a hire goes through the same admission a real one does. - */ -async function boot(stores = inMemoryStores(), options: { hostResolver?: boolean } = {}) { - const state = createFlowState({ - flows: { workforceAdmin: workforceAdminFlow as FlowInstance }, - stores: { default: { primary: stores } }, - modelResolver: createMockModelResolver({ policy: "allow" }), - // The host-level fallback `fsdev.config.ts` installs. Off by default: the - // hire, open and run legs do not reach it, since the admin flow and the - // seat each bring their own. - ...(options.hostResolver === true ? { resolvePrincipal: resolveKitchenSinkPrincipal } : {}), - }); - const router = (await state.getRouter()) as Router; - const runtime = await state.getRuntime(); - setWorkforceRegistrarImpl({ - register: (flow, options) => state.register(flow, options), - unregister: (id) => state.unregister(id), - kindAt: (id) => runtime.registry.get(id)?.kind, - }); - - // Every body names the admin user, as a client does (the session client - // always sends a `userId`). That makes the refusals below the pin's and not - // a missing-field 400 — and shows the body naming the right user gets a - // caller nowhere: only the verified principal counts. - const call = async (path: string[], token: string | undefined, body: unknown) => { - const headers: Record = { "content-type": "application/json" }; - if (token !== undefined) headers.authorization = `Bearer ${token}`; - const response = await router.POST( - new Request(`http://kitchen-sink.local/api/flows/${path.join("/")}`, { - method: "POST", - headers, - body: JSON.stringify(body), - }), - { params: { path } } - ); - const text = await response.text(); - return { status: response.status, json: text.length > 0 ? JSON.parse(text) : undefined }; - }; - - /** `GET /api/flows` — the catalog — as `token`: the status and the listed ids. */ - const catalog = async (token: string | undefined) => { - const headers: Record = {}; - if (token !== undefined) headers.authorization = `Bearer ${token}`; - const response = await router.GET( - new Request("http://kitchen-sink.local/api/flows", { headers }), - { params: { path: [] } } - ); - const json = (await response.json()) as { flows?: { id: string }[] }; - return { status: response.status, ids: (json.flows ?? []).map((flow) => flow.id) }; - }; - - /** `GET /api/flows/sessions` — the session listing — as `token`: the status and the listed ids. */ - const sessions = async (token: string | undefined) => { - const headers: Record = {}; - if (token !== undefined) headers.authorization = `Bearer ${token}`; - const response = await router.GET( - new Request("http://kitchen-sink.local/api/flows/sessions", { headers }), - { params: { path: ["sessions"] } } - ); - const json = (await response.json()) as { sessions?: { id: string }[] }; - return { status: response.status, ids: (json.sessions ?? []).map((session) => session.id) }; - }; - - /** Post an action and wait for its request to settle. */ - const act = async (flowId: string, action: string, input: unknown, token: string | undefined) => { - const posted = await call([flowId, "actions", action], token, { userId: ADMIN_USER_ID, input }); - if (posted.status >= 400) return { http: posted.status, error: posted.json?.error as string }; - const requestId = posted.json.request?.id as string; - for (let i = 0; i < 200; i++) { - const record = await runtime.stores.request.get(requestId); - if (record !== undefined && !["pending", "queued", "in_progress", "running"].includes(record.status)) { - return { http: posted.status, outcome: record.status }; - } - await new Promise((resolve) => setTimeout(resolve, 5)); - } - return { http: posted.status, outcome: "never settled" }; - }; - - /** - * The boot reload, as `fsdev.config.ts` runs it: every stored row hired back - * and admitted through the registrar's roster door. - */ - const reload = async () => { - const { seats, problems } = await reloadHiredSeats({ - stores: runtime.stores, - orgIds: [KITCHEN_SINK_ORG_ID], - workerFlows: kitchenSinkKinds, - }); - expect(problems).toEqual([]); - for (const seat of seats) workforceRegistrar.registerFromRoster(seat, { pin: seat.ownerPin }); - return seats.map((seat) => seat.id); - }; - - return { call, act, catalog, sessions, reload }; -} - -/** Boot, and hire `support.bo` into kitchen-sink with its admin credential. */ -async function bootWithHire(stores = inMemoryStores(), options: { hostResolver?: boolean } = {}) { - const app = await boot(stores, options); - const hired = await app.act( - "workforce-admin", - "hire", - { seatId: "support.bo", flow: "agent", instructions: "You take refund questions." }, - TOKEN - ); - // If the hire itself did not land, everything below is about nothing. - expect(hired).toEqual({ http: 202, outcome: "completed" }); - return app; -} - -afterAll(() => { - if (previousTokens === undefined) delete process.env.WORKFORCE_ADMIN_TOKENS; - else process.env.WORKFORCE_ADMIN_TOKENS = previousTokens; -}); - -describe("a seat hired over workforce-admin, reached with the hiring credential", () => { - it("opens a session for the operator who hired it", async () => { - const app = await bootWithHire(); - - const opened = await app.call([SEAT, "sessions"], TOKEN, { userId: ADMIN_USER_ID }); - - expect(opened.status).toBe(201); - }); - - it("runs an action for the operator who hired it", async () => { - const app = await bootWithHire(); - - const ran = await app.act(SEAT, "run", { message: "where is my order?" }, TOKEN); - - expect(ran).toEqual({ http: 202, outcome: "completed" }); - }); - - it("is listed in the catalog for the operator who hired it", async () => { - const app = await bootWithHire(); - - const listed = await app.catalog(TOKEN); - - expect(listed.status).toBe(200); - expect(listed.ids).toContain(SEAT); - }); - - it("lists the session it opened in the session listing for the operator who hired it", async () => { - const app = await bootWithHire(); - const opened = await app.call([SEAT, "sessions"], TOKEN, { userId: ADMIN_USER_ID, sessionId: "s-op" }); - expect(opened.status).toBe(201); - - const listed = await app.sessions(TOKEN); - - expect(listed.status).toBe(200); - expect(listed.ids).toContain("s-op"); - }); - - it("lists that session under the host resolver this app installs, too", async () => { - const app = await bootWithHire(inMemoryStores(), { hostResolver: true }); - const opened = await app.call([SEAT, "sessions"], TOKEN, { userId: ADMIN_USER_ID, sessionId: "s-op" }); - expect(opened.status).toBe(201); - - const listed = await app.sessions(TOKEN); - - // The host resolver names every caller the app's one visitor, not the - // operator the seat resolves. The seat's own resolver decides its rows. - expect(listed.status).toBe(200); - expect(listed.ids).toContain("s-op"); - }); - - it("still answers the operator after a restart brings it back from its row", async () => { - const stores = inMemoryStores(); - await bootWithHire(stores); - - const restarted = await boot(stores); - expect(await restarted.reload()).toEqual([SEAT]); - const ran = await restarted.act(SEAT, "run", { message: "still there?" }, TOKEN); - - expect(ran).toEqual({ http: 202, outcome: "completed" }); - }); -}); - -describe("a seat hired over workforce-admin stays closed to everyone else", () => { - it("refuses a token configured for another organization, which was refused at boot", async () => { - vi.spyOn(console, "error").mockImplementation(() => {}); - const app = await bootWithHire(); - - const opened = await app.call([SEAT, "sessions"], OTHER_ORG_TOKEN, { userId: ADMIN_USER_ID }); - const ran = await app.act(SEAT, "run", { message: "hello" }, OTHER_ORG_TOKEN); - - expect(opened.status).toBe(401); - expect(opened.json?.error).toMatch(/Invalid workforce-admin credential/); - expect(ran).toEqual({ http: 401, error: "Invalid workforce-admin credential." }); - }); - - it("is left out of the catalog for another organization and for a caller with no credential", async () => { - const app = await bootWithHire(); - - const elsewhere = await app.catalog(OTHER_ORG_TOKEN); - const anonymous = await app.catalog(undefined); - - expect(elsewhere.status).toBe(200); - expect(elsewhere.ids).not.toContain(SEAT); - // The catalog route stays exempt: no credential is a shorter list, not a 401. - expect(anonymous.status).toBe(200); - expect(anonymous.ids).not.toContain(SEAT); - }); - - it("keeps the seat's sessions out of the session listing for anyone else", async () => { - vi.spyOn(console, "error").mockImplementation(() => {}); - for (const hostResolver of [false, true]) { - const app = await bootWithHire(inMemoryStores(), { hostResolver }); - const opened = await app.call([SEAT, "sessions"], TOKEN, { userId: ADMIN_USER_ID, sessionId: "s-op" }); - expect(opened.status).toBe(201); - - const anonymous = await app.sessions(undefined); - const elsewhere = await app.sessions(OTHER_ORG_TOKEN); - - // No credential is a shorter list, not a 401. - expect(anonymous.status).toBe(200); - expect(anonymous.ids).not.toContain("s-op"); - expect(elsewhere.status).toBe(200); - expect(elsewhere.ids).not.toContain("s-op"); - } - }); - - it("refuses a caller with no credential, even one naming the org and user in the body", async () => { - const app = await bootWithHire(); - const claimed = { userId: ADMIN_USER_ID, orgId: KITCHEN_SINK_ORG_ID }; - - const opened = await app.call([SEAT, "sessions"], undefined, claimed); - const ran = await app.call([SEAT, "actions", "run"], undefined, { - ...claimed, - input: { message: "hello" }, - }); - - // The seat's own resolver refuses a missing credential before the pin runs. - expect(opened.status).toBe(401); - expect(ran.status).toBe(401); - }); -}); diff --git a/apps/kitchen-sink/test/hired-seat-visitor-auth.test.ts b/apps/kitchen-sink/test/hired-seat-visitor-auth.test.ts deleted file mode 100644 index 9376e7bc27..0000000000 --- a/apps/kitchen-sink/test/hired-seat-visitor-auth.test.ts +++ /dev/null @@ -1,128 +0,0 @@ -/** - * A seat hired over `workforce-admin` does not open for a visitor, in the app - * as it ships, with its host resolver beside the admin credential. - * - * The admin action pins its seat to the organization AND the admin user, so - * that seat has to resolve its callers with the admin credential - * (`hired-seat-auth.test.ts`). A visitor, who sends none, must be refused - * rather than heard as the app's own user. - * - * Every case boots the app's real `fsdev.config.ts`, the way - * `named-org.test.ts` does: the host resolver, the admin credential, the - * registrar and the admin flow are the ones the app ships, and every request - * goes through the router a browser reaches. - * - * Red state, produced before the green was trusted: make - * `withAdminAuthentication` never attach the resolver. Both cases go red. - * - * The in-app hire this file also covered, a seat's own `hire` tool pinning to - * the organization only, left with the tool (FIX-1611): no seat in this app - * carries it. - */ -import { afterEach, describe, expect, it, vi } from "vitest"; -import type { FlowState } from "@flow-state-dev/engine"; -import { seatAddress } from "@flow-state-dev/workforce"; - -import { ADMIN_USER_ID } from "@/lib/workforce-admin-auth"; -import { KITCHEN_SINK_ORG_ID } from "@/lib/kitchen-sink-principal"; - -const TOKEN = "tok-ks"; -const ADMIN_SEAT = seatAddress(KITCHEN_SINK_ORG_ID, "support.bo", ADMIN_USER_ID); - -// Each case imports the whole app afresh. The first import is cold, and beside -// `named-org.test.ts` doing the same in another worker it outruns vitest's 5s -// default. -vi.setConfig({ testTimeout: 30_000 }); - -type Router = Awaited>; - -afterEach(async () => { - const hmr = globalThis as { __fsdFlowstate?: FlowState }; - await hmr.__fsdFlowstate?.dispose(); - delete hmr.__fsdFlowstate; - vi.unstubAllEnvs(); -}); - -/** Boot the app from its real config, with an admin credential configured. */ -async function bootApp() { - vi.resetModules(); - vi.stubEnv("KITCHEN_SINK_TEST_MODE", "1"); - vi.stubEnv("STORE_TYPE", "memory"); - vi.stubEnv("WORKFORCE_ADMIN_TOKENS", `${KITCHEN_SINK_ORG_ID}:${TOKEN}`); - delete process.env.FSDEV_DEFAULT_MODEL; - - const flowstate = (await import("@/fsdev.config")).default as FlowState; - const runtime = await flowstate.getRuntime(); - const router = (await flowstate.getRouter()) as Router; - - /** A POST as the browser makes it: a body `userId`, which the resolver overrides. */ - const call = async (path: string[], token: string | undefined, body: Record) => { - const headers: Record = { "content-type": "application/json" }; - if (token !== undefined) headers.authorization = `Bearer ${token}`; - const response = await router.POST( - new Request(`http://localhost/api/flows/${path.join("/")}`, { - method: "POST", - headers, - body: JSON.stringify({ userId: "someone-else", ...body }), - }), - { params: { path } } - ); - const text = await response.text(); - return { status: response.status, json: text.length > 0 ? JSON.parse(text) : undefined }; - }; - - /** Post an action and wait for its request to settle. */ - const act = async ( - flowId: string, - action: string, - input: unknown, - token: string | undefined, - extra: Record = {} - ) => { - const posted = await call([flowId, "actions", action], token, { input, ...extra }); - if (posted.status >= 400) return { http: posted.status, error: posted.json?.error as string }; - const requestId = posted.json.request?.id as string; - for (let i = 0; i < 400; i++) { - const record = await runtime.stores.request.get(requestId); - if (record !== undefined && !["pending", "queued", "in_progress", "running"].includes(record.status)) { - return { http: posted.status, outcome: record.status }; - } - await new Promise((resolve) => setTimeout(resolve, 5)); - } - return { http: posted.status, outcome: "never settled" }; - }; - - /** The operator hires `support.bo` over `workforce-admin`: pinned to the org and the admin user. */ - const hireAsAdmin = async () => { - const hired = await act( - "workforce-admin", - "hire", - { seatId: "support.bo", flow: "agent", instructions: "You take refund questions." }, - TOKEN - ); - expect(hired).toEqual({ http: 202, outcome: "completed" }); - expect(runtime.registry.get(ADMIN_SEAT)?.kind).toBe("agent"); - }; - - return { call, act, hireAsAdmin }; -} - -describe("a seat hired over workforce-admin, in the same app", () => { - it("still refuses a caller with no credential, rather than hearing them as the visitor", async () => { - const app = await bootApp(); - await app.hireAsAdmin(); - - const opened = await app.call([ADMIN_SEAT, "sessions"], undefined, {}); - - expect(opened.status).toBe(401); - }); - - it("still answers the organization's admin credential", async () => { - const app = await bootApp(); - await app.hireAsAdmin(); - - const opened = await app.call([ADMIN_SEAT, "sessions"], TOKEN, {}); - - expect(opened.status).toBe(201); - }); -}); diff --git a/apps/kitchen-sink/test/mailbox-reply.test.ts b/apps/kitchen-sink/test/mailbox-reply.test.ts index 18a6d74b8c..30170bc221 100644 --- a/apps/kitchen-sink/test/mailbox-reply.test.ts +++ b/apps/kitchen-sink/test/mailbox-reply.test.ts @@ -85,9 +85,9 @@ type Item = { toolCall?: { name?: string; arguments?: string }; }; -/** Every conversation of a seat that mentions `token`, with its items. */ +/** Every conversation of a worker (its sessions on `agent`'s one copy) that mentions `token`, with its items. */ async function conversationsHolding(router: Router, seat: string, token: string): Promise { - const listed = await call(router, "GET", ["sessions"], undefined, `?flowId=${encodeURIComponent(seat)}&userId=${USER}&include=dispatch-runs&limit=100`); + const listed = await call(router, "GET", ["sessions"], undefined, `?flowId=agent&state.workerId=${encodeURIComponent(seat)}&userId=${USER}&include=dispatch-runs&limit=100`); const rows = (JSON.parse(listed.text) as { sessions: Array<{ id: string }> }).sessions; const out: Item[][] = []; for (const row of rows) { diff --git a/apps/kitchen-sink/test/mailbox-wake.test.ts b/apps/kitchen-sink/test/mailbox-wake.test.ts index 37cc27d633..dbf8882d38 100644 --- a/apps/kitchen-sink/test/mailbox-wake.test.ts +++ b/apps/kitchen-sink/test/mailbox-wake.test.ts @@ -25,9 +25,6 @@ * BR-10 two posts at once each run exactly once, in that same conversation. * BR-14 the post's own request carries no seat's answer: the wake runs in * the mailbox's hand-off request. - * FIX-1602 BR-11: a seat conversation this app's own wake opened before - * it moved onto Workforce's `wakeMemberSeats` takes the next post. - * Red: the helper's key changed, so the next post opens a second. * BR-11, BR-12 need a roster this app does not have (a seat in two * mailboxes, a refused wake), so they are held on the factory below, * with a roster built for them. @@ -39,16 +36,17 @@ * without one. */ import { afterEach, describe, expect, it, vi } from "vitest"; -import { DEFAULT_ORG_ID, dispatcher, handler, utility, type BlockDefinition } from "@flow-state-dev/core"; +import { DEFAULT_ORG_ID, defineFlow, handler } from "@flow-state-dev/core"; import { z } from "zod"; import type { FlowState, StoreRegistry } from "@flow-state-dev/engine"; import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; import { MAILBOX_KIND, + createWorkerInstallation, mailboxNotifyInputSchema, defineMailboxFlow, hireWorkforce, - type MailboxNotifyInput, + workerConfigSchema, } from "@flow-state-dev/workforce"; // Each case boots the whole app afresh, and the first import is cold. @@ -131,9 +129,18 @@ async function seatPost(sessionId: string, body: string, author: string) { type Message = { role: string; text: string }; type Conversation = { sessionId: string; parentSessionId?: string; messages: Message[] }; -/** Every conversation of a seat, dispatch runs included, with its kept messages. */ +/** + * Every conversation of a worker, dispatch runs included, with its kept + * messages: the sessions on `agent`'s one copy created naming the worker. + */ async function conversationsOf(router: Router, seat: string): Promise { - const listed = await call(router, "GET", ["sessions"], undefined, `?flowId=${encodeURIComponent(seat)}&userId=${USER}&include=dispatch-runs&limit=100`); + const listed = await call( + router, + "GET", + ["sessions"], + undefined, + `?flowId=agent&state.workerId=${encodeURIComponent(seat)}&userId=${USER}&include=dispatch-runs&limit=100`, + ); expect(listed.status, listed.text).toBe(200); const rows = (JSON.parse(listed.text) as { sessions: Array<{ id: string; parentSessionId?: string | null }> }).sessions; const out: Conversation[] = []; @@ -284,9 +291,10 @@ async function bind(stores: StoreRegistry, sessionId: string, members: string[]) describe("V3 · the wake factory, off the app's own roster", () => { /** - * `support.otto` is hired and registered. `support.iris` is hired and handed - * to the wake, but its flow is not registered, so its dispatch is refused. - * `support.lost` never loaded, so it has no seat to wake. + * `support.otto` is a standard worker on `agent`, whose copy is registered. + * `support.iris` runs on `listener`, whose copy is handed to the wake but not + * registered, so its dispatch is refused. `support.lost` never loaded, so + * there is no worker to wake. */ async function host() { vi.resetModules(); @@ -294,13 +302,31 @@ describe("V3 · the wake factory, off the app's own roster", () => { vi.stubEnv("GOAL_CONTROL", ""); const { notifyFor } = await import("@/workforce/mailbox-notify"); const { createKitchenSinkTestModelResolver } = await import("@/test/mock-flowstate"); - const [iris, otto] = hireWorkforce([ - { id: "support.iris", declared: {}, body: "You answer questions." }, - { id: "support.otto", declared: {}, body: "You answer questions." }, - ]); - const mailbox = defineMailboxFlow({ notify: notifyFor([iris!, otto!]) })(); + let flows: Record = {}; + const installation = createWorkerInstallation({ + standardWorkers: [ + { id: "support.iris", declared: { flow: "listener" }, body: "You answer questions." }, + { id: "support.otto", declared: {}, body: "You answer questions." }, + ], + workerFlows: () => flows as never, + }); + const quiet = handler({ name: "listener-heard", inputSchema: z.unknown(), outputSchema: z.unknown(), execute: () => null }); + const door = z.object({ message: z.string() }); + flows = { + listener: defineFlow({ + kind: "listener", + configSchema: workerConfigSchema(), + session: installation.session(), + resources: { ...installation.resources }, + actions: { run: { inputSchema: door, userMessage: (i: { message: string }) => i.message, block: quiet } }, + internal: { actions: { onMailboxPost: { inputSchema: mailboxNotifyInputSchema, block: quiet } } }, + }), + }; + const copies = hireWorkforce(installation); + const agent = copies.find((copy) => copy.id === "agent")!; + const mailbox = defineMailboxFlow({ notify: notifyFor(copies, installation) })(); const state = createFlowState({ - flows: { [MAILBOX_KIND]: mailbox, [otto!.id]: otto! }, + flows: { [MAILBOX_KIND]: mailbox, [agent.id]: agent }, stores: { default: { primary: inMemoryStores() } }, modelResolver: createKitchenSinkTestModelResolver(), }); @@ -317,8 +343,8 @@ describe("V3 · the wake factory, off the app's own roster", () => { runtimeConfig: { ...runtime.runtimeConfig }, }); const ottoRuns = async () => { - const sessions = await runtime.stores.session.list({ flowId: "support.otto", parentage: "all" }); - return sessions.filter((s) => s.parentSessionId != null); + const sessions = await runtime.stores.session.list({ flowId: "agent", parentage: "all" }); + return sessions.filter((s) => s.parentSessionId != null && (s.state as { workerId?: string }).workerId === "support.otto"); }; return { state, runtime, send, ottoRuns }; } @@ -368,87 +394,3 @@ describe("V3 · the wake factory, off the app's own roster", () => { }); }); -describe("V3 · a restart onto the package's wake", () => { - it("lands the next post in the seat conversation the app's own wake opened before the move (BR-11)", async () => { - vi.resetModules(); - vi.stubEnv("KITCHEN_SINK_TEST_MODE", "1"); - vi.stubEnv("GOAL_CONTROL", ""); - const { notifyFor } = await import("@/workforce/mailbox-notify"); - // The old wake's fallback, as it was: a name-only line for a member it did not run. - const notifyMember = handler({ - name: "kitchen-sink-notify-member", - inputSchema: mailboxNotifyInputSchema, - outputSchema: z.object({ notified: z.string() }), - execute: (input: MailboxNotifyInput) => ({ notified: input.member }), - }); - const { createKitchenSinkTestModelResolver } = await import("@/test/mock-flowstate"); - const [otto] = hireWorkforce([{ id: "support.otto", declared: {}, body: "You answer questions." }]); - const stores = inMemoryStores(); - - // The wake this app built for itself before it moved onto the package's, - // as it was in what finds a conversation: the dispatcher's name, target, - // entry and key. - const before = utility.keyedRouter({ - name: "kitchen-sink-notify", - inputSchema: mailboxNotifyInputSchema, - blocks: { - "support.otto": dispatcher({ - name: "wake-support.otto", - flowKind: "support.otto", - action: "onMailboxPost", - inputSchema: mailboxNotifyInputSchema, - session: { key: (p: MailboxNotifyInput) => `mailbox:${p.mailboxId}` }, - }), - }, - select: (p: MailboxNotifyInput) => (p.author !== undefined ? "" : p.member), - fallback: notifyMember, - }); - - /** Boot on one wake, post once, wait for otto to hear it, and shut down. */ - const runOn = async (notify: BlockDefinition, body: string) => { - const mailbox = defineMailboxFlow({ notify })(); - const state = createFlowState({ - flows: { [MAILBOX_KIND]: mailbox, [otto!.id]: otto! }, - stores: { default: { primary: stores } }, - modelResolver: createKitchenSinkTestModelResolver(), - }); - try { - const runtime = await state.getRuntime(); - if ((await runtime.stores.session.get("room.one")) === undefined) { - await bind(runtime.stores, "room.one", ["support.otto"]); - } - const sent = await runAction({ - orgId: DEFAULT_ORG_ID, - flow: mailbox, - actionName: "post", - input: { body }, - userId: USER, - sessionId: "room.one", - stores: runtime.stores, - runtimeConfig: { ...runtime.runtimeConfig }, - }); - expect(sent.error).toBeUndefined(); - const runs = async () => - (await runtime.stores.session.list({ flowId: "support.otto", parentage: "all" })).filter( - (s) => s.parentSessionId === "room.one", - ); - const heard = async () => { - for (const run of await runs()) { - const requests = await runtime.stores.request.list({ sessionId: run.id }); - if (requests.some((r) => r.status === "completed" && JSON.stringify(r.input).includes(body))) return true; - } - return false; - }; - await until(heard, `otto to hear "${body}"`); - return (await runs()).map((r) => r.id); - } finally { - await state.dispose(); - } - }; - - const opened = await runOn(before, "[scenario:wake] before the move"); - expect(opened).toHaveLength(1); - const after = await runOn(notifyFor([otto!]), "[scenario:wake] after the move"); - expect(after).toEqual(opened); - }); -}); diff --git a/apps/kitchen-sink/test/named-org.test.ts b/apps/kitchen-sink/test/named-org.test.ts index ce94d2028f..12c4b86698 100644 --- a/apps/kitchen-sink/test/named-org.test.ts +++ b/apps/kitchen-sink/test/named-org.test.ts @@ -2,8 +2,8 @@ * Kitchen-sink runs as one named organization — driven through the app's own * `fsdev.config.ts` and the router it builds, not through `runAction`. * - * Every case imports the real config. So the host resolver, the admin - * credential, the boot's mailbox open and the step that clears a pre-change + * Every case imports the real config. So the host resolver, the boot's + * mailbox open and the step that clears a pre-change * store's mailboxes are the ones the app ships, and a request goes through * route-level authentication exactly as a browser's does. Promoted from the * spec POC (`specs/issues/FIX-1500/poc/named-org/`). @@ -16,8 +16,8 @@ * Checks, by the spec's ids (`specs/issues/FIX-1500/PLAN.md`), and the red * state each was seen in before its green was trusted: * - * V18 A session on the assistant's flow, on a seat and on a mailbox binds to - * `kitchen-sink`, whatever the body says. Red: remove `resolvePrincipal` + * V18 A session on the assistant's flow, with a worker and on a mailbox + * binds to `kitchen-sink`, whatever the body says. Red: remove `resolvePrincipal` * from `fsdev.config.ts` — every session binds to `__fsd_default_org__`. * V19 A store written before the app named its organization is not * upgraded: it is wiped (the owner's call on #2159). The boot over one @@ -26,16 +26,6 @@ * mailbox is moved, rebound or deleted. Red: remove the guard in `fsdev.config.ts` — the boot fails with the * bare `mailbox "support.help" could not be opened — Request failed * (403)`, which names neither the cause nor the fix. - * V22 With `acme:t1,kitchen-sink:t2`, the `acme` token is refused (401) and - * named in the boot log, and the `kitchen-sink` token's `fire` releases - * the seat its `hire` made. Red: accept the `acme` binding — its token - * resolves, and its fire answers `This organization hired no seat`. - * - * V11 and V14 were proven through the rail's hire, and left with it (FIX-1611 - * D3): an operator's hire landing in `kitchen-sink` whatever its body names is - * `workforce-admin.test.ts` V10, and one surviving a restart is - * `hired-seat-auth.test.ts` and the goal check - * `goals/workforce-conventions/durable-hire-survives-redeploy/`. */ import { afterEach, describe, expect, it, vi } from "vitest"; import { mkdtemp, rm } from "node:fs/promises"; @@ -90,12 +80,11 @@ afterEach(async () => { vi.restoreAllMocks(); }); -async function bootApp(options: { dataDir?: string; tokens?: string; steps?: ScriptStep[] } = {}) { +async function bootApp(options: { dataDir?: string; steps?: ScriptStep[] } = {}) { vi.resetModules(); script.steps = options.steps ?? [{ text: "ok" }]; vi.stubEnv("KITCHEN_SINK_TEST_MODE", "1"); vi.stubEnv("STORE_TYPE", options.dataDir === undefined ? "memory" : "filesystem"); - vi.stubEnv("WORKFORCE_ADMIN_TOKENS", options.tokens ?? ""); delete process.env.FSDEV_DEFAULT_MODEL; // The config roots the filesystem profile at `/.fsdev/data`. if (options.dataDir !== undefined) vi.spyOn(process, "cwd").mockReturnValue(options.dataDir); @@ -154,11 +143,17 @@ async function act(router: Router, flowId: string, action: string, sessionId: st // --------------------------------------------------------------------------- describe("V18 · one organization, from the host resolver", () => { - it("binds the assistant's flow, a seat and a mailbox to kitchen-sink, whatever the body says", async () => { + it("binds the assistant's flow, a worker's conversation and a mailbox to kitchen-sink, whatever the body says", async () => { const { router } = await bootApp(); - for (const flowId of ["chat-agent", "support.devices", "support.general", "mailbox"]) { - const opened = await openSession(router, flowId, { orgId: "globex" }); + const opens: Array<[string, Record]> = [ + ["chat-agent", {}], + ["agent", { state: { workerId: "support.devices" } }], + ["agent", { state: { workerId: "support.general" } }], + ["mailbox", {}], + ]; + for (const [flowId, body] of opens) { + const opened = await openSession(router, flowId, { orgId: "globex", ...body }); expect(opened.status, `${flowId}: ${opened.text}`).toBe(201); expect(opened.orgId, flowId).toBe(ORG); } @@ -170,39 +165,6 @@ describe("V18 · one organization, from the host resolver", () => { }); -describe("V22 · every admin token is bound to kitchen-sink", () => { - it("refuses and names an acme token, and the kitchen-sink token fires the seat it hired", async () => { - const { runtime, router, log } = await bootApp({ tokens: "acme:t1,kitchen-sink:t2" }); - - expect(log.join("\n")).toMatch(/names organization "acme"/); - - // The operator's hire, pinned to the organization and the admin user. - const seat = `${ORG}.~workforce-admin.support.pat`; - const hired = await act( - router, - "workforce-admin", - "hire", - "admin-hire", - { seatId: "support.pat", flow: "agent", instructions: "Takes refunds." }, - {}, - { authorization: "Bearer t2" }, - ); - expect(hired.text).not.toMatch(/"type":"error"/); - expect(runtime.registry.get(seat)?.kind).toBe("agent"); - - const acme = await act(router, "workforce-admin", "fire", "admin-acme", { seatId: "support.pat" }, {}, { authorization: "Bearer t1" }); - expect(acme.status, acme.text).toBe(401); - expect(runtime.registry.get(seat)).toBeDefined(); - - const fired = await act(router, "workforce-admin", "fire", "admin-fire", { seatId: "support.pat" }, {}, { authorization: "Bearer t2" }); - // The action's `{ released }` result is a block output, which a client - // stream never carries; the registry below is the evidence it fired. - expect(fired.status, fired.text).toBe(200); - expect(fired.text).not.toMatch(/"type":"error"/); - expect(runtime.registry.get(seat)).toBeUndefined(); - }); -}); - describe("V19 · a store written before the app named its organization", () => { /** * The boot the app ran before it named its organization, for the part that @@ -211,8 +173,8 @@ describe("V19 · a store written before the app named its organization", () => { * development organization. */ async function preChangeBoot(dataDir: string) { - const { hireKitchenSinkWorkforce } = await import("@/workforce/hire"); - const workforce = await hireKitchenSinkWorkforce(); + const { buildKitchenSinkWorkforce } = await import("@/workforce/hire"); + const workforce = await buildKitchenSinkWorkforce(); const flowstate = createFlowState({ flows: Object.fromEntries(workforce.mailboxFlows.map((flow) => [flow.id, flow])), stores: { dev: { primary: filesystemStores({ rootDir: path.join(dataDir, ".fsdev", "data") }) } }, diff --git a/apps/kitchen-sink/test/roster-boot-report.test.tsx b/apps/kitchen-sink/test/roster-boot-report.test.tsx deleted file mode 100644 index c4916b6ee2..0000000000 --- a/apps/kitchen-sink/test/roster-boot-report.test.tsx +++ /dev/null @@ -1,236 +0,0 @@ -// @vitest-environment happy-dom -/** - * The skipped seats a boot could not bring back, on screen in the roster - * panel of the organization they belong to. - * - * The boot here is the real one minus the module it lives in: the real - * `reloadHiredSeats` over rows in a real in-memory store, then the same - * `admitReloadedSeats` `fsdev.config.ts` calls, with a registrar that can be - * told to refuse a seat. The panel is the shell's own `TeamPanel`, reading - * through the engine's collection routes as a browser would. Assertions are on - * the rendered DOM, so they hold whatever shape the report takes in between. - * - * `acme` holds two failures of different origin: a row the reload cannot turn - * into a seat, and a seat that loads and is then refused at registration. - * `beta` holds one good seat and no failure. - * - * Red states produced before these were trusted: - * - admit refusals into the flat list only, not the org's report: (b) fails - * and (a), (c), (d) stay green. - * - write every org's report from the flat problem list: (c) fails. - * - skip the write for an org with no problems: (d) fails, because boot - * one's report is still standing. - * - never write the report at all: V14 fails with the roster showing a - * clean list. - */ -import { afterEach, describe, expect, it } from "vitest"; -import { cleanup, render, waitFor, within } from "@testing-library/react"; -import { z } from "zod"; -import { defineFlow, handler } from "@flow-state-dev/core"; -import type { FlowInstance } from "@flow-state-dev/core/types"; -import { createFlowState, inMemoryStores } from "@flow-state-dev/engine"; -import { createResourceClient } from "@flow-state-dev/client"; -import { FlowProvider } from "@flow-state-dev/react"; -import { createMockModelResolver } from "@flow-state-dev/testing"; -import { reloadHiredSeats } from "@flow-state-dev/workforce"; - -import { TeamPanel } from "../components/team-panel"; -import { workforcePanelResources } from "../flows/chat-agent/shared/workforce-panels"; -import { admitReloadedSeats } from "../lib/roster-reload-report"; -import { ROSTER_BOOT_REPORT_REF } from "../lib/workforce-shell"; -import { kitchenSinkKinds } from "../workforce/hire"; - -const FLOW_KIND = "shell-panels"; -const ORGS = ["acme", "beta"]; - -/** The shell's panel declarations, on a flow whose sessions bind a verified org. */ -const panelFlow = defineFlow({ - kind: FLOW_KIND, - resources: workforcePanelResources, - actions: { - noop: { - inputSchema: z.object({}), - block: handler({ - name: "noop", - inputSchema: z.object({}), - outputSchema: z.object({}), - execute: async () => ({}), - }), - }, - }, - authentication: { - resolvePrincipal: (context) => { - const org = context.request?.headers.get("x-verified-org"); - return org == null ? null : { userId: `user-of-${org}`, orgId: org }; - }, - }, -}); - -function seatRow(seatId: string, flow: string) { - return { seatId, flow, settings: {}, instructions: null, owningOrgId: null, ownerUserId: null }; -} - -async function harness() { - const state = createFlowState({ - flows: { [FLOW_KIND]: panelFlow() }, - stores: { default: { primary: inMemoryStores() } }, - modelResolver: createMockModelResolver({}), - }); - const runtime = await state.getRuntime(); - const router = (await state.getRouter()) as Record< - string, - (request: Request, ctx: { params: { path: string[] } }) => Promise - >; - - /** A browser's fetch, pointed at the router, carrying one org's credential. */ - const fetcherFor = (org: string, reportReads: string[], failReport = false) => - async (input: RequestInfo | URL, init?: RequestInit): Promise => { - const url = new URL(String(input), "http://test"); - const path = url.pathname - .replace(/^\/api\/flows\/?/, "") - .split("/") - .filter((segment) => segment.length > 0) - .map(decodeURIComponent); - const method = (init?.method ?? "GET").toUpperCase(); - if (failReport && path.at(-1) === ROSTER_BOOT_REPORT_REF) { - reportReads.push(org); - return new Response(JSON.stringify({ error: "store unavailable" }), { status: 503 }); - } - const headers = new Headers(init?.headers); - headers.set("x-verified-org", org); - const response = await router[method]!(new Request(url, { ...init, headers }), { - params: { path }, - }); - if (path.at(-1) === ROSTER_BOOT_REPORT_REF) reportReads.push(org); - return response; - }; - - async function openSession(org: string): Promise { - const response = await router.POST!( - new Request(`http://test/api/flows/${FLOW_KIND}/sessions`, { - method: "POST", - headers: { "content-type": "application/json", "x-verified-org": org }, - body: JSON.stringify({ userId: `user-of-${org}` }), - }), - { params: { path: [FLOW_KIND, "sessions"] } }, - ); - const json = (await response.json()) as { session?: { id: string }; id?: string }; - const id = json.session?.id ?? json.id; - if (id === undefined) throw new Error(`no session: ${JSON.stringify(json)}`); - return id; - } - - /** One boot: the reload, then admission through a registrar that may refuse. */ - async function boot(refuse: ReadonlySet) { - const reload = await reloadHiredSeats({ - stores: runtime.stores, - orgIds: ORGS, - workerFlows: kitchenSinkKinds, - }); - await admitReloadedSeats({ - reload, - stores: runtime.stores, - admit: (seat: FlowInstance) => { - if (refuse.has(seat.id)) throw new Error("the registry refused this address"); - }, - }); - } - - /** The panel as the given org's member sees it, once the report has been read. */ - async function panelFor(org: string, options: { failReport?: boolean } = {}): Promise { - const sessionId = await openSession(org); - const reportReads: string[] = []; - const fetcher = fetcherFor(org, reportReads, options.failReport); - const client = createResourceClient({ baseUrl: "http://test", fetcher }); - const { container } = render( - - - , - ); - const panel = within(container).getByTestId("roster-panel").parentElement!; - // Not settled until BOTH reads are back: the seats, and the report. An - // assertion that the problems are absent means nothing before the report - // has been read. - await waitFor(() => { - expect(panel.querySelector("[data-roster-seats]")).not.toBeNull(); - expect(reportReads).toContain(org); - }); - await new Promise((resolve) => setTimeout(resolve, 0)); - return panel; - } - - return { stores: runtime.stores, boot, panelFor }; -} - -afterEach(cleanup); - -describe("V14 · a skipped seat is on screen, beside the seats", () => { - it("shows the seats and the skipped seat with its reason", async () => { - const h = await harness(); - await h.stores.resourceState.set("org", "acme", "workforce/roster/support.ada", seatRow("support.ada", "agent"), "any"); - await h.stores.resourceState.set("org", "acme", "workforce/roster/support.bo", seatRow("support.bo", "kind-that-is-gone"), "any"); - await h.boot(new Set()); - - const panel = await h.panelFor("acme"); - expect(panel.querySelector("[data-seat-id='support.ada']")).not.toBeNull(); - expect(panel.querySelector("[data-roster-problems]")).not.toBeNull(); - expect(panel.textContent).toContain("could not be loaded"); - expect(panel.textContent).toContain("kind-that-is-gone"); - }); -}); - -describe("V15 · two organizations, two boots, one report each", () => { - it("files each failure under its own org, and clears it on the next clean boot", async () => { - const h = await harness(); - const set = (org: string, seatId: string, flow: string) => - h.stores.resourceState.set("org", org, `workforce/roster/${seatId}`, seatRow(seatId, flow), "any"); - - // acme: a row that fails to load, and a seat that loads and is refused. - await set("acme", "support.bo", "kind-that-is-gone"); - await set("acme", "support.cy", "agent"); - // beta: one good seat, nothing wrong. - await set("beta", "support.ada", "agent"); - - await h.boot(new Set(["acme.support.cy"])); - - const acme = await h.panelFor("acme"); - // Soft, so a red run reports every one of (a)–(d) that failed rather than - // stopping at the first: each excludes one failure the others cannot. - // (a) the load failure - expect.soft(acme.textContent, "(a)").toContain('row "workforce/roster/support.bo"'); - // (b) the registration refusal - expect.soft(acme.textContent, "(b)").toContain("acme.support.cy — the registry refused this address"); - - // (c) beta names no problems, having read its report and drawn its seat - const beta = await h.panelFor("beta"); - expect(beta.querySelector("[data-seat-id='support.ada']")).not.toBeNull(); - expect.soft(beta.querySelector("[data-roster-problems]"), "(c)").toBeNull(); - expect.soft(beta.textContent, "(c)").not.toContain("acme"); - cleanup(); - - // Boot two, with both of acme's causes removed: the row repaired, and the - // address that refused the other seat freed. - await set("acme", "support.bo", "agent"); - await h.boot(new Set()); - - // (d) acme names no problems - const acmeAgain = await h.panelFor("acme"); - expect(acmeAgain.querySelector("[data-seat-id='support.bo']")).not.toBeNull(); - expect.soft(acmeAgain.querySelector("[data-roster-problems]"), "(d)").toBeNull(); - }); -}); - -describe("a boot report that cannot be read", () => { - it("says so on its own line, and does not count as a skipped seat", async () => { - const h = await harness(); - await h.stores.resourceState.set("org", "acme", "workforce/roster/support.ada", seatRow("support.ada", "agent"), "any"); - await h.boot(new Set()); - - const panel = await h.panelFor("acme", { failReport: true }); - expect(panel.textContent).toContain("could not be read"); - // Counting the failure as a seat would report one skipped seat that does - // not exist. - expect(panel.querySelector("[data-roster-problems]")).toBeNull(); - expect(panel.querySelector("[data-seat-id='support.ada']")).not.toBeNull(); - }); -}); diff --git a/apps/kitchen-sink/test/roster-reload-report.test.ts b/apps/kitchen-sink/test/roster-reload-report.test.ts deleted file mode 100644 index 0d4786a854..0000000000 --- a/apps/kitchen-sink/test/roster-reload-report.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -/** - * `admitReloadedSeats` on its failure path: a report that cannot be written - * is a line in the boot's log, not a boot that stops. - * - * Red state: await the write unguarded, and the first organization's store - * error rejects the whole call, so the second organization's seats are never - * admitted. - */ -import { describe, expect, it } from "vitest"; -import type { FlowInstance } from "@flow-state-dev/core/types"; -import type { HiredRosterReload } from "@flow-state-dev/workforce"; - -import { admitReloadedSeats } from "../lib/roster-reload-report"; - -const seat = (id: string) => ({ id }) as FlowInstance; - -describe("admitReloadedSeats", () => { - it("keeps admitting when one organization's report cannot be written, and says so", async () => { - const reload: HiredRosterReload = { - seats: [seat("acme.support.ada"), seat("beta.support.ada")], - problems: [], - byOrg: [ - { orgId: "acme", seats: [seat("acme.support.ada")], problems: [] }, - { orgId: "beta", seats: [seat("beta.support.ada")], problems: [] }, - ], - }; - const admitted: string[] = []; - const written: string[] = []; - - const result = await admitReloadedSeats({ - reload, - admit: (instance) => { - admitted.push(instance.id); - }, - stores: { - resourceState: { - set: async (_scope, orgId) => { - if (orgId === "acme") throw new Error("connection reset"); - written.push(orgId); - }, - }, - }, - }); - - expect(admitted).toEqual(["acme.support.ada", "beta.support.ada"]); - expect(written).toEqual(["beta"]); - expect(result.seats).toEqual(["acme.support.ada", "beta.support.ada"]); - // Both seats were admitted; a report-write failure is not a skipped seat. - expect(result.problems).toHaveLength(0); - expect(result.reportErrors).toHaveLength(1); - expect(result.reportErrors[0]).toContain('organization "acme"'); - expect(result.reportErrors[0]).toContain("connection reset"); - }); - - it("counts a report-write failure separately from skipped seats, with every seat admitted", async () => { - const reload: HiredRosterReload = { - seats: [seat("acme.support.ada")], - problems: [], - byOrg: [{ orgId: "acme", seats: [seat("acme.support.ada")], problems: [] }], - }; - const admitted: string[] = []; - - const result = await admitReloadedSeats({ - reload, - admit: (instance) => { - admitted.push(instance.id); - }, - stores: { - resourceState: { - set: async () => { - throw new Error("connection reset"); - }, - }, - }, - }); - - expect(admitted).toEqual(["acme.support.ada"]); - expect(result.seats).toEqual(["acme.support.ada"]); - // A report the boot could not write is not a seat the boot could not - // bring back — the seat is running, only the panel's picture of it isn't. - expect(result.problems).toHaveLength(0); - expect(result.reportErrors).toHaveLength(1); - expect(result.reportErrors[0]).toContain('organization "acme"'); - expect(result.reportErrors[0]).toContain("connection reset"); - }); -}); diff --git a/apps/kitchen-sink/test/seat-pane.test.tsx b/apps/kitchen-sink/test/seat-pane.test.tsx deleted file mode 100644 index 1e9d26f3dd..0000000000 --- a/apps/kitchen-sink/test/seat-pane.test.tsx +++ /dev/null @@ -1,109 +0,0 @@ -// @vitest-environment happy-dom -/** - * What a seat opened in the rail reads, by the kind of address it has. - * - * Only a seat hired into the whole organization has a public roster row, and - * its row is keyed by the seat id inside its address. A seat declared in a - * worker file has no row; a seat a user hired for themselves has a row the - * rail may not read, and its short id can equal an org-visible seat's. - * - * Checks, by the spec's ids (`specs/issues/FIX-1500/PLAN.md`), and the red - * state each was seen in before its green was trusted: - * - * V17 A user-owned seat, `.~.`, whose short id matches an - * org-visible seat's, opens as "not published" and reads nothing. Red: - * derive the topic with `splitSeatAddress` alone, which skips the user - * segment — the pane reads `support.pat` and shows the other seat's - * instructions. - * The org-visible case reads exactly one item, under the roster key the - * hire writes. Red: pass no `collectionRef` — the read goes to `roster`. - * - * And what a declared seat handles (FIX-1611 BR-1): its `WORKER.md`'s - * `description:`, drawn under its kind. Red: the pane before FIX-1611, which - * drew no description. - */ -import { afterEach, describe, expect, it } from "vitest"; -import { cleanup, render, waitFor, within } from "@testing-library/react"; -import { FlowProvider, type PanelItemSource } from "@flow-state-dev/react"; -import { HIRED_ROSTER_RESOURCE } from "@flow-state-dev/workforce"; - -import { SeatPane } from "../components/seat-pane"; - -const ORG = "kitchen-sink"; - -afterEach(cleanup); - -/** A resource client holding one org-visible seat, `support.pat`, that records every read. */ -function rosterWithPat() { - const reads: Array<[ref: string, topic: string]> = []; - const client: PanelItemSource = { - getCollectionItemState: async (_sessionId, ref, topic) => { - reads.push([ref, topic]); - if (ref !== HIRED_ROSTER_RESOURCE || topic !== "support.pat") return null; - return { - topic, - clientData: { seatId: "support.pat", flow: "agent", instructions: "Handles the org's refunds." }, - } as unknown as Awaited>; - }, - }; - return { client, reads }; -} - -function open(address: string, client: PanelItemSource): HTMLElement { - const { container } = render( - - - , - ); - return container; -} - -/** Let any read the pane started come back before asserting on what it did not do. */ -const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); - -describe("a seat opened in the rail", () => { - it("V17 · a user-owned seat sharing an org seat's short id is not published, and reads nothing", async () => { - const { client, reads } = rosterWithPat(); - const pane = open(`${ORG}.~workforce-admin.support.pat`, client); - await settle(); - - expect(within(pane).getByText("agent")).toBeTruthy(); - expect(pane.querySelector('[data-state="not-published"]')).not.toBeNull(); - expect(pane.textContent).not.toContain("Handles the org's refunds."); - expect(reads).toEqual([]); - }); - - it("a seat hired into the organization reads its one roster row and shows its instructions", async () => { - const { client, reads } = rosterWithPat(); - const pane = open(`${ORG}.support.pat`, client); - - await waitFor(() => expect(pane.querySelector('[data-state="text"]')?.textContent).toBe("Handles the org's refunds.")); - expect(reads).toEqual([[HIRED_ROSTER_RESOURCE, "support.pat"]]); - }); - - it("a seat declared in a worker file shows what it handles, is not published, and reads nothing", async () => { - const { client, reads } = rosterWithPat(); - const pane = open("support.devices", client); - await settle(); - - expect(within(pane).getByTestId("seat-description").textContent).toBe( - "Printers, laptops, phones, wifi and anything else with a power button.", - ); - expect(pane.querySelector('[data-state="not-published"]')).not.toBeNull(); - expect(reads).toEqual([]); - }); - - it("a hired seat draws no description: only a declared seat's file has one", async () => { - const { client } = rosterWithPat(); - const pane = open(`${ORG}.support.pat`, client); - await settle(); - - expect(within(pane).queryByTestId("seat-description")).toBeNull(); - }); -}); diff --git a/apps/kitchen-sink/test/shell-imports.test.ts b/apps/kitchen-sink/test/shell-imports.test.ts index a001309cc5..bdc2632933 100644 --- a/apps/kitchen-sink/test/shell-imports.test.ts +++ b/apps/kitchen-sink/test/shell-imports.test.ts @@ -43,13 +43,14 @@ describe("V9 · the shell's rail and panel are package components", () => { expect(page).not.toMatch(/components\/session-sidebar/); }); - it("draws the panel with the package's roster and board list", () => { + it("draws the panel with the package's board list, and the roster from Workforce's client", () => { const panel = read("components/team-panel.tsx"); const fromReact = importedFrom(panel, "@flow-state-dev/react"); - expect(fromReact).toEqual(expect.arrayContaining(["Roster", "BoardList"])); + expect(fromReact).toEqual(expect.arrayContaining(["BoardList"])); expect(fromReact).not.toContain("BoardColumns"); - expect(panel).toContain(" { diff --git a/apps/kitchen-sink/test/support-desk.test.ts b/apps/kitchen-sink/test/support-desk.test.ts index 7d6361fc11..adfe60f4f1 100644 --- a/apps/kitchen-sink/test/support-desk.test.ts +++ b/apps/kitchen-sink/test/support-desk.test.ts @@ -20,6 +20,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { __resetDeprecationWarningsForTests } from "@flow-state-dev/core"; import type { FlowState } from "@flow-state-dev/engine"; import { createSessionClient } from "@flow-state-dev/client"; +import { createWorkforceClient } from "@flow-state-dev/workforce/browser"; vi.setConfig({ testTimeout: 30_000 }); @@ -50,44 +51,48 @@ async function boot() { return (await res.json()) as unknown; }; // The page's session client, over the app's own router. - const sessions = createSessionClient({ - fetcher: async (input: RequestInfo | URL, init?: RequestInit) => { - const url = new URL(String(input), "http://localhost"); - const path = url.pathname - .replace(/^\/api\/flows\/?/, "") - .split("/") - .filter((segment) => segment.length > 0) - .map(decodeURIComponent); - const method = (init?.method ?? "GET").toUpperCase() as "GET" | "POST" | "PATCH" | "DELETE"; - return await router[method](new Request(url, init), { params: { path } }); - }, - }); - return { get, sessions }; + const sessionsFetcher = async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(input), "http://localhost"); + const path = url.pathname + .replace(/^\/api\/flows\/?/, "") + .split("/") + .filter((segment) => segment.length > 0) + .map(decodeURIComponent); + const method = (init?.method ?? "GET").toUpperCase() as "GET" | "POST" | "PATCH" | "DELETE"; + return await router[method](new Request(url, init), { params: { path } }); + }; + const sessions = createSessionClient({ fetcher: sessionsFetcher }); + // The page's workforce client, over the same router. + const workforce = createWorkforceClient({ userId: "devuser", fetcher: sessionsFetcher }); + return { get, sessions, workforce }; } describe("V1 · the boot serves one routed mailbox and four specialists", () => { - it("hires the four specialists on the agent kind, and no other seat", async () => { - const { get } = await boot(); - const { flows } = (await get([])) as { flows: Array<{ id: string; kind: string; cardinality: string }> }; - const seats = flows.filter((flow) => flow.cardinality === "collection" && flow.id !== flow.kind); - expect(seats.map((seat) => [seat.id, seat.kind]).sort()).toEqual([ - ["support.accounts", "agent"], - ["support.devices", "agent"], - ["support.fsd", "agent"], - ["support.general", "agent"], + it("runs the four specialists as standard workers on one copy of agent, and registers no copy per worker", async () => { + const { get, workforce } = await boot(); + const roster = await workforce.roster(); + expect(roster.map((worker) => [worker.id, worker.flow, worker.standard]).sort()).toEqual([ + ["support.accounts", "agent", true], + ["support.devices", "agent", true], + ["support.fsd", "agent", true], + ["support.general", "agent", true], ]); + const { flows } = (await get([])) as { flows: Array<{ id: string; kind: string }> }; + expect(flows.filter((flow) => flow.kind === "agent").map((flow) => flow.id)).toEqual(["agent"]); + expect(flows.filter((flow) => roster.some((worker) => worker.id === flow.id))).toEqual([]); }); it("opens one mailbox, support.help, on the built-in mailbox kind, beside the app's own flows", async () => { const { get } = await boot(); const { flows } = (await get([])) as { flows: Array<{ id: string; kind: string }> }; - // The workforce's kinds are the two built-ins; the rest are the app's own flows. + // The workforce's kinds are the built-ins: `agent`, the mailbox and the roster flow. The rest are the app's own flows. expect([...new Set(flows.map((flow) => flow.kind))].sort()).toEqual([ "agent", "chat-agent", "mailbox", "rich-text-component", "weekly-digest", + "workforce-roster", ]); const { sessions } = (await get(["sessions"], "?flowId=mailbox&limit=100")) as { sessions: Array<{ id: string }> }; expect(sessions.map((session) => session.id)).toEqual(["support.help"]); diff --git a/apps/kitchen-sink/test/workforce-admin.test.ts b/apps/kitchen-sink/test/workforce-admin.test.ts deleted file mode 100644 index 7300ff0d5c..0000000000 --- a/apps/kitchen-sink/test/workforce-admin.test.ts +++ /dev/null @@ -1,772 +0,0 @@ -/** - * `workforce-admin` — the hire and fire refusals, driven through the real - * `runAction` engine against in-memory stores. - * - * Each case names what would make it fail. The red states were produced and - * reverted before the greens here were trusted: - * - * V9 — register the admin flow unconditionally: the fail-closed assertion - * passes trivially and a default deployment has a hire path. - * V10 — return the org from the envelope instead of the token: the resolver - * hands back the body's organization for the kitchen-sink credential. - * V11 — for the ordinary duplicate, remove the address pre-check: the second - * hire reaches the row write, and `create()` refuses it there instead - * of the refusal naming what holds the address. - * **`upsert()` does NOT turn this case red, and that is worth knowing - * rather than assuming**: when the first hire registered, the address - * pre-check refuses the second one before any write happens, so the - * write verb is never reached. The two cases below that DO reach it — - * a stranded row with a free address, and two hires at once — are the - * ones where `create()` is load-bearing, and both go red under - * `upsert()`. - * V12 — read-then-write, or `upsert()`, instead of `create()`: both - * concurrent hires resolve and the last write wins. - * V13 — remove the compensating delete: a hire whose registration failed - * leaves a live row, so the seat appears at the next boot although the - * caller was told the hire failed. - * V15 — unregister by address alone: the foreign instance goes offline. - * - * V9b — run the organization check before the collision check: with - * `kitchen-sink:shared,elsewhere:shared` only `elsewhere`'s entry is - * dropped, and a secret handed out for `elsewhere` administers - * kitchen-sink. Produced: `adminCredentialConfigured()` read true. - * V22 — drop the organization check: an `elsewhere` token resolves, to a - * roster nothing in this app reads. Produced: the principal came back - * as `elsewhere`. - * V11 (settings shadow) — spread the row as `{ flow, ...settings }` in - * `packages/workforce/src/roster/rows.ts`: the hire takes the kind the - * settings bag names, not the row's `agent`. This app carries one - * kind, so the bag names one it does not carry and the hire is - * refused where it should have been accepted. - * V15b — gate `fire` on `liveKind !== storedKind` alone: a file-declared - * seat carrying the row's OWN kind is unregistered (`released: true`). - * - * `fire` releases an address only when BOTH clauses hold — this app registered - * it from a roster row, AND the live kind still matches the stored one. - * Neither subsumes the other, and V15b and V15 are the two red states that say - * so: drop the provenance clause and V15b fails, drop the kind clause and V15 - * fails. - */ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { FlowInstance } from "@flow-state-dev/core/types"; -import { createInMemoryStores, runAction } from "@flow-state-dev/engine"; -import { createMockModelResolver } from "@flow-state-dev/testing"; -import { seatAddress, splitSeatAddress } from "@flow-state-dev/workforce"; -import { - ADMIN_TOKENS_ENV, - adminCredentialConfigured, - adminPrincipalResolver, -} from "../lib/workforce-admin-auth"; -import { - setWorkforceRegistrarImpl, - workforceRegistrar, - type WorkforceRegistrar, -} from "../lib/workforce-registrar"; -import workforceAdminFlow from "../flows/workforce-admin/flow"; -import { KITCHEN_SINK_ORG_ID } from "../lib/kitchen-sink-principal"; - -const modelResolver = createMockModelResolver({ policy: "allow" }); - -/** The one organization every admin token must name. */ -const ORG = KITCHEN_SINK_ORG_ID; -/** Any other organization. A token may not name it; a row written under it before the pin may exist. */ -const OTHER_ORG = "elsewhere"; - -/** A registrar stub that records what was admitted, and can be made to refuse. */ -function stubRegistrar(options: { refuse?: boolean } = {}) { - const held = new Map(); - const impl: WorkforceRegistrar & { held: Map } = { - held, - register: (flow) => { - if (options.refuse === true) throw new Error("the registry refused this seat"); - held.set(flow.id, flow); - }, - unregister: (id) => held.delete(id), - kindAt: (id) => held.get(id)?.kind, - }; - setWorkforceRegistrarImpl(impl); - return impl; -} - -/** - * The admin flow instance. - * - * Imported statically, and `vi.resetModules()` is deliberately NOT used. A - * reset forks the module graph, so the flow would close over a *different* - * copy of `lib/workforce-registrar` than `stubRegistrar` installs into — which - * is how every successful hire in this file first failed with "the workforce - * registrar has not been installed". The flow's own resolver is never - * exercised through `runAction` (that is transport-level), so it does not - * matter that the module evaluated before the env was stubbed. - * - * Two different lifetimes are in play here, and only one of them is what V9 - * and V10 exercise. Calling `adminPrincipalResolver()` directly — which is - * what V9 and V10 do — re-reads the env on that call, so stubbing the env - * first and calling it after sees the stub. The resolver `flow.ts` actually - * wires in (`resolvePrincipal: adminPrincipalResolver()`) is called once, at - * module evaluation, and closes over whatever the env held at that moment; - * changing the env afterwards does not reach an already-imported flow. - */ -function adminFlow(): FlowInstance { - return workforceAdminFlow as FlowInstance; -} - -/** - * One admin action, through the real engine. - * - * The outcome is read off `ExecutionResult.error` rather than a status string. - * That distinction is load-bearing and was found by this file failing: `runAction` - * returns no `status` field at all, so an assertion like - * `expect(result.status).not.toBe("completed")` is satisfied by `undefined` and - * passes against an implementation that refuses nothing. - */ -async function callAdmin( - flow: FlowInstance, - stores: ReturnType, - actionName: "hire" | "fire", - input: unknown, - orgId: string = ORG, - userId: string = "admin", -) { - return runAction({ - flow, - actionName, - input, - userId, - orgId, - stores, - runtimeConfig: { modelResolver }, - }); -} - -/** Assert the call succeeded, naming the error when it did not. */ -function expectAccepted(result: { error?: { message?: string } }): void { - expect(result.error?.message ?? null).toBe(null); -} - -/** Assert the call was refused, and that the refusal says why. */ -function expectRefused(result: { error?: { message?: string } }, because: RegExp): void { - expect(result.error).toBeDefined(); - expect(result.error?.message ?? "").toMatch(because); -} - -/** The stored roster row for one seat, read straight out of the store. */ -async function storedRow( - stores: ReturnType, - seatId: string, - orgId: string = ORG -): Promise | undefined> { - const rows = await stores.resourceState.getByPrefix("org", orgId, "workforce/roster/"); - const match = Object.values(rows).find((row) => row.state.seatId === seatId); - return match?.state as Record | undefined; -} - -beforeEach(() => { - vi.stubEnv(ADMIN_TOKENS_ENV, `${ORG}:tok-ks`); -}); - -afterEach(() => { - vi.unstubAllEnvs(); -}); - -describe("V9 · the admin door is fail-closed", () => { - it("has no credential and therefore no resolver when the env is unset", () => { - vi.stubEnv(ADMIN_TOKENS_ENV, ""); - expect(adminCredentialConfigured()).toBe(false); - // `undefined` is what makes `fsdev.config.ts` leave the flow out of the - // `flows` map entirely. Registering it unconditionally and checking the - // credential inside the action would put a hire path on every default - // deployment, guarded by a check somebody could get wrong. - expect(adminPrincipalResolver()).toBeUndefined(); - }); - - it("refuses a request carrying no credential, and one carrying a wrong credential", () => { - const resolve = adminPrincipalResolver(); - expect(resolve).toBeDefined(); - const envelope = { flowKind: "workforce-admin", action: "hire", input: {} }; - - expect(() => - resolve!({ source: "http", request: new Request("http://x"), envelope }) - ).toThrow(/admin credential/i); - - expect(() => - resolve!({ - source: "http", - request: new Request("http://x", { headers: { authorization: "Bearer nope" } }), - envelope, - }) - ).toThrow(/Invalid/i); - }); -}); - -describe("V9b · a token two organizations share resolves neither", () => { - it("drops EVERY binding for it, including kitchen-sink's", () => { - // Somebody was handed `shared` believing it administers `elsewhere`. - // Refusing only the `elsewhere` entry — which the organization check alone - // would do — leaves that credential administering kitchen-sink. - // - // Red state: run the organization check before the collision check. - // `kitchen-sink:shared` survives and this reads true. - vi.spyOn(console, "error").mockImplementation(() => {}); - vi.stubEnv(ADMIN_TOKENS_ENV, `${ORG}:shared,${OTHER_ORG}:shared`); - - // The only token collided, so nothing is configured — which is what makes - // `fsdev.config.ts` leave the admin flow out of the `flows` map entirely. - expect(adminCredentialConfigured()).toBe(false); - expect(adminPrincipalResolver()).toBeUndefined(); - }); - - it("leaves an uncollided token working, and refuses the shared one", async () => { - vi.spyOn(console, "error").mockImplementation(() => {}); - vi.stubEnv(ADMIN_TOKENS_ENV, `${ORG}:shared,${OTHER_ORG}:shared,${ORG}:tok-ks`); - const resolve = adminPrincipalResolver(); - expect(resolve).toBeDefined(); - - const envelope = { flowKind: "workforce-admin", action: "hire", input: {} }; - const withToken = (token: string) => ({ - source: "http" as const, - request: new Request("http://x", { headers: { authorization: `Bearer ${token}` } }), - envelope, - }); - - expect(() => resolve!(withToken("shared"))).toThrow(/Invalid/i); - expect(await resolve!(withToken("tok-ks"))).toMatchObject({ orgId: ORG }); - }); - - it("treats one organization written twice under one token as one binding", () => { - // Not a collision: it is the same binding spelled twice, and failing it - // closed would refuse a config that names exactly one tenant. - vi.stubEnv(ADMIN_TOKENS_ENV, `${ORG}:tok-ks,${ORG}:tok-ks`); - expect(adminCredentialConfigured()).toBe(true); - }); -}); - -describe("V22 · a token may name only kitchen-sink", () => { - const envelope = { flowKind: "workforce-admin", action: "fire", input: {} }; - const withToken = (token: string) => ({ - source: "http" as const, - request: new Request("http://x", { headers: { authorization: `Bearer ${token}` } }), - envelope, - }); - - it("refuses an entry naming another organization, names it in the log, and keeps the kitchen-sink one", async () => { - const logged = vi.spyOn(console, "error").mockImplementation(() => {}); - vi.stubEnv(ADMIN_TOKENS_ENV, `${OTHER_ORG}:tok-x,${ORG}:tok-ks`); - const resolve = adminPrincipalResolver()!; - - expect(() => resolve(withToken("tok-x"))).toThrow(/Invalid/i); - expect(await resolve(withToken("tok-ks"))).toEqual({ userId: "workforce-admin", orgId: ORG }); - const log = logged.mock.calls.flat().join("\n"); - expect(log).toMatch(/names organization "elsewhere"/); - // The token itself never reaches the log. - expect(log).not.toContain("tok-x"); - }); - - it("leaves the admin flow unregistered when every entry names another organization", () => { - vi.spyOn(console, "error").mockImplementation(() => {}); - vi.stubEnv(ADMIN_TOKENS_ENV, `${OTHER_ORG}:tok-x`); - expect(adminCredentialConfigured()).toBe(false); - expect(adminPrincipalResolver()).toBeUndefined(); - }); -}); - -describe("V10 · the organization comes from the credential, never the body", () => { - it("returns kitchen-sink for its token even when the request body names another organization", async () => { - const resolve = adminPrincipalResolver()!; - const principal = await resolve({ - source: "http", - request: new Request("http://x", { headers: { authorization: "Bearer tok-ks" } }), - // The body names another organization. The stock resolver would believe - // it — that is the BP-031 hole this flow's own resolver exists to close. - envelope: { - flowKind: "workforce-admin", - action: "hire", - input: { orgId: OTHER_ORG, seatId: "support.ada", flow: "agent" }, - }, - }); - expect(principal).toEqual({ userId: "workforce-admin", orgId: ORG }); - }); -}); - -describe("V11 · a duplicate hire is refused and changes nothing", () => { - it("leaves the original row's settings and the original address intact", async () => { - const registrar = stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - const first = await callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "agent", - settings: { model: "front-model" }, - }); - expectAccepted(first); - - const second = await callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "agent", - settings: { model: "back-model" }, - }); - expectRefused(second, /already exists|support\.ada/i); - - // Not "one row still exists" — the ORIGINAL row, with the settings the - // first hire supplied. An `upsert` would leave one row too, carrying - // "back". - const row = await storedRow(stores, "support.ada"); - expect(row).toMatchObject({ flow: "agent", settings: { model: "front-model" } }); - expect(registrar.held.get(`${ORG}.~admin.support.ada`)?.config).toMatchObject({ model: "front-model" }); - }); - - it("refuses when a ROW exists although no instance holds the address", async () => { - // The case where `create()` is what does the refusing. A row can outlive - // its registration two ways: a sibling process hired the seat (its row is - // shared, its registration is not), and a compensating delete that itself - // failed. Either way the row is the roster, so the hire must refuse — and - // must not overwrite what is there. - // - // Red state: write with `upsert()` instead of `create()`. The second hire - // succeeds and the stored settings become "back". This is the copy-paste - // from the seat inventory next door, and it is the one that loses the - // refusal with no other symptom. - const registrar = stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - await callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "agent", - settings: { model: "front-model" }, - }); - // The address is released; the row is left exactly where it was. - registrar.held.delete(`${ORG}.~admin.support.ada`); - expect(await storedRow(stores, "support.ada")).toBeDefined(); - - const second = await callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "agent", - settings: { model: "back-model" }, - }); - - expectRefused(second, /already exists|support\.ada/i); - expect(await storedRow(stores, "support.ada")).toMatchObject({ - settings: { model: "front-model" }, - }); - }); - - it("hires the kind the ROW names, not one hidden in the settings bag", async () => { - // `settings` is a passthrough bag, so `settings.flow` is storable, and - // `settingsOf` strips `flow` as reserved before the kind validates — - // nothing downstream objects. With `hiredSeatManifest` spreading - // `{ flow: row.flow, ...row.settings }`, this hire would mint the kind the - // bag names while the stored row says `agent` forever. - // - // This app carries one kind, so the bag names one it does not carry: with - // the spread restored, the hire is refused for a kind the row never named - // and nothing is registered, where the row's own kind should have been - // hired. On an app with a second kind the same defect registers that kind - // under the row, and `fire` then strands it. - // - // Red state: restore that spread order in - // `packages/workforce/src/roster/rows.ts` and the hire is refused. - const registrar = stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - // Only the shadow key, deliberately: adding a setting of its own would - // make the row's kind refuse the bag for a reason that is not the defect. - const hired = await callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "agent", - settings: { flow: "desk-clerk" }, - }); - expectAccepted(hired); - - expect(registrar.held.get(`${ORG}.~admin.support.ada`)?.kind).toBe("agent"); - expect(await storedRow(stores, "support.ada")).toMatchObject({ flow: "agent" }); - - // The stored kind and the live kind agree, so the mismatch branch in - // `fire` is unreachable for this row: the seat is released and nothing is - // stranded. - const fired = await callAdmin(flow, stores, "fire", { seatId: "support.ada" }); - expectAccepted(fired); - expect(fired.output).toMatchObject({ released: true }); - expect(registrar.held.has(`${ORG}.~admin.support.ada`)).toBe(false); - expect(await storedRow(stores, "support.ada")).toBeUndefined(); - }); - - it("refuses a kind this app does not carry before anything is written", async () => { - stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - const result = await callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "a-kind-that-is-not-here", - settings: {}, - }); - expectRefused(result, /a-kind-that-is-not-here/); - expect(await storedRow(stores, "support.ada")).toBeUndefined(); - }); - - it("refuses a setting the kind's schema does not admit, leaving no row", async () => { - stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - const result = await callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "agent", - settings: { aSettingTheKindDoesNotHave: true }, - }); - expectRefused(result, /aSettingTheKindDoesNotHave/); - // The mint runs the kind's schema BEFORE the row is written, which is what - // "no row, no registration" requires. - expect(await storedRow(stores, "support.ada")).toBeUndefined(); - }); - - it("keeps a dotted organization's seat off the address another organization's seat answers on", async () => { - const registrar = stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - // Raw, `kitchen-sink.support` + `ada` would spell `kitchen-sink.support.ada`, - // the address `kitchen-sink` + `support.ada` answers on, and the second hire - // would rebind the first. The org is escaped into the address, so both land, - // apart, and each splits back to its own seat id. - const dottedOrg = `${ORG}.support`; - const dotted = await callAdmin(flow, stores, "hire", { seatId: "ada", flow: "agent", settings: {} }, dottedOrg); - const plain = await callAdmin(flow, stores, "hire", { seatId: "support.ada", flow: "agent", settings: {} }); - expect(dotted.error).toBeUndefined(); - expect(plain.error).toBeUndefined(); - - // This flow's hires are owned by the caller, `admin`. - const dottedAddress = seatAddress(dottedOrg, "ada", "admin"); - const plainAddress = seatAddress(ORG, "support.ada", "admin"); - expect(dottedAddress).not.toBe(plainAddress); - expect([...registrar.held.keys()].sort()).toEqual([dottedAddress, plainAddress].sort()); - expect(splitSeatAddress(dottedOrg, dottedAddress)).toBe("ada"); - expect(splitSeatAddress(ORG, dottedAddress)).toBeUndefined(); - expect(await storedRow(stores, "ada", dottedOrg)).toBeDefined(); - }); -}); - -describe("V12 · two hires of one seat arriving together", () => { - it("resolves exactly one, refuses the other, and leaves one row", async () => { - const registrar = stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - const [a, b] = await Promise.all([ - callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "agent", - settings: { model: "front-model" }, - }), - callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "agent", - settings: { model: "back-model" }, - }), - ]); - - const accepted = [a, b].filter((r) => r.error === undefined); - const refused = [a, b].filter((r) => r.error !== undefined); - expect(accepted).toHaveLength(1); - expect(refused).toHaveLength(1); - - const rows = await stores.resourceState.getByPrefix("org", ORG, "workforce/roster/"); - expect(Object.keys(rows)).toEqual(["workforce/roster/~admin/support.ada"]); - expect(registrar.held.size).toBe(1); - }); -}); - -describe("V13 · a registration that fails leaves nothing behind", () => { - it("deletes the row it just wrote and reports the registration failure", async () => { - stubRegistrar({ refuse: true }); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - const result = await callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "agent", - settings: { model: "front-model" }, - }); - - expectRefused(result, /refused this seat/); - // Without the compensating delete the row survives, the caller is told the - // hire failed, and the seat turns up at the next boot — a failed hire - // leaving a live seat behind. - expect(await storedRow(stores, "support.ada")).toBeUndefined(); - }); -}); - -describe("an admin hire's incarnation", () => { - it("is fresh on every hire, so a fire leaves a replacement's inventory row alone", async () => { - stubRegistrar(); - const flow = adminFlow(); - const address = `${ORG}.~admin.support.ada`; - // The replacement: a second admin hire of the same seat, as it would be - // written after this fire released the address. Its row's incarnation is - // what a boot would publish on its inventory row. - const elsewhere = createInMemoryStores(); - expectAccepted(await callAdmin(flow, elsewhere, "hire", { seatId: "support.ada", flow: "agent", settings: { model: "front-model" } })); - const replacement = (await storedRow(elsewhere, "support.ada"))!.incarnation as string; - - stubRegistrar(); - const stores = createInMemoryStores(); - expectAccepted(await callAdmin(flow, stores, "hire", { seatId: "support.ada", flow: "agent", settings: { model: "front-model" } })); - const own = (await storedRow(stores, "support.ada"))!.incarnation; - expect(typeof own).toBe("string"); - expect(own).not.toBe(replacement); - - // The replacement's boot published its inventory row before this fire's delete reached it. - const row = { id: address, kind: "agent", door: "run", hired: true, incarnation: replacement }; - await stores.resourceState.set("org", ORG, `inventory/seats/${address}`, row, "any"); - expectAccepted(await callAdmin(flow, stores, "fire", { seatId: "support.ada" })); - - expect((await stores.resourceState.get("org", ORG, `inventory/seats/${address}`))?.state).toMatchObject({ incarnation: replacement }); - }); -}); - -describe("fire", () => { - it("removes the row and the address, and the removal survives a re-read", async () => { - const registrar = stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - await callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "agent", - settings: { model: "front-model" }, - }); - const fired = await callAdmin(flow, stores, "fire", { seatId: "support.ada" }); - - expectAccepted(fired); - expect(fired.output).toMatchObject({ address: `${ORG}.~admin.support.ada`, released: true }); - expect(registrar.held.has(`${ORG}.~admin.support.ada`)).toBe(false); - expect(await storedRow(stores, "support.ada")).toBeUndefined(); - }); - - it("FIX-1621 BR-13 · a user-owned fire goes through Workforce's one removal: an inventory row at its address goes too", async () => { - const registrar = stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - const address = `${ORG}.~admin.support.ada`; - - await callAdmin(flow, stores, "hire", { seatId: "support.ada", flow: "agent", settings: { model: "front-model" } }); - // This app's hire writes no inventory row; one is seeded, as a boot - // publishes it (the hire's own incarnation), so the shared removal has - // something to prove it reached. - const incarnation = (await storedRow(stores, "support.ada"))!.incarnation as string; - await stores.resourceState.set("org", ORG, `inventory/seats/${address}`, { id: address, kind: "agent", door: "run", hired: true, incarnation }, "any"); - await stores.resourceState.set("org", ORG, `inventory/seats/${ORG}.support.bob`, { id: `${ORG}.support.bob`, kind: "agent", door: "run" }, "any"); - - const fired = await callAdmin(flow, stores, "fire", { seatId: "support.ada" }); - expectAccepted(fired); - expect(registrar.held.has(address)).toBe(false); - const seats = Object.keys(await stores.resourceState.getByPrefix("org", ORG, "inventory/seats/")); - expect(seats).toEqual([`inventory/seats/${ORG}.support.bob`]); - }); - - it("a fire that died after removing the caller's own row: the retry removes that seat's leftover inventory row and leaves an org seat sharing the id", async () => { - const registrar = stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - const address = `${ORG}.~admin.support.ada`; - await callAdmin(flow, stores, "hire", { seatId: "support.ada", flow: "agent", settings: { model: "front-model" } }); - // What a boot publishes for the seat, then what the dead fire left: its - // own roster row and its address gone, the inventory row not. - await stores.resourceState.set("org", ORG, `inventory/seats/${address}`, { id: address, kind: "agent", door: "run", hired: true, incarnation: null }, "any"); - const ownKey = Object.keys(await stores.resourceState.getByPrefix("org", ORG, "workforce/roster/")).find((key) => key.includes("~admin"))!; - const own = await stores.resourceState.get("org", ORG, ownKey); - await stores.resourceState.delete("org", ORG, ownKey, own!.version); - registrar.held.delete(address); - // An org seat under the same id, from when this app's hire wrote the flat key. - const legacy = { seatId: "support.ada", flow: "agent", settings: { model: "front-model" }, instructions: null }; - await stores.resourceState.set("org", ORG, "workforce/roster/support.ada", legacy, "any"); - - const retried = await callAdmin(flow, stores, "fire", { seatId: "support.ada" }); - expectAccepted(retried); - expect(retried.output).toMatchObject({ address, released: false }); - expect(Object.keys(await stores.resourceState.getByPrefix("org", ORG, "inventory/seats/"))).toEqual([]); - expect(Object.keys(await stores.resourceState.getByPrefix("org", ORG, "workforce/roster/"))).toEqual(["workforce/roster/support.ada"]); - }); - - it("a legacy org row and the caller's own row under one seat id: no owner is refused, and owner picks the row", async () => { - const registrar = stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - await callAdmin(flow, stores, "hire", { seatId: "support.ada", flow: "agent", settings: { model: "front-model" } }); - // A row from when this app's hire wrote the flat, org-visible key. - const legacy = { seatId: "support.ada", flow: "agent", settings: { model: "front-model" }, instructions: null }; - await stores.resourceState.set("org", ORG, "workforce/roster/support.ada", legacy, "any"); - const keys = async () => Object.keys(await stores.resourceState.getByPrefix("org", ORG, "workforce/roster/")).sort(); - const both = await keys(); - expect(both).toHaveLength(2); - - const refused = await callAdmin(flow, stores, "fire", { seatId: "support.ada" }); - expectRefused(refused, /"support\.ada" names two seats: the organization's and yours/); - expect(await keys()).toEqual(both); - - const fired = await callAdmin(flow, stores, "fire", { seatId: "support.ada", owner: "organization" }); - expectAccepted(fired); - expect(fired.output).toMatchObject({ address: `${ORG}.support.ada` }); - expect(await keys()).toEqual(both.filter((key) => key !== "workforce/roster/support.ada")); - expect(registrar.held.has(`${ORG}.~admin.support.ada`)).toBe(true); - }); - - it("refuses a seat this organization does not hold", async () => { - stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - const result = await callAdmin(flow, stores, "fire", { seatId: "support.nobody" }); - expectRefused(result, /hired no seat/); - }); - - it("refuses to fire another organization's seat, even by exact id", async () => { - // No token can name another organization any more, but a store written - // before that rule can hold one's rows. The lookup is still org-scoped. - stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - await callAdmin( - flow, stores, "hire", - { seatId: "support.ada", flow: "agent", settings: { model: "front-model" } }, - OTHER_ORG - ); - // Same seat id, different credential. The lookup is org-scoped. - const result = await callAdmin(flow, stores, "fire", { seatId: "support.ada" }, ORG); - expectRefused(result, /hired no seat/); - expect(await storedRow(stores, "support.ada", OTHER_ORG)).toBeDefined(); - }); - - it("V15b · leaves a FILE-DECLARED seat of the row's OWN kind alone (BR-28)", async () => { - // BR-28 is written in terms of provenance: "the address … is held by an - // instance that did NOT come from this org's row → nothing is - // unregistered". V15 above checks a foreign instance of a DIFFERENT kind, - // which a kind-equality check also catches — which is exactly why this - // gap survived. Here the kinds MATCH, so only real provenance can tell - // them apart. - // - // Reachable, not theoretical: hire a seat; later add a - // `workforce/teams/` folder declaring one at the same address with the - // same kind; restart. The file seat registers first, the reload's - // duplicate is skipped and named (BR-21), and the row survives. That is - // the state set up below. - // - // Red state: gate `fire` on `liveKind !== storedKind` again and this - // fails — the file-declared seat is unregistered, contradicting the - // refusal `fire` itself raises three lines earlier, which promises such a - // seat is removed by editing its folder. - const registrar = stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - await callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "agent", - settings: { model: "front-model" }, - }); - - // The restart: the address is released and re-taken by a seat this app did - // NOT register from the row — same address, same kind. - workforceRegistrar.unregister(`${ORG}.~admin.support.ada`); - registrar.held.set(`${ORG}.~admin.support.ada`, { - id: `${ORG}.~admin.support.ada`, - kind: "agent", - } as unknown as FlowInstance); - - const fired = await callAdmin(flow, stores, "fire", { seatId: "support.ada" }); - - expectAccepted(fired); - expect(fired.output).toMatchObject({ released: false }); - // The row goes — this org did hire it. The file-declared seat stays. - expect(await storedRow(stores, "support.ada")).toBeUndefined(); - expect(registrar.held.has(`${ORG}.~admin.support.ada`)).toBe(true); - }); - - it("V15 · leaves an address alone when a foreign instance holds it", async () => { - const registrar = stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - - await callAdmin(flow, stores, "hire", { - seatId: "support.ada", - flow: "agent", - settings: { model: "front-model" }, - }); - - // Something else takes the address between the hire and the fire. The - // address grammar is supposed to make this unreachable; the check is here - // because a guarantee nobody checks is how this goes wrong. - registrar.held.set(`${ORG}.~admin.support.ada`, { - id: `${ORG}.~admin.support.ada`, - kind: "some-other-kind", - } as unknown as FlowInstance); - - const fired = await callAdmin(flow, stores, "fire", { seatId: "support.ada" }); - - expectAccepted(fired); - expect(fired.output).toMatchObject({ released: false }); - // The row goes; the foreign instance stays. Unregistering by address alone - // would take it offline. - expect(await storedRow(stores, "support.ada")).toBeUndefined(); - expect(registrar.held.get(`${ORG}.~admin.support.ada`)?.kind).toBe("some-other-kind"); - }); -}); - -describe("user-owned addresses", () => { - it("lets alice and bob both hire research, on different addresses, without naming a kind", async () => { - const registrar = stubRegistrar(); - const flow = adminFlow(); - const stores = createInMemoryStores(); - const hired = async (userId: string) => - callAdmin( - flow, - stores, - "hire", - { seatId: "research", flow: "agent", instructions: `${userId}-PRIVATE` }, - ORG, - userId, - ); - - const alice = await hired("alice"); - const bob = await hired("bob"); - expectAccepted(alice); - expectAccepted(bob); - expect(alice.output).toMatchObject({ address: `${ORG}.~alice.research` }); - expect(bob.output).toMatchObject({ address: `${ORG}.~bob.research` }); - expect(registrar.held.has(`${ORG}.~alice.research`)).toBe(true); - expect(registrar.held.has(`${ORG}.~bob.research`)).toBe(true); - }); -}); - -describe("roster registration", () => { - it("refuses a hired seat that arrives with no pin, and does not mark it", () => { - const registrar = stubRegistrar(); - const seat = { id: `${ORG}.research`, kind: "agent" } as FlowInstance; - expect(() => workforceRegistrar.registerFromRoster(seat)).toThrow(/owner pin/); - expect(registrar.held.has(seat.id)).toBe(false); - expect(workforceRegistrar.isFromRoster(seat.id)).toBe(false); - }); - - it("admits a hired seat whose row already stamped a pin", () => { - const seen: Array<{ orgId: string; userId?: string } | undefined> = []; - setWorkforceRegistrarImpl({ - register: (_flow, options) => { - seen.push(options?.pin); - }, - unregister: () => false, - kindAt: () => undefined, - }); - const seat = { - id: `${ORG}.x`, - kind: "agent", - ownerPin: { orgId: ORG, userId: "alice" }, - } as FlowInstance; - workforceRegistrar.registerFromRoster(seat); - expect(seen).toEqual([{ orgId: ORG, userId: "alice" }]); - expect(workforceRegistrar.isFromRoster(`${ORG}.x`)).toBe(true); - }); -}); diff --git a/apps/kitchen-sink/test/workforce-packages.test.ts b/apps/kitchen-sink/test/workforce-packages.test.ts index 121f7e2a50..3f021d2714 100644 --- a/apps/kitchen-sink/test/workforce-packages.test.ts +++ b/apps/kitchen-sink/test/workforce-packages.test.ts @@ -27,14 +27,14 @@ vi.mock("@flow-state-dev/workforce", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, - hireWorkforce: (...args: Parameters) => { - hired.options.push(args[1]); - return actual.hireWorkforce(...args); + createWorkerInstallation: (...args: Parameters) => { + hired.options.push(args[0]); + return actual.createWorkerInstallation(...args); }, }; }); -const { hireKitchenSinkWorkforce } = await import("../workforce/hire"); +const { buildKitchenSinkWorkforce } = await import("../workforce/hire"); const { packageBlocks } = await import("../workforce/workforce.gen"); afterEach(() => { @@ -43,8 +43,8 @@ afterEach(() => { }); describe("the kitchen-sink hire and packages", () => { - it("passes the generated packageBlocks to the hire", async () => { - await hireKitchenSinkWorkforce(); + it("passes the generated packageBlocks to the installation", async () => { + await buildKitchenSinkWorkforce(); expect(hired.options.length).toBeGreaterThan(0); expect((hired.options[0] as { packageBlocks?: unknown }).packageBlocks).toBe(packageBlocks); }); @@ -52,7 +52,7 @@ describe("the kitchen-sink hire and packages", () => { it("does not start when the loader refused a package, naming its folder", async () => { const at = "teams/support/workers/iris/packages/refunds"; loader.packageErrors = [{ path: at, error: new Error("no PACKAGE.md"), kind: "package-load-failed" }]; - await expect(hireKitchenSinkWorkforce()).rejects.toThrow(at); + await expect(buildKitchenSinkWorkforce()).rejects.toThrow(at); expect(hired.options).toEqual([]); }); }); diff --git a/apps/kitchen-sink/test/workforce-shell.test.ts b/apps/kitchen-sink/test/workforce-shell.test.ts index 96d74911ea..6751a846a6 100644 --- a/apps/kitchen-sink/test/workforce-shell.test.ts +++ b/apps/kitchen-sink/test/workforce-shell.test.ts @@ -1,11 +1,11 @@ /** * The names the shell writes down, held to the tree they describe. * - * The rail's kind lists, the seats' descriptions and the panel's board ids are - * literals in `lib/workforce-shell.ts`, because a browser cannot read - * `workforce/`. That makes them a second copy, and a copy drifts: add a worker - * kind, reword a `description:`, or add a board to a `MAILBOX.md`, and the - * rail or the panel silently shows the old one. These cases fail on that drift. + * The rail's kind lists and the panel's board ids are literals in + * `lib/workforce-shell.ts`, because a browser cannot read `workforce/`. That + * makes them a second copy, and a copy drifts: add a worker flow or a board to + * a `MAILBOX.md`, and the rail or the panel silently shows the old one. These + * cases fail on that drift. * * Red states produced before these were trusted: * - add a kind to the tree and not to `SEAT_KINDS`: the seat-kind case fails. @@ -13,29 +13,21 @@ * naming the kind with no entry. * - misname `agent`'s field `message`: the answering-action case fails, * naming the field the kind actually takes. - * - reword one `description:` in a `WORKER.md`, or drop one entry from - * `SEAT_DESCRIPTIONS`: the description case fails, naming the seat. * - drop the board from `SHELL_BOARDS`: the board case fails. - * - remove `workforcePanelResources` from the chat-agent flow: the - * declaration case fails, which is the state in which every panel read - * answers "unknown resource". * - drop the board from `support.help`'s `MAILBOX.md`: the board case and * the mailbox flow's declaration case both fail. */ import { describe, expect, it } from "vitest"; import { z, type ZodTypeAny } from "zod"; -import { MAILBOX_KIND, mailboxBoard, mailboxBoardIds, HIRED_ROSTER_RESOURCE } from "@flow-state-dev/workforce"; +import { MAILBOX_KIND, mailboxBoard, mailboxBoardIds } from "@flow-state-dev/workforce"; import { readMailboxesDirectory, readWorkforce } from "@flow-state-dev/workforce/loader"; -import chatAgentFlow from "../flows/chat-agent/flow"; -import { hireKitchenSinkWorkforce, kitchenSinkKinds, workforceRoot } from "../workforce/hire"; +import { buildKitchenSinkWorkforce, workforceRoot } from "../workforce/hire"; import { mailboxKinds } from "../workforce/workforce.gen"; import { MAILBOX_KINDS, defaultConversation, - ROSTER_BOOT_REPORT_REF, SEAT_ASKS, - SEAT_DESCRIPTIONS, SEAT_KINDS, SHELL_BOARDS, SHELL_MAILBOXES, @@ -43,19 +35,9 @@ import { } from "../lib/workforce-shell"; describe("the shell's names match the workforce tree", () => { - it("lists every seat kind the app can hire into", () => { - expect([...SEAT_KINDS].sort()).toEqual(Object.keys(kitchenSinkKinds).sort()); - }); - - it("carries every declared seat's description as its WORKER.md has it, and no other seat's", async () => { - const { workers, errors } = await readWorkforce(workforceRoot); - expect(errors).toEqual([]); - const declared = Object.fromEntries( - workers.map((worker) => [worker.id, (worker.declared as { description?: string }).description]), - ); - // Not vacuous: the tree does declare seats. - expect(Object.keys(declared).length).toBeGreaterThan(0); - expect(SEAT_DESCRIPTIONS).toEqual(declared); + it("lists every worker flow the app runs workers on", async () => { + const { installation } = await buildKitchenSinkWorkforce(); + expect([...SEAT_KINDS].sort()).toEqual(Object.keys(installation.workerFlows()).sort()); }); it("lists every mailbox kind: the framework's own, plus the tree's", () => { @@ -94,8 +76,9 @@ describe("the shell's names match the workforce tree", () => { * input is exactly one required string field. Keyed by action, valued by that * field's name. */ -function oneStringActions(kind: string): Record { - const factory = (kitchenSinkKinds as Record)[kind] as { +async function oneStringActions(kind: string): Promise> { + const { installation } = await buildKitchenSinkWorkforce(); + const factory = installation.workerFlows()[kind]!.flow as unknown as { actions: Record; }; const found: Record = {}; @@ -113,10 +96,10 @@ describe("each seat kind's composer sends to an action the kind declares", () => expect(Object.keys(SEAT_ASKS).sort()).toEqual([...SEAT_KINDS].sort()); }); - it.each([...SEAT_KINDS])("%s: the named action takes exactly the named one string field, or it has none", (kind) => { + it.each([...SEAT_KINDS])("%s: the named action takes exactly the named one string field, or it has none", async (kind) => { const ask = seatAskFor(kind); if (ask === undefined) throw new Error(`SEAT_ASKS has no entry for "${kind}"`); - const actions = oneStringActions(kind); + const actions = await oneStringActions(kind); if ("none" in ask) { // "None" is only honest where there is truly nothing to answer through. expect(actions, `"${kind}" is written down as taking no messages`).toEqual({}); @@ -134,25 +117,13 @@ function expectBrowserReadable(resources: Record, ref: string, expect(declared!.client?.state?.read).toBe(true); } -describe("the shell's flow declares what the panel reads", () => { - const resources = (chatAgentFlow as unknown as { resources?: Record }) - .resources ?? {}; - - const cases: [label: string, ref: string][] = [ - ["the roster", HIRED_ROSTER_RESOURCE], - ["the boot report", ROSTER_BOOT_REPORT_REF], - ]; - - it.each(cases)("%s, readable by a browser", (_label, ref) => { - expectBrowserReadable(resources, ref, "chat-agent"); - }); - +describe("each board the panel reads is declared where it reads it", () => { // Each board is read through its mailbox's session, so it is the flow that // session runs on, the one the mailbox's file selects, that must declare it. it.each(SHELL_BOARDS.map((board) => [board.ref, board] as const))( "board %s, readable by a browser through its mailbox's session", async (_ref, board) => { - const { mailboxFlows } = await hireKitchenSinkWorkforce(); + const { mailboxFlows } = await buildKitchenSinkWorkforce(); const mailbox = SHELL_MAILBOXES.find(({ id }) => id === board.mailboxId); expect(mailbox, `SHELL_MAILBOXES has no mailbox "${board.mailboxId}"`).toBeDefined(); const flow = mailboxFlows.find(({ kind }) => kind === mailbox!.kind); @@ -166,7 +137,7 @@ describe("the shell's flow declares what the panel reads", () => { ); it("uses refs the collection route can address: one path segment each", () => { - for (const ref of [HIRED_ROSTER_RESOURCE, ROSTER_BOOT_REPORT_REF, ...SHELL_BOARDS.map((b) => b.ref)]) { + for (const ref of SHELL_BOARDS.map((b) => b.ref)) { expect(ref).not.toContain("/"); } }); diff --git a/apps/kitchen-sink/workforce/blocks/escalate.ts b/apps/kitchen-sink/workforce/blocks/escalate.ts index d0b4e7092e..508d3b1cad 100644 --- a/apps/kitchen-sink/workforce/blocks/escalate.ts +++ b/apps/kitchen-sink/workforce/blocks/escalate.ts @@ -8,19 +8,20 @@ * `tools:`, as each specialist's `WORKER.md` does. * * The model writes only the case. The mailbox and the board are named here, - * and the author is the seat's own `seatId`, which the hire writes into every - * seat's settings, so no model can file as another seat or onto another board. + * and the author is the worker the turn loaded, which the server checked when + * the conversation was created, so no model can file as another worker or + * onto another board. * * The dispatch is fire-and-forget: the row is written when the mailbox runs * `fileTask`, a moment after the tool returns, so the tool never sees the * mailbox's answer. The one refusal it could predict, it checks first: the - * mailbox files only its members' cases, so a seat that is not one (an - * operator can hire any seat with this tool) gets `filed: false` and sends + * mailbox files only its members' cases, so a worker that is not one (a user + * can hire a worker of their own with this tool) gets `filed: false` and sends * nothing, rather than a `filed: true` the mailbox would then refuse. Nothing * drains `escalations` in this app, and the boot says so. */ import { DispatchRefusedError, dispatcher, handler, sequencer, type BlockContext } from "@flow-state-dev/core"; -import { MAILBOX_KIND } from "@flow-state-dev/workforce"; +import { MAILBOX_KIND, verifiedWorkerOf } from "@flow-state-dev/workforce"; import { z } from "zod"; /** The mailbox a case is filed in. */ @@ -96,12 +97,14 @@ const fileIntoMailbox = dispatcher({ payload: (input, ctx: BlockContext) => ({ board: ESCALATION_BOARD, goal: input.case, - author: (ctx.flow.config as { seatId?: string }).seatId, + author: seatIdOf(ctx), }), }); -/** The calling seat's id, which the hire writes into every seat's settings. */ -const seatIdOf = (ctx: BlockContext): string | undefined => (ctx.flow.config as { seatId?: string }).seatId; +/** The calling worker's id: the one this turn loaded and checked. */ +function seatIdOf(ctx: BlockContext): string | undefined { + return verifiedWorkerOf(ctx.session as object); +} /** Whether the calling seat is one the mailbox files for. */ const isMember = (ctx: BlockContext): boolean => ESCALATION_MEMBERS.includes(seatIdOf(ctx) ?? ""); diff --git a/apps/kitchen-sink/workforce/hire.ts b/apps/kitchen-sink/workforce/hire.ts index 41854022b4..35fe28d6e3 100644 --- a/apps/kitchen-sink/workforce/hire.ts +++ b/apps/kitchen-sink/workforce/hire.ts @@ -1,36 +1,40 @@ /** * Kitchen-sink's workforce, assembled from its own files. * - * The point of this module is what it does *not* contain: no seat is named + * The point of this module is what it does *not* contain: no worker is named * here, and no block is. `blocks` comes from `workforce.gen.ts`, which - * `fsdev gen` writes from the tree beside this file, and the roster comes from + * `fsdev gen` writes from the tree beside this file, and the workers come from * the `teams/` folders: one mailbox, `support.help`, and four specialists on - * the built-in `agent` kind. Adding a tool means adding a file and re-running + * the built-in `agent` flow. Adding a tool means adding a file and re-running * the command — there is no second place to edit. * + * The specialists are standard workers: every user has them, and they run on + * one registered copy of `agent`. A user's own workers, hired or forked + * through the roster flow, run on that same copy. + * * This subtree is the whole of the app's Layer 2 usage. Nothing in `app/` - * reaches into it. Two edges lead in: `fsdev.config.ts`, which awaits the hire - * below and spreads the seats into the map it serves, and the - * `workforce-admin` flow, which hires against `kitchenSinkKinds`. That first - * edge is what makes the demonstration real — until it existed the bundler - * never resolved `workforce.gen.ts`'s imports, so the claim this tree exists - * to prove (a generated module of static imports survives a production build) - * was asserted and untested (FIX-1429). + * reaches into it. One edge leads in: `fsdev.config.ts`, which awaits the + * build below and spreads the copies into the map it serves. That edge is what + * makes the demonstration real — until it existed the bundler never resolved + * `workforce.gen.ts`'s imports, so the claim this tree exists to prove (a + * generated module of static imports survives a production build) was asserted + * and untested (FIX-1429). * * The mailbox is routed: each post from a person reaches the one specialist * whose `description:` fits it (`routeByPurpose`, on `ROUTE_MODEL`), and that * specialist's answer lands in the mailbox under its name. */ import { - mailboxBoardIds, - mailboxInstances, - mailboxPostCapability, + createWorkerInstallation, defineAgentWorkerFlow, defineMailboxFlow, hireWorkforce, + mailboxBoardIds, + mailboxInstances, routeByPurpose, + workerMailboxPostCapability, type MailboxManifest, - type HireOptions, + type WorkerInstallation, } from "@flow-state-dev/workforce"; import { readMailboxesDirectory, readWorkforce } from "@flow-state-dev/workforce/loader"; import type { FlowInstance } from "@flow-state-dev/core/types"; @@ -47,11 +51,11 @@ import { blocks, mailboxKinds, kinds, packageBlocks, seatBlocks } from "./workfo /** * `post-to-mailbox`, so a specialist can answer in a mailbox it belongs to, - * under its own name. Offered, not granted: only a seat whose file names the + * under its own name. Offered, not granted: only a worker whose file names the * tool can post, and every specialist's does. The goal check's * `post-without-author` control swaps in a stand-in, in test mode only. */ -const mailboxPost = mailboxPostControl() ?? mailboxPostCapability; +const mailboxPost = mailboxPostControl() ?? workerMailboxPostCapability; /** * The tool catalog: the scanned `workforce/blocks/` map, which holds @@ -60,38 +64,18 @@ const mailboxPost = mailboxPostControl() ?? mailboxPostCapability; */ const catalog = escalateControl(blocks) ?? blocks; -/** - * The kinds a seat may be hired into — generated, plus the built-in `agent` - * carrying the post tool and the tool catalog. - * - * Exported because a runtime hire and the boot reload must hire against the - * SAME map the file-declared roster does. Calling `defineAgentWorkerFlow` a - * second time elsewhere would build a *different* kind under the same name, so - * a seat hired over `workforce-admin` would carry a different tool catalog from - * its file-declared neighbours for no reason anyone stated. - * - * `catalog` is the whole of the custom-tool recipe on the app's side: the - * scanned map IS a tool catalog, so a seat naming one of its keys in `tools:` - * can call it. The app decides what the catalog holds; each seat decides which - * of it to use, and a key nobody names reaches nobody. - * - * The goal check's `no-landing` control swaps the kind for one that answers - * with the same tools and lands no text answer, in test mode only. - */ -export const kitchenSinkKinds: NonNullable = { - ...kinds, - agent: mailboxLandingControl(catalog, mailboxPost) ?? defineAgentWorkerFlow({ uses: [mailboxPost], catalog }), -}; - /** This directory — the workforce root, read at run time the way Markdown always is. */ export const workforceRoot = dirname(fileURLToPath(import.meta.url)); -/** One hired seat, the mailboxes the tree declared, plus what the loader could not read. */ -export interface HiredWorkforce { - seats: FlowInstance[]; +/** The installation, the copies it registers, the mailboxes the tree declared, and what the loader could not read. */ +export interface KitchenSinkWorkforce { + /** The worker model: the standard workers, and the checks every session of a worker flow meets. */ + installation: WorkerInstallation; + /** One copy per worker flow, and the roster flow. Register these. */ + copies: FlowInstance[]; /** - * One instance per DISTINCT mailbox kind the roster selected — never one per - * mailbox. Register these beside the seats; a mailbox is a named session on + * One instance per DISTINCT mailbox kind the tree selected — never one per + * mailbox. Register these beside the copies; a mailbox is a named session on * the instance its `MAILBOX.md` selected. */ mailboxFlows: FlowInstance[]; @@ -104,42 +88,26 @@ export interface HiredWorkforce { mailboxes: MailboxManifest[]; /** * Everything the loader could not read, by path — from **all three** of its - * error channels, not just the worker one. - * - * The three are separate on the loader's result because they are different - * severities: a worker slot that failed is a seat this app does not have, a - * skill that failed is a seat running short, and a `TEAM.md` that failed is a - * whole team's seats running without instructions their author wrote. They - * are flattened here because this app's answer to all three is the same — - * say so — and because a mailbox a caller forgets to destructure is a - * failure that reports nowhere, which is the one outcome collecting rather - * than throwing is supposed to make impossible. - * - * **A mailbox that failed to load is NOT here.** It throws above instead, for - * the reason the published mailboxes guide gives: a seat short is a roster - * running light, but a mailbox short is a team with nowhere to talk, and the - * seats that did load go on posting into the mailboxes that did open as though - * nothing were missing. Degrading is the right answer for a seat and the - * wrong one for a mailbox. + * error channels, not just the worker one. A worker folder that failed is a + * worker this app does not have, a skill that failed is a worker running + * short, and a `TEAM.md` that failed is a whole team running without the + * instructions its author wrote. This app's answer to all three is the same: + * say so. * - * **A package that failed to load is NOT here either.** It throws above, for - * the rule packages ship with: every package problem is a start-time - * refusal. A worker short a package is a worker without the instructions and - * tools its author gave it, running as though it had them. + * **A mailbox or a package that failed to load is NOT here.** Each throws + * instead: a mailbox short is a team with nowhere to talk, and a worker short + * a package runs without the instructions and tools its author gave it. */ errors: string[]; } /** - * Read the team's files and hire every seat they describe. + * Read the team's files and build the workforce they describe. * - * The `kinds` map is generated, not written: a seat's `flow:` names a kind that - * is on it because a file with that basename exists, and for no other reason. - * - * @returns The hired seats, ordered by id, and any folder the loader reported. - * @throws If any record cannot be hired; the message names every bad worker. + * @returns The installation, its copies and mailbox flows, and any folder the loader reported. + * @throws If a mailbox or a package fails to load, or a worker flow is refused. */ -export async function hireKitchenSinkWorkforce(): Promise { +export async function buildKitchenSinkWorkforce(): Promise { const { workers, errors, skillErrors, teamErrors, packageErrors } = await readWorkforce(workforceRoot); const read = await readMailboxesDirectory(workforceRoot); const mailboxErrors = read.errors; @@ -147,22 +115,12 @@ export async function hireKitchenSinkWorkforce(): Promise { // before anything is bound, in test mode only. const mailboxes = withMailboxRouteControl(read.mailboxes); - // FATAL, unlike the worker-side errors below, and the published guide is why: - // "a reported folder is a mailbox your app was supposed to have. Log a warning - // and carry on, and the app boots with a team that has nowhere to talk." - // A seat that fails to load is one seat short; a mailbox that fails to load is - // a place the team cannot talk, and the rest of the roster keeps posting into - // the ones that did open as though nothing were missing. if (mailboxErrors.length > 0) { throw new Error( `mailboxes: ${mailboxErrors.length} mailbox(es) failed to load\n` + mailboxErrors.map(({ path, error }) => ` ${path}: ${error.message}`).join("\n"), ); } - - // FATAL too. A refused package is left off every record that would have held - // it, and one with no blocks leaves the hire nothing to notice — so the only - // place its failure shows is here, and it has to stop start. if (packageErrors.length > 0) { throw new Error( `packages: ${packageErrors.length} package problem(s)\n` + @@ -171,43 +129,45 @@ export async function hireKitchenSinkWorkforce(): Promise { } // `seatBlocks` registers what each worker's own folder holds, for that - // worker alone. It grants nothing: a seat still names the block in its - // `tools:` before the model can call it. - // - // `packageBlocks` carries every package's blocks by folder; the hire gives - // each worker the ones of the packages it holds, and nothing else. - // - // `mailboxBoards` is what lets the hire say which declared board no seat - // drains. Without it the check has no roster to read and says nothing — - // which is the silence this app ships to make visible. - // - // Hired before the mailboxes are built, because the fan-out block wakes these - // seats: its addresses are the seats hired here, never a mailbox's stored - // members. - const seats = hireWorkforce(workers, { - workerFlows: kitchenSinkKinds, + // worker alone. It grants nothing: a worker still names the block in its + // `tools:` before the model can call it. `packageBlocks` carries every + // package's blocks by folder; a worker gets the ones of the packages it holds. + let flows: Record = {}; + const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: () => flows as never, seatBlocks, packageBlocks, - mailboxBoards: mailboxBoardIds(mailboxes), }); + // The generated flows, plus the built-in `agent` carrying the post tool and + // the tool catalog. The goal check's `no-landing` control swaps it for one + // that answers with the same tools and lands no text answer, in test mode only. + flows = { + ...kinds, + agent: + mailboxLandingControl(catalog, mailboxPost, installation) ?? + defineAgentWorkerFlow({ installation, uses: [mailboxPost], catalog }), + }; + // `mailboxBoards` is what lets the build say which declared board no copy + // drains. Without it the check has no roster to read and says nothing — + // which is the silence this app ships to make visible. + const copies = hireWorkforce(installation, { mailboxBoards: mailboxBoardIds(mailboxes) }); - // The generated map, plus the built-in under the key the binder seeds. No - // kind of this app's own is named here: `mailboxKinds` carries whatever - // files live under `flows/mailboxes/`, and `mailbox` is the framework's own - // seed, rebuilt to give it this app's fan-out block and its route. The route - // does nothing for a mailbox whose file has no `routing:` lines. + // The generated map, plus the built-in under the key the binder seeds. The + // fan-out wakes each standard worker the mailbox names, on its flow's copy. const mailboxFlows = mailboxInstances(mailboxes, { kinds: { ...mailboxKinds, mailbox: defineMailboxFlow({ - notify: notifyFor(seats), - route: routeByPurpose(seats, { model: ROUTE_MODEL }), + notify: notifyFor(copies, installation), + route: routeByPurpose(copies, { model: ROUTE_MODEL, installation }), }), }, }); return { - seats, + installation, + copies, mailboxFlows, mailboxes, errors: [ diff --git a/apps/kitchen-sink/workforce/mailbox-notify.ts b/apps/kitchen-sink/workforce/mailbox-notify.ts index f3b0d14997..ddaca57400 100644 --- a/apps/kitchen-sink/workforce/mailbox-notify.ts +++ b/apps/kitchen-sink/workforce/mailbox-notify.ts @@ -9,27 +9,28 @@ * `workforce/` is not walked, so a block that belongs to the built-in lives * here and stays off that map. * - * The wake is Workforce's `wakeMemberSeats`, over the seats hired at boot, - * with nothing of this app's added: every member of `support.help` is an agent - * seat that hears posts, so there is no member to stand in for. On a routed - * mailbox the route has already picked who hears a post, and the wake runs - * that seat alone. A seat's own post wakes nobody. The goal checks' two wake - * controls wrap it here, from `lib/mailbox-wake-control.ts`, and never reach - * the package. + * The wake is Workforce's `wakeMemberSeats`, over the copies registered at + * boot, with nothing of this app's added: every member of `support.help` is a + * standard worker on `agent`, which hears posts, so there is no member to + * stand in for. Each member wakes in a conversation of its own on the one + * `agent` copy. On a routed mailbox the route has already picked who hears a + * post, and the wake runs that worker alone. A worker's own post wakes nobody. + * The goal checks' two wake controls wrap it here, from + * `lib/mailbox-wake-control.ts`, and never reach the package. */ import type { BlockDefinition } from "@flow-state-dev/core"; import type { FlowInstance } from "@flow-state-dev/core/types"; -import { wakeMemberSeats } from "@flow-state-dev/workforce"; +import { wakeMemberSeats, type WorkerInstallation } from "@flow-state-dev/workforce"; import { withMailboxWakeControl } from "../lib/mailbox-wake-control"; /** - * The notify block for the hired roster: the wake for each member whose seat - * can hear a post. + * The notify block: the wake for each member that can hear a post. * - * @param seats The seats hired at boot. + * @param copies The copies registered at boot. + * @param installation The installation whose standard workers the members are. * @returns The block `defineMailboxFlow({ notify })` runs once per member per post. */ -export function notifyFor(seats: readonly FlowInstance[]): BlockDefinition { - return withMailboxWakeControl(wakeMemberSeats(seats)); +export function notifyFor(copies: readonly FlowInstance[], installation: WorkerInstallation): BlockDefinition { + return withMailboxWakeControl(wakeMemberSeats(copies, { installation })); } From 7158cc374465155bf0afc61ca4b7a021d2be7b97 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 01:40:28 +0000 Subject: [PATCH 06/12] test(goals): VG and the BR-24 grants goal on one shared copy; hire-plane goals retired (FIX-1788 P4 S15, VG, V7) goals/workers-as-resources/keeps-each-users-workers-their-own is the issue's goal, with its org-scoped-workers and no-create-check controls. The grants goal grades what each worker's model reaches on one copy, with a no-visibility-rule control. Goals that asserted a copy per worker move to the installation or are retired in goals/README.md, each naming the rule that replaced it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- goals/README.md | 20 +- .../run.mts | 55 +- .../runs-in-the-apps-organization/goal.md | 2 +- .../goal.md | 1 + .../goal.md | 1 + .../goal.md | 4 +- .../run.mts | 6 +- .../goal.md | 6 +- .../run.mts | 9 +- .../it-wakes-the-seat-a-file-declared/goal.md | 4 +- .../it-wakes-the-seat-a-file-declared/run.mts | 4 +- .../fixtures/input.json | 13 - .../goal.md | 22 - .../run.mts | 315 ---------- .../fixtures/input.json | 13 - .../keeps-a-hired-seat-with-its-owner/goal.md | 36 -- .../keeps-a-hired-seat-with-its-owner/run.mts | 465 -------------- .../fixtures/input.json | 9 - .../goal.md | 32 - .../run.mts | 445 ------------- .../fixtures/input.json | 11 - .../goal.md | 23 - .../run.mts | 211 ------- .../fixtures/input.json | 10 - .../goal.md | 26 - .../run.mts | 312 --------- .../repairs-a-seat-whose-kind-was-cut/app.mts | 241 ------- .../fixtures/input.json | 14 - .../repairs-a-seat-whose-kind-was-cut/goal.md | 25 - .../repairs-a-seat-whose-kind-was-cut/run.mts | 126 ---- .../start.mts | 156 ----- goals/lib/index.mts | 1 + goals/lib/workers.mts | 54 ++ .../teams/ops/mailboxes/desk/MAILBOX.md | 7 - .../teams/ops/workers/auditor/WORKER.md | 5 - .../it-hands-a-task-to-a-fresh-hire/goal.md | 33 - .../it-hands-a-task-to-a-fresh-hire/run.mts | 334 ---------- .../run.mts | 36 +- .../run.mts | 9 +- goals/manager-queue-lab/lab/host.mts | 73 ++- .../lab/workforce/flows/workers/builder.mts | 73 ++- .../workforce/flows/workers/coordinator.mts | 42 +- .../org-seats/cos-changes-the-roster/goal.md | 97 --- .../org-seats/cos-changes-the-roster/run.mts | 538 ---------------- .../cos-changes-the-roster/seat-asks.mts | 318 ---------- .../run.mts | 4 +- .../harness.mts | 8 +- goals/pentest-lab/lab/host.mts | 81 ++- goals/pentest-lab/lab/notify.mts | 24 +- goals/pentest-lab/lab/scope-check.mts | 10 +- .../lab/workforce/flows/workers/probe.mts | 51 +- goals/scripts/validate-control-shape.mts | 5 - .../fixtures/input.json | 8 - .../refuses-an-unpinned-register/goal.md | 19 - .../refuses-an-unpinned-register/run.mts | 244 ------- .../manifest.mts | 12 - .../run.mts | 75 ++- .../fixtures/flows.ts | 263 ++++---- .../goal.md | 16 +- .../run.mts | 222 +++---- .../fixtures/app.ts | 123 ++++ .../fixtures/input.json | 9 + .../teams/desk/workers/amy/WORKER.md | 5 + .../workers/amy/skills/refund-policy/SKILL.md | 5 + .../teams/research/workers/lead/WORKER.md | 6 + .../goal.md | 21 + .../run.mts | 249 ++++++++ .../harness.mts | 10 +- .../run.mts | 73 ++- .../fixtures/flows.ts | 33 +- .../goal.md | 3 +- .../run.mts | 38 +- .../workforce/flows/workers/desk-clerk.ts | 47 +- .../code-comes-from-files-alone/run.mts | 35 +- .../fixtures/input.json | 16 - .../durable-hire-survives-redeploy/goal.md | 21 - .../durable-hire-survives-redeploy/run.mts | 560 ----------------- .../goal.md | 2 + .../host.mts | 45 +- .../run.mts | 2 +- .../a-routed-post-gets-one-answer/goal.md | 2 + .../a-routed-post-gets-one-answer/host.mts | 26 +- .../a-routed-post-gets-one-answer/run.mts | 25 +- .../fixtures/flows.ts | 144 ++--- .../goal.md | 46 +- .../run.mts | 207 +++--- .../fixtures/flows.ts | 238 ++++--- .../goal.md | 20 +- .../run.mts | 133 ++-- .../fixtures/flows.ts | 161 ++--- .../goal.md | 105 ++-- .../run.mts | 423 ++++++------- .../fixtures/flows.ts | 187 ------ .../fixtures/input.json | 55 -- .../engineering/workers/legacy/WORKER.md | 6 - .../engineering/workers/intake/WORKER.md | 5 - .../teams/engineering/workers/lead/WORKER.md | 9 - .../engineering/workers/intake/WORKER.md | 6 - .../engineering/workers/analyst/WORKER.md | 7 - .../engineering/workers/scribe/WORKER.md | 6 - .../goal.md | 34 - .../run.mts | 594 ------------------ 102 files changed, 2074 insertions(+), 6947 deletions(-) delete mode 100644 goals/hire-plane/discover-survives-an-unaddressable-row/fixtures/input.json delete mode 100644 goals/hire-plane/discover-survives-an-unaddressable-row/goal.md delete mode 100644 goals/hire-plane/discover-survives-an-unaddressable-row/run.mts delete mode 100644 goals/hire-plane/keeps-a-hired-seat-with-its-owner/fixtures/input.json delete mode 100644 goals/hire-plane/keeps-a-hired-seat-with-its-owner/goal.md delete mode 100644 goals/hire-plane/keeps-a-hired-seat-with-its-owner/run.mts delete mode 100644 goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/fixtures/input.json delete mode 100644 goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/goal.md delete mode 100644 goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/run.mts delete mode 100644 goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/fixtures/input.json delete mode 100644 goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/goal.md delete mode 100644 goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/run.mts delete mode 100644 goals/hire-plane/reload-survives-an-unaddressable-row/fixtures/input.json delete mode 100644 goals/hire-plane/reload-survives-an-unaddressable-row/goal.md delete mode 100644 goals/hire-plane/reload-survives-an-unaddressable-row/run.mts delete mode 100644 goals/hire-plane/repairs-a-seat-whose-kind-was-cut/app.mts delete mode 100644 goals/hire-plane/repairs-a-seat-whose-kind-was-cut/fixtures/input.json delete mode 100644 goals/hire-plane/repairs-a-seat-whose-kind-was-cut/goal.md delete mode 100644 goals/hire-plane/repairs-a-seat-whose-kind-was-cut/run.mts delete mode 100644 goals/hire-plane/repairs-a-seat-whose-kind-was-cut/start.mts create mode 100644 goals/lib/workers.mts delete mode 100644 goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/fixtures/workforce/teams/ops/mailboxes/desk/MAILBOX.md delete mode 100644 goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/fixtures/workforce/teams/ops/workers/auditor/WORKER.md delete mode 100644 goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/goal.md delete mode 100644 goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/run.mts delete mode 100644 goals/org-seats/cos-changes-the-roster/goal.md delete mode 100644 goals/org-seats/cos-changes-the-roster/run.mts delete mode 100644 goals/org-seats/cos-changes-the-roster/seat-asks.mts delete mode 100644 goals/seat-hire/refuses-an-unpinned-register/fixtures/input.json delete mode 100644 goals/seat-hire/refuses-an-unpinned-register/goal.md delete mode 100644 goals/seat-hire/refuses-an-unpinned-register/run.mts create mode 100644 goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/app.ts create mode 100644 goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/input.json create mode 100644 goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/workforce/teams/desk/workers/amy/WORKER.md create mode 100644 goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/workforce/teams/desk/workers/amy/skills/refund-policy/SKILL.md create mode 100644 goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/workforce/teams/research/workers/lead/WORKER.md create mode 100644 goals/workers-as-resources/keeps-each-users-workers-their-own/goal.md create mode 100644 goals/workers-as-resources/keeps-each-users-workers-their-own/run.mts delete mode 100644 goals/workforce-conventions/durable-hire-survives-redeploy/fixtures/input.json delete mode 100644 goals/workforce-conventions/durable-hire-survives-redeploy/goal.md delete mode 100644 goals/workforce-conventions/durable-hire-survives-redeploy/run.mts delete mode 100644 goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/flows.ts delete mode 100644 goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/input.json delete mode 100644 goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/no-contract/teams/engineering/workers/legacy/WORKER.md delete mode 100644 goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/teams/engineering/workers/intake/WORKER.md delete mode 100644 goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/teams/engineering/workers/lead/WORKER.md delete mode 100644 goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/thin-with-body/teams/engineering/workers/intake/WORKER.md delete mode 100644 goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/undeclared-setting/teams/engineering/workers/analyst/WORKER.md delete mode 100644 goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/unknown-kind/teams/engineering/workers/scribe/WORKER.md delete mode 100644 goals/workforce-seats/two-seats-run-their-own-configuration/goal.md delete mode 100644 goals/workforce-seats/two-seats-run-their-own-configuration/run.mts diff --git a/goals/README.md b/goals/README.md index 403a373442..8e7d3ee39e 100644 --- a/goals/README.md +++ b/goals/README.md @@ -55,7 +55,7 @@ A title (` › it `), then the fields, then a verdict log. What separates a goal check from a dressed-up unit test: -1. **Assert on the user-visible surface, not the implementation.** Check the emitted items / `useSession` view / a real side effect / the returned answer (only when the claim is about what the model does) — not the output of the internal function that produced them. A check that asserts on `collapseToCanonicalLog()`'s return value can pass while the rendered stream double-fires; a check that asserts on what `useSession` shows cannot. When the claim is about data the system holds or a tool returns, grade the tool's output item for a read, or the stored row for a claim that the run wrote or changed something, not the model's retelling of it (a row that existed before the run proves nothing about a read). A retelling that fails is a lead, not a verdict, and prompting the model to recite never turns it green. `goals/org-seats/cos-changes-the-roster` grades `discover`'s `tool_output` this way. +1. **Assert on the user-visible surface, not the implementation.** Check the emitted items / `useSession` view / a real side effect / the returned answer (only when the claim is about what the model does) — not the output of the internal function that produced them. A check that asserts on `collapseToCanonicalLog()`'s return value can pass while the rendered stream double-fires; a check that asserts on what `useSession` shows cannot. When the claim is about data the system holds or a tool returns, grade the tool's output item for a read, or the stored row for a claim that the run wrote or changed something, not the model's retelling of it (a row that existed before the run proves nothing about a read). A retelling that fails is a lead, not a verdict, and prompting the model to recite never turns it green. 2. **Grade against the input.** Pull the concrete facts out of the fixture and assert they survived into the output. This is what catches "the pattern ran but dropped the data." Parameterize so swapping the fixture still works — that's the held-out guarantee in code. The prompt names every input the claim isn't about (the kind, the id, the target), so a correct model's clarifying question can't read as a failure. 3. **Use a real side effect for "exactly once" claims.** To prove a step didn't re-run, increment a real counter (a state value, a row, a file) and assert the count — not item de-duplication, which can hide a double-fire. 4. **Drive the real path.** Default is `runFsdev({ app, flow, action, input, capture })` (it runs from the app dir — config search is cwd-only). The capture file is `{ command, events, result }`; `readCapture(path)` parses it. Read it carefully — `_template/run.mts` shows the pattern: @@ -150,3 +150,21 @@ A model-backed goal check costs real model calls, and that cost is the point — Keep the **Model** field present and machine-readable (`**Model:** …` or `**Model.** …`) — `goal:all` reads it to decide what a `--model-free` sweep may run. `n/a` and `none` both mean model-free. A model-backed goal whose legs split can add `**Model-free run:** `NAME=value`` naming the env that runs only its model-free legs; a `--model-free` sweep then runs it with that env instead of skipping it. Reach for a new `goals/lib` helper only when a *third* goal needs the same scaffolding. Two copies is not yet a pattern; the library is for what every goal repeats, not for anything that could be shared. + +## Retired + +A goal is retired when the rule it proved no longer exists, and the line says which rule replaced it. Its history stays in git. + +Retired by FIX-1788, when workers became data on one copy per worker flow. Hiring writes a row in the hiring user's own scope and registers nothing, so there is no hired seat to pin, reload, repair or list: + +- `hire-plane/discover-survives-an-unaddressable-row`: nothing stored becomes a seat. The org's listing is the standard workers the files declare, and a user's roster lists their own workers beside them (FIX-1788 BR-9, BR-26). +- `hire-plane/keeps-a-hired-seat-with-its-owner`: a user's workers are rows in their own scope; another user's worker answers as one that doesn't exist, and their sessions stay theirs (BR-5, BR-11, BR-17), proven by `workers-as-resources/keeps-each-users-workers-their-own` leg b. +- `hire-plane/keeps-a-private-team-in-the-org-it-was-built-in`: the same, per organization; what a worker saves at user scope is its user's (BR-5, BR-23, BR-25), proven by `workers-as-resources/keeps-each-users-workers-their-own` legs a and b. +- `hire-plane/keeps-the-debug-listing-on-the-hire-plane`: there is no org roster of hires to list; a user's roster is in their own user scope (BR-1, BR-5). +- `hire-plane/reload-survives-an-unaddressable-row`: nothing is reloaded at boot; each turn reads its worker's row (BR-1, BR-20). +- `hire-plane/repairs-a-seat-whose-kind-was-cut`: a worker whose flow is gone refuses its turn, naming it, and an `edit` fixes it for the next turn (BR-19a, BR-20, BR-22). +- `seat-hire/refuses-an-unpinned-register`: no hire registers anything (BR-1, BR-26). Owner pins are still an engine mechanism until FIX-1798, proven by `hire-plane/refuses-a-board-drain-onto-a-seat-it-is-outside`. +- `org-seats/cos-changes-the-roster`: a chief of staff's hire and fire write the roster of the person it talks to (BR-1, BR-7, BR-8), and a roster lists that person's own workers beside the standard ones (BR-9). +- `mailbox-boards/it-hands-a-task-to-a-fresh-hire`: a task on a board names a standard worker, and its session is opened naming that worker (BR-18). A user's own worker isn't handed board tasks. +- `workforce-seats/two-seats-run-their-own-configuration`: a worker is no copy addressable by its own id; each flow is registered once and a session names its worker (BR-26). That each worker's turn runs on its own record's settings and none of its sibling's is proven by `workforce-seats/a-callers-own-agent-wins-every-seat` (b) and `workforce-seats/a-non-agent-seat-receives-its-skills` (b) and (c), and the admission control pair by the latter's (d) and (e). +- `workforce-conventions/durable-hire-survives-redeploy`: a hire is a row every turn reads, on any process, so there is nothing to restore after a redeploy (BR-1, BR-20), proven by `workers-as-resources/keeps-each-users-workers-their-own` leg a's second host. diff --git a/goals/agent-discovery/an-orchestrator-routes-a-task-by-asking/run.mts b/goals/agent-discovery/an-orchestrator-routes-a-task-by-asking/run.mts index 10d3139717..c865270ae1 100644 --- a/goals/agent-discovery/an-orchestrator-routes-a-task-by-asking/run.mts +++ b/goals/agent-discovery/an-orchestrator-routes-a-task-by-asking/run.mts @@ -21,12 +21,12 @@ * Run: pnpm tsx goals/agent-discovery/an-orchestrator-routes-a-task-by-asking/run.mts */ import { defineCapability, defineFlow, handler, DEFAULT_ORG_ID } from "@flow-state-dev/core"; -import { createInMemoryStores, createModelResolver, runAction } from "@flow-state-dev/engine"; +import { createInMemoryStores, createModelResolver, ensureSessionRecord, runAction } from "@flow-state-dev/engine"; import { createWorkforceCapability, defineAgentWorkerFlow, defineSeatInventoryCollection, - hireWorkforce, + createWorkerInstallation, hireWorkforce, type WorkerManifest, } from "@flow-state-dev/workforce"; import { z } from "zod"; @@ -124,7 +124,17 @@ async function route(blankPurposes: boolean): Promise<{ const { assign, assigned } = assignTool(); const roster = rosterFrom(fx.seats, blankPurposes); + // The coordinator is a worker from a record like any other. Its file names + // its tool and its instructions; it names NO seat and no roster. + const coordinatorRecord: WorkerManifest = { + id: fx.orchestrator.id, + declared: { tools: ["assign"] }, + body: fx.orchestrator.instructions, + }; + let flows: Record = {}; + const installation = createWorkerInstallation({ standardWorkers: [coordinatorRecord], workerFlows: () => flows as never }); const kind = defineAgentWorkerFlow({ + installation, model: DEFAULT_MODEL, catalog: { assign }, uses: [ @@ -136,17 +146,9 @@ async function route(blankPurposes: boolean): Promise<{ ], }); - // The coordinator is hired from a record like any other seat. Its file names - // its tool and its instructions; it names NO seat and no roster. - const coordinatorRecord: WorkerManifest = { - id: fx.orchestrator.id, - declared: { tools: ["assign"] }, - body: fx.orchestrator.instructions, - }; - const [coordinator] = hireWorkforce([coordinatorRecord], { - workerFlows: { agent: kind as never }, - }); - if (!coordinator) return { assigned, prompt: "", error: "the coordinator was not hired" }; + flows = { agent: kind }; + const coordinator = hireWorkforce(installation).find((copy) => copy.id === "agent"); + if (!coordinator) return { assigned, prompt: "", error: "no agent copy was registered" }; const stores = createInMemoryStores(); const runtimeConfig = { @@ -170,9 +172,34 @@ async function route(blankPurposes: boolean): Promise<{ }); if (seeded.error) return { assigned, prompt: "", error: `seeding failed: ${seeded.error.message}` }; + // The coordinator's session, created naming it. + const now = Date.now(); + await ensureSessionRecord( + stores, + session, + { + flow: coordinator as never, + sessionId: session, + principal: { userId: "goal-user", orgId: DEFAULT_ORG_ID }, + state: { workerId: coordinatorRecord.id }, + fromCaller: true, + via: "create", + }, + () => ({ + id: session, + flowKind: coordinator.kind, + flowId: coordinator.id, + userId: "goal-user", + orgId: DEFAULT_ORG_ID, + version: 0, + createdAt: now, + updatedAt: now, + journal: [], + }) as never, + ); const result = await runAction({ orgId: DEFAULT_ORG_ID, - flow: { ...coordinator, cardinality: "singleton" } as never, + flow: coordinator as never, actionName: "run" as never, input: { message: fx.task }, userId: "goal-user", diff --git a/goals/cli-principal/runs-in-the-apps-organization/goal.md b/goals/cli-principal/runs-in-the-apps-organization/goal.md index 70241ef48a..ec3fc34614 100644 --- a/goals/cli-principal/runs-in-the-apps-organization/goal.md +++ b/goals/cli-principal/runs-in-the-apps-organization/goal.md @@ -2,7 +2,7 @@ **Issue:** FIX-1551 (VG); re-pointed by FIX-1611. Needs FIX-1500 PR-B, which gives kitchen-sink its host resolver. **Outcome:** A developer runs a kitchen-sink seat from the terminal and it behaves as the app would for a browser visitor. `support.general` answers, and its conversation is stored in the `kitchen-sink` organization, where the app's own pages can see it. Before FIX-1551, the terminal ran in the framework's development organization. -**Re-pointed (FIX-1611).** Until FIX-1611 the seat was `support.mara`, a manager whose run hired a seat, and (c) read the hire's roster row. The page's hiring and the manager are gone; the operator hires over `workforce-admin`, which `durable-hire-survives-redeploy` checks. So the run is now an ordinary question to a specialist, and (c) reads the conversation it stored: the same question, "which organization did the terminal's run write under", asked of the one record every run writes. +**Re-pointed (FIX-1611).** Until FIX-1611 the seat was `support.mara`, a manager whose run hired a seat, and (c) read the hire's roster row. The page's hiring and the manager are gone; the operator hired over `workforce-admin`, which FIX-1788 has since removed. So the run is now an ordinary question to a specialist, and (c) reads the conversation it stored: the same question, "which organization did the terminal's run write under", asked of the one record every run writes. **Input:** `fixtures/input.json`: the seat, the action, the message, and the identity the app's resolver names. Held-out: the conversation id is fresh every run, so the check cannot pass on a record an earlier run left behind. Changing the seat to another specialist or the message wording must still pass a correct implementation. **Signal:** Three checks on one run. (a) The capture's `command.principal` is exactly the fixture's `expect` (`devuser` / `kitchen-sink` / `resolver`). (b) The run completes. (c) A zero-model read of the same filesystem store finds the run's conversation, belonging to `support.general`, stored under `kitchen-sink` and not under `__fsd_default_org__`. **Anti-game:** A hollow pass would grade the model's transcript, or the CLI's own claim about its identity. Neither proves where the conversation went. This check MUST read the conversation out of the store and must not treat `result.success` alone as proof. It must not reuse a fixed conversation id, or a record from an earlier run passes it. diff --git a/goals/devforce-lab/it-codes-in-the-projects-repository/goal.md b/goals/devforce-lab/it-codes-in-the-projects-repository/goal.md index f4e538d61d..c2465bb940 100644 --- a/goals/devforce-lab/it-codes-in-the-projects-repository/goal.md +++ b/goals/devforce-lab/it-codes-in-the-projects-repository/goal.md @@ -43,6 +43,7 @@ wrote anything. Rows are filed through the EM worker and run by its drain, as in | Control | Perturbs | Goes red on | |---|---|---| +| 2026-10-08 | `865abc573` + FIX-1788 P4 | n/a | PASS | On one copy per worker flow: the storefront run committed on its project's repository branch, the sandbox run worked on the project's files. | | `fixed-source` | the manager on the lab's one fixed scratch repository, as before | `a:marker` (and every leg that needs a project's source) | | `no-sync-back` | the host saves nothing back | `b:second-run-sees-file` (and `a:note-saved`, `b:file-saved`) | diff --git a/goals/devforce-lab/it-keeps-its-rows-on-the-mailboxes-board/goal.md b/goals/devforce-lab/it-keeps-its-rows-on-the-mailboxes-board/goal.md index e6114ea838..8fa4f9d8c8 100644 --- a/goals/devforce-lab/it-keeps-its-rows-on-the-mailboxes-board/goal.md +++ b/goals/devforce-lab/it-keeps-its-rows-on-the-mailboxes-board/goal.md @@ -45,6 +45,7 @@ FAIL on leg 2, *the mailbox's board returned no rows* (legs 3, 4 and 5 go red wi ## Verdict log | Date | Commit | Model | Verdict | Notes | |------|--------|-------|---------|-------| +| 2026-10-08 | `865abc573` + FIX-1788 P4 | n/a | PASS | On one copy per worker flow: a post on eng.feature ended as one completed row on the mailbox's own board, assignee coder. | | 2026-09-30 | a1b122eb1 | n/a | PASS | Board `eng.feature.work`, one completed row assignee `coder`; the door returns it with no private field and refuses the org-less read (401); one org copy, none in user storage; no unattended-board warning. | | 2026-09-30 | a1b122eb1 | n/a | FAIL (control `kind-ledger`) | Fails at leg 2, *the mailbox's board returned no rows*; legs 3, 4 and 5 red with it. As designed. | | 2026-09-30 | a1b122eb1 | n/a | PASS (board renamed `queue`) | The board's name and id are read off the tree; rename reverted. | diff --git a/goals/devforce-lab/it-ships-an-artifact-a-person-can-open/goal.md b/goals/devforce-lab/it-ships-an-artifact-a-person-can-open/goal.md index 0488119d53..f2f697c39f 100644 --- a/goals/devforce-lab/it-ships-an-artifact-a-person-can-open/goal.md +++ b/goals/devforce-lab/it-ships-an-artifact-a-person-can-open/goal.md @@ -26,7 +26,7 @@ convention file and in none of the lab's own code, before the run starts. transcript, the fan-out addressed the EM seat and recorded every other member `MAILBOX.md` declares as skipped (read off the tree, which must still declare the coder and the reviewer), and exactly one row exists. -2. The board's dispatch record names the coder seat and never the reviewer seat, by `flowId`. +2. The board's dispatch record names the coder seat and never the reviewer seat, by the worker each child session names (`workerId`). 3. The prompt the manager handed the agent carries all four held-out tokens. 4. Exactly one branch under `conductor/` resolves at the published address **after** the store is closed and the temporary repository and every checkout have been deleted, and it is at least one @@ -86,7 +86,7 @@ defeat waiting to come back quietly. | `already-passing` | a base ref seeded with **the artifact the run actually produced** | the base-ref half ACCEPTS, which is the vacuous-green shape BR-3's second half exists to catch | | `no-harness` | the harness slot throws, as an unauthenticated SDK does | the row settles **`errored`** and no branch carries a commit — it fails rather than substituting something | | `rejected-work` | a scripted run that commits work the brief did not ask for | the row settles `errored` rather than `completed`, which is **BR-4**: the artifact existing is never sufficient, and the row is what survives the run | -| `work-reaches-the-reviewer` | the board's `coder` assignee is addressed to the reviewer seat | a board dispatch record carries `flowId` = the reviewer, which the goal forbids | +| `work-reaches-the-reviewer` | the board's `coder` assignee is addressed to the reviewer seat | a board dispatch record carries `workerId` = the reviewer, which the goal forbids | `already-passing` is built from the run's own product rather than from an implementation written in the check, for two reasons: writing one would put the answer in a file BR-2 scans, and a base ref diff --git a/goals/devforce-lab/it-ships-an-artifact-a-person-can-open/run.mts b/goals/devforce-lab/it-ships-an-artifact-a-person-can-open/run.mts index 831acda974..dbbcbcb4d1 100644 --- a/goals/devforce-lab/it-ships-an-artifact-a-person-can-open/run.mts +++ b/goals/devforce-lab/it-ships-an-artifact-a-person-can-open/run.mts @@ -635,7 +635,7 @@ await runGoal(async () => { await lab.drain(COORDINATOR_SEAT); const reached = (await lab.dispatched(COORDINATOR_SEAT)).filter( - (child) => child.flowId === REVIEWER_SEAT, + (child) => child.workerId === REVIEWER_SEAT, ); if (reached.length === 0) { failures.push( @@ -888,13 +888,13 @@ await runGoal(async () => { // ---- BR-8, graded where the rule points: the board dispatch record --- const dispatches = await lab.dispatched(COORDINATOR_SEAT); - const toReviewer = dispatches.filter((child) => child.flowId === REVIEWER_SEAT); + const toReviewer = dispatches.filter((child) => child.workerId === REVIEWER_SEAT); if (toReviewer.length > 0) { failures.push( `${toReviewer.length} board dispatch(es) reached ${REVIEWER_SEAT}, which never receives work`, ); } - if (!dispatches.some((child) => child.flowId === ASSIGNED_SEAT)) { + if (!dispatches.some((child) => child.workerId === ASSIGNED_SEAT)) { failures.push( `no board dispatch names ${ASSIGNED_SEAT}, so there is no record the row reached the ` + `seat it was addressed to`, diff --git a/goals/devforce-lab/it-waits-for-a-person-before-it-files/goal.md b/goals/devforce-lab/it-waits-for-a-person-before-it-files/goal.md index 6df77193ea..9821575806 100644 --- a/goals/devforce-lab/it-waits-for-a-person-before-it-files/goal.md +++ b/goals/devforce-lab/it-waits-for-a-person-before-it-files/goal.md @@ -26,7 +26,7 @@ different valid feature still passes a correct implementation. 2. Approve, through `POST /eng.em/requests/:id/resume`: first a resume with no bearer (401) and one with `submit` (409) are refused and it stays pending; then approve answers 202, the request completes, exactly one row (derived from the held-out slug) settles `completed`, handed to the - coder seat by `flowId` and never to the reviewer, the coder reached once, nothing left pending + coder seat by `workerId` and never to the reviewer, the coder reached once, nothing left pending *(AR-8, AR-9, AR-11, AR-13)*; 3. Deny, on a fresh open: the request completes, no row, no dispatch, the coder not reached, and the EM's message says nothing was filed *(AR-10, AR-11)*; @@ -47,13 +47,15 @@ different valid feature still passes a correct implementation. a lab helper rather than by the route Shift Manager takes. So every read a person's client would make goes through the lab's HTTP door with its verified bearer; the answer goes only through the engine's resume route; rows are **enumerated**, never looked up by the id this check expects; and "the coder -started" is graded on the dispatch record by `flowId` and on the stub being reached, not on the +started" is graded on the dispatch record by `workerId` and on the stub being reached, not on the row's status alone. **Controls:** `GOAL_CONTROL=list` prints them. | Control | Perturbs | Goes red on | |---|---|---| +| 2026-10-08 | `865abc573` + FIX-1788 P4 | n/a | FAIL (control) | `no-gate`: legs 1, 3, 4c and 10 (a row before any approval). | +| 2026-10-08 | `865abc573` + FIX-1788 P4 | n/a | PASS | The ask raised in `s_eng_em`, a session on `em` naming the EM; answered through `em`'s resume route; approve filed one row handed to `eng.coder` by worker id; deny filed nothing. | | `no-gate` | the asking door files before it suspends | leg 1, "a row existed before any approval" (and legs 3 and 4c, a row after Deny) | **Model:** n/a (model-free by design; no key is read). diff --git a/goals/devforce-lab/it-waits-for-a-person-before-it-files/run.mts b/goals/devforce-lab/it-waits-for-a-person-before-it-files/run.mts index 4096c34f47..e5776342d7 100644 --- a/goals/devforce-lab/it-waits-for-a-person-before-it-files/run.mts +++ b/goals/devforce-lab/it-waits-for-a-person-before-it-files/run.mts @@ -185,7 +185,7 @@ async function answer( ): Promise<{ status: number; body: any }> { return await lab.door( "POST", - `${fixture.coordinatorSeat}/requests/${ask.requestId}/resume`, + `${lab.seats[fixture.coordinatorSeat]!.id}/requests/${ask.requestId}/resume`, { body: { suspensionId: ask.suspensionId, action }, bearer }, ); } @@ -194,7 +194,7 @@ async function answer( async function requestReaches(lab: Lab, requestId: string, want: string[]): Promise { let last = ""; for (let waited = 0; waited < wait.timeoutMs; waited += wait.pollMs) { - const r = await lab.door("GET", `${fixture.coordinatorSeat}/requests/${requestId}/status`); + const r = await lab.door("GET", `${lab.seats[fixture.coordinatorSeat]!.id}/requests/${requestId}/status`); last = r.body?.status ?? r.body?.request?.status ?? `http ${r.status}`; if (want.includes(last)) return last; await sleep(wait.pollMs); @@ -337,7 +337,7 @@ await runGoal(async () => { note("2", `the row "${row.id}" is not derived from "${feature.issue}"`); } if (row?.status !== "completed") note("2", `the row settled "${row?.status}", wanted "completed"`); - const reached = (await lab.dispatched(fixture.coordinatorSeat)).map((d) => d.flowId); + const reached = (await lab.dispatched(fixture.coordinatorSeat)).map((d) => d.workerId); if (reached.length !== 1 || reached[0] !== fixture.assignedSeat) { note("2", `the board handed the row to ${JSON.stringify(reached)}, wanted ["${fixture.assignedSeat}"]`); } @@ -479,7 +479,8 @@ await runGoal(async () => { [0, 1].map(() => raiseAsk({ state: lab.state, - emSeat: lab.seats[fixture.coordinatorSeat]!, + emFlow: lab.seats[fixture.coordinatorSeat]!, + emWorker: fixture.coordinatorSeat, feature: other, principal: { userId: LAB_USER_ID, orgId: LAB_ORG_ID }, ledger: lab.ledger, diff --git a/goals/devforce-lab/it-wakes-the-seat-a-file-declared/goal.md b/goals/devforce-lab/it-wakes-the-seat-a-file-declared/goal.md index 52dde83ab3..519e64e410 100644 --- a/goals/devforce-lab/it-wakes-the-seat-a-file-declared/goal.md +++ b/goals/devforce-lab/it-wakes-the-seat-a-file-declared/goal.md @@ -30,7 +30,7 @@ which the `WORKER.md` files name) and the board's `coder` assignee key. 2. each seat reports its own instructions, document ref and **exact** skill union from inside a running block, and the coordinator kind declares no task entry at all *(BR-3, BR-4)*; 3. one row, claimed once, handed to the seat the board's assignee names — graded on the **dispatch - record**, by `flowId` — with the third seat absent from it, and a second drain claiming nothing + record**, by the `workerId` each child session names — with the third seat absent from it, and a second drain claiming nothing *(BR-5, BR-6, BR-8, BR-9)*; 4. the prompt carries all four held-out tokens, the run's `cwd` is the checkout the framework itself derives for this row (and that derivation is injective over its components), and the row settles @@ -64,6 +64,8 @@ handed every skill in the tree. | Control | Perturbs | Goes red on | |---|---|---| +| 2026-10-08 | `865abc573` + FIX-1788 P4 | n/a | FAIL (control) | `address-the-reviewer`: the drain dispatched to ["eng.reviewer"] and the coder's tokens missing. `no-commit` and `stopped-at-limit`: the row settled pending. `swap-documents`: eng.coder reads engineering-handbook. `drop-own-skill`: eng.coder holds only commit-style. | +| 2026-10-08 | `865abc573` + FIX-1788 P4 | n/a | PASS | The lab on one copy per worker flow (`em`, `coder`, `agent`): the EM's board handed the row to a session on `coder` naming `eng.coder`, graded on the dispatch record's `workerId`; the reviewer on the same flow never reached; each seat's own files in its prompt. A tree naming `codr` registered nothing. | | `address-the-reviewer` | the board's assignee address | the dispatch record names the seat that must never be reached | | `no-commit` | what the run leaves behind | the row does not settle done | | `swap-documents` | the working seat's `document:` | its own brief's token cannot reach the prompt | diff --git a/goals/devforce-lab/it-wakes-the-seat-a-file-declared/run.mts b/goals/devforce-lab/it-wakes-the-seat-a-file-declared/run.mts index 402b39ae50..281f23fb88 100644 --- a/goals/devforce-lab/it-wakes-the-seat-a-file-declared/run.mts +++ b/goals/devforce-lab/it-wakes-the-seat-a-file-declared/run.mts @@ -365,7 +365,7 @@ await runGoal(async () => { } if (hiredAnyway >= 0) { note(`a tree naming an unregistered kind hired ${hiredAnyway} seats instead of refusing`); - } else if (!refusal.includes("nothing was hired") || !refusal.includes("codr")) { + } else if (!refusal.includes("nothing was registered") || !refusal.includes("codr")) { note(`the refusal did not name the unregistered kind and the empty roster: ${refusal}`); } @@ -457,7 +457,7 @@ await runGoal(async () => { // cannot tell the seat that was named from the seat that must never be // reached. That distinction is the whole of BR-8. const dispatched = await lab.dispatched(fixture.coordinatorSeat); - const reached = dispatched.map((child) => child.flowId ?? ""); + const reached = dispatched.map((child) => child.workerId ?? ""); if (!sameSet(reached, [fixture.assignedSeat])) { note( `the drain dispatched to ${JSON.stringify(reached)}, wanted exactly ` + diff --git a/goals/hire-plane/discover-survives-an-unaddressable-row/fixtures/input.json b/goals/hire-plane/discover-survives-an-unaddressable-row/fixtures/input.json deleted file mode 100644 index 78aec01e1e..0000000000 --- a/goals/hire-plane/discover-survives-an-unaddressable-row/fixtures/input.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "devUser": "dev", - "devHireSeatId": "eng.ada", - "fileSeatId": "eng.lead", - "fileSeatPurpose": "Breaks incoming requests into tasks and hands them out.", - "namedOrg": "acme", - "namedUser": "alice", - "namedSeatId": "support.ada", - "namedSeatInstructions": "You take the support queue.", - "tildeSeatId": "~support.bo", - "strayOrg": "globex", - "straySeatId": "stray" -} diff --git a/goals/hire-plane/discover-survives-an-unaddressable-row/goal.md b/goals/hire-plane/discover-survives-an-unaddressable-row/goal.md deleted file mode 100644 index 6d7c4b121b..0000000000 --- a/goals/hire-plane/discover-survives-an-unaddressable-row/goal.md +++ /dev/null @@ -1,22 +0,0 @@ -# hire-plane › discover survives an unaddressable row - -**Issue:** FIX-1541 -**Outcome:** A session asking the discovery door who it can hand work to still gets its seats when one stored hire can never be a seat. An app with no authentication runs as the development organization, whose id cannot be a seat address, so a runtime hire there leaves a row that can never be listed. Before, that one row blanked the whole seat listing for the org. Now the row is left out and every other seat is listed. The same holds for a seat id carrying the user-owned `~` marker in a signed-in org. A row stamped for a different organization is still withheld, not re-bound to the reading org. -**Input:** `fixtures/input.json` — the dev user, the dev hire's seat id, a file-declared seat and its purpose, the signed-in org, user, seat id and instructions, the `~` seat id, and the stray org and seat id. Held-out: every id and purpose is read from the fixture and graded against the discovery door's output. Swapping any of them must still pass. -**Signal:** against `createFlowState`'s HTTP router, one in-memory store shared by a dev app (no resolver) and a signed-in app, no model. The door is `discoveryTools` over `workforceManifestSources` with a hired-roster key, which is what `createWorkforceCapability` builds, run as an action. -(a) The dev app's `list` and `hire` actions complete with no identity, and the hire leaves a roster row under `DEFAULT_ORG_ID`. -(b) The dev app's `discover` completes. Its seats domain carries no `problem` and lists the file-declared seat with the fixture's purpose. -(c) The signed-in org hires one seat, and its cell also holds a `~` row and a row stamped `owningOrgId: ` with an inventory row of its own. `discover` as that org carries no `problem` and lists `.` with the fixture's instructions. -(d) No entry `.` is listed. - -**Anti-game:** a hollow pass would check that `discover` completed, which holds on the bug too: the door degrades a throwing domain to `{ entries: [], problem }` and the action still completes. So the check MUST see the seats domain carry no `problem` AND list the specific seat with the specific purpose from the fixture. Leg (d) has an inventory row for the stray address on purpose, so a fence that re-bound the row to the reading org would list it and fail. -**Model:** n/a — handlers only. The property is which stored rows the door lists. -**Run:** `pnpm tsx goals/hire-plane/discover-survives-an-unaddressable-row/run.mts` (build `@flow-state-dev/workforce` first; the goal imports its `dist`). -**Controls:** none in the runner. The red state is a source revert, so it fails for the reason the bug fails. -- Revert `packages/workforce/src/manifest-sources.ts` to `9041a2c28` (the hired-roster merge with no per-row guard), rebuild workforce. Must FAIL legs (b) and (c) only. - -## Verdict log -| Date | Commit | Model | Verdict | Notes | -|------|--------|-------|---------|-------| -| 2026-09-23 | `9041a2c28` + this change, with `manifest-sources.ts` reverted to `9041a2c28`, then restored | n/a | FAIL (expected) | **Legs (b) and (c) only:** `[b] the dev org's seats domain degraded to a problem: Organization id "__fsd_default_org__" must be lowercase letters, digits, and single hyphens ...`, `[b] the file-declared seat was not listed with its purpose: []`, `[c] acme's seats domain degraded to a problem: seat id "~support.bo" starts with "~" ...`, `[c] acme.support.ada was not listed with its instructions: []`. Leg (a) completed, so the dev hire really does write under the default org through the HTTP path. Leg (d) held. | -| 2026-09-23 | `9041a2c28` + this change (fix present) | n/a | PASS | Exit 0. Dev roster row stored under `__fsd_default_org__`; dev discover listed `["eng.lead"]` with no problem; acme discover listed `["acme.support.ada"]` with no problem, beside a `~support.bo` row and a row stamped for globex. | diff --git a/goals/hire-plane/discover-survives-an-unaddressable-row/run.mts b/goals/hire-plane/discover-survives-an-unaddressable-row/run.mts deleted file mode 100644 index e38f8839b1..0000000000 --- a/goals/hire-plane/discover-survives-an-unaddressable-row/run.mts +++ /dev/null @@ -1,315 +0,0 @@ -/** - * Goal check — one stored hire that can never be a seat does not blank an - * organization's seat listing. - * - * See goal.md for the contract and the source-revert control. - * - * Run: pnpm tsx goals/hire-plane/discover-survives-an-unaddressable-row/run.mts - */ -import { - createManifestRegistry, - defineFlow, - discoveryTools, - handler, - sequencer, -} from "@flow-state-dev/core"; -import { - DEFAULT_ORG_ID, - type JsonObject, - type ResourceCollectionRef, -} from "@flow-state-dev/core/types"; -import { createFlowState, inMemoryStores } from "@flow-state-dev/engine"; -import { - defineHiredRosterCollection, - defineSeatInventoryCollection, - toHiredSeatRow, - workforceManifestSources, -} from "@flow-state-dev/workforce"; -import { z } from "zod"; -import { loadFixture, runGoal } from "../../lib/index.mts"; - -type Fixture = { - devUser: string; - devHireSeatId: string; - fileSeatId: string; - fileSeatPurpose: string; - namedOrg: string; - namedUser: string; - namedSeatId: string; - namedSeatInstructions: string; - tildeSeatId: string; - strayOrg: string; - straySeatId: string; -}; - -type Router = { - GET: (request: Request, ctx: { params: { path: string[] } }) => Promise; - POST: (request: Request, ctx: { params: { path: string[] } }) => Promise; -}; - -type DomainResult = { domain: string; entries: { id: string; purpose: string }[]; problem?: string }; - -const fixture = loadFixture(import.meta.url); - -const SEATS = "seatRows"; -const ROSTER = "roster"; -const resources = { - [SEATS]: defineSeatInventoryCollection(), - [ROSTER]: defineHiredRosterCollection(), -}; - -/** - * The runtime-hire write an app makes: a roster row stamped with the - * session's org, and — where the seat has an address — its inventory row. - * Nothing here chooses the org. An app with no resolver gets DEFAULT_ORG_ID - * from the framework, which is the whole case. - */ -const hireInput = z.object({ - seatId: z.string(), - instructions: z.string().nullable().default(null), - listedAs: z.string().nullable().default(null), -}); -const hire = handler({ - name: "hire", - inputSchema: hireInput, - outputSchema: z.object({ orgId: z.string() }), - resources, - execute: async (input, ctx) => { - const orgId = ctx.session.identity.orgId ?? ""; - const roster = ctx.resources[ROSTER] as unknown as ResourceCollectionRef; - await roster.create( - input.seatId, - toHiredSeatRow({ - seatId: input.seatId, - flow: "agent", - instructions: input.instructions, - owningOrgId: orgId, - }) as unknown as JsonObject, - ); - if (input.listedAs !== null) { - const seats = ctx.resources[SEATS] as unknown as ResourceCollectionRef; - await seats.create(input.listedAs, { id: input.listedAs, kind: "agent" }); - } - return { orgId }; - }, -}); - -/** A seat registered from the file tree: its inventory row, and nothing else. */ -const listInput = z.object({ id: z.string() }); -const list = handler({ - name: "list-seat", - inputSchema: listInput, - outputSchema: z.object({ id: z.string() }), - resources, - execute: async (input, ctx) => { - const seats = ctx.resources[SEATS] as unknown as ResourceCollectionRef; - await seats.create(input.id, { id: input.id, kind: "agent" }); - return { id: input.id }; - }, -}); - -/** - * The discovery door a seat's `discover` tool is, built the way - * `createWorkforceCapability` builds it: the workforce's sources in one - * registry, the door over it. Run as an action so no model sits between the - * door and the check. - */ -const { discover } = discoveryTools( - createManifestRegistry( - workforceManifestSources({ - roster: { - workers: [ - { id: fixture.fileSeatId, declared: { description: fixture.fileSeatPurpose }, body: "" }, - ], - mailboxes: [], - }, - inventory: { seats: SEATS }, - hiredRoster: ROSTER, - }), - ), -); -const discoverInput = z.object({ domain: z.string().nullable().default("seats") }); -const discoverSeats = sequencer({ name: "discover-seats", inputSchema: discoverInput }).step(discover); - -const desk = defineFlow({ - kind: "desk", - resources, - actions: { - hire: { inputSchema: hireInput, block: hire }, - list: { inputSchema: listInput, block: list }, - discover: { inputSchema: discoverInput, block: discoverSeats }, - }, -}); - -const verified = { - resolvePrincipal: (context: { request?: Request }) => { - const userId = context.request?.headers.get("x-verified-user"); - const orgId = context.request?.headers.get("x-verified-org"); - return userId && orgId ? { userId, orgId } : null; - }, -}; - -type Who = { user: string; org: string }; - -async function call(router: Router, method: "GET" | "POST", path: string[], body?: unknown, who?: Who) { - const headers: Record = { "content-type": "application/json" }; - if (who !== undefined) { - headers["x-verified-user"] = who.user; - headers["x-verified-org"] = who.org; - } - const response = await router[method]( - new Request(`http://goal/api/flows/${path.join("/")}`, { - method, - headers, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }), - { params: { path } }, - ); - const text = await response.text(); - return { status: response.status, json: text.length > 0 ? JSON.parse(text) : undefined }; -} - -function unwrap(output: unknown): unknown { - return typeof output === "object" && output !== null && (output as { kind?: unknown }).kind === "inline" - ? (output as { value: unknown }).value - : output; -} - -/** - * Open a session, run one action, wait for it to settle, and return the - * outputs its blocks recorded. An action's return value rides its blocks' - * trace rows; the request record has no `output` field of its own. - */ -async function runAction( - app: ReturnType, - userId: string, - action: string, - input: unknown, - who?: Who, -): Promise<{ outcome: string; outputs: unknown[]; detail?: unknown }> { - const router = (await app.getRouter()) as Router; - const session = await call(router, "POST", ["desk", "sessions"], { userId }, who); - if (session.status !== 201) return { outcome: `http-${session.status}`, outputs: [], detail: session.json }; - const sessionId = session.json.session.id as string; - const posted = await call(router, "POST", ["desk", sessionId, "actions", action], { userId, input }, who); - if (posted.status >= 400) return { outcome: `http-${posted.status}`, outputs: [], detail: posted.json }; - const requestId = posted.json.request?.id as string; - const stores = (await app.getRuntime()).stores; - for (let i = 0; i < 400; i++) { - const record = (await stores.request.get(requestId)) as - | { status?: string; error?: unknown; items?: Array> } - | undefined; - if (record?.status !== undefined && !["pending", "in_progress", "running", "queued"].includes(record.status)) { - const outputs = (record.items ?? []) - .filter((item) => item.type === "block_trace") - .map((item) => unwrap(item.output)); - return { outcome: record.status, outputs, detail: record.error }; - } - await new Promise((r) => setTimeout(r, 5)); - } - return { outcome: "timed-out", outputs: [] }; -} - -/** The seats domain out of a `discover` run, wherever in the trace it landed. */ -function seatsDomain(outputs: unknown[]): DomainResult | undefined { - for (const output of outputs) { - const domains = (output as { domains?: DomainResult[] } | undefined)?.domains; - const seats = domains?.find((domain) => domain.domain === "seats"); - if (seats !== undefined) return seats; - } - return undefined; -} - -await runGoal(async () => { - const failures: string[] = []; - const fail = (leg: string, line: string) => failures.push(`[${leg}] ${line}`); - const stores = inMemoryStores(); - - // (a) An app with no resolver: the file-declared seat is registered, and a - // runtime hire leaves a roster row under DEFAULT_ORG_ID. - const devApp = createFlowState({ flows: { desk: desk() }, stores: { default: { primary: stores } } }); - const listed = await runAction(devApp, fixture.devUser, "list", { id: fixture.fileSeatId }); - if (listed.outcome !== "completed") fail("a", `registering the file seat did not complete: ${JSON.stringify(listed)}`); - const devHire = await runAction(devApp, fixture.devUser, "hire", { seatId: fixture.devHireSeatId }); - if (devHire.outcome !== "completed") fail("a", `dev hire did not complete: ${JSON.stringify(devHire)}`); - const devRow = await (await devApp.getRuntime()).stores.resourceState.get( - "org", - DEFAULT_ORG_ID, - `workforce/roster/${fixture.devHireSeatId}`, - ); - if (devRow === undefined) fail("a", `no roster row landed under ${DEFAULT_ORG_ID}`); - - // (b) The dev session asks who it can hand work to. - const devDiscover = await runAction(devApp, fixture.devUser, "discover", { domain: "seats" }); - const devSeats = seatsDomain(devDiscover.outputs); - if (devDiscover.outcome !== "completed" || devSeats === undefined) { - fail("b", `dev discover returned no seats domain: ${JSON.stringify(devDiscover)}`); - } else { - if (devSeats.problem !== undefined) fail("b", `the dev org's seats domain degraded to a problem: ${devSeats.problem}`); - const file = devSeats.entries.find((entry) => entry.id === fixture.fileSeatId); - if (file === undefined || file.purpose !== fixture.fileSeatPurpose) { - fail("b", `the file-declared seat was not listed with its purpose: ${JSON.stringify(devSeats.entries)}`); - } - } - - // (c) A signed-in org hires one good seat. Beside it in the same cell: a row - // whose seat id carries the user-owned `~` marker, and a row stamped for - // another org (FIX-1529's fence) whose inventory row also exists. - const namedApp = createFlowState({ - flows: { desk: desk() }, - resolvePrincipal: verified.resolvePrincipal, - stores: { default: { primary: stores } }, - }); - const who = { user: fixture.namedUser, org: fixture.namedOrg }; - const namedAddress = `${fixture.namedOrg}.${fixture.namedSeatId}`; - const strayAddress = `${fixture.namedOrg}.${fixture.straySeatId}`; - const namedHire = await runAction( - namedApp, - fixture.namedUser, - "hire", - { seatId: fixture.namedSeatId, instructions: fixture.namedSeatInstructions, listedAs: namedAddress }, - who, - ); - if (namedHire.outcome !== "completed") fail("c", `named hire did not complete: ${JSON.stringify(namedHire)}`); - const primary = await stores.resolve(["primary"]); - await primary.resourceState!.set( - "org", - fixture.namedOrg, - `workforce/roster/${fixture.tildeSeatId}`, - toHiredSeatRow({ seatId: fixture.tildeSeatId, flow: "agent", owningOrgId: fixture.namedOrg }) as unknown as JsonObject, - "any", - ); - await primary.resourceState!.set( - "org", - fixture.namedOrg, - `workforce/roster/${fixture.straySeatId}`, - toHiredSeatRow({ seatId: fixture.straySeatId, flow: "agent", owningOrgId: fixture.strayOrg }) as unknown as JsonObject, - "any", - ); - await runAction(namedApp, fixture.namedUser, "list", { id: strayAddress }, who); - - const namedDiscover = await runAction(namedApp, fixture.namedUser, "discover", { domain: "seats" }, who); - const namedSeats = seatsDomain(namedDiscover.outputs); - if (namedDiscover.outcome !== "completed" || namedSeats === undefined) { - fail("c", `named discover returned no seats domain: ${JSON.stringify(namedDiscover)}`); - } else { - if (namedSeats.problem !== undefined) fail("c", `${fixture.namedOrg}'s seats domain degraded to a problem: ${namedSeats.problem}`); - const good = namedSeats.entries.find((entry) => entry.id === namedAddress); - if (good === undefined || good.purpose !== fixture.namedSeatInstructions) { - fail("c", `${namedAddress} was not listed with its instructions: ${JSON.stringify(namedSeats.entries)}`); - } - // (d) The stray row is withheld, not re-bound to the reading org. - if (namedSeats.entries.some((entry) => entry.id === strayAddress)) { - fail("d", `the row stamped for ${fixture.strayOrg} was listed as ${strayAddress}`); - } - } - - return { - failures, - evidence: - `dev roster row stored under ${DEFAULT_ORG_ID}; dev discover listed ` + - `${JSON.stringify(devSeats?.entries.map((entry) => entry.id))} with no problem; ` + - `${fixture.namedOrg} discover listed ${JSON.stringify(namedSeats?.entries.map((entry) => entry.id))} ` + - `with no problem, beside a "${fixture.tildeSeatId}" row and a row stamped for ${fixture.strayOrg}`, - }; -}); diff --git a/goals/hire-plane/keeps-a-hired-seat-with-its-owner/fixtures/input.json b/goals/hire-plane/keeps-a-hired-seat-with-its-owner/fixtures/input.json deleted file mode 100644 index c07d8c4c77..0000000000 --- a/goals/hire-plane/keeps-a-hired-seat-with-its-owner/fixtures/input.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "ownerOrg": "acme", - "otherOrg": "globex", - "ownerUser": "alice", - "peerUser": "bob", - "foreignUser": "mallory", - "seatId": "research", - "legacySeatId": "eng.lead", - "secret": "ACME-ONLY-ROADMAP-MARKER", - "widePattern": "workforce/[area]/[owner]/[seat]", - "managerId": "eng.manager", - "hiredSeatId": "analyst" -} diff --git a/goals/hire-plane/keeps-a-hired-seat-with-its-owner/goal.md b/goals/hire-plane/keeps-a-hired-seat-with-its-owner/goal.md deleted file mode 100644 index eab0d4ebd5..0000000000 --- a/goals/hire-plane/keeps-a-hired-seat-with-its-owner/goal.md +++ /dev/null @@ -1,36 +0,0 @@ -# hire-plane › it keeps a hired seat with its owner - -**Issue:** FIX-1529 (leg h: FIX-1542) -**Outcome:** A seat hired for one person in one organization stays there. A teammate cannot list, open, or run it. Another organization cannot either, including after the process restarts and the row is read back. The org roster's browser collection does not hand back that person's private row, and in an app that installs the private roster collection, a flow whose collection pattern could resolve onto those rows is not admitted. -**Input:** `fixtures/input.json` — two orgs, three users, two seat ids, the private marker, and the wide pattern. Held-out: every id and the marker are read from the fixture and graded against HTTP responses and the `seen/*` rows the actions write. Swapping any of them must still pass. -**Signal:** against `createFlowState`'s HTTP router, in-memory stores, no model. -(a) The owner opens the seat and the action writes the fixture marker into her organization's `seen` row. -(b) The teammate's `POST` to open that seat is `404`, and so is the other organization's. Neither write creates a `seen` row. -(c) `GET /api/flows` for the owner lists the seat. The same call for the other organization, and with no identity, does not. A shared app flow stays listed for the other organization, and that organization can run it. -(d) After the seat is released and registered again under the other organization's pin, the owner's old session resumes as `404` and the marker is not written again. -(e) A private roster row holding the marker is invisible to the teammate's read through the browser collection: the action records `undefined`, and the marker is absent. -(f) The app flow declares `defineHiredRosterPrivateCollection()`. Registering a flow that declares the fixture's wide pattern then throws, and no `seen` row from that flow contains the marker. -(g) A stored row whose `owningOrgId` is the other organization is a reload problem. Opening the address it would have minted is `404`. -(h) A manager seat calls `createSeatHireCapability`'s `hire` under the owner organization, with the fixture marker as instructions. The row it wrote is copied as-is into both organizations' roster cells. Reloaded in the owner organization it mints; reloaded in the other it is a named problem and mints nothing. The other organization's user opens the address the copy would have minted and gets `404`, so the marker is never read there. - -**Anti-game:** a hollow pass would assert that `ownerPin` is set, or that some request returned 404, without an owner run that actually writes the marker — both hold if every address 404s, and the pin field holds if admission never consults it. So the check MUST see the marker written by the owner, MUST see that same marker absent from the teammate's and the other organization's reads, MUST see the shared app flow still run for the other organization, and MUST grade the catalog by who is asking. It must not grade `pinOf` or the address string. For (h), a refused reload proves nothing on its own, because a broken row is refused everywhere: the same copied row MUST mint in the owner organization, and the row MUST come from the real `hire` tool, not be hand-written with a stamp. -**Model:** n/a — handlers only. The property is who can open and read the seat, not model output. -**Run:** `pnpm tsx goals/hire-plane/keeps-a-hired-seat-with-its-owner/run.mts` -**Controls:** none in the runner. The red state is a source revert, so it fails for the reason a missing fence fails and not because the runner skipped a leg. -- Drop the collection pattern check from `getOptional` in `packages/engine/src/context/resource-registry.ts`, and make `ownerKeyAdmits` and `ownerKeyMaySeed` return `true` in `packages/engine/src/resources/owner-private.ts`. Must FAIL leg (e) only. Dropping the pattern check alone leaves leg (e) green, because the two key fences still hold the row back. -- Make `patternsReach` return false in `packages/engine/src/resources/owner-private.ts`. Must FAIL leg (f) only. -- Drop `owningOrgId: orgId` from the `hire` tool's `toHiredSeatRow` call in `packages/workforce/src/seat-hire-capability.ts`, then rebuild workforce. Must FAIL leg (h) only. - -## Verdict log -| Date | Commit | Model | Verdict | Notes | -|------|--------|-------|---------|-------| -| 2026-09-23 | `ef5228f8b` with the collection pattern check removed from `packages/engine/src/context/resource-registry.ts`, then restored | n/a | FAIL (expected) | **Leg (e) only.** `browser read returned` the JSON row whose `instructions` were `ACME-ONLY-ROADMAP-MARKER`, and `browser read contained the marker`. No other goal leg failed. Same revert, outside the goal: fence D expected instructions `undefined` and received `ALICE-PRIVATE: my research assistant`; the resource-collection pattern case expected `getOptional` of `positions/AAPL/history` to be undefined and received the collection ref. Restored with `git checkout -- packages/engine/src/context/resource-registry.ts`. | -| 2026-09-23 | `ef5228f8b` with `rosterPatternOverlapsPrivate` forced to `return false`, then restored | n/a | FAIL (expected) | **Goal leg (f) only:** `pattern workforce/[area]/[owner]/[seat] was admitted`. The other goal legs stayed green. Blast radius outside the goal, because that predicate is also the gate for a literally deep roster pattern: the engine fence test that registers `workforce/roster/**` failed at its first assertion (`expected to throw`), so the wide-pattern expects later in that same test did not run. The workforce test that defines `workforce/roster/**` failed the same way. The other 12 fence tests and the other 7 hire-plane tests stayed green. Restored with `git checkout -- packages/core/src/types/collection-patterns.ts`. | -| 2026-09-23 | `ef5228f8b` (fence restored; this goal is the check that ran against it) | n/a | PASS | `pnpm tsx goals/hire-plane/keeps-a-hired-seat-with-its-owner/run.mts` exit 0. Owner wrote `ACME-ONLY-ROADMAP-MARKER` at `acme.~alice.research`; teammate and globex got 404; catalog listed the seat for the owner only; resume after re-pin was 404; browser read was `undefined`; `workforce/[area]/[owner]/[seat]` was refused; a row owned by globex was a reload problem and did not open. Shared app still ran for globex. After the restore, fence 13 and workforce hire-plane 8 were green. | -| 2026-09-23 | `4f03faef2` with `owningOrgId: orgId` dropped from the `hire` tool's row in `packages/workforce/src/seat-hire-capability.ts`, workforce rebuilt, then restored | n/a | FAIL (expected) | **Leg (h) only:** `reload in globex minted globex.analyst from the copied row`, `reported no problem for the copied row`, `globex opened the copied seat as 201`, and `globex ran the copied seat and read the marker`. Legs (a)–(g) stayed green, and the same row still minted `acme.analyst` in acme. Same revert, outside the goal: the workforce test "stamps the row with the principal's org" failed (`expected null to be 'acme'`); the other 755 stayed green. Restored with `git checkout -- packages/workforce/src/seat-hire-capability.ts`. | -| 2026-09-23 | `4f03faef2` (stamp restored) | n/a | PASS | Legs (a)–(h) green. The capability's `analyst` row reloaded in acme and was a named reload problem in globex, where `globex.analyst` opened as 404. Workforce 756/756. | -| 2026-09-24 | `f8c299b8e` + FIX-1549 PR-A, with the app flow's `defineHiredRosterPrivateCollection()` not yet installed | n/a | FAIL (expected) | **Leg (f) only:** `pattern workforce/[area]/[owner]/[seat] was admitted`. Registration's check now runs only in a registry that holds an owner-private collection, and this app did not install one. The runner now installs the private roster on the app flow, the shape a Workforce app hiring user-owned seats has. | -| 2026-09-24 | `f8c299b8e` + FIX-1549 PR-A, with only the collection pattern check dropped from `getOptional`, then restored | n/a | PASS | The old leg (e) control no longer goes red: the key fence and the seed fence each still keep `~alice/research` from the teammate. The control is now all three together (next row). | -| 2026-09-24 | `f8c299b8e` + FIX-1549 PR-A, with the pattern check dropped from `getOptional` and `ownerKeyAdmits` and `ownerKeyMaySeed` forced to `true`, then restored | n/a | FAIL (expected) | **Leg (e) only:** `browser read returned` the JSON row whose `instructions` were `ACME-ONLY-ROADMAP-MARKER`, and `browser read contained the marker`. Legs (a)–(d) and (f)–(h) stayed green. | -| 2026-09-24 | `f8c299b8e` + FIX-1549 PR-A, with `patternsReach` forced to `return false`, then restored | n/a | FAIL (expected) | **Leg (f) only:** `pattern workforce/[area]/[owner]/[seat] was admitted`. | -| 2026-09-24 | `f8c299b8e` + FIX-1549 PR-A (private roster installed on the app flow) | n/a | PASS | `pnpm tsx goals/hire-plane/keeps-a-hired-seat-with-its-owner/run.mts` exit 0. Every leg green; `workforce/[area]/[owner]/[seat]` was refused. | diff --git a/goals/hire-plane/keeps-a-hired-seat-with-its-owner/run.mts b/goals/hire-plane/keeps-a-hired-seat-with-its-owner/run.mts deleted file mode 100644 index 0ac743355f..0000000000 --- a/goals/hire-plane/keeps-a-hired-seat-with-its-owner/run.mts +++ /dev/null @@ -1,465 +0,0 @@ -/** - * Goal check — a hired seat stays with the organization and the user that - * hired it, on the HTTP router, with no model. - * - * See goal.md for the contract, including the three source-revert controls. - * - * Run: pnpm tsx goals/hire-plane/keeps-a-hired-seat-with-its-owner/run.mts - */ -import { defineFlow, defineResourceCollection, handler, type FlowInstance } from "@flow-state-dev/core"; -import { createFlowState, executeBlock, inMemoryStores } from "@flow-state-dev/engine"; -import type { ResourceCollectionRef } from "@flow-state-dev/core/types"; -import { - createSeatHireCapability, - defineAgentWorkerFlow, - defineHiredRosterCollection, - defineHiredRosterPrivateCollection, - encodeUserSegment, - hireWorkforce, - reloadHiredSeats, - seatAddress, - workerConfigSchema, - type HireOptions, -} from "@flow-state-dev/workforce"; -import { createTestContext, mockGenerator } from "@flow-state-dev/testing"; -import { z } from "zod"; -import { loadFixture, runGoal, stripIntentOverrides, workerDoor } from "../../lib/index.mts"; - -type Fixture = { - ownerOrg: string; - otherOrg: string; - ownerUser: string; - peerUser: string; - foreignUser: string; - seatId: string; - legacySeatId: string; - secret: string; - widePattern: string; - managerId: string; - hiredSeatId: string; -}; - -type Who = { user: string; org: string }; - -stripIntentOverrides(); - -const fixture = loadFixture(import.meta.url); -const tagInput = z.object({ tag: z.string() }); - -const resources = { - seen: defineResourceCollection({ - pattern: "seen/*", - scope: "org", - stateSchema: z.object({ - instance: z.string(), - as: z.string(), - instructions: z.string().nullable(), - }), - client: { state: { read: true } }, - }), - roster: defineHiredRosterCollection(), -}; - -const verified = { - resolvePrincipal: (context: { request?: Request }) => { - const userId = context.request?.headers.get("x-verified-user"); - const orgId = context.request?.headers.get("x-verified-org"); - return userId && orgId ? { userId, orgId } : null; - }, -}; - -const whoami = handler({ - name: "whoami", - inputSchema: tagInput, - outputSchema: z.object({ ok: z.boolean() }), - resources, - execute: async (input, ctx) => { - const seen = ctx.resources.seen as unknown as ResourceCollectionRef; - const config = ctx.flow.config as { instructions?: string }; - const instance = (ctx.flow as unknown as { id: string }).id; - const { userId = "", orgId = "" } = ctx.session.identity; - await seen.create(input.tag, { - instance, - as: `${userId}@${orgId}`, - instructions: config.instructions ?? null, - }); - return { ok: true }; - }, -}); - -const peekBrowser = handler({ - name: "peek-browser", - inputSchema: tagInput, - outputSchema: z.object({ ok: z.boolean() }), - resources, - execute: async (input, ctx) => { - const ref = ctx.resources.roster as unknown as ResourceCollectionRef; - const key = `~${encodeUserSegment(fixture.ownerUser)}/${fixture.seatId}`; - let got: string; - try { - const row = await ref.getOptional(key); - got = row === undefined ? "undefined" : JSON.stringify(row.state); - } catch (error) { - got = `threw: ${(error as Error).message}`; - } - const seen = ctx.resources.seen as unknown as ResourceCollectionRef; - const { userId = "", orgId = "" } = ctx.session.identity; - await seen.create(input.tag, { - instance: "peek-browser", - as: `${userId}@${orgId}`, - instructions: got, - }); - return { ok: true }; - }, -}); - -const seatKind = defineFlow({ - kind: "seat", - cardinality: "collection", - configSchema: z.object({ instructions: z.string().nullable().default(null) }), - resources, - actions: { ...workerDoor, whoami: { inputSchema: tagInput, block: whoami } }, - authentication: verified, -}); - -// The app hires user-owned seats, so it installs the private roster beside -// the browser roster. Holding that owner-private collection is what arms -// registration's check, which leg (f) grades. -const appFlow = defineFlow({ - kind: "app", - resources: { ...resources, rosterPrivate: defineHiredRosterPrivateCollection() }, - actions: { - whoami: { inputSchema: tagInput, block: whoami }, - peekBrowser: { inputSchema: tagInput, block: peekBrowser }, - }, - authentication: verified, -}); - -const owner: Who = { user: fixture.ownerUser, org: fixture.ownerOrg }; -const peer: Who = { user: fixture.peerUser, org: fixture.ownerOrg }; -const foreign: Who = { user: fixture.foreignUser, org: fixture.otherOrg }; -const ownedAddress = seatAddress(fixture.ownerOrg, fixture.seatId, fixture.ownerUser); -const legacyAddress = seatAddress(fixture.ownerOrg, fixture.legacySeatId); -const claimedAddress = seatAddress(fixture.ownerOrg, "claimed"); - -await runGoal(async () => { - const failures: string[] = []; - const fail = (leg: string, line: string) => failures.push(`[${leg}] ${line}`); - const stores = inMemoryStores(); - const state = createFlowState({ - flows: { app: appFlow() }, - resolvePrincipal: verified.resolvePrincipal, - stores: { default: { primary: stores } }, - }); - const router = (await state.getRouter()) as { - GET: (request: Request, ctx: { params: { path: string[] } }) => Promise; - POST: (request: Request, ctx: { params: { path: string[] } }) => Promise; - }; - const runtime = await state.getRuntime(); - - const call = async (method: "GET" | "POST", path: string[], who?: Who, body?: unknown) => { - const headers: Record = { "content-type": "application/json" }; - if (who !== undefined) { - headers["x-verified-user"] = who.user; - headers["x-verified-org"] = who.org; - } - const response = await router[method]( - new Request(`http://goal/api/flows/${path.join("/")}`, { - method, - headers, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }), - { params: { path } }, - ); - const text = await response.text(); - return { status: response.status, json: text.length > 0 ? JSON.parse(text) : undefined }; - }; - - const seenInstructions = async (org: string, tag: string): Promise => { - const row = (await runtime.stores.resourceState.get("org", org, `seen/${tag}`)) as - | { state?: { instructions?: string } } - | undefined; - return row?.state?.instructions ?? undefined; - }; - - const open = async (who: Who, address: string) => - call("POST", [address, "sessions"], who, { userId: who.user }); - - const run = async (who: Who, sessionId: string, action: string, tag: string, address = "app") => { - const posted = await call("POST", [address, sessionId, "actions", action], who, { - userId: who.user, - input: { tag }, - }); - if (posted.status >= 400) return { http: posted.status, error: posted.json?.error as string | undefined }; - const requestId = posted.json.request?.id as string; - for (let i = 0; i < 100; i++) { - const status = (await call("GET", [address, "requests", requestId, "status"], who)).json - ?.status as string | undefined; - if (status && !["pending", "in_progress", "running", "queued"].includes(status)) { - return { http: posted.status, outcome: status }; - } - await new Promise((r) => setTimeout(r, 5)); - } - return { http: posted.status, outcome: "timed-out" }; - }; - - const catalogIds = async (who?: Who): Promise => { - const listed = await call("GET", [], who); - const flows = (listed.json?.flows ?? []) as { id: string }[]; - return flows.map((flow) => flow.id); - }; - - state.register( - seatKind({ id: ownedAddress, config: { instructions: fixture.secret } }) as unknown as FlowInstance, - { pin: { orgId: fixture.ownerOrg, userId: fixture.ownerUser } }, - ); - - const ownerSession = await open(owner, ownedAddress); - if (ownerSession.status !== 201) { - fail("a", `owner open returned ${ownerSession.status} ${JSON.stringify(ownerSession.json)}`); - } else { - const ran = await run(owner, ownerSession.json.session.id as string, "whoami", "owner", ownedAddress); - if (ran.outcome !== "completed") fail("a", `owner run did not complete: ${JSON.stringify(ran)}`); - const wrote = await seenInstructions(fixture.ownerOrg, "owner"); - if (wrote !== fixture.secret) fail("a", `owner seen instructions were ${JSON.stringify(wrote)}`); - } - - const peerOpen = await open(peer, ownedAddress); - if (peerOpen.status !== 404) fail("b", `teammate open returned ${peerOpen.status}`); - if ((await seenInstructions(fixture.ownerOrg, "peer")) !== undefined) { - fail("b", "teammate open wrote a seen row"); - } - - const foreignOpen = await open(foreign, ownedAddress); - if (foreignOpen.status !== 404) fail("c", `other org open returned ${foreignOpen.status}`); - const ownerCatalog = await catalogIds(owner); - const foreignCatalog = await catalogIds(foreign); - const anonymousCatalog = await catalogIds(); - if (!ownerCatalog.includes(ownedAddress)) fail("c", "owner catalog omitted the seat"); - if (foreignCatalog.includes(ownedAddress)) fail("c", "other org catalog listed the seat"); - if (anonymousCatalog.includes(ownedAddress)) fail("c", "anonymous catalog listed the seat"); - if (!foreignCatalog.includes("app")) fail("c", "other org catalog omitted the shared app flow"); - const foreignApp = await open(foreign, "app"); - if (foreignApp.status !== 201) fail("c", `shared app open for the other org returned ${foreignApp.status}`); - else { - const ran = await run(foreign, foreignApp.json.session.id as string, "whoami", "shared"); - if (ran.outcome !== "completed") fail("c", `shared app did not run: ${JSON.stringify(ran)}`); - } - - const resumeSession = ownerSession.json?.session?.id as string | undefined; - state.unregister(ownedAddress); - state.register( - seatKind({ id: ownedAddress, config: { instructions: fixture.secret } }) as unknown as FlowInstance, - { pin: { orgId: fixture.otherOrg, userId: fixture.foreignUser } }, - ); - if (resumeSession !== undefined) { - const resumed = await run(owner, resumeSession, "whoami", "resumed", ownedAddress); - if (resumed.http !== 404) fail("d", `resume after re-pin returned ${JSON.stringify(resumed)}`); - if ((await seenInstructions(fixture.ownerOrg, "resumed")) !== undefined) { - fail("d", "resume wrote the marker"); - } - } - - const primary = await stores.resolve(["primary"]); - await primary.resourceState!.set( - "org", - fixture.ownerOrg, - `workforce/roster/~${encodeUserSegment(fixture.ownerUser)}/${fixture.seatId}`, - { - seatId: fixture.seatId, - flow: "seat", - settings: {}, - instructions: fixture.secret, - owningOrgId: fixture.ownerOrg, - ownerUserId: fixture.ownerUser, - }, - "any", - ); - const peerApp = await open(peer, "app"); - if (peerApp.status !== 201) fail("e", `teammate app open returned ${peerApp.status}`); - else { - const ran = await run(peer, peerApp.json.session.id as string, "peekBrowser", "browser"); - if (ran.outcome !== "completed") fail("e", `browser read did not complete: ${JSON.stringify(ran)}`); - const got = await seenInstructions(fixture.ownerOrg, "browser"); - if (got !== "undefined") fail("e", `browser read returned ${JSON.stringify(got)}`); - if (got?.includes(fixture.secret)) fail("e", "browser read contained the marker"); - } - - let wideRefused = ""; - try { - const wide = defineFlow({ - kind: "wide", - resources: { - ...resources, - wide: defineResourceCollection({ - pattern: fixture.widePattern, - scope: "org", - stateSchema: z.object({}).passthrough(), - }), - }, - actions: { - whoami: { inputSchema: tagInput, block: whoami }, - }, - authentication: verified, - })(); - state.register(wide); - wideRefused = ""; - } catch (error) { - wideRefused = (error as Error).message; - } - if (wideRefused.length === 0) { - fail("f", `pattern ${fixture.widePattern} was admitted`); - } else if (!wideRefused.includes(fixture.widePattern)) { - fail("f", `refusal did not name the pattern: ${wideRefused}`); - } - if ((await seenInstructions(fixture.ownerOrg, "wide"))?.includes(fixture.secret)) { - fail("f", "admitted pattern wrote the marker"); - } - - state.unregister(ownedAddress); - await primary.resourceState!.set( - "org", - fixture.ownerOrg, - `workforce/roster/${fixture.legacySeatId}`, - { - seatId: fixture.legacySeatId, - flow: "seat", - settings: {}, - instructions: fixture.secret, - owningOrgId: fixture.otherOrg, - ownerUserId: null, - }, - "any", - ); - const reloaded = await reloadHiredSeats({ - stores: runtime.stores, - orgIds: [fixture.ownerOrg], - workerFlows: { seat: seatKind }, - }); - const claimed = reloaded.seats.find((seat) => seat.id === claimedAddress || seat.id === legacyAddress); - if (claimed !== undefined) fail("g", `reload minted ${claimed.id}`); - if (reloaded.problems.length === 0) fail("g", "reload reported no problem for the foreign owning org"); - const claimedOpen = await open(foreign, legacyAddress); - if (claimedOpen.status !== 404) fail("g", `foreign-owned row opened as ${claimedOpen.status}`); - - // (h) A row the seat-hire capability wrote, copied into another org's cell, - // is refused on reload. The hire is a manager seat calling `hire` under the - // owner org; the stored value is then copied as-is into both cells. - const hiredKind = defineFlow({ - kind: "hired", - cardinality: "collection", - configSchema: workerConfigSchema(), - resources, - actions: { ...workerDoor, whoami: { inputSchema: tagInput, block: whoami } }, - authentication: verified, - }); - const hireKinds: NonNullable = { hired: hiredKind }; - const seatHire = createSeatHireCapability({ - workerFlows: hireKinds, - register: (seat, pin) => state.register(seat, { pin }), - unregister: (id) => state.unregister(id), - kindAt: (id) => runtime.registry.get(id)?.kind, - instanceAt: (id) => runtime.registry.get(id), - }); - hireKinds.agent = defineAgentWorkerFlow({ uses: [seatHire] }); - const [manager] = hireWorkforce( - [{ id: fixture.managerId, declared: { tools: ["hire"] }, body: "Expands the roster." }], - { workerFlows: hireKinds }, - ); - const hiredAddress = seatAddress(fixture.ownerOrg, fixture.hiredSeatId); - const copiedAddress = seatAddress(fixture.otherOrg, fixture.hiredSeatId); - const rosterKey = `workforce/roster/${fixture.hiredSeatId}`; - let copied: unknown; - if (manager === undefined) { - fail("h", "hireWorkforce minted no manager"); - } else { - const hireRun = await createTestContext({ - flow: { ...manager, cardinality: "singleton" }, - orgId: fixture.ownerOrg, - org: { state: {} }, - sessionId: "goal-hire", - sequencerName: manager.actions.run!.block.name, - declaredResources: manager.actions.run!.block.declaredResources, - generators: { - "agent-answer": mockGenerator({ - name: "agent-answer", - script: [ - { - toolCalls: [ - { - toolCallId: "hire-1", - toolName: "hire", - args: { seatId: fixture.hiredSeatId, flow: "hired", instructions: fixture.secret }, - }, - ], - }, - { text: "done" }, - ] as never, - }), - }, - }); - const hired = await executeBlock({ - block: manager.actions.run!.block, - input: { message: "hire the named seat" }, - ctx: hireRun.ctx, - }); - if (hired.error !== undefined) fail("h", `capability hire failed: ${hired.error.message}`); - const written = (await hireRun.stores.resourceState.get("org", fixture.ownerOrg, rosterKey)) as - | { state?: unknown } - | undefined; - copied = written?.state; - if (copied === undefined) fail("h", `the capability wrote no row at ${rosterKey}`); - } - if (copied !== undefined) { - state.unregister(hiredAddress); - for (const org of [fixture.ownerOrg, fixture.otherOrg]) { - await primary.resourceState!.set("org", org, rosterKey, copied as never, "any"); - } - const home = await reloadHiredSeats({ - stores: runtime.stores, - orgIds: [fixture.ownerOrg], - workerFlows: hireKinds, - }); - if (!home.seats.some((seat) => seat.id === hiredAddress)) { - fail("h", `the capability's row did not reload in ${fixture.ownerOrg}: ${home.problems.join("; ")}`); - } - const away = await reloadHiredSeats({ - stores: runtime.stores, - orgIds: [fixture.otherOrg], - workerFlows: hireKinds, - }); - // What a host does with a reload: register each seat under its own pin. - for (const seat of away.seats) { - const pin = (seat as { ownerPin?: { orgId: string; userId?: string } }).ownerPin; - state.register(seat, pin === undefined ? undefined : { pin }); - } - if (away.seats.some((seat) => seat.id === copiedAddress)) { - fail("h", `reload in ${fixture.otherOrg} minted ${copiedAddress} from the copied row`); - } - if (!away.problems.some((problem) => problem.includes(fixture.hiredSeatId))) { - fail("h", `reload in ${fixture.otherOrg} reported no problem for the copied row`); - } - const copiedOpen = await open(foreign, copiedAddress); - if (copiedOpen.status !== 404) { - fail("h", `${fixture.otherOrg} opened the copied seat as ${copiedOpen.status}`); - if (copiedOpen.status === 201) { - await run(foreign, copiedOpen.json.session.id as string, "whoami", "copied", copiedAddress); - if ((await seenInstructions(fixture.otherOrg, "copied"))?.includes(fixture.secret)) { - fail("h", `${fixture.otherOrg} ran the copied seat and read the marker`); - } - } - } - } - - const evidence = - failures.length > 0 - ? "" - : `owner wrote ${fixture.secret} at ${ownedAddress}; teammate and ${fixture.otherOrg} got 404; ` + - `catalog listed the seat for the owner only; resume after re-pin was 404; ` + - `browser read was undefined; ${fixture.widePattern} was refused; ` + - `a row owned by ${fixture.otherOrg} was a reload problem and did not open; ` + - `the capability's ${fixture.hiredSeatId} row reloaded in ${fixture.ownerOrg} and was a ` + - `reload problem in ${fixture.otherOrg}, where ${copiedAddress} did not open. ` + - `Shared app still ran for ${fixture.otherOrg}.`; - return { failures, evidence }; -}); diff --git a/goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/fixtures/input.json b/goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/fixtures/input.json deleted file mode 100644 index 8aea2d8174..0000000000 --- a/goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/fixtures/input.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "ownerOrg": "acme", - "otherOrg": "globex", - "ownerUser": "alice", - "peerUser": "bob", - "seatId": "research", - "hireInstructions": "ALICE-PRIVATE-HIRE-INSTRUCTIONS", - "marker": "ACME-ALICE-SAVED-MARKER" -} diff --git a/goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/goal.md b/goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/goal.md deleted file mode 100644 index 15e5eedd49..0000000000 --- a/goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/goal.md +++ /dev/null @@ -1,32 +0,0 @@ -# hire-plane › it keeps a private team in the org it was built in - -**Issue:** FIX-1538 (the assembled proof of epic FIX-1528, ER-15) -**Outcome:** A seat Alice hires for herself while signed in to Acme stays in Acme and stays hers, at every door and in what it saves. Alice signed in to Globex, and Bob in Acme, cannot list, open, run, resume, drain work onto, or see it in the debug listing. What the seat saved for her is read back by her own next Acme run, and not by her Globex seat or Bob's Acme seat of the same kind, which both start empty. -**Input:** `fixtures/input.json`: two orgs, the owner and a teammate, the seat id, the owner's hire instructions and the marker she saves. Held-out: every id, the instructions and the marker are read from the fixture and graded against HTTP responses, the task ledger, the session store and the `seen/*` rows each run writes. Swapping any of them must still pass. -**Signal:** against `createFlowState`'s HTTP router and worker pool, in-memory stores, debug endpoints on, no model. Each person hires a private `research` seat through the app's owner-private roster collection; the host reloads the roster with `reloadHiredSeats` and registers each seat under the pin copied from its row. Callers: Alice in Acme (owner), Alice in Globex, Bob in Acme. -(a) The owner opens her private seat and its `save` action writes the marker to a shared user-scoped collection and to her user state. -(b) `GET /api/flows` lists the seat for the owner and for neither other caller. -(c) Opening a session on it is `404` for both others. -(d) A session-less action on it is `404` for both, and no `seen` row is written. -(e) An action on the owner's session is refused for both, and no `seen` row is written. -(f) A board in Globex drained by Alice, and a board in Acme drained by Bob, onto the seat: the row ends `errored` and unheld, no session is minted on the seat for that (user, org), and the seat's worker never runs. -(g) Neither other caller's debug resource listing contains the owner's private roster row; the owner's does. -(h) The owner's next run on the seat, in a fresh session, reads the marker from the collection and from user state. -(i) Alice's own Globex seat of the same kind reads no marker. -(j) Bob's Acme seat of the same kind reads no marker. - -**Anti-game:** a hollow pass would grade 404s and empty reads alone, which all hold if every seat is unreachable or stores nothing. So the check MUST see the owner's own save complete and her next run read the marker back from both halves (h), MUST see her debug listing contain her row (g), and MUST mint the three seats from real roster rows through `reloadHiredSeats` rather than hand-writing a pin. It must not grade storage keys, `ownerPin`, or the address string. (i) and (j) grade what a seat's own run read, not what the store holds. -**Model:** n/a (handlers only). The property is which cell a seat's run reads, and who reaches the seat, not model output. -**Run:** `pnpm tsx goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/run.mts` (after `pnpm --filter "@flow-state-dev/workforce..." build`) -**Controls:** none in the runner. The red state is a source revert of the key derivation in `packages/engine/src/stores/scope-keys.ts`, then an engine rebuild, so it fails the way a missing cell fails. -- Make `sharedUserKey` return today's key (the bare person) for a pinned flow. Must FAIL leg (i) only: (h) stays green because the owner still reads her own writes, and (j) stays green because Bob's person key was never Alice's. -- Drop the person from the cell, keying it by org alone. Must FAIL leg (j) only. - -The door legs (b)–(g) have their own source-revert controls in the sibling goals that introduced them; neither control above touches a door, so they stay green here by design. - -## Verdict log -| Date | Commit | Model | Verdict | Notes | -|------|--------|-------|---------|-------| -| 2026-09-24 | `7f51403a4` with `sharedUserKey` returning the bare person for a pinned flow, engine rebuilt, then restored | n/a | FAIL (expected) | **Leg (i) only:** `globex.~alice.research read {"seat":"globex.~alice.research","as":"alice@globex","notes":["ACME-ALICE-SAVED-MARKER"],"state":"ACME-ALICE-SAVED-MARKER"}`. Legs (a)–(h) and (j) stayed green. Same revert, outside the goal: engine 10 of 2687 failed, all in the two new seat-cell suites; scheduled 2 of 81 failed, both in the new seat-schedule suite. No pre-existing test failed. | -| 2026-09-24 | `7f51403a4` with the person dropped from the cell (org alone), engine rebuilt, then restored | n/a | FAIL (expected) | **Leg (j) only:** `acme.~bob.research read {"seat":"acme.~bob.research","as":"bob@acme","notes":["ACME-ALICE-SAVED-MARKER"],"state":"ACME-ALICE-SAVED-MARKER"}`. Legs (a)–(i) stayed green. | -| 2026-09-24 | `7f51403a4` (derivation restored, engine rebuilt) | n/a | PASS | Exit 0. alice@acme saved `ACME-ALICE-SAVED-MARKER`; for alice@globex and bob@acme the seat was unlisted, open 404, run 404, resume refused, drain errored unheld with no session minted, debug listing without the private row. The owner's next run read the marker from notes and state; `globex.~alice.research` and `acme.~bob.research` read `notes: []`, `state: null`. | diff --git a/goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/run.mts b/goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/run.mts deleted file mode 100644 index 9aa4bf3dd1..0000000000 --- a/goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/run.mts +++ /dev/null @@ -1,445 +0,0 @@ -/** - * Goal check — a person's private team stays in the organization it was built - * in: Alice's private Acme seat walked through every door and both halves of - * its stored-data cell, on the HTTP router and the worker pool, with no model. - * - * See goal.md for the contract, including the source-revert controls. - * - * Run: pnpm tsx goals/hire-plane/keeps-a-private-team-in-the-org-it-was-built-in/run.mts - */ -import { - defineFlow, - defineResourceCollection, - dispatcher, - handler, - type FlowInstance, -} from "@flow-state-dev/core"; -import { createFlowState, inMemoryStores } from "@flow-state-dev/engine"; -import type { JsonObject, ResourceCollectionRef } from "@flow-state-dev/core/types"; -import { taskBoard, taskWorkerInputSchema } from "@flow-state-dev/orchestration/task-board"; -import { - defineTaskCollection, - type Task, - type TaskWorkerInput, -} from "@flow-state-dev/orchestration/tasks"; -import { - defineHiredRosterPrivateCollection, - hiredRosterStorageKey, - reloadHiredSeats, - seatAddress, - toHiredSeatRow, - workerConfigSchema, -} from "@flow-state-dev/workforce"; -import { z } from "zod"; -import { loadFixture, runGoal, stripIntentOverrides, workerDoor } from "../../lib/index.mts"; - -type Fixture = { - ownerOrg: string; - otherOrg: string; - ownerUser: string; - peerUser: string; - seatId: string; - hireInstructions: string; - marker: string; -}; - -type Who = { user: string; org: string }; - -stripIntentOverrides(); - -const fixture = loadFixture(import.meta.url); -const BOARD_ID = "team-work"; -const LEDGER_ID = "team-work-ledger"; -const ROW = "t-private-seat"; - -const verified = { - resolvePrincipal: (context: { request?: Request }) => { - const userId = context.request?.headers.get("x-verified-user"); - const orgId = context.request?.headers.get("x-verified-org"); - return userId && orgId ? { userId, orgId } : null; - }, -}; - -const tagInput = z.object({ tag: z.string() }); -const saveInput = z.object({ tag: z.string(), marker: z.string() }); - -/** The seat's shared user-scoped memory: what the cell holds. */ -const notes = defineResourceCollection({ - pattern: "notes/*", - scope: "user", - stateSchema: z.object({ marker: z.string() }), -}); - -/** Org-scoped record of what a run saw or did, so every leg grades a real write. */ -const seen = defineResourceCollection({ - pattern: "seen/*", - scope: "org", - stateSchema: z.object({ - seat: z.string(), - as: z.string(), - notes: z.array(z.string()), - state: z.string().nullable(), - }), -}); - -const whoAmI = (ctx: { session: { identity: { userId?: string; orgId?: string } } }) => - `${ctx.session.identity.userId ?? ""}@${ctx.session.identity.orgId ?? ""}`; -const seatOf = (ctx: { flow: unknown }) => (ctx.flow as { id: string }).id; - -const save = handler({ - name: "save", - inputSchema: saveInput, - outputSchema: z.object({ ok: z.boolean() }), - resources: { notes, seen }, - execute: async (input, ctx) => { - await (ctx.resources.notes as unknown as ResourceCollectionRef).create(input.tag, { - marker: input.marker, - }); - await ctx.user.patchState({ marker: input.marker }); - return { ok: true }; - }, -}); - -const read = handler({ - name: "read", - inputSchema: tagInput, - outputSchema: z.object({ ok: z.boolean() }), - resources: { notes, seen }, - execute: async (input, ctx) => { - const rows = await (ctx.resources.notes as unknown as ResourceCollectionRef).list(); - await (ctx.resources.seen as unknown as ResourceCollectionRef).create(input.tag, { - seat: seatOf(ctx), - as: whoAmI(ctx), - notes: rows.map((row) => String((row.state as { marker: string }).marker)), - state: (ctx.user.state as { marker?: string | null }).marker ?? null, - }); - return { ok: true }; - }, -}); - -/** A board hand-off onto the seat; it records the run, so a refused one leaves nothing. */ -const seatWork = handler({ - name: "seat-work", - inputSchema: taskWorkerInputSchema, - outputSchema: z.object({ handled: z.string() }), - resources: { notes, seen }, - execute: async (input: TaskWorkerInput, ctx) => { - await (ctx.resources.seen as unknown as ResourceCollectionRef).create(`drain-${input.taskId}`, { - seat: seatOf(ctx), - as: whoAmI(ctx), - notes: [], - state: null, - }); - return { handled: input.taskId }; - }, -}); - -const ledger = () => defineTaskCollection({ id: LEDGER_ID, scope: "org" }); - -const seatKind = defineFlow({ - kind: "research", - cardinality: "collection", - configSchema: workerConfigSchema(), - resources: { notes, seen }, - user: { stateSchema: z.object({ marker: z.string().nullable().default(null) }) }, - actions: { ...workerDoor, - save: { inputSchema: saveInput, block: save }, - read: { inputSchema: tagInput, block: read }, - // The seat's own board binds the claim gate on `work`; it holds no rows. - drain: { - block: taskBoard({ - name: "seat-board", - boardId: BOARD_ID, - collection: ledger(), - workers: { - work: dispatcher({ name: "seat-hand-off", action: "work", session: "per-task" }), - }, - }).drain, - }, - }, - task: { actions: { work: { block: seatWork } } }, - authentication: verified, -}); - -const ownerSeat = seatAddress(fixture.ownerOrg, fixture.seatId, fixture.ownerUser); -const ownerOtherOrgSeat = seatAddress(fixture.otherOrg, fixture.seatId, fixture.ownerUser); -const peerSeat = seatAddress(fixture.ownerOrg, fixture.seatId, fixture.peerUser); - -const boardFlow = defineFlow({ - kind: "board", - actions: { - start: { - block: taskBoard({ - name: "team-board", - boardId: BOARD_ID, - collection: ledger(), - workers: { - private: dispatcher({ - name: "to-private-seat", - flowKind: ownerSeat, - action: "work", - session: "per-task", - }), - }, - initialTasks: [{ id: ROW, goal: "work for the owner's private seat", assignee: "private", input: {} }], - }).drain, - }, - }, - authentication: verified, -}); - -const privateRoster = defineHiredRosterPrivateCollection(); - -/** Hires a private `research` seat for the session's user, through the owner-private roster collection. */ -const hire = handler({ - name: "hire", - inputSchema: z.object({}), - outputSchema: z.object({ ok: z.boolean() }), - resources: { privateRoster }, - execute: async (_input, ctx) => { - const { userId = "", orgId = "" } = ctx.session.identity; - const row = toHiredSeatRow({ - seatId: fixture.seatId, - flow: "research", - instructions: userId === fixture.ownerUser && orgId === fixture.ownerOrg ? fixture.hireInstructions : null, - owningOrgId: orgId, - ownerUserId: userId, - }); - const [owner, seat] = hiredRosterStorageKey(row).split("/"); - await (ctx.resources.privateRoster as unknown as ResourceCollectionRef).create( - { owner: owner!, seat: seat! }, - row as unknown as JsonObject, - ); - return { ok: true }; - }, -}); - -const appFlow = defineFlow({ - kind: "app", - resources: { privateRoster }, - actions: { hire: { inputSchema: z.object({}), block: hire } }, - authentication: verified, -}); - -const owner: Who = { user: fixture.ownerUser, org: fixture.ownerOrg }; -const ownerElsewhere: Who = { user: fixture.ownerUser, org: fixture.otherOrg }; -const peer: Who = { user: fixture.peerUser, org: fixture.ownerOrg }; -const outsiders: Array<[string, Who]> = [ - [`${ownerElsewhere.user}@${ownerElsewhere.org}`, ownerElsewhere], - [`${peer.user}@${peer.org}`, peer], -]; - -await runGoal(async () => { - const failures: string[] = []; - const fail = (leg: string, line: string) => failures.push(`[${leg}] ${line}`); - const state = createFlowState({ - flows: { app: appFlow(), board: boardFlow() }, - resolvePrincipal: verified.resolvePrincipal, - stores: { default: { primary: inMemoryStores() } }, - // What `fsdev dev` does; leg (g) only exists with it on. - debugEndpointsEnabled: true, - debugAllowAnonymousLocal: true, - }); - const router = (await state.getRouter()) as { - GET: (request: Request, ctx: { params: { path: string[] } }) => Promise; - POST: (request: Request, ctx: { params: { path: string[] } }) => Promise; - }; - const runtime = await state.getRuntime(); - - const call = async (method: "GET" | "POST", path: string[], who: Who, body?: unknown) => { - const response = await router[method]( - new Request(`http://goal/api/flows/${path.join("/")}`, { - method, - headers: { - "content-type": "application/json", - "x-verified-user": who.user, - "x-verified-org": who.org, - }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }), - { params: { path } }, - ); - const text = await response.text(); - let json: any; - try { - json = text.length > 0 ? JSON.parse(text) : undefined; - } catch { - json = undefined; - } - return { status: response.status, text, json }; - }; - - const open = (who: Who, flowId: string) => call("POST", [flowId, "sessions"], who, { userId: who.user }); - - /** POST an action, then wait for the request to settle. `sessionId` undefined = session-less. */ - const act = async (who: Who, flowId: string, sessionId: string | undefined, action: string, input: unknown) => { - const path = sessionId === undefined ? [flowId, "actions", action] : [flowId, sessionId, "actions", action]; - const posted = await call("POST", path, who, { userId: who.user, input }); - if (posted.status >= 400) return { http: posted.status, outcome: undefined as string | undefined }; - const requestId = posted.json.request?.id as string; - for (let i = 0; i < 300; i++) { - const status = (await call("GET", [flowId, "requests", requestId, "status"], who)).json?.status as - | string - | undefined; - if (status && !["pending", "in_progress", "running", "queued"].includes(status)) { - return { http: posted.status, outcome: status }; - } - await new Promise((r) => setTimeout(r, 5)); - } - return { http: posted.status, outcome: "timed-out" }; - }; - - const seenRow = async (org: string, tag: string) => - (await runtime.stores.resourceState.get("org", org, `seen/${tag}`))?.state as - | { seat: string; as: string; notes: string[]; state: string | null } - | undefined; - - /** A fresh session on `flowId`, a `read`, and what that run saw. */ - const readAs = async (leg: string, who: Who, flowId: string, tag: string) => { - const opened = await open(who, flowId); - if (opened.status !== 201) { - fail(leg, `${who.user}@${who.org} could not open ${flowId}: ${opened.status}`); - return undefined; - } - const ran = await act(who, flowId, opened.json.session.id as string, "read", { tag }); - if (ran.outcome !== "completed") fail(leg, `read on ${flowId} ended ${JSON.stringify(ran)}`); - const row = await seenRow(who.org, tag); - if (row === undefined) fail(leg, `read on ${flowId} recorded nothing`); - return row; - }; - - const sawMarker = (row: { notes: string[]; state: string | null } | undefined) => - row !== undefined && (row.notes.includes(fixture.marker) || row.state === fixture.marker); - - // Setup: each person hires a private `research` seat in their org through - // the app, and the host reloads the roster and registers every seat under - // the pin copied from its row — the path a restart takes. - for (const who of [owner, ownerElsewhere, peer]) { - const session = await open(who, "app"); - const hired = session.status === 201 ? await act(who, "app", session.json.session.id, "hire", {}) : undefined; - if (hired?.outcome !== "completed") fail("setup", `${who.user}@${who.org} hire ended ${JSON.stringify(hired)}`); - } - const reloaded = await reloadHiredSeats({ - stores: runtime.stores, - orgIds: [fixture.ownerOrg, fixture.otherOrg], - workerFlows: { research: seatKind }, - }); - if (reloaded.problems.length > 0) fail("setup", `reload problems: ${reloaded.problems.join("; ")}`); - for (const seat of reloaded.seats) { - const pin = (seat as FlowInstance).ownerPin; - state.register(seat as FlowInstance, pin === undefined ? undefined : { pin }); - } - const minted = reloaded.seats.map((seat) => seat.id).sort(); - const expected = [ownerSeat, ownerOtherOrgSeat, peerSeat].sort(); - if (JSON.stringify(minted) !== JSON.stringify(expected)) { - fail("setup", `reload minted ${JSON.stringify(minted)}, expected ${JSON.stringify(expected)}`); - return { failures, evidence: "" }; - } - - // (a) The owner opens her private seat and saves the marker to a shared - // user resource and to her user state. - const ownerOpen = await open(owner, ownerSeat); - const ownerSession = ownerOpen.status === 201 ? (ownerOpen.json.session.id as string) : undefined; - if (ownerSession === undefined) fail("a", `owner open returned ${ownerOpen.status}`); - else { - const saved = await act(owner, ownerSeat, ownerSession, "save", { tag: "saved", marker: fixture.marker }); - if (saved.outcome !== "completed") fail("a", `owner save ended ${JSON.stringify(saved)}`); - } - - // (b) The catalog lists the seat for the owner only. - const listed = async (who: Who) => - ((await call("GET", [], who)).json?.flows ?? []).map((flow: { id: string }) => flow.id) as string[]; - if (!(await listed(owner)).includes(ownerSeat)) fail("b", "the owner's catalog omitted her seat"); - for (const [name, who] of outsiders) { - if ((await listed(who)).includes(ownerSeat)) fail("b", `${name}'s catalog listed ${ownerSeat}`); - } - - for (const [name, who] of outsiders) { - // (c) Opening it is 404. - const opened = await open(who, ownerSeat); - if (opened.status !== 404) fail("c", `${name} opened ${ownerSeat} as ${opened.status}`); - // (d) Running an action on it is 404. - const ran = await act(who, ownerSeat, undefined, "read", { tag: `run-${who.user}-${who.org}` }); - if (ran.http !== 404) fail("d", `${name} ran an action on ${ownerSeat}: ${JSON.stringify(ran)}`); - // (e) Resuming the owner's session is refused. - if (ownerSession !== undefined) { - const resumed = await act(who, ownerSeat, ownerSession, "read", { tag: `resume-${who.user}-${who.org}` }); - if (resumed.http < 400) fail("e", `${name} resumed the owner's session: ${JSON.stringify(resumed)}`); - } - for (const tag of [`run-${who.user}-${who.org}`, `resume-${who.user}-${who.org}`]) { - for (const org of [fixture.ownerOrg, fixture.otherOrg]) { - if ((await seenRow(org, tag)) !== undefined) fail("d/e", `${name}'s refused call still ran (${tag})`); - } - } - } - - // (f) A board in each outsider's org, drained by that outsider, onto the - // seat: the row ends errored and unheld, and no session is minted. - for (const [name, who] of outsiders) { - const board = await open(who, "board"); - if (board.status !== 201) { - fail("f", `${name} could not open the board: ${board.status}`); - continue; - } - const drained = await act(who, "board", board.json.session.id as string, "start", {}); - if (drained.outcome !== "completed") fail("f", `${name}'s drain ended ${JSON.stringify(drained)}`); - let row: Task | undefined; - for (let i = 0; i < 100; i++) { - row = (await runtime.stores.resourceState.get("org", who.org, `${LEDGER_ID}/${ROW}`))?.state as Task | undefined; - if (row !== undefined && row.status !== "in_progress" && row.status !== "pending") break; - await new Promise((r) => setTimeout(r, 10)); - } - if (row?.status !== "errored") fail("f", `${name}'s row ended ${row?.status}, not errored`); - if (row?.claimedBy !== undefined) fail("f", `${name}'s row is still claimed by ${JSON.stringify(row.claimedBy)}`); - const sessions = await runtime.stores.session.list({ userId: who.user, parentage: "all" }); - // Same person in another org is still an outsider: count by (user, org). - const onSeat = sessions.filter((record) => record.flowId === ownerSeat && record.orgId === who.org).length; - if (onSeat > 0) fail("f", `${onSeat} session(s) minted on ${ownerSeat} for ${name}`); - if ((await seenRow(who.org, `drain-${ROW}`)) !== undefined) fail("f", `the seat ran ${name}'s hand-off`); - } - - // (g) With debug endpoints on, neither outsider's debug listing shows the - // owner's private roster row; the owner's own listing does. - const debugBody = async (who: Who) => { - const session = await open(who, "app"); - if (session.status !== 201) return { ok: false, body: "" }; - const base = ["sessions", session.json.session.id as string, "debug", "resources"]; - const tree = await call("GET", base, who); - const items = await call("GET", [...base, "privateRoster", "items"], who); - return { ok: tree.status === 200 && items.status === 200, body: tree.text + items.text }; - }; - const ownerDebug = await debugBody(owner); - if (!ownerDebug.ok || !ownerDebug.body.includes(fixture.hireInstructions)) { - fail("g", "the owner's debug listing did not show her private roster row"); - } - for (const [name, who] of outsiders) { - const debug = await debugBody(who); - if (!debug.ok) fail("g", `${name}'s debug reads were not all 200`); - if (debug.body.includes(fixture.hireInstructions)) fail("g", `${name}'s debug listing showed the owner's private row`); - } - - // (h) The owner's next run on her seat reads the marker back. - const back = await readAs("h", owner, ownerSeat, "owner-again"); - if (back !== undefined && !(back.notes.includes(fixture.marker) && back.state === fixture.marker)) { - fail("h", `the owner's next run read ${JSON.stringify(back)}, not ${fixture.marker} in notes and state`); - } - - // (i) Alice's own Globex seat of the same kind reads no marker. - const elsewhere = await readAs("i", ownerElsewhere, ownerOtherOrgSeat, "owner-in-other-org"); - if (sawMarker(elsewhere)) fail("i", `${ownerOtherOrgSeat} read ${JSON.stringify(elsewhere)}`); - - // (j) Bob's Acme seat of the same kind reads no marker. - const peers = await readAs("j", peer, peerSeat, "peer"); - if (sawMarker(peers)) fail("j", `${peerSeat} read ${JSON.stringify(peers)}`); - - await state.dispose(); - const evidence = - failures.length > 0 - ? "" - : `${fixture.ownerUser}@${fixture.ownerOrg} saved ${fixture.marker} at ${ownerSeat}. ` + - `For ${outsiders.map(([name]) => name).join(" and ")}: not listed, open 404, run 404, resume refused, ` + - `drain errored unheld with no session minted, debug listing without the private row. ` + - `The owner's next run read ${fixture.marker} from notes and state; ` + - `${ownerOtherOrgSeat} read ${JSON.stringify(elsewhere)}; ${peerSeat} read ${JSON.stringify(peers)}.`; - return { failures, evidence }; -}); diff --git a/goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/fixtures/input.json b/goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/fixtures/input.json deleted file mode 100644 index edb7021761..0000000000 --- a/goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/fixtures/input.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "ownerOrg": "acme", - "otherOrg": "globex", - "ownerUser": "alice", - "peerUser": "bob", - "foreignUser": "mallory", - "seatId": "research", - "orgSeatId": "eng.lead", - "secret": "ALICE-ONLY-HIRE-MARKER", - "orgSecret": "ACME-ORG-ROSTER-MARKER" -} diff --git a/goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/goal.md b/goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/goal.md deleted file mode 100644 index d068f43e25..0000000000 --- a/goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/goal.md +++ /dev/null @@ -1,23 +0,0 @@ -# hire-plane › it keeps the debug listing on the hire plane - -**Issue:** FIX-1535 -**Outcome:** With debug endpoints switched on, which is what `fsdev dev` does, a session's debug resource listing shows only the hire rows that session's user may see. A teammate in the same organization does not get another user's private hire row, its instructions, or its count. Another organization gets neither that row nor the org roster. The owner still sees her own row, and a teammate still sees the org-visible roster. -**Input:** `fixtures/input.json`: two orgs, three users, a private seat id, an org seat id, and one marker for each row. Held-out: every id and both markers are read from the fixture and graded against the debug responses. Swapping any of them must still pass. -**Signal:** against `createFlowState`'s HTTP router with `debugEndpointsEnabled: true`, in-memory stores, no model. The owner's `hire` action writes her private row through the workforce's owner-private roster collection and one org row through the org roster, both through the resource handle. Each leg reads `GET …/debug/resources`, `…/debug/resources/privateRoster/items` and `…/debug/resources/roster/items` from its own session. -(a) The owner's hire completes. Her debug reads contain the private marker and her private item count is 1. -(b) The teammate's debug reads are all 200, contain no private marker, list no private topic, report a private item count of 0, and list exactly the org seat on the org roster, marker included. -(c) The other organization's debug reads are all 200 and contain neither marker. - -**Anti-game:** a hollow pass would assert that the teammate's listing is empty, or that some debug request returned 404. Both hold if the debug routes list nothing for anyone. So the check MUST see the owner's own debug read return her marker, MUST see the teammate still receive the org-visible row, and MUST grade the teammate's reads for the private marker in every body, including the tree's count. -**Model:** n/a (handlers only). The property is which stored rows a debug read returns, not model output. -**Run:** `pnpm tsx goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/run.mts` (after `pnpm --filter @flow-state-dev/workforce... build`) -**Controls:** none in the runner. The red state is a source revert, so it fails for the reason a missing fence fails and not because the runner skipped a leg. -- Drop `ownerKeyAdmits` from `collectionKeyVisible` in `packages/engine/src/routes/debug-snapshot.ts`. Must FAIL leg (b) only. - -## Verdict log -| Date | Commit | Model | Verdict | Notes | -|------|--------|-------|---------|-------| -| 2026-09-23 | `c0960b6d8` with `privateRosterAdmits` dropped from `collectionKeyVisible`, engine rebuilt, then restored | n/a | FAIL (expected) | **Leg (b) only:** `teammate debug listing contained the owner's marker`, `teammate private topics ["~alice/research"]`, `teammate private itemCount was 1`. Legs (a) and (c) stayed green. | -| 2026-09-23 | `c0960b6d8` (fence restored, engine rebuilt) | n/a | PASS | Exit 0. alice hired research; her debug listing showed `ALICE-ONLY-HIRE-MARKER` (count 1). bob's debug listing showed `eng.lead` only (private count 0, marker absent). globex's debug listing showed neither marker. | -| 2026-09-24 | `f8c299b8e` + FIX-1549 PR-A, with `ownerKeyAdmits` dropped from `collectionKeyVisible`, then restored | n/a | FAIL (expected) | **Leg (b) only:** `teammate debug listing contained the owner's marker`, `teammate private topics ["~alice/research"]`, `teammate private itemCount was 1`. | -| 2026-09-24 | `f8c299b8e` + FIX-1549 PR-A | n/a | PASS | Legs (a)–(c) green on the generic key predicate. | diff --git a/goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/run.mts b/goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/run.mts deleted file mode 100644 index 5ab405183b..0000000000 --- a/goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/run.mts +++ /dev/null @@ -1,211 +0,0 @@ -/** - * Goal check — with debug endpoints switched on, the debug resource listing - * shows a session only the hire rows its user may see, on the HTTP router, - * with no model. - * - * See goal.md for the contract, including the source-revert control. - * - * Run: pnpm tsx goals/hire-plane/keeps-the-debug-listing-on-the-hire-plane/run.mts - */ -import { defineFlow, handler } from "@flow-state-dev/core"; -import { createFlowState, inMemoryStores } from "@flow-state-dev/engine"; -import type { JsonObject, ResourceCollectionRef } from "@flow-state-dev/core/types"; -import { - defineHiredRosterCollection, - defineHiredRosterPrivateCollection, - hiredRosterStorageKey, - toHiredSeatRow, -} from "@flow-state-dev/workforce"; -import { z } from "zod"; -import { loadFixture, runGoal } from "../../lib/index.mts"; - -type Fixture = { - ownerOrg: string; - otherOrg: string; - ownerUser: string; - peerUser: string; - foreignUser: string; - seatId: string; - orgSeatId: string; - secret: string; - orgSecret: string; -}; - -type Who = { user: string; org: string }; - -const fixture = loadFixture(import.meta.url); - -const resources = { - roster: defineHiredRosterCollection(), - privateRoster: defineHiredRosterPrivateCollection(), -}; - -const verified = { - resolvePrincipal: (context: { request?: Request }) => { - const userId = context.request?.headers.get("x-verified-user"); - const orgId = context.request?.headers.get("x-verified-org"); - return userId && orgId ? { userId, orgId } : null; - }, -}; - -// Writes the session user's private hire row through the owner-private roster, and -// one org-visible row through the org roster, the way a hire does. -const hire = handler({ - name: "hire", - inputSchema: z.object({}), - outputSchema: z.object({ ok: z.boolean() }), - resources, - execute: async (_input, ctx) => { - const { userId = "", orgId = "" } = ctx.session.identity; - const own = toHiredSeatRow({ - seatId: fixture.seatId, - flow: "seat", - instructions: fixture.secret, - owningOrgId: orgId, - ownerUserId: userId, - }); - // The writer's pattern is `[owner]/[seat]`; the owner segment is the - // `~` half of the row's storage key. - const [ownerSegment, seat] = hiredRosterStorageKey(own).split("/"); - await (ctx.resources.privateRoster as unknown as ResourceCollectionRef).create( - { owner: ownerSegment!, seat: seat! }, - own as unknown as JsonObject, - ); - const shared = toHiredSeatRow({ - seatId: fixture.orgSeatId, - flow: "seat", - instructions: fixture.orgSecret, - owningOrgId: orgId, - }); - await (ctx.resources.roster as unknown as ResourceCollectionRef).create( - hiredRosterStorageKey(shared), - shared as unknown as JsonObject, - ); - return { ok: true }; - }, -}); - -const appFlow = defineFlow({ - kind: "app", - resources, - actions: { hire: { inputSchema: z.object({}), block: hire } }, - authentication: verified, -}); - -const owner: Who = { user: fixture.ownerUser, org: fixture.ownerOrg }; -const peer: Who = { user: fixture.peerUser, org: fixture.ownerOrg }; -const foreign: Who = { user: fixture.foreignUser, org: fixture.otherOrg }; - -await runGoal(async () => { - const failures: string[] = []; - const fail = (leg: string, line: string) => failures.push(`[${leg}] ${line}`); - const state = createFlowState({ - flows: { app: appFlow() }, - resolvePrincipal: verified.resolvePrincipal, - stores: { default: { primary: inMemoryStores() } }, - // What `fsdev dev` does. The property under test only exists with it on. - debugEndpointsEnabled: true, - debugAllowAnonymousLocal: true, - }); - const router = (await state.getRouter()) as { - GET: (request: Request, ctx: { params: { path: string[] } }) => Promise; - POST: (request: Request, ctx: { params: { path: string[] } }) => Promise; - }; - - const call = async (method: "GET" | "POST", path: string[], who: Who, body?: unknown) => { - const response = await router[method]( - new Request(`http://goal/api/flows/${path.join("/")}`, { - method, - headers: { - "content-type": "application/json", - "x-verified-user": who.user, - "x-verified-org": who.org, - }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }), - { params: { path } }, - ); - const text = await response.text(); - return { status: response.status, text, json: text.length > 0 ? JSON.parse(text) : undefined }; - }; - - const open = async (who: Who): Promise => { - const opened = await call("POST", ["app", "sessions"], who, { userId: who.user }); - return opened.status === 201 ? (opened.json.session.id as string) : undefined; - }; - - const runHire = async (who: Who, sessionId: string): Promise => { - const posted = await call("POST", ["app", sessionId, "actions", "hire"], who, { - userId: who.user, - input: {}, - }); - if (posted.status >= 400) return `http ${posted.status}`; - const requestId = posted.json.request?.id as string; - for (let i = 0; i < 100; i++) { - const status = (await call("GET", ["app", "requests", requestId, "status"], who)).json - ?.status as string | undefined; - if (status && !["pending", "in_progress", "running", "queued"].includes(status)) return status; - await new Promise((r) => setTimeout(r, 5)); - } - return "timed-out"; - }; - - // Every debug read a session can make of the two rosters. - const debugReads = async (who: Who, sessionId: string) => { - const base = ["sessions", sessionId, "debug", "resources"]; - const tree = await call("GET", base, who); - const privateItems = await call("GET", [...base, "privateRoster", "items"], who); - const orgItems = await call("GET", [...base, "roster", "items"], who); - const entries = (tree.json?.resources ?? []) as { primaryName: string; itemCount?: number }[]; - const topics = (r: { json?: { items?: { topic: string }[] } }) => - (r.json?.items ?? []).map((item) => item.topic); - return { - statuses: [tree.status, privateItems.status, orgItems.status], - body: tree.text + privateItems.text + orgItems.text, - privateCount: entries.find((e) => e.primaryName === "privateRoster")?.itemCount, - privateTopics: topics(privateItems), - orgTopics: topics(orgItems), - }; - }; - - const ownerSession = await open(owner); - const peerSession = await open(peer); - const foreignSession = await open(foreign); - if (ownerSession === undefined || peerSession === undefined || foreignSession === undefined) { - fail("setup", "a session did not open"); - return { failures, evidence: "" }; - } - - // (a) The owner hires and her own session's debug listing shows the row. - const hired = await runHire(owner, ownerSession); - if (hired !== "completed") fail("a", `owner hire did not complete: ${hired}`); - const mine = await debugReads(owner, ownerSession); - if (mine.statuses.some((s) => s !== 200)) fail("a", `owner debug statuses ${mine.statuses}`); - if (!mine.body.includes(fixture.secret)) fail("a", "owner debug listing did not show her row"); - if (mine.privateCount !== 1) fail("a", `owner private itemCount was ${mine.privateCount}`); - - // (b) A teammate's session in the same org: the org row, never the private one. - const theirs = await debugReads(peer, peerSession); - if (theirs.statuses.some((s) => s !== 200)) fail("b", `teammate debug statuses ${theirs.statuses}`); - if (theirs.body.includes(fixture.secret)) fail("b", "teammate debug listing contained the owner's marker"); - if (theirs.privateTopics.length !== 0) fail("b", `teammate private topics ${JSON.stringify(theirs.privateTopics)}`); - if (theirs.privateCount !== 0) fail("b", `teammate private itemCount was ${theirs.privateCount}`); - if (JSON.stringify(theirs.orgTopics) !== JSON.stringify([fixture.orgSeatId])) { - fail("b", `teammate org roster topics ${JSON.stringify(theirs.orgTopics)}`); - } - if (!theirs.body.includes(fixture.orgSecret)) fail("b", "teammate lost the org-visible row"); - - // (c) Another org's session sees neither row. - const outside = await debugReads(foreign, foreignSession); - if (outside.statuses.some((s) => s !== 200)) fail("c", `other org debug statuses ${outside.statuses}`); - if (outside.body.includes(fixture.secret)) fail("c", "other org saw the owner's marker"); - if (outside.body.includes(fixture.orgSecret)) fail("c", "other org saw the org roster marker"); - - const evidence = - failures.length > 0 - ? "" - : `${fixture.ownerUser} hired ${fixture.seatId}; her debug listing showed ${fixture.secret} (count 1). ` + - `${fixture.peerUser}'s debug listing showed ${fixture.orgSeatId} only (private count 0, marker absent). ` + - `${fixture.otherOrg}'s debug listing showed neither marker.`; - return { failures, evidence }; -}); diff --git a/goals/hire-plane/reload-survives-an-unaddressable-row/fixtures/input.json b/goals/hire-plane/reload-survives-an-unaddressable-row/fixtures/input.json deleted file mode 100644 index 711783fa56..0000000000 --- a/goals/hire-plane/reload-survives-an-unaddressable-row/fixtures/input.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "namedOrg": "acme", - "namedUser": "alice", - "devUser": "dev", - "devSeatId": "lead", - "namedSeatId": "support.ada", - "strayOrg": "globex", - "straySeatId": "stray", - "marker": "ACME-SEAT-ANSWERED-AFTER-RESTART" -} diff --git a/goals/hire-plane/reload-survives-an-unaddressable-row/goal.md b/goals/hire-plane/reload-survives-an-unaddressable-row/goal.md deleted file mode 100644 index dcf744c251..0000000000 --- a/goals/hire-plane/reload-survives-an-unaddressable-row/goal.md +++ /dev/null @@ -1,26 +0,0 @@ -# hire-plane › reload survives an unaddressable row - -**Issue:** FIX-1536 -**Outcome:** An app with no authentication that hires a seat at runtime does not take the rest of the roster down at the next boot. That hire lands under the development organization, and comes back as a seat at that organization's escaped address (FIX-1757; before it, the id could not be an address and the row came back as one named problem). Every other organization's seats still reload, register and answer. A row stamped for a different organization is still refused, not minted. -**Input:** `fixtures/input.json` — the signed-in org and user, the dev user, the two seat ids, the stray org and seat id, and a marker. Held-out: every id is read from the fixture and graded against the reload result and a real run on the reloaded seat. Swapping any of them must still pass. -**Signal:** against `createFlowState`'s HTTP router, one in-memory store shared by four app instances (dev, signed-in, and a restart of each: one with the signed-in resolver, one with none), no model. -(a) The dev app's `hire` action, run with no identity, completes and leaves a roster row under `DEFAULT_ORG_ID`. -(b) The signed-in app's `hire` action completes for the named org. -(c) `reloadHiredSeats` over `[DEFAULT_ORG_ID, ]` resolves. It returns `.` and the dev row at the escaped default-org address, written out in the runner from the documented escape rule (not taken from `seatAddress`), and names no default-org problem. Both seats then answer an `answer` run over HTTP: the named seat on the restarted signed-in app, and the dev seat on a restarted app with no resolver, called with no identity at its escaped address. -(d) A row in the named org's cell stamped `owningOrgId: ` is a `cannot be registered under` problem, and no seat with its id is returned. - -**Anti-game:** a hollow pass would check that `problems` is non-empty, which holds when reload names both bad rows and returns nothing else. So the check MUST see the named org's seat come back and answer a real run after the restart, MUST see the dev row come back at the escaped default-org address the runner computes from the documented rule (never from `seatAddress`, the helper under test) and answer an `answer` run over HTTP with no identity on the resolver-less restart, and MUST see the stray row refused rather than minted. It must not grade the address string alone. -**Model:** n/a — handlers only. The property is which stored rows come back as seats. -**Run:** `pnpm tsx goals/hire-plane/reload-survives-an-unaddressable-row/run.mts` (build `@flow-state-dev/core`, `@flow-state-dev/engine` and `@flow-state-dev/workforce` first; the goal imports their `dist`). -**Controls:** none in the runner. The red state is a source edit, so it fails for the reason the bug fails. -- Break default-org admission: in `packages/engine/src/context/instance-pin.ts` `pinMismatchReason`, return `"owning-org"` whenever `pin.orgId === DEFAULT_ORG_ID`, then rebuild engine. Must FAIL leg (c) only, with the dev seat answering `404 Unknown flow` at its escaped address. -- (Historical, pre-FIX-1757) reverting `packages/workforce/src/roster/reload.ts` to `ffe2b6e26` failed leg (c) by rejecting the reload. Since the default org became addressable, that revert no longer turns this goal red. - -## Verdict log -| Date | Commit | Model | Verdict | Notes | -|------|--------|-------|---------|-------| -| 2026-09-23 | `636542bc6` with `reload.ts` reverted to `ffe2b6e26`, then restored | n/a | FAIL (expected) | **Leg (c) only:** `reload rejected, so no org's seats came back: Organization id "__fsd_default_org__" must be lowercase letters, digits, and single hyphens ...`. Legs (a) and (b) completed, so the dev hire really does write under the default org through the HTTP path. Restored with `git checkout HEAD -- packages/workforce/src/roster/reload.ts` and rebuilt. | -| 2026-09-23 | `636542bc6` (fix present) | n/a | PASS | Exit 0. Dev hire stored under `__fsd_default_org__`; reload over `[__fsd_default_org__, acme]` returned `["acme.support.ada"]` and 2 problems; `acme.support.ada` answered after restart; default-org row named as `organization "__fsd_default_org__", row "workforce/roster/lead"`; stray row refused as `owned by organization "globex" and cannot be registered under "acme"`. | -| 2026-10-04 | `d5225ecd8` + FIX-1757 (org escaped into the address) | n/a | PASS | Leg (c) re-pointed: the default org is now addressable. Reload returned `["%5F%5Ffsd%5Fdefault%5Forg%5F%5F.lead","acme.support.ada"]` and 1 problem (the stray row, refused as before); `acme.support.ada` answered after restart. | -| 2026-10-04 | FIX-1757 `37c0d738d`, default-org admission broken in `instance-pin.ts`, then restored | n/a | FAIL (expected) | **Leg (c) only:** `%5F%5Ffsd%5Fdefault%5Forg%5F%5F.lead did not answer over HTTP on the resolver-less host: {"http":404,"detail":{"error":"Unknown flow \"%5F%5Ffsd%5Fdefault%5Forg%5F%5F.lead\""}}`. Restored and rebuilt. | -| 2026-10-04 | FIX-1757 `37c0d738d` | n/a | PASS | Exit 0. The dev seat came back at `%5F%5Ffsd%5Fdefault%5Forg%5F%5F.lead` (expected address computed independently of `seatAddress`) and answered over HTTP with no identity on a resolver-less host; `acme.support.ada` answered on the signed-in host; stray row refused. | diff --git a/goals/hire-plane/reload-survives-an-unaddressable-row/run.mts b/goals/hire-plane/reload-survives-an-unaddressable-row/run.mts deleted file mode 100644 index 82a273eef5..0000000000 --- a/goals/hire-plane/reload-survives-an-unaddressable-row/run.mts +++ /dev/null @@ -1,312 +0,0 @@ -/** - * Goal check — a runtime hire made by an app with no authentication does not - * take the rest of the roster down at the next boot. - * - * See goal.md for the contract and the source-revert control. - * - * Run: pnpm tsx goals/hire-plane/reload-survives-an-unaddressable-row/run.mts - */ -import { defineFlow, handler, type FlowInstance } from "@flow-state-dev/core"; -import { - DEFAULT_ORG_ID, - type JsonObject, - type ResourceCollectionRef, -} from "@flow-state-dev/core/types"; -import { createFlowState, inMemoryStores } from "@flow-state-dev/engine"; -import { - defineHiredRosterCollection, - reloadHiredSeats, - toHiredSeatRow, - workerConfigSchema, -} from "@flow-state-dev/workforce"; -import { z } from "zod"; -import { loadFixture, runGoal, workerDoor } from "../../lib/index.mts"; - -type Fixture = { - namedOrg: string; - namedUser: string; - devUser: string; - devSeatId: string; - namedSeatId: string; - strayOrg: string; - straySeatId: string; - marker: string; -}; - -type Router = { - GET: (request: Request, ctx: { params: { path: string[] } }) => Promise; - POST: (request: Request, ctx: { params: { path: string[] } }) => Promise; -}; - -const fixture = loadFixture(import.meta.url); - -/** - * The address an org-visible hire under `orgId` answers on, written out here from - * the documented rule (`[a-z0-9-]` kept, every other UTF-8 byte as `%XX`) - * rather than taken from `seatAddress`, the helper under test. - */ -function expectedAddress(orgId: string, seatId: string): string { - const org = [...new TextEncoder().encode(orgId)] - .map((byte) => { - const ch = String.fromCharCode(byte); - return /[a-z0-9-]/.test(ch) ? ch : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`; - }) - .join(""); - return `${org}.${seatId}`; -} - -/** A roster row as the store's JSON shape — the same cast the seat-hire writer makes. */ -function asStored(row: ReturnType): JsonObject { - return row as unknown as JsonObject; -} - -const resources = { roster: defineHiredRosterCollection() }; -const hireInput = z.object({ seatId: z.string() }); -const tagInput = z.object({ tag: z.string() }); - -/** - * The runtime-hire write an app makes: the org is the session's, and the row - * goes in with `create()`. Nothing here chooses the org — an app with no - * resolver gets DEFAULT_ORG_ID from the framework, which is the whole case. - */ -const hire = handler({ - name: "hire", - inputSchema: hireInput, - outputSchema: z.object({ orgId: z.string() }), - resources, - execute: async (input, ctx) => { - const orgId = ctx.session.identity.orgId ?? ""; - const roster = ctx.resources.roster as unknown as ResourceCollectionRef; - await roster.create( - input.seatId, - asStored(toHiredSeatRow({ seatId: input.seatId, flow: "clerk", owningOrgId: orgId })), - ); - return { orgId }; - }, -}); - -/** What a reloaded seat does when asked: record who answered, and as whom. */ -const answer = handler({ - name: "answer", - inputSchema: tagInput, - outputSchema: z.object({ answeredAs: z.string() }), - execute: (_input, ctx) => ({ answeredAs: (ctx.flow as unknown as { id: string }).id }), -}); - -const clerk = defineFlow({ - kind: "clerk", - cardinality: "collection", - configSchema: workerConfigSchema(), - actions: { ...workerDoor, answer: { inputSchema: tagInput, block: answer } }, -}); -const kinds = { clerk }; - -const hiring = defineFlow({ - kind: "hiring", - resources, - actions: { hire: { inputSchema: hireInput, block: hire } }, -}); - -const verified = { - resolvePrincipal: (context: { request?: Request }) => { - const userId = context.request?.headers.get("x-verified-user"); - const orgId = context.request?.headers.get("x-verified-org"); - return userId && orgId ? { userId, orgId } : null; - }, -}; - -async function call( - router: Router, - method: "GET" | "POST", - path: string[], - body?: unknown, - who?: { user: string; org: string }, -) { - const headers: Record = { "content-type": "application/json" }; - if (who !== undefined) { - headers["x-verified-user"] = who.user; - headers["x-verified-org"] = who.org; - } - const response = await router[method]( - // The URL as a client builds it (each segment encoded); `params.path` as - // Next hands it (each decoded once). - new Request(`http://goal/api/flows/${path.map(encodeURIComponent).join("/")}`, { - method, - headers, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }), - { params: { path } }, - ); - const text = await response.text(); - return { status: response.status, json: text.length > 0 ? JSON.parse(text) : undefined }; -} - -/** Open a session on `flowId`, run one action, and wait for it to settle. */ -async function runAction( - router: Router, - flowId: string, - userId: string, - action: string, - input: unknown, - who?: { user: string; org: string }, -): Promise<{ http: number; outcome?: string; detail?: unknown }> { - const session = await call(router, "POST", [flowId, "sessions"], { userId }, who); - if (session.status !== 201) return { http: session.status, detail: session.json }; - const sessionId = session.json.session.id as string; - const posted = await call(router, "POST", [flowId, sessionId, "actions", action], { userId, input }, who); - if (posted.status >= 400) return { http: posted.status, detail: posted.json }; - const requestId = posted.json.request?.id as string; - for (let i = 0; i < 200; i++) { - const status = (await call(router, "GET", [flowId, "requests", requestId, "status"], undefined, who)) - .json?.status as string | undefined; - if (status && !["pending", "in_progress", "running", "queued"].includes(status)) { - return { http: posted.status, outcome: status }; - } - await new Promise((r) => setTimeout(r, 5)); - } - return { http: posted.status, outcome: "timed-out" }; -} - -await runGoal(async () => { - const failures: string[] = []; - const fail = (leg: string, line: string) => failures.push(`[${leg}] ${line}`); - const stores = inMemoryStores(); - const namedAddress = expectedAddress(fixture.namedOrg, fixture.namedSeatId); - - // (a) An app with no resolver hires at runtime. One store is shared by both - // apps below because it is ONE deployment's database seen twice. - const devApp = createFlowState({ - flows: { hiring: hiring() }, - stores: { default: { primary: stores } }, - }); - const devRouter = (await devApp.getRouter()) as Router; - const devHire = await runAction(devRouter, "hiring", fixture.devUser, "hire", { - seatId: fixture.devSeatId, - }); - if (devHire.outcome !== "completed") fail("a", `dev hire did not complete: ${JSON.stringify(devHire)}`); - const devRuntime = await devApp.getRuntime(); - const devRow = await devRuntime.stores.resourceState.get( - "org", - DEFAULT_ORG_ID, - `workforce/roster/${fixture.devSeatId}`, - ); - if (devRow === undefined) fail("a", `no roster row landed under ${DEFAULT_ORG_ID}`); - - // (b) A signed-in organization hires through the same action. - const authedApp = createFlowState({ - flows: { hiring: hiring() }, - resolvePrincipal: verified.resolvePrincipal, - stores: { default: { primary: stores } }, - }); - const authedRouter = (await authedApp.getRouter()) as Router; - const who = { user: fixture.namedUser, org: fixture.namedOrg }; - const namedHire = await runAction( - authedRouter, - "hiring", - fixture.namedUser, - "hire", - { seatId: fixture.namedSeatId }, - who, - ); - if (namedHire.outcome !== "completed") fail("b", `named hire did not complete: ${JSON.stringify(namedHire)}`); - - // (d) setup: a row in the named org's cell stamped for another org — the - // fence FIX-1529 added, which this fix must not loosen. - const primary = await stores.resolve(["primary"]); - await primary.resourceState!.set( - "org", - fixture.namedOrg, - `workforce/roster/${fixture.straySeatId}`, - asStored(toHiredSeatRow({ seatId: fixture.straySeatId, flow: "clerk", owningOrgId: fixture.strayOrg })), - "any", - ); - - // (c) The restart: a fresh app over the same store reloads BOTH orgs, the - // default one first so it is the first row the reload meets. - const restarted = createFlowState({ - flows: {}, - resolvePrincipal: verified.resolvePrincipal, - stores: { default: { primary: stores } }, - }); - const restartedRuntime = await restarted.getRuntime(); - let reload: Awaited> | undefined; - try { - reload = await reloadHiredSeats({ - stores: restartedRuntime.stores, - orgIds: [DEFAULT_ORG_ID, fixture.namedOrg], - workerFlows: kinds, - }); - } catch (error) { - fail("c", `reload rejected, so no org's seats came back: ${(error as Error).message}`); - } - - if (reload !== undefined) { - const ids = reload.seats.map((seat) => seat.id); - if (!ids.includes(namedAddress)) fail("c", `reload did not return ${namedAddress}; got ${JSON.stringify(ids)}`); - // The dev hire comes back as a seat: the default org is escaped into its - // address rather than refused. - const devAddress = expectedAddress(DEFAULT_ORG_ID, fixture.devSeatId); - const devProblem = reload.problems.find((problem) => problem.includes(DEFAULT_ORG_ID)); - if (!ids.includes(devAddress) || devProblem !== undefined) { - fail( - "c", - `the default-org row did not come back as ${devAddress}: ${JSON.stringify(ids)}, ` + - `problems ${JSON.stringify(reload.problems)}`, - ); - } - const strayProblem = reload.problems.find((problem) => problem.includes(fixture.strayOrg)); - if (strayProblem === undefined || !strayProblem.includes("cannot be registered under")) { - fail("d", `the row stamped for ${fixture.strayOrg} was not refused: ${JSON.stringify(reload.problems)}`); - } - if (ids.some((id) => id.endsWith(`.${fixture.straySeatId}`))) { - fail("d", `the row stamped for ${fixture.strayOrg} was minted: ${JSON.stringify(ids)}`); - } - - // (c) The reloaded seats are not just returned; they register and answer. - // The named org's on the signed-in host; the dev seat on a host with - // no resolver, the only place a default-org pin admits anyone. - const devRestarted = createFlowState({ - flows: {}, - stores: { default: { primary: stores } }, - }); - for (const seat of reload.seats) { - const pin = seat.ownerPin ?? { orgId: fixture.namedOrg }; - (pin.orgId === DEFAULT_ORG_ID ? devRestarted : restarted).register(seat as FlowInstance, { pin }); - } - const devAnswered = await runAction( - (await devRestarted.getRouter()) as Router, - devAddress, - fixture.devUser, - "answer", - { tag: fixture.marker }, - ); - if (devAnswered.outcome !== "completed") { - fail("c", `${devAddress} did not answer over HTTP on the resolver-less host: ${JSON.stringify(devAnswered)}`); - } - const restartedRouter = (await restarted.getRouter()) as Router; - const answered = await runAction( - restartedRouter, - namedAddress, - fixture.namedUser, - "answer", - { tag: fixture.marker }, - who, - ); - if (answered.outcome !== "completed") { - fail("c", `${namedAddress} did not answer after restart: ${JSON.stringify(answered)}`); - } - - if (failures.length === 0) { - return { - failures, - evidence: - `dev hire stored under ${DEFAULT_ORG_ID}; reload over [${DEFAULT_ORG_ID}, ${fixture.namedOrg}] ` + - `returned ${JSON.stringify(ids)} and ${reload.problems.length} problems; ` + - `${namedAddress} answered after restart; default-org row came back as ${devAddress} ` + - `and answered over HTTP with no identity; ` + - `stray row refused: ${strayProblem}`, - }; - } - } - return { failures, evidence: "" }; -}); diff --git a/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/app.mts b/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/app.mts deleted file mode 100644 index c49bf4d8c5..0000000000 --- a/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/app.mts +++ /dev/null @@ -1,241 +0,0 @@ -/** - * The app this goal starts four times over one SQLite file. - * - * Model-free. Two seat kinds, each answering one `answer` action with the - * address it runs at. Before the release (`release: "before"`) the app carries - * both; after it (`"after"`) the cut kind is gone and the kept kind's settings - * require one more key, so a seat hired without it is refused at start. - * - * The `ops` flow mounts the seat-hire blocks as actions, plus `repair`: the - * approval a person answers before a seat is retired or re-hired. It suspends - * on a stock `human_approval`; Approve applies the repair, Deny changes nothing. - * - * Under `GOAL_CONTROL=fire-keeps-inventory`, retire is today's fire: the roster - * row is deleted and the address released, and the inventory row stays. - */ -import { defineFlow, handler, sequencer, SuspensionRejectedError } from "@flow-state-dev/core"; -import type { BlockContext, FlowInstance, ResourceCollectionRef } from "@flow-state-dev/core/types"; -import { createFlowState, runAction } from "@flow-state-dev/engine"; -import { sqliteStores } from "@flow-state-dev/store-sqlite"; -import { - createSeatHireBlocks, - defineHiredRosterCollection, - defineSeatInventoryCollection, - HIRED_ROSTER_RESOURCE, - reloadHiredSeats, - SEAT_INVENTORY_RESOURCE, - seatAddress, - workerConfigSchema, -} from "@flow-state-dev/workforce"; -import { z } from "zod"; -import { workerDoor } from "../../lib/worker-door.mts"; - -export type Fixture = { - orgId: string; - userId: string; - cutKind: string; - keptKind: string; - requiredSetting: string; - settingValue: string; - cutSeat: string; - rehireSeat: string; - refusedSeat: string; - healthySeat: string; - firedBeforeSeat: string; - marker: string; -}; - -export type Release = "before" | "after"; - -const tagInput = z.object({ tag: z.string() }); - -/** What a seat does when asked: say which address answered. */ -const answer = handler({ - name: "answer", - inputSchema: tagInput, - outputSchema: z.object({ answeredAs: z.string(), tag: z.string() }), - execute: (input, ctx) => ({ answeredAs: (ctx.flow as unknown as { id: string }).id, tag: input.tag }), -}); - -function seatKind(kind: string, setting: string, required: boolean) { - return defineFlow({ - kind, - cardinality: "collection", - configSchema: workerConfigSchema().extend({ [setting]: required ? z.string() : z.string().optional() }), - actions: { answer: { inputSchema: tagInput, block: answer }, ...workerDoor }, - } as never); -} - -/** The kind map this release boots with. */ -export function kindsFor(fixture: Fixture, release: Release) { - return release === "before" - ? { - [fixture.cutKind]: seatKind(fixture.cutKind, fixture.requiredSetting, false), - [fixture.keptKind]: seatKind(fixture.keptKind, fixture.requiredSetting, false), - } - : { [fixture.keptKind]: seatKind(fixture.keptKind, fixture.requiredSetting, true) }; -} - -const repairInput = z.object({ - op: z.enum(["retire", "rehire"]), - seatId: z.string(), - flow: z.string().optional(), - settings: z.record(z.unknown()).optional(), -}); -const decision = repairInput.extend({ approved: z.boolean() }); - -/** The ask: a stock approval naming the repair. */ -const gate = handler({ - name: "repair-gate", - inputSchema: repairInput, - outputSchema: decision, - execute: async (input, ctx) => { - try { - await ctx.suspend!({ - reason: "human_approval", - message: `${input.op === "retire" ? "Retire" : `Re-hire onto ${input.flow}`} ${input.seatId}?`, - allow: ["approve", "reject"], - }); - return { ...input, approved: true }; - } catch (error) { - if (error instanceof SuspensionRejectedError) return { ...input, approved: false }; - throw error; - } - }, -}); - -/** The control: retire as fire was before this change, leaving the inventory row. */ -function todaysFire(unregister: (id: string) => boolean) { - return handler({ - name: "fire-keeps-inventory", - inputSchema: z.object({ seatId: z.string() }), - outputSchema: z.object({ released: z.boolean() }), - execute: async (input, ctx: BlockContext) => { - const orgId = String(ctx.org?.identity.orgId ?? ctx.org?.identity.id); - const roster = ctx.resources[HIRED_ROSTER_RESOURCE] as unknown as ResourceCollectionRef; - await roster.delete(input.seatId); - return { released: unregister(seatAddress(orgId, input.seatId)) }; - }, - }); -} - -/** Open the app over `dbFile`, reload the stored roster, and register what comes back. */ -export async function openApp(options: { fixture: Fixture; release: Release; dbFile: string; control?: string }) { - const { fixture, release } = options; - const kinds = kindsFor(fixture, release); - let registry: { get(id: string): { kind: string } | undefined } | undefined; - let state: ReturnType; - - const register = (seat: FlowInstance, pin: { orgId: string; userId?: string }) => state.register(seat, { pin }); - const unregister = (id: string) => state.unregister(id); - const blocks = createSeatHireBlocks({ - workerFlows: kinds, - register, - unregister, - kindAt: (id) => registry?.get(id)?.kind, - }); - const retire = options.control === "fire-keeps-inventory" ? todaysFire(unregister) : blocks.fire; - - const repair = sequencer({ name: "repair", inputSchema: repairInput }) - .step(gate) - .stepIf((d: any) => d.approved === true && d.op === "retire", (d: any) => ({ seatId: d.seatId }), retire) - .stepIf( - (d: any) => d.approved === true && d.op === "rehire", - (d: any) => ({ seatId: d.seatId, flow: d.flow, settings: d.settings ?? {} }), - blocks.rehire, - ); - - const ops = defineFlow({ - kind: "ops", - resources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection(), - }, - actions: { - hire: { block: blocks.hire }, - brokenSeats: { block: blocks.brokenSeats }, - repair: { block: repair, durable: true }, - }, - } as never)(); - - state = createFlowState({ - flows: { ops: ops as never }, - stores: { default: { primary: sqliteStores({ filename: options.dbFile }) } }, - durable: true, - resolvePrincipal: (context: { request?: Request }) => { - const userId = context.request?.headers.get("x-verified-user"); - const orgId = context.request?.headers.get("x-verified-org"); - return userId && orgId ? { userId, orgId } : null; - }, - } as never); - const runtime = await state.getRuntime(); - registry = runtime.registry as never; - - // The boot: the stored roster read back, each seat registered under its own pin. - const reload = await reloadHiredSeats({ stores: runtime.stores, orgIds: [fixture.orgId], workerFlows: kinds }); - for (const seat of reload.seats) { - state.register(seat, { pin: (seat as { ownerPin?: { orgId: string } }).ownerPin ?? { orgId: fixture.orgId } }); - } - - const router = (await state.getRouter()) as Record Promise>; - const who = { "x-verified-user": fixture.userId, "x-verified-org": fixture.orgId }; - const call = async (method: "GET" | "POST", path: string[], body?: unknown) => { - const response = await router[method]!( - new Request(`http://goal/api/flows/${path.map(encodeURIComponent).join("/")}`, { - method, - headers: { "content-type": "application/json", ...who }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }), - { params: { path } }, - ); - const text = await response.text(); - return { status: response.status, json: text.length > 0 ? JSON.parse(text) : undefined }; - }; - - /** - * Wait for a request to leave the running states. After a resume, a request - * still reading `suspended` has not picked the answer up yet, so it waits on that too. - */ - const settle = async (flowId: string, requestId: string, resumed = false): Promise<{ status: string; body: any }> => { - const running = ["pending", "in_progress", "running", "queued", ...(resumed ? ["suspended"] : [])]; - for (let i = 0; i < 400; i++) { - const polled = await call("GET", [flowId, "requests", requestId, "status"]); - const status = polled.json?.status as string | undefined; - if (status && !running.includes(status)) return { status, body: polled.json }; - await new Promise((r) => setTimeout(r, 10)); - } - return { status: "timed-out", body: undefined }; - }; - - /** Run one action in a fresh session as the fixture's person, through the HTTP router. */ - const act = async (flowId: string, action: string, input: unknown) => { - const session = await call("POST", [flowId, "sessions"], { userId: fixture.userId }); - if (session.status !== 201) return { status: `session ${session.status}`, body: session.json, requestId: "" }; - const sessionId = session.json.session.id as string; - const posted = await call("POST", [flowId, sessionId, "actions", action], { userId: fixture.userId, input }); - if (posted.status >= 400) return { status: `http ${posted.status}`, body: posted.json, requestId: "" }; - const requestId = posted.json.request.id as string; - return { ...(await settle(flowId, requestId)), requestId }; - }; - - /** - * Run one `ops` action and hand back what it answered — for the read, whose - * answer is the surface a person sees. The HTTP status route carries no output. - */ - let n = 0; - const answerOf = async (action: string, input: unknown) => { - n += 1; - return (await runAction({ - flow: ops, - actionName: action, - input, - userId: fixture.userId, - orgId: fixture.orgId, - sessionId: `goal-${action}-${Date.now()}-${n}`, - stores: runtime.stores, - runtimeConfig: { ...runtime.runtimeConfig }, - } as never)) as { output?: unknown; error?: { message?: string } }; - }; - - return { state, runtime, reload, call, act, settle, answerOf }; -} diff --git a/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/fixtures/input.json b/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/fixtures/input.json deleted file mode 100644 index 5b6bdea809..0000000000 --- a/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/fixtures/input.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "orgId": "support-desk", - "userId": "u-owner", - "cutKind": "desk-clerk", - "keptKind": "concierge", - "requiredSetting": "queue", - "settingValue": "billing", - "cutSeat": "support.joe", - "rehireSeat": "support.kim", - "refusedSeat": "support.lin", - "healthySeat": "support.ada", - "firedBeforeSeat": "support.old", - "marker": "tag-7d1c" -} diff --git a/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/goal.md b/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/goal.md deleted file mode 100644 index 4cd78ce157..0000000000 --- a/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/goal.md +++ /dev/null @@ -1,25 +0,0 @@ -# hire-plane › it repairs a seat whose kind was cut - -**Issue:** FIX-1621 -**Outcome:** An app ships a release that cuts a seat kind. Every stored seat hired into it stops coming back, and the start names each one. A person can now ask which stored seats don't come back and why, and clear each one on their approval: retire it, or re-hire it onto a kind the app still carries. The next start names no refused seat, the re-hired seats answer at their old addresses, and the team list shows only seats that are hired, including leaving out a seat fired before this change. -**Input:** `fixtures/input.json`: the organization and person, the cut kind and the kept kind, the setting the kept kind starts requiring, and five seat ids (one to retire, one to re-hire after its kind was cut, one the kept kind now refuses, one healthy, one fired before this change). Held-out: every id and kind is read from the fixture; swapping any of them must still pass. -**Signal:** one app opened four times, each start its own process, over one SQLite file; no model. -1. Start 1 (the release that carried both kinds) hires the five seats through the `hire` action. The fifth is then left the way an earlier fire left it: roster row gone, inventory row kept (`1:hired`, `1:fired-before-seeded`). -2. Start 2 (the cut kind gone, the kept kind requiring the setting) names exactly the three broken rows (`2:start-names-each`). `brokenSeats` lists exactly those three, two `kind-gone` and one `refused` (`2:read-lists-exactly`), with the same row and detail text the start printed (`2:read-agrees-with-start`). A retire raised as a `human_approval` and answered Deny changes the row and leaves it listed (`2:deny-changes-nothing`). Three asks (retire, two re-hires) are raised and left pending (`2:asks-pending`). -3. Start 3 is a restart with the asks still open; the start still names all three (`3:still-broken-after-restart`), and the person approves each through the resume route (`3:approved`). -4. Start 4 names **zero** problems (`4:no-refused-seat`), the read lists none (`4:read-empty`), the retired seat's inventory row is gone (`team-list:retired-row-gone`), the team list (inventory joined with roster) lists neither the retired seat nor the earlier-fired one (`team-list:no-cut-seat`) and lists the three seats still hired (`team-list:hired-seats-listed`), and each of those answers an `answer` run at its old address on the kept kind (`4:answers:`). - -**Anti-game:** a hollow pass would grade what `fire` or `rehire` returned, or a mocked store. So every claim is read back by a later process from the SQLite file, the HTTP router or the start's own report: never a block's return value except the read's, which is the surface under test. The read is graded against the start's report line for line, so a read that guessed its own list fails. -**Model:** n/a. The blocks are model-free; the model-driven ask is FIX-1719's. -**Run:** `pnpm tsx goals/hire-plane/repairs-a-seat-whose-kind-was-cut/run.mts` -**Controls:** -- `GOAL_CONTROL=fire-keeps-inventory` — retire is fire as it was before this change: roster row deleted, address released, inventory row kept. Must FAIL `team-list:retired-row-gone` only. `team-list:no-cut-seat` still passes under it, because the team-list join hides a row with no roster row; that is the read side of the same rule, and why the inventory row itself is graded. - -On today's `main` the run fails at start 2: `createSeatHireBlocks` has no `brokenSeats` or `rehire`. - -## Verdict log -| Date | Commit | Model | Verdict | Notes | -|------|--------|-------|---------|-------| -| 2026-10-02 | `9427a4da4` with `packages/workforce/src` checked out from `origin/main` (`f3ce816b1`), then restored | n/a | FAIL (expected) | Exit 1 at start 1: `@flow-state-dev/workforce/browser` does not provide `listedSeatRows`, and `createSeatHireBlocks` has no `brokenSeats` or `rehire`. Today's `main` has no read to grade. | -| 2026-10-02 | `9427a4da4`, `GOAL_CONTROL=fire-keeps-inventory` | n/a | FAIL (expected) | Exit 1, **`team-list:retired-row-gone` only**: `the inventory still holds support-desk.support.joe`. Every other assertion held, `team-list:no-cut-seat` included, because the join hides the row. | -| 2026-10-02 | `9427a4da4` | n/a | PASS | Exit 0. Start 2 named 3 rows; the read listed `support.joe` and `support.kim` as `kind-gone` and `support.lin` as `refused` with the start's own detail; Deny left `support.joe`'s row unchanged and listed; after a restart the person approved one retire and two re-hires; start 4 reported 0 problems, the read listed none, the team list was `support.kim`, `support.lin`, `support.ada` (no `support.joe`, no `support.old`), and all three answered on `concierge`. | diff --git a/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/run.mts b/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/run.mts deleted file mode 100644 index c1aeafbfb1..0000000000 --- a/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/run.mts +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Goal check — after an app cuts a kind, a person sees each stored seat that no - * longer comes back and why, clears it on their approval, and the next start - * names no refused seat while the team list shows only hired seats. - * - * Four starts of one app, each its own process, over one SQLite file. See - * goal.md for the contract and the control. - * - * Run: pnpm tsx goals/hire-plane/repairs-a-seat-whose-kind-was-cut/run.mts - * Control: GOAL_CONTROL=fire-keeps-inventory pnpm tsx goals/hire-plane/repairs-a-seat-whose-kind-was-cut/run.mts - */ -import { spawnSync } from "node:child_process"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join } from "node:path"; -import { fileURLToPath } from "node:url"; -import { loadFixture, runGoal } from "../../lib/index.mts"; -import type { Fixture } from "./app.mts"; - -const fixture = loadFixture(import.meta.url); -const here = dirname(fileURLToPath(import.meta.url)); -const control = process.env.GOAL_CONTROL; - -type Out = Record; - -/** Start the app once, as its own process, and read what it printed. */ -function start(step: string, statePath: string): Out { - const child = spawnSync(process.execPath, [...process.execArgv, join(here, "start.mts"), step, statePath], { - encoding: "utf8", - env: process.env, - timeout: 120_000, - }); - const line = child.stdout.split("\n").find((l) => l.startsWith("RESULT ")); - if (line === undefined) { - throw new Error(`start "${step}" printed no result (exit ${child.status}): ${child.stderr.slice(-2000)}`); - } - return JSON.parse(line.slice("RESULT ".length)) as Out; -} - -await runGoal(async () => { - const failures: string[] = []; - const check = (name: string, ok: boolean, detail: unknown) => { - if (!ok) failures.push(`[${name}] ${typeof detail === "string" ? detail : JSON.stringify(detail)}`); - }; - const dir = mkdtempSync(join(tmpdir(), "fsd-goal-repair-")); - const statePath = join(dir, "state.json"); - writeFileSync(statePath, JSON.stringify({ fixture, dbFile: join(dir, "app.db"), ...(control ? { control } : {}) })); - const address = (seatId: string) => `${fixture.orgId}.${seatId}`; - const broken = [fixture.cutSeat, fixture.rehireSeat, fixture.refusedSeat]; - - try { - // ---- start 1: the release that carried the kind -------------------------- - const s1 = start("hire", statePath); - check("1:hired", Object.values(s1.hired).every((s) => s === "completed"), s1.hired); - check("1:fired-before-seeded", !s1.roster.includes(fixture.firedBeforeSeat) && s1.inventory.includes(address(fixture.firedBeforeSeat)), s1); - - // ---- start 2: the kind is cut ---------------------------------------------- - const s2 = start("ask", statePath); - const named = (seatId: string, problems: string[] = s2.problems) => - problems.filter((p) => p.includes(`roster/${seatId}"`)).length; - check("2:start-names-each", broken.every((seatId) => named(seatId) === 1) && s2.problems.length === broken.length, s2.problems); - check("2:read-ok", s2.read.error === undefined, s2.read.error); - const reasons = Object.fromEntries((s2.read.entries as Out[]).map((e) => [e.seatId, e.reason])); - check( - "2:read-lists-exactly", - JSON.stringify(reasons) === - JSON.stringify({ [fixture.cutSeat]: "kind-gone", [fixture.rehireSeat]: "kind-gone", [fixture.refusedSeat]: "refused" }), - reasons, - ); - const readLines = (s2.read.entries as Out[]).map((e) => `organization "${fixture.orgId}", row "${e.key}" — ${e.detail}`).sort(); - check("2:read-agrees-with-start", JSON.stringify(readLines) === JSON.stringify([...s2.problems].sort()), { readLines, problems: s2.problems }); - check( - "2:deny-changes-nothing", - s2.deny.raised === "suspended" && s2.deny.answered === "completed" && s2.deny.rowUnchanged && s2.deny.stillListed, - s2.deny, - ); - check("2:asks-pending", Object.values(s2.raised).every((s) => s === "suspended"), s2.raised); - - // ---- start 3: a restart, then the person approves ------------------------- - const s3 = start("answer", statePath); - check("3:still-broken-after-restart", broken.every((seatId) => named(seatId, s3.problems) === 1), s3.problems); - check( - "3:approved", - ["retire", "rehire", "refused"].every((label) => s3.answered[label] === "completed"), - s3.answered, - ); - - // ---- start 4: the next start --------------------------------------------- - const s4 = start("verify", statePath); - check("4:no-refused-seat", s4.problems.length === 0, s4.problems); - check("4:read-empty", s4.read.error === undefined && s4.read.entries.length === 0, s4.read); - check( - "team-list:retired-row-gone", - !s4.inventory.includes(address(fixture.cutSeat)), - `the inventory still holds ${address(fixture.cutSeat)}: ${JSON.stringify(s4.inventory)}`, - ); - check( - "team-list:no-cut-seat", - !s4.teamList.includes(address(fixture.cutSeat)) && !s4.teamList.includes(address(fixture.firedBeforeSeat)), - s4.teamList, - ); - check( - "team-list:hired-seats-listed", - [fixture.healthySeat, fixture.rehireSeat, fixture.refusedSeat].every((seatId) => s4.teamList.includes(address(seatId))), - s4.teamList, - ); - for (const seatId of [fixture.healthySeat, fixture.rehireSeat, fixture.refusedSeat]) { - check( - `4:answers:${seatId}`, - s4.answers[seatId]?.status === "completed" && s4.answers[seatId]?.kind === fixture.keptKind, - s4.answers[seatId], - ); - } - - return { - failures, - evidence: - `start 2 named ${s2.problems.length} rows and the read listed ${JSON.stringify(reasons)} with the same detail; ` + - `Deny left ${fixture.cutSeat}'s row unchanged; after a restart the person approved retire + 2 re-hires; ` + - `start 4 reported ${s4.problems.length} problems, the read listed none, the team list is ${JSON.stringify(s4.teamList)}, ` + - `and ${Object.keys(s4.answers).join(", ")} answered on ${fixture.keptKind}`, - }; - } finally { - rmSync(dir, { recursive: true, force: true }); - } -}); diff --git a/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/start.mts b/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/start.mts deleted file mode 100644 index 63aac4e5bf..0000000000 --- a/goals/hire-plane/repairs-a-seat-whose-kind-was-cut/start.mts +++ /dev/null @@ -1,156 +0,0 @@ -/** - * One start of the app, as its own process. `run.mts` spawns this four times - * over one SQLite file and grades what each start printed. - * - * tsx start.mts - * - * `state.json` carries the fixture, the database file, the control and what - * earlier starts left for later ones (the pending asks). This process prints - * one line, `RESULT `, and exits. - */ -import { readFileSync, writeFileSync } from "node:fs"; -import { listedSeatRows } from "@flow-state-dev/workforce/browser"; -import { openApp, type Fixture } from "./app.mts"; - -type State = { - fixture: Fixture; - dbFile: string; - control?: string; - pending?: Array<{ label: string; requestId: string; suspensionId: string }>; -}; - -const [step, statePath] = process.argv.slice(2) as [string, string]; -const state = JSON.parse(readFileSync(statePath, "utf8")) as State; -const { fixture } = state; -const ROSTER = "workforce/roster/"; -const SEATS = "inventory/seats/"; - -const app = await openApp({ - fixture, - release: step === "hire" ? "before" : "after", - dbFile: state.dbFile, - control: state.control, -}); -const stores = app.runtime.stores; - -/** Every row under a prefix in the org, by its key relative to the prefix. */ -async function rows(prefix: string): Promise>> { - const found = await stores.resourceState.getByPrefix("org", fixture.orgId, prefix); - return Object.fromEntries( - Object.entries(found).map(([key, value]) => [key.slice(prefix.length), (value as { state: Record }).state]), - ); -} - -/** The pending suspension a repair request raised. */ -async function suspensionOf(requestId: string): Promise { - const found = await stores.suspensions.list({ requestId } as never); - return found.find((s) => s.requestId === requestId && s.status === "pending")?.suspensionId; -} - -async function resume(requestId: string, suspensionId: string, action: "approve" | "reject") { - const posted = await app.call("POST", ["ops", "requests", requestId, "resume"], { - suspensionId, - action, - resumedBy: fixture.userId, - }); - if (posted.status >= 400) return { status: `http ${posted.status}`, body: posted.json }; - return app.settle("ops", requestId, true); -} - -const brokenSeats = async () => { - const read = await app.answerOf("brokenSeats", {}); - return { error: read.error?.message, entries: (read.output ?? []) as Array> }; -}; - -const result: Record = { problems: app.reload.problems }; - -if (step === "hire") { - const withSetting = { [fixture.requiredSetting]: fixture.settingValue }; - const hires: Array<[string, string, Record]> = [ - [fixture.cutSeat, fixture.cutKind, {}], - [fixture.rehireSeat, fixture.cutKind, {}], - [fixture.refusedSeat, fixture.keptKind, {}], - [fixture.healthySeat, fixture.keptKind, withSetting], - [fixture.firedBeforeSeat, fixture.keptKind, withSetting], - ]; - const hired: Record = {}; - for (const [seatId, flow, settings] of hires) { - hired[seatId] = (await app.act("ops", "hire", { seatId, flow, settings, instructions: `You are ${seatId}.` })).status; - } - // A seat fired before this change, the way that fire left it: its roster row - // gone, its inventory row still there. - const key = `${ROSTER}${fixture.firedBeforeSeat}`; - const stored = await stores.resourceState.get("org", fixture.orgId, key); - if (stored !== undefined) await stores.resourceState.delete("org", fixture.orgId, key, stored.version); - Object.assign(result, { hired, roster: Object.keys(await rows(ROSTER)), inventory: Object.keys(await rows(SEATS)) }); -} - -if (step === "ask") { - result.read = await brokenSeats(); - - // Deny: the row must not move. - const before = (await rows(ROSTER))[fixture.cutSeat]; - const denied = await app.act("ops", "repair", { op: "retire", seatId: fixture.cutSeat }); - const deniedSuspension = await suspensionOf(denied.requestId); - const deny = deniedSuspension === undefined ? { status: "no pending ask" } : await resume(denied.requestId, deniedSuspension, "reject"); - result.deny = { - raised: denied.status, - answered: deny.status, - rowUnchanged: JSON.stringify((await rows(ROSTER))[fixture.cutSeat]) === JSON.stringify(before), - stillListed: (await brokenSeats()).entries.some((entry) => entry.seatId === fixture.cutSeat), - }; - - // The asks a person answers after a restart. - const asks: Array<[string, Record]> = [ - ["retire", { op: "retire", seatId: fixture.cutSeat }], - ["rehire", { op: "rehire", seatId: fixture.rehireSeat, flow: fixture.keptKind, settings: { [fixture.requiredSetting]: fixture.settingValue } }], - ["refused", { op: "rehire", seatId: fixture.refusedSeat, flow: fixture.keptKind, settings: { [fixture.requiredSetting]: fixture.settingValue } }], - ]; - const pending: NonNullable = []; - const raised: Record = {}; - for (const [label, input] of asks) { - const asked = await app.act("ops", "repair", input); - raised[label] = asked.status; - const suspensionId = await suspensionOf(asked.requestId); - if (suspensionId !== undefined) pending.push({ label, requestId: asked.requestId, suspensionId }); - } - result.raised = raised; - writeFileSync(statePath, JSON.stringify({ ...state, pending })); -} - -if (step === "answer") { - const answered: Record = {}; - for (const ask of state.pending ?? []) { - answered[ask.label] = (await resume(ask.requestId, ask.suspensionId, "approve")).status; - } - result.answered = answered; -} - -if (step === "verify") { - const inventory = await rows(SEATS); - const roster = await rows(ROSTER); - const teamList = listedSeatRows( - fixture.orgId, - Object.values(inventory) as Array<{ id: string; kind: string }>, - Object.values(roster).map((row) => ({ - seatId: String(row.seatId), - incarnation: typeof row.incarnation === "string" ? row.incarnation : null, - })), - ); - const answers: Record = {}; - for (const seatId of [fixture.healthySeat, fixture.rehireSeat, fixture.refusedSeat]) { - const address = `${fixture.orgId}.${seatId}`; - const ran = await app.act(address, "answer", { tag: fixture.marker }); - answers[seatId] = { status: ran.status, kind: app.runtime.registry.get(address)?.kind }; - } - Object.assign(result, { - read: await brokenSeats(), - teamList: teamList.map((row) => row.id), - inventory: Object.keys(inventory), - roster: Object.keys(roster), - answers, - }); -} - -process.stdout.write(`RESULT ${JSON.stringify(result)}\n`); -process.exit(0); diff --git a/goals/lib/index.mts b/goals/lib/index.mts index 83ce978351..c1af2fe80b 100644 --- a/goals/lib/index.mts +++ b/goals/lib/index.mts @@ -23,3 +23,4 @@ export * from "./model.mts"; export * from "./specs.mts"; export * from "./server.mts"; export * from "./worker-door.mts"; +export * from "./workers.mts"; diff --git a/goals/lib/workers.mts b/goals/lib/workers.mts new file mode 100644 index 0000000000..6ba42c643c --- /dev/null +++ b/goals/lib/workers.mts @@ -0,0 +1,54 @@ +/** + * The installation a goal's app builds, and the copies it registers. + * + * Every worker runs on one registered copy of the flow it names. A worker flow + * is built on the installation (its `session`, its `resources`), and the + * installation reads the flows when it first needs them, so the two are + * built in one step: + * + * ```ts + * const { installation, copies } = installWorkers(workers, (installation) => ({ + * note: defineNoteFlow(installation), + * })); + * ``` + * + * `copies` is `hireWorkforce(installation)`: one copy per worker flow, at its + * kind (`agent` included, bound to the installation when `build` names none), + * and the roster flow. + */ +import type { FlowInstance } from "@flow-state-dev/core/types"; +import { + createWorkerInstallation, + hireWorkforce, + type WorkerInstallation, + type WorkerInstallationOptions, + type WorkerManifest, +} from "@flow-state-dev/workforce"; + +/** What {@link installWorkers} takes beside the workers and the flows. */ +export type InstallWorkersOptions = Omit & { + /** The mailboxes' board ids, for `hireWorkforce`'s unattended-board warning. */ + mailboxBoards?: readonly string[]; +}; + +/** + * Build the installation over `workers` and the worker flows `build` returns + * for it, and register one copy of each. + * + * @throws What `hireWorkforce` throws: a worker that would be refused on its + * first turn, or a worker flow that doesn't declare the installation's session. + */ +export function installWorkers( + workers: readonly WorkerManifest[], + build: (installation: WorkerInstallation) => Record, + options: InstallWorkersOptions = {}, +): { installation: WorkerInstallation; copies: FlowInstance[] } { + const { mailboxBoards, ...rest } = options; + let flows: Record = {}; + const installation = createWorkerInstallation({ ...rest, standardWorkers: workers, workerFlows: () => flows as never }); + flows = build(installation); + return { + installation, + copies: hireWorkforce(installation, mailboxBoards === undefined ? {} : { mailboxBoards }), + }; +} diff --git a/goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/fixtures/workforce/teams/ops/mailboxes/desk/MAILBOX.md b/goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/fixtures/workforce/teams/ops/mailboxes/desk/MAILBOX.md deleted file mode 100644 index 157b902b63..0000000000 --- a/goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/fixtures/workforce/teams/ops/mailboxes/desk/MAILBOX.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -description: Where the ops team takes requests, and keeps the tasks it hands out. -members: [ops.auditor] -boards: [work] ---- - -Requests come in here. Each task names the worker it is for. diff --git a/goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/fixtures/workforce/teams/ops/workers/auditor/WORKER.md b/goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/fixtures/workforce/teams/ops/workers/auditor/WORKER.md deleted file mode 100644 index 2d51f8f0a0..0000000000 --- a/goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/fixtures/workforce/teams/ops/workers/auditor/WORKER.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -description: Audits what it is asked to, and answers in as few words as it can. ---- - -Do exactly what the task asks. When a task asks for one word, reply with that word and nothing else. diff --git a/goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/goal.md b/goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/goal.md deleted file mode 100644 index e353dff30c..0000000000 --- a/goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/goal.md +++ /dev/null @@ -1,33 +0,0 @@ -# mailbox-boards › it hands a task to a fresh hire - -**Issue:** FIX-1778 (the spec's goal, check VG) - -**Outcome:** A coordinator hires a worker for a skill nobody has, files it a task by name on a mailbox's task list, and the worker receives that task and runs it. The same holds for a worker hired before a restart, and for a worker the files declare on a list no code wired it to. A name nobody holds is refused when the task is filed. - -**Input:** `fixtures/workforce/` — one team `ops`, one mailbox `desk` whose `MAILBOX.md` declares `boards: [work]`, and one declared worker `auditor` on the built-in `agent` kind. No worker kind is wired to the list. Each task's goal is "Reply with the word `` and nothing else.", the word random hex picked at run time, so a result holding it can only come from a model that read this task. - -**Signal:** four legs over a real `createFlowState` host. The host is played the way an app plays it: the `agent` kind takes tasks from the mailbox's lists, the mailbox checks assignees with the worker lookup's filing check, and a coordinator flow holds the hire tool and a board over the list whose fallback asks the lookup. The legs act only through the coordinator's `hire`, the mailbox's `fileTask` and the coordinator's `drain`. - -(a) **Hired after start.** The coordinator hires an `agent` worker, then files it a task by name and drains. (b) **Hired before a restart.** Hired, the host disposed and rebooted over the same storage (its hires reloaded the way a host reloads them), then filed and drained. (c) **A declared worker** on the list. Each of a–c passes only when: the task settles `completed` with the word in its result; the run the row links to is on the named worker's own flow (its flow id is the worker's address); that run's input holds the task's goal; and no request on any other flow took the task. (d) **A name nobody holds** is refused by `fileTask`, naming it, and no row for it exists. - -**Anti-game:** The check never registers a flow by hand (the hire tool registers, and the boot reload re-registers), never calls the lookup, and never seeds a row. It grades the run off the row's run link and the stored request records, never off the drain's report. The word is held out, so a canned result can't pass. - -**Model:** `openai/gpt-5.4-mini` for the workers, through the AI Gateway (`AI_GATEWAY_API_KEY`). - -**Run:** `pnpm tsx goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/run.mts` - -**Controls:** each must FAIL leg a on "no run on the hire's flow", with the hire landing. - -- `GOAL_CONTROL=fixed-routes`: the board holds one fixed route per declared worker and no lookup, the shape a list had before this change. -- `GOAL_CONTROL=pinned-gate`: the `agent` kind takes tasks only from a list of its own, the shape a kind that declares its own board has. - -Under D3 (ii) legs a and c would subscribe the worker to the list before filing. That fence is checked in the filing door FIX-1779 ships, so this check does not subscribe; re-run it with the subscription once that door lands. - -## Verdict log - -| Date | Commit | Model | Verdict | Notes | -|------|--------|-------|---------|-------| -| 2026-10-05 | claude/project-thread-x3ofux on 4c8e19ef, uncommitted | openai/gpt-5.4-mini | PASS | a: `licenses-eb4a`, hired after start, completed on `org%5Ffresh%5Fhire.licenses-eb4a` with result `"adff3827"`. b: `keeper-d107`, hired before the restart, completed on its address with `"905c7712"`. c: `ops.auditor` completed on `ops.auditor` with `"dd1b8034"`. d: `nobody-4988` refused, "unknown-assignee: No worker is named \"nobody-4988\"", no row. | -| 2026-10-05 | same (control: `fixed-routes`) | openai/gpt-5.4-mini | FAIL (expected) | a and b: "no run on the hire's flow", the row errored "no block registered under key \"licenses-8a38\" … Available: ops.auditor". The hires landed. c passed on its fixed route. | -| 2026-10-05 | same (control: `pinned-gate`) | openai/gpt-5.4-mini | FAIL (expected) | a, b and c: "no run on the hire's flow", the row left `in_progress`: the worker's task door refused a list it does not take tasks from, before reading the row. The hires landed. | -| 2026-10-05 | 3f7ee50d + review fixes (filer at hand-over, queued door) | openai/gpt-5.4-mini | PASS | a: `licenses-6d27` → "c9ceae73". b: `keeper-d1da` → "b0d3d9c2". c: `ops.auditor` → "6494cad9". d: `nobody-9103` refused "unknown-assignee". | diff --git a/goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/run.mts b/goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/run.mts deleted file mode 100644 index c15f93bdb8..0000000000 --- a/goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/run.mts +++ /dev/null @@ -1,334 +0,0 @@ -/** - * Goal check — a task on a mailbox's task list names a worker, including one - * hired a moment ago, and that worker receives the task and runs it. - * - * One app, played the way a host plays it: a mailbox with one task list that - * no worker kind was wired to, the `agent` kind taking tasks from the - * mailbox's lists, a coordinator flow holding the hire tool and a board over - * the list whose fallback asks the worker lookup who a name means. The legs - * act only through the coordinator's hire, the mailbox's `fileTask` and the - * coordinator's drain. Nothing here registers a worker by hand, calls the - * lookup, or seeds a row. - * - * Legs: - * a an `agent` worker hired after start is handed a task filed for it by name - * b the same, for a worker hired before a restart - * c a worker the files declare, on a list no code wired it to - * d a name nobody holds is refused at filing, and no row exists - * - * Each of a–c passes only when the task settles `completed` with the held-out - * word in its result, the run that settled it is on the named worker's own - * flow (its id is the worker's address), that run's input holds the task's - * goal, and no other flow ran the task. - * - * Run: pnpm tsx goals/mailbox-boards/it-hands-a-task-to-a-fresh-hire/run.mts - * Controls (must FAIL leg a on "a run on the hire's flow"): - * GOAL_CONTROL=fixed-routes the board has only a fixed route per declared worker, no lookup - * GOAL_CONTROL=pinned-gate the agent kind takes tasks only from a list of its own - */ -import { randomBytes } from "node:crypto"; -import { fileURLToPath } from "node:url"; -import { defineFlow, dispatcher } from "@flow-state-dev/core"; -import type { FlowInstance, TaskFlowTarget } from "@flow-state-dev/core/types"; -import { createFlowState, createModelResolver, inMemoryStores, runAction } from "@flow-state-dev/engine"; -import type { FlowStateRuntime } from "@flow-state-dev/engine"; -import { taskBoard } from "@flow-state-dev/orchestration/task-board"; -import { - HIRED_ROSTER_RESOURCE, - SEAT_INVENTORY_RESOURCE, - createSeatHireBlocks, - createWorkerLookup, - defineAgentWorkerFlow, - defineHiredRosterCollection, - defineMailboxFlow, - defineSeatInventoryCollection, - hireWorkforce, - mailboxBoard, - mailboxBoardIds, - mailboxInstances, - openMailboxes, - reloadHiredSeats, - seatAddress, - type MailboxManifest, - type WorkerLookup -} from "@flow-state-dev/workforce"; -import { readMailboxesDirectory, readWorkforce } from "@flow-state-dev/workforce/loader"; -import { runGoal } from "../../lib/index.mts"; - -const TREE = fileURLToPath(new URL("./fixtures/workforce", import.meta.url)); -const MODEL = "openai/gpt-5.4-mini"; -const ORG_ID = "org_fresh_hire"; -const USER_ID = "u_coordinator"; -const CONTROL = process.env.GOAL_CONTROL ?? ""; - -// A bare createModelResolver rejects an env intent-ladder override; clear it so -// the resolver wires the AI Gateway from AI_GATEWAY_API_KEY. -for (const key of Object.keys(process.env)) { - if (key === "FSDEV_DEFAULT_MODEL" || key.startsWith("FSDEV_INTENT_")) delete process.env[key]; -} - -type Act = (flow: FlowInstance, sessionId: string, actionName: string, input: unknown) => Promise<{ output?: any; error?: any }>; - -interface Host { - runtime: FlowStateRuntime; - act: Act; - mailbox: FlowInstance; - mailboxId: string; - listName: string; - listId: string; - coordinator: FlowInstance; - declaredWorker: string; - dispose: () => Promise; -} - -/** Boot the app over `adapter`: what a host does at start, including reloading its hires. */ -async function boot(adapter: unknown): Promise { - const roster = await readWorkforce(TREE); - const read = await readMailboxesDirectory(TREE); - if (roster.errors.length > 0 || read.errors.length > 0) throw new Error("the tree did not load cleanly"); - const mailboxes: MailboxManifest[] = read.mailboxes; - const holding = mailboxes.find((m) => ((m.declared.boards as string[] | undefined) ?? []).length > 0)!; - const listName = (holding.declared.boards as string[])[0]!; - const list = mailboxBoard(holding.id, listName); - const listIds = mailboxBoardIds(mailboxes); - - let lookup: WorkerLookup | undefined; - let runtime: FlowStateRuntime | undefined; - - // Under `pinned-gate` a worker takes tasks only from a list of its own, - // the way a kind that declares its own board does. - const agent = defineAgentWorkerFlow({ - model: MODEL, - taskLists: CONTROL === "pinned-gate" ? [mailboxBoard("ops.own", listName).id] : listIds - }); - const kinds = { agent } as never; - const declared = hireWorkforce(roster.workers, { workerFlows: kinds, mailboxBoards: listIds }); - const declaredWorker = declared[0]!.id; - - const [mailbox] = mailboxInstances(mailboxes, { - kinds: { - mailbox: defineMailboxFlow({ - checkAssignee: (name, listId, ctx) => lookup!.filingCheck()(name, listId, ctx) - }) as never - } - }); - - let state: ReturnType | undefined; - const hire = createSeatHireBlocks({ - workerFlows: kinds, - register: (seat, pin) => state!.register(seat, { pin }), - unregister: (id) => state!.unregister(id), - kindAt: (id) => runtime?.registry.get(id)?.kind, - instanceAt: (id) => runtime?.registry.get(id) - }); - - // The coordinator's board over the list. Its fallback hands each task to - // whichever worker its name means; under `fixed-routes` it holds one fixed - // route per worker the files declare, and nothing else. - const handOver = (name: string, flowKind: string | TaskFlowTarget) => - dispatcher({ name, action: "work", session: "per-task", flowKind } as never); - const board = taskBoard({ - name: "desk", - boardId: list.id, - collection: list, - concurrency: 1, - ...(CONTROL === "fixed-routes" - ? { workers: Object.fromEntries(declared.map((w) => [w.id, handOver(`route-${w.id}`, w.id)])) } - : { - workers: {}, - defaultWorker: handOver("hand-over", (task, ctx) => lookup!.flowKind(task, ctx)) - }) - } as never); - const coordinator = defineFlow({ - kind: "coordinator", - resources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection() - }, - actions: { hire: { block: hire.hire }, drain: { block: board.drain } } - } as never)({ id: "coordinator" }) as FlowInstance; - - state = createFlowState({ - flows: { - [mailbox!.kind]: mailbox!, - [coordinator.id]: coordinator, - ...Object.fromEntries(declared.map((w) => [w.id, w])) - }, - stores: { default: { primary: adapter } }, - modelResolver: createModelResolver() - } as never); - runtime = await state.getRuntime(); - const live = runtime; - - // The host's boot: workers hired before this start come back. - const reloaded = await reloadHiredSeats({ stores: live.stores, orgIds: [ORG_ID], workerFlows: kinds }); - for (const seat of reloaded.seats) state.register(seat, { pin: seat.ownerPin! }); - lookup = createWorkerLookup({ instanceAt: (id) => live.registry.get(id), declared: declared.map((w) => w.id) }); - - await openMailboxes(mailboxes, { client: sessionApi(live), userId: USER_ID }).catch(() => undefined); - - const act: Act = async (flow, sessionId, actionName, input) => { - try { - return (await runAction({ - flow, - actionName, - input, - userId: USER_ID, - orgId: ORG_ID, - sessionId, - stores: live.stores, - runtimeConfig: { ...live.runtimeConfig } - } as never)) as { output?: any; error?: any }; - } catch (error) { - return { error }; - } - }; - - return { - runtime: live, - act, - mailbox: mailbox!, - mailboxId: holding.id, - listName, - listId: list.id, - coordinator, - declaredWorker, - dispose: () => state!.dispose() - }; -} - -/** File a task for `name`, drain the list, and grade what ran it. */ -async function leg(h: Host, label: string, name: string, address: string, failures: string[]): Promise { - const word = randomBytes(4).toString("hex"); - const goal = `Reply with the word ${word} and nothing else.`; - const filed = await h.act(h.mailbox, h.mailboxId, "fileTask", { board: h.listName, goal, assignee: name }); - const taskId = filed.output?.taskId as string | undefined; - if (taskId === undefined) { - failures.push(`${label}: the task for "${name}" was not filed: ${String(filed.error?.message ?? filed.error)}`); - return `${label}: not filed`; - } - - const drained = await h.act(h.coordinator, "s_coordinator", "drain", {}); - if (drained.error !== undefined) failures.push(`${label}: the drain failed: ${String(drained.error?.message ?? drained.error)}`); - - let row: Record | undefined; - for (let i = 0; i < 600; i += 1) { - row = (await h.runtime.stores.resourceState.get("org", ORG_ID, `${h.listId}/${taskId}`))?.state as Record | undefined; - if (row?.status === "completed" || row?.status === "errored") break; - await new Promise((resolve) => setTimeout(resolve, 200)); - } - - // A run on the named worker's flow: the run the row links to. - const linked = row?.run?.sessionId === undefined ? undefined : await h.runtime.stores.session.get(row.run.sessionId); - const runFlow = (linked as { flowId?: string } | undefined)?.flowId; - if (runFlow !== address) { - failures.push(`${label}: no run on the hire's flow — the task's run is on ${JSON.stringify(runFlow)}, not "${address}" (row ${row?.status}: ${row?.error ?? ""})`); - } - // That run's input holds this task's goal. - const request = row?.run?.requestId === undefined ? undefined : await h.runtime.stores.request.get(row.run.requestId); - if (!JSON.stringify((request as { input?: unknown } | undefined)?.input ?? "").includes(word)) { - failures.push(`${label}: the run's input does not hold the task's goal`); - } - // No other flow ran it. - const all = await h.runtime.stores.request.list({ userId: USER_ID }); - const others = all.filter( - (r) => (r as { input?: { taskId?: string } }).input?.taskId === taskId && (r as { flowId?: string }).flowId !== address - ); - if (others.length > 0) failures.push(`${label}: ${others.length} run(s) on other flows took the task`); - if (row?.status !== "completed") failures.push(`${label}: the task is ${row?.status}, not completed`); - if (!String(row?.output ?? "").toLowerCase().includes(word)) { - failures.push(`${label}: the result ${JSON.stringify(row?.output)} does not hold the word ${word}`); - } - return `${label}: "${name}" → ${row?.status} on ${runFlow}, result ${JSON.stringify(row?.output)} (word ${word})`; -} - -await runGoal(async () => { - const failures: string[] = []; - const evidence: string[] = []; - const adapter = inMemoryStores(); - - // ---- a. hired after start --------------------------------------------------- - let h = await boot(adapter); - const freshName = `licenses-${randomBytes(2).toString("hex")}`; - const hired = await h.act(h.coordinator, "s_coordinator", "hire", { - seatId: freshName, - flow: "agent", - instructions: "You audit our dependencies' licenses. When a task asks for one word, reply with only that word." - }); - const freshAddress = seatAddress(ORG_ID, freshName); - if (hired.output?.address !== freshAddress) { - failures.push(`a: the hire did not land: ${String(hired.error?.message ?? JSON.stringify(hired.output))}`); - } else { - evidence.push(await leg(h, "a", freshName, freshAddress, failures)); - } - - // ---- b. hired before a restart ---------------------------------------------- - const keptName = `keeper-${randomBytes(2).toString("hex")}`; - const kept = await h.act(h.coordinator, "s_coordinator", "hire", { - seatId: keptName, - flow: "agent", - instructions: "When a task asks for one word, reply with only that word." - }); - if (kept.error !== undefined) failures.push(`b: the hire did not land: ${String(kept.error?.message ?? kept.error)}`); - await h.dispose(); - h = await boot(adapter); - evidence.push(await leg(h, "b", keptName, seatAddress(ORG_ID, keptName), failures)); - - // ---- c. a declared worker, on a list no code wired it to -------------------- - evidence.push(await leg(h, "c", h.declaredWorker, h.declaredWorker, failures)); - - // ---- d. a name nobody holds --------------------------------------------------- - const ghost = `nobody-${randomBytes(2).toString("hex")}`; - const refused = await h.act(h.mailbox, h.mailboxId, "fileTask", { board: h.listName, goal: "never filed", assignee: ghost }); - const listed = await h.act(h.mailbox, h.mailboxId, "readBoard", { board: h.listName }); - const ghostRows = ((listed.output?.tasks ?? []) as Array<{ assignee?: string }>).filter((t) => t.assignee === ghost); - if (refused.error === undefined) failures.push(`d: a task for "${ghost}" was filed`); - else if (!String(refused.error?.message).includes(ghost)) failures.push(`d: the refusal does not name "${ghost}": ${refused.error?.message}`); - if (ghostRows.length > 0) failures.push(`d: ${ghostRows.length} row(s) exist for "${ghost}"`); - evidence.push(`d: "${ghost}" → ${String(refused.error?.message ?? "filed")}`); - - await h.dispose(); - return { failures, evidence: evidence.join("\n") }; -}); - -/** `openMailboxes`'s session API, as the session route would bind it. */ -function sessionApi(runtime: FlowStateRuntime) { - const stores = runtime.stores; - return { - createSession: async (options: { flowKind: string; userId: string; sessionId?: string; orgId?: string; description?: string; state?: Record }) => { - const id = String(options.sessionId); - if ((await stores.session.get(id)) !== undefined) { - throw Object.assign(new Error(`Session "${id}" 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 ?? ORG_ID, - description: options.description, - 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)) as - | { flowKind: string; flowId?: string; userId: string; orgId?: string; state?: Record } - | undefined; - return { flowKind: String(found?.flowKind), flowId: found?.flowId, userId: String(found?.userId), orgId: found?.orgId, state: found?.state }; - }, - deleteSession: async (sessionId: string) => { - await stores.session.delete(sessionId); - } - }; -} diff --git a/goals/mailbox-boards/it-runs-a-row-a-file-declared-board-holds/run.mts b/goals/mailbox-boards/it-runs-a-row-a-file-declared-board-holds/run.mts index 005bfb4bb0..81f3284966 100644 --- a/goals/mailbox-boards/it-runs-a-row-a-file-declared-board-holds/run.mts +++ b/goals/mailbox-boards/it-runs-a-row-a-file-declared-board-holds/run.mts @@ -33,7 +33,7 @@ import { join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { z } from "zod"; import { defineFlow, dispatcher, handler } from "@flow-state-dev/core"; -import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; +import { createFlowState, inMemoryStores, runAction, ensureSessionRecord } from "@flow-state-dev/engine"; import { taskBoard, taskWorkerInputSchema } from "@flow-state-dev/orchestration/task-board"; import type { Task, TaskWorkerInput } from "@flow-state-dev/orchestration/tasks"; import { @@ -41,7 +41,7 @@ import { mailboxBoard, mailboxBoardIds, mailboxInstances, - hireWorkforce, + createWorkerInstallation, hireWorkforce, openMailboxes, workerConfigSchema, type MailboxManifest, @@ -114,11 +114,15 @@ await runGoal(async () => { } } - // ---- the two kinds. Neither writes a ledger id. --------------------------- + // ---- the two kinds, each one copy for its workers. Neither writes a ledger id. + let workerFlows: Record = {}; + const installation = createWorkerInstallation({ standardWorkers: workers, workerFlows: () => workerFlows as never }); const emKind = defineFlow({ kind: "em", cardinality: "collection", configSchema: workerConfigSchema(), + session: installation.session(), + resources: { ...installation.resources }, actions: { ...workerDoor, file: { // The EM has no board, no collection and no drain — the one line that @@ -169,8 +173,9 @@ await runGoal(async () => { kind: "coder", cardinality: "collection", configSchema: workerConfigSchema(), - // The whole of what a seat declares to reach the mailbox's ledger. - resources: { [seatBoard.id]: seatBoard }, + session: installation.session(), + // The whole of what a seat declares to reach the mailbox's ledger, beside the installation's. + resources: { [seatBoard.id]: seatBoard, ...installation.resources }, actions: { ...workerDoor, drain: { block: board.drain } } } as never); @@ -180,8 +185,8 @@ await runGoal(async () => { mailboxKinds: Record; }; const instances = mailboxInstances(mailboxes, { kinds: generated.mailboxKinds }); - const seats = hireWorkforce(workers, { - workerFlows: { em: emKind as never, coder: coderKind as never }, + workerFlows = { em: emKind, coder: coderKind }; + const seats = hireWorkforce(installation, { // One warning on stderr is expected, naming the board nobody drains. A // warning naming the coder's board would mean its declaration missed. mailboxBoards: mailboxBoardIds(mailboxes) @@ -268,6 +273,19 @@ await runGoal(async () => { const mailboxInstance = instances.find((instance) => instance.kind === MAILBOX_KIND)!; const em = seats.find((seat) => seat.kind === "em")!; const coder = seats.find((seat) => seat.kind === "coder")!; + /** A worker's own session on its flow's one copy, created naming it. */ + const seatSession = async (flow: { id: string; kind: string }) => { + const worker = workers.find((w) => w.declared.flow === flow.kind)!.id; + const sessionId = `s_${worker}`; + const now = Date.now(); + await ensureSessionRecord( + runtime.stores, + sessionId, + { flow: flow as never, sessionId, principal: { userId: USER_ID, orgId: ORG_ID }, state: { workerId: worker }, fromCaller: true, via: "create" }, + () => ({ id: sessionId, flowKind: flow.kind, flowId: flow.id, userId: USER_ID, orgId: ORG_ID, version: 0, createdAt: now, updatedAt: now, journal: [] }) as never + ); + return sessionId; + }; // ---- b. the mailbox says what it holds, by name ------------------------- const view = await act(mailboxInstance, mailbox.id, "read", {}); @@ -279,7 +297,7 @@ await runGoal(async () => { // ---- c. one seat files one row, through the mailbox --------------------- const goal = `wire the ${boardName} board end to end`; - const filed = await act(em, `s_${em.id}`, "file", { goal }); + const filed = await act(em, await seatSession(em), "file", { goal }); if (filed.error !== undefined) { failures.push(`the EM seat could not file a row: ${String(filed.error)}`); } @@ -287,7 +305,7 @@ await runGoal(async () => { // ---- d. the OTHER seat's board claims it and runs it -------------------- // Nothing here names the row, the assignee or the worker: the drain is // handed nothing but a request to run. - const drained = await act(coder, `s_${coder.id}`, "drain", {}); + const drained = await act(coder, await seatSession(coder), "drain", {}); if (drained.error !== undefined) { failures.push(`the coder seat's board could not drain: ${String(drained.error)}`); } diff --git a/goals/manager-queue-lab/it-routes-a-queue-to-the-seats-their-files-name/run.mts b/goals/manager-queue-lab/it-routes-a-queue-to-the-seats-their-files-name/run.mts index f08412c5ec..5981de97b5 100644 --- a/goals/manager-queue-lab/it-routes-a-queue-to-the-seats-their-files-name/run.mts +++ b/goals/manager-queue-lab/it-routes-a-queue-to-the-seats-their-files-name/run.mts @@ -388,8 +388,13 @@ await runGoal(async () => { ); } // Nothing of the coordinator's travels with the row. The brief IS the - // row; there is no ambient dump. - const carried = JSON.stringify(session.state ?? {}); + // row; there is no ambient dump. The one thing the session holds is the + // worker it runs, which is the seat that claimed the row. + const { workerId, ...rest } = (session.state ?? {}) as Record; + if (workerId !== line.seat) { + note(`row ${row.id}'s child session names worker ${String(workerId)}, not ${line.seat}, which ran it`); + } + const carried = JSON.stringify(rest); if (carried.includes("desk-") || carried.length > 2) { note(`row ${row.id}'s child session carries state it was not handed: ${carried}`); } diff --git a/goals/manager-queue-lab/lab/host.mts b/goals/manager-queue-lab/lab/host.mts index 7ed009530d..2b44a1821b 100644 --- a/goals/manager-queue-lab/lab/host.mts +++ b/goals/manager-queue-lab/lab/host.mts @@ -4,7 +4,9 @@ * and differ by one block. * * What `openLab` does, in order, and nothing else: read the tree, build the - * kinds, hire, register, open the mailbox, hand back handles. Every file it + * installation and its two worker flows, register one copy of each, open the + * mailbox, hand back handles. Every worker drains in its own session on its + * flow's copy, and the session names it. Every file it * reads is found by walking from one root; no file is named in this code. * * ## The three things that are the lab's rather than the framework's @@ -30,7 +32,7 @@ * out here either. */ -import { createFlowState, runAction } from "@flow-state-dev/engine"; +import { createFlowState, ensureSessionRecord, runAction } from "@flow-state-dev/engine"; import type { BlockDefinition, FlowInstance } from "@flow-state-dev/core/types"; import type { Task } from "@flow-state-dev/orchestration/tasks"; import { @@ -38,6 +40,7 @@ import { mailboxBoard, mailboxBoardIds, mailboxInstances, + createWorkerInstallation, hireWorkforce, openMailboxes, type MailboxBoardCollection, @@ -217,7 +220,7 @@ export interface OpenLabOptions { /** Everything a check needs to drive and observe one lab. */ export interface Lab { roster: DeclaredRoster; - /** The hired seats, by id. */ + /** Each worker's flow copy, by the worker's id. */ seats: Record; /** The coordinator seat's id, read off the tree rather than named. */ coordinatorId: string; @@ -331,7 +334,17 @@ export async function openLab(options: OpenLabOptions): Promise { const drainWidth = options.drainWidth ?? drainWidthFromEnv(); + // The installation the two worker flows run their workers on. It reads the + // flows when it first needs them, so they are built on it below. + let workerFlows: Record = {}; + const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: () => workerFlows as never, + seatBlocks, + }); + const builderKind = defineBuilderWorkerFlow({ + installation, board, desks, assignees, @@ -357,6 +370,7 @@ export async function openLab(options: OpenLabOptions): Promise { })); const coordinator = defineCoordinatorWorkerFlow({ + installation, board, composeBoard: options.composeBoard ?? true, ...(options.door === undefined ? {} : { door: options.door }), @@ -364,21 +378,20 @@ export async function openLab(options: OpenLabOptions): Promise { seats: hiredSeats, }); - // Refuses the WHOLE roster when any record cannot be hired, naming the - // worker. Nothing is returned partially, so a refusal cannot leave a short - // roster running — which is where BR-3's seat-folder board lands. - const hired = hireWorkforce(workers, { - workerFlows: { - [COORDINATOR_KIND]: coordinator.kind as never, - [BUILDER_KIND]: builderKind as never, - }, - seatBlocks, + // Refuses the WHOLE roster when any worker would be refused on its turn, + // naming the worker. Nothing is registered partially, so a refusal cannot + // leave a short roster running — which is where BR-3's seat-folder board lands. + workerFlows = { [COORDINATOR_KIND]: coordinator.kind, [BUILDER_KIND]: builderKind }; + const hired = hireWorkforce(installation, { // Every minted id is declared by a hired seat, so this says nothing. A // warning on stderr here would mean a builder's declaration missed. mailboxBoards: mailboxBoardIds(mailboxes), }); const seats: Record = Object.fromEntries( - hired.map((seat) => [seat.id, seat]), + workers.map((worker) => [ + worker.id, + hired.find((copy) => copy.kind === worker.declared.flow) as FlowInstance, + ]), ); const instances = mailboxInstances(mailboxes); @@ -386,7 +399,7 @@ export async function openLab(options: OpenLabOptions): Promise { const state = createFlowState({ flows: { ...Object.fromEntries(instances.map((instance) => [instance.kind, instance])), - ...Object.fromEntries(hired.map((seat) => [seat.id, seat])), + ...Object.fromEntries(hired.map((copy) => [copy.id, copy])), }, stores: { default: { primary: options.stores } }, ...(options.modelResolver === undefined ? {} : { modelResolver: options.modelResolver }), @@ -466,6 +479,38 @@ export async function openLab(options: OpenLabOptions): Promise { await openMailboxes(mailboxes, { client, userId: LAB_USER_ID }); + // Each worker's drain session, created naming it, the way the session route + // creates one: the installation's check runs, and the name is readonly after. + for (const worker of workers) { + const sessionId = drainSessionId(worker.id); + const now = Date.now(); + await ensureSessionRecord( + runtime.stores, + sessionId, + { + flow: seats[worker.id] as never, + sessionId, + principal: { userId: LAB_USER_ID, orgId: LAB_ORG_ID }, + state: { workerId: worker.id }, + fromCaller: true, + via: "create", + }, + () => + ({ + id: sessionId, + flowKind: seats[worker.id]!.kind, + flowId: seats[worker.id]!.id, + userId: LAB_USER_ID, + orgId: LAB_ORG_ID, + lineageId: `lin_${sessionId}`, + version: 0, + createdAt: now, + updatedAt: now, + journal: [], + }) as never, + ); + } + const mailboxInstance = instances.find((instance) => instance.kind === MAILBOX_KIND); if (mailboxInstance === undefined) { throw new Error(`the tree at ${root} produced no "${MAILBOX_KIND}" instance to act on`); diff --git a/goals/manager-queue-lab/lab/workforce/flows/workers/builder.mts b/goals/manager-queue-lab/lab/workforce/flows/workers/builder.mts index 53fb63c56f..9f4e936f42 100644 --- a/goals/manager-queue-lab/lab/workforce/flows/workers/builder.mts +++ b/goals/manager-queue-lab/lab/workforce/flows/workers/builder.mts @@ -2,7 +2,8 @@ * The `builder` worker kind — one file under `workforce/flows/workers/`, * basename = the kind id every builder `WORKER.md` names in its `flow:` line. * - * Three seats are hired onto this one kind. What makes them different is the + * Three seats are workers on this one flow, one registered copy, each draining + * in its own session, which names it. What makes them different is the * routing key each answers for, and **that key reaches a seat two ways on * purpose**, because the whole of BR-4 lives in the gap between them: * @@ -10,8 +11,9 @@ * is the implementation under test. It narrows what the seat's drain claims * and it is the only thing VG's negative control moves. * - **The tree** — each `WORKER.md`'s own `answersFor:` line, which arrives in - * the seat's config bag and is reported back out from inside the running - * work. This is the oracle, and it is never read by any wiring here. + * the worker's settings when its turn loads it and is reported back out from + * inside the running work. This is the oracle, and it is never read by any + * wiring here. * * Grading the map against itself would move the oracle along with the * implementation and the control would stay green. So the wiring reads the map @@ -43,9 +45,10 @@ * * The seat under `workers` is a `dispatcher({ action, session: "per-task" })` — * a **same-flow hand-off**. The row is claimed by the drain and then run in its - * own child session, on this same flow instance, at the `task` entry below. One - * ledger declaration, one hop, and a child session per row that carries a - * `parentSessionId` and none of the coordinator's transcript. + * own child session, on this same flow, at the `task` entry below, naming the + * same worker as the drain that claimed it. One ledger declaration, one hop, + * and a child session per row that carries a `parentSessionId` and none of the + * coordinator's transcript. * * Nothing here declares the ledger a second time: the entry is reachable from * this flow's own board, which is what the orphan-task-entry guard wants. The @@ -61,7 +64,13 @@ import { type TaskDispatcher, type TaskWorkerInput, } from "@flow-state-dev/orchestration/tasks"; -import { workerConfigSchema, type MailboxBoardCollection } from "@flow-state-dev/workforce"; +import { + WORKER_ID_STATE_KEY, + workerConfigOf, + workerConfigSchema, + type MailboxBoardCollection, + type WorkerInstallation, +} from "@flow-state-dev/workforce"; import { appendFileSync } from "node:fs"; import { z } from "zod"; import { ledgerOf } from "../../../ledger.mts"; @@ -96,13 +105,22 @@ export const HOLD_ENTRY = "hold"; */ const ANSWERS_FOR_KEY = "answersFor"; -/** What a builder seat's settings bag holds: the contract, plus its own desk. */ +/** + * What a builder seat's settings bag holds: the contract, plus its own desk. + * Optional here because the flow's one copy has no desk of its own; each + * worker's file names one, and the host routes only the workers that do. + */ export function builderSettingsSchema() { return workerConfigSchema().extend({ - [ANSWERS_FOR_KEY]: z.string().min(1), + [ANSWERS_FOR_KEY]: z.string().min(1).optional(), }); } +/** The worker a builder session runs, as its session names it (checked when the session was created). */ +function seatOf(ctx: BlockContext): string { + return String((ctx.session.state as Record)[WORKER_ID_STATE_KEY] ?? ""); +} + /** The parts of the bag this module reads where the bag's type is erased. */ interface BuilderConfig { answersFor: string; @@ -110,7 +128,7 @@ interface BuilderConfig { /** One line the work leaves behind — a real file, outside the board entirely. */ export const workLineSchema = z.object({ - /** The seat instance that ran it, off `ctx.flow.id`. */ + /** The worker that ran it, off the session it ran in. */ seat: z.string(), /** What that seat's OWN FILE says it answers for — the oracle, from the tree. */ declaredAssignee: z.string(), @@ -127,9 +145,9 @@ export type WorkLine = z.infer; /** * A claim narrowed to one seat's desk. * - * Per **seat**, resolved at claim time off `ctx.flow.id`, because three seats - * share one kind and therefore one board object: a key captured when the board - * was built would be one key for all three. + * Per **seat**, resolved at claim time off the drain session's worker, because + * three seats share one flow and therefore one board object: a key captured + * when the board was built would be one key for all three. * * A seat the map does not name claims nothing at all, rather than falling back * to a bare claim — the failure a fallback produces is a seat quietly eating @@ -138,8 +156,7 @@ export type WorkLine = z.infer; function deskDispatcher(assignees: Record): TaskDispatcher { return { async claim(collection, workerId, ctx) { - const seat = String((ctx.flow as { id?: string }).id ?? ""); - const desk = assignees[seat]; + const desk = assignees[seatOf(ctx)]; if (desk === undefined) return null; return collection.claim(workerId, { // No status arm — claimability is the substrate's call, and adding one @@ -152,6 +169,8 @@ function deskDispatcher(assignees: Record): TaskDispatcher { } export interface BuilderWorkerFlowOptions { + /** The installation that runs this flow's workers. */ + installation: WorkerInstallation; /** The mailbox's own ledger — the one the `MAILBOX.md` declared by name. */ board: MailboxBoardCollection; /** @@ -193,7 +212,7 @@ export interface BuilderWorkerFlowOptions { * * @param options The ledger, the board's desk vocabulary, the seat map under * test, the drain width, and where finished work leaves its line. - * @returns The flow factory `hireWorkforce` mints one copy of per builder record. + * @returns The flow `hireWorkforce` registers one copy of, for every builder worker. */ export function defineBuilderWorkerFlow(options: BuilderWorkerFlowOptions) { const outbox = options.outbox; @@ -215,9 +234,9 @@ export function defineBuilderWorkerFlow(options: BuilderWorkerFlowOptions) { inputSchema: taskWorkerInputSchema, outputSchema: workLineSchema, execute: async (input: TaskWorkerInput, ctx: BlockContext): Promise => { - const config = ctx.flow.config as unknown as BuilderConfig; + const config = workerConfigOf(ctx) as unknown as BuilderConfig; const line: WorkLine = { - seat: String((ctx.flow as { id?: string }).id ?? ""), + seat: seatOf(ctx) || "", declaredAssignee: config.answersFor, taskId: input.taskId, goal: input.goal, @@ -246,6 +265,8 @@ export function defineBuilderWorkerFlow(options: BuilderWorkerFlowOptions) { name: `${BUILDER_KIND}-hand-off-${desk}`, action: WORK_ENTRY, session: "per-task", + // The row's session names the worker whose drain claimed it. + state: (_task, ctx) => ({ [WORKER_ID_STATE_KEY]: seatOf(ctx) }), }), ]), ), @@ -265,7 +286,7 @@ export function defineBuilderWorkerFlow(options: BuilderWorkerFlowOptions) { inputSchema: z.object({}).optional(), outputSchema: z.object({ taskId: z.string().nullable(), leaseMs: z.number() }), execute: async (_input: unknown, ctx: BlockContext) => { - const seat = String((ctx.flow as { id?: string }).id ?? ""); + const seat = seatOf(ctx); const desk = options.assignees[seat]; const ledger = await ledgerOf(ctx, options.board.id); const claimed = await ledger.claim(`hold:${seat}`, { @@ -276,10 +297,24 @@ export function defineBuilderWorkerFlow(options: BuilderWorkerFlowOptions) { }, }); + const installation = options.installation; + /** Loads the turn's worker, on every run of a request, so `workerConfigOf` reads it. */ + const loadWorker = handler({ + name: `${BUILDER_KIND}-load-worker`, + inputSchema: z.unknown(), + resources: { ...installation.resources }, + execute: async (_input: unknown, ctx: BlockContext) => ({ + worker: (await installation.resolveWorker(ctx as never, BUILDER_KIND)).id, + }), + }); + return defineFlow({ kind: BUILDER_KIND, cardinality: "collection", configSchema: builderSettingsSchema(), + session: installation.session(), + resources: { [options.board.id]: options.board, ...installation.resources }, + request: { onStarted: loadWorker }, actions: { ...workerDoor, [DRAIN_ENTRY]: { block: board.drain, diff --git a/goals/manager-queue-lab/lab/workforce/flows/workers/coordinator.mts b/goals/manager-queue-lab/lab/workforce/flows/workers/coordinator.mts index 94421805af..1f39208e7c 100644 --- a/goals/manager-queue-lab/lab/workforce/flows/workers/coordinator.mts +++ b/goals/manager-queue-lab/lab/workforce/flows/workers/coordinator.mts @@ -47,8 +47,10 @@ import { buildTaskToolsList } from "@flow-state-dev/orchestration"; import type { Task } from "@flow-state-dev/orchestration/tasks"; import { mailboxBoardTaskTools, + workerConfigOf, workerConfigSchema, type MailboxBoardCollection, + type WorkerInstallation, } from "@flow-state-dev/workforce"; import { z } from "zod"; import { ledgerOf, rowsOf } from "../../../ledger.mts"; @@ -94,6 +96,16 @@ interface CoordinatorConfig { model?: string; } +/** + * The settings this turn runs with: the coordinator worker's, as its turn + * loaded them. A probe that resolves the generator's tools outside any turn + * (it has no session) hands them as `ctx.flow.config` instead. + */ +function settingsOf(ctx: BlockContext): CoordinatorConfig { + const probe = (ctx as { session?: object }).session === undefined; + return (probe ? ctx.flow.config : workerConfigOf(ctx)) as unknown as CoordinatorConfig; +} + /** What intake is handed: the pieces of work, in the words they arrived in. */ export const intakeInputSchema = z.object({ work: z.array(z.string().min(1)).min(1), @@ -120,6 +132,8 @@ function noteTool(): GeneratorTool { } export interface CoordinatorWorkerFlowOptions { + /** The installation that runs this flow's workers. */ + installation: WorkerInstallation; /** The mailbox's own ledger — the one the `MAILBOX.md` declared by name. */ board: MailboxBoardCollection; /** @@ -152,7 +166,7 @@ export interface CoordinatorWorkerFlowOptions { * * @param options The ledger, whether to compose the board capability, the * default model, and the seats the queue reports on. - * @returns `{ kind, intake }` — the flow `hireWorkforce` mints a copy of, and + * @returns `{ kind, intake }` — the flow `hireWorkforce` registers a copy of, and * the generator itself, so a check can read the tool names it resolves * without having to run a model to find out. */ @@ -278,7 +292,6 @@ export function defineCoordinatorWorkerFlow(options: CoordinatorWorkerFlowOption const intake = generator({ name: "coordinator-intake", inputSchema: intakeInputSchema, - flowConfigSchema: coordinatorSettingsSchema(), // The grant, and the whole of it — under the lab's own door. ...(options.composeBoard && door === "capability" ? { uses: [mailboxBoardTaskTools(board)] } @@ -288,15 +301,12 @@ export function defineCoordinatorWorkerFlow(options: CoordinatorWorkerFlowOption // what taking the other door costs. ...(door === "catalog" ? { resources: { [board.id]: board } } : {}), prompt: [ - (_input: unknown, ctx: BlockContext) => - (ctx.flow.config as unknown as CoordinatorConfig).teamInstructions, - (_input: unknown, ctx: BlockContext) => - (ctx.flow.config as unknown as CoordinatorConfig).instructions, + (_input: unknown, ctx: BlockContext) => settingsOf(ctx).teamInstructions, + (_input: unknown, ctx: BlockContext) => settingsOf(ctx).instructions, ], - model: (_input: unknown, ctx: BlockContext) => - (ctx.flow.config as unknown as CoordinatorConfig).model ?? options.defaultModel, + model: (_input: unknown, ctx: BlockContext) => settingsOf(ctx).model ?? options.defaultModel, tools: (_input: unknown, ctx: BlockContext): GeneratorTool[] => - (ctx.flow.config as unknown as CoordinatorConfig).tools + (settingsOf(ctx).tools ?? []) .map((name) => catalog[name]) .filter((tool): tool is GeneratorTool => tool !== undefined), user: (input: z.infer) => @@ -304,10 +314,24 @@ export function defineCoordinatorWorkerFlow(options: CoordinatorWorkerFlowOption input.work.map((piece, index) => `${index + 1}. ${piece}`).join("\n"), } as never); + const installation = options.installation; + /** Loads the turn's worker, on every run of a request, so `workerConfigOf` reads it. */ + const loadWorker = handler({ + name: `${COORDINATOR_KIND}-load-worker`, + inputSchema: z.unknown(), + resources: { ...installation.resources }, + execute: async (_input: unknown, ctx: BlockContext) => ({ + worker: (await installation.resolveWorker(ctx as never, COORDINATOR_KIND)).id, + }), + }); + const kind = defineFlow({ kind: COORDINATOR_KIND, cardinality: "collection", configSchema: coordinatorSettingsSchema(), + session: installation.session(), + resources: { [board.id]: board, ...installation.resources }, + request: { onStarted: loadWorker }, actions: { ...workerDoor, [INTAKE_ENTRY]: { block: intake, description: "Take work in and file it onto the board." }, [QUEUE_ENTRY]: { block: readQueue, description: "Read the queue. Writes nothing." }, diff --git a/goals/org-seats/cos-changes-the-roster/goal.md b/goals/org-seats/cos-changes-the-roster/goal.md deleted file mode 100644 index c09b278802..0000000000 --- a/goals/org-seats/cos-changes-the-roster/goal.md +++ /dev/null @@ -1,97 +0,0 @@ -# org-seats › the chief of staff changes the roster - -**Issue:** FIX-1719 - -**Outcome:** A Lab that declares a chief of staff gets it as a running seat, and a person changes -who works there by asking it. A hire lands at once. A fire lands only after the person approves it. -Both hold across restarts. - -Before this, a Lab's seats were whatever its files declared. Adding or removing one meant editing -a folder and restarting the server. No seat could do it, and no person could ask for it. - -**Input:** the DevTeam profile (`packages/shift-manager/teams/devteam`), whose tree -(`packages/shift-manager/teams/devteam/workforce`) declares `org/workers/chief-of-staff`. The check serves it -three times through Shift Manager's own command, over one SQLite file it owns. The seat it -asks for is **held out**: `coder-`, picked at run time, so no file in the repository -can name it. The mailbox and its members are read off the tree, never spelled in the check. - -**Signal:** nine legs, read through the routes Shift Manager reads. The seat inventory comes through -the mailbox's session, the stored roster through the chief of staff's, and whether a seat answers -comes from opening a session on its address. - -1. **boot**: the chief of staff is listed from the tree, on the `agent` kind, with a door. No - other declared seat names `hire`, `fire` or `rehire`. -2. **discover**: asked who is on the feature mailbox, the chief of staff calls `discover`, and what - that turn's `discover` calls returned lists every declared member by its full id (`eng.em`, not - `em`, matched as a whole id) in the mailbox's member list, and gives each one the kind its file - declares (`em`, `coder`, `agent`). Members and kinds may come from separate calls in the turn. - Graded on the tool's output, read off the session's `tool_output` items, never on the answer's - wording: who is on a mailbox is data, and the check does not grade the model reciting it. -3. **hire**: asked for a coder under the held-out id, it hires one at once. No approval is raised. - The seat is listed, its roster row is written, and its address answers. -4. **discover hired** (BR-23): in a fresh session, asked which workers the organization has hired - (the question names neither the worker nor a kind), the chief of staff calls `discover`, and a - result in that turn carries the held-out worker by its full id on kind `coder`. Graded on the - tool's output, as in leg 2. -5. **restart**: after a restart the hired seat is still listed, still rostered, and still answers. -6. **ask**: asked to fire it, the turn suspends on one `human_approval` naming the verb, the seat - and its kind. Nothing has changed yet. -7. **answer**: the approval goes through the engine's resume route, as Inbox sends it. The route - takes it and the turn completes. -8. **seat gone**: after a second restart the seat has no inventory row and no roster row, and its - address no longer answers. -9. **a seat asks** (BR-21): a declared seat, not the person, asks the chief of staff for a hire, - and the hire lands. DevTeam has no seat that messages another (its EM files rows, its coder and - reviewer run a harness), so this leg runs its own small host in process (`seat-asks.mts`): a - chief of staff holding `hire` on a real model, and an `ops.lead` seat whose one job posts its - own file's request into `ops.room` as itself. The held-out seat id lives only in that file; the - check starts the seat with an empty input. Nothing new carries the request: the post goes - through the mailbox's own `post` with the seat's `seatId` as author, and the mailbox's notify - hands it to the chief of staff's `onMailboxPost`, where the agent kind hears a post. Graded on - what the mailbox handed the chief of staff (exactly one delivery, author `ops.lead`) and on all - three of a hire's outcomes for the held-out id: its roster row and its inventory row, both on - kind `agent`, and its address answering a session opened through the session route. - -**Anti-game:** no hire or fire block is called by the check. Every change goes through the chief -of staff's own turn on a real model, and every restart is a new process over the same file. The -grade is read off the stores through the HTTP routes, never off the model's words. - -**Control** (`GOAL_CONTROL=list` prints it). It must go red: - -| Control | Perturbs | Goes red on | -|---|---|---| -| `deny-fire` | the person's answer: Deny instead of Approve | **seat gone** only: the seat is still listed, rostered and answering. **answer** stays green, since the route takes a Deny and the turn completes | -| `hide-hired-from-discover` | the hired seat's roster row, which discover reads a hire from, is moved aside for the discover-hired turn and put back after | **discover hired** only: the answer lists the declared seats and not the hire; every later leg stays green | -| `drop-member-from-discover` | one member is taken out of the mailbox's inventory row, which discover reads members from, for the discover turn and put back after | **discover** only: the turn's result lists the mailbox without that member; every later leg stays green | -| `no-seat-delivery` | the mailbox's notify hands the seat's post to nobody | **a seat asks** only: no delivery to the chief of staff, and no roster row, no inventory row and no address for the held-out id | - -The tree with no chief of staff (today's `main`) goes red at **boot**: `Unknown flow -"chief-of-staff"`. - -**Model:** `openai/gpt-5.4-mini` for the chief of staff, through the default resolver. Needs one of -`AI_GATEWAY_API_KEY`, `OPENAI_API_KEY` or `OPENROUTER_API_KEY`. With none set, the check fails -with a precondition message and grades nothing. - -**Run:** `pnpm tsx goals/org-seats/cos-changes-the-roster/run.mts` - -**Controls:** `GOAL_CONTROL=deny-fire pnpm tsx goals/org-seats/cos-changes-the-roster/run.mts`, -`GOAL_CONTROL=no-seat-delivery pnpm tsx goals/org-seats/cos-changes-the-roster/run.mts`, -`GOAL_CONTROL=hide-hired-from-discover pnpm tsx goals/org-seats/cos-changes-the-roster/run.mts`, -`GOAL_CONTROL=drop-member-from-discover pnpm tsx goals/org-seats/cos-changes-the-roster/run.mts` - -## Verdict log -| Date | Commit | Model | Verdict | Notes | -|------|--------|-------|---------|-------| -| 2026-10-02 | a65594ee1+wip (FIX-1719 PR 2) | openai/gpt-5.4-mini | PASS | All six legs green. `deny-fire` FAILS at seat gone (listed, rostered, answering). With `org/` removed from the tree it FAILS at boot (`Unknown flow "chief-of-staff"`). The fire only suspended once core's lazily loaded models carried `generateStep`/`streamStep`; before that, the ask came back to the model as a failed tool call and the turn completed with no approval raised. | -| 2026-10-02 | 3307072fd (FIX-1719 PR 2, Codex round 2 + #2649 round 5) | openai/gpt-5.4-mini | PASS | All six legs green; the ask now carries `owner: null` and the row's incarnation. `deny-fire` FAILS at seat gone (listed, rostered, answering). One earlier `deny-fire` run stopped at discover instead, the model answering without naming the members; the rerun reached seat gone. | -| 2026-10-02 | 145c1eac7 (FIX-1719 PR 2, Codex round 4 + #2649 93da431f5 + #2645 c1ee781d0) | openai/gpt-5.4-mini | PASS | All six legs green; discover now names `chief-of-staff` among eng.feature's members. `deny-fire` FAILS at seat gone (listed, rostered, answering). One earlier run stopped at discover, the model answering without calling `discover`; the rerun passed. | -| 2026-10-02 | 29c794d58+round 5 (FIX-1719 PR 2, Codex review 5394601632) | openai/gpt-5.4-mini | PASS | All six legs green with the stricter checks: the hired row is kind `coder` in the roster and the inventory, before and after the restart, and the fire raised exactly one `human_approval` naming verb, seat, kind and message. `deny-fire` FAILS at seat gone (listed, rostered, answering). | -| 2026-10-02 | a27de5337+round 6 (FIX-1719 PR 2, Codex reviews 5394840713 + 5394907534) | openai/gpt-5.4-mini | PASS | All seven legs green; the resume and the turn settling are now their own **answer** leg. `deny-fire` FAILS at seat gone only (listed, rostered, answering); answer stays green. | -| 2026-10-02 | fb1b751cd+BR-21 (FIX-1719 PR 2, Codex 5395145040) | openai/gpt-5.4-mini | PASS | All eight legs green, including **a seat asks**: `ops.lead` posted its own request as itself, the mailbox handed the chief of staff one post from `ops.lead`, and the held-out seat has a roster row on kind `agent`. `deny-fire` FAILS at seat gone only. `no-seat-delivery` FAILS at a seat asks only (no delivery, no row); every DevTeam leg stays green. | -| 2026-10-02 | 79440ac14+round 10 (FIX-1719 PR 2, Codex round 10) | openai/gpt-5.4-mini | PASS | All eight legs green with the stricter checks: **a seat asks** now needs the roster row, the inventory row (both kind `agent`) and the address answering 201 on the session route; **discover** needs every member's full seat id. `deny-fire` FAILS at seat gone only. `no-seat-delivery` FAILS at a seat asks only (no delivery, no roster row, no inventory row). | -| 2026-10-02 | 5f89fc3c9+round 11 (FIX-1719 PR 2, Codex round 11) | openai/gpt-5.4-mini | PASS | All nine legs green, including **discover hired**: a fresh session's answer named the held-out seat by its full id with kind `coder`. `hide-hired-from-discover` FAILS at discover hired only (the answer listed the declared seats and not the hire; restart, ask, answer and seat gone stay green). `deny-fire` FAILS at seat gone only. `no-seat-delivery` FAILS at a seat asks only. One earlier control run also stopped at **discover**, the model answering without the members; the rerun did not. | -| 2026-10-02 | b97efb4c6+round 12 (FIX-1719 PR 2, local, not pushed) | openai/gpt-5.4-mini | PASS | **discover** now also needs each member's declared kind on its line. With the first wording ("list each seat's id and the worker kind") one run FAILED at discover, the model declining to give kinds from the mailbox lookup; the question now says to look up each seat. On that wording, 4 of 5 runs PASS all nine legs; one FAILED at **hire**, the model refusing to hire without a `document` setting it had read on `eng.coder`. Controls on the final code: `hide-hired-from-discover` FAILS at discover hired only, `deny-fire` at seat gone only, `no-seat-delivery` at a seat asks only. | -| 2026-10-02 | 484158ba2+P1s (FIX-1719 PR 2, local, merged with main fe3d41fe1, not pushed) | openai/gpt-5.4-mini | PASS | All nine legs green on the tree merged with main (#2645, #2649, #2647). `deny-fire` FAILS at seat gone only, `no-seat-delivery` at a seat asks only, `hide-hired-from-discover` at discover hired only. | -| 2026-10-05 | 3aae17e28+FIX-1781 | openai/gpt-5.4-mini | PASS | On `3aae17e28` the check FAILED 5 of 5 standalone runs at **discover**: `discover` returned all four members, and the answer left out `chief-of-staff` (once `eng.em` too). The chief of staff's `WORKER.md` now says to name every member a mailbox lookup returns, itself included. 10 standalone runs: **discover** green in all 10; 9 PASS all nine legs, one FAILED at **hire** (the model refusing to hire a `coder` without `settings.document`, the miss already logged on 2026-10-02). `deny-fire` FAILS at seat gone only, `no-seat-delivery` at a seat asks only, `hide-hired-from-discover` at discover hired only. | -| 2026-10-05 | f609f03f1+review (FIX-1781, #2768) | openai/gpt-5.4-mini | PASS | Self-inclusion is now conditional on `discover` returning the chief of staff, so it can't add itself to a mailbox it isn't on. The bare conditional ("when you are one of them, list yourself too") FAILED 1 of 5 at **discover** (`chief-of-staff` left out). The final wording ("drop none ... leaving yourself out is the usual mistake") PASSED 8 of 8 standalone. Asked five times who is on `eng.triage` (members: `eng.em`), the answer named only `eng.em`. `deny-fire` FAILS at seat gone only, `no-seat-delivery` at a seat asks only, `hide-hired-from-discover` at discover hired only. | -| 2026-10-05 | 031e74065+deterministic discover (FIX-1781, #2768) | openai/gpt-5.4-mini | PASS | The prompt lines telling the chief of staff to list every member, itself included, are reverted from its `WORKER.md` and the docs page. **discover** and **discover hired** now grade what the turn's `discover` calls returned, not the answer. 12 standalone runs: 11 PASS all nine legs; one FAILED at **discover**: the model called `discover` on mailboxes and workers with `detail: "thin"`, which returns no member list and no kinds, and then answered anyway (`eng.coder`, `eng.em`, `eng.reviewer — reviewer`: the chief of staff missing, one kind wrong). A thin mailbox entry carries no members at all, so that answer was a guess. Controls: `deny-fire` FAILS at seat gone only; `hide-hired-from-discover` at discover hired only; `drop-member-from-discover` at discover only (`3 members: eng.em, eng.coder, eng.reviewer`). `no-seat-delivery` FAILED at a seat asks only on its second run; its first also FAILED at **discover**, the turn's results giving no kinds. | diff --git a/goals/org-seats/cos-changes-the-roster/run.mts b/goals/org-seats/cos-changes-the-roster/run.mts deleted file mode 100644 index 501ab99cde..0000000000 --- a/goals/org-seats/cos-changes-the-roster/run.mts +++ /dev/null @@ -1,538 +0,0 @@ -/** - * Goal check: a Lab that declares a chief of staff gets it as a running seat, - * and a person changes who works there by asking it. A hire lands at once, a - * fire lands only on Approve, and both hold across restarts. See goal.md. - * - * Real path, real model. The DevTeam profile (`packages/shift-manager/teams/ - * devteam`) is served by Shift Manager's own command over a SQLite file - * this check owns, started three times over that one file. Every change goes - * through the chief of staff's own turn on `openai/gpt-5.4-mini`; the approval - * goes through the engine's resume route, as Inbox sends it. What happened is - * read through the Lab's routes, the ones Shift Manager reads: the seat - * inventory through the mailbox's session, the roster through the chief of - * staff's, a seat's address by opening a session on it. - * - * Legs (each failure is tagged with its leg): - * - * boot the chief of staff is listed from the tree, on the agent kind, - * with a door; no other declared seat names a hire or fire tool - * discover asked who is on the feature mailbox, it calls discover, and what - * that turn's discover calls returned lists every declared member - * by its full id, each on the kind its file declares (graded on - * the tool's output, never on the answer's wording) - * hire asked for a seat, it hires one at once: no ask is raised, the - * seat is listed, its roster row is written, its address answers - * discover hired in a fresh session, asked which workers were hired, it - * calls discover, and what it returned carries the new worker by - * its full id on kind coder - * restart after a restart the hired seat is still listed and answers - * ask asked to fire it, it raises one human_approval naming the seat, - * and nothing changes yet - * answer the resume route takes the answer and the turn completes - * seat gone on Approve, and after a second restart, the seat is gone from - * the inventory and the roster, and its address no longer answers - * a seat asks a declared seat posts its own hire request into its mailbox, - * the mailbox hands it to the chief of staff from that seat, and - * the hire lands: roster row, inventory row, and an address that - * answers (its own small host: seat-asks.mts) - * - * Controls: - * - * deny-fire Deny instead of Approve. Must fail at "seat gone" only. - * no-seat-delivery The mailbox hands the seat's post to nobody. Must fail at - * "a seat asks" only. - * hide-hired-from-discover The hired seat's roster row, which discover reads - * a hire from, is moved aside for the discover-hired turn - * and put back after. Must fail at "discover hired" only. - * drop-member-from-discover One member is taken out of the mailbox's - * inventory row, which discover reads members from, for the - * discover turn and put back after. Must fail at "discover" - * only. - * - * Run: pnpm tsx goals/org-seats/cos-changes-the-roster/run.mts - * Control: GOAL_CONTROL=deny-fire pnpm tsx goals/org-seats/cos-changes-the-roster/run.mts - * Control: GOAL_CONTROL=no-seat-delivery pnpm tsx goals/org-seats/cos-changes-the-roster/run.mts - * Control: GOAL_CONTROL=hide-hired-from-discover pnpm tsx goals/org-seats/cos-changes-the-roster/run.mts - * Control: GOAL_CONTROL=drop-member-from-discover pnpm tsx goals/org-seats/cos-changes-the-roster/run.mts - */ -import { spawn, type ChildProcess } from "node:child_process"; -import { randomBytes } from "node:crypto"; -import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { createSQLiteStores } from "@flow-state-dev/store-sqlite"; -import { HIRED_ROSTER_PREFIX } from "@flow-state-dev/workforce"; -import { readDeclaredRoster } from "@flow-state-dev/workforce/loader"; -import { LAB_ORG_ID } from "../../../packages/shift-manager/teams/devteam/host.mts"; -import { CODER_KIND } from "../../../packages/shift-manager/teams/devteam/workforce/flows/workers/coder.mts"; -import { REPO_ROOT, goalTmpDir, intentFreeEnv, runGoal } from "../../lib/index.mts"; -import { SHIFT_MANAGER_COMMAND, servedAddresses } from "../../lib/shift-manager.mts"; -import { ASKER, runSeatAsks } from "./seat-asks.mts"; - -const CONTROL = process.env.GOAL_CONTROL ?? ""; -const CONTROLS = ["deny-fire", "no-seat-delivery", "hide-hired-from-discover", "drop-member-from-discover"] as const; - -/** Whether `text` names `id` exactly: not inside a longer id, not as a bare suffix of it. */ -function standsAlone(text: string, id: string): boolean { - return new RegExp(`(? new Promise((resolve) => setTimeout(resolve, ms)); - -// ---- serving the Lab ----------------------------------------------------------- - -type Served = { origin: string; child: ChildProcess; exited: Promise; log: () => string }; - -/** - * Serve DevTeam over `store` through Shift Manager's command. The pages - * are a stub: this check reads routes, never the screen. - */ -async function startDevTeam(store: string, pages: string): Promise { - const workDir = mkdtempSync(join(SCRATCH, "run-")); - let log = ""; - const child = spawn(TSX, [SHIFT_MANAGER_COMMAND, "--config", DEVTEAM_CONFIG, "--port", "0", "--no-open", "--assets", pages], { - cwd: workDir, - env: intentFreeEnv(process.env, { INIT_CWD: workDir, GOAL_CONTROL: "", DEVTEAM_STORE: store }), - stdio: ["ignore", "pipe", "pipe"], - }); - child.stdout!.on("data", (d) => (log += String(d))); - child.stderr!.on("data", (d) => (log += String(d))); - let gone = false; - const exited = new Promise((resolve) => - child.on("exit", () => { - gone = true; - resolve(); - }), - ); - for (let waited = 0; waited < 120_000; waited += 250) { - const served = servedAddresses(log); - if (served !== undefined) return { origin: served.origin, child, exited, log: () => log }; - if (gone) break; - await sleep(250); - } - child.kill("SIGTERM"); - throw new Error(`Shift Manager's command never served DevTeam. Log tail:\n${log.slice(-3000)}`); -} - -async function stop(served: Served): Promise { - served.child.kill("SIGTERM"); - await served.exited; -} - -// ---- the Lab's routes ------------------------------------------------------------ - -type Item = { - id: string; - type: string; - status?: string; - role?: string; - output?: unknown; - toolCall?: { name?: string; arguments?: string }; - requestId?: string; - suspensionId?: string; - reason?: string; - message?: string; - data?: unknown; - content?: unknown; -}; - -async function labApi(origin: string) { - // The person's identity and bearer, as the page is handed them. - const html = await (await fetch(`${origin}/`)).text(); - const config = /window\.__FSD_DEVTOOL_CONFIG__ = (\{.*?\});<\/script>/.exec(html)?.[1]; - if (config === undefined) throw new Error("the served page carries no connection config"); - const { userId, bearerToken } = JSON.parse(config) as { userId: string; bearerToken?: string }; - const enc = encodeURIComponent; - - const call = async (method: string, path: string, body?: unknown): Promise<{ status: number; body: any }> => { - const response = await fetch(`${origin}/api/flows${path}`, { - method, - headers: { "content-type": "application/json", ...(bearerToken === undefined ? {} : { authorization: `Bearer ${bearerToken}` }) }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }); - const text = await response.text(); - return { status: response.status, body: text.length === 0 ? null : JSON.parse(text) }; - }; - const get = async (path: string): Promise => { - const { status, body } = await call("GET", path); - if (status !== 200) throw new Error(`GET ${path}: ${status} ${JSON.stringify(body)}`); - return body; - }; - - /** Every row of the collection at `pattern`, read through a session whose flow declares it. */ - const collection = async (sessionId: string, pattern: string): Promise>> => { - const manifest = await get(`/sessions/${enc(sessionId)}/manifest`); - const ref = (manifest.resources as Array<{ kind: string; pattern?: string; ref: string }>).find( - (r) => r.kind === "collection" && r.pattern === pattern, - )?.ref; - if (ref === undefined) throw new Error(`session ${sessionId} declares no collection ${pattern}`); - const rows: Array> = []; - let cursor: string | undefined; - for (let page = 0; page < 50; page += 1) { - const body = await get(`/sessions/${enc(sessionId)}/resources/${enc(ref)}?limit=200${cursor === undefined ? "" : `&cursor=${enc(cursor)}`}`); - rows.push(...((body.items ?? []) as Array<{ clientData?: Record }>).map((i) => i.clientData ?? {})); - if (body.nextCursor === undefined || body.nextCursor === cursor) break; - cursor = body.nextCursor; - } - return rows; - }; - - /** A new session on `flowId` for the person, or the refusal. */ - const openSession = (flowId: string) => call("POST", `/${enc(flowId)}/sessions`, { userId }); - - /** Every item of `types` in one session, in stored order. */ - const items = async (sessionId: string, types: string): Promise => { - const out: Item[] = []; - for (let offset = 0, page = 0; page < 50; page += 1) { - const body = await get(`/sessions/${enc(sessionId)}/state?include_items=true&item_types=${types}&offset=${offset}&limit=200`); - out.push(...(body.items ?? [])); - if (body.pagination?.hasMore !== true) break; - offset = body.pagination.nextOffset ?? offset + 200; - } - return out; - }; - - /** Wait for a request to leave the running states (and `suspended`, after a resume). */ - const settle = async (flowId: string, requestId: string, resumed = false): Promise => { - const running = ["pending", "queued", "in_progress", "running", ...(resumed ? ["suspended"] : [])]; - for (const until = Date.now() + TURN_MS; Date.now() < until; await sleep(500)) { - const polled = await call("GET", `/${enc(flowId)}/requests/${enc(requestId)}/status`); - const status = polled.body?.status as string | undefined; - if (status !== undefined && !running.includes(status)) return status; - } - return "timed-out"; - }; - - /** Say one line to the chief of staff in `sessionId`, and wait for its turn to end. */ - const say = async (sessionId: string, message: string) => { - const posted = await call("POST", `/${enc(COS)}/${enc(sessionId)}/actions/run`, { userId, input: { message } }); - if (posted.status >= 400) throw new Error(`the chief of staff's door refused the line: ${posted.status} ${JSON.stringify(posted.body)}`); - const requestId = posted.body.request.id as string; - return { requestId, status: await settle(COS, requestId) }; - }; - - /** The text of the last assistant message in a session. */ - const lastReply = async (sessionId: string): Promise => { - const messages = (await items(sessionId, "message")).filter((i) => i.role === "assistant"); - return JSON.stringify(messages.at(-1)?.content ?? ""); - }; - - /** - * What the chief of staff's `discover` calls returned in one turn: how many - * it made, and every entry across them. This, not the answer's wording, is - * what a discover leg grades: who is on a mailbox is data. - */ - const discovered = async (sessionId: string, requestId: string) => { - const calls = (await items(sessionId, "tool_output")).filter( - (i) => i.requestId === requestId && i.toolCall?.name === "discover" && i.status === "completed", - ); - const entries = calls.flatMap((c) => - (((c.output as { domains?: Array<{ entries?: DiscoverEntry[] }> } | undefined)?.domains) ?? []).flatMap((d) => d.entries ?? []), - ); - // Each call's arguments as the model sent them, so a failure says what it asked for. - const asked = calls.map((c) => c.toolCall?.arguments ?? "").join(" "); - return { calls: calls.length, entries, asked }; - }; - - return { userId, call, get, collection, openSession, items, settle, say, lastReply, discovered }; -} - -/** One entry of a `discover` result; `contract` comes back only on `detail: "full"`. */ -type DiscoverEntry = { id: string; kind: string; purpose?: string; contract?: string }; - -/** Whether a seat entry's contract says it runs on `kind` (`Hired into the "" worker kind`). */ -function runsOn(entry: DiscoverEntry | undefined, kind: string): boolean { - return entry?.contract?.includes(`"${kind}" worker kind`) === true; -} - -// ---- the goal ------------------------------------------------------------------ - -await runGoal(async () => { - if (!MODEL_KEYS.some((key) => (process.env[key] ?? "") !== "")) { - return { - failures: [`precondition: the chief of staff runs a real model, and none of ${MODEL_KEYS.join(", ")} is set, so nothing here was checked`], - evidence: "", - }; - } - - // Read off the tree, never spelled here: the org, the mailbox and its members. - const tree = await readDeclaredRoster(DEVTEAM_TREE); - const mailbox = tree.mailboxes[0]; - if (mailbox === undefined) throw new Error("the DevTeam tree declares no mailbox"); - const members = (mailbox.declared.members as string[] | undefined) ?? []; - // The held-out seat: picked now, so no file in the repository can name it. - const seat = `coder-${randomBytes(3).toString("hex")}`; - - mkdirSync(SCRATCH, { recursive: true }); - const pages = mkdtempSync(join(SCRATCH, "pages-")); - writeFileSync(join(pages, "index.html"), "routes only"); - const store = join(mkdtempSync(join(SCRATCH, "store-")), "devteam.sqlite"); - - const failures: string[] = []; - const evidence: string[] = []; - const fail = (leg: string, why: string) => failures.push(`${leg}: ${why}`); - // The seat-asks leg's own failures, kept apart: it runs on its own host, so - // a failure there must not stop the DevTeam legs from being graded. - const seatAskFailures: string[] = []; - /** Every failure, the control's tag on each when one is set. */ - const graded = (): string[] => { - const all = [...seatAskFailures, ...failures]; - return CONTROL === "" ? all : all.map((f) => `[control ${CONTROL}] ${f}`); - }; - - // ---- a seat asks (BR-21): its own small host, since DevTeam has no seat - // that messages another. The request lives only in the asking seat's file. - { - const asked = `helper-${randomBytes(3).toString("hex")}`; - const result = await runSeatAsks(asked, CONTROL === "no-seat-delivery", SCRATCH); - const toCos = result.deliveries.filter((d) => d.member === COS); - const problems: string[] = []; - if (result.startStatus !== "completed") problems.push(`"${ASKER}" did not finish its job: ${result.startStatus}`); - if (toCos.length !== 1 || !toCos[0]!.delivered) { - problems.push(`the mailbox handed "${ASKER}"'s post to the chief of staff ${toCos.filter((d) => d.delivered).length} time(s), not once`); - } else if (toCos[0]!.author !== ASKER) { - problems.push(`the post the chief of staff heard is from ${JSON.stringify(toCos[0]!.author)}, not "${ASKER}"`); - } - // A hire's three outcomes (BR-8): the roster row, the inventory row, and an address that answers. - if (!result.rostered) problems.push(`no roster row for "${asked}" after the seat's request`); - else if (result.rosterKind !== "agent") problems.push(`"${asked}" was hired as ${String(result.rosterKind)}, not "agent"`); - if (result.address === undefined) problems.push(`no inventory row for "${asked}" after the seat's request`); - else if (result.listedKind !== "agent") problems.push(`"${asked}" is listed as kind ${String(result.listedKind)}, not "agent"`); - else if (result.answers !== 201) problems.push(`"${result.address}" does not answer: ${String(result.answers)}`); - if (problems.length > 0) { - for (const problem of problems) seatAskFailures.push(`a seat asks: ${problem}`); - } else { - evidence.push( - `a seat asks: "${ASKER}" posted its own request as itself, the mailbox handed it to the chief of staff from "${ASKER}", ` + - `and "${asked}" has a roster row and an inventory row on kind agent, and ${String(result.address)} answers ${String(result.answers)}; ` + - `the check sent the seat id to no one`, - ); - } - } - - /** The hired seat's address, from the inventory row whose id ends with it. */ - const reads = async (api: Awaited>, cosSession: string) => { - const inventory = await api.collection(mailbox.id, "inventory/seats/*"); - const roster = await api.collection(cosSession, "workforce/roster/*"); - const row = inventory.find((r) => typeof r.id === "string" && (r.id as string).endsWith(`.${seat}`)); - const rosterRow = roster.find((r) => r.seatId === seat); - return { - inventory, - listed: row !== undefined, - address: row?.id as string | undefined, - rostered: rosterRow !== undefined, - // The kind the seat was hired onto, as each collection records it. - listedKind: row?.kind as string | undefined, - rosterKind: rosterRow?.flow as string | undefined, - }; - }; - - // ---- boot 1: the tree's chief of staff, then the hire --------------------- - let served = await startDevTeam(store, pages); - let address: string | undefined; - try { - const api = await labApi(served.origin); - const opened = await api.openSession(COS); - if (opened.status !== 201) { - fail("boot", `the chief of staff's address did not answer: ${opened.status} ${JSON.stringify(opened.body)}`); - return { failures: graded(), evidence: "" }; - } - const cosSession = opened.body.session.id as string; - - const inventory = await api.collection(mailbox.id, "inventory/seats/*"); - const cos = inventory.find((r) => r.id === COS); - if (cos === undefined) fail("boot", `no "${COS}" row in the seat inventory: ${JSON.stringify(inventory.map((r) => r.id))}`); - else if (cos.kind !== "agent" || typeof cos.door !== "string") fail("boot", `"${COS}" is listed as ${JSON.stringify(cos)}`); - const otherHirers = tree.workers.filter( - (w) => w.id !== COS && ((w.declared.tools as string[] | undefined) ?? []).some((t) => ["hire", "fire", "rehire"].includes(t)), - ); - if (otherHirers.length > 0) fail("boot", `seats other than ${COS} name a hire tool: ${otherHirers.map((w) => w.id).join(", ")}`); - evidence.push(`boot: "${COS}" listed on kind ${String(cos?.kind)} with door ${String(cos?.door)}, and no other declared seat names hire or fire`); - - // discover: graded on what the turn's `discover` calls returned, never on - // the answer's wording. Under the control, one member is dropped from the - // mailbox's inventory row (what discover reads members from) for this turn - // only and put back after, so every later leg is unchanged. - const mailboxKey = `inventory/mailboxes/${mailbox.id}`; - const dropped = members.includes(COS) ? COS : members[0]; - const sideDiscover = createSQLiteStores({ filename: store }); - const mailboxRow = CONTROL === "drop-member-from-discover" ? await sideDiscover.resourceState.get("org", LAB_ORG_ID, mailboxKey) : undefined; - if (mailboxRow !== undefined) { - const state = mailboxRow.state as { members?: string[] }; - await sideDiscover.resourceState.set("org", LAB_ORG_ID, mailboxKey, { ...state, members: (state.members ?? []).filter((m) => m !== dropped) } as never, "any" as never); - } - try { - const asked = await api.say(cosSession, `Who is on the ${mailbox.id} mailbox? Look up the mailbox, then look up each of its seats, and list every seat's id with the worker kind it runs on, one seat per line.`); - const found = await api.discovered(cosSession, asked.requestId); - // Each member by its full seat id, standing alone in the mailbox's member - // list (a bare "em" is not "eng.em", and "eng.em" inside a longer id is - // not that seat), and a seat entry with that exact id on the kind its - // file declares. The members and the kinds may come from separate calls. - const kindOf = (id: string) => tree.workers.find((w) => w.id === id)?.declared.flow as string | undefined; - const box = found.entries.find((e) => e.kind === "mailbox" && e.id === mailbox.id); - const missing = members.filter((m) => !standsAlone(box?.contract ?? "", m)); - const wrongKind = members - .filter((m) => kindOf(m) === undefined || !runsOn(found.entries.find((e) => e.kind === "seat" && e.id === m), kindOf(m)!)) - .map((m) => `${m} (kind ${String(kindOf(m))})`); - const said = (await api.lastReply(cosSession)).slice(0, 300); - if (asked.status !== "completed") fail("discover", `the turn ended ${asked.status}`); - else if (found.calls === 0) fail("discover", `the chief of staff answered without calling discover: ${said}`); - else if (box?.contract === undefined) fail("discover", `no discover result in the turn lists ${mailbox.id}'s members (calls: ${found.asked}): ${said}`); - else if (missing.length > 0) fail("discover", `discover returned ${mailbox.id} without ${missing.join(", ")} by full seat id: ${box.contract}`); - else if (wrongKind.length > 0) fail("discover", `no discover result in the turn gives ${wrongKind.join(", ")} (calls: ${found.asked}): ${said}`); - else evidence.push(`discover: asked who is on ${mailbox.id}, its discover calls returned ${members.map((m) => `${m} (${String(kindOf(m))})`).join(", ")}`); - } finally { - if (mailboxRow !== undefined) await sideDiscover.resourceState.set("org", LAB_ORG_ID, mailboxKey, mailboxRow.state as never, "any" as never); - sideDiscover.close(); - } - - // hire - const hired = await api.say(cosSession, `Please hire one more coder for the team, with the seat id "${seat}".`); - const asksAfterHire = (await api.items(cosSession, "suspension")).length; - const afterHire = await reads(api, cosSession); - if (hired.status !== "completed") fail("hire", `the turn ended ${hired.status} (a hire must not wait for anyone)`); - if (asksAfterHire !== 0) fail("hire", `${asksAfterHire} approval(s) were raised for a hire`); - if (!afterHire.listed) fail("hire", `no inventory row for "${seat}": ${JSON.stringify(afterHire.inventory.map((r) => r.id))}`); - if (!afterHire.rostered) fail("hire", `no roster row for "${seat}"; the chief of staff said ${(await api.lastReply(cosSession)).slice(0, 400)}`); - if (afterHire.listed && afterHire.rostered && (afterHire.listedKind !== CODER_KIND || afterHire.rosterKind !== CODER_KIND)) { - fail("hire", `"${seat}" was hired as kind ${String(afterHire.rosterKind)} (roster) / ${String(afterHire.listedKind)} (inventory), not "${CODER_KIND}"`); - } - address = afterHire.address; - if (address !== undefined) { - const answers = await api.openSession(address); - if (answers.status !== 201) fail("hire", `"${address}" does not answer: ${answers.status}`); - else evidence.push(`hire: "${seat}" hired at once as ${address} (kind ${String(afterHire.inventory.find((r) => r.id === address)?.kind)}), no ask raised, its address answers`); - } - - // discover hired (BR-23): a fresh turn finds the seat it just hired. The - // question names neither the seat nor its kind; the line of the answer - // that names the seat must carry both. Under the control, the hired - // seat's roster row (what discover reads a hire from) is moved aside for - // this turn only and put back after, so every later leg is unchanged. - if (address !== undefined) { - const rosterKey = `${HIRED_ROSTER_PREFIX}${seat}`; - const side = createSQLiteStores({ filename: store }); - const hidden = CONTROL === "hide-hired-from-discover" ? await side.resourceState.get("org", LAB_ORG_ID, rosterKey) : undefined; - if (hidden !== undefined) await side.resourceState.delete("org", LAB_ORG_ID, rosterKey, "any" as never); - try { - // A session of its own, so the hire turn's own words can't answer it. - const fresh = (await api.openSession(COS)).body.session.id as string; - const turn = await api.say(fresh, "Which seats has this organization hired? Look it up and give each one's full seat id and the worker kind it was hired into."); - const found = await api.discovered(fresh, turn.requestId); - const entry = found.entries.find((e) => e.kind === "seat" && (e.id === seat || e.id === address)); - const said = (await api.lastReply(fresh)).slice(0, 400); - if (turn.status !== "completed") fail("discover hired", `the turn ended ${turn.status}`); - else if (found.calls === 0) fail("discover hired", `the chief of staff answered without calling discover: ${said}`); - else if (entry === undefined) fail("discover hired", `no discover result in the turn carries "${seat}" by its full id (calls: ${found.asked}): ${said}`); - else if (!runsOn(entry, CODER_KIND)) fail("discover hired", `discover returned "${entry.id}" without its kind "${CODER_KIND}": ${String(entry.contract)}`); - else evidence.push(`discover hired: asked which seats were hired, its discover calls returned ${entry.id} on kind ${CODER_KIND}`); - } finally { - if (hidden !== undefined) await side.resourceState.set("org", LAB_ORG_ID, rosterKey, hidden.state as never, "any" as never); - side.close(); - } - } - } finally { - await stop(served); - } - // A failed discover or discover-hired turn changed nothing (any row a control - // moved is back), so the legs after it still run; any other failure leaves - // nothing to carry on with. - const blocking = failures.filter((f) => !f.startsWith("discover:") && !f.startsWith("discover hired:")); - if (blocking.length > 0 || address === undefined) { - if (blocking.length === 0) fail("hire", "no address to carry on with"); - return { failures: graded(), evidence: evidence.join("; ") }; - } - - // ---- boot 2: the hire held; then the fire, through the person's answer ---- - served = await startDevTeam(store, pages); - try { - const api = await labApi(served.origin); - const cosSession = (await api.openSession(COS)).body.session.id as string; - const afterRestart = await reads(api, cosSession); - if (!afterRestart.listed || !afterRestart.rostered) fail("restart", `after a restart "${seat}" is listed=${afterRestart.listed}, rostered=${afterRestart.rostered}`); - else if (afterRestart.listedKind !== CODER_KIND || afterRestart.rosterKind !== CODER_KIND) { - fail("restart", `after a restart "${seat}" is kind ${String(afterRestart.rosterKind)} (roster) / ${String(afterRestart.listedKind)} (inventory), not "${CODER_KIND}"`); - } - const answers = await api.openSession(address); - if (answers.status !== 201) fail("restart", `after a restart "${address}" does not answer: ${answers.status}`); - else evidence.push(`restart: "${seat}" still listed, rostered and answering`); - - const fire = await api.say(cosSession, `Please fire the seat "${seat}".`); - const asks = (await api.items(cosSession, "suspension")).filter((i) => i.requestId === fire.requestId); - const ask = asks[0] as (Item & { data?: { verb?: string; seatId?: string; kind?: string | null } }) | undefined; - const beforeAnswer = await reads(api, cosSession); - if (fire.status !== "suspended" || ask === undefined) { - fail("ask", `the fire did not wait for a person: the turn ended ${fire.status} with ${asks.length} ask(s); the chief of staff said ${(await api.lastReply(cosSession)).slice(0, 400)}`); - } else if (asks.length !== 1) { - // Exactly one: a second ask on the request would be a second change waiting. - fail("ask", `the fire raised ${asks.length} asks, not one: ${JSON.stringify(asks.map((a) => a.data))}`); - } else { - const askProblems: string[] = []; - if (ask.reason !== "human_approval") askProblems.push(`reason ${JSON.stringify(ask.reason)}`); - if (ask.data?.verb !== "fire") askProblems.push(`verb ${JSON.stringify(ask.data?.verb)}`); - if (ask.data?.seatId !== seat) askProblems.push(`seat ${JSON.stringify(ask.data?.seatId)}`); - if (ask.data?.kind !== CODER_KIND) askProblems.push(`kind ${JSON.stringify(ask.data?.kind)}`); - if (typeof ask.message !== "string" || !ask.message.includes(seat)) askProblems.push(`message ${JSON.stringify(ask.message)}`); - if (askProblems.length > 0) { - fail("ask", `the ask is not a human_approval to fire "${seat}" (kind "${CODER_KIND}"): ${askProblems.join(", ")}`); - return { failures: graded(), evidence: evidence.join("; ") }; - } - if (!beforeAnswer.listed || !beforeAnswer.rostered) fail("ask", `"${seat}" changed before anyone answered`); - else evidence.push(`ask: one ${ask.reason} "${ask.message}" ${JSON.stringify(ask.data)}, "${seat}" untouched while it waits`); - - const action = CONTROL === "deny-fire" ? "reject" : "approve"; - const resumed = await api.call("POST", `/${encodeURIComponent(COS)}/requests/${encodeURIComponent(fire.requestId)}/resume`, { - suspensionId: ask.suspensionId, - action, - }); - // The answer is its own leg, so the control can only go red on what the - // answer did to the seat, never on a refused resume or a stuck turn. - if (resumed.status >= 400) fail("answer", `the resume route refused ${action}: ${resumed.status} ${JSON.stringify(resumed.body)}`); - const settled = await api.settle(COS, fire.requestId, true); - if (settled !== "completed") fail("answer", `after ${action} the turn ended ${settled}`); - if (resumed.status < 400 && settled === "completed") evidence.push(`answer: the resume route took ${action} and the turn completed`); - } - } finally { - await stop(served); - } - - // ---- boot 3: what the answer did, after a second restart ----------------- - served = await startDevTeam(store, pages); - try { - const api = await labApi(served.origin); - const cosSession = (await api.openSession(COS)).body.session.id as string; - const after = await reads(api, cosSession); - const answers = await api.openSession(address); - if (after.listed) fail("seat gone", `"${seat}" is still in the seat inventory after the answer and a restart`); - if (after.rostered) fail("seat gone", `"${seat}" still has a roster row after the answer and a restart`); - if (answers.status === 201) fail("seat gone", `"${address}" still answers after the answer and a restart`); - if (!after.listed && !after.rostered && answers.status !== 201) { - evidence.push(`seat gone: after Approve and a second restart "${seat}" has no inventory row, no roster row, and "${address}" answers ${answers.status}`); - } - } finally { - await stop(served); - } - - return { - failures: graded(), - evidence: `DevTeam served three times by Shift Manager's command over one SQLite file, the chief of staff on a real model. ${evidence.join("; ")}`, - }; -}); diff --git a/goals/org-seats/cos-changes-the-roster/seat-asks.mts b/goals/org-seats/cos-changes-the-roster/seat-asks.mts deleted file mode 100644 index a47bc4f5ab..0000000000 --- a/goals/org-seats/cos-changes-the-roster/seat-asks.mts +++ /dev/null @@ -1,318 +0,0 @@ -/** - * The "a seat asks" leg (BR-21): a declared seat, not the person, asks the - * chief of staff for a hire, and the hire lands. - * - * DevTeam has no seat that messages another seat: its EM files rows and its - * coder and reviewer run a harness. So this leg runs its own small host, in - * process, over a tree written at run time: - * - * - `org/workers/chief-of-staff/` on the built-in `agent` kind, holding `hire`, - * on a real model; - * - `teams/ops/workers/lead/` on this fixture's `requester` kind, whose one - * job is to post its own instructions into its mailbox, as itself. The - * held-out seat id it asks for lives only in that file; - * - `teams/ops/mailboxes/room/`, with both as members. - * - * Nothing new carries the request. The lead posts through the mailbox's own - * `post` action with its `seatId` as the author, which is how a seat posts. - * The mailbox runs its notify block per member, and the block hands the post - * to the chief of staff's `onMailboxPost`, the entry the agent kind hears a - * post on and answers like any message. The stock wake skips a post that - * names an author, so that two seats can't answer each other forever; here - * the lead never hears a post, so no loop can start, and the block delivers - * to the chief of staff only. - * - * `dropDelivery` is the control's seam: the block records the post and hands - * it to nobody. - */ -import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { defineFlow, dispatcher, handler, sequencer } from "@flow-state-dev/core"; -import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; -import { - MAILBOX_KIND, - mailboxInstances, - mailboxNotifyInputSchema, - createSeatHireCapability, - defineAgentWorkerFlow, - defineMailboxFlow, - hireWorkforce, - openMailboxes, - workerConfigSchema, - type MailboxNotifyInput, - type HireOptions, -} from "@flow-state-dev/workforce"; -import { readMailboxesDirectory, readWorkforce } from "@flow-state-dev/workforce/loader"; -import { z } from "zod"; -import { workerDoor } from "../../lib/worker-door.mts"; - -const ORG = "seat-asks"; -const USER = "u_seat_asks"; -const COS = "chief-of-staff"; -/** The seat that asks, by the id its folder gives it. */ -export const ASKER = "ops.lead"; -const MAILBOX = "ops.room"; -const ROSTER_PREFIX = "workforce/roster/"; -const INVENTORY_PREFIX = "inventory/seats/"; - -const files = (requested: string): Record => ({ - "org/workers/chief-of-staff/WORKER.md": `--- -description: The one seat that changes who works here. -flow: agent -model: openai/gpt-5.4-mini -tools: [hire] ---- - -You are the chief of staff for this organization. Seats and people message you -when they need someone hired. When a seat asks you to hire someone, call \`hire\` -with the seat id it names and \`flow: "agent"\`, then say in one sentence what you -did. -`, - "teams/ops/workers/lead/WORKER.md": `--- -description: Leads ops, and asks the chief of staff when the team needs a hand. -flow: requester ---- - -Chief of staff: ops needs another pair of hands. Please hire an agent seat with -the seat id "${requested}". -`, - "teams/ops/mailboxes/room/MAILBOX.md": `--- -description: Where ops talks. -members: [ops.lead, chief-of-staff] ---- - -Ops, and whoever ops asks for help. -`, -}); - -/** Post the seat's own instructions into its mailbox, as the seat. */ -const requester = defineFlow({ - kind: "requester", - cardinality: "collection", - configSchema: workerConfigSchema(), - actions: { ...workerDoor, - start: { - inputSchema: z.object({}).strict(), - block: sequencer({ name: "requester-start", inputSchema: z.object({}).strict() }) - .step( - handler({ - name: "requester-line", - inputSchema: z.object({}).strict(), - outputSchema: z.object({ mailbox: z.string(), body: z.string(), author: z.string() }), - flowConfigSchema: z.object({ seatId: z.string().min(1), instructions: z.string() }), - execute: (_input, ctx) => ({ - mailbox: MAILBOX, - body: ctx.flow.config.instructions.trim(), - author: ctx.flow.config.seatId, - }), - }), - ) - .step( - dispatcher({ - name: "requester-post", - flowKind: MAILBOX_KIND, - action: "post", - inputSchema: z.object({ mailbox: z.string(), body: z.string(), author: z.string() }), - session: { id: (line: { mailbox: string }) => line.mailbox }, - payload: (line: { body: string; author: string }) => ({ body: line.body, author: line.author }), - } as never), - ), - }, - }, -} as never); - -/** What the mailbox handed on, per member. */ -export interface Delivery { - member: string; - author: string | null; - body: string; - delivered: boolean; -} - -/** The notify block: hand a post to the chief of staff, record every member. */ -function notifyCos(log: Delivery[], dropDelivery: boolean) { - const decide = handler({ - name: "seat-asks-decide", - inputSchema: mailboxNotifyInputSchema, - outputSchema: mailboxNotifyInputSchema.extend({ deliver: z.boolean() }), - execute: (post: MailboxNotifyInput) => { - const deliver = post.member === COS && !dropDelivery; - log.push({ member: post.member, author: post.author ?? null, body: post.body, delivered: deliver }); - return { ...post, deliver }; - }, - }); - const toCos = dispatcher({ - name: "seat-asks-to-cos", - flowKind: COS, - action: "onMailboxPost", - inputSchema: mailboxNotifyInputSchema.extend({ deliver: z.boolean() }), - session: { key: (post: MailboxNotifyInput) => `mailbox:${post.mailboxId}` }, - payload: ({ deliver: _deliver, ...post }: MailboxNotifyInput & { deliver: boolean }) => post, - } as never); - return sequencer({ name: "seat-asks-notify", inputSchema: mailboxNotifyInputSchema }) - .step(decide) - .stepIf((post: { deliver: boolean }) => post.deliver, toCos as never); -} - -/** What the leg saw. */ -export interface SeatAsksResult { - requested: string; - startStatus: string | undefined; - deliveries: Delivery[]; - rostered: boolean; - rosterKind: string | undefined; - /** The hired seat's address: the id of the inventory row ending in the seat id, or `undefined` when none is listed. */ - address: string | undefined; - /** The inventory row's kind. */ - listedKind: string | undefined; - /** The status a session opened on the address through the session route got; `undefined` when there was no address. */ - answers: number | undefined; - hireError?: string; -} - -/** - * Boot the host, have the lead do its job, and wait for the hire. - * - * @param requested The held-out seat id, written only into the lead's file. - * @param dropDelivery The control: the mailbox hands the lead's post to nobody. - */ -export async function runSeatAsks(requested: string, dropDelivery: boolean, scratch: string): Promise { - const tree = mkdtempSync(join(scratch, "seat-asks-")); - for (const [rel, text] of Object.entries(files(requested))) { - mkdirSync(join(tree, rel, ".."), { recursive: true }); - writeFileSync(join(tree, rel), text); - } - const { workers, errors } = await readWorkforce(tree); - const { mailboxes, errors: mailboxErrors } = await readMailboxesDirectory(tree); - if (errors.length > 0 || mailboxErrors.length > 0) { - throw new Error(`the fixture tree did not load: ${[...errors, ...mailboxErrors].map((e) => `${e.path}: ${e.error.message}`).join("; ")}`); - } - - const log: Delivery[] = []; - let registrar: { register(seat: never, options: { pin: unknown }): void; unregister(id: string): boolean } | undefined; - const kinds: NonNullable = { requester: requester as never }; - const seatHire = createSeatHireCapability({ - workerFlows: kinds, - register: (seat, pin) => registrar!.register(seat as never, { pin }), - unregister: (id) => registrar!.unregister(id), - allowKinds: ["agent"], - }); - kinds.agent = defineAgentWorkerFlow({ uses: [seatHire] }) as never; - const seats = hireWorkforce(workers, { workerFlows: kinds }); - const mailboxFlows = mailboxInstances(mailboxes, { - kinds: { [MAILBOX_KIND]: defineMailboxFlow({ notify: notifyCos(log, dropDelivery) as never }) as never }, - }); - - const stores = inMemoryStores(); - const state = createFlowState({ - flows: { - ...Object.fromEntries(mailboxFlows.map((flow) => [flow.kind, flow])), - ...Object.fromEntries(seats.map((seat) => [seat.id, seat])), - }, - stores: { default: { primary: stores } }, - // The session route's verified caller: the host's person, in the host's org. - resolvePrincipal: () => ({ userId: USER, orgId: ORG }), - } as never); - const runtime = await state.getRuntime(); - registrar = state as never; - - // The session route's stand-in, binding the host's org as that route would. - await openMailboxes(mailboxes, { - client: { - createSession: async (create: { flowKind: string; userId: string; sessionId?: string; description?: string; state?: Record }) => { - const id = String(create.sessionId); - const now = Date.now(); - await runtime.stores.session.set( - id, - { - id, - flowKind: create.flowKind, - flowId: create.flowKind, - userId: create.userId, - orgId: ORG, - description: create.description, - state: create.state ?? {}, - lineageId: `lin_${id}`, - version: 0, - createdAt: now, - updatedAt: now, - journal: [], - } as never, - "absent", - ); - return { id }; - }, - getSession: async (sessionId: string) => { - const found = (await runtime.stores.session.get(sessionId)) as { flowKind: string; flowId?: string; userId: string; state?: Record } | undefined; - return { flowKind: String(found?.flowKind), flowId: found?.flowId, userId: String(found?.userId), state: found?.state }; - }, - deleteSession: async (sessionId: string) => { - await runtime.stores.session.delete(sessionId); - }, - } as never, - userId: USER, - }); - - // The lead does its job. The check hands it nothing: the request is the lead's own. - const lead = runtime.registry.get(ASKER); - if (lead === undefined) throw new Error(`no "${ASKER}" seat was registered`); - let startStatus: string | undefined; - try { - const started = (await runAction({ - flow: lead, - actionName: "start", - input: {}, - userId: USER, - orgId: ORG, - stores: runtime.stores, - runtimeConfig: { ...runtime.runtimeConfig }, - } as never)) as { requestId?: string; error?: unknown }; - startStatus = - started.error !== undefined - ? `failed: ${String((started.error as Error)?.message ?? started.error)}` - : (await runtime.stores.request.get(started.requestId!))?.status; - } catch (error) { - startStatus = `threw: ${error instanceof Error ? error.message : String(error)}`; - } - - // The hand-offs are detached: wait for a hire's two rows, the roster row and - // the inventory row, up to two minutes. - let row: { state?: unknown } | undefined; - let listed: { id: string; kind?: string } | undefined; - for (let waited = 0; waited < 120_000; waited += 500) { - row = (await runtime.stores.resourceState.get("org", ORG, `${ROSTER_PREFIX}${requested}`)) as typeof row; - const inventory = await runtime.stores.resourceState.getByPrefix("org", ORG, INVENTORY_PREFIX); - listed = Object.values(inventory) - .map((entry) => (entry as { state?: { id?: unknown; kind?: string } }).state) - .find((seat): seat is { id: string; kind?: string } => typeof seat?.id === "string" && seat.id.endsWith(`.${requested}`)); - if (row?.state != null && listed !== undefined) break; - if (dropDelivery && waited >= 10_000) break; - await new Promise((resolve) => setTimeout(resolve, 500)); - } - - // The third outcome: the address answers on the session route a browser opens it through. - let answers: number | undefined; - if (listed !== undefined) { - const router = (await state.getRouter()) as unknown as Record Promise>; - const path = [listed.id, "sessions"]; - const response = await router.POST!( - new Request(`http://goal/api/flows/${path.map(encodeURIComponent).join("/")}`, { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ userId: USER }), - }), - { params: { path } }, - ); - answers = response.status; - } - return { - requested, - startStatus, - deliveries: log, - rostered: row?.state != null, - rosterKind: (row?.state as { flow?: string } | null | undefined)?.flow, - address: listed?.id, - listedKind: listed?.kind, - answers, - }; -} diff --git a/goals/pentest-lab/a-post-reaches-both-declared-seats/run.mts b/goals/pentest-lab/a-post-reaches-both-declared-seats/run.mts index 563f2db6c0..26a4d2c1cb 100644 --- a/goals/pentest-lab/a-post-reaches-both-declared-seats/run.mts +++ b/goals/pentest-lab/a-post-reaches-both-declared-seats/run.mts @@ -1041,8 +1041,8 @@ await runGoal(async () => { } } // A short roster that still runs is the failure being excluded. - if (!refusal.includes("nothing was hired")) { - note(`BR-18/${label}: the refusal does not say nothing was hired: ${refusal}`); + if (!refusal.includes("nothing was registered")) { + note(`BR-18/${label}: the refusal does not say nothing was registered: ${refusal}`); } if (refusal.includes(tree.otherWorker)) { note(`BR-18/${label}: the refusal blames the valid seat "${tree.otherWorker}" too`); diff --git a/goals/pentest-lab/a-seat-answers-from-its-own-document/harness.mts b/goals/pentest-lab/a-seat-answers-from-its-own-document/harness.mts index 608bc5fd02..b32368e906 100644 --- a/goals/pentest-lab/a-seat-answers-from-its-own-document/harness.mts +++ b/goals/pentest-lab/a-seat-answers-from-its-own-document/harness.mts @@ -19,6 +19,7 @@ import { createGateway } from "@ai-sdk/gateway"; import { createModelResolver, generator } from "@flow-state-dev/core"; import { inMemoryStores } from "@flow-state-dev/engine"; +import { workerConfigOf } from "@flow-state-dev/workforce"; const LAB = process.env.LAB_MODULE!; const { openLab, LAB_TREE } = await import(`${LAB}/host.mts`); @@ -53,13 +54,14 @@ const scopeCheck = createScopeCheck(); * The seat's own instructions are the system prompt, its own document is the * context, and its own `tools:` fence decides what it can call. Nothing here * names a seat, a document or a tool: every value comes off the facts the - * reading block produced from that seat's config. + * reading block produced from that seat's config, or off the settings of the + * worker the turn loaded. */ const answer = generator({ name: "probe-answer-with-a-model", inputSchema: seatFactsSchema, prompt: (facts: any) => facts.instructions, - model: (_input: any, ctx: any) => ctx.flow.config.model, + model: (_input: any, ctx: any) => (workerConfigOf(ctx) as { model?: string }).model, context: (facts: any) => ({ your_document: facts.document, your_skills: facts.skillNames @@ -70,7 +72,7 @@ const answer = generator({ // seat may call the catalog keys its own file names, and an empty list means // none — whatever else the catalog carries. tools: (_input: any, ctx: any) => - (ctx.flow.config.tools ?? []).map((key: string) => + (((workerConfigOf(ctx) as { tools?: string[] }).tools) ?? []).map((key: string) => key === scopeCheck.key ? scopeCheck.block : undefined ).filter(Boolean), user: (facts: any) => `${POST}\n\nAnswer in one short line.`, diff --git a/goals/pentest-lab/lab/host.mts b/goals/pentest-lab/lab/host.mts index bbd0d076cb..f0c1f4085e 100644 --- a/goals/pentest-lab/lab/host.mts +++ b/goals/pentest-lab/lab/host.mts @@ -20,7 +20,7 @@ * it fails. */ -import { createFlowState, runAction, type FlowState, type StoreRegistry } from "@flow-state-dev/engine"; +import { createFlowState, ensureSessionRecord, runAction, type FlowState, type StoreRegistry } from "@flow-state-dev/engine"; import { handler } from "@flow-state-dev/core"; import type { BlockDefinition, FlowInstance } from "@flow-state-dev/core/types"; import { z } from "zod"; @@ -28,7 +28,9 @@ import { MAILBOX_KIND, mailboxInstances, defineMailboxFlow, + createWorkerInstallation, hireWorkforce, + inventorySeats, openMailboxes, openInventory, resourcesFromDocs, @@ -295,14 +297,6 @@ export async function openLab(options: OpenLabOptions): Promise { const scopeCheck = options.scopeCheck ?? createScopeCheck(); - const seatKind = defineProbeWorkerFlow({ - answer: options.answer ?? serverAnswer, - catalog: { [scopeCheck.key]: scopeCheck.block }, - resources, - ...(options.defaultModel === undefined ? {} : { defaultModel: options.defaultModel }), - ...(options.suppressPostBack === true ? { postBackEnabled: false } : {}), - }); - // The control mutates the RECORD, before the mint, so a redirected seat // genuinely runs on the other document rather than being graded as if it did. const overrides = options.documentOverrides ?? {}; @@ -320,12 +314,31 @@ export async function openLab(options: OpenLabOptions): Promise { }; }); - // Refuses the WHOLE roster when any record cannot be hired, naming the - // worker. Nothing is returned partially, so a refusal cannot leave a short - // roster running. - const hired = hireWorkforce(workers, { workerFlows: { [SEAT_KIND]: seatKind as never } }); + // The installation the seat flow runs its workers on. It reads the flow when + // it first needs it, so the flow is built on it just below. + let workerFlows: Record = {}; + const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: () => workerFlows as never, + }); + const seatKind = defineProbeWorkerFlow({ + installation, + answer: options.answer ?? serverAnswer, + catalog: { [scopeCheck.key]: scopeCheck.block }, + resources, + ...(options.defaultModel === undefined ? {} : { defaultModel: options.defaultModel }), + ...(options.suppressPostBack === true ? { postBackEnabled: false } : {}), + }); + workerFlows = { [SEAT_KIND]: seatKind }; + + // Refuses the WHOLE roster when any worker would be refused on its turn, + // naming the worker. Nothing is registered partially, so a refusal cannot + // leave a short roster running. + const hired = hireWorkforce(installation); + const seatCopy = hired.find((copy) => copy.kind === SEAT_KIND)!; + // Each worker's flow copy, by the worker's id. const seats: Record = Object.fromEntries( - hired.map((seat) => [seat.id, seat]) + workers.map((worker) => [worker.id, seatCopy]) ); // Who the router can reach. Every declared member of every mailbox that is @@ -375,6 +388,7 @@ export async function openLab(options: OpenLabOptions): Promise { const mailboxKind = defineMailboxFlow({ notify: labNotify({ addresses, + flowOf: () => seatCopy.id, log: notifyLog, ...(options.routeAuthoredLines === true ? { routeAuthoredLines: true } : {}), }), @@ -388,7 +402,7 @@ export async function openLab(options: OpenLabOptions): Promise { const state = createFlowState({ flows: Object.fromEntries([ ...registeredMailboxes.map((instance) => [instance.id, instance]), - ...hired.map((seat) => [seat.id, seat]), + ...hired.map((copy) => [copy.id, copy]), ]), stores: { default: { primary: options.stores } }, // Ignores the request. One caller, and a body read would be caller-controlled identity (BP-031). @@ -469,7 +483,7 @@ export async function openLab(options: OpenLabOptions): Promise { // The inventory, in-process, under the lab's org, once the mailbox sessions // it registers from exist. A problem fails the open, naming it. if (options.inventory === true) { - const flows: Record = { [MAILBOX_KIND]: mailboxInstance, ...seats }; + const flows: Record = { [MAILBOX_KIND]: mailboxInstance, [seatCopy.id]: seatCopy }; const run = async (request: InventoryActionRequest): Promise => { const flow = flows[request.flowKind]; if (flow === undefined) throw new Error(`no flow is served under "${request.flowKind}"`); @@ -488,7 +502,7 @@ export async function openLab(options: OpenLabOptions): Promise { return result; }; const opened = await openInventory( - { seats: hired, mailboxes: allMailboxes }, + { seats: inventorySeats(installation), mailboxes: allMailboxes }, { run, seatWriter: { flowKind: MAILBOX_KIND }, userId: LAB_USER_ID, orgId: LAB_ORG_ID }, ); if (opened.problems.length > 0) { @@ -590,13 +604,34 @@ export async function openLab(options: OpenLabOptions): Promise { // `omitOrg` is the same call with no org. The message does not say // OrgRequired, so that probe prefixes the error's name for the grade. const omitOrg = inspectOptions?.omitOrg === true; - const result = await act( - seat, - "inspect", - {}, - `${omitOrg ? "no-org" : "inspect"}-${seatId}`, - omitOrg ? { omitOrg: true } : undefined, + const sessionId = `${omitOrg ? "no-org" : "inspect"}-${seatId}`; + // The worker's session, created naming it, the way the session route does. + const now = Date.now(); + await ensureSessionRecord( + runtime.stores, + sessionId, + { + flow: seat as never, + sessionId, + principal: { userId: LAB_USER_ID, orgId: LAB_ORG_ID }, + state: { workerId: seatId }, + fromCaller: true, + via: "create", + }, + () => + ({ + id: sessionId, + flowKind: seat.kind, + flowId: seat.id, + userId: LAB_USER_ID, + orgId: LAB_ORG_ID, + version: 0, + createdAt: now, + updatedAt: now, + journal: [], + }) as never, ); + const result = await act(seat, "inspect", {}, sessionId, omitOrg ? { omitOrg: true } : undefined); if (result.error === undefined) { return { facts: (result.output ?? {}) as Record }; } diff --git a/goals/pentest-lab/lab/notify.mts b/goals/pentest-lab/lab/notify.mts index 1cfd7c1951..47f98ca423 100644 --- a/goals/pentest-lab/lab/notify.mts +++ b/goals/pentest-lab/lab/notify.mts @@ -26,6 +26,7 @@ import { handler, sequencer, dispatcher } from "@flow-state-dev/core"; import { mailboxNotifyInputSchema, type MailboxNotifyInput } from "@flow-state-dev/workforce"; +import { WORKER_ID_STATE_KEY } from "@flow-state-dev/workforce/browser"; import { z } from "zod"; import { BRIEF_ENTRY } from "./workforce/flows/workers/probe.mts"; @@ -65,12 +66,14 @@ export function createNotifyLog(): NotifyLog { export interface LabNotifyOptions { /** - * Member id → the hired seat's instance id it is delivered to. + * Member id → the worker it is delivered to. * * A member absent from this map is BR-9's case: recorded and skipped. Every - * id here is a seat `hireWorkforce` minted, so a dispatcher can name it. + * id here is a standard worker the tree declares. */ addresses: Record; + /** The flow a worker runs on, where its delivery's session is opened. */ + flowOf: (workerId: string) => string; /** Where the run's routing decisions are recorded. */ log: NotifyLog; /** @@ -91,7 +94,7 @@ export interface LabNotifyOptions { * @returns The block to pass as `defineMailboxFlow({ notify })`. */ export function labNotify(options: LabNotifyOptions) { - const { addresses, log } = options; + const { addresses, log, flowOf } = options; const members = Object.keys(addresses); /** @@ -140,26 +143,27 @@ export function labNotify(options: LabNotifyOptions) { }); /** - * One dispatcher per member, because `flowKind` is a static instance id. + * One dispatcher per member, because `flowKind` is a static flow id. * - * `session: { key }`, never `{ id }`: a seat has no session until something - * wakes it, and an exact id nothing created is refused `session-not-found` by - * name. The `key` child is derived, created on first delivery, and inherits - * the sender's org — which is what carries the seats' document reads. + * `session: { key, state }`, never `{ id }`: a seat has no session until + * something wakes it, and an exact id nothing created is refused + * `session-not-found` by name. The `key` child is derived, created on first + * delivery naming the member's worker, and inherits the sender's org — which + * is what carries the seats' document reads. * Settled by a run, with the `{ id }` shape as its control. */ const toSeat = (member: string) => dispatcher({ name: `lab-notify-${member.replace(/\./g, "-")}`, action: BRIEF_ENTRY, - flowKind: addresses[member]!, + flowKind: flowOf(addresses[member]!), inputSchema: decisionSchema, payload: (decision: Decision) => ({ mailboxId: decision.mailboxId, body: decision.body, member: decision.member, }), - session: { key: () => member }, + session: { key: () => member, state: { [WORKER_ID_STATE_KEY]: addresses[member]! } }, } as never); let seq: any = sequencer({ diff --git a/goals/pentest-lab/lab/scope-check.mts b/goals/pentest-lab/lab/scope-check.mts index ad7fb9d8f7..728cc48b1f 100644 --- a/goals/pentest-lab/lab/scope-check.mts +++ b/goals/pentest-lab/lab/scope-check.mts @@ -25,6 +25,7 @@ import { handler } from "@flow-state-dev/core"; import type { BlockContext } from "@flow-state-dev/core/types"; +import { WORKER_ID_STATE_KEY } from "@flow-state-dev/workforce/browser"; import { z } from "zod"; /** @@ -35,7 +36,7 @@ export const SCOPE_CHECK_KEY = "scope-check"; /** One recorded call: which seat made it, and what it asked about. */ export interface ScopeCheckCall { - /** The calling seat's own instance id, off `ctx.flow.id`. */ + /** The calling seat's own id, off the worker its session names. */ by: string; /** Whatever the caller passed as the host — its own document's value, if it read one. */ host: string; @@ -79,10 +80,11 @@ export function createScopeCheck(): ScopeCheck { }), outputSchema: z.object({ clearance: z.string() }), execute: (input: { host: string }, ctx: BlockContext) => { - // `ctx.flow.id` is the calling seat's own instance id — the same value - // the seat posts under. Recorded so a call can be attributed rather than + // The session's worker is the calling seat's own id — the same value the + // seat posts under. Recorded so a call can be attributed rather than // merely counted: BR-21 turns on `recon` calling and `triage` not. - calls.push({ by: (ctx.flow as { id?: string }).id ?? "", host: input.host }); + const by = (ctx.session.state as Record)[WORKER_ID_STATE_KEY]; + calls.push({ by: typeof by === "string" ? by : "", host: input.host }); return { clearance }; }, }); diff --git a/goals/pentest-lab/lab/workforce/flows/workers/probe.mts b/goals/pentest-lab/lab/workforce/flows/workers/probe.mts index c940e46855..c86db9d77d 100644 --- a/goals/pentest-lab/lab/workforce/flows/workers/probe.mts +++ b/goals/pentest-lab/lab/workforce/flows/workers/probe.mts @@ -28,7 +28,7 @@ import { dispatcher, handler, sequencer, defineFlow } from "@flow-state-dev/core"; import type { DeclaredResources } from "@flow-state-dev/core"; import type { BlockContext, BlockDefinition } from "@flow-state-dev/core/types"; -import { MAILBOX_KIND, MAILBOX_SEAT_POST_ACTION } from "@flow-state-dev/workforce"; +import { MAILBOX_KIND, MAILBOX_SEAT_POST_ACTION, WORKER_ID_STATE_KEY, workerConfigOf, type WorkerInstallation } from "@flow-state-dev/workforce"; import { z } from "zod"; import { workerDoor } from "../../../../../lib/worker-door.mts"; @@ -85,7 +85,7 @@ const seatSkillSchema = z * only prove the mint agrees with itself. */ export const seatFactsSchema = z.object({ - /** The seat's own instance id, off `ctx.flow.id`. */ + /** The worker this session runs, off the session. */ member: z.string(), /** The mailbox this delivery named, or null when read directly through `inspect`. */ mailboxId: z.string().nullable(), @@ -131,7 +131,12 @@ interface SeatConfig { /** This seat's own skills, off its own config — the route the built-in kind reads them by. */ function seatSkillsOf(ctx: BlockContext): Array<{ name: string; skillMd: string }> { - return (ctx.flow.config as Partial | undefined)?.seatSkills ?? []; + return (workerConfigOf(ctx) as Partial).seatSkills ?? []; +} + +/** The worker this session runs, as the session names it (checked when it was created). */ +function seatOf(ctx: BlockContext): string { + return String((ctx.session.state as Record)[WORKER_ID_STATE_KEY] ?? ""); } /** What one worker of this kind configures, in its file. */ @@ -153,9 +158,10 @@ function settingsSchema(catalog: Record>, defa /** * The lab's own setting: which file-declared document this seat reads, by * the ref the resources convention minted (bare at org level, - * `teams//` for a team's). + * `teams//` for a team's). Optional on the flow's one copy; a + * worker that names none is refused by name when it reads. */ - [DOCUMENT_KEY]: z.string().min(1), + [DOCUMENT_KEY]: z.string().min(1).optional(), model: z.string().default(defaultModel), @@ -261,13 +267,13 @@ const readOwnFacts = handler({ await ctx.sequencer.patchState({ mailboxId: input.mailboxId, post: input.body ?? null }); } - const config = ctx.flow.config as unknown as SeatConfig; + const config = workerConfigOf(ctx) as unknown as SeatConfig; // A seat that named no document is refused by name here, which is where the // `.optional()` above is paid for. if (config.document === undefined) { throw new Error( - `seat "${(ctx.flow as { id?: string }).id}" declares no \`document:\`, so it has ` + + `seat "${seatOf(ctx)}" declares no \`document:\`, so it has ` + `nothing to read. Every seat of this kind names one file-declared document.` ); } @@ -277,7 +283,7 @@ const readOwnFacts = handler({ const ref = ctx.resources[config.document]; if (ref === undefined) { throw new Error( - `seat "${(ctx.flow as { id?: string }).id}" names document "${config.document}", ` + + `seat "${seatOf(ctx)}" names document "${config.document}", ` + `which is not installed on this flow. Installed: ${Object.keys(ctx.resources).join(", ")}` ); } @@ -286,7 +292,7 @@ const readOwnFacts = handler({ const skills = seatSkillsOf(ctx); return { - member: (ctx.flow as { id?: string }).id ?? "", + member: seatOf(ctx), mailboxId: input.mailboxId ?? null, post: input.body ?? null, instructions: config.instructions ?? "", @@ -305,8 +311,8 @@ const readOwnFacts = handler({ * * The mailbox id comes off the sequencer's own state rather than off the * running value, because the answer slot's output is a bare string and a - * generator's cannot be anything else. The author is `ctx.flow.id` — the seat's - * own instance id, which is also its declared membership name, so BR-7's post + * generator's cannot be anything else. The author is the session's worker — the + * seat's own id, which is also its declared membership name, so BR-7's post * is made under an identity the seat reads off itself rather than one the * delivery told it to claim. */ @@ -319,7 +325,7 @@ const composePost = handler({ return { mailboxId: state.mailboxId ?? "", body: line, - author: (ctx.flow as { id?: string }).id ?? "", + author: seatOf(ctx), }; }, }); @@ -346,6 +352,8 @@ const postBack = dispatcher({ } as never); export interface ProbeWorkerFlowOptions { + /** The installation that runs this flow's workers. */ + installation: WorkerInstallation; /** * The answering block — a `SeatFacts` in, one line of text out. * @@ -374,7 +382,7 @@ export interface ProbeWorkerFlowOptions { * Build the seat kind. * * @param options The answer slot, the tool catalog, and the documents to install. - * @returns The flow factory `hireWorkforce` mints one copy of per worker record. + * @returns The flow `hireWorkforce` registers one copy of, for every worker on it. */ export function defineProbeWorkerFlow(options: ProbeWorkerFlowOptions) { const catalog = options.catalog ?? {}; @@ -393,15 +401,28 @@ export function defineProbeWorkerFlow(options: ProbeWorkerFlowOptions) { ? answering : answering.step(composePost).step(postBack); + const installation = options.installation; + /** Loads the turn's worker, on every run of a request, so `workerConfigOf` reads it. */ + const loadWorker = handler({ + name: `${SEAT_KIND}-load-worker`, + inputSchema: z.unknown(), + resources: { ...installation.resources }, + execute: async (_input: unknown, ctx: BlockContext) => ({ + worker: (await installation.resolveWorker(ctx as never, SEAT_KIND)).id, + }), + }); + return defineFlow({ kind: SEAT_KIND, - // One copy per worker record, each addressed by its own id. + // One copy for every worker on it; each session names its worker. cardinality: "collection", configSchema: settings, + session: installation.session(), // Installed at flow level. Org-scoped, and organization identity is // unconditional, so the org registry is always built for a request that // reaches the reading block. - resources: options.resources, + resources: { ...options.resources, ...installation.resources }, + request: { onStarted: loadWorker }, actions: { ...workerDoor, [INSPECT_ENTRY]: { block: readOwnFacts, diff --git a/goals/scripts/validate-control-shape.mts b/goals/scripts/validate-control-shape.mts index 76d0c8cda2..006374f070 100644 --- a/goals/scripts/validate-control-shape.mts +++ b/goals/scripts/validate-control-shape.mts @@ -75,11 +75,6 @@ const PAIRS = [ file: "goals/workforce-seats/a-non-agent-seat-receives-its-skills/fixtures/flows.ts", control: "noContractFlow", twin: "handRolledFlow" - }, - { - file: "goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/flows.ts", - control: "noContractFlow", - twin: "handRolledFlow" } ] as const; diff --git a/goals/seat-hire/refuses-an-unpinned-register/fixtures/input.json b/goals/seat-hire/refuses-an-unpinned-register/fixtures/input.json deleted file mode 100644 index c3da6d1776..0000000000 --- a/goals/seat-hire/refuses-an-unpinned-register/fixtures/input.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "orgId": "acme", - "otherOrg": "globex", - "managerId": "eng.manager", - "seatId": "eng.ada", - "unpinnedSeat": "eng.stray", - "foreignSeat": "eng.lead" -} diff --git a/goals/seat-hire/refuses-an-unpinned-register/goal.md b/goals/seat-hire/refuses-an-unpinned-register/goal.md deleted file mode 100644 index a0034a8c0b..0000000000 --- a/goals/seat-hire/refuses-an-unpinned-register/goal.md +++ /dev/null @@ -1,19 +0,0 @@ -# seat-hire › it refuses an unpinned register - -**Issue:** FIX-1529 (soft-fence on FIX-1525 / FIX-1526) -**Outcome:** A hired seat cannot join the live roster without an owner pin `{ orgId, userId? }` taken from the hire row's roster owner. An unpinned register leaves the address empty. A hire that succeeds pins the org that owns the roster row. A seat whose address reads like another org still carries the pin it was given, not the name in the address. -**Input:** `fixtures/input.json` — two organizations (`orgId`, `otherOrg`), a manager seat, the seat a hire mints, a different seat used only for the unpinned refuse, and a foreign seat id whose address starts with the other org. Held-out: swapping those strings must still pass a correct implementation. The two orgs must differ, or the pin-vs-address leg has nothing to grade. The unpinned seat must not be the hired seat, or a control that admits it would take the hire's address. -**Signal:** Three legs on one run. (a) `registerHiredSeat` with no pin throws and the live roster does not gain the seat. (b) A manager seat names `hire` under `orgId`; the register callback receives `{ orgId }` from that roster cell, the address `${orgId}.${seatId}` is live, and the hire's return names that address. (c) The same register path admits a seat whose id is `${otherOrg}.${foreignSeat}` with pin `{ orgId }`; the recorded pin is `orgId`, not `otherOrg`. PASS prints the hire address and both pins. -**Anti-game:** A hollow pass would assert that `registerHiredSeat` throws while hire still calls `register(seat)` with no pin — so this check MUST grade the pin the hire tool actually handed the live roster, not only the helper. A hollow pass would also assert `pin.orgId` equals the first segment of the address — true on every ordinary hire, and true of a writer that parses ownership off the id — so leg (c) MUST use an address whose first segment is the other org. The check MUST grade the live map (empty after the refuse, present after hire), not the error string alone. -**Model:** n/a — the hire tool is a handler; the generator is only how a seat names it. -**Run:** `pnpm tsx goals/seat-hire/refuses-an-unpinned-register/run.mts` -**Controls:** -- `GOAL_CONTROL=unpinned-ok` — skip the refuse and admit with no pin. Must FAIL, naming leg (a). -- `GOAL_CONTROL=pin-from-address` — admit the foreign seat with a pin parsed from its id. Must FAIL, naming leg (c). - -## Verdict log -| Date | Commit | Model | Verdict | Notes | -|------|--------|-------|---------|-------| -| 2026-09-23 | 68985d67c | n/a | **PASS** | Unpinned `acme.eng.stray` stayed empty. Hire of `acme.eng.ada` through the manager's `hire` tool pinned `{"orgId":"acme"}` from the roster cell. `globex.eng.lead` carried `{"orgId":"acme"}`, so the address's first segment did not win. | -| 2026-09-23 | 68985d67c | n/a | **FAIL (expected)** | `GOAL_CONTROL=unpinned-ok` — admitted with no pin. Red on leg (a) only: *registerHiredSeat admitted a hired seat with no pin*; *acme.eng.stray is live after an unpinned register*. Hire of `eng.ada` stayed green. | -| 2026-09-23 | 68985d67c | n/a | **FAIL (expected)** | `GOAL_CONTROL=pin-from-address` — foreign seat pinned from its id. Red on leg (c) only: *globex.eng.lead recorded pin {"orgId":"globex"}, wanted { orgId: "acme" }*. | diff --git a/goals/seat-hire/refuses-an-unpinned-register/run.mts b/goals/seat-hire/refuses-an-unpinned-register/run.mts deleted file mode 100644 index 39f2c72c97..0000000000 --- a/goals/seat-hire/refuses-an-unpinned-register/run.mts +++ /dev/null @@ -1,244 +0,0 @@ -/** - * Goal check — a hired seat cannot join the live roster without an owner pin. - * - * Three legs. (a) is the refuse: no pin, nothing admitted. (b) is the hire - * tool: a manager names `hire` and the live roster records the pin from the - * roster cell, not a guess. (c) is pin ≠ address: a seat whose id reads like - * another org still carries the pin it was given. - * - * Real path, no model. See goal.md for the contract. - * - * Run: pnpm tsx goals/seat-hire/refuses-an-unpinned-register/run.mts - */ -import { - createSeatHireCapability, - defineAgentWorkerFlow, - hireWorkforce, - registerHiredSeat, - type HiredSeatOwnerPin, - type HireOptions, - type WorkerManifest, -} from "@flow-state-dev/workforce"; -import type { FlowInstance } from "@flow-state-dev/core"; -import { executeBlock } from "@flow-state-dev/engine"; -import { createTestContext, mockGenerator } from "@flow-state-dev/testing"; -import { loadFixture, runGoal, stripIntentOverrides } from "../../lib/index.mts"; - -type Fixture = { - orgId: string; - otherOrg: string; - managerId: string; - seatId: string; - unpinnedSeat: string; - foreignSeat: string; -}; - -stripIntentOverrides(); - -const fixture = loadFixture(import.meta.url); -const CONTROL = process.env.GOAL_CONTROL ?? ""; - -function liveRoster() { - const held = new Map(); - return { - register(seat: FlowInstance, pin: HiredSeatOwnerPin) { - if (held.has(seat.id)) { - throw new Error(`"${seat.id}" is already registered`); - } - held.set(seat.id, { seat, pin }); - }, - unregister(id: string) { - return held.delete(id); - }, - kindAt(id: string) { - return held.get(id)?.seat.kind; - }, - instanceAt(id: string) { - return held.get(id)?.seat; - }, - pinAt(id: string) { - return held.get(id)?.pin; - }, - has(id: string) { - return held.has(id); - }, - }; -} - -function admit( - register: (seat: FlowInstance, pin: HiredSeatOwnerPin) => void, - seat: FlowInstance, - pin: HiredSeatOwnerPin | undefined, -): void { - if (CONTROL === "unpinned-ok") { - register(seat, pin as HiredSeatOwnerPin); - return; - } - registerHiredSeat(register, seat, pin); -} - -function record(over: Partial & { id: string }): WorkerManifest { - return { declared: {}, body: "", ...over }; -} - -function hireReturn(items: unknown[]): { seatId?: string; address?: string } | undefined { - const visit = (value: unknown): { seatId?: string; address?: string } | undefined => { - if (value === null || typeof value !== "object") return undefined; - const row = value as Record; - if (typeof row.seatId === "string" && typeof row.address === "string") { - return { seatId: row.seatId, address: row.address }; - } - for (const nested of Object.values(row)) { - const found = visit(nested); - if (found !== undefined) return found; - } - return undefined; - }; - for (const item of items) { - const found = visit(item); - if (found !== undefined) return found; - } - return undefined; -} - -await runGoal(async () => { - if (fixture.orgId === fixture.otherOrg) { - return { - failures: [ - `the fixture's orgId and otherOrg are both "${fixture.orgId}" — leg (c) has nothing to grade`, - ], - evidence: "", - }; - } - if (fixture.unpinnedSeat === fixture.seatId) { - return { - failures: [ - `the fixture's unpinnedSeat and seatId are both "${fixture.seatId}" — admitting the unpinned seat would take the hire's address`, - ], - evidence: "", - }; - } - - const failures: string[] = []; - const evidence: string[] = []; - const live = liveRoster(); - const stray = { id: `${fixture.orgId}.${fixture.unpinnedSeat}`, kind: "agent" } as FlowInstance; - - // ---- (a) unpinned register leaves the address empty ---------------------- - let threw = false; - try { - admit(live.register, stray, undefined); - } catch (error) { - threw = String(error).includes("owner pin"); - if (!threw) { - failures.push( - `leg (a): the refuse threw ${JSON.stringify(String(error))} rather than naming the owner pin`, - ); - } - } - if (!threw) { - failures.push("leg (a): registerHiredSeat admitted a hired seat with no pin"); - } - if (live.has(stray.id)) { - failures.push( - `leg (a): ${stray.id} is live after an unpinned register — the address must stay empty`, - ); - } - - // ---- (b) hire pins the roster owner -------------------------------------- - const kinds: NonNullable = {}; - const seatHire = createSeatHireCapability({ - workerFlows: kinds, - register: live.register, - unregister: live.unregister, - kindAt: live.kindAt, - instanceAt: live.instanceAt, - }); - kinds.agent = defineAgentWorkerFlow({ uses: [seatHire] }); - - const [manager] = hireWorkforce( - [record({ id: fixture.managerId, declared: { tools: ["hire"] }, body: "Expands the roster." })], - { workerFlows: kinds }, - ); - if (manager === undefined) { - return { failures: ["leg (b): hireWorkforce minted no manager"], evidence: "" }; - } - - const runtime = await createTestContext({ - flow: { ...manager, cardinality: "singleton" }, - orgId: fixture.orgId, - org: { state: {} }, - sessionId: "goal-session", - sequencerName: manager.actions.run!.block.name, - declaredResources: manager.actions.run!.block.declaredResources, - generators: { - "agent-answer": mockGenerator({ - name: "agent-answer", - script: [ - { - toolCalls: [ - { - toolCallId: "hire-1", - toolName: "hire", - args: { seatId: fixture.seatId, flow: "agent" }, - }, - ], - }, - { text: "done" }, - ] as never, - }), - }, - }); - const hired = await executeBlock({ - block: manager.actions.run!.block, - input: { message: "hire the named seat" }, - ctx: runtime.ctx, - }); - - const address = `${fixture.orgId}.${fixture.seatId}`; - const payload = hireReturn(hired.items); - if (hired.error !== undefined) { - failures.push(`leg (b): hire failed: ${hired.error.message}`); - } - if (payload?.address !== address || payload.seatId !== fixture.seatId) { - failures.push( - `leg (b): hire returned ${JSON.stringify(payload)}, wanted { seatId: "${fixture.seatId}", address: "${address}" }`, - ); - } - if (!live.has(address)) { - failures.push(`leg (b): ${address} is not live after hire`); - } - const hirePin = live.pinAt(address); - if (hirePin?.orgId !== fixture.orgId) { - failures.push( - `leg (b): hire pinned ${JSON.stringify(hirePin)}, wanted { orgId: "${fixture.orgId}" } from the roster cell`, - ); - } - - // ---- (c) pin is not parsed from the address ------------------------------ - const foreignId = `${fixture.otherOrg}.${fixture.foreignSeat}`; - const foreign = { id: foreignId, kind: "agent" } as FlowInstance; - const foreignPin = - CONTROL === "pin-from-address" - ? { orgId: foreignId.split(".")[0] ?? "" } - : { orgId: fixture.orgId }; - admit(live.register, foreign, foreignPin); - const recorded = live.pinAt(foreignId); - if (recorded?.orgId !== fixture.orgId) { - failures.push( - `leg (c): ${foreignId} recorded pin ${JSON.stringify(recorded)}, wanted { orgId: "${fixture.orgId}" } — ` + - `the first address segment is "${fixture.otherOrg}" and must not win`, - ); - } - if (recorded?.orgId === fixture.otherOrg) { - failures.push( - `leg (c): the pin was parsed from the address (${fixture.otherOrg}) rather than taken from the hire row`, - ); - } - - evidence.push( - `unpinned ${stray.id} stayed empty; hire of ${address} pinned ${JSON.stringify(hirePin)}; ` + - `${foreignId} carried ${JSON.stringify(recorded)}`, - ); - return { failures, evidence: evidence.join("; ") }; -}); diff --git a/goals/shift-manager/one-person-runs-a-labs-projects-and-people/manifest.mts b/goals/shift-manager/one-person-runs-a-labs-projects-and-people/manifest.mts index 0c086cb3d3..026c21499a 100644 --- a/goals/shift-manager/one-person-runs-a-labs-projects-and-people/manifest.mts +++ b/goals/shift-manager/one-person-runs-a-labs-projects-and-people/manifest.mts @@ -29,8 +29,6 @@ export interface Entry { /** Every check that boots the DevTeam tree, other than the closure's own and the three named above. */ function devteamBooters(): string[] { const named = new Set([ - "goals/hire-plane/repairs-a-seat-whose-kind-was-cut", - "goals/org-seats/cos-changes-the-roster", "goals/shift-manager/it-groups-workstreams-under-their-projects", "goals/shift-manager/one-person-runs-a-labs-projects-and-people", // FIX-1737's closure goal: another epic's, matched only by naming devteam, and its part 3 reruns checks listed here. @@ -59,14 +57,6 @@ function devteamBooters(): string[] { */ type Expect = { legs: RegExp[]; only?: RegExp }; const EXPECTED: Record> = { - // "Must FAIL `team-list:retired-row-gone` only." - "goals/hire-plane/repairs-a-seat-whose-kind-was-cut": { - "fire-keeps-inventory": { legs: [/^\[team-list:retired-row-gone\]/], only: /^\[team-list:retired-row-gone\]/ }, - }, - // "**discover** only: ... every later leg stays green" - "goals/org-seats/cos-changes-the-roster": { - "drop-member-from-discover": { legs: [/^\[control drop-member-from-discover\] discover:/], only: /^\[control drop-member-from-discover\] discover:/ }, - }, "goals/shift-manager/it-groups-workstreams-under-their-projects": { unread: { legs: [/^\[control unread\] PROJECTS equals the store's rows:/] }, "gap-tabs": { legs: [/^\[control gap-tabs\] a project's four tabs:/] }, @@ -149,8 +139,6 @@ export function gradeControl(path: string, control: string, exit: number | null, export function manifest(): Entry[] { return [ - { id: "P3.1", path: "goals/hire-plane/repairs-a-seat-whose-kind-was-cut", controls: ["fire-keeps-inventory"] }, - { id: "P3.2", path: "goals/org-seats/cos-changes-the-roster", controls: ["drop-member-from-discover"], covered: "deny-fire (b3)" }, { id: "P3.3", path: "goals/shift-manager/it-groups-workstreams-under-their-projects", diff --git a/goals/task-run-link/it-names-the-run-working-each-task/run.mts b/goals/task-run-link/it-names-the-run-working-each-task/run.mts index 2d82b86d52..b2ccc15497 100644 --- a/goals/task-run-link/it-names-the-run-working-each-task/run.mts +++ b/goals/task-run-link/it-names-the-run-working-each-task/run.mts @@ -44,7 +44,7 @@ import { fileURLToPath } from "node:url"; import { z } from "zod"; import { DEFAULT_ORG_ID, defineFlow, dispatcher, handler } from "@flow-state-dev/core"; import type { ResourceCollectionRef } from "@flow-state-dev/core/types"; -import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; +import { createFlowState, ensureSessionRecord, inMemoryStores, runAction } from "@flow-state-dev/engine"; import { taskBoard, taskWorkerInputSchema } from "@flow-state-dev/orchestration/task-board"; import { getOrCreateTaskCollection, @@ -58,7 +58,9 @@ import { mailboxBoard, mailboxBoardIds, mailboxInstances, + createWorkerInstallation, hireWorkforce, + WORKER_ID_STATE_KEY, openMailboxes, workerConfigSchema, type MailboxManifest, @@ -77,10 +79,10 @@ const CONVO_B = "s_convo_b"; const ENTRY = "work"; const MARKER_COMPONENT = "run-link-goal-marker"; /** - * The kind a seat names when its rows run on the DRAINER's flow. It holds no - * task entry of its own: the drainer's flow declares the entry its hand-off - * addresses. Any other kind a seat names is a flow of its own, which the seat's - * hand-off addresses by the seat's instance id. + * The kind a seat names when its rows run on the DRAINER's flow, as the + * drainer. It holds no task entry of its own: the drainer's flow declares the + * entry its hand-off addresses. Any other kind a seat names is a flow of its + * own, which the seat's hand-off addresses, in a session naming the seat. */ const PASSIVE_KIND = "seat"; @@ -208,14 +210,23 @@ await runGoal(async () => { } }); + // A row's session names its worker: the seat, on a flow of its own; the + // drainer whose drain handed it over, on the drainer's flow. const address = (seat: (typeof seats)[number]) => dispatcher({ name: `run-link-goal-hand-${seat.name}`, action: ENTRY, session: seat.policy, - ...(seat.flow !== undefined ? { flowKind: seat.id } : {}) + ...(seat.flow !== undefined + ? { flowKind: seat.flow, state: { [WORKER_ID_STATE_KEY]: seat.id } } + : { state: (_task, ctx) => ({ [WORKER_ID_STATE_KEY]: (ctx.session.state as Record)[WORKER_ID_STATE_KEY] }) }) }); + // The installation every worker flow below runs its workers on. It reads the + // flows when it first needs them, so they are built on it below. + let workerFlows: Record = {}; + const installation = createWorkerInstallation({ standardWorkers: workers, workerFlows: () => workerFlows as never }); + const BOARD_ID = `${ledger.id}-board`; const leadBoard = taskBoard({ name: "run-link-goal-lead", @@ -227,7 +238,8 @@ await runGoal(async () => { kind: drainer.declared.flow as string, cardinality: "collection", configSchema: workerConfigSchema(), - resources: { [ledger.id]: ledger }, + session: installation.session(), + resources: { [ledger.id]: ledger, ...installation.resources }, actions: { drain: { block: leadBoard.drain }, ...workerDoor }, task: { actions: { [ENTRY]: { block: work } } } } as never); @@ -248,7 +260,8 @@ await runGoal(async () => { kind: seat.flow!, cardinality: "collection", configSchema: seatConfig, - resources: { [ledger.id]: ledger }, + session: installation.session(), + resources: { [ledger.id]: ledger, ...installation.resources }, actions: { drain: { block: board.drain }, ...workerDoor }, task: { actions: { [ENTRY]: { block: work } } } } as never) @@ -260,18 +273,18 @@ await runGoal(async () => { kind: PASSIVE_KIND, cardinality: "collection", configSchema: seatConfig, + session: installation.session(), + resources: { ...installation.resources }, actions: { ...workerDoor,} } as never); const instances = mailboxInstances(mailboxes); - const hired = hireWorkforce(workers, { - workerFlows: { - [drainer.declared.flow as string]: leadKind as never, - [PASSIVE_KIND]: passiveKind as never, - ...(otherKinds as Record) - }, - mailboxBoards: mailboxBoardIds(mailboxes) - }); + workerFlows = { + [drainer.declared.flow as string]: leadKind, + [PASSIVE_KIND]: passiveKind, + ...otherKinds + }; + const hired = hireWorkforce(installation, { mailboxBoards: mailboxBoardIds(mailboxes) }); const state = createFlowState({ flows: { ...Object.fromEntries(instances.map((instance) => [instance.kind, instance])), @@ -340,7 +353,35 @@ await runGoal(async () => { } as never)) as { output?: unknown; error?: unknown; requestId?: string }; const mailboxInstance = instances.find((instance) => instance.kind === MAILBOX_KIND)!; - const lead = hired.find((seat) => seat.id === drainer.id)!; + const lead = hired.find((copy) => copy.kind === drainer.declared.flow)!; + // The two conversations that drain the board, each created naming the drainer. + for (const sessionId of [CONVO_A, CONVO_B]) { + const now = Date.now(); + await ensureSessionRecord( + runtime.stores, + sessionId, + { + flow: lead as never, + sessionId, + principal: { userId: USER_ID, orgId: ORG_ID }, + state: { [WORKER_ID_STATE_KEY]: drainer.id }, + fromCaller: true, + via: "create" + }, + () => + ({ + id: sessionId, + flowKind: lead.kind, + flowId: lead.id, + userId: USER_ID, + orgId: ORG_ID, + version: 0, + createdAt: now, + updatedAt: now, + journal: [] + }) as never + ); + } const row = async (taskId: string): Promise => (await runtime.stores.resourceState.get("org", ORG_ID, `${ledger.id}/${taskId}`))?.state as Task | undefined; diff --git a/goals/worker-contract/runs-workers-only-on-registered-flows/fixtures/flows.ts b/goals/worker-contract/runs-workers-only-on-registered-flows/fixtures/flows.ts index 09dc3cc15d..2421f93bd1 100644 --- a/goals/worker-contract/runs-workers-only-on-registered-flows/fixtures/flows.ts +++ b/goals/worker-contract/runs-workers-only-on-registered-flows/fixtures/flows.ts @@ -2,15 +2,14 @@ * The goal's worker flows: five an app can register, and three that * each break one rule of the worker contract. Every one is a flow an author * could write; none is shaped to trip the check. + * + * Each is built on the installation, as every worker flow is (FIX-1788): it + * declares the installation's session, so a session names its worker, and + * one copy runs every worker on it. */ import { z } from "zod"; import { defineFlow, defineResourceCollection, handler } from "@flow-state-dev/core"; -import { - sharedResource, - workerConfigSchema, - writeShared, - type WorkerInstallation -} from "@flow-state-dev/workforce"; +import { sharedResource, workerConfigSchema, writeShared, type WorkerInstallation } from "@flow-state-dev/workforce"; const message = z.object({ message: z.string() }); @@ -26,53 +25,55 @@ function hearing(name: string) { execute: (input, ctx) => { ctx.emit.message(`${name} heard: ${input.message}`); return { heard: input.message }; - } - }) + }, + }), }; } -/** An app's own worker flow. */ -export const triageFlow = defineFlow({ - kind: "triage", - cardinality: "collection", - configSchema: workerConfigSchema().extend({ desk: z.string().default("front") }), - actions: { run: hearing("triage") } -}); +/** The flows an app registers, and the three that each break one rule, built on `workers`. */ +export function defineFlows(workers: WorkerInstallation) { + const bound = { session: workers.session(), resources: { ...workers.resources } }; -/** A coordinator: its delegates live in its session state. */ -export const coordinatorFlow = defineFlow({ - kind: "coordinator", - cardinality: "collection", - configSchema: workerConfigSchema(), - session: { stateSchema: z.object({ delegates: z.array(z.string()).default([]) }) }, - actions: { - run: { - inputSchema: message, - userMessage: (input: { message: string }) => input.message, - block: handler({ - name: "coordinator-route", - inputSchema: message, - outputSchema: z.object({ delegates: z.array(z.string()) }), - execute: (_input, ctx) => { - const delegates = (ctx.session.state as { delegates?: string[] }).delegates ?? []; - ctx.emit.message(`delegates: ${delegates.join(", ") || "none"}`); - return { delegates }; - } - }) - } - } -}); + /** An app's own worker flow. */ + const triageFlow = defineFlow({ + kind: "triage", + cardinality: "collection", + configSchema: workerConfigSchema().extend({ desk: z.string().default("front") }), + ...bound, + actions: { run: hearing("triage") }, + }); -const noteInput = z.object({ key: z.string(), text: z.string() }); -const notes = sharedResource("team-notes/*", { text: z.string() }); + /** A coordinator: its delegates live in its session state. */ + const coordinatorFlow = defineFlow({ + kind: "coordinator", + cardinality: "collection", + configSchema: workerConfigSchema(), + session: workers.session({ delegates: z.array(z.string()).default([]) }), + resources: { ...workers.resources }, + actions: { + run: { + inputSchema: message, + userMessage: (input: { message: string }) => input.message, + block: handler({ + name: "coordinator-route", + inputSchema: message, + outputSchema: z.object({ delegates: z.array(z.string()) }), + execute: (_input, ctx) => { + const delegates = (ctx.session.state as { delegates?: string[] }).delegates ?? []; + ctx.emit.message(`delegates: ${delegates.join(", ") || "none"}`); + return { delegates }; + }, + }), + }, + }, + }); -/** - * A flow that writes a shared resource through the helper, as the worker its - * session was created with: the turn loads the worker, and the helper names - * the worker the turn loaded (FIX-1788). - */ -export function defineSharerFlow(workers: WorkerInstallation) { - return defineFlow({ + /** + * A flow that writes a shared resource through the helper, as the worker its + * session was created with: the turn loads the worker, and the helper names + * the worker the turn loaded (FIX-1788). + */ + const sharerFlow = defineFlow({ kind: "sharer", cardinality: "collection", configSchema: workerConfigSchema(), @@ -91,88 +92,102 @@ export function defineSharerFlow(workers: WorkerInstallation) { await workers.resolveWorker(ctx, "sharer"); await writeShared(ctx, "notes", input.key, { text: input.text }); return { shared: input.key }; - } - }) - } - } + }, + }), + }, + }, }); -} - -const board = defineResourceCollection({ - pattern: "team-board/*", - scope: "org", - stateSchema: z.object({ text: z.string() }) -}); -/** A flow whose author built it to keep org data of its own: every member reads it. */ -export const orgKeeperFlow = defineFlow({ - kind: "org-keeper", - cardinality: "collection", - configSchema: workerConfigSchema(), - actions: { - run: hearing("org-keeper"), - keep: { - inputSchema: noteInput, - block: handler({ - name: "org-keeper-keep", + /** A flow whose author built it to keep org data of its own: every member reads it. */ + const orgKeeperFlow = defineFlow({ + kind: "org-keeper", + cardinality: "collection", + configSchema: workerConfigSchema(), + ...bound, + actions: { + run: hearing("org-keeper"), + keep: { inputSchema: noteInput, - outputSchema: z.object({ kept: z.string() }), - resources: { board }, - execute: async (input, ctx) => { - await (ctx.resources.board as unknown as { - create: (key: string, state: { text: string }, options?: { replace?: boolean }) => Promise; - }).create(input.key, { text: input.text }, { replace: true }); - return { kept: input.key }; - } - }) - } - } -}); + block: handler({ + name: "org-keeper-keep", + inputSchema: noteInput, + outputSchema: z.object({ kept: z.string() }), + resources: { board }, + execute: async (input, ctx) => { + await ( + ctx.resources.board as unknown as { + create: (key: string, state: { text: string }, options?: { replace?: boolean }) => Promise; + } + ).create(input.key, { text: input.text }, { replace: true }); + return { kept: input.key }; + }, + }), + }, + }, + }); -const note = z.object({ note: z.string() }); + /** Breaks one rule: no action takes a person's message. */ + const doorlessFlow = defineFlow({ + kind: "doorless", + cardinality: "collection", + configSchema: workerConfigSchema(), + ...bound, + actions: { + work: { + inputSchema: note, + block: handler({ name: "doorless-work", inputSchema: note, outputSchema: note, execute: (input) => input }), + }, + }, + }); -/** Breaks one rule: no action takes a person's message. */ -export const doorlessFlow = defineFlow({ - kind: "doorless", - cardinality: "collection", - configSchema: workerConfigSchema(), - actions: { - work: { - inputSchema: note, - block: handler({ name: "doorless-work", inputSchema: note, outputSchema: note, execute: (input) => input }) - } - } -}); + /** Breaks one rule: declares the configuration by hand, with `seatId` as a number. */ + const numberedFlow = defineFlow({ + kind: "numbered", + cardinality: "collection", + configSchema: z.object({ + instructions: z.string().optional(), + teamInstructions: z.string().optional(), + seatSkills: z.array(z.any()).default([]), + seatTools: z.array(z.any()).default([]), + seatPackages: z.array(z.any()).optional(), + seatId: z.number().optional(), + }), + ...bound, + actions: { run: hearing("numbered") }, + }); -/** Breaks one rule: declares the configuration by hand, with `seatId` as a number. */ -export const numberedFlow = defineFlow({ - kind: "numbered", - cardinality: "collection", - configSchema: z.object({ - instructions: z.string().optional(), - teamInstructions: z.string().optional(), - seatSkills: z.array(z.any()).default([]), - seatTools: z.array(z.any()).default([]), - seatPackages: z.array(z.any()).optional(), - seatId: z.number().optional() - }), - actions: { run: hearing("numbered") } -}); + /** Breaks one rule: declares `writtenBy` optional, so an entry can name nobody. */ + const looseAttributionFlow = defineFlow({ + kind: "loose-attribution", + cardinality: "collection", + configSchema: workerConfigSchema(), + session: workers.session(), + resources: { + ...workers.resources, + notes: defineResourceCollection({ + pattern: "loose-notes/*", + scope: "org", + stateSchema: z.object({ + text: z.string(), + writtenBy: z.object({ userId: z.string().min(1), workerId: z.string().min(1).optional() }).optional(), + }), + }), + }, + actions: { run: hearing("loose-attribution") }, + }); -/** Breaks one rule: declares `writtenBy` optional, so an entry can name nobody. */ -export const looseAttributionFlow = defineFlow({ - kind: "loose-attribution", - cardinality: "collection", - configSchema: workerConfigSchema(), - resources: { - notes: defineResourceCollection({ - pattern: "loose-notes/*", - scope: "org", - stateSchema: z.object({ - text: z.string(), - writtenBy: z.object({ userId: z.string().min(1), workerId: z.string().min(1).optional() }).optional() - }) - }) - }, - actions: { run: hearing("loose-attribution") } + return { + registered: { triage: triageFlow, coordinator: coordinatorFlow, sharer: sharerFlow, "org-keeper": orgKeeperFlow }, + broken: { doorless: doorlessFlow, numbered: numberedFlow, "loose-attribution": looseAttributionFlow }, + }; +} + +const noteInput = z.object({ key: z.string(), text: z.string() }); +const notes = sharedResource("team-notes/*", { text: z.string() }); +const note = z.object({ note: z.string() }); + +const board = defineResourceCollection({ + pattern: "team-board/*", + scope: "org", + stateSchema: z.object({ text: z.string() }), }); diff --git a/goals/worker-contract/runs-workers-only-on-registered-flows/goal.md b/goals/worker-contract/runs-workers-only-on-registered-flows/goal.md index 57287e8752..cb86f85a89 100644 --- a/goals/worker-contract/runs-workers-only-on-registered-flows/goal.md +++ b/goals/worker-contract/runs-workers-only-on-registered-flows/goal.md @@ -1,24 +1,26 @@ # worker-contract › it runs workers only on registered flows **Issue:** FIX-1789 -**Outcome:** An app runs a worker only on a flow it registered as a worker flow. Before any worker runs, each registered flow is shown to take the configuration a real hire supplies, to have one door, and to declare any resource with `writtenBy` through `sharedResource()`. A flow kept for declared workers refuses a hired worker. The built-in `agent` keeps a worker's own state off org scope, and a shared note names who wrote it. +**Outcome:** An app runs a worker only on a flow it registered as a worker flow. Before any worker runs, each registered flow is shown to take the configuration a real hire supplies, to have one door, and to declare any resource with `writtenBy` through `sharedResource()`. A flow kept for declared workers refuses a user's own worker. The built-in `agent` keeps a worker's own state off org scope, and a shared note names who wrote it. **Input:** `fixtures/workforce/` — five worker files (one per registered flow, `helper` on the built-in `agent` with one skill) — and `fixtures/flows.ts`: an app flow (`triage`), a coordinator whose delegates live in session state (`coordinator`, kept for declared workers), a flow writing a shared resource (`sharer`), a flow writing org data of its own on purpose (`org-keeper`), and three flows each breaking one rule (`doorless`, `numbered` with `seatId` as a number, `loose-attribution` with an optional `writtenBy`). `fixtures/input.json` holds the org, the two users, the worker ids, the note, and bob's own stored worker. Held-out: the ids, users and texts are read from the fixture and graded against what boot refuses and what the store holds. -**Signal:** on the real path — `readWorkforce`, `hireWorkforce`, `createFlowState` with in-memory stores, `runAction` for two users of one org, `reloadHiredSeats` — and no model. -(a) Hiring the files against all eight flows throws one boot error naming `doorless` (no door), `numbered` (`seatId`) and `loose-attribution` (`writtenBy`), naming none of the five that meet the contract, and saying nothing was hired. No worker names a broken flow, so the refusal is about the flows, not a worker. +**Signal:** on the real path — `readWorkforce`, `createWorkerInstallation`, `hireWorkforce`, `createFlowState` with in-memory stores, the engine's session birth naming each worker, `runAction` for two users of one org — and no model. Every flow is built on the installation and registered once (FIX-1788). +(a) Registering the installation with all eight flows throws one boot error naming `doorless` (no door), `numbered` (`seatId`) and `loose-attribution` (`writtenBy`), naming none of the five that meet the contract, and saying nothing was hired. No worker names a broken flow, so the refusal is about the flows, not a worker. (b) After alice's and then bob's run on `helper` (the built-in `agent`), every skills-drawer write alice's run made landed in user scope, none in the org's cells, and bob's run read or wrote none of the cells alice's run wrote. Alice's note through `sharer`, in a session created naming `support.scout`, is stored at org scope as `{ text, writtenBy: { userId: alice, workerId: support.scout } }`: the worker the turn loaded (FIX-1788 moved `writeShared` from the `seatId` setting to the session's worker, so the sharer flow is a worker-model flow). The `org-keeper` flow, which writes org data by its author's choice, registered and wrote its row. -(c) Bob's hired worker (a stored roster row with his owner pin) naming `coordinator` is not reloaded: the reload's problem names `"coordinator"` and says it is kept for declared workers, and the stored row is byte-identical after. The declared `support.coord` on the same flow runs. -**Anti-game:** a hollow pass would grade what `workerFlowProblems` returns, or the flow's declarations. This check never calls the contract function: leg a reads the error `hireWorkforce` throws at boot; leg b records every read and write the real `agent` run makes against the store, and fails when alice's run wrote no drawer row at all (an empty set would pass the org check vacuously); leg c reads the reload's own problems and the stored row. Each broken flow is one an author could write and breaks exactly one rule; the `numbered` flow names every configuration key, so only the value is wrong. +(c) Bob's own worker (a row on his roster, written before the flow was kept for declared workers) naming `coordinator` can't run: a session created naming it is refused, naming `"coordinator"` and saying it is kept for declared workers, and the stored row is byte-identical after. The declared `support.coord` on the same flow runs. +**Anti-game:** a hollow pass would grade what `workerFlowProblems` returns, or the flow's declarations. This check never calls the contract function: leg a reads the error `hireWorkforce` throws at boot; leg b records every read and write the real `agent` run makes against the store, and fails when alice's run wrote no drawer row at all (an empty set would pass the org check vacuously); leg c reads the session create's own refusal and the stored row. Each broken flow is one an author could write and breaks exactly one rule; the `numbered` flow names every configuration key, so only the value is wrong. **Model:** n/a — handlers and a scripted generator. The property is which flows boot and where a run's state lands, not model output. **Run:** `pnpm tsx goals/worker-contract/runs-workers-only-on-registered-flows/run.mts` **Controls:** none in the runner. The spec names today's `main` as the control, and the runner cannot load there: `workerFlows`, `sharedResource` and `writeShared` do not exist on `main`. So each leg's control reverts that leg's mechanism to `main`'s behaviour, one at a time, and must fail that leg only: -- In `packages/workforce/src/hire.ts`, comment out `checkWorkerFlows(flows);` (no registration check, as on `main`). Must FAIL `[a] the app … hired`. +- In `packages/workforce/src/workers/register.ts` and `packages/workforce/src/hire.ts`, comment out `checkWorkerFlows(…)` (no registration check, as on `main`). Must FAIL `[a] the app … registered`. - In `packages/workforce/src/agent-worker-flow.ts`, comment out `scope: "user",` (the drawer at the library's org default, as on `main`). Must FAIL `[b] alice's drawer rows are in the org's cells` and `[b] bob's run touched alice's drawer`. -- In `packages/workforce/src/hire.ts`, make the standard-only `if` false (no standard-only, as on `main`). Must FAIL `[c] bob's hired worker runs on the kept flow`. +- In `packages/workforce/src/workers/installation.ts`, make the create check's standard-only `if` false (no standard-only, as on `main`). Must FAIL `[c] bob's own worker runs on the kept flow`. - In `packages/workforce/src/shared-resource.ts`, read `workerId` as `undefined` instead of the turn's verified worker. Must FAIL `[b] the shared note is …` (FIX-1788). ## Verdict log | Date | Commit | Model | Verdict | Notes | |------|--------|-------|---------|-------| +| 2026-10-08 | `865abc573` + FIX-1788 P4 (all restored) | n/a | PASS | Legs a, b, c green on one copy per flow. One boot error named doorless, numbered and loose-attribution and hired nothing; alice's 2 drawer writes landed in user scope and bob's run touched neither; the note named alice and support.scout; a session naming bob's own worker on "coordinator" was refused and his row left as stored, and support.coord ran on it. | +| 2026-10-08 | `865abc573` + FIX-1788 P4, each control then restored | n/a | FAIL (expected) | `checkWorkerFlows` commented out: **a** only (`registered 9 cop(ies)`). Drawer `scope: "user"` commented out: **b** only (`org/acme:agent`). The create check's standard-only `if` false: **c** only. `writeShared` reading no worker: **b** only (`writtenBy` without `workerId`). | | 2026-10-07 | FIX-1789 branch, `checkWorkerFlows(flows);` commented out, then restored | n/a | FAIL (expected) | **Leg a only:** `[a] the app with doorless, numbered, loose-attribution hired 5 worker(s)`. Legs b and c stayed green. | | 2026-10-07 | FIX-1789 branch, `scope: "user",` commented out in the built-in agent, then restored | n/a | FAIL (expected) | **Leg b only:** `[b] alice's drawer rows are in the org's cells: org/acme:support.helper` and `[b] bob's run touched alice's drawer: getByPrefix org/acme:support.helper`. Legs a and c stayed green. | | 2026-10-07 | FIX-1789 branch, the standard-only check forced false, then restored | n/a | FAIL (expected) | **Leg c only:** `[c] bob's hired worker runs on the kept flow "coordinator"`, and the reload reported no problem. Legs a and b stayed green. | diff --git a/goals/worker-contract/runs-workers-only-on-registered-flows/run.mts b/goals/worker-contract/runs-workers-only-on-registered-flows/run.mts index b3ade0bb77..b337010f3c 100644 --- a/goals/worker-contract/runs-workers-only-on-registered-flows/run.mts +++ b/goals/worker-contract/runs-workers-only-on-registered-flows/run.mts @@ -3,11 +3,12 @@ * worker flow, and the built-in `agent` keeps a worker's own state off org * scope while a shared note names who wrote it. * - * Real path, no model: the roster is read from files, hired through - * `hireWorkforce`, booted with `createFlowState`, run with `runAction` for two - * users of one org, and a hired worker comes back from a stored roster row - * through `reloadHiredSeats`. Graded on what boot refuses and what the store - * holds after each run, never on what the contract check returns. + * Real path, no model: the roster is read from files, registered through + * `hireWorkforce`, booted with `createFlowState`, and run with `runAction` + * for two users of one org, each in a session created naming its worker. A + * user's own worker on a flow kept for declared workers is refused when a + * session names it. Graded on what boot refuses and what the store holds + * after each run, never on what the contract check returns. * * See goal.md for the contract and the source-revert controls. * @@ -17,26 +18,11 @@ import { join } from "node:path"; import type { FlowInstance } from "@flow-state-dev/core/types"; import { createFlowState, ensureSessionRecord, inMemoryStores, runAction } from "@flow-state-dev/engine"; import { createMockModelResolver, mockGenerator } from "@flow-state-dev/testing"; -import { - createWorkerInstallation, - HIRED_ROSTER_PREFIX, - hireWorkforce, - reloadHiredSeats, - seatAddress, - toHiredSeatRow, - type HireOptions -} from "@flow-state-dev/workforce"; +import { resolveUserStorageKey } from "@flow-state-dev/engine"; +import { createWorkerInstallation, hireWorkforce } from "@flow-state-dev/workforce"; import { readWorkforce } from "@flow-state-dev/workforce/loader"; import { fixtureDir, loadFixture, runGoal, silentLogger, stripIntentOverrides } from "../../lib/index.mts"; -import { - coordinatorFlow, - doorlessFlow, - looseAttributionFlow, - numberedFlow, - defineSharerFlow, - orgKeeperFlow, - triageFlow -} from "./fixtures/flows.ts"; +import { defineFlows } from "./fixtures/flows.ts"; type Fixture = { orgId: string; @@ -57,20 +43,6 @@ stripIntentOverrides(); const fixture = loadFixture(import.meta.url); -/** - * The app's worker flows. The coordinator is kept for declared workers. The - * sharer runs its worker on the worker model, which the files' roster builds - * once read, so it joins the map then. - */ -const registered: NonNullable = { - triage: triageFlow, - [fixture.keptFlow]: { flow: coordinatorFlow, standardOnly: true }, - "org-keeper": orgKeeperFlow -}; - -/** The same app with three flows that each break one rule. */ -const BROKEN = { doorless: doorlessFlow, numbered: numberedFlow, "loose-attribution": looseAttributionFlow }; - type Access = { user: string; op: string; scopeType: string; scopeId: string; key: string }; await runGoal(async () => { @@ -83,19 +55,30 @@ await runGoal(async () => { return { failures: [`the fixture tree did not load: ${JSON.stringify([tree.errors, tree.skillErrors])}`], evidence: "" }; } const workers = tree.workers; - const installation = createWorkerInstallation({ standardWorkers: workers, workerFlows: () => registered }); - registered.sharer = defineSharerFlow(installation); + /** The app's installation, with the broken flows beside its own when `broken`. The coordinator is kept for declared workers. */ + const install = (broken: boolean) => { + let flows: Record = {}; + const installation = createWorkerInstallation({ standardWorkers: workers, workerFlows: () => flows as never }); + const built = defineFlows(installation); + flows = { + ...built.registered, + [fixture.keptFlow]: { flow: built.registered.coordinator, standardOnly: true }, + ...(broken ? built.broken : {}) + }; + return { installation, registered: Object.keys(built.registered), broken: Object.keys(built.broken) }; + }; // ---- leg a · three broken flows refused at boot, by name; nothing hired ---- let brokenSeats: FlowInstance[] | undefined; let bootError = ""; + const withBroken = install(true); try { - brokenSeats = hireWorkforce(workers, { workerFlows: { ...registered, ...BROKEN } }); + brokenSeats = hireWorkforce(withBroken.installation); } catch (error) { bootError = error instanceof Error ? error.message : String(error); } if (brokenSeats !== undefined) { - fail("a", `the app with ${Object.keys(BROKEN).join(", ")} hired ${brokenSeats.length} worker(s)`); + fail("a", `the app with ${withBroken.broken.join(", ")} registered ${brokenSeats.length} cop(ies)`); } else { const named = (flow: string) => bootError.includes(`worker flow "${flow}"`); if (!named("doorless") || !bootError.includes("no door")) fail("a", `the boot error does not name the doorless flow: ${bootError}`); @@ -103,7 +86,7 @@ await runGoal(async () => { if (!named("loose-attribution") || !bootError.includes("writtenBy")) { fail("a", `the boot error does not name loose-attribution's \`writtenBy\`: ${bootError}`); } - for (const good of ["agent", ...Object.keys(registered)]) { + for (const good of ["agent", ...withBroken.registered]) { if (named(good)) fail("a", `the boot error refuses "${good}", which meets the contract`); } if (!bootError.includes("nothing was hired")) fail("a", `the boot error does not say nothing was hired: ${bootError}`); @@ -111,17 +94,20 @@ await runGoal(async () => { } // ---- boot the app that meets the contract ------------------------ - const seats = hireWorkforce(workers, { workerFlows: registered }); - const seatById = new Map(seats.map((seat) => [seat.id, seat])); - const seat = (id: string): FlowInstance => { - const found = seatById.get(id); - if (found === undefined) throw new Error(`no seat "${id}" was hired; hired: ${[...seatById.keys()].join(", ")}`); + const { installation } = install(false); + const copies = hireWorkforce(installation); + const copyById = new Map(copies.map((copy) => [copy.id, copy])); + /** The copy of the flow `workerId` runs on. */ + const flowOf = (workerId: string): FlowInstance => { + const kind = (installation.standardWorker(workerId)?.declared.flow as string | undefined) ?? "agent"; + const found = copyById.get(kind); + if (found === undefined) throw new Error(`no copy of "${kind}" was registered; registered: ${[...copyById.keys()].join(", ")}`); return found; }; - evidence.push(`booted ${seats.length} workers on ${new Set(seats.map((s) => s.kind)).size} flows`); + evidence.push(`booted ${workers.length} workers on ${copies.length - 1} flows, one copy each`); const state = createFlowState({ - flows: Object.fromEntries(seats.map((s) => [s.id, s])), + flows: Object.fromEntries(copies.map((copy) => [copy.id, copy])), stores: { default: { primary: inMemoryStores() } }, modelResolver: createMockModelResolver({ generators: { @@ -161,16 +147,47 @@ await runGoal(async () => { return (getAll as (...args: unknown[]) => Promise)(scopeType, scopeId, ...rest); }) as typeof store.getAll; - const run = async (flow: FlowInstance, actionName: string, user: string, input: unknown) => { + /** Open `sessionId` naming `worker`, through the one session-birth path, as `user`. */ + const open = async (worker: string, user: string, sessionId: string) => { + const flow = flowOf(worker); + const now = Date.now(); + await ensureSessionRecord( + runtime.stores, + sessionId, + { + flow, + sessionId, + principal: { userId: user, orgId: fixture.orgId }, + state: { workerId: worker }, + fromCaller: true, + via: "create" + }, + () => ({ + id: sessionId, + flowKind: flow.kind, + flowId: flow.id, + userId: user, + orgId: fixture.orgId, + version: 0, + createdAt: now, + updatedAt: now, + journal: [] + }) + ); + }; + /** One turn of `worker`'s `actionName`, as `user`, in a session naming the worker. */ + const run = async (worker: string, actionName: string, user: string, input: unknown) => { + const sessionId = `${user}-${worker}-${actionName}`; + await open(worker, user, sessionId); runningAs = user; try { return await runAction({ orgId: fixture.orgId, - flow, + flow: flowOf(worker), actionName, input, userId: user, - sessionId: `${user}-${flow.id}-${actionName}`, + sessionId, stores: runtime.stores, runtimeConfig: { ...runtime.runtimeConfig, logger: silentLogger } } as never); @@ -180,14 +197,13 @@ await runGoal(async () => { }; // ---- leg b · the built-in agent's own state stays in its user's scope ---- - const helper = seat(fixture.helper); for (const user of [fixture.alice, fixture.bob]) { - const result = await run(helper, "run", user, { message: fixture.question }); - if (result.error !== undefined) fail("b", `${user}'s run on ${helper.id} failed: ${JSON.stringify(result.error)}`); + const result = await run(fixture.helper, "run", user, { message: fixture.question }); + if (result.error !== undefined) fail("b", `${user}'s run on ${fixture.helper} failed: ${JSON.stringify(result.error)}`); } const drawer = accesses.filter((a) => a.key.startsWith("skills/") && a.user !== ""); const aliceWrites = drawer.filter((a) => a.user === fixture.alice && a.op === "set"); - if (aliceWrites.length === 0) fail("b", `alice's run on ${helper.id} wrote no skills drawer rows, so nothing below is evidence`); + if (aliceWrites.length === 0) fail("b", `alice's run on ${fixture.helper} wrote no skills drawer rows, so nothing below is evidence`); const orgRows = aliceWrites.filter((a) => a.scopeType === "org"); if (orgRows.length > 0) { fail("b", `alice's drawer rows are in the org's cells: ${[...new Set(orgRows.map((a) => `org/${a.scopeId}`))].join(", ")}`); @@ -203,33 +219,7 @@ await runGoal(async () => { // Her shared note names her, and her worker: the one her session was // created with, which the turn loaded. - const scout = seat(fixture.scout); - const shareSession = `${fixture.alice}-${scout.id}-share`; - const now = Date.now(); - await ensureSessionRecord( - runtime.stores, - shareSession, - { - flow: scout, - sessionId: shareSession, - principal: { userId: fixture.alice, orgId: fixture.orgId }, - state: { workerId: fixture.scout }, - fromCaller: true, - via: "create" - }, - () => ({ - id: shareSession, - flowKind: scout.kind, - flowId: scout.id, - userId: fixture.alice, - orgId: fixture.orgId, - version: 0, - createdAt: now, - updatedAt: now, - journal: [] - }) - ); - const shared = await run(scout, "share", fixture.alice, fixture.note); + const shared = await run(fixture.scout, "share", fixture.alice, fixture.note); if (shared.error !== undefined) fail("b", `alice's note failed: ${JSON.stringify(shared.error)}`); const stored = (await get("org", fixture.orgId, `team-notes/${fixture.note.key}`)) as { state?: unknown } | undefined; const want = { text: fixture.note.text, writtenBy: { userId: fixture.alice, workerId: fixture.scout } }; @@ -240,38 +230,58 @@ await runGoal(async () => { } // A flow its author built to keep org data registered, and every member reads what it wrote (Q2). - const keeper = seat(fixture.keeper); - const kept = await run(keeper, "keep", fixture.alice, fixture.board); + const kept = await run(fixture.keeper, "keep", fixture.alice, fixture.board); const boardRow = (await get("org", fixture.orgId, `team-board/${fixture.board.key}`)) as { state?: { text?: string } } | undefined; if (kept.error !== undefined || boardRow?.state?.text !== fixture.board.text) { fail("b", `the org-keeper's own org data was not written: ${JSON.stringify(kept.error ?? boardRow)}`); } - // ---- leg c · a hired worker on a kept flow is refused ------------------ - const row = toHiredSeatRow({ - seatId: fixture.bobsOwn.seatId, + // ---- leg c · a user's own worker on a kept flow is refused --------------- + // Bob's own worker row, naming the kept flow, as a row written before the + // flow was kept for declared workers leaves it: hire refuses to write one now. + const bobsCell = resolveUserStorageKey(fixture.bob, fixture.orgId, { id: "", isolateUserState: false }); + const rowKey = `workforce/workers/${fixture.bobsOwn.seatId}`; + const row = { flow: fixture.keptFlow, - owningOrgId: fixture.orgId, - ownerUserId: fixture.bob - }); - const rowKey = `${HIRED_ROSTER_PREFIX}${fixture.bobsOwn.seatId}`; - await set("org", fixture.orgId, rowKey, row as never, "any" as never); - const before = JSON.stringify(await get("org", fixture.orgId, rowKey)); - const reload = await reloadHiredSeats({ stores: runtime.stores, orgIds: [fixture.orgId], workerFlows: registered }); - const bobsAddress = seatAddress(fixture.orgId, fixture.bobsOwn.seatId, fixture.bob); - if (reload.seats.some((s) => s.id === bobsAddress)) { - fail("c", `bob's hired worker runs on the kept flow "${fixture.keptFlow}"`); + description: null, + instructions: "You hand work on.", + teamInstructions: null, + skills: [], + settings: {}, + forkedFrom: null + }; + await set("user", bobsCell, rowKey, row as never, "any" as never); + const before = JSON.stringify(await get("user", bobsCell, rowKey)); + let refusal = ""; + try { + const flow = copyById.get(fixture.keptFlow)!; + const sessionId = `${fixture.bob}-${fixture.bobsOwn.seatId}`; + const now = Date.now(); + await ensureSessionRecord( + runtime.stores, + sessionId, + { + flow, + sessionId, + principal: { userId: fixture.bob, orgId: fixture.orgId }, + state: { workerId: fixture.bobsOwn.seatId }, + fromCaller: true, + via: "create" + }, + () => ({ id: sessionId, flowKind: flow.kind, flowId: flow.id, userId: fixture.bob, orgId: fixture.orgId, version: 0, createdAt: now, updatedAt: now, journal: [] }) + ); + } catch (error) { + refusal = error instanceof Error ? error.message : String(error); } - const problem = reload.problems.join("\n"); - if (!problem.includes(`"${fixture.keptFlow}"`) || !problem.includes("declared workers")) { - fail("c", `the refusal does not name the kept flow and say it is kept for declared workers: ${problem}`); + if (refusal === "") fail("c", `bob's own worker runs on the kept flow "${fixture.keptFlow}"`); + else if (!refusal.includes(`"${fixture.keptFlow}"`) || !refusal.includes("declared workers")) { + fail("c", `the refusal does not name the kept flow and say it is kept for declared workers: ${refusal}`); } - if (JSON.stringify(await get("org", fixture.orgId, rowKey)) !== before) fail("c", "bob's stored worker was changed by the boot"); - const coord = seat(fixture.coordinator); - const standardRun = await run(coord, "run", fixture.alice, { message: "who takes this?" }); + if (JSON.stringify(await get("user", bobsCell, rowKey)) !== before) fail("c", "bob's stored worker was changed"); + const standardRun = await run(fixture.coordinator, "run", fixture.alice, { message: "who takes this?" }); if (standardRun.error !== undefined) fail("c", `the declared worker on "${fixture.keptFlow}" did not run: ${JSON.stringify(standardRun.error)}`); - if (!reload.seats.some((s) => s.id === bobsAddress) && standardRun.error === undefined) { - evidence.push(`c: bob's hired worker on "${fixture.keptFlow}" was refused at reload and left as stored; ${coord.id} ran on it`); + if (refusal !== "" && standardRun.error === undefined) { + evidence.push(`c: a session naming bob's own worker on "${fixture.keptFlow}" was refused and his row left as stored; ${fixture.coordinator} ran on it`); } } finally { await state.dispose(); diff --git a/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/app.ts b/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/app.ts new file mode 100644 index 0000000000..ef0165a44c --- /dev/null +++ b/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/app.ts @@ -0,0 +1,123 @@ +/** + * The app the goal runs: workers as data, on two worker flows. + * + * - `agent`, the built-in, registered once and bound to the installation; + * - `research`, a worker flow the app writes, whose door answers with the + * worker the turn loaded and its instructions, and whose `reassign` action + * tries to move the session to another worker; + * - the roster flow, with `hire`, `fork` and `fire`. + * + * A caller is the user and org two headers name: the stand-in for a host's + * verified identity. `agent` answers from a scripted model that says which of + * the run's markers its prompt held, so a turn shows what it was configured + * with, never what a test wished it said. + * + * Two controls weaken one thing each, in the app's wiring only: + * `org-scoped-workers` keeps the user's workers at org scope, and + * `no-create-check` drops the worker flows' create check. + */ +import { defineFlow, handler } from "@flow-state-dev/core"; +import type { FlowInstance } from "@flow-state-dev/core/types"; +import { createMockModelResolver, type MockGeneratorInstance } from "@flow-state-dev/testing"; +import { + createWorkerHireBlocks, + createWorkerInstallation, + defineAgentWorkerFlow, + defineWorkerCollection, + defineWorkerRosterFlow, + workerConfigSchema, + WORKERS_RESOURCE, + type WorkerInstallation, + type WorkerManifest, +} from "@flow-state-dev/workforce"; +import { z } from "zod"; + +export type Control = "org-scoped-workers" | "no-create-check" | undefined; + +/** The flow kind of the app's own worker flow. */ +export const RESEARCH = "research"; + +/** Trusts two headers as the verified principal. */ +export const verified = { + resolvePrincipal: (context: { request?: Request }) => { + const userId = context.request?.headers.get("x-verified-user"); + const orgId = context.request?.headers.get("x-verified-org"); + return userId && orgId ? { userId, orgId } : null; + }, +}; + +/** A model that answers with every one of `markers` its prompt holds. */ +export function markerEchoModel(markers: readonly string[]) { + const echo = { + name: "agent-answer", + calls: [], + reset: () => undefined, + next: (input: unknown) => { + const prompt = JSON.stringify(input); + const seen = markers.filter((marker) => prompt.includes(marker)); + return { text: `seen: ${seen.length === 0 ? "none" : seen.join(" ")}` }; + }, + } as unknown as MockGeneratorInstance; + return createMockModelResolver({ generators: { "agent-answer": echo }, policy: "allow" }); +} + +function researchFlow(installation: WorkerInstallation) { + const door = z.object({ message: z.string() }).strict(); + return defineFlow({ + kind: RESEARCH, + configSchema: workerConfigSchema(), + session: installation.session(), + resources: { ...installation.resources }, + actions: { + run: { + inputSchema: door, + userMessage: (input: { message: string }) => input.message, + block: handler({ + name: "research-run", + inputSchema: door, + resources: { ...installation.resources }, + execute: async (_input, ctx) => { + const worker = await installation.resolveWorker(ctx, RESEARCH); + return { answer: `${worker.id}: ${String(worker.config.instructions ?? "")}` }; + }, + }), + }, + reassign: { + inputSchema: z.object({ to: z.string() }).strict(), + block: handler({ + name: "research-reassign", + inputSchema: z.object({ to: z.string() }).strict(), + execute: async (input, ctx) => { + await (ctx.session as unknown as { patchState(p: object): Promise }).patchState({ workerId: input.to }); + return { reassigned: input.to }; + }, + }), + }, + }, + }); +} + +/** One host's flows: one copy each of `agent`, `research` and the roster flow. */ +export function appFlows(workers: WorkerManifest[], control: Control): FlowInstance[] { + let flows: Record = {}; + const installation = createWorkerInstallation({ standardWorkers: workers, workerFlows: () => flows as never }); + if (control === "org-scoped-workers") { + (installation.resources as Record)[WORKERS_RESOURCE] = { ...defineWorkerCollection(), scope: "org" }; + } + const bound: WorkerInstallation = + control === "no-create-check" + ? { ...installation, session: (shape) => ({ ...installation.session(shape), createCheck: undefined as never }) } + : installation; + + const agent = defineAgentWorkerFlow({ installation: bound }); + const research = researchFlow(bound); + flows = { agent, [RESEARCH]: research }; + + const { hire, fork, fire } = createWorkerHireBlocks(bound); + const roster = defineWorkerRosterFlow(bound, { + hire: { inputSchema: hire.inputSchema, block: hire }, + fork: { inputSchema: fork.inputSchema, block: fork }, + fire: { inputSchema: fire.inputSchema, block: fire }, + }); + return [agent({ id: "agent" }), research(), roster()] as unknown as FlowInstance[]; +} diff --git a/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/input.json b/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/input.json new file mode 100644 index 0000000000..0205b23330 --- /dev/null +++ b/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/input.json @@ -0,0 +1,9 @@ +{ + "org": "acme", + "alice": "alice", + "bob": "bob", + "standard": { "onAgent": "desk.amy", "onResearch": "research.lead" }, + "markers": { "onAgent": "AMY-DESK-7Q", "onResearch": "LEAD-RESEARCH-2M", "skill": "SKILL-REFUND-R9" }, + "fork": { "id": "my-desk" }, + "hire": { "id": "scribe", "instructions": "You take notes. Sign every answer SCRIBE-NOTES-5H." , "marker": "SCRIBE-NOTES-5H" } +} diff --git a/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/workforce/teams/desk/workers/amy/WORKER.md b/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/workforce/teams/desk/workers/amy/WORKER.md new file mode 100644 index 0000000000..3f82f5a0a2 --- /dev/null +++ b/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/workforce/teams/desk/workers/amy/WORKER.md @@ -0,0 +1,5 @@ +--- +description: Answers the front desk. +--- + +You are the front desk. Sign every answer AMY-DESK-7Q. diff --git a/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/workforce/teams/desk/workers/amy/skills/refund-policy/SKILL.md b/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/workforce/teams/desk/workers/amy/skills/refund-policy/SKILL.md new file mode 100644 index 0000000000..89828410e1 --- /dev/null +++ b/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/workforce/teams/desk/workers/amy/skills/refund-policy/SKILL.md @@ -0,0 +1,5 @@ +--- +description: The refund policy. +--- + +Refunds take five working days from approval. Cite SKILL-REFUND-R9. diff --git a/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/workforce/teams/research/workers/lead/WORKER.md b/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/workforce/teams/research/workers/lead/WORKER.md new file mode 100644 index 0000000000..f371192d4b --- /dev/null +++ b/goals/workers-as-resources/keeps-each-users-workers-their-own/fixtures/workforce/teams/research/workers/lead/WORKER.md @@ -0,0 +1,6 @@ +--- +flow: research +description: Leads research. +--- + +You lead research. Sign every answer LEAD-RESEARCH-2M. diff --git a/goals/workers-as-resources/keeps-each-users-workers-their-own/goal.md b/goals/workers-as-resources/keeps-each-users-workers-their-own/goal.md new file mode 100644 index 0000000000..c94345987d --- /dev/null +++ b/goals/workers-as-resources/keeps-each-users-workers-their-own/goal.md @@ -0,0 +1,21 @@ +# workers-as-resources › it keeps each user's workers their own + +**Issue:** FIX-1788 (epic FIX-1786) +**Outcome:** In one org, each user's workers are theirs alone: another user can't open, read, run or create a session with them. Every worker runs on one shared copy of the flow it names, with its own memory on the built-in `agent`. A user hires or forks a worker without a restart and can't change a standard one. +**Input:** `fixtures/workforce/` — two `WORKER.md` standard workers on two flows: one on `agent` holding a skill, one on the app's own `research` flow. `fixtures/input.json` — the org, two users, the fork's and the hire's ids, the hire's instructions and the marker each worker's configuration carries. `fixtures/app.ts` — the app: `agent` bound to the installation, the `research` worker flow, and the roster flow with `hire`, `fork` and `fire`, behind a principal two headers name. Held-out: the standard workers' ids come from the tree and every other id and marker from the fixture, so another tree, other ids or other markers must pass too. +**Signal:** two processes of the app, each the real HTTP router over one on-disk SQLite file, the second started before anything is hired. Every call goes through the shipped clients (`createWorkforceClient`, `createSessionClient`, `createClient`). +(a) Alice forks the standard `agent` worker (`a:fork`) and hires one of her own (`a:hire`), and her roster lists both beside the standard workers, each with its flow (`a:roster`). `ensureWorkerSession` opens one session per worker, twice the same one, and a turn in each answers with its own configuration's marker and no other's: the standard worker and its fork (`a:standard`, `a:fork-answers`), the hire through the second process (`a:second-host`), and the `research` worker (`a:research`). Every agent turn asks for the standard worker's skill by name: the standard worker and the fork answer with it, and the hire, which holds none, doesn't (`a:own-memory`). Neither process's registry changes, and none holds a copy named for a worker (`a:one-copy`). +(b) Bob's roster lists none of Alice's workers (`b:reads-worker`); his `findWorkerSession` for her hire finds nothing (`b:find`); opening her session (`b:open`), running a turn in it (`b:run`) and creating a session naming her worker (`b:create`) are refused. A session created with no worker (`b:no-worker`), a turn whose input names a worker, on both flows (`b:names-worker`), a turn that moves a `research` session to another worker, after which the session still answers as its own (`b:reassign`), and Alice's hire, which runs on `agent`, given a session on `research` (`b:other-flow`) are each refused. +**Anti-game:** a hollow pass would read the session's stored `workerId` (proving what was written, not what a caller reaches), seed a worker row directly, register a copy per worker that happens to answer right, or let the model say whatever the check wants. So the check MUST NOT assert on a stored `workerId` or any key string; it MUST hire and fork only through the roster flow's actions; it MUST grade each answer by the markers the turn's prompt held, read back from the request's output over the routes; it MUST reach the hire through a process started before the hire; and it MUST count the registry, not trust that nothing was minted. A refusal counts only when the call threw or its run ended other than `completed`. +**Model:** n/a, a scripted model: `agent` answers with the markers its prompt held. Access is under test, not answers. +**Run:** `pnpm tsx goals/workers-as-resources/keeps-each-users-workers-their-own/run.mts` +**Controls:** `GOAL_CONTROL=org-scoped-workers` keeps the users' workers at org scope, in the app's wiring. It must FAIL leg b on `b:reads-worker` (Bob reads Alice's worker); `b:create` fails with it, and leg a stays green. `GOAL_CONTROL=no-create-check` drops the worker flows' create check. It must FAIL leg b on `b:create` (Bob's create naming Alice's worker writes a session); `b:other-flow` fails with it, and leg a stays green. + +## Verdict log +| Date | Commit | Model | Verdict | Notes | +|------|--------|-------|---------|-------| +| 2026-10-07 | fix/FIX-1788-p4 (pre-PR) | scripted | PASS | a: Alice forked `my-desk` and hired `scribe`; four workers answered as their own configuration on one copy per flow (`agent`, `research`, `workforce-roster`), `scribe` through the second process with no restart, and read no other worker's skill. b: every reach for Alice's workers, and every way to run a session as another worker, refused. | +| 2026-10-07 | fix/FIX-1788-p4 (pre-PR), `GOAL_CONTROL=org-scoped-workers` | scripted | FAIL (expected) | `b:reads-worker` — Bob reads `my-desk`, `scribe` on his roster; `b:create` with it. Leg a passed. | +| 2026-10-07 | fix/FIX-1788-p4 (pre-PR), `GOAL_CONTROL=no-create-check` | scripted | FAIL (expected) | `b:create` — Bob's create naming Alice's `scribe` wrote a session; `b:other-flow` with it. Leg a passed. | +| 2026-10-07 | fix/FIX-1788-p4 (pre-PR), `agent`'s drawer partition removed by hand | scripted | FAIL (expected) | `a:own-memory` — `scribe` answered with the standard worker's `SKILL-REFUND-R9`. Nothing else failed. | +| 2026-10-07 | origin/main ac39e7c14 (engine and workforce sources as on `main`) | scripted | FAIL (expected) | Neither leg runs: `main` can't run `agent` as one copy for every worker. The copy is refused at boot, `"seatId": Required`, because each copy there is minted for one worker. | diff --git a/goals/workers-as-resources/keeps-each-users-workers-their-own/run.mts b/goals/workers-as-resources/keeps-each-users-workers-their-own/run.mts new file mode 100644 index 0000000000..cc15954934 --- /dev/null +++ b/goals/workers-as-resources/keeps-each-users-workers-their-own/run.mts @@ -0,0 +1,249 @@ +/** + * Goal check — in one org, each user's workers are theirs alone, every worker + * runs on one shared copy of the flow it names with its own memory on + * `agent`, and a hire reaches a second process without a restart. + * + * Real path, no mocking but a scripted model, out of CI: two hosts of one app, + * each the real HTTP router over one on-disk SQLite file, driven through the + * shipped clients the way an app drives them. See goal.md for the contract. + * + * Run: pnpm tsx goals/workers-as-resources/keeps-each-users-workers-their-own/run.mts + * Controls: GOAL_CONTROL=org-scoped-workers must FAIL leg b on "b:reads-worker"; + * GOAL_CONTROL=no-create-check must FAIL leg b on "b:create". + */ +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createClient, createSessionClient, type ClientFetch } from "@flow-state-dev/client"; +import { createFlowApiRouter, createFlowRegistry, type FlowRegistry, type StoreRegistry } from "@flow-state-dev/engine"; +import { createSQLiteStores } from "@flow-state-dev/store-sqlite"; +import { createWorkforceClient, ROSTER_FLOW_KIND } from "@flow-state-dev/workforce/browser"; +import { readWorkforce } from "@flow-state-dev/workforce/loader"; +import { fixtureDir, loadFixture, runGoal, silentLogger, stripIntentOverrides } from "../../lib/index.mts"; +import { appFlows, markerEchoModel, RESEARCH, verified, type Control } from "./fixtures/app"; + +type Fixture = { + org: string; + alice: string; + bob: string; + standard: { onAgent: string; onResearch: string }; + markers: { onAgent: string; onResearch: string; skill: string }; + fork: { id: string }; + hire: { id: string; instructions: string; marker: string }; +}; + +stripIntentOverrides(); + +const fixture = loadFixture(import.meta.url); +const CONTROLS = ["org-scoped-workers", "no-create-check"] as const; +const control = process.env.GOAL_CONTROL as Control; +if (control !== undefined && !(CONTROLS as readonly string[]).includes(control)) { + throw new Error(`Unknown GOAL_CONTROL "${control}". This goal understands: ${CONTROLS.join(", ")}.`); +} + +const tree = await readWorkforce(join(fixtureDir(import.meta.url), "workforce")); +if (tree.errors.length > 0 || tree.skillErrors.length > 0) { + throw new Error(`the fixture tree did not load: ${JSON.stringify([tree.errors, tree.skillErrors])}`); +} +const MARKERS = [fixture.markers.onAgent, fixture.markers.onResearch, fixture.markers.skill, fixture.hire.marker]; + +/** One process of the app over the SQLite file. */ +function host(dbFile: string) { + const stores = createSQLiteStores({ filename: dbFile }) as unknown as StoreRegistry; + const registry: FlowRegistry = createFlowRegistry(); + for (const flow of appFlows(tree.workers, control)) registry.register(flow); + const router = createFlowApiRouter({ + registry, + stores, + resolvePrincipal: verified.resolvePrincipal, + modelResolver: markerEchoModel(MARKERS), + logger: silentLogger, + staleSweepIntervalMs: 0, + } as never) as unknown as Record Promise>; + + /** A fetch that hands each request to this host's router as `user`. */ + const fetcher = + (user: string): ClientFetch => + async (input, init) => { + const url = new URL(String(input), "http://goal.local"); + const headers = new Headers(init?.headers); + headers.set("x-verified-user", user); + headers.set("x-verified-org", fixture.org); + const path = url.pathname.replace(/^\/api\/flows\/?/, "").split("/").filter(Boolean).map(decodeURIComponent); + const method = (init?.method ?? "GET").toUpperCase(); + return router[method]!(new Request(url, { ...init, headers }), { params: { path } }); + }; + + /** What one user reaches through this host: the shipped clients, nothing else. */ + const as = (user: string) => { + const transport = { fetcher: fetcher(user) }; + const sessions = createSessionClient(transport); + const workforce = createWorkforceClient({ userId: user, ...transport }); + /** One action, followed to its end: its status, its output and its error. */ + const act = async (flowKind: string, sessionId: string, action: string, input: unknown) => { + const actions = createClient({ flowKind, userId: user, ...transport }); + const started = await actions.sendAction(action, input, { sessionId }); + const until = Date.now() + 15_000; + let status = (await actions.getRequestStatus(started.request.id)).status; + while (status === "in_progress") { + if (Date.now() > until) throw new Error(`${action} on ${sessionId} never settled`); + await new Promise((resolve) => setTimeout(resolve, 10)); + status = (await actions.getRequestStatus(started.request.id)).status; + } + const listed = await sessions.listSessionRequests(sessionId, { includeResultOutput: true, limit: 100 }); + const found = listed.find((request) => request.id === started.request.id); + return { status, output: JSON.stringify(found?.result?.output ?? null), error: found?.result?.error?.message ?? null }; + }; + return { sessions, workforce, act }; + }; + return { registry, as, close: () => (stores as unknown as { close(): void }).close() }; +} + +/** Whether `attempt` was refused: it threw, or its run ended other than completed. */ +async function refused(attempt: () => Promise<{ status: string } | unknown>): Promise { + try { + const result = await attempt(); + return result !== null && typeof result === "object" && "status" in result && (result as { status: string }).status !== "completed"; + } catch { + return true; + } +} + +await runGoal(async () => { + const failures: string[] = []; + const evidence: string[] = []; + const { markers, standard, fork, hire } = fixture; + const dbFile = join(mkdtempSync(join(tmpdir(), "fsd-workers-as-resources-")), "goal.db"); + + const first = host(dbFile); + // The second process is up before anything is hired. + const second = host(dbFile); + const registered = (h: ReturnType) => h.registry.list().map((flow) => flow.id).sort(); + const before = { first: registered(first), second: registered(second) }; + + // ---- leg a: Alice forks, hires and talks -------------------------------- + const alice = first.as(fixture.alice); + await alice.workforce.roster(); // her roster session + const [rosterSession] = await alice.sessions.listSessions({ flowKind: ROSTER_FLOW_KIND, userId: fixture.alice }); + if (rosterSession === undefined) return { failures: ["a:roster — Alice has no roster session"], evidence: "" }; + const forked = await alice.act(ROSTER_FLOW_KIND, rosterSession.id, "fork", { from: standard.onAgent, id: fork.id }); + if (forked.status !== "completed") failures.push(`a:fork — fork ended ${forked.status}: ${forked.error}`); + const hired = await alice.act(ROSTER_FLOW_KIND, rosterSession.id, "hire", { + id: hire.id, + flow: "agent", + instructions: hire.instructions, + }); + if (hired.status !== "completed") failures.push(`a:hire — hire ended ${hired.status}: ${hired.error}`); + + const roster = (await alice.workforce.roster()).map((entry) => `${entry.id}@${entry.flow}`).sort(); + for (const expected of [`${fork.id}@agent`, `${hire.id}@agent`, `${standard.onAgent}@agent`, `${standard.onResearch}@${RESEARCH}`]) { + if (!roster.includes(expected)) failures.push(`a:roster — Alice's roster lacks ${expected}: ${roster.join(", ")}`); + } + + // Each worker answers as its own configuration. The hire is reached through + // the second process, which was never restarted. + const talks: Array<{ worker: string; via: ReturnType; own: string[]; leg: string }> = [ + { worker: standard.onAgent, via: first, own: [markers.onAgent, markers.skill], leg: "a:standard" }, + { worker: fork.id, via: first, own: [markers.onAgent, markers.skill], leg: "a:fork-answers" }, + { worker: hire.id, via: second, own: [hire.marker], leg: "a:second-host" }, + { worker: standard.onResearch, via: first, own: [markers.onResearch], leg: "a:research" }, + ]; + const sessionOf = new Map(); + for (const talk of talks) { + const client = talk.via.as(fixture.alice); + let session: { id: string; flowKind: string }; + try { + session = await client.workforce.ensureWorkerSession({ worker: talk.worker }); + } catch (error) { + failures.push(`${talk.leg} — ensureWorkerSession(${talk.worker}) refused: ${(error as Error).message}`); + continue; + } + sessionOf.set(talk.worker, session); + const again = await client.workforce.ensureWorkerSession({ worker: talk.worker }); + if (again.id !== session.id) failures.push(`${talk.leg} — a second ensureWorkerSession(${talk.worker}) opened another session`); + // Every worker is asked for the skill only the standard worker and its fork hold. + const turn = await client.act(session.flowKind, session.id, "run", { message: "/refund-policy Who are you?" }); + if (turn.status !== "completed") { + failures.push(`${talk.leg} — ${talk.worker}'s turn ended ${turn.status}: ${turn.error}`); + continue; + } + for (const marker of talk.own) { + if (!turn.output.includes(marker)) failures.push(`${talk.leg} — ${talk.worker} answered without its own ${marker}: ${turn.output}`); + } + for (const marker of MARKERS.filter((m) => !talk.own.includes(m))) { + if (!turn.output.includes(marker)) continue; + // A skill seen by a worker that doesn't hold it came from another + // worker's drawer: the standard worker and the fork both run first. + const leg = marker === markers.skill ? "a:own-memory" : talk.leg; + failures.push(`${leg} — ${talk.worker} answered with another worker's ${marker}: ${turn.output}`); + } + } + for (const [name, h] of [["first", first], ["second", second]] as const) { + const after = registered(h); + if (JSON.stringify(after) !== JSON.stringify(before[name])) { + failures.push(`a:one-copy — the ${name} process's registry changed: ${before[name].join(", ")} → ${after.join(", ")}`); + } + const perWorker = after.filter((id) => [fork.id, hire.id, standard.onAgent, standard.onResearch].includes(id)); + if (perWorker.length > 0) failures.push(`a:one-copy — the ${name} process registered a copy per worker: ${perWorker.join(", ")}`); + } + evidence.push( + `a: Alice forked ${fork.id} and hired ${hire.id}; ${talks.length} workers answered as their own configuration on one copy per flow (${before.first.join(", ")}), ${hire.id} through the second process with no restart, and ${hire.id} read no other worker's skills`, + ); + + // ---- leg b: Bob reaches for Alice's workers ------------------------------ + const bob = first.as(fixture.bob); + const bobsRoster = (await bob.workforce.roster()).map((entry) => entry.id); + const leaked = bobsRoster.filter((id) => id === fork.id || id === hire.id); + if (leaked.length > 0) failures.push(`b:reads-worker — Bob reads Alice's worker(s) ${leaked.join(", ")} on his roster`); + const hireSession = sessionOf.get(hire.id); + try { + const found = await bob.workforce.findWorkerSession({ worker: hire.id }); + if (found !== undefined) failures.push(`b:find — Bob found ${found.id}, a session with Alice's ${hire.id}`); + } catch { + // Refused outright: nothing found. + } + if (hireSession !== undefined) { + if (!(await refused(() => bob.sessions.getSession(hireSession.id)))) { + failures.push(`b:open — Bob opened Alice's session ${hireSession.id}`); + } + if (!(await refused(() => bob.act("agent", hireSession.id, "run", { message: "hello" })))) { + failures.push(`b:run — Bob ran a turn in Alice's session ${hireSession.id}`); + } + } + if (!(await refused(() => bob.sessions.createSession({ flowKind: "agent", userId: fixture.bob, state: { workerId: hire.id } })))) { + failures.push(`b:create — Bob's create naming Alice's ${hire.id} wrote a session`); + } + if (!(await refused(() => alice.sessions.createSession({ flowKind: "agent", userId: fixture.alice })))) { + failures.push("b:no-worker — a session was created on agent with no worker"); + } + if (!(await refused(() => alice.sessions.createSession({ flowKind: RESEARCH, userId: fixture.alice, state: { workerId: hire.id } })))) { + failures.push(`b:other-flow — Alice's ${hire.id}, which runs on agent, got a session on ${RESEARCH}`); + } + const deskSession = sessionOf.get(standard.onAgent); + if (deskSession !== undefined) { + if (!(await refused(() => alice.act("agent", deskSession.id, "run", { message: "hello", workerId: hire.id })))) { + failures.push(`b:names-worker — a turn on agent whose message named ${hire.id} ran`); + } + } + const researchSession = sessionOf.get(standard.onResearch); + if (researchSession !== undefined) { + if (!(await refused(() => alice.act(RESEARCH, researchSession.id, "run", { message: "hello", workerId: hire.id })))) { + failures.push(`b:names-worker — a turn on ${RESEARCH} whose message named ${hire.id} ran`); + } + if (!(await refused(() => alice.act(RESEARCH, researchSession.id, "reassign", { to: hire.id })))) { + failures.push(`b:reassign — a turn moved a ${RESEARCH} session to ${hire.id}`); + } + const after = await alice.act(RESEARCH, researchSession.id, "run", { message: "Who are you now?" }); + if (!after.output.includes(markers.onResearch) || after.output.includes(hire.marker)) { + failures.push(`b:reassign — after the refused move, the session answered as: ${after.output}`); + } + } + evidence.push( + "b: Bob's roster lists none of Alice's workers, and his find, open, run and create naming her worker are refused; a session with no worker, a turn naming a worker, a turn moving a session to another worker, and a session on a flow the worker doesn't run on are refused", + ); + if (control !== undefined) evidence.push(`control ${control} active`); + + first.close(); + second.close(); + return { failures, evidence: evidence.join("; ") }; +}); diff --git a/goals/workforce-conventions/a-mailbox-holds-the-work-a-seat-drains/harness.mts b/goals/workforce-conventions/a-mailbox-holds-the-work-a-seat-drains/harness.mts index 87c0580efb..4a81841ff9 100644 --- a/goals/workforce-conventions/a-mailbox-holds-the-work-a-seat-drains/harness.mts +++ b/goals/workforce-conventions/a-mailbox-holds-the-work-a-seat-drains/harness.mts @@ -47,6 +47,8 @@ interface TreeSpec { boardHolder: { id: string; address: string }; /** Declared members, per mailbox id — who a fan-out on that mailbox addresses. */ membersByMailbox: Record; + /** The flow each member's worker runs on; one copy of it is the member's seat. */ + flowByMember: Record; mailboxOwner: string; appUserId: string; } @@ -203,7 +205,7 @@ out.sessions = sessions; // framework's half: a seat's post is never routed, so the // fan-out walks the whole roster. // `delivered` — which members a delivery was made to: a wake dispatched to -// that member's seat (`wake-`), or the name-only line +// that member's seat (`wake--`), or the name-only line // the goal checks' `name-only-notify` control puts in the // wake's place (`kitchen-sink-notify-member`). // @@ -245,7 +247,9 @@ for (const mailbox of TREE.mailboxes) { sawFanOut: fanOut.length > 0, reached: fanOut.reduce((n: number, t: any) => n + (t.output?.shape?.entries?.length ?? 0), 0), delivered: [ - ...members.filter((member) => traces.some((t: any) => t.blockName === `wake-${member}`)), + ...members.filter((member) => + traces.some((t: any) => t.blockName === `wake-${TREE.flowByMember[member]}-${member}`), + ), ...traces .filter((t: any) => t.blockName === NAME_ONLY_BLOCK) .map((t: any) => String(t.output?.value?.notified ?? "")) @@ -278,7 +282,7 @@ out.notified = notified; const members = new Set(Object.values(TREE.membersByMailbox).flat()); out.hearsPosts = [...members] .filter((member) => { - const seat = registry.get(member) as { internal?: { actions?: object } } | undefined; + const seat = registry.get(TREE.flowByMember[member] ?? "") as { internal?: { actions?: object } } | undefined; return Object.prototype.hasOwnProperty.call(seat?.internal?.actions ?? {}, "onMailboxPost"); }) .sort(); diff --git a/goals/workforce-conventions/a-mailbox-holds-the-work-a-seat-drains/run.mts b/goals/workforce-conventions/a-mailbox-holds-the-work-a-seat-drains/run.mts index 65e194980a..46946dcc1f 100644 --- a/goals/workforce-conventions/a-mailbox-holds-the-work-a-seat-drains/run.mts +++ b/goals/workforce-conventions/a-mailbox-holds-the-work-a-seat-drains/run.mts @@ -34,7 +34,7 @@ import ts from "typescript"; import { z } from "zod"; import { createSessionClient } from "@flow-state-dev/client"; import { defineFlow, handler } from "@flow-state-dev/core"; -import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; +import { createFlowState, ensureSessionRecord, inMemoryStores, runAction } from "@flow-state-dev/engine"; import { taskBoard, taskWorkerInputSchema } from "@flow-state-dev/orchestration/task-board"; import type { Task, TaskWorkerInput } from "@flow-state-dev/orchestration/tasks"; import { @@ -43,6 +43,7 @@ import { mailboxInstances, mailboxNotifyInputSchema, defineMailboxFlow, + createWorkerInstallation, hireWorkforce, openMailboxes, wakeMemberSeats, @@ -431,6 +432,16 @@ function appLegs(failures: string[], evidence: string[]): void { mailboxes: manifests.map((m) => ({ id: m.id, address: m.declaredKind ?? "mailbox" })), boardHolder: { id: boardHolder.id, address: boardHolder.declaredKind ?? "mailbox" }, membersByMailbox: Object.fromEntries(manifests.map((m) => [m.id, m.members])), + // The flow each member's worker runs on, off its own WORKER.md: the + // copy of that flow is the seat a post to the member reaches. + flowByMember: Object.fromEntries( + [...new Set(manifests.flatMap((m) => m.members))].map((member) => { + const [team, name] = member.split("."); + const file = join(WORKFORCE, "teams", team!, "workers", name!, "WORKER.md"); + const { frontmatter } = existsSync(file) ? splitManifest(readFileSync(file, "utf8")) : { frontmatter: "" }; + return [member, frontmatter.match(/^flow:\s*(.+)$/m)?.[1]?.trim() ?? "agent"]; + }), + ), mailboxOwner, appUserId, }), @@ -594,7 +605,13 @@ async function fixtureLegs(failures: string[], evidence: string[]): Promise = {}; + const installation = createWorkerInstallation({ + standardWorkers: roster.workers, + workerFlows: () => workerFlows as never, + }); const noteRan = handler({ name: "fixture-run-row", inputSchema: taskWorkerInputSchema, @@ -612,6 +629,8 @@ async function fixtureLegs(failures: string[], evidence: string[]): Promise instance.kind === "mailbox")!; const members = (holder.declared.members as string[] | undefined) ?? []; + /** The copy a member's worker runs on: the flow its file names, or the built-in agent. */ + const copyOf = (member: string) => { + const flow = roster.workers.find((w) => w.id === member)?.declared.flow ?? "agent"; + return seats.find((s) => s.kind === flow); + }; const hearsPosts = members.filter((member) => { - const seat = seats.find((s) => s.id === member) as { internal?: { actions?: object } } | undefined; + const seat = copyOf(member) as { internal?: { actions?: object } } | undefined; return Object.prototype.hasOwnProperty.call(seat?.internal?.actions ?? {}, "onMailboxPost"); }); if (hearsPosts.length === 0) { @@ -776,7 +799,7 @@ async function fixtureLegs(failures: string[], evidence: string[]): Promise 0, reached: fanOut.reduce((n: number, t: any) => n + (t.output?.shape?.entries?.length ?? 0), 0), delivered: [ - ...members.filter((member) => traces.some((t: any) => t.blockName === `wake-${member}`)), + ...members.filter((member) => traces.some((t: any) => t.blockName === `wake-${copyOf(member)?.id}-${member}`)), ...traces .filter((t: any) => t.blockName === "fixture-notify-member") .map((t: any) => String(t.output?.value?.notified ?? "")) @@ -812,7 +835,35 @@ async function fixtureLegs(failures: string[], evidence: string[]): Promise w.declared.flow === coder.kind)!.id; + const sessionId = `s_${worker}`; + const now = Date.now(); + await ensureSessionRecord( + runtime.stores, + sessionId, + { + flow: coder as never, + sessionId, + principal: { userId: FIXTURE_USER, orgId: orgId! }, + state: { workerId: worker }, + fromCaller: true, + via: "create", + }, + () => + ({ + id: sessionId, + flowKind: coder.kind, + flowId: coder.id, + userId: FIXTURE_USER, + orgId, + version: 0, + createdAt: now, + updatedAt: now, + journal: [], + }) as never, + ); + const drained = await act(coder, sessionId, "drain", {}); if (drained.error !== undefined) failures.push(`V8: the coder's drain failed: ${String(drained.error)}`); } for (const [i, name] of unwired.entries()) { diff --git a/goals/workforce-conventions/a-team-says-once-what-its-seats-are-told/fixtures/flows.ts b/goals/workforce-conventions/a-team-says-once-what-its-seats-are-told/fixtures/flows.ts index 715030c1ad..b5a241ad58 100644 --- a/goals/workforce-conventions/a-team-says-once-what-its-seats-are-told/fixtures/flows.ts +++ b/goals/workforce-conventions/a-team-says-once-what-its-seats-are-told/fixtures/flows.ts @@ -13,7 +13,7 @@ * string would satisfy neither on its own. */ import { defineFlow, handler, sequencer } from "@flow-state-dev/core"; -import { workerConfigSchema } from "@flow-state-dev/workforce"; +import { workerConfigSchema, workerConfigOf, type WorkerInstallation } from "@flow-state-dev/workforce"; import { z } from "zod"; import { workerDoor } from "../../../lib/worker-door.mts"; @@ -81,14 +81,15 @@ const recordLayers = handler({ name: "triage-record", inputSchema, outputSchema: z.void(), - flowConfigSchema: needsInstructionLayers, sessionStateSchema: seatState, execute: async (_input, ctx) => { + // The turn's worker, as the flow's `request.onStarted` loaded it. + const config = needsInstructionLayers.parse(workerConfigOf(ctx)); await ctx.session.patchState({ - team: ctx.flow.config.teamInstructions ?? null, - teamKeyPresent: Object.hasOwn(ctx.flow.config, "teamInstructions"), - own: ctx.flow.config.instructions ?? null, - desk: ctx.flow.config.desk + team: config.teamInstructions ?? null, + teamKeyPresent: Object.hasOwn(config, "teamInstructions"), + own: config.instructions ?? null, + desk: config.desk }); } }); @@ -113,16 +114,30 @@ const clientView = { } }; -/** Composes the contract. No model, no generator — handlers only. */ -export const triageFlow = defineFlow({ +/** + * Composes the contract. No model, no generator — handlers only. One copy runs + * every worker on it; a session names its worker, and the flow's + * `request.onStarted` loads it on every turn. + */ +export function defineTriageFlow(installation: WorkerInstallation) { + const loadWorker = handler({ + name: "triage-load-worker", + inputSchema: z.unknown(), + resources: { ...installation.resources }, + execute: async (_input, ctx) => ({ worker: (await installation.resolveWorker(ctx, TRIAGE_KIND)).id }) + }); + return defineFlow({ kind: TRIAGE_KIND, cardinality: "collection", configSchema: workerConfigSchema().extend({ desk: z.string().default("front") }), + resources: { ...installation.resources }, + request: { onStarted: loadWorker }, actions: { ...workerDoor, run: { inputSchema, block: sequencer({ name: "triage-work", inputSchema }).tap(start).tap(recordLayers) } }, - session: { stateSchema: seatState, client: clientView } + session: { ...installation.session(seatState.shape), client: clientView } }); +} diff --git a/goals/workforce-conventions/a-team-says-once-what-its-seats-are-told/goal.md b/goals/workforce-conventions/a-team-says-once-what-its-seats-are-told/goal.md index e5112674b4..2bc2330c15 100644 --- a/goals/workforce-conventions/a-team-says-once-what-its-seats-are-told/goal.md +++ b/goals/workforce-conventions/a-team-says-once-what-its-seats-are-told/goal.md @@ -10,7 +10,7 @@ **Signal:** against the real HTTP router (`createFlowApiRouter`) over on-disk SQLite stores, matching its siblings. The records come from the real loader (`readWorkforce`), never hand-built: the folders are half of what is under test. (a) `readWorkforce` reads the tree with no errors of any of its three kinds and produces three records. `teams` carries **only** the team that wrote a file, and that record's `description` is the one the file declared — asserted here because nothing else consumes it yet, so a description validated and then dropped would otherwise go unnoticed. One `hireWorkforce` call turns all three records into seats of the non-agent kind. -(b) Each seat runs `POST /api/flows///actions/run` to completion. After closing the stores, reopening the same file and building a fresh host, `GET /api/flows/sessions//state` shows what a block **nested inside the action** read from `ctx.flow.config`: for the two seats on the team with a file, its team's instructions **and** its own, as two separate values matching the two files byte for byte, plus its own desk. +(b) Each worker, in a session created naming it on the flow's one copy, runs `POST /api/flows///actions/run` to completion. After closing the stores, reopening the same file and building a fresh host, `GET /api/flows/sessions//state` shows what a block **nested inside the action** read from the turn's worker: for the two seats on the team with a file, its team's instructions **and** its own, as two separate values matching the two files byte for byte, plus its own desk. (c) The seat on the team with no `TEAM.md` carries **no `teamInstructions` key at all**, and its own instructions are unchanged. Absence is graded on `Object.hasOwn` inside the running block, not on the value: an empty string reads back falsy and would slip past a truthiness check, and absent-not-empty is precisely what this feature promises. (d) The same key **is** present for the two seats whose team wrote one. Without this leg, (c) is equally consistent with the key never reaching anybody, which would pass every absence check in the file. @@ -24,6 +24,7 @@ ## Verdict log | Date | Commit | Model | Verdict | Notes | |------|--------|-------|---------|-------| +| 2026-10-08 | `865abc573` + FIX-1788 P4 | n/a (handlers only) | PASS | On one copy of the triage flow: each worker's session named it, and the nested block read the turn's worker (loaded in `request.onStarted`): both seats on the team with a TEAM.md showed the team layer and their own as two values; the seat on the team without one carried no `teamInstructions` key. | | 2026-09-18 | fix/FIX-1377-team-md (pre-PR) | n/a (handlers only) | PASS | The loader read the two-team tree, surfaced `pentest` alone in `teams` with its declared description, and all three records hired into a kind with no model in it. All three ran through the real HTTP route; after closing the SQLite file and rebuilding the host, `pentest.recon` and `pentest.scout` each showed their team's instructions and their own as two distinct values, and `billing.desk` showed `teamInstructions` **absent** from its bag with its own instructions intact. | | 2026-09-18 | fix/FIX-1377-team-md (control, join removed) | n/a | FAIL (expected) | Dropping the attach in `readWorkforce` took legs (b) and (d) red for both pentest seats — *"its nested block saw team instructions null"* and *"its team wrote a TEAM.md, but the key was absent from its bag"* — while (c) stayed green, which is the point of (d): absence alone cannot tell a working feature from an absent one. | | 2026-09-18 | fix/FIX-1377-team-md (control, one layer for every seat) | n/a | FAIL (expected) | Handing every record the first team's layer was caught by (c): *"billing.desk: its team wrote no TEAM.md, but the key was present in its bag"*. Confirms the isolation half is graded and not assumed. | diff --git a/goals/workforce-conventions/a-team-says-once-what-its-seats-are-told/run.mts b/goals/workforce-conventions/a-team-says-once-what-its-seats-are-told/run.mts index e8072d8566..1bd1ae0f52 100644 --- a/goals/workforce-conventions/a-team-says-once-what-its-seats-are-told/run.mts +++ b/goals/workforce-conventions/a-team-says-once-what-its-seats-are-told/run.mts @@ -17,17 +17,17 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { createFlowApiRouter, createFlowRegistry, type StoreRegistry } from "@flow-state-dev/engine"; import { createSQLiteStores } from "@flow-state-dev/store-sqlite"; -import { hireWorkforce, type HireOptions } from "@flow-state-dev/workforce"; import { readWorkforce } from "@flow-state-dev/workforce/loader"; import type { FlowInstance } from "@flow-state-dev/core/types"; import { fixtureDir, + installWorkers, loadFixture, runGoal, silentLogger, stripIntentOverrides } from "../../lib/index.mts"; -import { TRIAGE_KIND, triageFlow } from "./fixtures/flows"; +import { TRIAGE_KIND, defineTriageFlow } from "./fixtures/flows"; type SeatFixture = { id: string; desk: string; own: string }; type Side = { team: string; seats: SeatFixture[] }; @@ -45,8 +45,6 @@ stripIntentOverrides(); const fixture = loadFixture(import.meta.url); const allSeats = [...fixture.withLayer.seats, ...fixture.withoutLayer.seats]; -const kinds: HireOptions["workerFlows"] = { [TRIAGE_KIND]: triageFlow as never }; - const tree = (name: string): string => join(fixtureDir(import.meta.url), name); function host(stores: StoreRegistry, flows: FlowInstance[]) { @@ -57,8 +55,24 @@ function host(stores: StoreRegistry, flows: FlowInstance[]) { type Router = ReturnType; -async function act(router: Router, address: string, sessionId: string): Promise { - const path = [address, sessionId, "actions", "run"]; +/** Open `sessionId` on the one copy, naming `worker`, as the session route does for a person. */ +async function open(router: Router, worker: string, sessionId: string): Promise { + const path = [TRIAGE_KIND, "sessions"]; + const res = await router.POST( + new Request(`http://goal/api/flows/${path.join("/")}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ userId: fixture.userId, sessionId, state: { workerId: worker } }) + }), + { params: { path } } + ); + return res.status; +} + +async function act(router: Router, worker: string, sessionId: string): Promise { + const opened = await open(router, worker, sessionId); + if (opened !== 201) return new Response(`the session naming "${worker}" was not created (${opened})`, { status: opened }); + const path = [TRIAGE_KIND, sessionId, "actions", "run"]; return router.POST( new Request(`http://goal/api/flows/${path.join("/")}`, { method: "POST", @@ -137,12 +151,12 @@ await runGoal(async () => { ); } - const seats = hireWorkforce(workers, { workerFlows: kinds }); - if (seats.length !== allSeats.length) { - failures.push(`hired ${seats.length} seat(s), wanted ${allSeats.length}`); + const { copies: seats } = installWorkers(workers, (installation) => ({ [TRIAGE_KIND]: defineTriageFlow(installation) })); + if (seats.filter((copy) => copy.kind === TRIAGE_KIND).length !== 1) { + failures.push(`registered ${seats.filter((copy) => copy.kind === TRIAGE_KIND).length} copies of "${TRIAGE_KIND}", wanted one`); } evidence.push( - "the real loader read a tree of two teams — one with a TEAM.md, one without — and one hireWorkforce call turned all three records into seats of a kind with no model in it" + "the real loader read a tree of two teams — one with a TEAM.md, one without — and one copy of a flow with no model in it runs all three workers" ); // ---- (b) each seat RUNS, and its nested block reads both layers ---------- @@ -157,7 +171,7 @@ await runGoal(async () => { // no request to wait on, so polling anyway would report a second, // invented failure beside the real one. if (res.status !== 202) { - failures.push(`${seat.id}: expected 202 from its own address, got ${res.status}`); + failures.push(`${seat.id}: expected 202 from "${TRIAGE_KIND}", got ${res.status}: ${await res.clone().text()}`); continue; } const requestId = body.request?.id; @@ -208,7 +222,7 @@ await runGoal(async () => { if (ran.runs !== 1) failures.push(`${seat.id}: ran ${String(ran.runs)} times`); } evidence.push( - "after closing the store and rebuilding the host, both seats on the team with a TEAM.md show their team's instructions AND their own, as two separate values read off ctx.flow.config inside a nested block" + "after closing the store and rebuilding the host, both seats on the team with a TEAM.md show their team's instructions AND their own, as two separate values read off the turn's worker inside a nested block" ); // ---- (c) the sibling team's seat carries NO layer, and none of theirs -- diff --git a/goals/workforce-conventions/code-comes-from-files-alone/fixtures/workforce/flows/workers/desk-clerk.ts b/goals/workforce-conventions/code-comes-from-files-alone/fixtures/workforce/flows/workers/desk-clerk.ts index 619691becb..b8b52e9bff 100644 --- a/goals/workforce-conventions/code-comes-from-files-alone/fixtures/workforce/flows/workers/desk-clerk.ts +++ b/goals/workforce-conventions/code-comes-from-files-alone/fixtures/workforce/flows/workers/desk-clerk.ts @@ -1,22 +1,27 @@ /** - * The fixture's one custom worker kind: a desk clerk whose `answer` action - * tags a note with the desk the seat's own `WORKER.md` sets. + * The fixture's one custom worker flow: a desk clerk whose `answer` action + * tags a note with the desk the worker's own `WORKER.md` sets. * * Nothing registers it. `fsdev gen` walks this folder and puts it on the * `kinds` map of `workforce.gen.ts` under its basename, `desk-clerk`, the name - * both seats' files give in their `flow:` line. The goal check hires from that - * map and never imports this module. + * both workers' files give in their `flow:` line. The goal check hands that map + * to the installation and never imports this module. * - * Model-free on purpose: the check grades which seat's settings reached the + * A `workerFlow(...)` builder, because the flow is built on the installation + * that runs its workers (its session names the worker, and the flow's + * `request.onStarted` loads it), and a module in its own file has no + * installation to import. + * + * Model-free on purpose: the check grades which worker's settings reached the * answer, and a model would only add a way to fail that has nothing to do * with that. */ import { defineFlow, handler, type BlockContext } from "@flow-state-dev/core"; -import { workerConfigSchema } from "@flow-state-dev/workforce"; +import { workerConfigOf, workerConfigSchema, workerFlow } from "@flow-state-dev/workforce"; import { z } from "zod"; import { workerDoor } from "../../../../../../lib/worker-door.mts"; -/** The seat contract plus this kind's own key, which a `WORKER.md` sets at its top level. */ +/** The worker contract plus this flow's own key, which a `WORKER.md` sets at its top level. */ const settings = workerConfigSchema().extend({ desk: z.string().default("front"), }); @@ -26,14 +31,28 @@ const answer = handler({ inputSchema: z.object({ note: z.string().min(1) }), outputSchema: z.object({ said: z.string() }), execute: (input: { note: string }, ctx: BlockContext) => { - const { desk } = ctx.flow.config as z.infer; + const { desk } = workerConfigOf(ctx) as z.infer; return { said: `[${desk} desk] ${input.note}` }; }, }); -export default defineFlow({ - kind: "desk-clerk", - cardinality: "collection", - configSchema: settings, - actions: { ...workerDoor, answer: { block: answer } }, -} as never); +export default workerFlow((installation) => + defineFlow({ + kind: "desk-clerk", + cardinality: "collection", + configSchema: settings, + session: installation.session(), + resources: { ...installation.resources }, + request: { + onStarted: handler({ + name: "desk-clerk-load-worker", + inputSchema: z.unknown(), + resources: { ...installation.resources }, + execute: async (_input: unknown, ctx: BlockContext) => ({ + worker: (await installation.resolveWorker(ctx, "desk-clerk")).id, + }), + }), + }, + actions: { ...workerDoor, answer: { block: answer } }, + } as never), +); diff --git a/goals/workforce-conventions/code-comes-from-files-alone/run.mts b/goals/workforce-conventions/code-comes-from-files-alone/run.mts index b30428df6f..fbbbcd3cf4 100644 --- a/goals/workforce-conventions/code-comes-from-files-alone/run.mts +++ b/goals/workforce-conventions/code-comes-from-files-alone/run.mts @@ -57,7 +57,7 @@ import { dirname, join, relative, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { DEFAULT_ORG_ID } from "@flow-state-dev/core"; import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; -import { hireWorkforce, type WorkerManifest } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, hireWorkforce, type WorkerManifest } from "@flow-state-dev/workforce"; import { readWorkforce } from "@flow-state-dev/workforce/loader"; import { KITCHEN_SINK, REPO_ROOT, loadFixture, runGoal } from "../../lib/index.mts"; @@ -377,25 +377,40 @@ await runGoal(async () => { const first = workers[0]!.declared; workers = workers.map((worker) => ({ ...worker, declared: { ...first } })); } - const seats = hireWorkforce(workers, { workerFlows: generated.kinds as never }); + const installation = createWorkerInstallation({ standardWorkers: workers, workerFlows: generated.kinds as never }); + const copies = hireWorkforce(installation); const state = createFlowState({ - flows: Object.fromEntries(seats.map((seat) => [seat.id, seat])), + flows: Object.fromEntries(copies.map((copy) => [copy.id, copy])), stores: { default: { primary: inMemoryStores() } }, } as never); try { const runtime = await state.getRuntime(); + const router = await state.getRouter(); const seen: Record = {}; + const copy = copies.find((c) => c.kind === fixture.host.kind); + if (copy === undefined) fail("d", `no copy of the tree's custom flow "${fixture.host.kind}" was registered (registered: ${copies.map((c) => c.id).join(", ")})`); for (const seatId of fixture.host.seats) { - const seat = seats.find((s) => s.id === seatId); - if (seat === undefined) { - fail("d", `${seatId} was not hired from the fixture tree (hired: ${seats.map((s) => s.id).join(", ")})`); - continue; + if (copy === undefined) break; + const declaredFlow = installation.standardWorker(seatId)?.declared.flow; + if (declaredFlow !== fixture.host.kind) { + fail("d", `${seatId} runs on "${String(declaredFlow)}", not the tree's custom flow "${fixture.host.kind}"`); } - if (seat.kind !== fixture.host.kind) { - fail("d", `${seatId} was hired on "${seat.kind}", not the tree's custom kind "${fixture.host.kind}"`); + // A session on the one copy, created naming the worker. + const sessionPath = [copy.id, "sessions"]; + const created = await router.POST( + new Request(`http://goal/api/flows/${sessionPath.join("/")}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ userId: fixture.host.userId, sessionId: `s_${seatId}`, state: { workerId: seatId } }), + }), + { params: { path: sessionPath } }, + ); + if (created.status !== 201) { + fail("d", `${seatId}: its session was not created (${created.status}): ${await created.text()}`); + continue; } const ran = (await runAction({ - flow: seat, + flow: copy, actionName: "answer", input: { note: fixture.host.note }, userId: fixture.host.userId, diff --git a/goals/workforce-conventions/durable-hire-survives-redeploy/fixtures/input.json b/goals/workforce-conventions/durable-hire-survives-redeploy/fixtures/input.json deleted file mode 100644 index c944ddfe54..0000000000 --- a/goals/workforce-conventions/durable-hire-survives-redeploy/fixtures/input.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "userId": "goal-durable-hire", - "ask": "[scenario:recall] what were you told before this?", - "replyMarker": "[reply:recall]", - "port": 3991, - "org": "kitchen-sink", - "adminUser": "workforce-admin", - "otherOrg": "elsewhere", - "controlSeat": "support.general", - "goodSeat": "support.bo", - "missingKindSeat": "support.cy", - "tokenSeat": "support.di", - "otherOrgSeat": "support.ev", - "kind": "agent", - "missingKind": "kind-this-app-does-not-carry" -} diff --git a/goals/workforce-conventions/durable-hire-survives-redeploy/goal.md b/goals/workforce-conventions/durable-hire-survives-redeploy/goal.md deleted file mode 100644 index 4d74766912..0000000000 --- a/goals/workforce-conventions/durable-hire-survives-redeploy/goal.md +++ /dev/null @@ -1,21 +0,0 @@ -# workforce-conventions › a hired team survives a redeploy - -**Issue:** FIX-1475; re-pointed by FIX-1611 -**Outcome:** Someone hires a team into a running app over its ordinary HTTP route, redeploys, and the team is still there — the seats answer at the same addresses, carrying the instructions the hire supplied rather than any default. Hiring writes the seat down; the next start reads it back. A stored seat the current code can no longer run costs one seat, not the deployment. -**Input:** `apps/kitchen-sink`, built for Next and served by `next start`, with `STORE_TYPE=filesystem` so one store outlives the process, and `WORKFORCE_ADMIN_TOKENS` configuring an admin credential for `kitchen-sink`, the one organization the app runs as, plus a second token bound to another organization (`elsewhere`) that the app must refuse. A seat the admin credential hires answers at `kitchen-sink.~workforce-admin.` and is reached with that credential. Held out: the instructions of the seat leg 3 grades carry a **token generated at check time** — nothing in the app, the tree or this file can supply it. - -**Re-pointed (FIX-1611).** Until FIX-1611 every seat here was a `desk-clerk`, the control was the file-declared `support.ada`, and the token rode in the clerk's `desk` setting, which the kind wrote into its answer. That kind is gone; the app carries only the built-in `agent`. Every hire is now an `agent` seat with the token in its **instructions**, the control is the file-declared `support.general`, and every seat is asked `[scenario:recall]` over its `run` action: the scripted model answers `[reply:recall]` followed by every token it was handed before the question, and a seat's instructions are among what it was handed. So a token in the answer is a token in the instructions the seat came back with. The good seat of leg 1 carries a second check-time token in the same place. -**Signal:** Six legs on one run. (0) the file-declared `support.general` answers the recall question, asserted first and re-asserted after every restart. (1) a hire over `workforce-admin` answers straight away in the hiring process; a hire naming a kind the app does not carry is refused and leaves no address; a hire carrying the other organization's token is refused with 401 and leaves no address. (2–3) a seat hired with a check-time token answers **after a restart** and its answer carries **that token**. (4) a stored row edited to name a kind the code does not carry leaves the app serving, the other seats answering, that one address 404ing, the boot naming the skip, and the bad row unrepaired. (5) firing the token seat and restarting leaves a 404 that no start brings back. PASS prints the token seat's answer, the degrade evidence and the fire evidence; any mismatch is a FAIL. -**Anti-game:** A hollow pass would assert that the seat answered 200 after a restart — which an app that re-read the same `WORKER.md` files, or hired every seat onto one shared default, passes without storing anything. So leg 3 grades a value **only the stored row can carry**: a token minted by this run, sent in the hire's instructions, and read back out of the answer. A seat coming back on a file-declared default or a kind's own default cannot produce it. The store directory is **removed before the run**, so a roster an earlier run left behind cannot be what passes. The file-declared control in leg 0 is the inverse probe: it is asserted before everything and re-asserted after every restart, so a zero on a durability leg is distinguishable from an app that simply is not serving. Leg 4 edits a row **the app itself wrote** rather than fabricating one, because a fabricated row tests the parser while the real failure is a kind deleted from the source after the row was written. Running against the **Next-built** app rather than the source tree is what makes it a check of the decision: a roster read lazily on first request, or held in module memory, behaves differently across a real process boundary. -**Model:** scripted; the goal grades the tokens the recall answer names, not the model. The server runs with `KITCHEN_SINK_TEST_MODE=1` (kitchen-sink's scripted model, keyless). The recall scenario names only tokens that reached the model before the question, so the check-time token in the answer came from the seat's stored instructions; nothing else in the answer is graded. -**Run:** `pnpm tsx goals/workforce-conventions/durable-hire-survives-redeploy/run.mts` - -## Verdict log -| Date | Commit | Model | Verdict | Notes | -|------|--------|-------|---------|-------| -| 2026-09-27 | FIX-1611 branch on 315976e5f, uncommitted | scripted | **PASS** | **Re-pointed** at the `agent` kind: every hire carries its check-time token in `instructions`, every seat is asked `[scenario:recall]` over `run`, and the control is the file-declared `support.general`. All six legs green on one run of the Next-built app: `kitchen-sink.~workforce-admin.support.di` answered `[reply:recall] hire-token-…` after a restart, carrying the token this run minted; the control answered `[reply:recall] Nothing came before this.` before and after every restart; the degrade and fire legs held. **Its recorded mutations, re-taken on this roster, each reverted after its run:** (1) *the boot reloads nothing* (`orgIds: orgIds.slice(0, 0)` in `fsdev.config.ts`): red with `support.di did not survive the restart — it 404s`, the control green. (3) *instructions dropped* (`body: ""` in `hiredSeatManifest`, the row's instructions no longer reaching the seat; the `settings` mutation it replaces has nothing to drop on this kind): legs 1 and 3 red, `support.bo` and `support.di` answering `Nothing came before this.` in place of their tokens. (4) *another org's token accepted* (the org refusal in `workforce-admin-auth.ts` disabled): leg 1 red, `returned 200 rather than 401`. (2) *the row never written* (the private-roster `create` in `workforce-admin/flow.ts` skipped): leg 1 red, `expected exactly one stored roster row for "support.bo" … found 0`. | -| 2026-09-26 | b3a8f1b3c + FIX-1598 | none | **PASS** | **Re-keyed to the single-org kitchen-sink (FIX-1598).** On `main` at `b3a8f1b3c` the check was red: the app refused both `acme` and `bravo` admin tokens (`refusing a WORKFORCE_ADMIN_TOKENS entry that names organization "acme"`), so `workforce-admin` was never registered and every hire answered `404 Unknown flow "workforce-admin"`; the run then threw at leg 4 (`expected exactly one stored roster row for "support.bo" … found 0`). The fixture now binds the admin token to `kitchen-sink`, keeps a second token bound to `elsewhere` as the org that must be refused, and addresses hired seats at `kitchen-sink.~workforce-admin.` with the admin credential on every seat call. Legs and grading are unchanged apart from one added assertion in leg 1: the `elsewhere` token's hire answers 401 and leaves no address. Green on one run: `kitchen-sink.~workforce-admin.support.di` answered `[desk- desk] is the printer fixed?` after a restart, the degrade and fire legs held, and the control answered throughout. **No named `GOAL_CONTROL`; falsified by mutation, each reverted and re-run green.** (1) *The boot reloads nothing*, now spelled `orgIds: orgIds.slice(0, 0)` in `fsdev.config.ts`: leg 3 red with `did not survive the restart — it 404s`, the control silent. The earlier spelling, `reload.seats` sliced to empty, **no longer bites**: admission now reads the per-organization slices, so that mutation passes green. (2) *The row is never written*, the admin hire's `privateRosterOf(ctx).create(…)` removed: red, reported as leg 4's setup throw, the wording limit the first row records. (3) *Settings dropped*, `...row.settings` removed from `hiredSeatManifest`: legs 1 and 3 red with `[front desk] …` in place of the token. (4) *Another org's token accepted*, the org refusal in `workforce-admin-auth.ts` removed: leg 1 red with `returned 200 rather than 401`. | -| 2026-09-21 | 3e24c1f9d | none | **PASS** | **First verdict, on the real path: `next start` against the Next-built app, all six legs green on one run.** Build: `pnpm packages:build` then `pnpm --filter @flow-state-dev/kitchen-sink build`, both clean. **Control:** the file-declared `support.ada` answered `[front desk] …` before anything else and again after every restart, so every zero below means something. **Durability:** `acme.support.di` was hired with `desk` set to a token minted by this run, the process was stopped and restarted from the same build, and it answered `[desk-bf298a88-0760-4051-9995-b3a7af8f7afc desk] is the printer fixed?` — carrying that token, which no `WORKER.md` and no kind default can produce. **Admission:** a hire naming a kind the app does not carry was refused and left no address. **Org fence:** a hire whose *body* named `bravo` under `acme`'s credential wrote its row under **acme**, and no `bravo` org record was ever created. **Degrade:** a stored row edited to name a missing kind left the app serving, `acme.support.bo` 404ing, the boot naming the skip, and the row **unrepaired** on disk. **Fire:** firing `acme.support.di` and restarting left a 404 with the row gone from storage. **Falsifiability — all three of `PLAN.md`'s red states produced on this branch, each observed and reverted, with the check re-run green after every revert.** (1) *The boot reload registers nothing* — the reload loop in `fsdev.config.ts` sliced to empty: leg 3 red with `acme.support.di did not survive the restart — it 404s, so the hire was never written down`, and the control silent, so the zero is durability and not a dead app. `PLAN.md` spells this sabotage `for (const seat of [])`, which **does not compile** — TypeScript narrows `[]` to `never[]` and the build dies on `seat.id` before the check ever runs, so it was re-aimed to `reload.seats.slice(0, 0)`, which registers nothing and still typechecks. (2) *The hire is never written down* — the `rosterOf(ctx).create(…)` row write removed from the admin flow's hire, registering in process only: leg 1 still green (the seat answers straight away in the hiring process) and leg 3 red with the same 404 text. That pair **is** the *hired* / *written down* split the issue exists for. (3) *The seat comes back on a default* — `hiredSeatManifest`'s `...row.settings` dropped so `desk` falls to its schema default: leg 3 red with `answered after the restart but said "[front desk] …", which does not carry the token this check generated … so it came back on a default rather than on the settings the hire supplied`. Leg 1 went red too, which `PLAN.md` did not predict: the same mapping mints the in-process seat, so the check catches this defect one leg earlier than the plan claimed. **A property of the check, found only by producing these:** `runGoal` reports a *thrown* error as the sole failure and discards the legs already graded, so red state (2) printed leg 4's setup throw (`expected exactly one stored roster row for "support.bo" … found 0`) instead of leg 3's reason; leg 3's own text was recovered by stopping the runner after leg 3. The check goes red either way — only its wording misleads. Recorded, not fixed. | -| 2026-09-26 | 081f6fe83 (main) and FIX-1589 branch | none | FAIL (pre-existing) | **Red identically on `main` and on this branch, so not this branch's.** Leg 0 (the control, `support.ada` answering `[front desk] …`) is green on both, on the scripted model now that the server runs under `KITCHEN_SINK_TEST_MODE=1`. The run then throws at leg 4's setup, `expected exactly one stored roster row for "support.bo" … found 0`: kitchen-sink is single-org now, the `acme`/`bravo` admin tokens this check hires with are refused, and `workforce-admin` answers `Unknown flow`. As the first row records, `runGoal` reports that throw and discards the legs graded before it. Needs its own issue: the check has to hire through the app's one org. | -| 2026-09-21 | — | — | *superseded* | **An earlier `NOT RUN` on this contract was wrong, and the way it was wrong is worth keeping.** It read: *`pnpm build` fails at `packages/patterns/src/debate/index.ts:314`, verified pre-existing on pristine `origin/main`.* Both halves were true and the conclusion did not follow. Reproducing a failure on `main` establishes only that this branch did not cause it — **not** that the build is broken. `apps/kitchen-sink`'s `build` script is `fsdev gen && next build` and does not build packages, so in a worktree with no `dist/` it typechecks `packages/**` **source** instead of emitted `.d.ts`; that is why the error landed on a source line in a package this app only consumes. CI (`.github/workflows/ci.yml`) runs `pnpm packages:build` first, which is why it stayed green throughout. The check was aimed at a *neighbour* of the claim — BP-003's first shape — and the fix was one command. | -| — | — | — | **FINDING** | **`GET /api/flows` is unauthenticated and now enumerates every organization's hired seats by address.** Executed on this branch, not read: with two seats registered at `acme.support.ada` and `bravo.support.ada`, a `GET /api/flows` carrying **no credential at all** returned `200` and listed both by full id, alongside each one's `kind`, `cardinality`, `requireUser`, `requiresOrg`, action names and full action input schemas. The route is classified `{ kind: "exempt" }` in `routes/route-auth.ts` and answered from `registry.list()` in `routes/http-handlers.ts`. Not leaked: a seat's `settings`, its `instructions`, sessions, or team membership — the `config` bag is not projected. Nothing in the listing marks a row as org-owned either: `requiresOrg` is derived from what a flow's *blocks* declare, and read `false` for an org-owned instance in this run, so it cannot be used to post-filter. The endpoint was harmless while it listed demo flow *shapes*; a durable hire is what turns it into an inventory of customers. **Owned by FIX-1486, consumed and not owned here (ER-17)** — recorded rather than fixed, and disclosed to readers in `apps/docs/docs/workforce/durable-hire.md`. | diff --git a/goals/workforce-conventions/durable-hire-survives-redeploy/run.mts b/goals/workforce-conventions/durable-hire-survives-redeploy/run.mts deleted file mode 100644 index 00afa08901..0000000000 --- a/goals/workforce-conventions/durable-hire-survives-redeploy/run.mts +++ /dev/null @@ -1,560 +0,0 @@ -/** - * Goal check — a team hired while the app runs is still there after a redeploy. - * - * Six legs, over the real HTTP route against the **Next-built** app, restarted - * from the same build between them. The restart is the whole point: a roster - * that only lives in the process that hired it passes every in-process test - * ever written and fails the one thing this issue exists to deliver. - * - * 0 the CONTROL, asserted before anything else. The file-declared - * `support.general` answers, and keeps answering across every restart - * below. - * A failure here means the probe is blind — the app is not serving, or the - * store was wiped — not that durability broke. Without it, a zero on any - * other leg means nothing. - * - * 1 HIRE two seats. One good, one naming a kind the app does not carry. The - * good one answers; the bad one is refused and leaves no address behind. - * A credential bound to another organization is refused outright. - * - * 2 HIRE a third whose instructions carry a token GENERATED AT CHECK TIME, - * then restart. - * - * 3 the DURABILITY leg. The token seat answers after the restart and its - * answer carries THAT token — read from what this check sent, never - * written into the check. A seat answering from a file-declared default, - * or from a kind's own default, has no way to produce it. - * - * Every seat is on the built-in `agent` kind, and every call asks it - * `[scenario:recall]`: the scripted model answers with each token it was - * handed before the question, and its instructions are among what it was - * handed. So a token in the answer is a token in the instructions the seat - * came back with. - * - * 4 the DEGRADE leg. A stored row is edited on disk to name a kind the code - * does not carry — which is what a real one looks like once a kind is - * deleted from the source. After a restart the app SERVES, the other - * seats answer, that one address 404s, and the boot named it. - * - * 5 the FIRE leg. Firing the token seat and restarting leaves a 404, and the - * seat does not come back — so the removal was durable, not in-process. - * - * Persistence is the filesystem store profile (`STORE_TYPE=filesystem`), which - * is what makes "the same store across two processes" true without a database. - * The store directory is removed before the run, so a stale roster from an - * earlier run can never be what passes leg 3. - * - * The app runs as one organization, `kitchen-sink`, and every admin token must - * name it (`apps/kitchen-sink/lib/workforce-admin-auth.ts`). A seat the admin - * credential hires is owned by the admin user, so it answers at - * `kitchen-sink.~workforce-admin.` and resolves its callers with that - * same credential. - * - * Run: pnpm tsx goals/workforce-conventions/durable-hire-survives-redeploy/run.mts - */ -import { spawn, execFileSync, type ChildProcess } from "node:child_process"; -import { existsSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { randomUUID } from "node:crypto"; -import { seatAddress } from "@flow-state-dev/workforce"; -import { KITCHEN_SINK, loadFixture, runGoal } from "../../lib/index.mts"; - -interface Fixture { - userId: string; - /** What every seat is asked: the recall scenario. */ - ask: string; - /** The marker the recall answer carries. */ - replyMarker: string; - port: number; - org: string; - adminUser: string; - otherOrg: string; - controlSeat: string; - goodSeat: string; - missingKindSeat: string; - tokenSeat: string; - otherOrgSeat: string; - kind: string; - missingKind: string; -} - -const fixture = loadFixture(import.meta.url); -const ORIGIN = `http://127.0.0.1:${fixture.port}`; -const DATA_DIR = join(KITCHEN_SINK, ".fsdev", "data"); - -/** The admin credential for the one organization this app runs as. */ -const TOKEN = `tok-${randomUUID()}`; -/** - * A token whose entry names another organization. The app refuses it when the - * credentials are read, so "which org" still has a wrong answer to give: a hire - * carrying it must be turned away and write nothing. - */ -const OTHER_ORG_TOKEN = `tok-${randomUUID()}`; -const ADMIN_TOKENS = `${fixture.org}:${TOKEN},${fixture.otherOrg}:${OTHER_ORG_TOKEN}`; - -const SERVER_ENV = { - ...process.env, - PORT: String(fixture.port), - FSD_ENV: "dev", - STORE_TYPE: "filesystem", - WORKFORCE_ADMIN_TOKENS: ADMIN_TOKENS, - // A seat's answer calls a model: the scripted one, keyless. The goal grades - // the tokens the recall scenario names, which only the seat's instructions - // can hold, not the model's words. - KITCHEN_SINK_TEST_MODE: "1", -}; - -/** - * A runtime-hired seat's address. Only these carry the organization, and the - * admin user who owns them. - * - * A FILE-declared seat does not: `hireKitchenSinkWorkforce` mints it under the - * id its folders spell (`support.general`), with no org segment, because a file is - * not hired into an organization. The control below therefore addresses the - * bare id — using this helper for it is what made the first run of this check - * report a blind probe, which is the control working rather than failing. - */ -const address = (seat: string, org = fixture.org): string => seatAddress(org, seat, fixture.adminUser); - -// --------------------------------------------------------------------------- -// The server, and the two predicates that must not be shared -// --------------------------------------------------------------------------- - -/** - * The flow index's status, or `undefined` when nothing answered. - * - * Refusing to start wants ANY answer: something holding the port is a reason to - * stop. Readiness wants a 200 specifically — a process answering 4xx/5xx is - * listening but not serving, and grading it is how a run passes against a - * server it did not build. - */ -async function flowIndexStatus(): Promise { - try { - return (await fetch(`${ORIGIN}/api/flows`)).status; - } catch { - return undefined; - } -} - -let server: ChildProcess | undefined; -/** Everything the running server has written to stderr since it started. */ -let serverLog = ""; - -async function startServer(): Promise { - if ((await flowIndexStatus()) !== undefined) { - throw new Error( - `something is already answering on ${ORIGIN}; stop it first, or this check would grade it ` + - `instead of the build it just made` - ); - } - serverLog = ""; - // Detached, so the kill below reaches the whole group: `pnpm start` execs - // `next start` as a child, and signalling only the shim leaves the server up - // for the next leg to grade. - server = spawn("pnpm", ["start"], { - cwd: KITCHEN_SINK, - env: SERVER_ENV, - stdio: ["ignore", "pipe", "pipe"], - detached: true, - }); - server.stdout?.on("data", (chunk: Buffer) => { serverLog += chunk.toString(); }); - server.stderr?.on("data", (chunk: Buffer) => { serverLog += chunk.toString(); }); - - let last: number | undefined; - for (let i = 0; i < 180; i += 1) { - last = await flowIndexStatus(); - if (last === 200) return; - if (server.exitCode !== null) { - throw new Error( - `the app exited with code ${server.exitCode} before it served ${ORIGIN}/api/flows:\n${serverLog}` - ); - } - await new Promise((resolve) => setTimeout(resolve, 500)); - } - throw new Error( - `the built app never served ${ORIGIN}/api/flows — ` + - (last === undefined ? "nothing answered" : `the last answer was ${last}`) + - `\n${serverLog}` - ); -} - -async function stopServer(): Promise { - const log = serverLog; - if (server?.pid !== undefined) { - try { - process.kill(-server.pid, "SIGTERM"); - } catch { - // already gone - } - } - server = undefined; - // Wait for the port to actually free, or the next start refuses on its own - // guard and the failure reads as "something else is listening". - for (let i = 0; i < 60; i += 1) { - if ((await flowIndexStatus()) === undefined) return log; - await new Promise((resolve) => setTimeout(resolve, 500)); - } - throw new Error(`the app kept answering on ${ORIGIN} after SIGTERM`); -} - -async function restart(): Promise { - const log = await stopServer(); - await startServer(); - return log; -} - -// --------------------------------------------------------------------------- -// The app's surfaces -// --------------------------------------------------------------------------- - -function seatHeaders(): Record { - return { "content-type": "application/json", authorization: `Bearer ${TOKEN}` }; -} - -interface AdminResult { - status: number; - body: string; -} - -async function admin(action: "hire" | "fire", input: unknown, token = TOKEN): Promise { - const res = await fetch(`${ORIGIN}/api/flows/workforce-admin/actions/${action}`, { - method: "POST", - headers: { - "content-type": "application/json", - accept: "text/event-stream", - authorization: `Bearer ${token}`, - }, - body: JSON.stringify({ userId: fixture.userId, input }), - }); - return { status: res.status, body: await res.text() }; -} - -/** - * Ask a seat the recall question through its `run` action and return the text - * it put on the wire, or `undefined` when the address does not resolve. - * - * Read off the inline SSE stream an `Accept: text/event-stream` POST returns — - * the same stream a browser client reads, so nothing here is a back channel. - * - * Every seat call carries the admin credential. A seat the admin hired resolves - * its callers with it, and refuses anyone else; the file-declared control - * resolves through the app's host resolver, which reads nothing on the request. - */ -async function answerOf(seatAddress: string): Promise { - const created = await fetch(`${ORIGIN}/api/flows/${seatAddress}/sessions`, { - method: "POST", - headers: seatHeaders(), - body: JSON.stringify({ userId: fixture.userId, orgId: fixture.org }), - }); - if (created.status === 404) return undefined; - if (!created.ok) throw new Error(`${seatAddress}: creating a session returned ${created.status}`); - const sessionId = ((await created.json()) as { session: { id: string } }).session.id; - - const res = await fetch(`${ORIGIN}/api/flows/${seatAddress}/${sessionId}/actions/run`, { - method: "POST", - headers: { ...seatHeaders(), accept: "text/event-stream" }, - body: JSON.stringify({ userId: fixture.userId, orgId: fixture.org, input: { message: fixture.ask } }), - }); - if (res.status === 404) return undefined; - if (!res.ok) throw new Error(`${seatAddress}: its run action returned ${res.status}`); - - let said = ""; - for (const line of (await res.text()).split("\n")) { - if (!line.startsWith("data: ")) continue; - const event = JSON.parse(line.slice(6)) as { - type: string; - item?: { type: string; content?: { text?: string }[] }; - }; - if (event.type !== "item.done" || event.item?.type !== "message") continue; - said = event.item.content?.map((part) => part.text ?? "").join("") ?? ""; - } - return said; -} - -/** Whether an address resolves at all — a 404 on session create is the miss. */ -async function resolves(seatAddress: string): Promise { - const created = await fetch(`${ORIGIN}/api/flows/${seatAddress}/sessions`, { - method: "POST", - headers: seatHeaders(), - body: JSON.stringify({ userId: fixture.userId, orgId: fixture.org }), - }); - return created.status !== 404; -} - -// --------------------------------------------------------------------------- -// The store, reached directly — leg 4 needs a row no API would write -// --------------------------------------------------------------------------- - -function walk(dir: string, out: string[] = []): string[] { - if (!existsSync(dir)) return out; - for (const name of readdirSync(dir)) { - const path = join(dir, name); - if (statSync(path).isDirectory()) walk(path, out); - else out.push(path); - } - return out; -} - -/** - * The on-disk leaf holding one seat's roster row. - * - * Found by walking and then reading each candidate's `seatId`, rather than by - * rebuilding the store's path scheme. Two reasons, and the second was found by - * this check failing rather than reasoned out in advance: the scheme is the - * store's business, and it **percent-encodes the dot** — `support.bo` is filed - * as `support%2Ebo.json`, so matching the seat id against the path finds - * nothing while the row is sitting right there. - */ -function rosterFileFor(seatId: string): string { - const matches = walk(DATA_DIR) - .filter((path) => path.includes(join("workforce", "roster")) && path.endsWith(".json")) - .filter((path) => { - try { - const raw = JSON.parse(readFileSync(path, "utf8")) as unknown; - return Array.isArray(raw) && (raw[3] as { seatId?: string } | undefined)?.seatId === seatId; - } catch { - return false; - } - }); - if (matches.length !== 1) { - throw new Error( - `expected exactly one stored roster row for "${seatId}" under ${DATA_DIR}, found ${matches.length}` + - (matches.length > 0 ? `:\n ${matches.join("\n ")}` : "") - ); - } - return matches[0]!; -} - -/** - * Rewrite a stored row's `flow` to a kind the code does not carry. - * - * This is what a real bad row looks like: it was written by a past runtime - * against code that has since moved. Fabricating a row from nothing would test - * the parser; editing one the app itself wrote tests the thing that actually - * happens. - */ -function breakStoredKind(seatId: string): void { - const path = rosterFileFor(seatId); - const raw = JSON.parse(readFileSync(path, "utf8")) as unknown; - if (!Array.isArray(raw)) { - throw new Error(`the stored row at ${path} is not this store's envelope: ${typeof raw}`); - } - const state = raw[3] as Record; - state.flow = fixture.missingKind; - writeFileSync(path, JSON.stringify(raw)); -} - -// --------------------------------------------------------------------------- - -await runGoal(async () => { - const failures: string[] = []; - const evidence: string[] = []; - // Both shaped as the tokens the recall scenario names (`-token-`). - const token = `hire-token-${randomUUID().replace(/-/g, "")}`; - const goodToken = `good-token-${randomUUID().replace(/-/g, "")}`; - - // A run must never inherit a roster. Otherwise leg 3 could pass against a - // seat an earlier run hired, which is the one false green that would look - // exactly like success. - rmSync(DATA_DIR, { recursive: true, force: true }); - - // Built here rather than assumed, so the check cannot grade a `.next` a - // previous branch left behind. - execFileSync("pnpm", ["build"], { cwd: KITCHEN_SINK, stdio: "inherit" }); - - try { - await startServer(); - - // ---- (0) the control, before anything else ----------------------------- - const controlFirst = await answerOf(fixture.controlSeat); - if (controlFirst === undefined || !controlFirst.includes(fixture.replyMarker)) { - // Nothing below can mean anything if the app is not serving its - // file-declared team, so this is reported on its own. - return { - failures: [ - `the probe is blind: the file-declared ${fixture.controlSeat} answered ` + - `${JSON.stringify(controlFirst)} rather than a ${fixture.replyMarker} answer, so a ` + - `failure on any durability leg below would not mean durability broke`, - ], - evidence: "", - }; - } - - // ---- (1) hire two seats, one of which names a kind that is not here ----- - const good = await admin("hire", { - seatId: fixture.goodSeat, - flow: fixture.kind, - instructions: `You take refund questions. Your case tag is ${goodToken}.`, - }); - if (good.status !== 200) { - failures.push(`hiring ${fixture.goodSeat} returned ${good.status}: ${good.body.slice(0, 400)}`); - } - const goodAnswer = await answerOf(address(fixture.goodSeat)); - if (goodAnswer === undefined || !goodAnswer.includes(goodToken)) { - failures.push( - `${address(fixture.goodSeat)} was hired but answered ${JSON.stringify(goodAnswer)} — it should ` + - `carry the instructions the hire supplied (${goodToken}), straight away, in this process` - ); - } - - const refused = await admin("hire", { - seatId: fixture.missingKindSeat, - flow: fixture.missingKind, - }); - if (refused.status === 200 && !refused.body.includes("error")) { - failures.push( - `hiring ${fixture.missingKindSeat} into "${fixture.missingKind}" was accepted; a kind this app ` + - `does not carry must be refused before anything is written` - ); - } - if (await resolves(address(fixture.missingKindSeat))) { - failures.push(`${address(fixture.missingKindSeat)} resolves, but its hire was refused`); - } - - // A credential bound to another organization administers nothing here. - const elsewhere = await admin( - "hire", - { seatId: fixture.otherOrgSeat, flow: fixture.kind, instructions: "You answer for elsewhere." }, - OTHER_ORG_TOKEN - ); - if (elsewhere.status !== 401) { - failures.push( - `a hire carrying a token bound to "${fixture.otherOrg}" returned ${elsewhere.status} rather than 401 — ` + - `this app runs as "${fixture.org}" only: ${elsewhere.body.slice(0, 400)}` - ); - } - if ((await resolves(address(fixture.otherOrgSeat))) || (await resolves(address(fixture.otherOrgSeat, fixture.otherOrg)))) { - failures.push(`${fixture.otherOrgSeat} resolves, but its hire carried a refused credential`); - } - - // ---- (2) hire a seat carrying a token minted right now ------------------ - const tokenHire = await admin("hire", { - seatId: fixture.tokenSeat, - flow: fixture.kind, - instructions: `You work a queue the check named: ${token}.`, - }); - if (tokenHire.status !== 200) { - failures.push(`hiring ${fixture.tokenSeat} returned ${tokenHire.status}: ${tokenHire.body.slice(0, 400)}`); - } - - // The body says another organization. The credential says this one. The - // credential is what must decide — otherwise "the org comes from the - // principal" is a sentence with no mechanism behind it. - await admin("hire", { - orgId: fixture.otherOrg, - seatId: "support.spoof", - flow: fixture.kind, - instructions: "You were hired with a spoofed organization.", - }); - if (await resolves(address("support.spoof", fixture.otherOrg))) { - failures.push( - `a hire whose BODY named "${fixture.otherOrg}" landed there; under "${fixture.org}"'s credential it ` + - `must land in "${fixture.org}" and leave the other organization untouched` - ); - } - if (!(await resolves(address("support.spoof")))) { - failures.push( - `a hire whose body named "${fixture.otherOrg}" did not land in "${fixture.org}" either — the ` + - `credential's organization is what the row should have been written under` - ); - } - - // ---- (3) the durability leg -------------------------------------------- - await restart(); - - const controlAfter = await answerOf(fixture.controlSeat); - if (controlAfter === undefined || !controlAfter.includes(fixture.replyMarker)) { - failures.push( - `after the restart the file-declared ${fixture.controlSeat} answered ${JSON.stringify(controlAfter)} — ` + - `the control failed, so the durability result below is not interpretable` - ); - } - - const tokenAfter = await answerOf(address(fixture.tokenSeat)); - if (tokenAfter === undefined) { - failures.push( - `${address(fixture.tokenSeat)} did not survive the restart — it 404s, so the hire was never written down` - ); - } else if (!tokenAfter.includes(token)) { - failures.push( - `${address(fixture.tokenSeat)} answered after the restart but said ${JSON.stringify(tokenAfter)}, ` + - `which does not carry the token this check generated (${token}) — so it came back on a default ` + - `rather than on the instructions the hire supplied` - ); - } - evidence.push( - `across a restart of the Next-built app: ${address(fixture.tokenSeat)} said ` + - `${JSON.stringify(tokenAfter)} carrying the check-time token, control ${fixture.controlSeat} still ` + - `answering (${JSON.stringify(controlAfter)})` - ); - - // ---- (4) the degrade leg ------------------------------------------------ - breakStoredKind(fixture.goodSeat); - await restart(); - - if (!(await resolves(fixture.controlSeat))) { - failures.push( - `after a row naming a missing kind was stored, the app stopped serving the file-declared team — ` + - `one unusable row must not take the deployment down` - ); - } - const tokenStillThere = await answerOf(address(fixture.tokenSeat)); - if (tokenStillThere === undefined || !tokenStillThere.includes(token)) { - failures.push( - `the other hired seat stopped answering once one row went bad — a skip must cost one seat, not the roster` - ); - } - if (await resolves(address(fixture.goodSeat))) { - failures.push( - `${address(fixture.goodSeat)} still resolves although its stored row names "${fixture.missingKind}", ` + - `which this app does not carry` - ); - } - if (!serverLog.includes(fixture.goodSeat) || !serverLog.includes("skipped")) { - failures.push( - `the boot did not name the seat it skipped. A count and a list are owed wherever the roster is ` + - `shown; the log is what this check can observe across a process boundary. Server output:\n${serverLog.slice(-1500)}` - ); - } - // The bad row is left exactly as it was — a boot never repairs data it did - // not understand, because the repair destroys the evidence of why. - const afterBoot = JSON.parse(readFileSync(rosterFileFor(fixture.goodSeat), "utf8")) as unknown[]; - if ((afterBoot[3] as { flow?: string }).flow !== fixture.missingKind) { - failures.push( - `the boot rewrote the row it could not use — it now reads ` + - `${JSON.stringify((afterBoot[3] as { flow?: string }).flow)} rather than the stored ` + - `"${fixture.missingKind}"` - ); - } - evidence.push( - `with one stored row naming a kind the code does not carry: the app served, ` + - `${address(fixture.goodSeat)} 404'd, the boot named it, and the row was left unrepaired` - ); - - // ---- (5) the fire leg --------------------------------------------------- - const fired = await admin("fire", { seatId: fixture.tokenSeat }); - if (fired.status !== 200) { - failures.push(`firing ${fixture.tokenSeat} returned ${fired.status}: ${fired.body.slice(0, 400)}`); - } - if (await resolves(address(fixture.tokenSeat))) { - failures.push(`${address(fixture.tokenSeat)} still resolves in the process that fired it`); - } - - await restart(); - if (await resolves(address(fixture.tokenSeat))) { - failures.push( - `${address(fixture.tokenSeat)} came back after a restart — the fire removed the address but not the row` - ); - } - if (!(await resolves(fixture.controlSeat))) { - failures.push(`the control stopped answering after the fire leg's restart`); - } - evidence.push( - `after firing ${address(fixture.tokenSeat)} and restarting, its address 404s and it is gone from the roster` - ); - } finally { - await stopServer().catch(() => undefined); - } - - return { failures, evidence: evidence.join("; ") }; -}); diff --git a/goals/workforce-mailboxes/a-fresh-host-wakes-its-member-agents/goal.md b/goals/workforce-mailboxes/a-fresh-host-wakes-its-member-agents/goal.md index a3bc993a11..ddf2912ce8 100644 --- a/goals/workforce-mailboxes/a-fresh-host-wakes-its-member-agents/goal.md +++ b/goals/workforce-mailboxes/a-fresh-host-wakes-its-member-agents/goal.md @@ -30,6 +30,8 @@ The **import** and **source** legs have no control: a checkout without the expor ## Verdict log | Date | Commit | Model | Verdict | Notes | |------|--------|-------|---------|-------| +| 2026-10-08 | `865abc573` + FIX-1788 P4 | scripted | FAIL (control) | `no-wake`: **woken** only (desk.amy and desk.oz hold 0 conversations). `no-author-filter`: **seat-post** only (desk.amy's own post heard by both). | +| 2026-10-08 | `865abc573` + FIX-1788 P4 | scripted | PASS | One copy each of `agent` and `note`; the wake runs `wakeMemberSeats(copies, { installation })`. desk.amy and desk.oz each hold one conversation of desk.front, a session on `agent` naming them, each post heard once and answered; desk.amy's own post heard by no worker; desk.ned (on `note`) none. | | 2026-09-26 | FIX-1602 branch on a52bab37a, uncommitted | scripted | FAIL (control) | **`GOAL_CONTROL=no-wake`, taken first.** Failed at **woken** only: `desk.amy holds 0 conversations of desk.front (want 1)`, and the same for `desk.oz`. | | 2026-09-26 | FIX-1602 branch on a52bab37a, uncommitted | scripted | FAIL (control) | `GOAL_CONTROL=no-author-filter`. Failed at **seat-post** only: `desk.amy's own post was heard by desk.amy ("u_fresh_host in desk.front: seat-token-… I looked; it is empty."), desk.oz (…)`. | | 2026-09-26 | FIX-1602 branch on a52bab37a, uncommitted | scripted | FAIL (by hand) | The export removed from the mailbox barrel: failed at **import** (`@flow-state-dev/workforce exports no wakeMemberSeats`). Restored. | diff --git a/goals/workforce-mailboxes/a-fresh-host-wakes-its-member-agents/host.mts b/goals/workforce-mailboxes/a-fresh-host-wakes-its-member-agents/host.mts index 30a4cd5d87..162cc30700 100644 --- a/goals/workforce-mailboxes/a-fresh-host-wakes-its-member-agents/host.mts +++ b/goals/workforce-mailboxes/a-fresh-host-wakes-its-member-agents/host.mts @@ -3,13 +3,15 @@ * * Everything here comes from the published packages and the team's files: no * kitchen-sink code, and no dispatcher or router of the app's own. The wake is - * one call, `wakeMemberSeats(seats)`, in the built-in mailbox kind's notify - * slot. The goal check reads this file's source to hold it to that. + * one call, `wakeMemberSeats(copies, { installation })`, in the built-in + * mailbox kind's notify slot. The goal check reads this file's source to hold + * it to that. * - * The app has one kind of its own, `note`, whose seats take notes when asked - * and declare no `onMailboxPost`, so a post runs nothing on them. Every other - * seat is the built-in `agent` kind, answered by a scripted model so the check - * needs no key. + * The app has one worker flow of its own, `note`, whose workers take notes + * when asked and declare no `onMailboxPost`, so a post runs nothing on them. + * Every other worker runs on the built-in `agent`, answered by a scripted + * model so the check needs no key. Each flow is registered once; a woken + * worker's conversation is a session on its flow, naming it. * * `adaptNotify` is the goal check's seam for its controls, and nothing else: * given the wake this app builds, it returns the block the mailbox runs, or @@ -22,12 +24,14 @@ import { createFlowState, inMemoryStores, type FlowState } from "@flow-state-dev import { createMockModelResolver, mockGenerator } from "@flow-state-dev/testing"; import { mailboxInstances, + createWorkerInstallation, defineMailboxFlow, hireWorkforce, openMailboxes, wakeMemberSeats, workerConfigSchema, - type MailboxManifest + type MailboxManifest, + type WorkerInstallation } from "@flow-state-dev/workforce"; import { readMailboxesDirectory, readWorkforce } from "@flow-state-dev/workforce/loader"; @@ -59,13 +63,16 @@ export const MAILBOX_OWNER = "u_fresh_host"; /** What an agent seat answers with, whatever it heard. */ export const REPLY_MARKER = "[reply:fresh-host]"; -/** This app's own kind: takes a note when asked directly, and hears no posts. */ -const note = defineFlow({ - kind: "note", - cardinality: "collection", - configSchema: workerConfigSchema(), - actions: { ...workerDoor, take: { block: handler({ name: "note-take", execute: () => ({}) }) } } -} as never); +/** This app's own worker flow: takes a note when asked directly, and hears no posts. */ +const defineNote = (installation: WorkerInstallation) => + defineFlow({ + kind: "note", + cardinality: "collection", + configSchema: workerConfigSchema(), + session: installation.session(), + resources: { ...installation.resources }, + actions: { ...workerDoor, take: { block: handler({ name: "note-take", execute: () => ({}) }) } } + } as never); /** The app, booted: its router, what it hired, and a way to shut it down. */ export interface FreshHost { @@ -94,9 +101,13 @@ export async function startFreshHost( throw new Error(`the tree did not load: ${[...errors, ...mailboxErrors].map((e) => e.path).join(", ")}`); } - // Hire first: the wake reaches these seats, never a mailbox's stored members. - const seats = hireWorkforce(workers, { workerFlows: { note: note as never } }); - const wake = wakeMemberSeats(seats); + // The flows first: the wake reaches the workers on these copies, never a + // mailbox's stored members. + let flows: Record = {}; + const installation = createWorkerInstallation({ standardWorkers: workers, workerFlows: () => flows as never }); + flows = { note: defineNote(installation) }; + const seats = hireWorkforce(installation); + const wake = wakeMemberSeats(seats, { installation }); const notify = adaptNotify === undefined ? wake : adaptNotify(wake); const mailboxFlows = mailboxInstances(mailboxes, { kinds: { mailbox: notify === undefined ? defineMailboxFlow() : defineMailboxFlow({ notify }) } diff --git a/goals/workforce-mailboxes/a-fresh-host-wakes-its-member-agents/run.mts b/goals/workforce-mailboxes/a-fresh-host-wakes-its-member-agents/run.mts index ca0deb3f22..874c6be610 100644 --- a/goals/workforce-mailboxes/a-fresh-host-wakes-its-member-agents/run.mts +++ b/goals/workforce-mailboxes/a-fresh-host-wakes-its-member-agents/run.mts @@ -124,7 +124,7 @@ await runGoal(async () => { if (res.status !== 200) throw new Error(`post "${body}" refused: ${res.status} ${res.text.slice(0, 300)}`); }; const conversationsOf = async (seat: string): Promise => { - const listed = await call("GET", ["sessions"], undefined, `?flowId=${encodeURIComponent(seat)}&userId=${MAILBOX_OWNER}&include=dispatch-runs&limit=100`); + const listed = await call("GET", ["sessions"], undefined, `?flowId=agent&state.workerId=${encodeURIComponent(seat)}&userId=${MAILBOX_OWNER}&include=dispatch-runs&limit=100`); const rows = (JSON.parse(listed.text) as { sessions?: Array<{ id: string; parentSessionId?: string | null }> }).sessions ?? []; const out: Conversation[] = []; for (const row of rows) { diff --git a/goals/workforce-mailboxes/a-routed-post-gets-one-answer/goal.md b/goals/workforce-mailboxes/a-routed-post-gets-one-answer/goal.md index 2f1a6ca715..847bd4117a 100644 --- a/goals/workforce-mailboxes/a-routed-post-gets-one-answer/goal.md +++ b/goals/workforce-mailboxes/a-routed-post-gets-one-answer/goal.md @@ -38,6 +38,8 @@ The **import**, **source** and **unrouted** legs have no control; each was redde ## Verdict log | Date | Commit | Model | Verdict | Notes | |------|--------|-------|---------|-------| +| 2026-10-08 | `865abc573` + FIX-1788 P4 | scripted | FAIL (control) | `no-route`: one, lands, followup, held, context, fallback only. `no-landing` (the quiet kind now built on the installation, with a door): one, lands, followup, held, context only. `no-transcript`: followup only. `no-context`: context only. | +| 2026-10-08 | `865abc573` + FIX-1788 P4 | scripted | PASS | Every worker flow registered once; `wakeMemberSeats(copies, { installation })` and `routeByPurpose(copies, { model, installation })`. Each routed post reached one specialist, its conversation a session on `agent` naming it, and one answer landed by it; follow-up, hold, context and fallback as before. | | 2026-09-27 | FIX-1610 branch on 0efb98483, uncommitted | scripted | FAIL (control) | `GOAL_CONTROL=no-route`. Failed at **one**, **lands**, **followup**, **held**, **context**, **fallback** only: `tok-…p1 was heard by [support.devices, support.accounts, support.fsd, support.general] (want [support.devices])`; `tok-…p1 has 0 answer line(s)`; `tok-…p3's route made 0 evaluation call(s)`; `support.general's answer to tok-…p8 does not name item-…: []`. | | 2026-09-27 | FIX-1610 branch on 0efb98483, uncommitted | scripted | FAIL (control) | `GOAL_CONTROL=no-landing`. Failed at **one**, **lands**, **followup**, **held**, **context** only: `tok-…p1 has 0 answer line(s) in support.help: [] (want one, by support.devices)`; `tok-…p2 was heard by [support.devices] (want [support.accounts])` (held for devices, which never answered in the channel). | | 2026-09-27 | FIX-1610 branch on 0efb98483, uncommitted | scripted | FAIL (control) | `GOAL_CONTROL=no-transcript`. Failed at **followup** only: `tok-…p3 was heard by [support.general] (want [support.accounts])`; `tok-…p3's route made 1 evaluation call(s), not seeing a line by support.accounts`. | diff --git a/goals/workforce-mailboxes/a-routed-post-gets-one-answer/host.mts b/goals/workforce-mailboxes/a-routed-post-gets-one-answer/host.mts index 9ed0505c27..7a0e3e9d2f 100644 --- a/goals/workforce-mailboxes/a-routed-post-gets-one-answer/host.mts +++ b/goals/workforce-mailboxes/a-routed-post-gets-one-answer/host.mts @@ -3,8 +3,10 @@ * * Everything here comes from the published packages and the team's files: no * kitchen-sink code, and no dispatcher or router of the app's own. The wake is - * `wakeMemberSeats(seats)` in the built-in mailbox kind's notify slot, and the - * route is `routeByPurpose(seats, { model })`. A mailbox that declares + * `wakeMemberSeats(copies, { installation })` in the built-in mailbox kind's + * notify slot, and the route is `routeByPurpose(copies, { model, installation })`. + * Every worker flow is registered once, and a woken worker's conversation is a + * session on its flow, naming it. A mailbox that declares * `routing:` in its file is routed; one that doesn't wakes every agent member. * The goal check reads this file's source to hold it to that. * @@ -36,12 +38,14 @@ import { } from "@flow-state-dev/testing"; import { mailboxInstances, + createWorkerInstallation, defineMailboxFlow, hireWorkforce, openMailboxes, routeByPurpose, wakeMemberSeats, - type MailboxManifest + type MailboxManifest, + type WorkerInstallation } from "@flow-state-dev/workforce"; import { readMailboxesDirectory, readWorkforce } from "@flow-state-dev/workforce/loader"; @@ -58,8 +62,8 @@ export const ROUTE_MODEL = "vercel/typesafe-ai/jev"; export interface HostSeams { /** The mailbox files as the host reads them, before anything is built. */ adaptMailboxes?: (mailboxes: MailboxManifest[]) => MailboxManifest[]; - /** Kinds the app registers beside the built-ins, by name. */ - kinds?: Record; + /** Worker flows the app registers beside the built-ins, by name, built on the installation. */ + kinds?: (installation: WorkerInstallation) => Record; /** The wake the mailbox's notify slot runs. */ adaptNotify?: (wake: BlockDefinition) => BlockDefinition; /** The route's scripted evaluation model, as the resolver hands it over. */ @@ -139,14 +143,18 @@ export async function startRoutedHost(tree: string, seams: HostSeams = {}): Prom } const mailboxes = seams.adaptMailboxes?.(read.mailboxes) ?? read.mailboxes; - // Hire first: the wake and the route reach these seats, never a mailbox's stored members. - const seats = hireWorkforce(workers, seams.kinds === undefined ? {} : { workerFlows: seams.kinds as never }); - const wake = wakeMemberSeats(seats); + // The flows first: the wake and the route reach the workers on these copies, + // never a mailbox's stored members. + let flows: Record = {}; + const installation = createWorkerInstallation({ standardWorkers: workers, workerFlows: () => flows as never }); + flows = seams.kinds?.(installation) ?? {}; + const seats = hireWorkforce(installation); + const wake = wakeMemberSeats(seats, { installation }); const mailboxFlows = mailboxInstances(mailboxes, { kinds: { mailbox: defineMailboxFlow({ notify: seams.adaptNotify?.(wake) ?? wake, - route: routeByPurpose(seats, { model: ROUTE_MODEL }) + route: routeByPurpose(seats, { model: ROUTE_MODEL, installation }) }) } }); diff --git a/goals/workforce-mailboxes/a-routed-post-gets-one-answer/run.mts b/goals/workforce-mailboxes/a-routed-post-gets-one-answer/run.mts index 159cbe0a2c..d77581f52f 100644 --- a/goals/workforce-mailboxes/a-routed-post-gets-one-answer/run.mts +++ b/goals/workforce-mailboxes/a-routed-post-gets-one-answer/run.mts @@ -45,13 +45,15 @@ import { readFileSync } from "node:fs"; import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; import { z } from "zod"; -import { createModelResolver, defineFlow, generator, type BlockDefinition } from "@flow-state-dev/core"; +import { createModelResolver, defineFlow, generator, handler, type BlockDefinition } from "@flow-state-dev/core"; import type { EvaluationModel, ModelResolver } from "@flow-state-dev/core/types"; import { mailboxNotifyInputSchema, + workerConfigOf, workerConfigSchema, type MailboxManifest, - type MailboxNotifyInput + type MailboxNotifyInput, + type WorkerInstallation } from "@flow-state-dev/workforce"; import { readMailboxesDirectory } from "@flow-state-dev/workforce/loader"; import { gatewayModel, runGoal } from "../../lib/index.mts"; @@ -86,12 +88,12 @@ const heard = (post: MailboxNotifyInput) => `${post.author ?? post.principal} in * the recent lines as context, and posts nothing. A kind of the app's own gets * the routed mark and decides what to do with it; this one does nothing. */ -function quietAgentKind() { +function quietAgentKind(installation: WorkerInstallation) { const answer = generator({ name: "agent-answer", inputSchema: mailboxNotifyInputSchema, model: "scripted/answer", - prompt: (_post: MailboxNotifyInput, ctx) => (ctx.flow.config as { instructions?: string }).instructions ?? "", + prompt: (_post: MailboxNotifyInput, ctx) => (workerConfigOf(ctx) as { instructions?: string }).instructions ?? "", context: [ (post: MailboxNotifyInput) => post.recent === undefined || post.recent.length === 0 @@ -101,11 +103,20 @@ function quietAgentKind() { user: heard }); const run = generator({ name: "agent-answer", inputSchema: z.object({ message: z.string() }), model: "scripted/answer", prompt: "", user: (i: { message: string }) => i.message }); + const loadWorker = handler({ + name: "quiet-agent-load-worker", + inputSchema: z.unknown(), + resources: { ...installation.resources }, + execute: async (_input, ctx) => ({ worker: (await installation.resolveWorker(ctx, "agent")).id }) + }); return defineFlow({ kind: "agent", cardinality: "collection", configSchema: workerConfigSchema(), - actions: { run: { inputSchema: z.object({ message: z.string() }), block: run } }, + session: installation.session(), + resources: { ...installation.resources }, + request: { onStarted: loadWorker }, + actions: { run: { inputSchema: z.object({ message: z.string() }), block: run, userMessage: (i: { message: string }) => i.message } }, internal: { actions: { onMailboxPost: { inputSchema: mailboxNotifyInputSchema, block: answer, userMessage: heard } } } } as never); } @@ -119,7 +130,7 @@ function controlSeams(): HostSeams { mailboxes.map(({ declared: { routing: _routing, ...declared }, ...rest }) => ({ ...rest, declared })) }; case "no-landing": - return { kinds: { agent: quietAgentKind() } }; + return { kinds: (installation: WorkerInstallation) => ({ agent: quietAgentKind(installation) }) }; case "no-transcript": return { adaptEvaluation: (model: EvaluationModel) => @@ -164,7 +175,7 @@ function reader(app: RoutedHost, owner: string) { }, /** A seat's conversations of one mailbox: the kept messages of each. */ conversationsOf: async (seat: string, mailboxId: string): Promise => { - const listed = await call("GET", ["sessions"], undefined, `?flowId=${encodeURIComponent(seat)}&userId=${owner}&include=dispatch-runs&limit=100`); + const listed = await call("GET", ["sessions"], undefined, `?flowId=agent&state.workerId=${encodeURIComponent(seat)}&userId=${owner}&include=dispatch-runs&limit=100`); const rows = (JSON.parse(listed.text) as { sessions?: Array<{ id: string; parentSessionId?: string | null }> }).sessions ?? []; const out: Message[][] = []; for (const row of rows.filter((r) => r.parentSessionId === mailboxId)) { diff --git a/goals/workforce-seats/a-callers-own-agent-wins-every-seat/fixtures/flows.ts b/goals/workforce-seats/a-callers-own-agent-wins-every-seat/fixtures/flows.ts index abc5f92028..52b03b35d8 100644 --- a/goals/workforce-seats/a-callers-own-agent-wins-every-seat/fixtures/flows.ts +++ b/goals/workforce-seats/a-callers-own-agent-wins-every-seat/fixtures/flows.ts @@ -1,94 +1,78 @@ /** - * The caller's own `agent` — the replacement path, in both the shape that - * works and the shape that does not. + * The caller's own `agent`, built on the installation: one copy every worker + * on `agent` runs on, which reads each turn's worker through the installation. * - * Both declare `kind: "agent"`, so both pass the hire step's mismatched-kind - * check and both MINT. Only `collection` survives registration, which is the - * whole reason this goal reaches the registry instead of stopping at the hire. + * `desk` is the tell: the built-in declares no such setting, so a worker whose + * turn reads one ran on the caller's flow. */ import { defineFlow, handler, sequencer } from "@flow-state-dev/core"; -import { workerConfigSchema } from "@flow-state-dev/workforce"; +import { workerConfigSchema, type WorkerInstallation } from "@flow-state-dev/workforce"; import { z } from "zod"; import { workerDoor } from "../../../lib/worker-door.mts"; const inputSchema = z.object({ note: z.string() }); -/** - * The caller's settings bag. `desk` is the tell: the built-in has no such - * setting, so a seat carrying one cannot be ours. - */ +/** The caller's settings bag. */ const callerSettings = workerConfigSchema().extend({ desk: z.string().default("front") }); -const seatState = z.object({ - instructions: z.string().nullable().default(null), - desk: z.string().nullable().default(null), - runs: z.number().default(0) -}); - -const start = handler({ - name: "caller-start", - inputSchema, - outputSchema: inputSchema, - sessionStateSchema: seatState, - execute: async (input, ctx) => { - await ctx.session.patchState({ runs: (ctx.session.state.runs ?? 0) + 1 }); - return input; - } -}); - -/** Writes what THIS seat's own bag carried, so the far end can read it back. */ -const recordSettings = handler({ - name: "caller-record", - inputSchema, - outputSchema: z.void(), - flowConfigSchema: callerSettings, - sessionStateSchema: seatState, - execute: async (_input, ctx) => { - await ctx.session.patchState({ - instructions: ctx.flow.config.instructions ?? null, - desk: ctx.flow.config.desk - }); - } -}); - -const clientView = { - derived: { - ran: (ctx: { state: { instructions?: string | null; desk?: string | null; runs?: number } }) => ({ - instructions: ctx.state.instructions ?? null, - desk: ctx.state.desk ?? null, - runs: ctx.state.runs ?? 0 - }) - } -}; - -const actions = { - run: { +/** The caller's flow, built on `installation`. */ +export function defineCallerAgent(installation: WorkerInstallation) { + const seatState = z.object({ + instructions: z.string().nullable().default(null), + desk: z.string().nullable().default(null), + runs: z.number().default(0) + }); + const start = handler({ + name: "caller-start", inputSchema, - block: sequencer({ name: "caller-agent-work", inputSchema }).step(start).tap(recordSettings) - }, - ...workerDoor -}; - -/** The supported replacement: declared `collection`, as the contract requires. */ -export const callerAgentFlow = defineFlow({ - kind: "agent", - cardinality: "collection", - configSchema: callerSettings, - actions, - session: { stateSchema: seatState, client: clientView } -}); - -/** - * The control. Identical but for the missing `cardinality`, which makes it a - * singleton. Its seats mint exactly like the one above and are refused one by - * one at REGISTRATION — the failure a check that stopped at the hire would - * never see. - */ -export const callerAgentSingleton = defineFlow({ - kind: "agent", - configSchema: callerSettings, - actions, - session: { stateSchema: seatState, client: clientView } -}); + outputSchema: inputSchema, + sessionStateSchema: seatState, + execute: async (input, ctx) => { + await ctx.session.patchState({ runs: (ctx.session.state.runs ?? 0) + 1 }); + return input; + } + }); + /** Writes what THIS turn's worker carries, so the far end can read it back. */ + const recordSettings = handler({ + name: "caller-record", + inputSchema, + outputSchema: z.void(), + sessionStateSchema: seatState, + resources: { ...installation.resources }, + execute: async (_input, ctx) => { + const { config } = await installation.resolveWorker(ctx, "agent"); + await ctx.session.patchState({ + instructions: typeof config.instructions === "string" ? config.instructions : null, + desk: typeof config.desk === "string" ? config.desk : null + }); + } + }); + const session = installation.session(seatState.shape); + return defineFlow({ + kind: "agent", + cardinality: "collection", + configSchema: callerSettings, + resources: { ...installation.resources }, + actions: { + run: { + inputSchema, + block: sequencer({ name: "caller-agent-work", inputSchema }).step(start).tap(recordSettings) + }, + ...workerDoor + }, + session: { + ...session, + client: { + derived: { + ran: (ctx: { state: { instructions?: string | null; desk?: string | null; runs?: number } }) => ({ + instructions: ctx.state.instructions ?? null, + desk: ctx.state.desk ?? null, + runs: ctx.state.runs ?? 0 + }) + } + } + } + }); +} diff --git a/goals/workforce-seats/a-callers-own-agent-wins-every-seat/goal.md b/goals/workforce-seats/a-callers-own-agent-wins-every-seat/goal.md index eb5f6c568b..391196462c 100644 --- a/goals/workforce-seats/a-callers-own-agent-wins-every-seat/goal.md +++ b/goals/workforce-seats/a-callers-own-agent-wins-every-seat/goal.md @@ -1,45 +1,43 @@ # A caller's own `agent` wins every seat -A team that does not want our stock worker registers their own flow under `agent`, and theirs runs -every seat on the roster — including the records that never mention a kind at all. +A team that does not want our stock worker hands the installation their own flow under `agent`, and +theirs runs every worker on the roster — including the records that never mention a flow at all. +Rewritten for FIX-1788: workers are data on one registered copy of their flow. ## The contract -Three worker records, one call, the app's own `agent` passed in `kinds`: +Three worker records, one installation, the app's own `agent` among its worker flows: -(a) **Every** seat resolves to the caller's flow, not just the first. Graded per seat by reading -each seat's own settings bag — `desk` is a setting only the caller's flow declares, and `model` is -one only the built-in declares. Two records leave `flow:` out entirely and one writes `flow: agent`; -both shapes must land on the caller's flow. +(a) One call to `hireWorkforce` registers **one** copy of `agent`, at its kind, and none at any +worker's id. -(b) Those seats **register**, through the real flow registry. +(b) **Every** worker runs on it, as itself. Each one's session is created naming it through the +real HTTP route, and runs to completion there. A block nested inside the action loads the turn's +worker through the installation and records its own record's body as `instructions` and its +`desk`, a setting only the caller's flow declares. Two records leave `flow:` out entirely and one +writes `flow: agent`; both shapes must land on the caller's flow. -(c) One seat runs to completion over the real HTTP route, and its own record's body is read back at -the far end as that seat's `instructions`, from a block nested inside the action. - -(d) **The control run.** The same roster with the replacement declared a *singleton* — no -`cardinality: "collection"` — mints all three seats and is refused at **registration**. This is the -leg that gives the others their meaning: the mint is not the gate, so a check that stopped at the -hire would pass while every seat was still broken. +**Control:** `GOAL_CONTROL=builtin-agent` hands the installation no flow of its own, so `agent` is +the built-in. Must FAIL: the built-in declares no `desk`, so every worker is refused before anything +registers, each named. ## Why it is shaped this way -Counting instances is the trap. Asserting that three seats came back passes even when all three are -ours, so the check reads each seat's identity through its own bag instead. - -Registration is the second trap. A replacement declared the ordinary way is a singleton whose seats -mint perfectly well and are then refused one by one when they are registered, which is why the -contract requires `cardinality: "collection"` and why this check carries a control run that must -fail there. +Counting copies is the trap: one copy comes back whichever flow it is. So the check reads each +worker's identity through what its own turn loaded instead. -No model runs. What is graded is which flow answered and which settings reached it, so the seats run -on handlers. +No model runs. What is graded is which flow answered and which settings reached it, so the workers +run on handlers. **Model:** n/a — handlers only. The property under test is which flow answered and which settings reached it, not model output. +**Run:** `pnpm tsx goals/workforce-seats/a-callers-own-agent-wins-every-seat/run.mts` + ## Runs | Date | Branch | Model | Verdict | Notes | |------|--------|-------|---------|-------| +| 2026-10-08 | `865abc573` + FIX-1788 P4 | n/a | PASS | One `agent` copy, the caller's, for three workers (1 naming the flow, 2 naming none); each ran through the real HTTP route in a session naming it, and its own body and `desk` reached the nested block. | +| 2026-10-08 | `865abc573` + FIX-1788 P4, `GOAL_CONTROL=builtin-agent` | n/a | FAIL (expected) | `hireWorkforce: 3 standard worker problem(s); nothing was registered`, each worker named for `"desk" is not a declared setting`. | | 2026-09-13 | fix/fix-1363 | n/a | PASS | All three seats resolved to the caller's flow (1 naming the kind, 2 naming none), registered, and one ran end to end with its own body arriving as `instructions`. The control run minted three seats and was refused at registration. | | 2026-09-13 | fix/fix-1363 (control: built-in merged *over* the caller's kinds) | n/a | FAIL (expected) | With the precedence inverted, all three records hired into the built-in and were refused at the mint — `Flow "agent" instance "engineering.lead" has an invalid config bag: "desk" is not a declared setting`. Pins that the check is sensitive to the merge order, which is the one line acceptance criterion 4 rests on. | diff --git a/goals/workforce-seats/a-callers-own-agent-wins-every-seat/run.mts b/goals/workforce-seats/a-callers-own-agent-wins-every-seat/run.mts index a741686584..6c31eb94c4 100644 --- a/goals/workforce-seats/a-callers-own-agent-wins-every-seat/run.mts +++ b/goals/workforce-seats/a-callers-own-agent-wins-every-seat/run.mts @@ -1,32 +1,32 @@ /** - * Goal check — a team's own worker replaces ours, for every seat on the roster. + * Goal check — a team's own worker flow replaces ours, for every worker on + * the roster. * - * Three worker records. Two name no kind at all and one names `agent` - * explicitly, so all three would take the built-in. The app registers its own - * flow under `agent`, and every one of them runs on the app's flow instead — - * checked seat by seat, because one-seat-right-and-the-rest-ours is the failure - * a single assertion misses. + * Three worker records. Two name no flow at all and one names `agent` + * explicitly, so all three would run on the built-in. The app hands the + * installation its own flow under `agent`, and every one of them runs on the + * app's flow instead: one registered copy, checked worker by worker, because + * one-worker-right-and-the-rest-ours is the failure a single assertion misses. * - * The seats then REGISTER, through the real flow registry, and one runs to - * completion over the real HTTP route so its own record's instructions can be - * read back at the far end. Registration is the point: the mint is not the - * gate. The control run at the end proves that — the same roster with the - * replacement declared as a singleton mints exactly the same three seats and is - * refused at registration. + * Each worker's session is created naming it, through the real HTTP route, + * and runs to completion there; a block nested inside the action reads the + * turn's worker and records its own record's instructions and `desk`, a + * setting only the caller's flow declares. * * Real path, no mocking, no model. See goal.md for the contract. * * Run: pnpm tsx goals/workforce-seats/a-callers-own-agent-wins-every-seat/run.mts + * Control: GOAL_CONTROL=builtin-agent (the app passes no flow of its own) must FAIL at (b) for every worker. */ import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createFlowApiRouter, createFlowRegistry, type StoreRegistry } from "@flow-state-dev/engine"; import { createSQLiteStores } from "@flow-state-dev/store-sqlite"; -import { AGENT_KIND, hireWorkforce, type WorkerManifest } from "@flow-state-dev/workforce"; +import { AGENT_KIND, type WorkerManifest } from "@flow-state-dev/workforce"; import type { FlowInstance } from "@flow-state-dev/core/types"; -import { loadFixture, runGoal, silentLogger, stripIntentOverrides } from "../../lib/index.mts"; -import { callerAgentFlow, callerAgentSingleton } from "./fixtures/flows"; +import { installWorkers, loadFixture, runGoal, silentLogger, stripIntentOverrides } from "../../lib/index.mts"; +import { defineCallerAgent } from "./fixtures/flows"; type Worker = { id: string; @@ -40,6 +40,9 @@ type Fixture = { userId: string; note: string; roster: Worker[] }; stripIntentOverrides(); +const CONTROL = process.env.GOAL_CONTROL ?? ""; +if (CONTROL !== "" && CONTROL !== "builtin-agent") throw new Error(`unknown GOAL_CONTROL "${CONTROL}"`); + const fixture = loadFixture(import.meta.url); /** @@ -52,7 +55,7 @@ function records(): WorkerManifest[] { declared: { description: worker.description, desk: worker.desk, - // The two shapes that must land on the same kind: an absent key, and the + // The two shapes that must land on the same flow: an absent key, and the // name written out. ...(worker.namesTheKind ? { flow: AGENT_KIND } : {}) }, @@ -60,34 +63,25 @@ function records(): WorkerManifest[] { })); } -function host(stores: StoreRegistry, flows: FlowInstance[]) { +type Router = ReturnType; + +function host(stores: StoreRegistry, flows: FlowInstance[]): Router { const registry = createFlowRegistry(); registry.registerMany(flows); return createFlowApiRouter({ registry, stores, runtimeConfig: { logger: silentLogger } } as never); } -type Router = ReturnType; - -async function act(router: Router, address: string, sessionId: string): Promise { - const path = [address, sessionId, "actions", "run"]; - return router.POST( +async function call(router: Router, method: "GET" | "POST", path: string[], body?: unknown): Promise { + return router[method]( new Request(`http://goal/api/flows/${path.join("/")}`, { - method: "POST", - body: JSON.stringify({ userId: fixture.userId, input: { note: fixture.note } }) + method, + headers: { "content-type": "application/json" }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) }), { params: { path } } ); } -async function ranOn(router: Router, sessionId: string) { - const path = ["sessions", sessionId, "state"]; - const res = await router.GET(new Request(`http://goal/api/flows/${path.join("/")}`), { params: { path } }); - const body = (await res.json()) as { - clientData?: { session?: { ran?: { instructions?: string | null; desk?: string | null; runs?: number } } }; - }; - return { status: res.status, ...(body.clientData?.session?.ran ?? {}) }; -} - async function settled(stores: StoreRegistry, requestId: string): Promise { for (let i = 0; i < 200; i += 1) { const record = await stores.request.get(requestId); @@ -97,124 +91,65 @@ async function settled(stores: StoreRegistry, requestId: string): Promise (error instanceof Error ? error.message : String(error)); - await runGoal(async () => { const failures: string[] = []; const evidence: string[] = []; const dir = mkdtempSync(join(tmpdir(), "fsd-caller-agent-")); - const dbFile = join(dir, "goal.db"); - - const roster = records(); - const seats = hireWorkforce(roster, { workerFlows: { [AGENT_KIND]: callerAgentFlow } }); - // ---- (a) EVERY seat resolved to the caller's flow ---------------------- - { - if (seats.length !== roster.length) { - failures.push(`hired ${seats.length} seat(s) from ${roster.length} record(s)`); - } + // ---- (a) one copy of `agent`, and it is the caller's ---------------------- + const { copies } = installWorkers(records(), (installation) => + CONTROL === "builtin-agent" ? {} : { [AGENT_KIND]: defineCallerAgent(installation) } + ); + const agents = copies.filter((copy) => copy.kind === AGENT_KIND); + if (agents.length !== 1 || agents[0]!.id !== AGENT_KIND) { + failures.push(`(a) ${agents.length} copies of "${AGENT_KIND}" registered (${agents.map((c) => c.id).join(", ")}), wanted one, at its kind`); + } + if (copies.some((copy) => fixture.roster.some((w) => w.id === copy.id))) failures.push("(a) a copy was registered at a worker's id"); + evidence.push(`one call registered ${agents.length} copy of "${AGENT_KIND}" for ${fixture.roster.length} workers`); + // ---- (b) every worker runs on it, as itself ------------------------------- + const stores = createSQLiteStores({ filename: join(dir, "goal.db") }) as unknown as StoreRegistry; + try { + const router = host(stores, copies); for (const worker of fixture.roster) { - const seat = seats.find((s) => s.id === worker.id); - if (seat === undefined) { - failures.push(`${worker.id}: no seat was hired for this record`); + const sessionId = `s_${worker.id.replace(/\W/g, "_")}`; + const created = await call(router, "POST", [AGENT_KIND, "sessions"], { + userId: fixture.userId, + sessionId, + state: { workerId: worker.id } + }); + if (created.status !== 201) { + failures.push(`(b) ${worker.id}: its session was not created: ${created.status} ${await created.text()}`); + continue; + } + const res = await call(router, "POST", [AGENT_KIND, sessionId, "actions", "run"], { + userId: fixture.userId, + input: { note: fixture.note } + }); + if (res.status !== 202) { + failures.push(`(b) ${worker.id}: expected 202 from the "${AGENT_KIND}" copy, got ${res.status}: ${await res.text()}`); continue; } - // Counting instances is the anti-game trap: three seats come back even - // when all three are ours. Read each seat's own bag instead — `desk` is - // a setting only the caller's flow declares, and `model` is one only - // ours does. - const config = seat.config as Record; - if (config.desk !== worker.desk) { - failures.push(`${worker.id}: carries desk ${JSON.stringify(config.desk)}, wanted ${JSON.stringify(worker.desk)} — this seat is not the caller's flow`); + const body = (await res.json()) as { request?: { id: string } }; + const status = await settled(stores, body.request?.id ?? ""); + if (status !== "completed") failures.push(`(b) ${worker.id}: request ended ${String(status)}`); + const state = await call(router, "GET", ["sessions", sessionId, "state"]); + const ran = ((await state.json()) as { + clientData?: { session?: { ran?: { instructions?: string | null; desk?: string | null; runs?: number } } }; + }).clientData?.session?.ran; + if ((ran?.instructions ?? "").trim() !== worker.body.trim()) { + failures.push(`(b) ${worker.id}: its nested block saw instructions ${JSON.stringify(ran?.instructions)}`); } - if (Object.hasOwn(config, "model")) { - failures.push(`${worker.id}: carries a "model" setting, which only the built-in declares — the replacement did not win this seat`); + if (ran?.desk !== worker.desk) { + failures.push(`(b) ${worker.id}: its nested block saw desk ${JSON.stringify(ran?.desk)}, wanted ${JSON.stringify(worker.desk)} — this turn did not run on the caller's flow`); } } - const named = fixture.roster.filter((w) => w.namesTheKind).length; evidence.push( - `all ${seats.length} seats resolved to the caller's own agent — ${named} naming the kind and ${seats.length - named} naming none` + `every worker — ${named} naming the flow and ${fixture.roster.length - named} naming none — ran on the caller's copy through the real HTTP route, its own record's body arriving as \`instructions\` and its \`desk\` with it` ); - } - - // ---- (b) and those seats REGISTER --------------------------------------- - let stores: StoreRegistry = createSQLiteStores({ filename: dbFile }) as unknown as StoreRegistry; - { - let router: Router | undefined; - try { - router = host(stores, seats); - } catch (error) { - failures.push(`registering the caller's seats threw: ${messageOf(error)}`); - } - - if (router !== undefined) { - evidence.push("every seat registered through the real flow registry"); - - // ---- (c) one seat runs, and its OWN record's instructions arrive ---- - const lead = fixture.roster[0]!; - const session = "s_lead"; - const res = await act(router, lead.id, session); - if (res.status !== 202) { - failures.push(`${lead.id}: expected 202 from its own address, got ${res.status}`); - } else { - const body = (await res.json()) as { request?: { id: string } }; - const status = await settled(stores, body.request?.id ?? ""); - if (status !== "completed") failures.push(`${lead.id}: request ended ${String(status)}`); - - const seen = await ranOn(router, session); - if (seen.status !== 200) failures.push(`${lead.id}: /state returned ${seen.status}`); - if ((seen.instructions ?? "").trim() !== lead.body.trim()) { - failures.push(`${lead.id}: its nested block saw instructions ${JSON.stringify(seen.instructions)}`); - } - if (seen.desk !== lead.desk) { - failures.push(`${lead.id}: its nested block saw desk ${String(seen.desk)}`); - } - if (seen.runs !== 1) failures.push(`${lead.id}: ran ${String(seen.runs)} times`); - - evidence.push( - "one seat ran to completion through the real HTTP route, and its own record's body reached a block nested inside the action as `instructions`" - ); - } - } - } - (stores as unknown as { close(): void }).close(); - - // ---- (d) the control: a singleton replacement must FAIL at registration -- - // Without this leg, (b) proves nothing — a check that cannot fail has - // verified nothing, and the mint is demonstrably not the gate. - { - const controlStores = createSQLiteStores({ filename: join(dir, "control.db") }) as unknown as StoreRegistry; - let controlSeats: FlowInstance[] | undefined; - try { - controlSeats = hireWorkforce(roster, { workerFlows: { [AGENT_KIND]: callerAgentSingleton } }); - } catch (error) { - failures.push( - `the control roster was refused at the HIRE (${messageOf(error)}) — it is supposed to mint and fail later, so this leg no longer proves registration is the gate` - ); - } - - if (controlSeats !== undefined) { - if (controlSeats.length !== roster.length) { - failures.push(`the control minted ${controlSeats.length} seat(s), wanted ${roster.length}`); - } - let registered = false; - try { - host(controlStores, controlSeats); - registered = true; - } catch { - // Expected: a singleton's seats are refused one by one, by name. - } - if (registered) { - failures.push("a singleton replacement registered cleanly — registration is not refusing what the contract says it must"); - } else { - evidence.push( - "the control run — the same roster with the replacement declared a singleton — minted all three seats and was refused at registration, which is what proves this check reaches the registry at all" - ); - } - } - (controlStores as unknown as { close(): void }).close(); + } finally { + (stores as unknown as { close(): void }).close(); } return { failures, evidence: evidence.join("; ") }; diff --git a/goals/workforce-seats/a-non-agent-seat-receives-its-skills/fixtures/flows.ts b/goals/workforce-seats/a-non-agent-seat-receives-its-skills/fixtures/flows.ts index b9ac4687c2..ccb5be7ccb 100644 --- a/goals/workforce-seats/a-non-agent-seat-receives-its-skills/fixtures/flows.ts +++ b/goals/workforce-seats/a-non-agent-seat-receives-its-skills/fixtures/flows.ts @@ -1,20 +1,40 @@ /** - * A hireable worker kind with no model in it. + * A worker flow with no model in it, run by one registered copy for every + * worker on it. * * This is the whole point of the goal beside it: the admission contract is not - * an agent feature. A kind that never calls a generator composes the same - * contract, is handed the same bag, and receives the skills its seat's folders - * resolved — and a block nested inside its action can read them. + * an agent feature. A flow that never calls a generator composes the same + * contract, and each turn's worker, loaded through the installation, carries + * the skills its folders resolved — and a block nested inside its action can + * read them. * - * Three kinds, and they do not all make the same claim. `triageFlow` composes - * the contract and carries the DELIVERY claim: a nested block reads the skills - * its seat's folders resolved. `noContractFlow` and `handRolledFlow` are a - * control pair carrying the STRUCTURAL claim: hire imposes a bag, and a schema - * that cannot accept it is refused. They run a different action set on purpose - * — see `controlActions` below. + * Three flows, and they do not all make the same claim. `defineTriageFlow` + * composes the contract and carries the DELIVERY claim: a nested block reads + * the skills the turn's worker's folders resolved. `noContractFlow` and + * `handRolledFlow` are a control pair carrying the STRUCTURAL claim: a worker + * is checked against its flow's `configSchema`, and a schema that cannot take + * the bag a worker is handed is refused. They run a different action set on + * purpose — see `controlActions` below. + * + * Each member of the pair is built on its own installation, read from the + * fixture trees here, because a flow declares one installation's session: + * `controlInstallation` holds the good workers and the legacy one on the + * no-contract flow, `twinInstallation` the good workers and one on the + * hand-rolled flow. The pair stays two top-level `defineFlow` calls, which + * `goals/scripts/validate-control-shape.mts` reads. */ +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; import { defineFlow, handler, sequencer } from "@flow-state-dev/core"; -import { workerConfigSchema } from "@flow-state-dev/workforce"; +import type { BlockContext } from "@flow-state-dev/core/types"; +import { + createWorkerInstallation, + workerConfigOf, + workerConfigSchema, + type WorkerInstallation, + type WorkerManifest +} from "@flow-state-dev/workforce"; +import { readWorkforce } from "@flow-state-dev/workforce/loader"; import { z } from "zod"; import { workerDoor } from "../../../lib/worker-door.mts"; @@ -22,34 +42,57 @@ export const TRIAGE_KIND = "request-triage"; export const NO_CONTRACT_KIND = "request-triage-legacy"; export const HAND_ROLLED_KIND = "request-triage-handrolled"; +const here = dirname(fileURLToPath(import.meta.url)); + +/** The good tree's workers, and the control tree's legacy one. */ +const good = (await readWorkforce(join(here, "workforce"))).workers; +const legacy = (await readWorkforce(join(here, "no-contract"))).workers; + +/** The one worker on the hand-rolled flow, hand-built: the twin's positive half. */ +export const HAND_ROLLED_WORKER: WorkerManifest = { + id: "support.handrolled", + declared: { description: "Hand-rolled, never composed.", flow: HAND_ROLLED_KIND, desk: "loft" }, + body: "You hold the hand-rolled desk." +}; + const inputSchema = z.object({ note: z.string() }); -/** What the seat records about itself while running. */ +/** What the worker records about itself while running. */ const seatState = z.object({ - /** The seat's skill names, in the order they reached the block. */ + /** The worker's skill names, in the order they reached the block. */ skills: z.array(z.string()).nullable().default(null), desk: z.string().nullable().default(null), + /** Whether the turn's worker carried the contract's `seatSkills` key at all. */ + hasSeatSkills: z.boolean().nullable().default(null), runs: z.number().default(0) }); -/** - * What the nested block needs of whatever flow installs it. - * - * It names `seatSkills` — the contract's key — which is what makes this a read - * of the admitted bag rather than of anything this fixture arranged. - */ -const needsSeatSkills = z.object({ - seatSkills: z.array(z.object({ name: z.string() })), - desk: z.string() -}); +const clientView = { + derived: { + ran: (ctx: { + state: { skills?: string[] | null; desk?: string | null; hasSeatSkills?: boolean | null; runs?: number }; + }) => ({ + skills: ctx.state.skills ?? null, + desk: ctx.state.desk ?? null, + hasSeatSkills: ctx.state.hasSeatSkills ?? null, + runs: ctx.state.runs ?? 0 + }) + } +}; + +/** The flow's `request.onStarted`: loads the turn's worker, on every run of a request. */ +function loadWorker(installation: WorkerInstallation, kind: string) { + return handler({ + name: `${kind}-load-worker`, + inputSchema: z.unknown(), + resources: { ...installation.resources }, + execute: async (_input: unknown, ctx: BlockContext) => ({ worker: (await installation.resolveWorker(ctx, kind)).id }) + }); +} /** - * Counts the turn, and reads no config at all — so a pass here cannot mask a + * Counts the turn, and reads no setting at all — so a pass here cannot mask a * nested failure. - * - * State-only, so it declares no `outputSchema`, returns nothing, and is chained - * with `.tap()` (BP-012 / BP-014). The mutation is already observable in the - * state-change log; echoing the input back would only pad the items log. */ const start = handler({ name: "triage-start", @@ -60,69 +103,46 @@ const start = handler({ }); /** - * The nested read — the far end of the journey a skill folder takes. + * The nested read — the far end of the journey a skill folder takes: the + * turn's worker, as the installation loaded it. * * Order is preserved rather than sorted: the contract promises level order - * (org, then team, then the seat's own), and sorting here would throw away the - * only evidence of it. + * (org, then team, then the worker's own), and sorting here would throw away + * the only evidence of it. */ const recordSkills = handler({ name: "triage-record", inputSchema, outputSchema: z.void(), - flowConfigSchema: needsSeatSkills, sessionStateSchema: seatState, execute: async (_input, ctx) => { + const config = workerConfigOf(ctx) as { seatSkills?: Array<{ name: string }>; desk?: string }; await ctx.session.patchState({ - skills: ctx.flow.config.seatSkills.map((skill) => skill.name), - desk: ctx.flow.config.desk + skills: (config.seatSkills ?? []).map((skill) => skill.name), + desk: config.desk ?? null, + hasSeatSkills: Object.hasOwn(config, "seatSkills") }); } }); -const clientView = { - derived: { - ran: (ctx: { state: { skills?: string[] | null; desk?: string | null; runs?: number } }) => ({ - skills: ctx.state.skills ?? null, - desk: ctx.state.desk ?? null, - runs: ctx.state.runs ?? 0 - }) - } -}; - -/** - * What the CONTROL pair's nested block needs: the kind's own setting, and - * nothing the admission contract imposes. - * - * Mirrors the sibling goal's `needsDesk`. The reason it exists is the reason - * the control pair does not share `triageFlow`'s action set: `recordSkills` - * independently requires `seatSkills` through its `flowConfigSchema`, so a - * control that ran it would be refused by that block's requirement whether or - * not its own schema could accept the imposed bag. Both causes would produce - * the same refusal, and the control would certify whichever one the reader - * already believed — the exact conflation this pair was rebuilt to remove. - */ -const needsDesk = z.object({ desk: z.string() }); - /** - * The control pair's nested read: its own setting only. - * - * Still NESTED rather than at the action root, for the reason `recordSkills` - * is: the pair's positive half must run to completion on a real spread, not - * merely mint. + * The control pair's nested read: its own setting, and whether the contract's + * key arrived, but no requirement on any setting. A block that required + * `seatSkills` would refuse the control on its own, whether or not its schema + * could take the bag, and certify whichever cause the reader already believed. */ const recordDesk = handler({ name: "triage-record-desk", inputSchema, outputSchema: z.void(), - flowConfigSchema: needsDesk, sessionStateSchema: seatState, execute: async (_input, ctx) => { - await ctx.session.patchState({ desk: ctx.flow.config.desk }); + const config = workerConfigOf(ctx) as { desk?: string }; + await ctx.session.patchState({ desk: config.desk ?? null, hasSeatSkills: Object.hasOwn(config, "seatSkills") }); } }); -/** The delivery claim's action set — reads the admitted `seatSkills`. */ +/** The delivery claim's action set — reads the turn's `seatSkills`. */ const actions = { run: { inputSchema, @@ -132,10 +152,10 @@ const actions = { }; /** - * The structural claim's action set — requires only `desk`. + * The structural claim's action set — requires no setting. * * Separate from `actions` so that the control pair's outcome is decided by - * each kind's own `configSchema` and by nothing else in the fixture. + * each flow's own `configSchema` and by nothing else in the fixture. */ const controlActions = { run: { @@ -146,31 +166,42 @@ const controlActions = { }; /** Composes the contract. No model, no generator — handlers only. */ -export const triageFlow = defineFlow({ - kind: TRIAGE_KIND, - cardinality: "collection", - configSchema: workerConfigSchema().extend({ desk: z.string().default("front") }), - actions, - session: { stateSchema: seatState, client: clientView } +export function defineTriageFlow(installation: WorkerInstallation) { + return defineFlow({ + kind: TRIAGE_KIND, + cardinality: "collection", + configSchema: workerConfigSchema().extend({ desk: z.string().default("front") }), + resources: { ...installation.resources }, + request: { onStarted: loadWorker(installation, TRIAGE_KIND) }, + actions, + session: { ...installation.session(seatState.shape), client: clientView } + }); +} + +let controlFlows: Record = {}; +/** The good workers, and the legacy one on the no-contract flow. */ +export const controlInstallation = createWorkerInstallation({ + standardWorkers: [...good, ...legacy], + workerFlows: () => controlFlows as never +}); + +let twinFlows: Record = {}; +/** The good workers, and the one on the hand-rolled flow. */ +export const twinInstallation = createWorkerInstallation({ + standardWorkers: [...good, HAND_ROLLED_WORKER], + workerFlows: () => twinFlows as never }); /** - * The control: a schema that **cannot accept the bag hire imposes**, because it - * omits `seatSkills`. + * The control: a schema that **cannot take the bag a worker is handed**, + * because it omits `seatSkills`. * - * Deliberately not "the same kind with `workerConfigSchema()` removed". That + * Deliberately not "the same flow with `workerConfigSchema()` removed". That * version refuses too, but removing the helper also removes every contract key, - * so the refusal is equally consistent with hire checking whether the helper - * was CALLED — which it does not and cannot. A control that conflates two - * causes certifies whichever one the reader already believes. This one declares - * three of the four contract keys and omits the one that makes the bag - * unacceptable, so only the structural cause is left. - * - * For the same reason it runs `controlActions` rather than `triageFlow`'s: an - * action set containing `recordSkills` would REQUIRE `seatSkills` through that - * block's own `flowConfigSchema`, and this kind would then be refused by the - * block whether or not its schema could accept the imposed bag — a second - * cause, reintroducing the conflation the paragraph above removes. + * so the refusal is equally consistent with a check on whether the helper was + * CALLED — which there is not and cannot be. This one declares the other + * contract keys and omits the one that makes the bag unacceptable, so only the + * structural cause is left. */ export const noContractFlow = defineFlow({ kind: NO_CONTRACT_KIND, @@ -178,26 +209,24 @@ export const noContractFlow = defineFlow({ configSchema: z.object({ instructions: z.string().optional(), teamInstructions: z.string().optional(), - // Declared so `seatSkills` stays the SINGLE missing key: the contract grew a - // fourth, and a control that omitted two would no longer isolate one cause. + // Declared so `seatSkills` stays the SINGLE missing key. seatTools: z.array(z.any()).default([]), - // The packages a seat holds, checked at boot like every other key. seatPackages: z.array(z.any()).optional(), - // The sixth, imposed on every seat: its own id. + // Imposed on every worker: its own id. seatId: z.string().optional(), - // `seatSkills` omitted — the single reason the imposed bag is refused. + // `seatSkills` omitted — the single reason the bag is refused. desk: z.string().default("front") }), + resources: { ...controlInstallation.resources }, + request: { onStarted: loadWorker(controlInstallation, NO_CONTRACT_KIND) }, actions: controlActions, - session: { stateSchema: seatState, client: clientView } + session: { ...controlInstallation.session(seatState.shape), client: clientView } }); /** - * The positive half of the same rule: a hand-written schema that accepts - * everything hire imposes, without ever calling `workerConfigSchema()`. - * - * It hires. Without it, the refusal above would still be consistent with a - * nominal check, and this goal would certify a rule the implementation rejects. + * The positive half of the same rule: a hand-written schema that takes + * everything a worker is handed, without ever calling `workerConfigSchema()`. + * It registers, and its worker runs. * * Runs `controlActions` like its twin, so the pair differs in exactly one * thing: whether its `configSchema` declares `seatSkills`. @@ -209,15 +238,16 @@ export const handRolledFlow = defineFlow({ instructions: z.string().optional(), teamInstructions: z.string().optional(), seatSkills: z.array(z.object({ name: z.string(), skillMd: z.string() }).passthrough()).default([]), - // The fourth contract key. A hand-rolled schema has to add each one as the - // contract grows — which is the cost this fixture exists to show, not a - // reason to stop hand-rolling. seatTools: z.array(z.any()).default([]), seatPackages: z.array(z.any()).optional(), - // The sixth, imposed on every seat: its own id. seatId: z.string().optional(), desk: z.string().default("front") }), + resources: { ...twinInstallation.resources }, + request: { onStarted: loadWorker(twinInstallation, HAND_ROLLED_KIND) }, actions: controlActions, - session: { stateSchema: seatState, client: clientView } + session: { ...twinInstallation.session(seatState.shape), client: clientView } }); + +controlFlows = { [TRIAGE_KIND]: defineTriageFlow(controlInstallation), [NO_CONTRACT_KIND]: noContractFlow }; +twinFlows = { [TRIAGE_KIND]: defineTriageFlow(twinInstallation), [HAND_ROLLED_KIND]: handRolledFlow }; diff --git a/goals/workforce-seats/a-non-agent-seat-receives-its-skills/goal.md b/goals/workforce-seats/a-non-agent-seat-receives-its-skills/goal.md index f90ffbbaf4..9a14927b41 100644 --- a/goals/workforce-seats/a-non-agent-seat-receives-its-skills/goal.md +++ b/goals/workforce-seats/a-non-agent-seat-receives-its-skills/goal.md @@ -1,25 +1,27 @@ # workforce-seats › a non-agent seat receives its skills **Issue:** FIX-1367 (thin `WorkerConfig` admission for hireable kinds; builds on FIX-1356's skills file convention and FIX-1325's seat factory) -**Outcome:** An app defines a worker flow kind with **no model and no generator in it**, composes the admission contract into its settings schema, and hires two seats from a workforce tree that declares skills at three levels — an `org/skills/` folder, a team's, and one beside a worker. Each seat runs an action to completion through the real HTTP route, and a block **nested inside that action** reads the skills its own folders declared off `ctx.flow.config.seatSkills`, in level order. Neither seat holds the other's team-level or own-folder skills; both hold the org folder's. With the contract stripped from that same kind, the whole roster refuses at the hire, the message names the worker and the fix, and nothing is registered. +**Outcome:** An app defines a worker flow with **no model and no generator in it**, composes the admission contract into its settings schema, and runs two workers on one registered copy of it, from a workforce tree that declares skills at three levels — an `org/skills/` folder, a team's, and one beside a worker. Each worker runs an action to completion through the real HTTP route, in a session naming it, and a block **nested inside that action** reads the skills its own folders declared off the turn's worker, in level order. Neither worker holds the other's team-level or own-folder skills; both hold the org folder's. With the contract stripped from a flow, the whole installation refuses at boot, the message names the worker, the flow and the missing key, and nothing is registered. Rewritten for FIX-1788: workers are data on one copy of their flow, and a turn reads its worker through the installation. -**Why a non-agent kind.** The claim this issue makes is about *every hireable kind*, not about the built-in `agent`. An end-to-end run of the agent kind would be green for a mechanism that only ever worked on the one kind that happened to declare the key — which is exactly the defect being removed. The kind here calls no model, so a pass cannot be coming from anything an agent does. +**Why a non-agent flow.** The claim is about *every worker flow*, not about the built-in `agent`. An end-to-end run of the agent would be green for a mechanism that only ever worked on the one flow that happened to declare the key. The flow here calls no model, so a pass cannot be coming from anything an agent does. -**Input:** `fixtures/input.json` — the two seat ids, each one's own setting, and the skill names each one's folders declare. `fixtures/workforce/**` carries the same thing as files: `org/skills/house-style/`, `teams/support/skills/triage-tone/`, `teams/support/workers/desk/skills/escalation/`, `teams/billing/skills/dunning/`, and a `WORKER.md` per seat. `fixtures/no-contract/` is the control tree. Held-out: every id, setting and skill name is read from the fixture and graded against what the running blocks reported, so swapping any of them still passes a correct implementation. **Each seat's own setting differs from its schema's default on purpose** — a setting dropped on the way to the flow would otherwise read back as the default and pass. +**Input:** `fixtures/input.json` — the two worker ids, each one's own setting, and the skill names each one's folders declare. `fixtures/workforce/**` carries the same thing as files: `org/skills/house-style/`, `teams/support/skills/triage-tone/`, `teams/support/workers/desk/skills/escalation/`, `teams/billing/skills/dunning/`, and a `WORKER.md` per worker. `fixtures/no-contract/` is the control tree. Held-out: every id, setting and skill name is read from the fixture and graded against what the running blocks reported, so swapping any of them still passes a correct implementation. **Each worker's own setting differs from its schema's default on purpose** — a setting dropped on the way to the turn would otherwise read back as the default and pass. **Signal:** against the real HTTP router (`createFlowApiRouter`) over on-disk SQLite stores, matching its siblings in this family. The records come from the real loader (`readWorkforce`), never hand-built: the folders are half of what is under test. -(a) `readWorkforce` reads the tree with no errors and produces two records; one `hireWorkforce` call turns them into two seats of the non-agent kind. -(b) Each seat runs `POST /api/flows///actions/run` to completion. After closing the stores, reopening the same file and building a fresh host, `GET /api/flows/sessions//state` shows what a block **nested inside the action** read from `ctx.flow.config`: its own skill names as a **sequence** in level order (org, team, own), and its own desk. -(c) Neither seat's list equals the other's; neither holds a skill from the other's team or worker folder; both hold the org folder's. -(d) A kind whose schema omits only `seatSkills`: the hire throws, naming the worker and `seatSkills`, returns nothing, and the good seats' addresses 404 on a host built from what came back. It omits **one** contract key rather than all of them on purpose — a control that drops the helper drops every key with it, and its refusal would then be equally consistent with hire checking whether the helper was called. It also runs its **own action set**, requiring only its `desk`: the delivery kind's action set contains a block that independently requires `seatSkills` through its `flowConfigSchema`, so a control sharing it would be refused by that block whether or not its schema could accept the imposed bag. -(e) A hand-written schema that never calls `workerConfigSchema()` but accepts everything hiring imposes is hired, carrying the imposed `seatSkills`. It runs the same `desk`-only action set as (d), so the pair differs in exactly one thing: whether its schema declares `seatSkills`. This is what makes (d) mean what it says: admission is decided by what a schema accepts, not by which helper built it. +(a) `readWorkforce` reads the tree with no errors and produces two records; `hireWorkforce` registers one copy of the non-agent flow, at its kind. +(b) Each worker's session is created naming it, and runs `POST /api/flows///actions/run` to completion. After closing the stores, reopening the same file and building a fresh host, `GET /api/flows/sessions//state` shows what a block **nested inside the action** read from the turn's worker: its own skill names as a **sequence** in level order (org, team, own), and its own desk. +(c) Neither worker's list equals the other's; neither holds a skill from the other's team or worker folder; both hold the org folder's. +(d) A flow whose schema omits only `seatSkills`, with one worker on it: `hireWorkforce` throws, naming the worker, the flow and `seatSkills`, and says nothing was registered. It omits **one** contract key rather than all of them on purpose — a control that drops the helper drops every key with it, and its refusal would then be equally consistent with a check on whether the helper was called. It also runs its **own action set**, requiring no setting: a block that required `seatSkills` would refuse it on its own. +(e) A hand-written schema that never calls `workerConfigSchema()` but takes everything a worker is handed registers, and its worker's turn carries `seatSkills`. It runs the same action set as (d), so the pair differs in exactly one thing: whether its schema declares `seatSkills`. This is what makes (d) mean what it says: admission is decided by what a schema takes, not by which helper built it. -**Anti-game:** a hollow pass would assert the hires returned and the requests completed — true even when every seat holds an empty catalog, or one shared one. So the check MUST read the skills back through `/state` rather than off the returned instance, because the claim is that the bag reached a RUNNING BLOCK and a bag asserted on the instance proves only the mint; MUST read from a **nested** block rather than the action root, since a root-only read proves nothing about the context spread that carries the value down; MUST close the stores and rebuild the host first, so nothing is served from a live context; MUST compare the names as an ordered **sequence**, since a set check passes for a bag assembled backwards and level order is part of the promise; MUST assert each seat does NOT hold its sibling's folders, since one shared bag is always right for somebody; MUST use a kind with no model, since an agent run cannot distinguish the contract from the agent kind's own path; MUST assert the control refusal left **nothing** registered, since a refusal after a partial hire is not a refusal; and MUST keep the control pair off any action set whose blocks require `seatSkills`, since such a block refuses the control on its own and lets the pair pass while hiring imposes nothing. That last property is checked statically by `goals/scripts/validate-control-shape.mts` (rule C4). +**Anti-game:** a hollow pass would assert the hires returned and the requests completed — true even when every seat holds an empty catalog, or one shared one. So the check MUST read the skills back through `/state` rather than off the returned instance, because the claim is that the bag reached a RUNNING BLOCK; MUST read from a **nested** block rather than the action root, since a root-only read proves nothing about the context spread that carries the value down; MUST close the stores and rebuild the host first, so nothing is served from a live context; MUST compare the names as an ordered **sequence**, since a set check passes for a bag assembled backwards and level order is part of the promise; MUST assert each seat does NOT hold its sibling's folders, since one shared bag is always right for somebody; MUST use a kind with no model, since an agent run cannot distinguish the contract from the agent kind's own path; MUST assert the control refusal registered **nothing**, since a refusal after a partial registration is not a refusal; and MUST keep the control pair off any action set whose blocks require `seatSkills`, since such a block refuses the control on its own and lets the pair pass while hiring imposes nothing. That last property is checked statically by `goals/scripts/validate-control-shape.mts` (rule C4). **Model:** n/a — handlers only, by construction. The property under test is which settings reach a running block. **Run:** `pnpm tsx goals/workforce-seats/a-non-agent-seat-receives-its-skills/run.mts` ## Verdict log | Date | Commit | Model | Verdict | Notes | |------|--------|-------|---------|-------| +| 2026-10-08 | `865abc573` + FIX-1788 P4 | n/a (handlers only) | PASS | One `request-triage` copy ran both workers through the real HTTP route, each in a session naming it; after closing the SQLite file and rebuilding the host, `support.desk` showed `["house-style","triage-tone","escalation"]` and `billing.desk` `["house-style","dunning"]`, each with its own desk. The no-contract installation refused naming `support.legacy`, the flow and `seatSkills`, nothing registered; the hand-rolled worker's turn carried `seatSkills`. `guard:control-shape` passes. | +| 2026-10-08 | `865abc573` + FIX-1788 P4, `seatSkills` added to the no-contract schema (then restored) | n/a | FAIL (expected) | `the flow with no contract registered 4 cop(ies) instead of refusing`: (d) is graded on the key. | | 2026-09-17 | fix/FIX-1367 (pre-PR) | n/a (handlers only) | PASS | The loader read the three-level tree and both records hired into a kind with no model in it. Both ran through the real HTTP route; after closing the SQLite file and rebuilding the host, `support.desk`'s nested block showed `["house-style","triage-tone","escalation"]` and `billing.desk`'s showed `["house-style","dunning"]`, each with its own desk. Neither held the other's team or own-folder skills; both held the org folder's. With the contract stripped, the hire refused naming `support.legacy` and `workerConfigSchema()`, and the good seats' addresses 404'd. | | 2026-09-17 | fix/FIX-1367 (control run, hire delivers no skills) | n/a | FAIL (expected) | With the factory imposing a hard-coded empty list instead of the record's skills, leg (b) went red for both seats — *"its nested block saw [], its folders declared […]"* — and legs (c) took it too. This is the control that proves the check reaches the delivery it claims to grade, rather than passing on the seats merely running. | | 2026-09-17 | fix/FIX-1367 (control run, a seat handed a sibling's folder) | n/a | FAIL (expected) | Copying `teams/support/skills/triage-tone/` into `teams/billing/skills/` was caught by leg (c): *"billing.desk: holds its sibling's skills ["triage-tone"]"*, and by (b)'s sequence check. Confirms the isolation half is graded and not assumed. | diff --git a/goals/workforce-seats/a-non-agent-seat-receives-its-skills/run.mts b/goals/workforce-seats/a-non-agent-seat-receives-its-skills/run.mts index 2c3f05578b..5a4662f68f 100644 --- a/goals/workforce-seats/a-non-agent-seat-receives-its-skills/run.mts +++ b/goals/workforce-seats/a-non-agent-seat-receives-its-skills/run.mts @@ -18,17 +18,18 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { createFlowApiRouter, createFlowRegistry, type StoreRegistry } from "@flow-state-dev/engine"; import { createSQLiteStores } from "@flow-state-dev/store-sqlite"; -import { hireWorkforce, type HireOptions } from "@flow-state-dev/workforce"; +import { hireWorkforce } from "@flow-state-dev/workforce"; import { readWorkforce } from "@flow-state-dev/workforce/loader"; import type { FlowInstance } from "@flow-state-dev/core/types"; -import { fixtureDir, loadFixture, runGoal, silentLogger, stripIntentOverrides } from "../../lib/index.mts"; +import { fixtureDir, installWorkers, loadFixture, runGoal, silentLogger, stripIntentOverrides } from "../../lib/index.mts"; import { TRIAGE_KIND, NO_CONTRACT_KIND, HAND_ROLLED_KIND, - triageFlow, - noContractFlow, - handRolledFlow + HAND_ROLLED_WORKER, + controlInstallation, + defineTriageFlow, + twinInstallation } from "./fixtures/flows"; type SeatFixture = { @@ -51,20 +52,6 @@ stripIntentOverrides(); const fixture = loadFixture(import.meta.url); const { support, billing } = fixture.seats; -const kinds: HireOptions["workerFlows"] = { - [TRIAGE_KIND]: triageFlow as never, - // The positive half of the structural rule: hand-written, accepts the bag, hires. - [HAND_ROLLED_KIND]: handRolledFlow as never -}; - -/** - * The same flows with the control registered, so its refusal is about the - * contract it never composed, not about a kind the app forgot to pass. Kept - * off `kinds`: a worker flow that misses the contract refuses the whole - * installation at boot. - */ -const withNoContract: HireOptions["workerFlows"] = { ...kinds, [NO_CONTRACT_KIND]: noContractFlow as never }; - const tree = (name: string): string => join(fixtureDir(import.meta.url), name); function host(stores: StoreRegistry, flows: FlowInstance[]) { @@ -75,8 +62,22 @@ function host(stores: StoreRegistry, flows: FlowInstance[]) { type Router = ReturnType; -async function act(router: Router, address: string, sessionId: string): Promise { - const path = [address, sessionId, "actions", "run"]; +/** Open `sessionId` on `flow`, naming `worker`, as the session route does for a person. */ +async function open(router: Router, flow: string, worker: string, sessionId: string): Promise { + const path = [flow, "sessions"]; + const res = await router.POST( + new Request(`http://goal/api/flows/${path.join("/")}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ userId: fixture.userId, sessionId, state: { workerId: worker } }) + }), + { params: { path } } + ); + return res.status; +} + +async function act(router: Router, flow: string, sessionId: string): Promise { + const path = [flow, sessionId, "actions", "run"]; return router.POST( new Request(`http://goal/api/flows/${path.join("/")}`, { method: "POST", @@ -93,7 +94,9 @@ async function ranOn(router: Router, sessionId: string) { params: { path } }); const body = (await res.json()) as { - clientData?: { session?: { ran?: { skills?: string[] | null; desk?: string | null; runs?: number } } }; + clientData?: { + session?: { ran?: { skills?: string[] | null; desk?: string | null; hasSeatSkills?: boolean | null; runs?: number } }; + }; }; return { status: res.status, ...(body.clientData?.session?.ran ?? {}) }; } @@ -123,10 +126,13 @@ await runGoal(async () => { if (skillErrors.length > 0) failures.push(`the loader reported skill errors: ${JSON.stringify(skillErrors)}`); if (workers.length !== 2) failures.push(`the tree produced ${workers.length} record(s), wanted 2`); - const seats = hireWorkforce(workers, { workerFlows: kinds }); - if (seats.length !== 2) failures.push(`hired ${seats.length} seat(s), wanted 2`); + const { copies: seats } = installWorkers(workers, (installation) => ({ [TRIAGE_KIND]: defineTriageFlow(installation) })); + const triageCopies = seats.filter((copy) => copy.kind === TRIAGE_KIND); + if (triageCopies.length !== 1 || triageCopies[0]!.id !== TRIAGE_KIND) { + failures.push(`${triageCopies.length} copies of "${TRIAGE_KIND}" registered, wanted one, at its kind`); + } evidence.push( - "the real loader read the tree and one hireWorkforce call turned both records into seats of a kind with no model in it" + `the real loader read the tree, and one copy of "${TRIAGE_KIND}", a flow with no model in it, runs both workers` ); // ---- (b) each seat RUNS, and its nested block reads its own skills ------- @@ -134,7 +140,12 @@ await runGoal(async () => { { const router = host(stores, seats); for (const id of [support.id, billing.id]) { - const res = await act(router, id, sessions[id]!); + const opened = await open(router, TRIAGE_KIND, id, sessions[id]!); + if (opened !== 201) { + failures.push(`${id}: its session on "${TRIAGE_KIND}" was not created (${opened})`); + continue; + } + const res = await act(router, TRIAGE_KIND, sessions[id]!); const body = (await res.json()) as { request?: { id: string } }; // One failure per thing that actually went wrong. A rejected action has @@ -144,7 +155,7 @@ await runGoal(async () => { // one. A check that invents a failure is worse than a check that misses // one: whoever reads the output is told two things broke when one did. if (res.status !== 202) { - failures.push(`${id}: expected 202 from its own address, got ${res.status}`); + failures.push(`${id}: expected 202 from "${TRIAGE_KIND}", got ${res.status}`); continue; } const requestId = body.request?.id; @@ -156,7 +167,7 @@ await runGoal(async () => { const status = await settled(stores, requestId); if (status !== "completed") failures.push(`${id}: request ended ${String(status)}`); } - evidence.push("both seats ran an action to completion through the real HTTP route, with no model call"); + evidence.push("both workers ran an action to completion through the real HTTP route, each in a session naming it, with no model call"); } (stores as unknown as { close(): void }).close(); @@ -189,7 +200,7 @@ await runGoal(async () => { if (ran.runs !== 1) failures.push(`${seat.id}: ran ${String(ran.runs)} times`); } evidence.push( - "after closing the store and rebuilding the host, each seat's nested block shows the skills its own folders declared, in level order, read off ctx.flow.config.seatSkills" + "after closing the store and rebuilding the host, each worker's nested block shows the skills its own folders declared, in level order, read off the turn's worker" ); // ---- (c) control: a seat is NOT handed its sibling's folders ----------- @@ -217,72 +228,62 @@ await runGoal(async () => { `both seats hold the org folder's "${fixture.orgSkill}" and neither holds the other's team or own-folder skills` ); - // ---- (d) control: strip the contract, and nothing is hired ------------- + // ---- (d) control: a schema that can't take the bag registers nothing --- { - const { workers: legacy } = await readWorkforce(tree(fixture.control.dir)); let hired: FlowInstance[] | undefined; let refusal = ""; try { - hired = hireWorkforce([...workers, ...legacy], { workerFlows: withNoContract }); + hired = hireWorkforce(controlInstallation); } catch (error) { refusal = messageOf(error); } if (hired !== undefined) { - failures.push(`the kind with no contract hired ${hired.length} seat(s) instead of refusing`); + failures.push(`the flow with no contract registered ${hired.length} cop(ies) instead of refusing`); } else { - for (const name of [`worker flow "${NO_CONTRACT_KIND}"`, "seatSkills"]) { - if (!refusal.includes(name)) { - failures.push(`the refusal does not name "${name}": ${refusal}`); - } - } - // A refusal after a partial hire is not a refusal — the seats whose own - // kind was fine are gone too, so nothing can be registered. - const emptied = host(stores, hired ?? []); - const res = await act(emptied, billing.id, "s_refused"); - if (res.status !== 404) { - failures.push(`a seat was registered anyway (${billing.id} answered ${res.status})`); + for (const name of [fixture.control.id, NO_CONTRACT_KIND, "seatSkills", "nothing was registered"]) { + if (!refusal.includes(name)) failures.push(`the refusal does not name "${name}": ${refusal}`); } } evidence.push( - "a kind whose schema omits seatSkills refuses the whole roster at boot, naming the flow and the missing key, and nothing is registered" + "a flow whose schema omits seatSkills refuses the whole installation at boot, naming the worker, the flow and the missing key, and nothing is registered" ); } // ---- (e) control: admission is structural, not nominal ---------------- // - // (d) shows a refusal. On its own it is equally consistent with hire - // checking whether `workerConfigSchema()` was CALLED — it does not and - // cannot. So a hand-written schema that never calls the helper, but accepts - // everything hire imposes, must hire exactly like a composed kind. + // (d) shows a refusal. On its own it is equally consistent with a check on + // whether `workerConfigSchema()` was CALLED — there is none. So a + // hand-written schema that never calls the helper, but takes everything a + // worker is handed, must register and run exactly like a composed flow. { let hired: FlowInstance[] | undefined; let refusal = ""; try { - hired = hireWorkforce( - [ - ...workers, - { - id: "support.handrolled", - declared: { description: "Hand-rolled, never composed.", flow: HAND_ROLLED_KIND }, - body: "You hold the hand-rolled desk." - } - ], - { workerFlows: kinds } - ); + hired = hireWorkforce(twinInstallation); } catch (error) { refusal = messageOf(error); } if (hired === undefined) { - failures.push(`a hand-written schema that accepts the imposed bag was refused: ${refusal}`); + failures.push(`a hand-written schema that takes the bag was refused: ${refusal}`); } else { - const seat = hired.find((s) => s.id === "support.handrolled"); - if (seat === undefined) failures.push("the hand-rolled kind hired no seat"); - else if (!Object.hasOwn(seat.config, "seatSkills")) { - failures.push("the hand-rolled seat hired without the imposed seatSkills key"); + const twinStores = createSQLiteStores({ filename: join(dir, "twin.db") }) as unknown as StoreRegistry; + try { + const router = host(twinStores, hired); + const session = "s_handrolled"; + const opened = await open(router, HAND_ROLLED_KIND, HAND_ROLLED_WORKER.id, session); + const res = opened === 201 ? await act(router, HAND_ROLLED_KIND, session) : undefined; + const requestId = res?.status === 202 ? ((await res.json()) as { request?: { id: string } }).request?.id : undefined; + const status = requestId === undefined ? undefined : await settled(twinStores, requestId); + const ran = await ranOn(router, session); + if (status !== "completed") failures.push(`the hand-rolled worker's turn ended ${String(status)} (session ${opened}, action ${res?.status})`); + else if (ran.hasSeatSkills !== true) failures.push("the hand-rolled worker's turn carried no seatSkills key"); + else if (ran.desk !== HAND_ROLLED_WORKER.declared.desk) failures.push(`the hand-rolled worker's turn saw desk ${String(ran.desk)}`); + } finally { + (twinStores as unknown as { close(): void }).close(); } } evidence.push( - "a hand-written schema that never calls workerConfigSchema() but accepts the imposed bag hires exactly like a composed kind, so (d)'s refusal is about what the schema takes and not about which helper built it" + "a hand-written schema that never calls workerConfigSchema() but takes the bag registers, and its worker's turn carries seatSkills, so (d)'s refusal is about what the schema takes and not about which helper built it" ); } } diff --git a/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/fixtures/flows.ts b/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/fixtures/flows.ts index 1bb46ca083..acb4877cb6 100644 --- a/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/fixtures/flows.ts +++ b/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/fixtures/flows.ts @@ -1,27 +1,35 @@ /** - * One worker kind, built the way an app builds one: the documents its - * `resources/` folder declared, spread into a flow-level map beside a store of - * its own. + * One worker flow, built the way an app builds one on an installation: one + * registered copy every worker runs on, the installation's documents spread + * into its resources beside a store of its own, and the installation's + * visibility rule, so each turn's model reaches only its worker's documents. * - * A factory rather than a module-level constant, because the documents come off - * disk. That is also what makes the fixture honest: the flow-level map holds a - * `${STORE}` the allowlist must never touch, beside documents it must narrow. - * A fixture whose flow-level map held nothing but documents would be green for - * a resolver that silently deletes the app's own machinery. + * Its actions are core's model-facing document tools, mounted as they are: + * the same blocks a model calls, so a check runs them as a model would, with + * no model. Beside them, `peek`, an app's own tool built on core's lookup. * - * No model, no generator. What is graded is which resources reached a running - * block and which of them it could write. + * `withoutRule` builds the same flow with no visibility rule: the control. */ -import { defineFlow, defineResource, handler, sequencer } from "@flow-state-dev/core"; -import type { DeclaredResources } from "@flow-state-dev/core"; -import type { ResourceDoc } from "@flow-state-dev/workforce"; -import { resourcesFromDocs, workerConfigSchema } from "@flow-state-dev/workforce"; +import { + createManifestRegistry, + defineFlow, + defineResource, + discoveryTools, + handler, + readResourceContentTool, + resolveResourceByUri, + resourcesManifestSource, + resourceSearchTools, + writeResourceContentTool, +} from "@flow-state-dev/core"; +import type { WorkerInstallation } from "@flow-state-dev/workforce"; +import { workerConfigSchema } from "@flow-state-dev/workforce"; import { z } from "zod"; import { workerDoor } from "../../../lib/worker-door.mts"; export const DESK_KIND = "desk"; -/** The app's own store, declared at flow level beside the documents. Not a document. */ +/** The app's own store, declared beside the documents. Not a document, and no grant governs it. */ export const STORE = "audit-log"; const auditLog = defineResource({ @@ -29,108 +37,49 @@ const auditLog = defineResource({ scope: "org", stateSchema: z.object({ entries: z.array(z.string()).default([]) }), default: { entries: [] }, - writable: true + writable: true, }); -const inputSchema = z.object({ note: z.string() }); - -/** What the seat records about what it could actually touch. */ -const seatState = z.object({ - /** Every resource key the block resolved, sorted. */ - reach: z.array(z.string()).nullable().default(null), - /** Every one of those it could also write, sorted. */ - wrote: z.array(z.string()).nullable().default(null), - runs: z.number().default(0) -}); - -const start = handler({ - name: "desk-start", - inputSchema, - execute: async (_input, ctx) => { - await ctx.session.incState({ runs: 1 }); - } +/** An app's own tool: open a document by uri through core's lookup, and say whether it found one. */ +const peek = handler({ + name: "peek", + inputSchema: z.object({ uri: z.string() }), + outputSchema: z.object({ found: z.boolean() }), + execute: async ({ uri }, ctx) => ({ found: (await resolveResourceByUri(uri, ctx)) !== undefined }), }); /** - * The nested read — what this seat can reach, and what it can write. + * Build the desk flow on `installation`. * - * Both halves are probed by DOING them, never by reading a flag: `ro` is only - * worth anything if the write actually refuses at the seam, and a check that - * asserted `writable === false` would pass for a flag nothing consults. + * @param options.withoutRule The control: no visibility rule, so every turn's + * model reaches every document, as a flow that sets none does. */ -function probe(keys: readonly string[]) { - return handler({ - name: "desk-probe", - inputSchema, - outputSchema: z.void(), - // Every document is org-scoped. Organization identity is unconditional, so - // an org registry is always built and no declaration is needed — the older - // opt-in let a request be admitted with no org, building no registry and - // reading every document as unregistered: a green `reach: []` for the wrong - // reason. - sessionStateSchema: seatState, - execute: async (_input, ctx) => { - const reach: string[] = []; - const wrote: string[] = []; - for (const key of keys) { - let ref: { setState(next: Record): Promise } | undefined; - try { - ref = ctx.resources.get(key) as unknown as typeof ref; - } catch { - continue; - } - if (ref === undefined) continue; - reach.push(key); - try { - await ref.setState({ touched: true }); - wrote.push(key); - } catch { - // A refused write is the point of the `ro` half, not an error here. - } - } - await ctx.session.patchState({ reach: reach.sort(), wrote: wrote.sort() }); - } +export function buildDesk(installation: WorkerInstallation, options: { withoutRule?: boolean } = {}) { + const { globResources, grepResourceContent } = resourceSearchTools(); + const { discover } = discoveryTools(createManifestRegistry([resourcesManifestSource()])); + // The turn's worker, loaded on every run of a request, a resumed one included. + const loadWorker = handler({ + name: "desk-load-worker", + inputSchema: z.unknown(), + resources: { ...installation.resources }, + execute: async (_input, ctx) => ({ worker: (await installation.resolveWorker(ctx, DESK_KIND)).id }), }); -} - -const clientView = { - derived: { - ran: (ctx: { state: { reach?: string[] | null; wrote?: string[] | null; runs?: number } }) => ({ - reach: ctx.state.reach ?? null, - wrote: ctx.state.wrote ?? null, - runs: ctx.state.runs ?? 0 - }) - } -}; - -/** - * Build the kind from the documents the loader found. - * - * Returns the catalog too, because that is the same map the app hands - * `hireWorkforce` as `documents` — one list, spread into the flow and passed to - * the hire step, never built twice. - */ -export function buildDesk(documents: ResourceDoc[]): { - deskFlow: ReturnType; - catalog: DeclaredResources; - probedKeys: string[]; -} { - const catalog = resourcesFromDocs(documents); - const probedKeys = [...Object.keys(catalog), STORE].sort(); - - const deskFlow = defineFlow({ + return defineFlow({ kind: DESK_KIND, cardinality: "collection", configSchema: workerConfigSchema(), - resources: { ...catalog, [STORE]: auditLog } as DeclaredResources, - actions: { ...workerDoor, - run: { - inputSchema, - block: sequencer({ name: "desk-work", inputSchema }).tap(start).tap(probe(probedKeys)) - } + session: installation.session(), + resources: { ...installation.resources, ...installation.documents, [STORE]: auditLog }, + ...(options.withoutRule === true ? {} : { resourceVisibility: installation.resourceVisibility }), + request: { onStarted: loadWorker }, + actions: { + ...workerDoor, + read: { inputSchema: z.object({ uri: z.string().optional() }), block: readResourceContentTool() }, + write: { inputSchema: z.object({ uri: z.string(), content: z.string() }), block: writeResourceContentTool() }, + glob: { inputSchema: z.object({}).passthrough(), block: globResources }, + grep: { inputSchema: z.object({ pattern: z.string() }).passthrough(), block: grepResourceContent }, + discover: { inputSchema: z.object({}).passthrough(), block: discover }, + peek: { inputSchema: z.object({ uri: z.string() }), block: peek }, }, - session: { stateSchema: seatState, client: clientView } }); - - return { deskFlow, catalog, probedKeys }; } diff --git a/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/goal.md b/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/goal.md index 6be8c4ba84..78a4edb88e 100644 --- a/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/goal.md +++ b/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/goal.md @@ -1,71 +1,66 @@ # workforce-seats › a seat reaches the documents its file names -**Issue:** FIX-1381 (seat resource allowlist; builds on FIX-1380's D-11 and on the resources file convention) +**Issue:** FIX-1381 (seat resource allowlist); rewritten for FIX-1788 (V7, BR-24): workers share one copy of their flow, and the grants narrow what each turn's model reaches. -**Outcome:** An org puts two documents in its workforce tree and writes one line in each seat's -`WORKER.md` saying which of them that seat may touch. The lead consults the handbook and cannot -rewrite it. The CFO keeps payroll current and cannot see the handbook. A seat whose file says -nothing keeps the reach it had before any of this existed. Nobody loses the app's own store, which -no seat file mentions and no grant governs. +**Outcome:** An org puts two documents in its workforce tree and writes one line in each worker's +`WORKER.md` saying which of them that worker may touch. The workers run on one registered copy of +their flow. The lead's model consults the handbook and cannot rewrite it. The CFO's model keeps +payroll current and cannot see the handbook. A worker whose file says nothing reaches both, as +before. A document a worker isn't granted answers its model exactly as one that doesn't exist. -**Input:** `fixtures/input.json` — three seat ids and, per seat, the documents it should reach and -the ones it should be able to write. `fixtures/workforce/**` carries the same thing as files: -`org/resources/handbook.md`, `org/resources/payroll.md`, and a `WORKER.md` per seat — one granting +**Input:** `fixtures/input.json` — three worker ids and, per worker, the documents it should reach +and the ones it should be able to write. `fixtures/workforce/**` carries the same thing as files: +`org/resources/handbook.md`, `org/resources/payroll.md`, and a `WORKER.md` per worker — one granting `handbook` bare, one granting `payroll: rw`, one declaring no `resources:` key at all. `fixtures/typo/` is the control tree, one character wrong in a grant. Held-out: every id, ref and -expected set is read from the fixture and graded against what the running block managed, so renaming -a document or moving a grant still passes a correct implementation. **The flow-level map holds the -app's own `audit-log` store beside the documents on purpose** — a fixture whose flow-level map held -nothing but documents is green for a resolver that deletes the app's own machinery. - -**Signal:** against the real HTTP router (`createFlowApiRouter`) over on-disk SQLite stores, matching -its siblings in this family. The records and the documents come from the real loader -(`readDeclaredRoster`), never hand-built: the files are half of what is under test. - -(a) The loader reads the tree with no problems — three worker records and two documents — and one -`hireWorkforce` call, handed the same `resourcesFromDocs` map the flow was built from, turns them -into three seats of one kind. - -(b) Each seat runs `POST /api/flows///actions/run` to completion. After closing the -stores, reopening the same file and building a fresh host, `GET /api/flows/sessions//state` -shows what a block **nested inside the action** managed: every resource key it could resolve, and -every one of those it could also write. - -(c) Each seat's document set is exactly what its own file names, and its written set is exactly what -its file grants. The bare grant reads and does not write. The `rw` grant writes. The seat that -declared nothing reaches and writes both. - -(d) All three still reach **and write** the app's own `audit-log`, which no seat file mentions. - -(e) No two of the three reached the same set. - -(f) A seat file granting a ref no document matches refuses the whole roster at the hire, naming the -seat and the ref, and saying that nothing was hired against the count of the WHOLE roster — the -good workers in the same call included. - -**Anti-game:** a hollow pass would assert the hires returned and the requests completed — true even -when every seat holds the same map. So the check MUST read what the seat reached back through -`/state` rather than off the returned instance, because a map asserted on `seat.resources` proves -the mint and nothing about what a block holds; MUST read from a **nested** block, since a root-only -read proves nothing about the context spread that carries the map down; MUST close the stores and -rebuild the host first, so nothing is served from a live context; MUST probe writability by -**actually writing**, since asserting `writable === false` passes for a flag nothing consults; MUST -assert the app's own store survives every grant (d), since a resolver that narrows to the granted -documents alone is otherwise fully green; MUST assert no two seats saw the same set (e), since one -shared map is always right for somebody; and MUST read the control's all-or-nothing claim off the -refusal itself rather than off a host built from what came back, since -`hireWorkforce` returns its seats: when it throws there is no array, so such a host is empty -whatever happened and a 404 from it is a check that cannot fail. - -**Model:** n/a — handlers only, by construction. What is graded is which resources reached a running -block and which of them it could write. +expected set is read from the fixture and graded against what the tools answered, so renaming a +document or moving a grant still passes a correct implementation. + +**Signal:** the real loader (`readDeclaredRoster`), `createWorkerInstallation` and `hireWorkforce`, +and a flow built the way the docs tell an app to build a custom worker flow: the installation's +session, its documents beside the app's own `audit-log` store, its `resourceVisibility` rule, and +`resolveWorker` in `request.onStarted`. The flow's actions are core's model-facing document tools +(`readResourceContent` with and without a uri, `writeResourceContent`, `globResources`, +`grepResourceContent`, the `discover` door) and `peek`, an app tool built on core's +`resolveResourceByUri`: the blocks a model calls, run as a model would, with no model. Each worker's +session is created naming it through the session route. + +(a) The loader reads the tree with no problems — three workers and two documents — and +`hireWorkforce` registers one copy of the flow, at its kind, and none at any worker's id. + +(b) Each worker's model lists, globs, greps and discovers exactly the documents its own file grants. + +(c) Reading, writing or looking up a document the worker isn't granted answers exactly as for a +document that doesn't exist, through core's tools and through the app's own. + +(d) A bare grant is read and not written; an `rw` grant is written; a worker naming nothing writes both. + +(e) No two of the three reached the same set, on the one copy. + +(f) A worker file granting a ref no document matches registers nothing: `hireWorkforce` refuses, +naming the worker and the ref. + +**Anti-game:** a hollow pass would read one worker's reach and stop, which one shared map satisfies. +So the check MUST run all three workers on the ONE copy and see different answers (e), MUST probe +writability by actually writing, MUST compare a refused document's answer against a real missing +document's answer rather than only seeing an error, and MUST grade the app's own tool, since a rule +honoured only by core's listing is still a leak through every app tool. The control removes the +rule and nothing else. + +**Model:** n/a — handlers only, by construction. What is graded is what each worker's tools answered. **Run:** `pnpm tsx goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/run.mts` +**Controls:** +- `GOAL_CONTROL=no-visibility-rule` builds the same flow with no `resourceVisibility`. Must FAIL — + `the first worker's model lists the second's document`, with (b), (c), (d) and (e) red beside it. + ## Verdict log | Date | Commit | Model | Verdict | Notes | |------|--------|-------|---------|-------| +| 2026-10-08 | `865abc573` + this change | n/a | PASS | One `desk` copy ran three workers: `engineering.lead` lists `["handbook"]` and writes nothing, `engineering.cfo` lists and writes `["payroll"]`, `engineering.chief` lists and writes both, through read, glob, grep, discover and the app's `peek`. Another worker's document read, wrote and was looked up as a missing one. The typo tree registered nothing, naming `engineering.typo`. | +| 2026-10-08 | `865abc573` + this change, `GOAL_CONTROL=no-visibility-rule` | n/a | FAIL (expected) | `the first worker's model lists the second's document: engineering.lead lists ["payroll"]`, with every worker listing both documents, reading and writing the other's, and the three sets equal. | | 2026-09-19 | claude/fix-1381-l4c9yh | n/a | PASS | All six legs. The lead reached `handbook` and wrote nothing; the CFO reached and wrote `payroll`; the seat declaring nothing reached and wrote both. All three kept `audit-log`. The typo tree refused the whole roster naming `engineering.typo` and `hanbdook`, and the good seat's address 404'd afterwards. | | 2026-09-19 | (control: the mint ignores the resolved grant) | n/a | FAIL (expected) | Both granted seats reached `["handbook","payroll"]` and wrote both, and legs (c) and (e) both fired. Pins that the check is sensitive to the map reaching the mint at all. | | 2026-09-19 | (control: the narrowed map built from the granted documents alone) | n/a | FAIL (expected) | Leg (d) only: every granted seat lost `audit-log`. This is the construction the spec's first draft described, and the leg that exists to catch it. | diff --git a/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/run.mts b/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/run.mts index 9b0285a96a..fdc0f9f61e 100644 --- a/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/run.mts +++ b/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/run.mts @@ -1,30 +1,29 @@ /** - * Goal check — a seat reaches the documents its own file names, and nothing - * else. + * Goal check — a worker's model reaches the documents its own file names, and + * nothing else, on one shared copy of its flow. * - * One workforce tree, read by the real loader. Three seats of one kind, hired - * in one call: one granting a document read-only, one granting a different one - * `rw`, and one naming no documents at all. Each runs an action to completion - * through the real HTTP router, and a block NESTED inside that action tries to - * reach and to write every document the app declared plus the app's own store. - * What it managed is read back through `/state` after the stores are closed and - * the host rebuilt. + * One workforce tree, read by the real loader. Three workers on one flow, + * registered once: one granting a document read-only, one granting another + * `rw`, and one naming no documents at all. Each opens a session on the one + * copy, created naming it, and runs core's model-facing document tools (list, + * read, write, search, the discovery door) and an app tool built on core's + * lookup, as its model would. What each reached is graded off what the tools + * answered. * * Real path, no mocking, no model. See goal.md for the contract. * * Run: pnpm tsx goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/run.mts + * Control: GOAL_CONTROL=no-visibility-rule (the flow sets no rule) must FAIL on + * "the first worker's model lists the second's document". */ -import { mkdtempSync } from "node:fs"; import { DEFAULT_ORG_ID } from "@flow-state-dev/core"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { createFlowApiRouter, createFlowRegistry, type StoreRegistry } from "@flow-state-dev/engine"; -import { createSQLiteStores } from "@flow-state-dev/store-sqlite"; -import { hireWorkforce } from "@flow-state-dev/workforce"; -import { readDeclaredRoster } from "@flow-state-dev/workforce/loader"; import type { FlowInstance } from "@flow-state-dev/core/types"; +import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engine"; +import { createWorkerInstallation, hireWorkforce, resourcesFromDocs } from "@flow-state-dev/workforce"; +import { readDeclaredRoster } from "@flow-state-dev/workforce/loader"; +import { join } from "node:path"; import { fixtureDir, loadFixture, runGoal, silentLogger, stripIntentOverrides } from "../../lib/index.mts"; -import { DESK_KIND, STORE, buildDesk } from "./fixtures/flows"; +import { DESK_KIND, buildDesk } from "./fixtures/flows"; type SeatFixture = { id: string; reaches: string[]; writes: string[] }; type Fixture = { @@ -38,268 +37,196 @@ type Fixture = { stripIntentOverrides(); -const fixture = loadFixture(import.meta.url); -const roster = [fixture.seats.lead, fixture.seats.cfo, fixture.seats.chief]; +const CONTROL = process.env.GOAL_CONTROL ?? ""; +if (CONTROL !== "" && CONTROL !== "no-visibility-rule") throw new Error(`unknown GOAL_CONTROL "${CONTROL}"`); +const fixture = loadFixture(import.meta.url); +const workers = [fixture.seats.lead, fixture.seats.cfo, fixture.seats.chief]; const tree = (name: string): string => join(fixtureDir(import.meta.url), name); - -function host(stores: StoreRegistry, flows: FlowInstance[]) { - const registry = createFlowRegistry(); - registry.registerMany(flows); - return createFlowApiRouter({ registry, stores, runtimeConfig: { logger: silentLogger } } as never); -} - -type Router = ReturnType; - -async function act(router: Router, address: string, sessionId: string): Promise { - const path = [address, sessionId, "actions", "run"]; - return router.POST( - new Request(`http://goal/api/flows/${path.join("/")}`, { - method: "POST", - // No `orgId` — the caller does not supply one (FIX-1442). The server - // binds the session's organization itself, and the seat's org-scoped - // documents are resolved against THAT. An org-injecting wrapper here - // would make this goal prove nothing about the framework. - body: JSON.stringify({ userId: fixture.userId, input: { note: fixture.note } }) - }), - { params: { path } } - ); -} - -/** What a seat's NESTED block actually reached and wrote, through the public route. */ -async function ranOn(router: Router, sessionId: string) { - const path = ["sessions", sessionId, "state"]; - const res = await router.GET(new Request(`http://goal/api/flows/${path.join("/")}`), { - params: { path } +/** A document's uri, as core's tools name it: every document is org-scoped. */ +const uri = (ref: string): string => `org/${ref}`; +const sorted = (values: Iterable): string[] => [...new Set(values)].sort(); +const same = (a: readonly string[], b: readonly string[]): boolean => JSON.stringify(sorted(a)) === JSON.stringify(sorted(b)); +/** The documents among `uris`, as refs. */ +const documentsIn = (uris: readonly string[]): string[] => + sorted(uris.filter((u) => fixture.documents.some((ref) => uri(ref) === u)).map((u) => u.slice("org/".length))); + +/** Build the installation and its copies over `root`, as an app does at boot. */ +async function boot(root: string) { + const declared = await readDeclaredRoster(root); + let flows: Record = {}; + const installation = createWorkerInstallation({ + standardWorkers: declared.workers, + workerFlows: () => flows as never, + documents: resourcesFromDocs(declared.documents), }); - const body = (await res.json()) as { - clientData?: { session?: { ran?: { reach?: string[] | null; wrote?: string[] | null; runs?: number } } }; - }; - return { status: res.status, ...(body.clientData?.session?.ran ?? {}) }; + flows = { [DESK_KIND]: buildDesk(installation, { withoutRule: CONTROL === "no-visibility-rule" }) }; + return { declared, installation, copies: () => hireWorkforce(installation) }; } -async function settled(stores: StoreRegistry, requestId: string): Promise { - for (let i = 0; i < 200; i += 1) { - const record = await stores.request.get(requestId); - if (record !== undefined && record.status !== "in_progress") return record.status; - await new Promise((r) => setTimeout(r, 25)); - } - return undefined; -} - -const messageOf = (error: unknown): string => - error instanceof Error ? error.message : String(error); - -const same = (a: readonly string[], b: readonly string[]): boolean => - JSON.stringify([...a].sort()) === JSON.stringify([...b].sort()); - await runGoal(async () => { const failures: string[] = []; const evidence: string[] = []; - const dir = mkdtempSync(join(tmpdir(), "fsd-seat-resources-")); - const dbFile = join(dir, "goal.db"); - const sessions: Record = Object.fromEntries( - roster.map((seat, i) => [seat.id, `s_seat_${i}`]) - ); - // ---- (a) the real loader reads the tree, and one call hires it ---------- - const declared = await readDeclaredRoster(tree("workforce")); + // ---- (a) the real loader reads the tree; one copy of the flow runs every worker + const { declared, copies: register } = await boot(tree("workforce")); if (declared.problems.length > 0) { failures.push(`the loader reported ${declared.problems.length} problem(s): ${JSON.stringify(declared.problems.map((p) => `${p.layer} ${p.path}: ${p.error.message}`))}`); } - if (declared.workers.length !== roster.length) { - failures.push(`the tree produced ${declared.workers.length} record(s), wanted ${roster.length}`); + if (!same(declared.workers.map((w) => w.id), workers.map((w) => w.id))) { + failures.push(`the tree produced workers ${JSON.stringify(declared.workers.map((w) => w.id))}, wanted ${JSON.stringify(workers.map((w) => w.id))}`); } if (!same(declared.documents.map((d) => d.ref), fixture.documents)) { - failures.push( - `the tree produced documents ${JSON.stringify(declared.documents.map((d) => d.ref))}, wanted ${JSON.stringify(fixture.documents)}` - ); + failures.push(`the tree produced documents ${JSON.stringify(declared.documents.map((d) => d.ref))}, wanted ${JSON.stringify(fixture.documents)}`); } - - const { deskFlow, catalog } = buildDesk(declared.documents); - const kinds = { [DESK_KIND]: deskFlow as never }; - - const seats = hireWorkforce(declared.workers, { workerFlows: kinds, documents: catalog }); - if (seats.length !== roster.length) failures.push(`hired ${seats.length} seat(s), wanted ${roster.length}`); - evidence.push( - `the real loader read ${declared.workers.length} seat files and ${declared.documents.length} documents, and one hireWorkforce call turned them into ${seats.length} seats of one kind` - ); - - // ---- (b) every seat RUNS, through the real route ------------------------ - let stores: StoreRegistry = createSQLiteStores({ filename: dbFile }) as unknown as StoreRegistry; - { - const router = host(stores, seats); - for (const seat of roster) { - const res = await act(router, seat.id, sessions[seat.id]!); - const body = (await res.json()) as { request?: { id: string } }; - if (res.status !== 202) { - failures.push(`${seat.id}: expected 202 from its own address, got ${res.status}`); - continue; + const copies = register(); + const desks = copies.filter((copy) => copy.kind === DESK_KIND); + if (desks.length !== 1 || desks[0]!.id !== DESK_KIND) { + failures.push(`${desks.length} copies of "${DESK_KIND}" registered (${desks.map((c) => c.id).join(", ")}), wanted one, at its kind`); + } + if (copies.some((copy) => workers.some((w) => w.id === copy.id))) failures.push("a copy was registered at a worker's id"); + const desk = desks[0] as FlowInstance; + + const state = createFlowState({ + flows: Object.fromEntries(copies.map((copy) => [copy.id, copy])), + stores: { default: { primary: inMemoryStores() } }, + } as never); + try { + const runtime = await state.getRuntime(); + const router = await state.getRouter(); + + /** Open a session on the one desk copy, naming `worker`. */ + const open = async (worker: string): Promise => { + const sessionId = `s_${worker.replace(/\W/g, "_")}`; + const path = [DESK_KIND, "sessions"]; + const res = await router.POST( + new Request(`http://goal/api/flows/${path.join("/")}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ userId: fixture.userId, sessionId, state: { workerId: worker } }), + }), + { params: { path } }, + ); + if (res.status !== 201) throw new Error(`the session naming "${worker}" was not created: ${res.status} ${await res.text()}`); + return sessionId; + }; + /** Run one of the copy's tools in `sessionId`, as its worker's model would. */ + const tool = async (sessionId: string, actionName: string, input: unknown) => { + const result = await runAction({ + orgId: DEFAULT_ORG_ID, + flow: desk, + actionName, + input, + userId: fixture.userId, + sessionId, + stores: runtime.stores, + runtimeConfig: { ...runtime.runtimeConfig, logger: silentLogger }, + }); + const error = result.error as { message?: unknown } | undefined; + return { output: result.output as any, error: error === undefined ? undefined : String(error.message ?? error) }; + }; + + const seen: Record = {}; + const sessions: Record = {}; + for (const worker of workers) sessions[worker.id] = await open(worker.id); + + // ---- (b) what each worker's model lists, searches and discovers ------ + for (const worker of workers) { + const sessionId = sessions[worker.id]!; + const listed = await tool(sessionId, "read", {}); + const globbed = await tool(sessionId, "glob", {}); + const grepped = await tool(sessionId, "grep", { pattern: "#" }); + const discovered = await tool(sessionId, "discover", {}); + for (const [name, answered] of Object.entries({ listed, globbed, grepped, discovered })) { + if (answered.error !== undefined) failures.push(`${worker.id}: ${name} failed: ${answered.error}`); } - const requestId = body.request?.id; - if (requestId === undefined) { - failures.push(`${seat.id}: accepted with 202 but the response carried no request id`); - continue; + const lists = documentsIn(listed.output?.uris ?? []); + seen[worker.id] = lists; + const views: Record = { + lists, + "glob finds": documentsIn(globbed.output?.uris ?? []), + "grep finds": documentsIn((grepped.output?.matches ?? []).map((m: { uri: string }) => m.uri)), + "discover names": fixture.documents.filter((ref) => JSON.stringify(discovered.output ?? {}).includes(uri(ref))), + }; + for (const [view, refs] of Object.entries(views)) { + if (!same(refs, worker.reaches)) { + failures.push(`${worker.id}'s model ${view} ${JSON.stringify(refs)}, its file grants ${JSON.stringify(worker.reaches)}`); + } } - const status = await settled(stores, requestId); - if (status !== "completed") failures.push(`${seat.id}: request ended ${String(status)}`); - } - evidence.push("all three seats ran an action to completion through the real HTTP route, with no model call"); - - // ---- (b2) the STORED identity, and that it is stable ------------------ - // - // The documents these seats read are org-scoped, so the organization the - // server bound each session to is what the whole check above resolves - // against. Nothing in this run supplied one: the property is that the - // framework did, that it is the development default, and — the part a - // single request cannot show — that a SECOND request on the same session - // resolves the same organization rather than a fresh one. - for (const seat of roster) { - const stored = await stores.session.get(sessions[seat.id]!); - if (stored?.orgId !== DEFAULT_ORG_ID) { - failures.push( - `${seat.id}: its session stored orgId ${JSON.stringify(stored?.orgId)}, wanted the framework default` - ); + // The control's named assertion: the first worker's model must not list the second's document. + if (worker === workers[0]) { + const theirs = workers[1]!.reaches.filter((ref) => !worker.reaches.includes(ref)); + const leaked = lists.filter((ref) => theirs.includes(ref)); + if (leaked.length > 0) failures.push(`the first worker's model lists the second's document: ${worker.id} lists ${JSON.stringify(leaked)}`); } } - // A session of its own, so this probe does not disturb the per-seat run - // counts the checks below read. - const probeSession = "s_org_stability_probe"; - const first = await act(router, roster[0]!.id, probeSession); - if (first.status === 202) { - const firstId = ((await first.json()) as { request?: { id: string } }).request?.id; - if (firstId !== undefined) await settled(stores, firstId); - } - const second = await act(router, roster[0]!.id, probeSession); - if (second.status !== 202) { - failures.push( - `a second request on an existing session was not admitted (${second.status}) — the organization the server resolves is not stable across requests` - ); - } else { - // Settled before the store closes below, so the run does not outlive its - // own connection. - const secondId = ((await second.json()) as { request?: { id: string } }).request?.id; - if (secondId !== undefined) { - const status = await settled(stores, secondId); - if (status !== "completed") { - failures.push(`the second request on an existing session ended ${String(status)}`); + // ---- (c) a document it isn't granted answers as one that doesn't exist + const missing = "org/no-such-document"; + for (const worker of workers) { + const sessionId = sessions[worker.id]!; + for (const ref of fixture.documents) { + const read = await tool(sessionId, "read", { uri: uri(ref) }); + const peeked = await tool(sessionId, "peek", { uri: uri(ref) }); + if (worker.reaches.includes(ref)) { + if (read.error !== undefined || typeof read.output?.content !== "string") failures.push(`${worker.id} can't read ${ref}, which its file grants: ${read.error}`); + if (peeked.output?.found !== true) failures.push(`${worker.id}'s app tool doesn't find ${ref}, which its file grants`); + continue; + } + const absent = await tool(sessionId, "read", { uri: missing }); + if (read.error === undefined) failures.push(`${worker.id}'s model read ${ref}, which its file doesn't grant`); + else if (read.error !== absent.error?.replace(missing, uri(ref))) { + failures.push(`${worker.id} reading ${ref} answered "${read.error}", not what a missing document answers ("${absent.error}")`); + } + if (peeked.output?.found !== false) failures.push(`${worker.id}'s app tool found ${ref}, which its file doesn't grant`); + const write = await tool(sessionId, "write", { uri: uri(ref), content: "rewritten" }); + const absentWrite = await tool(sessionId, "write", { uri: missing, content: "rewritten" }); + if (write.error === undefined) failures.push(`${worker.id}'s model wrote ${ref}, which its file doesn't grant`); + else if (write.error !== absentWrite.error?.replace(missing, uri(ref))) { + failures.push(`${worker.id} writing ${ref} answered "${write.error}", not what a missing document answers ("${absentWrite.error}")`); } } } - evidence.push( - `every seat's session was stored bound to "${DEFAULT_ORG_ID}" though no caller named one, and a second request on an existing session resolved the same organization and was admitted` - ); - } - - (stores as unknown as { close(): void }).close(); - stores = createSQLiteStores({ filename: dbFile }) as unknown as StoreRegistry; - { - const router = host(stores, seats); - // ---- (c) each seat reached exactly what its own file named ----------- - // - // Graded from what the RUNNING BLOCK managed, never off the returned - // instance: a map asserted on `seat.resources` proves the mint and nothing - // about what a block holds. `wrote` is a real `setState`, not a flag. - const seen: Record = {}; - for (const seat of roster) { - const ran = await ranOn(router, sessions[seat.id]!); - if (ran.status !== 200) failures.push(`${seat.id}: /state returned ${ran.status}`); - if (ran.runs !== 1) failures.push(`${seat.id}: ran ${String(ran.runs)} times`); - - const reach = ran.reach ?? []; - const wrote = ran.wrote ?? []; - seen[seat.id] = { reach, wrote }; - - // The store is the app's own and belongs to no grant, so it is compared - // separately — see (d). Here the documents alone. - const documentsReached = reach.filter((key) => key !== fixture.store); - const documentsWritten = wrote.filter((key) => key !== fixture.store); - - if (!same(documentsReached, seat.reaches)) { - failures.push( - `${seat.id}: reached documents ${JSON.stringify(documentsReached)}, its file names ${JSON.stringify(seat.reaches)}` - ); - } - if (!same(documentsWritten, seat.writes)) { - failures.push( - `${seat.id}: wrote documents ${JSON.stringify(documentsWritten)}, its file grants ${JSON.stringify(seat.writes)}` - ); + // ---- (d) a read-only grant can't be written; an `rw` grant can -------- + for (const worker of workers) { + const sessionId = sessions[worker.id]!; + const wrote: string[] = []; + for (const ref of worker.reaches) { + const write = await tool(sessionId, "write", { uri: uri(ref), content: `${worker.id} was here` }); + if (write.error === undefined) wrote.push(ref); } + if (!same(wrote, worker.writes)) failures.push(`${worker.id}'s model wrote ${JSON.stringify(sorted(wrote))}, its file lets it write ${JSON.stringify(worker.writes)}`); } - evidence.push( - "after closing the store and rebuilding the host, each seat's nested block reached exactly the documents its own file names — the read-only grant read its document and could not write it, the rw grant wrote its own, and neither could see the other's" - ); - // ---- (d) the app's own store is not what a grant governs ------------- - // - // BR-15, on the real path. Without this the whole check is equally green - // for a resolver that narrows to the granted documents alone and silently - // deletes everything else the app declared at flow level. - for (const seat of roster) { - const { reach, wrote } = seen[seat.id] ?? { reach: [], wrote: [] }; - if (!reach.includes(fixture.store)) { - failures.push(`${seat.id}: lost the app's own "${fixture.store}", which no seat file mentions`); - } - if (!wrote.includes(fixture.store)) { - failures.push(`${seat.id}: could not write the app's own "${fixture.store}"`); - } - } + // ---- (e) one copy, and still no two workers reached the same set ------ + const sets = workers.map((w) => JSON.stringify(seen[w.id] ?? [])); + if (new Set(sets).size !== sets.length) failures.push(`two workers on the one copy reached the same documents: ${JSON.stringify(seen)}`); + evidence.push( - `all three seats still reach and write the app's own "${STORE}", which no grant names and none may narrow` + `one "${DESK_KIND}" copy ran ${workers.length} workers: ` + + workers.map((w) => `${w.id} lists ${JSON.stringify(seen[w.id])} and writes ${JSON.stringify(w.writes)}`).join("; ") + + `; another worker's document read, wrote and was looked up as one that doesn't exist`, ); + } finally { + await state.dispose(); + } - // ---- (e) two seats of one kind really do differ ---------------------- - // - // The anti-game. A single shared map is always right for somebody, and - // (c) alone would pass for a kind that narrowed once for all three. - const lead = seen[fixture.seats.lead.id]?.reach ?? []; - const cfo = seen[fixture.seats.cfo.id]?.reach ?? []; - const chief = seen[fixture.seats.chief.id]?.reach ?? []; - if (same(lead, cfo)) failures.push("the two granted seats reached the same set — one shared map, not two seats' own"); - if (same(lead, chief)) failures.push("a granted seat reached what the ungranted one did — the grant changed nothing"); - evidence.push("no two of the three seats reached the same set, so the narrowing is per seat and not per kind"); - - // ---- (f) control: a ref that matches no document refuses ------------- - { - const typo = await readDeclaredRoster(tree(fixture.control.dir)); - let hired: FlowInstance[] | undefined; - let refusal = ""; - try { - hired = hireWorkforce([...declared.workers, ...typo.workers], { workerFlows: kinds, documents: catalog }); - } catch (error) { - refusal = messageOf(error); - } - if (hired !== undefined) { - failures.push(`a seat granting a ref no document matches hired ${hired.length} seat(s) instead of refusing`); - } else { - for (const name of [fixture.control.id, fixture.control.ref]) { - if (!refusal.includes(name)) failures.push(`the refusal does not name "${name}": ${refusal}`); - } - // A refusal after a partial hire is not a refusal. Asserted on the - // refusal itself, which is the only place the fact is observable: - // `hireWorkforce` returns its seats, so when it throws there is no - // array to inspect and a host built from one would be empty whatever - // happened. The message says how many of how many, and that nothing - // was hired — both of which change the moment the whole roster stops - // being the unit. - const total = declared.workers.length + typo.workers.length; - if (!refusal.includes("nothing was hired")) { - failures.push(`the refusal does not say nothing was hired: ${refusal}`); - } - if (!refusal.includes(`of ${total} workers`)) { - failures.push( - `the refusal is not against the whole roster of ${total}: ${refusal}` - ); - } - } - evidence.push( - "a seat file granting a ref no document matches refuses the whole roster at the hire, naming the seat and the ref, and reports nothing hired against the whole roster's count" - ); - } + // ---- (f) a file granting a ref no document matches registers nothing ---- + const typo = await boot(tree(fixture.control.dir)); + let refusal = ""; + let registered = -1; + try { + registered = typo.copies().length; + } catch (error) { + refusal = error instanceof Error ? error.message : String(error); + } + if (registered >= 0) failures.push(`a tree granting "${fixture.control.ref}" registered ${registered} copies instead of refusing`); + else if (!refusal.includes(fixture.control.id) || !refusal.includes(fixture.control.ref) || !refusal.includes("nothing was registered")) { + failures.push(`the refusal did not name the worker, the ref and that nothing was registered: ${refusal}`); + } else { + evidence.push(`a tree granting "${fixture.control.ref}" registered nothing, naming ${fixture.control.id}`); } - (stores as unknown as { close(): void }).close(); return { failures, evidence: evidence.join("; ") }; }); diff --git a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/flows.ts b/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/flows.ts deleted file mode 100644 index f6cf2cce7d..0000000000 --- a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/flows.ts +++ /dev/null @@ -1,187 +0,0 @@ -/** - * The two worker flow kinds an app defines in code — what a worker's folder - * points at, never what the folder builds. - * - * Both compose the admission contract, as every hireable kind must. One is - * opinionated — it REQUIRES `instructions`, so a seat of that kind without a - * body is a failed hire. One is thin: it requires only a setting of its own and - * leaves the contract's instructions door empty. - * - * Both read their settings from a block NESTED inside the action sequencer - * rather than at the root, because a read that works at the root proves nothing - * about the context spread that carries the value down. Neither calls a model: - * the property under test is which settings reach a running block. - */ -import { defineFlow, handler, sequencer } from "@flow-state-dev/core"; -import { workerConfigSchema } from "@flow-state-dev/workforce"; -import { z } from "zod"; -import { workerDoor } from "../../../lib/worker-door.mts"; - -export const CUSTOM_AGENT_KIND = "custom-agent"; -export const INTAKE_KIND = "intake"; -export const NO_CONTRACT_KIND = "legacy-desk"; -export const HAND_ROLLED_KIND = "hand-rolled-desk"; - -const inputSchema = z.object({ note: z.string() }); - -/** What a seat records about itself while running. Shared by both kinds. */ -const seatState = z.object({ - /** The body, as it reached a block — null when the seat carries none. */ - instructions: z.string().nullable().default(null), - model: z.string().nullable().default(null), - desk: z.string().nullable().default(null), - runs: z.number().default(0) -}); - -/** What the opinionated kind's nested block needs of whatever flow installs it. */ -const needsInstructions = z.object({ instructions: z.string(), model: z.string() }); -/** What the thin kind's nested block needs. Note: no instructions. */ -const needsDesk = z.object({ desk: z.string() }); - -/** The root: reads no config at all, so it cannot mask a nested failure. */ -const start = handler({ - name: "seat-start", - inputSchema, - outputSchema: inputSchema, - execute: async (input, ctx) => { - await ctx.session.incState({ runs: 1 }); - return input; - } -}); - -/** Nested read, opinionated kind — the far end of the body's journey. */ -const recordInstructions = handler({ - name: "custom-agent-record", - inputSchema, - outputSchema: z.void(), - flowConfigSchema: needsInstructions, - sessionStateSchema: seatState, - execute: async (_input, ctx) => { - await ctx.session.patchState({ - instructions: ctx.flow.config.instructions, - model: ctx.flow.config.model - }); - } -}); - -/** Nested read, thin kind — writes its own setting and no instructions. */ -const recordDesk = handler({ - name: "intake-record", - inputSchema, - outputSchema: z.void(), - flowConfigSchema: needsDesk, - sessionStateSchema: seatState, - execute: async (_input, ctx) => { - await ctx.session.patchState({ desk: ctx.flow.config.desk }); - } -}); - -const clientView = { - derived: { - ran: (ctx: { - state: { instructions?: string | null; model?: string | null; desk?: string | null; runs?: number }; - }) => ({ - instructions: ctx.state.instructions ?? null, - model: ctx.state.model ?? null, - desk: ctx.state.desk ?? null, - runs: ctx.state.runs ?? 0 - }) - } -}; - -export const customAgentFlow = defineFlow({ - kind: CUSTOM_AGENT_KIND, - cardinality: "collection", - configSchema: workerConfigSchema().extend({ - /** - * REQUIRED here, which is this kind's own call: the contract's own - * `instructions` is optional, and a kind is free to tighten it. That is - * what makes this kind opinionated — a seat of this kind without - * instructions is a failed hire. - */ - instructions: z.string(), - model: z.string().default("openai/gpt-5.4-mini"), - tools: z.array(z.string()).default([]) - }), - actions: { ...workerDoor, - run: { inputSchema, block: sequencer({ name: "custom-agent-work", inputSchema }).step(start).tap(recordInstructions) } - }, - session: { stateSchema: seatState, client: clientView } -}); - -export const intakeFlow = defineFlow({ - kind: INTAKE_KIND, - cardinality: "collection", - // Thin in what it REQUIRES, not in what it admits. It composes the contract - // like every hireable kind, so `instructions` is a door it has and leaves - // empty; the seat under it carries none because its record has no body. - configSchema: workerConfigSchema().extend({ desk: z.string().default("front") }), - actions: { ...workerDoor, - run: { inputSchema, block: sequencer({ name: "intake-work", inputSchema }).step(start).tap(recordDesk) } - }, - session: { stateSchema: seatState, client: clientView } -}); - -/** - * A kind whose schema **cannot accept the bag hire imposes** — it declares - * `instructions` but not `seatSkills`. - * - * Deliberately not "a kind with no contract keys at all". That version refused - * too, but for a reason that only *coincided* with the rule: stripping the - * helper also stripped the keys, so the observed refusal was equally consistent - * with hire checking whether `workerConfigSchema()` was called. It is not — see - * `handRolledFlow` below. This kind isolates the real cause by declaring part - * of the contract and still missing a key the bag carries. - */ -export const noContractFlow = defineFlow({ - kind: NO_CONTRACT_KIND, - cardinality: "collection", - configSchema: z.object({ - instructions: z.string().optional(), - teamInstructions: z.string().optional(), - // Declared so `seatSkills` stays the SINGLE missing key: the contract grew a - // fourth, and a control that omitted two would no longer isolate one cause. - seatTools: z.array(z.any()).default([]), - // The packages a seat holds, checked at boot like every other key. - seatPackages: z.array(z.any()).optional(), - // The sixth, imposed on every seat: its own id. - seatId: z.string().optional(), - // `seatSkills` is absent — the one key that makes the bag unacceptable. - desk: z.string().default("front") - }), - actions: { ...workerDoor, - run: { inputSchema, block: sequencer({ name: "legacy-work", inputSchema }).step(start).tap(recordDesk) } - }, - session: { stateSchema: seatState, client: clientView } -}); - -/** - * The other half of the same rule, and the reason the refusal above means what - * it says: a schema that accepts the imposed bag **without ever calling - * `workerConfigSchema()`** hires exactly like a composed kind. - * - * Without this, the goal would certify a nominal invariant the implementation - * rejects — "a kind that did not call the helper refuses" — which is true of - * its fixture and false of the system. - */ -export const handRolledFlow = defineFlow({ - kind: HAND_ROLLED_KIND, - cardinality: "collection", - configSchema: z.object({ - instructions: z.string().optional(), - teamInstructions: z.string().optional(), - seatSkills: z.array(z.object({ name: z.string(), skillMd: z.string() }).passthrough()).default([]), - // The fourth contract key. A hand-rolled schema has to add each one as the - // contract grows — which is the cost this fixture exists to show, not a - // reason to stop hand-rolling. - seatTools: z.array(z.any()).default([]), - seatPackages: z.array(z.any()).optional(), - // The sixth, imposed on every seat: its own id. - seatId: z.string().optional(), - desk: z.string().default("front") - }), - actions: { ...workerDoor, - run: { inputSchema, block: sequencer({ name: "hand-rolled-work", inputSchema }).step(start).tap(recordDesk) } - }, - session: { stateSchema: seatState, client: clientView } -}); diff --git a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/input.json b/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/input.json deleted file mode 100644 index 1083126d5d..0000000000 --- a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/input.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "userId": "u_workforce_goal", - "note": "Take a look at the board and tell me what is blocked.", - "roster": { - "lead": { - "id": "engineering.lead", - "flow": "custom-agent", - "description": "Holds the engineering board and breaks work into tasks.", - "model": "openai/gpt-5.4", - "tools": [ - "board", - "search" - ], - "body": "You are the engineering lead. You do not write code yourself — you break the\nrequest into tasks, assign them, and report what came back." - }, - "intake": { - "id": "engineering.intake", - "flow": "intake", - "description": "The front door. Routes an incoming request to whoever should hold it.", - "desk": "mezzanine" - } - }, - "refusals": { - "unknownKind": { - "dir": "unknown-kind", - "id": "engineering.scribe", - "flow": "note-taker", - "description": "Writes the meeting up afterwards.", - "body": "You take notes and post a summary." - }, - "undeclaredSetting": { - "dir": "undeclared-setting", - "id": "engineering.analyst", - "flow": "custom-agent", - "description": "Reads the numbers.", - "key": "temperature", - "value": "0.2", - "body": "You read the numbers and say what changed." - }, - "noContract": { - "dir": "no-contract", - "id": "engineering.legacy", - "flow": "legacy-desk", - "description": "An older desk, still on a flow kind that predates the admission contract.", - "body": "You hold the older desk and pass anything you cannot place to the front door." - } - }, - "thinWithBody": { - "dir": "thin-with-body", - "id": "engineering.intake", - "flow": "intake", - "description": "The front door. Routes an incoming request to whoever should hold it.", - "body": "You greet whoever arrives and pass them on to the right desk." - } -} diff --git a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/no-contract/teams/engineering/workers/legacy/WORKER.md b/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/no-contract/teams/engineering/workers/legacy/WORKER.md deleted file mode 100644 index 8cec5740d0..0000000000 --- a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/no-contract/teams/engineering/workers/legacy/WORKER.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -description: An older desk, still on a flow kind that predates the admission contract. -flow: legacy-desk ---- - -You hold the older desk and pass anything you cannot place to the front door. diff --git a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/teams/engineering/workers/intake/WORKER.md b/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/teams/engineering/workers/intake/WORKER.md deleted file mode 100644 index cf0a2d0f39..0000000000 --- a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/teams/engineering/workers/intake/WORKER.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -description: The front door. Routes an incoming request to whoever should hold it. -flow: intake -desk: mezzanine ---- diff --git a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/teams/engineering/workers/lead/WORKER.md b/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/teams/engineering/workers/lead/WORKER.md deleted file mode 100644 index 566841ca1e..0000000000 --- a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/teams/engineering/workers/lead/WORKER.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -description: Holds the engineering board and breaks work into tasks. -flow: custom-agent -model: openai/gpt-5.4 -tools: [board, search] ---- - -You are the engineering lead. You do not write code yourself — you break the -request into tasks, assign them, and report what came back. diff --git a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/thin-with-body/teams/engineering/workers/intake/WORKER.md b/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/thin-with-body/teams/engineering/workers/intake/WORKER.md deleted file mode 100644 index 163cbf4a53..0000000000 --- a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/thin-with-body/teams/engineering/workers/intake/WORKER.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -description: The front door. Routes an incoming request to whoever should hold it. -flow: intake ---- - -You greet whoever arrives and pass them on to the right desk. diff --git a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/undeclared-setting/teams/engineering/workers/analyst/WORKER.md b/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/undeclared-setting/teams/engineering/workers/analyst/WORKER.md deleted file mode 100644 index c68936d445..0000000000 --- a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/undeclared-setting/teams/engineering/workers/analyst/WORKER.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -description: Reads the numbers. -flow: custom-agent -temperature: "0.2" ---- - -You read the numbers and say what changed. diff --git a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/unknown-kind/teams/engineering/workers/scribe/WORKER.md b/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/unknown-kind/teams/engineering/workers/scribe/WORKER.md deleted file mode 100644 index 177ac54a2a..0000000000 --- a/goals/workforce-seats/two-seats-run-their-own-configuration/fixtures/unknown-kind/teams/engineering/workers/scribe/WORKER.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -description: Writes the meeting up afterwards. -flow: note-taker ---- - -You take notes and post a summary. diff --git a/goals/workforce-seats/two-seats-run-their-own-configuration/goal.md b/goals/workforce-seats/two-seats-run-their-own-configuration/goal.md deleted file mode 100644 index bbcf0afd1e..0000000000 --- a/goals/workforce-seats/two-seats-run-their-own-configuration/goal.md +++ /dev/null @@ -1,34 +0,0 @@ -# workforce-seats › two seats run their own configuration - -**Issue:** FIX-1325 (the seat factory; builds on FIX-1321/1322 cardinality and instance ids, FIX-1323 instance-isolated state, FIX-1331 per-copy settings) -**Outcome:** An app defines two worker flow kinds in code and hires two workers — one opinionated, one thin. Each becomes a copy addressable by its own id, behaving according to the settings its own record declared and none of its sibling's, still true after a restart. The opinionated worker's record body reached its flow as `instructions` and a block nested inside its action ran on it. The thin worker is a fully addressable seat that runs to completion carrying no instructions at all. A record naming a kind the app didn't define, a record declaring a setting its flow never offered, and a record whose flow kind's schema cannot accept the settings hiring imposes all refuse at the hire, with nothing hired and nothing registered. - -**Where the records come from — stated by the run, not chosen by hand.** The two records are produced by the real loader (`readWorkforceDirectory` over `fixtures/teams/`, one folder per worker) when `@flow-state-dev/workforce/loader` exists, and hand-built exactly as `WorkerManifest` declares them when it does not. The selector is the presence of that export — nothing here is a judgement call — and the run prints which source it used as its **first line of output**, repeated in the verdict log below, so a reader can tell which bar a green run cleared without reading the script. Every clause below binds both paths, refusal cases included: the fixture tree is a stronger source for the same records, not a replacement for the checks. - -**Input:** `fixtures/input.json` — the two worker ids with the settings and body each declares, the three bad records (an unknown kind, an undeclared setting, a kind with no contract), and the thin record with a body added. `fixtures/teams/**/WORKER.md` and the three refusal trees beside it carry the same records as files. Held-out: every id, setting and marker is read from the fixture and graded against what the HTTP routes return afterwards; swapping any of them must still pass a correct implementation. **Each declared setting differs from its flow's schema default on purpose** — a setting that was dropped on the way to the flow would otherwise read back as the default and pass. -(0) Before anything runs, every `WORKER.md` in the fixture trees is compared against `input.json` key by key and body by body — whole values, not substrings. The two roster sources cannot drift apart unnoticed, which is what keeps whichever path is *not* running from quietly weakening. -**Signal:** against the real HTTP router (`createFlowApiRouter`) over on-disk SQLite stores, matching its siblings under `goals/flow-instances/`. -(a) One `hireWorkforce` call turns the two records into two flow copies, ordered by id, each carrying its own record's id as its address — not its flow kind. -(b) Each seat runs `POST /api/flows///actions/run` to completion. After closing the stores, reopening the same file and building a fresh host, `GET /api/flows/sessions//state` shows each seat what a block **nested inside its action** read from `ctx.flow.config`: for the opinionated worker, its record's body as `instructions` and its own model; for the thin worker, its own desk, no instructions, and no model. Neither shows the other's value. -(c) `POST` against the bare flow kind — `custom-agent`, `intake` — is a 404 for both. The kind is not an address. -(d) Three bad rosters, each hired alongside the good records: an unknown flow kind, a setting the flow never declared, and a record whose flow kind's schema cannot accept the settings hiring imposes. Each throws, naming the worker and the offending thing (`seatSkills` for the third), returns nothing, and leaves the good worker's address a 404 on a host built from what came back. -(e) The thin seat's own record with a body added hires, and the body arrives in its bag as `instructions`. Graded at the mint, because the claim here is what was *admitted*; that an admitted value reaches a running block is (b)'s claim and is proved there. -(f) A hand-written schema that never calls `workerConfigSchema()` but accepts everything hiring imposes is hired, carrying the imposed `seatSkills`. This is what makes (d) mean what it says: admission is decided by what a schema accepts, not by which helper built it, so a control that merely skipped the helper would prove the wrong rule. - -**Anti-game:** a hollow pass would assert the hires returned and the requests completed — true even when both seats share one settings bag and one silently wins. So the check MUST read the settings back through `/state` rather than off the returned instance, since the question is whether the value reached the running blocks; MUST read them from a NESTED block rather than the action root, because a root-only read proves nothing about the context spread that carries the value down; MUST close the stores and rebuild the host before reading, so nothing is served from a live context; MUST assert each seat's sibling value is **absent** as well as its own present, since one shared bag is always right for somebody; MUST address each worker by the exact id its record carried, since grading `flowKind` proves nothing — both workers of a kind share it; MUST assert the bare kind 404s, since that is the address the slash-separated identity would have answered on; and MUST assert every refusal left **nothing** registered, since a refusal after a partial hire is not a refusal. Thinness is graded as a **pair** over the same record — the thin seat is live and runs carrying no instructions, *and* the identical record with a body added hires carrying exactly that body — because "carries no instructions" alone is satisfied by never hiring the worker at all, and the differential pins the absence on the record rather than on a missing seat. -**Model:** n/a — handlers only. The property under test is which settings reach a running block, not model output; a generator here would add a model call and prove nothing more. -**Run:** `pnpm tsx goals/workforce-seats/two-seats-run-their-own-configuration/run.mts` - -> **On the body's whitespace.** The instructions are graded trimmed on both sides. What travels verbatim is the instructions; the newline a Markdown file ends with belongs to the file, and pinning it would make this goal a test of the loader's trailing-whitespace policy rather than of the body's journey. - -## Verdict log -| Date | Commit | Model | Verdict | Notes | -|------|--------|-------|---------|-------| -| 2026-09-10 | fix/FIX-1325 (pre-PR) | n/a (handlers only) | PASS | **Roster source: hand-built manifests (loader not landed)** — `@flow-state-dev/workforce/loader` does not exist yet, so the run took the fallback half and said so on its first line. One call produced two copies in id order, each carrying its record's id. Both ran an action to completion through the real route. After closing the SQLite file and rebuilding the host, the lead's nested block showed its record's body as `persona` and its own model, with no desk; the intake seat showed its own desk, no persona and no model. Both bare kinds 404'd. The three bad rosters each refused, naming the worker, the offending kind/setting/`persona`, and left the good worker's address a 404. | -| 2026-09-10 | fix/FIX-1325 (control run, one settings bag shared across the roster) | n/a | FAIL (expected) | With the first record's bag reused for every later record — the "settings belong to the roster" shape this design rejects — the hire refused outright: `worker "engineering.lead" — Flow "custom-agent" instance "engineering.lead" has an invalid config bag: "desk" is not a declared setting`. An earlier version of this fixture set the lead's model to the flow's schema default, and under that control the shared bag passed leg (b) unnoticed; the fixture values were changed to differ from their defaults, which is what the "held-out" note above now pins. | -| 2026-09-10 | fix/FIX-1325 (control run, a fixture tree drifted from input.json) | n/a | FAIL (expected) | Changing the lead's `WORKER.md` model to `openai/gpt-5.4-mini` while `input.json` still said `openai/gpt-5.4` was caught by leg (0): *"its WORKER.md declares model: …, input.json says … — the fixture tree and input.json have drifted"*. A first version of this check used `includes` and passed this control, because the drifted value contains the expected one as a prefix; it compares whole values now. | -| 2026-09-10 | fix/FIX-1325 (control run, an empty body folded as `persona: ""`) | n/a | FAIL (expected) | Handing every record's body to its flow — empty ones included — instead of only a non-empty one turned the thin seat into a failed hire: `worker "engineering.intake" — Flow "intake" instance "engineering.intake" has an invalid config bag: "persona" is not a declared setting`. This is the trap the spec's implementer notes name: an empty string is not "no instructions". | -| 2026-09-10 | fix/FIX-1344-instructions-key (pre-PR) | n/a (handlers only) | PASS | **Roster source: `readWorkforceDirectory(fixtures/teams)`** — the loader path, not the hand-built fallback. Re-run after the seat factory's imposed setting was respelled `instructions`. One call produced two copies in id order; both ran an action to completion through the real HTTP route; after closing the SQLite file and rebuilding the host, the lead's nested block showed its record's body as `instructions` and its own model, and the intake seat showed its own desk with neither. Both bare kinds 404'd; the three bad rosters each refused and left the good worker's address a 404. | -| 2026-09-10 | fix/FIX-1344-instructions-key (control run, the imposed key left as `persona`) | n/a | FAIL (expected) | With the factory still handing the body over as `persona` while the fixture flow declares `instructions`, leg (a) refused before anything ran: `worker "engineering.lead" — … "instructions": Required; "persona" is not a declared setting`. Confirms the goal actually reads the imposed key rather than passing on the seats merely existing. | -| 2026-09-17 | fix/FIX-1367 (pre-PR) | n/a (handlers only) | PASS | **Roster source: `readWorkforceDirectory(fixtures/teams)`.** Re-run after every hireable kind began composing the admission contract. Legs (a)–(c) unchanged. Leg (d)'s third case **changed**: "a body handed to a flow kind that never declared one" is no longer reachable — `instructions` is one of the three settings every composed kind admits, so no kind can refuse a body — and its place is taken by a kind whose schema cannot accept the imposed bag, which refuses naming `engineering.legacy` and `seatSkills`. The thinness pair moved to leg (e) and is now a differential over one record rather than a positive and a refusal. | -| 2026-09-17 | fix/FIX-1367 (review round 6) | n/a (handlers only) | PASS | **Leg (d)'s control was rebuilt, because it passed for the wrong reason.** Its kind declared no contract keys at all, so removing the helper also removed the keys — the refusal was equally consistent with hire checking whether `workerConfigSchema()` was called, which it does not and cannot. The control now declares `instructions` and `teamInstructions` but omits `seatSkills`, so the refusal can only be about a bag the schema will not take, and it is graded on `seatSkills` rather than on the helper's name. New **leg (f)** is the other half: a hand-written schema that never calls the helper but accepts everything hire imposes, which hires exactly like a composed kind. Without (f) this goal certified a nominal invariant the implementation rejects. | diff --git a/goals/workforce-seats/two-seats-run-their-own-configuration/run.mts b/goals/workforce-seats/two-seats-run-their-own-configuration/run.mts deleted file mode 100644 index 1c540289e3..0000000000 --- a/goals/workforce-seats/two-seats-run-their-own-configuration/run.mts +++ /dev/null @@ -1,594 +0,0 @@ -/** - * Goal check — a described worker becomes one you can talk to. - * - * Two worker records, two flow kinds an app defined in code, one call. Each - * worker becomes a copy addressable by its own id, running on the settings its - * own record declared and none of its sibling's — read back through the real - * HTTP router after a restart, from a block nested inside the action. A record - * naming a kind nobody defined, one declaring a setting its flow never offered, - * and a body handed to a flow kind that never asked for one all refuse at the - * hire, with nothing registered. - * - * Real path, no mocking, no model. See goal.md for the contract. - * - * Run: pnpm tsx goals/workforce-seats/two-seats-run-their-own-configuration/run.mts - */ -import { mkdtempSync, readFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { createFlowApiRouter, createFlowRegistry, type StoreRegistry } from "@flow-state-dev/engine"; -import { createSQLiteStores } from "@flow-state-dev/store-sqlite"; -import { hireWorkforce, type HireOptions, type WorkerManifest } from "@flow-state-dev/workforce"; -import type { FlowInstance } from "@flow-state-dev/core/types"; -import { fixtureDir, loadFixture, runGoal, silentLogger, stripIntentOverrides } from "../../lib/index.mts"; -import { - INTAKE_KIND, - CUSTOM_AGENT_KIND, - NO_CONTRACT_KIND, - HAND_ROLLED_KIND, - intakeFlow, - customAgentFlow, - noContractFlow, - handRolledFlow -} from "./fixtures/flows"; - -type LeadFixture = { - id: string; - flow: string; - description: string; - model: string; - tools: string[]; - body: string; -}; -type IntakeFixture = { id: string; flow: string; description: string; desk: string }; -type RefusalFixture = { - dir: string; - id: string; - flow: string; - description: string; - body: string; - key?: string; - value?: string; -}; -type Fixture = { - userId: string; - note: string; - roster: { lead: LeadFixture; intake: IntakeFixture }; - refusals: { - unknownKind: RefusalFixture; - undeclaredSetting: RefusalFixture; - noContract: RefusalFixture; - }; - /** - * The thin seat's own record with a body added. No longer a refusal: every - * hireable kind composes the admission contract, so `instructions` is a door - * every kind has. It is the second half of the thinness pair instead — the - * same record, hiring, carrying the body its file wrote. - */ - thinWithBody: RefusalFixture; -}; - -stripIntentOverrides(); - -const fixture = loadFixture(import.meta.url); -const { lead, intake } = fixture.roster; - -const kinds: HireOptions["workerFlows"] = { - [CUSTOM_AGENT_KIND]: customAgentFlow, - [INTAKE_KIND]: intakeFlow, - // The positive control for the structural rule: a hand-written schema that - // accepts the imposed bag, which hires exactly like a composed one. - [HAND_ROLLED_KIND]: handRolledFlow -}; - -/** - * The same flows with the control added. Passed so the refusal it earns is - * about a bag its schema cannot take, and not about a kind the app forgot to - * register — two different failures. Kept off `kinds`: a worker flow that - * misses the contract refuses the whole installation at boot. - */ -const withNoContract: HireOptions["workerFlows"] = { ...kinds, [NO_CONTRACT_KIND]: noContractFlow }; - -// --------------------------------------------------------------------------- -// Where the records come from. The selector is mechanical — the presence of the -// loader export, never a judgement call — and the run says which half it took, -// so a reader can tell which bar a green run cleared. -// --------------------------------------------------------------------------- - -type LoaderModule = { - readWorkforceDirectory?: (root: string) => Promise<{ workers: WorkerManifest[] }>; -}; - -/** Not a literal specifier: the subpath does not exist until the loader lands. */ -const LOADER_SPECIFIER = "@flow-state-dev/workforce/loader"; - -const loader: LoaderModule | undefined = await import(LOADER_SPECIFIER).then( - (mod: LoaderModule) => (typeof mod.readWorkforceDirectory === "function" ? mod : undefined), - () => undefined -); - -const rosterSource = loader - ? `readWorkforceDirectory(fixtures/teams)` - : "hand-built manifests (loader not landed)"; -console.log(`roster source: ${rosterSource}`); - -/** Hand-built exactly as the shared record type declares it. */ -function handBuilt(over: { - id: string; - declared: Record; - body?: string; -}): WorkerManifest { - return { id: over.id, declared: over.declared, body: over.body ?? "" }; -} - -const handBuiltRosters: Record = { - teams: [ - handBuilt({ - id: lead.id, - declared: { - description: lead.description, - flow: lead.flow, - model: lead.model, - tools: lead.tools - }, - body: lead.body - }), - handBuilt({ - id: intake.id, - declared: { description: intake.description, flow: intake.flow, desk: intake.desk } - }) - ], - [fixture.refusals.unknownKind.dir]: [ - handBuilt({ - id: fixture.refusals.unknownKind.id, - declared: { - description: fixture.refusals.unknownKind.description, - flow: fixture.refusals.unknownKind.flow - }, - body: fixture.refusals.unknownKind.body - }) - ], - [fixture.refusals.undeclaredSetting.dir]: [ - handBuilt({ - id: fixture.refusals.undeclaredSetting.id, - declared: { - description: fixture.refusals.undeclaredSetting.description, - flow: fixture.refusals.undeclaredSetting.flow, - [fixture.refusals.undeclaredSetting.key!]: fixture.refusals.undeclaredSetting.value - }, - body: fixture.refusals.undeclaredSetting.body - }) - ], - [fixture.refusals.noContract.dir]: [ - handBuilt({ - id: fixture.refusals.noContract.id, - declared: { - description: fixture.refusals.noContract.description, - flow: fixture.refusals.noContract.flow - }, - body: fixture.refusals.noContract.body - }) - ], - [fixture.thinWithBody.dir]: [ - handBuilt({ - id: fixture.thinWithBody.id, - declared: { - description: fixture.thinWithBody.description, - flow: fixture.thinWithBody.flow - }, - body: fixture.thinWithBody.body - }) - ] -}; - -/** - * The `WORKER.md` a record's id maps to — which is also the folder convention - * under test: "engineering.lead" lives at teams/engineering/workers/lead/. - */ -function workerFile(tree: string, id: string): string { - const [team, name] = id.split("."); - const base = tree === "teams" ? fixtureDir(import.meta.url) : join(fixtureDir(import.meta.url), tree); - return join(base, "teams", team ?? "", "workers", name ?? "", "WORKER.md"); -} - -/** - * What a `WORKER.md` declares: its frontmatter keys, and the body under them. - * - * Not a loader — it produces no records and nothing under test consumes it. - * It exists only to compare the two fixture sources to each other. - */ -function declarationsOf(text: string): { front: Map; body: string } { - const parsed = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(text); - if (parsed === null) return { front: new Map(), body: text.trim() }; - const front = new Map(); - for (const line of (parsed[1] ?? "").split("\n")) { - const at = line.indexOf(":"); - if (at <= 0) continue; - front.set(line.slice(0, at).trim(), line.slice(at + 1).trim().replace(/^"(.*)"$/, "$1")); - } - return { front, body: (parsed[2] ?? "").trim() }; -} - -/** - * What keeps the two roster sources honest. - * - * The fixture tree is what the loader path reads; `input.json` is what every - * assertion grades against and what the hand-built path builds from. Nothing - * would otherwise notice them drifting apart — a model string changed in one - * and not the other would quietly weaken whichever path is not running. Values - * are compared whole: a substring check would let "openai/gpt-5.4-mini" pass - * for "openai/gpt-5.4". - * - * **Temporary, and delete it here rather than move it.** This exists only while - * the fixture tree goes unread. Once `readWorkforceDirectory` lands, the run - * takes the loader path, the tree becomes the roster the assertions grade, and - * a drift between the two sources fails on its own — so this check, and the - * `declarationsOf` parse under it, go with it. - */ -function declares(tree: string, id: string, expected: Record, body: string): string[] { - const path = workerFile(tree, id); - let text: string; - try { - text = readFileSync(path, "utf8"); - } catch { - return [`${id}: no WORKER.md at ${path}`]; - } - const seen = declarationsOf(text); - const drift = Object.entries(expected) - .filter(([key, value]) => seen.front.get(key) !== value) - .map( - ([key, value]) => - `${id}: its WORKER.md declares ${key}: ${JSON.stringify(seen.front.get(key) ?? null)}, input.json says ` + - `${JSON.stringify(value)} — the fixture tree and input.json have drifted` - ); - if (seen.body !== body.trim()) { - drift.push(`${id}: its WORKER.md body differs from the one in input.json — the two sources have drifted`); - } - return drift; -} - -/** One fixture tree's records, from whichever source this run is using. */ -async function roster(tree: string): Promise { - if (loader?.readWorkforceDirectory) { - const root = tree === "teams" ? fixtureDir(import.meta.url) : join(fixtureDir(import.meta.url), tree); - const { workers } = await loader.readWorkforceDirectory(root); - return workers; - } - return handBuiltRosters[tree]!; -} - -// --------------------------------------------------------------------------- -// The host. -// --------------------------------------------------------------------------- - -function host(stores: StoreRegistry, flows: FlowInstance[]) { - const registry = createFlowRegistry(); - registry.registerMany(flows); - return createFlowApiRouter({ registry, stores, runtimeConfig: { logger: silentLogger } } as never); -} - -type Router = ReturnType; - -async function act(router: Router, address: string, sessionId: string): Promise { - const path = [address, sessionId, "actions", "run"]; - return router.POST( - new Request(`http://goal/api/flows/${path.join("/")}`, { - method: "POST", - body: JSON.stringify({ userId: fixture.userId, input: { note: fixture.note } }) - }), - { params: { path } } - ); -} - -/** What a seat's blocks actually ran on, through the public `/state` route. */ -async function ranOn(router: Router, sessionId: string) { - const path = ["sessions", sessionId, "state"]; - const res = await router.GET(new Request(`http://goal/api/flows/${path.join("/")}`), { - params: { path } - }); - const body = (await res.json()) as { - clientData?: { - session?: { ran?: { instructions?: string | null; model?: string | null; desk?: string | null; runs?: number } }; - }; - }; - return { status: res.status, ...(body.clientData?.session?.ran ?? {}) }; -} - -async function settled(stores: StoreRegistry, requestId: string): Promise { - for (let i = 0; i < 200; i += 1) { - const record = await stores.request.get(requestId); - if (record !== undefined && record.status !== "in_progress") return record.status; - await new Promise((r) => setTimeout(r, 25)); - } - return undefined; -} - -const messageOf = (error: unknown): string => - error instanceof Error ? error.message : String(error); - -await runGoal(async () => { - const failures: string[] = []; - const evidence: string[] = [`roster source: ${rosterSource}`]; - const dir = mkdtempSync(join(tmpdir(), "fsd-workforce-seats-")); - const dbFile = join(dir, "goal.db"); - const sessions: Record = { [lead.id]: "s_lead", [intake.id]: "s_intake" }; - - const records = await roster("teams"); - // Hired once. Registering the same copies in each host is the shape an app - // has anyway — one hire at boot, whatever is built around it afterwards. - const seats = hireWorkforce(records, { workerFlows: kinds }); - - // ---- (0) the two roster sources still say the same thing --------------- - { - const { unknownKind, undeclaredSetting, noContract } = fixture.refusals; - const { thinWithBody } = fixture; - failures.push( - ...declares( - "teams", - lead.id, - { - description: lead.description, - flow: lead.flow, - model: lead.model, - tools: `[${lead.tools.join(", ")}]` - }, - lead.body - ), - ...declares("teams", intake.id, { description: intake.description, flow: intake.flow, desk: intake.desk }, ""), - ...declares( - unknownKind.dir, - unknownKind.id, - { description: unknownKind.description, flow: unknownKind.flow }, - unknownKind.body - ), - ...declares( - undeclaredSetting.dir, - undeclaredSetting.id, - { - description: undeclaredSetting.description, - flow: undeclaredSetting.flow, - [undeclaredSetting.key!]: undeclaredSetting.value! - }, - undeclaredSetting.body - ), - ...declares( - noContract.dir, - noContract.id, - { description: noContract.description, flow: noContract.flow }, - noContract.body - ), - ...declares( - thinWithBody.dir, - thinWithBody.id, - { description: thinWithBody.description, flow: thinWithBody.flow }, - thinWithBody.body - ) - ); - evidence.push( - "every WORKER.md in the fixture trees declares exactly what input.json says it does, so neither roster source can drift from the other unnoticed" - ); - } - - // ---- (a) one call, one copy per record, each answering to its own id ---- - { - if (records.length !== 2) { - failures.push(`the roster produced ${records.length} record(s), wanted 2`); - } - const ids = seats.map((s) => s.id); - if (ids.join(",") !== [intake.id, lead.id].join(",")) { - failures.push(`hired ${JSON.stringify(ids)}, wanted the two record ids in id order`); - } - if (seats.some((s) => s.id === CUSTOM_AGENT_KIND || s.id === INTAKE_KIND)) { - failures.push("a seat is addressed by its flow kind rather than by its own id"); - } - evidence.push("one call turned the two records into two flow copies, each carrying its record's id"); - } - - // ---- (b) each seat runs on its OWN record's settings, read after a restart - let stores: StoreRegistry = createSQLiteStores({ filename: dbFile }) as unknown as StoreRegistry; - { - const router = host(stores, seats); - for (const id of [lead.id, intake.id]) { - const res = await act(router, id, sessions[id]!); - const body = (await res.json()) as { request?: { id: string } }; - if (res.status !== 202) failures.push(`${id}: expected 202 from its own address, got ${res.status}`); - const status = await settled(stores, body.request?.id ?? ""); - if (status !== "completed") failures.push(`${id}: request ended ${String(status)}`); - } - evidence.push("both seats ran an action to completion through the real HTTP route"); - } - - (stores as unknown as { close(): void }).close(); - stores = createSQLiteStores({ filename: dbFile }) as unknown as StoreRegistry; - { - const router = host(stores, seats); - - const seenLead = await ranOn(router, sessions[lead.id]!); - if (seenLead.status !== 200) failures.push(`${lead.id}: /state returned ${seenLead.status}`); - // The body's whole journey, observed at the far end: file (or record) → - // config bag → a block nested inside the action. - if ((seenLead.instructions ?? "").trim() !== lead.body.trim()) { - failures.push(`${lead.id}: its nested block saw instructions ${JSON.stringify(seenLead.instructions)}`); - } - if (seenLead.model !== lead.model) { - failures.push(`${lead.id}: its nested block ran on model ${String(seenLead.model)}`); - } - // The sibling's setting must be ABSENT, not merely different — one shared - // bag is always right for somebody. - if (seenLead.desk != null) { - failures.push(`${lead.id}: read its sibling's desk (${String(seenLead.desk)})`); - } - if (seenLead.runs !== 1) failures.push(`${lead.id}: ran ${String(seenLead.runs)} times`); - - const seenIntake = await ranOn(router, sessions[intake.id]!); - if (seenIntake.status !== 200) failures.push(`${intake.id}: /state returned ${seenIntake.status}`); - // The thin seat is a LIVE seat, not an omission: it ran, and what it wrote - // is its own flow's setting. - if (seenIntake.desk !== intake.desk) { - failures.push(`${intake.id}: its nested block saw desk ${String(seenIntake.desk)}`); - } - if (seenIntake.instructions != null) { - failures.push(`${intake.id}: a thin seat carried instructions (${String(seenIntake.instructions)})`); - } - if (seenIntake.model != null) { - failures.push(`${intake.id}: read its sibling's model (${String(seenIntake.model)})`); - } - if (seenIntake.runs !== 1) failures.push(`${intake.id}: ran ${String(seenIntake.runs)} times`); - - evidence.push( - "after closing the store and rebuilding the host, each seat's nested block shows the settings its own record declared — the lead's body arrived as its instructions — and no sibling's" - ); - - // ---- (c) the bare flow kind is not an address ------------------------- - for (const kind of [CUSTOM_AGENT_KIND, INTAKE_KIND]) { - const res = await act(router, kind, `s_bare_${kind}`); - if (res.status !== 404) { - failures.push(`the bare kind "${kind}" answered with ${res.status}, wanted 404`); - } - } - evidence.push("neither bare flow kind is an address — both 404"); - } - - // ---- (d) three refusals, each leaving nothing registered ---------------- - { - const cases = [ - { - what: "a record naming a kind the app did not define", - records: [...records, ...(await roster(fixture.refusals.unknownKind.dir))], - flows: kinds, - names: [fixture.refusals.unknownKind.id, fixture.refusals.unknownKind.flow] - }, - { - what: "a record declaring a setting its flow never offered", - records: [...records, ...(await roster(fixture.refusals.undeclaredSetting.dir))], - flows: kinds, - names: [fixture.refusals.undeclaredSetting.id, fixture.refusals.undeclaredSetting.key!] - }, - { - what: "a record whose flow kind's schema cannot accept the imposed bag", - // Graded on the STRUCTURAL rule. The kind declares `instructions` and - // `teamInstructions` but not `seatSkills`, so the refusal can only be - // about the bag it cannot take — it is not merely a kind that skipped - // the helper, which leg (f) shows hires fine. Refused when the flows are - // registered, before any worker, so it names the flow, not the worker. - records: [ - records.find((r) => r.id === lead.id)!, - ...(await roster(fixture.refusals.noContract.dir)) - ], - flows: withNoContract, - names: [`worker flow "${NO_CONTRACT_KIND}"`, "seatSkills"] - } - ]; - - for (const testCase of cases) { - let hired: FlowInstance[] | undefined; - let refusal = ""; - try { - hired = hireWorkforce(testCase.records, { workerFlows: testCase.flows }); - } catch (error) { - refusal = messageOf(error); - } - if (hired !== undefined) { - failures.push(`${testCase.what}: the hire returned ${hired.length} seat(s) instead of refusing`); - continue; - } - for (const name of testCase.names) { - if (!refusal.includes(name)) { - failures.push(`${testCase.what}: the refusal does not name "${name}": ${refusal}`); - } - } - // A refusal after a partial hire is not a refusal: nothing came back, so - // nothing can be registered, and the good worker's address is dead too. - const router = host(stores, hired ?? []); - const res = await act(router, lead.id, `s_refused_${testCase.names[0]}`); - if (res.status !== 404) { - failures.push(`${testCase.what}: a seat was registered anyway (${lead.id} answered ${res.status})`); - } - } - evidence.push( - "an unknown kind and an undeclared setting each refuse at the hire, naming the worker, and a kind whose schema cannot accept the imposed bag refuses at boot, naming the flow, each with nothing hired and nothing registered" - ); - } - - // ---- (e) thinness is the RECORD's, not the seat's absence --------------- - // - // The other half of the pair. Leg (b) showed the thin seat running with no - // instructions; on its own that is equally true of a worker never hired. So - // the same record, with a body added, must hire and carry that body — which - // pins the absence on the record rather than on the seat being missing. - // - // Graded at the mint: the claim here is what was ADMITTED. That a value - // admitted this way reaches a running block is leg (b)'s claim, proved there - // through `/state` on the lead. - { - const bodied = await roster(fixture.thinWithBody.dir); - let hired: FlowInstance[] | undefined; - let refusal = ""; - try { - hired = hireWorkforce(bodied, { workerFlows: kinds }); - } catch (error) { - refusal = messageOf(error); - } - if (hired === undefined) { - failures.push(`the thin record with a body added refused instead of hiring: ${refusal}`); - } else { - const seat = hired.find((s) => s.id === fixture.thinWithBody.id); - if (seat === undefined) { - failures.push(`the thin record with a body added hired no seat at ${fixture.thinWithBody.id}`); - } else { - const carried = (seat.config as { instructions?: string }).instructions ?? ""; - if (carried.trim() !== fixture.thinWithBody.body.trim()) { - failures.push( - `the thin record's added body did not reach its bag: ${JSON.stringify(carried)}` - ); - } - // And the seat's skills door is open on it too — present and empty, - // which is what a roster with no skills folders resolves to. - if (!Object.hasOwn(seat.config, "seatSkills")) { - failures.push(`${fixture.thinWithBody.id}: hired with no seatSkills key in its bag`); - } - } - } - evidence.push( - "the thin seat's own record with a body added hires and carries that body as its instructions, so its emptiness in (b) is its record's and not a missing seat" - ); - } - - // ---- (f) admission is STRUCTURAL, not nominal --------------------------- - // - // Leg (d) shows a kind refusing. On its own that is equally consistent with - // hire checking whether `workerConfigSchema()` was called — which it does not - // and cannot. So a hand-written schema that never calls the helper, but does - // accept everything hire imposes, must hire exactly like a composed kind. - // Without this the goal would certify a rule the implementation rejects. - { - const handRolled: WorkerManifest = { - id: "engineering.handrolled", - declared: { description: "Hand-rolled, never composed.", flow: HAND_ROLLED_KIND }, - body: "You hold the hand-rolled desk." - }; - let hired: FlowInstance[] | undefined; - let refusal = ""; - try { - hired = hireWorkforce([...records, handRolled], { workerFlows: kinds }); - } catch (error) { - refusal = messageOf(error); - } - if (hired === undefined) { - failures.push(`a hand-written schema that accepts the imposed bag was refused: ${refusal}`); - } else { - const seat = hired.find((s) => s.id === handRolled.id); - if (seat === undefined) { - failures.push("the hand-rolled kind hired no seat"); - } else if (!Object.hasOwn(seat.config, "seatSkills")) { - failures.push("the hand-rolled seat was hired without the imposed seatSkills key"); - } - } - evidence.push( - "a hand-written schema that never calls workerConfigSchema() but accepts the imposed bag hires exactly like a composed kind, so (d)'s refusal is about what the schema takes and not about which helper built it" - ); - } - - (stores as unknown as { close(): void }).close(); - return { failures, evidence: evidence.join("; ") }; -}); From 9ea11deff0178909cfbc911dd2f093256ac5fddd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 01:40:28 +0000 Subject: [PATCH 07/12] docs(workforce): workers as data, talking to a worker, and resource visibility (FIX-1788 P4 S16) Hiring and forking replaces the runtime-hire page; Workers on disk gains Talking to a worker and the shared-copy flow contract; every example builds an installation. Resources gains resourceVisibility. The workforce, shift-manager and cli READMEs follow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- apps/docs/docs/cli/configuration.md | 8 +- .../docs/devtool/debug-vs-client-state.md | 2 - apps/docs/docs/devtool/overview.md | 2 +- apps/docs/docs/glossary.md | 4 +- apps/docs/docs/orchestration/agents.md | 6 +- apps/docs/docs/resources/overview.md | 14 + apps/docs/docs/server/background-work.md | 2 +- apps/docs/docs/workforce/built-in-worker.md | 82 +- .../docs/workforce/capabilities-on-disk.md | 9 +- apps/docs/docs/workforce/chief-of-staff.md | 179 ++-- apps/docs/docs/workforce/code-on-disk.md | 51 +- apps/docs/docs/workforce/documents-on-disk.md | 80 +- .../docs/workforce/durable-hire-store.svg | 88 -- apps/docs/docs/workforce/durable-hire.md | 693 ++------------ apps/docs/docs/workforce/hired-seat-reach.svg | 95 -- apps/docs/docs/workforce/inventory.md | 33 +- apps/docs/docs/workforce/mailboxes.md | 88 +- apps/docs/docs/workforce/overview.md | 53 +- apps/docs/docs/workforce/packages-on-disk.md | 17 +- .../docs/workforce/seat-mailbox-records.svg | 26 +- apps/docs/docs/workforce/seat-person-data.svg | 70 -- apps/docs/docs/workforce/ui.md | 4 +- apps/docs/docs/workforce/workers-on-disk.md | 475 +++++++--- .../docs/workforce/workforce-overview.svg | 32 +- packages/cli/README.md | 2 +- packages/workforce/README.md | 883 +++++++----------- 26 files changed, 1097 insertions(+), 1901 deletions(-) delete mode 100644 apps/docs/docs/workforce/durable-hire-store.svg delete mode 100644 apps/docs/docs/workforce/hired-seat-reach.svg delete mode 100644 apps/docs/docs/workforce/seat-person-data.svg diff --git a/apps/docs/docs/cli/configuration.md b/apps/docs/docs/cli/configuration.md index b50d4d4ac6..14e18605f6 100644 --- a/apps/docs/docs/cli/configuration.md +++ b/apps/docs/docs/cli/configuration.md @@ -167,10 +167,10 @@ anything is written: - A session belongs to the user and organization it was created with. Resuming one with `--session` as anyone else is refused, as it would be over HTTP. Use a new session id. -- A [hired seat](/docs/workforce/durable-hire#who-can-reach-a-hired-seat) runs only for the owner - it's pinned to. A run whose user or organization falls outside that pin is refused, whether the - identity came from your resolver or from `--user` and `--org`. Name the owner with `--org`, plus - `--user` for a seat one member owns. +- A flow copy registered with an owner pin runs only for the owner it's pinned to. A run whose + user or organization falls outside that pin is refused, whether the identity came from your + resolver or from `--user` and `--org`. Name the owner with `--org`, plus `--user` for a copy + pinned to one member. - A session with no organization recorded on it is refused and left unchanged. The message points to the upgrade steps in [Which organization a record belongs to](/docs/persistence/overview#which-organization-a-record-belongs-to). diff --git a/apps/docs/docs/devtool/debug-vs-client-state.md b/apps/docs/docs/devtool/debug-vs-client-state.md index 05913f62f8..691ea175ee 100644 --- a/apps/docs/docs/devtool/debug-vs-client-state.md +++ b/apps/docs/docs/devtool/debug-vs-client-state.md @@ -27,8 +27,6 @@ For each storage key the session touches, the debug response includes: It does not apply `prefetchWindow`: a collection lists all of its items, not a window of them. It does not apply `client.data` to the storage view either; that projection is shown alongside the raw state, not in place of it. -The workforce roster is the exception to the full listing. A [user-owned seat](../workforce/durable-hire.md#hiring-a-seat-only-one-member-can-reach) that belongs to a user other than the session's user doesn't appear in the collection's item list or its item count, and fetching its content returns 404. - On any collection, fetching content for a topic that doesn't match the collection's pattern also returns 404. The endpoint is read-only. You can't mutate state through it. diff --git a/apps/docs/docs/devtool/overview.md b/apps/docs/docs/devtool/overview.md index 83fa7d0dc4..8e29a6ac72 100644 --- a/apps/docs/docs/devtool/overview.md +++ b/apps/docs/docs/devtool/overview.md @@ -177,7 +177,7 @@ The tab appears on a session whose flow declares at least one of the three inven - **Registered mailboxes:** Id, Kind, Members, and Registered, the time the mailbox first registered. - **Registered memberships:** Seat and Mailbox. -A mailbox's session declares all three. Some flows declare only part: a seat carrying the [`seat-hire` tools](/docs/workforce/durable-hire) declares only the seat collection. A collection the flow doesn't declare reads "Not installed on this flow.", which is different from an empty section such as "No seats registered." When nothing is registered anywhere, the tab says so and points at the usual cause: the app never calls `openInventory` at boot. +A mailbox's session declares all three. Some flows declare only part. A collection the flow doesn't declare reads "Not installed on this flow.", which is different from an empty section such as "No seats registered." When nothing is registered anywhere, the tab says so and points at the usual cause: the app never calls `openInventory` at boot. Every row is labelled registered. Rows are never removed, so a fired seat stays listed, and a mailbox's members are the ones it had when it registered. The tab is a record of what has been registered here. It can't tell you which seats are working now. diff --git a/apps/docs/docs/glossary.md b/apps/docs/docs/glossary.md index 1adec76019..2a1a0d5a7f 100644 --- a/apps/docs/docs/glossary.md +++ b/apps/docs/docs/glossary.md @@ -105,8 +105,8 @@ These sit beside Orchestration on Core and don't use a task board. | **Team** | workforce | A folder of workers under `teams//`, with an optional `TEAM.md` whose body every worker on the team reads. A team is not a flow and has no address. | Workers | | **Org worker** | workforce | A worker under `org/workers//`. It belongs to no team. | Worker | | **Built-in worker** | workforce | The `agent` kind every worker runs on unless its file names another `flow:`. See [The built-in worker](./workforce/built-in-worker.md). | Flow (collection), generator, skills | -| **Hire** | workforce | `hireWorkforce` turns each worker record into a flow instance. Your app registers what comes back. | Flow instance | -| **Roster** | workforce | The workers you hire. The ones hired while the app runs are kept as rows, so they come back after a restart. See [Hiring while the app runs](./workforce/durable-hire.md). | Org resource collection | +| **Hire** | workforce | A user adds a worker of their own, as a row in their data. `hireWorkforce` gives back one copy of each worker flow, which your app registers. | Flow instance | +| **Roster** | workforce | A user's workers: their own, and the standard ones your files declare. See [Hiring and forking](./workforce/durable-hire.md). | Org resource collection | | **Fire** | workforce | Removes a worker hired while the app runs. A worker declared in a file leaves when its folder is deleted. | Roster row, inventory row | | **Mailbox** | workforce | One `MAILBOX.md`: a named session on the shared `mailbox` flow, with members, a charter and a transcript. See [Mailboxes](./workforce/mailboxes.md). | Session, flow | | **Member** | workforce | A worker id on a mailbox's member list. A post wakes each member whose flow kind handles posts, or only the chosen one on a routed mailbox. | Worker address | diff --git a/apps/docs/docs/orchestration/agents.md b/apps/docs/docs/orchestration/agents.md index 59f5be99c7..b18f189f14 100644 --- a/apps/docs/docs/orchestration/agents.md +++ b/apps/docs/docs/orchestration/agents.md @@ -167,11 +167,11 @@ Both forms default to `scope: "org"`, so a persona is shared across users unless `createWorkforceCapability({ roster, inventory })` returns a capability named `workforce` that gives every seat of the kind one tool: `discover`, which answers what seats and mailboxes have been registered, and whatever other domains you hand it. Pass the declared roster and the registry keys the [inventory](../workforce/inventory)'s seat and mailbox rows are mounted under. See [Discovery](./discovery). -## Hired workers +## Workforce workers -Workforce is a separate product. `hireWorkforce` turns a roster into configured flow copies you register and open a session against. A board's workers are blocks that claim tasks from a collection. +Workforce is a separate product. A Workforce worker is a configuration run by one shared copy of the flow it names, and you talk to it by opening a session that names it. A board's workers are blocks that claim tasks from a collection. -A hired worker's flow can mount a board, and that board's workers are any of the three above. A task's `assignee` can also name a hired worker: a board whose `defaultWorker` asks Workforce's worker lookup hands the task to the worker of that name. See [Giving a task to a worker](../workforce/overview#giving-a-task-to-a-worker). +A worker flow can mount a board, and that board's workers are any of the three above. A task's `assignee` can also name a standard Workforce worker: a board whose `defaultWorker` asks Workforce's worker lookup hands the task to the worker of that name. See [Giving a task to a worker](../workforce/overview#giving-a-task-to-a-worker). ## Related pages diff --git a/apps/docs/docs/resources/overview.md b/apps/docs/docs/resources/overview.md index a7e60bfc65..aa2e4bb6ff 100644 --- a/apps/docs/docs/resources/overview.md +++ b/apps/docs/docs/resources/overview.md @@ -289,6 +289,20 @@ Resource collections take the same flags, declared once on the collection and ap The generic tools address resources by their scope-qualified uri (for example `session/files/readme.md`), the same handle the [search tools](/docs/resources/searching) return — so a result from `globResources` or `grepResourceContent` feeds straight into `readResourceContentTool`. +A flow can also narrow what the model reaches on a single turn. Give it a `resourceVisibility` rule, and the built-in resource tools, the `discover` door, and any tool you build on them treat a resource the rule hides as one that doesn't exist: it isn't listed, searched, read or written, and asking for it by its uri gets the same answer as asking for a missing one. A resource the rule marks read-only is read but not written. With no rule, the model reaches what it reaches today. + +```ts +defineFlow({ + kind: "desk", + resources: { handbook, payroll }, + // Called on every listing and lookup: keep it synchronous, and decide from what your server wrote, never the turn's input. + resourceVisibility: (ctx, { name }) => (name === "payroll" && !isFinance(ctx) ? "hidden" : "visible"), + actions: { /* … */ }, +}); +``` + +The rule decides what the model sees, not what your code does: a block that reads a resource by reference, as `ctx.resources.payroll`, still reads it. Workforce sets the rule for you, so a worker's model reaches only the documents its `WORKER.md` grants, even when many workers share one flow. + ## Resource collections Static resources have a fixed name. Resource collections let you create typed sets of resources dynamically at runtime — useful when the number of instances isn't known ahead of time (file collections, per-topic knowledge, dynamic workspaces). diff --git a/apps/docs/docs/server/background-work.md b/apps/docs/docs/server/background-work.md index e8f41a2a17..660b9edce8 100644 --- a/apps/docs/docs/server/background-work.md +++ b/apps/docs/docs/server/background-work.md @@ -117,7 +117,7 @@ A refusal at run time throws `DispatchRefusedError`, with `code: | `refused` | Meaning | |---|---| | `no-entry` | The addressed flow declares no entry at that address | -| `flow-not-found` | A `flowKind` names a flow this server has not registered, or a [hired seat](../workforce/durable-hire.md#who-can-reach-a-hired-seat) the sending session may not open: one pinned to another organization, or a user-owned seat that belongs to another user. The refusal is the same in both cases, so `flow-not-found` doesn't tell you which one you hit | +| `flow-not-found` | A `flowKind` names a flow this server has not registered, or a flow copy registered with an owner pin the sending session may not open: one pinned to another organization, or to another user. The refusal is the same in both cases, so `flow-not-found` doesn't tell you which one you hit | | `session-not-found` | An `id` names a session that does not exist, or one that belongs to another user | | `session-not-addressable` | An `id` names a session on a flow other than the one addressed | | `key-occupied` | The `key` derived a session id already held by a record that is not this conversation's run | diff --git a/apps/docs/docs/workforce/built-in-worker.md b/apps/docs/docs/workforce/built-in-worker.md index 8d4190c092..3b2c6eacdd 100644 --- a/apps/docs/docs/workforce/built-in-worker.md +++ b/apps/docs/docs/workforce/built-in-worker.md @@ -18,19 +18,18 @@ You are the engineering lead. You break work into tasks and report back. ``` ```ts -import { hireWorkforce } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, hireWorkforce } from "@flow-state-dev/workforce"; import { readWorkforce } from "@flow-state-dev/workforce/loader"; const { workers } = await readWorkforce("./workforce"); -const seats = hireWorkforce(workers); - -flowRegistry.registerMany(seats); +const installation = createWorkerInstallation({ standardWorkers: workers }); +flowRegistry.registerMany(hireWorkforce(installation)); ``` -No `workerFlows` argument, no flow of your own. The body becomes the worker's instructions and steers its answers; `description` is a label for the roster and never reaches the model. +No `workerFlows` argument, no flow of your own. Every worker that runs on `agent` shares its one registered copy, and each turn runs as the worker its session names. The body becomes the worker's instructions and steers its answers; `description` is a label for the roster and never reaches the model. -The settings a worker writes for itself are `instructions`, `model`, `tools`, the `skills` switches below, `capabilities` — which picks presets from the capabilities the kind carries, covered in [Capabilities on disk](./capabilities-on-disk.md) — and `packages`, which takes [packages](./packages-on-disk.md) from its team's or the org's library. Four more reach the seat in the same bag, put there by the hire rather than by the file: the team's instructions, the skills the worker's folders hold, the blocks its `tools:` resolved out of its own levels, and the instructions and blocks of the packages it holds. A file that declares one of those four is refused by name. `flow: agent` names the same kind explicitly, and hires the same way. +The settings a worker writes for itself are `instructions`, `model`, `tools`, the `skills` switches below, `capabilities` — which picks presets from the capabilities the kind carries, covered in [Capabilities on disk](./capabilities-on-disk.md) — and `packages`, which takes [packages](./packages-on-disk.md) from its team's or the org's library. Four more reach the worker in the same bag, put there by the installation rather than by the file: the team's instructions, the skills the worker's folders hold, the blocks its `tools:` resolved out of its own levels, and the instructions and blocks of the packages it holds. A file that declares one of those four is refused by name. `flow: agent` names the same kind explicitly, and hires the same way. ## Tools @@ -59,27 +58,28 @@ What the key *means* is not. `tools` is reserved across hireable kinds for one t To give the built-in a tool catalog, build the kind yourself with `defineAgentWorkerFlow` and pass it under `agent`: ```ts -import { defineAgentWorkerFlow, hireWorkforce } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, defineAgentWorkerFlow, hireWorkforce } from "@flow-state-dev/workforce"; import { readWorkforce } from "@flow-state-dev/workforce/loader"; import { boardTool, searchTool } from "./tools"; const { workers } = await readWorkforce("./workforce"); -const seats = hireWorkforce(workers, { - workerFlows: { - agent: defineAgentWorkerFlow({ - catalog: { board: boardTool, search: searchTool }, - }), - }, +const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: () => ({ + agent: defineAgentWorkerFlow({ installation, catalog: { board: boardTool, search: searchTool } }), + }), }); +const flows = hireWorkforce(installation); ``` -`defineAgentWorkerFlow()` with no arguments is the built-in itself, so the copy you pass replaces it rather than adding to it. It takes over for every seat that runs on the `agent` kind: the records that leave `flow:` out, and any that name `agent` outright. A worker naming any other kind is unaffected. Hire with no `workerFlows` at all and the workers have no tool catalog. +`workerFlows` is a function here because the built-in is built on the installation: it takes the installation's session, so each session names its worker, and loads that worker on every turn. The function is read when first needed. The copy you pass replaces the built-in rather than adding to it. It takes over for every worker that runs on `agent`: the records that leave `flow:` out, and any that name `agent` outright. A worker naming any other flow is unaffected. With no `workerFlows` at all the installation adds the built-in itself, and the workers have no tool catalog. `defineAgentWorkerFlow` takes: | Option | What it does | | --- | --- | +| `installation` | The installation that runs this flow's workers. Required for a copy you register: `hireWorkforce` refuses a worker flow that doesn't declare the installation's session. | | `catalog` | The tools every worker of this kind may name in `tools:`, by key — `workforce.gen.ts`'s `blocks` export goes straight in. Left out, the only names a worker can resolve are the ones its own folders register. Whatever a catalog tool declares as a resource is installed on the kind, for every worker of it. | | `skills` | Skills every worker of this kind holds, on top of the ones its own folders hold. A name that collides with a skill a worker already holds is refused at the hire. | | `model` | The model a worker uses when its own file names none. | @@ -88,33 +88,35 @@ const seats = hireWorkforce(workers, { | `taskLists` | The mailbox boards this kind's workers take tasks from, by id (`mailboxBoardIds(mailboxes)`). Left out, the kind takes no tasks. See [Taking a task](#taking-a-task). | | `uses` | Capabilities every worker of this kind carries, attached to the generator that answers. | | `afterAnswer` | A block that runs after the worker answers, without changing the reply. | -| `isolateUserState` | Give each worker its own user-scoped storage instead of one shared cell. | +| `isolateUserState` | Keep this flow's user-scoped storage apart from other flows'. Every worker on `agent` shares one copy, so a user's workers on it still share one cell. | -`classifierModel` and `confidenceThreshold` belong to the kind: nothing reads either until a worker turns `skills.enableLlmClassifier` on, and a `WORKER.md` that names one is refused at the hire, by name, along with any other setting the kind does not declare. The last three are what [Giving workers memory](#giving-workers-memory) uses. +`classifierModel` and `confidenceThreshold` belong to the kind: nothing reads either until a worker turns `skills.enableLlmClassifier` on, and a `WORKER.md` that names one is refused at the hire, by name, along with any other setting the kind does not declare. `uses` and `afterAnswer` are what [Giving workers memory](#giving-workers-memory) uses. -A replacement declares `kind: "agent"`, like any other kind passed under its own name. It also declares `cardinality: "collection"`, which is what lets one definition have many copies. Leave that out and each seat mints, then is refused when you register it. +A replacement declares `kind: "agent"`, like any other flow passed under its own name. ## Taking a task A worker on this kind can be handed a task from a mailbox's board, by name, when you build the kind with `taskLists`: ```ts -import { defineAgentWorkerFlow, hireWorkforce, mailboxBoardIds } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, defineAgentWorkerFlow, hireWorkforce, mailboxBoardIds } from "@flow-state-dev/workforce"; const boardIds = mailboxBoardIds(mailboxes); -const hired = hireWorkforce(workers, { - workerFlows: { agent: defineAgentWorkerFlow({ taskLists: boardIds }) }, +const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: () => ({ agent: defineAgentWorkerFlow({ installation, taskLists: boardIds }) }), }); +const flows = hireWorkforce(installation); ``` Each task runs as one turn, in a session of its own when the board hands tasks over `per-task`. The worker answers with its own instructions, tools and model. The message is the task's title, goal and context. The answer is stored as the task's result, and the task completes. If the turn fails, the attempt fails, and the task's `maxAttempts` decides whether it runs again. Nothing is posted to a mailbox unless the worker's own tools post it. -Without `taskLists` the kind takes no tasks, and that includes the built-in you get when you pass no `workerFlows`. A task given to one of its workers is refused, saying the worker takes no tasks. The board side, and who a task's name can reach, is in [Handing a row to the worker it names](./mailboxes.md#handing-a-row-to-the-worker-it-names). +A board hands tasks to standard workers only: whoever drains it opens the task's session, and nobody can open one with another user's worker. Without `taskLists` the kind takes no tasks, and that includes the built-in you get when you pass no `workerFlows`. A task given to one of its workers is refused, saying the worker takes no tasks. The board side, and who a task's name can reach, is in [Handing a row to the worker it names](./mailboxes.md#handing-a-row-to-the-worker-it-names). ## What a worker keeps -A conversation keeps its recent turns, each person keeps their own copy of the worker's skills, and memory, once you add it, is kept per person. +A conversation keeps its recent turns, each worker keeps its own skills for each person, and memory, once you add it, is kept per person. ![A conversation holds recent turns, a worker's skills are kept per person, and memory is kept per person](./built-in-worker-memory.svg) @@ -193,10 +195,10 @@ The built-in sees only the conversation it's in: each turn, its model gets that You turn it on by composing it into your own copy of the kind. A *capability* is a bundle you attach to a block — the context it injects, the tools it adds, the storage it needs — and memory ships as one. [Memory](../memory/overview.md) covers the system itself: its tiers, what each one stores, and every knob `system()` takes. What follows is how a roster of workers picks it up. -It rides on the last three options in the table above: `uses`, `afterAnswer` and `isolateUserState`. Here is the whole recipe: +It rides on two options in the table above: `uses` and `afterAnswer`. Here is the whole recipe: ```ts -import { AGENT_KIND, defineAgentWorkerFlow, hireWorkforce } from "@flow-state-dev/workforce"; +import { AGENT_KIND, createWorkerInstallation, defineAgentWorkerFlow, hireWorkforce } from "@flow-state-dev/workforce"; import { readWorkforce } from "@flow-state-dev/workforce/loader"; import { system } from "@flow-state-dev/memory"; import { boardTool, searchTool } from "./tools"; @@ -208,7 +210,15 @@ const mem = system({ semantic: true, }); +const { workers } = await readWorkforce("./workforce"); + +const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: () => ({ [AGENT_KIND]: remembers }), +}); + const remembers = defineAgentWorkerFlow({ + installation, catalog: { board: boardTool, search: searchTool }, uses: [ mem.capability.presets({ @@ -221,18 +231,14 @@ const remembers = defineAgentWorkerFlow({ episodic: true, // things that happened }), ], - // Each worker remembers separately. - isolateUserState: true, // The write side. Without this, nothing is ever recorded. afterAnswer: mem.captureFromItems, }); -const { workers } = await readWorkforce("./workforce"); - -const seats = hireWorkforce(workers, { workerFlows: { [AGENT_KIND]: remembers } }); +const flows = hireWorkforce(installation); ``` -Tell a worker something in one conversation and it knows it in the next. +Tell a worker something in one conversation and it knows it in the next. Memory is kept per person, and every worker on `agent` shares one copy, so one person's workers on it share what it remembers. It never reaches another person. ### The parts that are easy to get wrong @@ -268,19 +274,19 @@ tools: [memory/recall] --- ``` -### What isolation does and does not give you - -`isolateUserState: true` keys each worker's storage on that worker's id, so two workers serving the same person do not read each other's memory. Leave it off and they share one per user per organization, as every flow does. - -![Where a hired seat keeps what it learns about alice. Inside the acme organization: one cell for alice in acme, holding her user record and her shared user-scoped resources, which every flow in acme uses, hired seats included; and one cell per seat for flow-isolated data, such as alice in acme for acme.support.ada. In globex, alice has a separate cell of her own, which nothing in acme reads. A projected resource is stored by your own hooks, so key its rows by the organization too.](./seat-person-data.svg) +### Whose memory it is -It is a decision for the whole kind. A roster is all-separate or all-shared; you cannot keep one shared store across the team while giving each worker its own of something else. +Memory is stored in the person's user scope, in the organization they're signed in to, so it never +reaches another person or another organization. Every worker on `agent` runs on one shared copy, +so one person's workers on it share that memory: tell one of them something and another may +recall it. Their skills are the exception, kept apart per worker by the built-in itself. -The flag decides *where* a worker's memory is stored, so anything that moves the key leaves the old memory behind. Renaming a worker does it, because the key is the worker's id. So does turning the flag on for a roster that has already been talking to people, because shared and separate are different places. Neither has a migration. Decide it before the roster has anything worth keeping, or accept that workers start fresh. +`isolateUserState: true` keeps the `agent` flow's user-scoped storage apart from every other +flow's. It doesn't separate workers on `agent`: they share the one copy it keys on. ## Related pages -- [Workers on disk](./workers-on-disk.md) — the folder tree, `WORKER.md`, `readWorkforce`, and `hireWorkforce`. +- [Workers on disk](./workers-on-disk.md) — the folder tree, `WORKER.md`, `readWorkforce`, `hireWorkforce`, and talking to a worker. - [Workforce](./overview.md) — what a hired roster is, and when to reach for it instead of a task board. - [Skills](../skills/overview.md) — what a `SKILL.md` is and what goes in one. - [Activation paths](../skills/activation.md) — the ways a skill becomes active, and what each costs. diff --git a/apps/docs/docs/workforce/capabilities-on-disk.md b/apps/docs/docs/workforce/capabilities-on-disk.md index 3c392d5303..d223edccaf 100644 --- a/apps/docs/docs/workforce/capabilities-on-disk.md +++ b/apps/docs/docs/workforce/capabilities-on-disk.md @@ -67,6 +67,7 @@ A capability and a resource have two destinations, so `splitResourceModules` sep ```ts import { + createWorkerInstallation, defineAgentWorkerFlow, hireWorkforce, resourcesFromDocs, @@ -77,10 +78,12 @@ import { resourceModules } from "./workforce/workforce.gen"; const { capabilities, resources } = splitResourceModules(resourceModules); -const agent = defineAgentWorkerFlow({ uses: capabilities }); - const { workers } = await readWorkforce("./workforce"); -const seats = hireWorkforce(workers, { workerFlows: { agent } }); +const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: () => ({ agent: defineAgentWorkerFlow({ installation, uses: capabilities }) }), +}); +const flows = hireWorkforce(installation); ``` `capabilities` goes to the worker kind's `uses`, which is the same option you would pass a hand-written capability to. `resources` merges into the flow's resource map beside the Markdown documents: diff --git a/apps/docs/docs/workforce/chief-of-staff.md b/apps/docs/docs/workforce/chief-of-staff.md index 13de7e0cdf..50673122e5 100644 --- a/apps/docs/docs/workforce/chief-of-staff.md +++ b/apps/docs/docs/workforce/chief-of-staff.md @@ -2,27 +2,27 @@ title: The chief of staff sidebar_position: 12 sidebar_label: Chief of staff -description: "One seat a person asks who works here, and asks to change it. Hires land at once; a fire waits for the person's approval. It can also start projects." +description: "One worker a person asks who works here, and asks for workers of their own. Hires land at once; a fire waits for the person's approval. It can also start projects." --- # The chief of staff -The chief of staff is a seat a person talks to about the organization itself. Ask it who works here or who is in a mailbox, and it looks it up. Ask it for another seat, and it hires one. Ask it for one fewer, and it puts the fire in front of you to approve. Nothing is removed until you do. Give it the project tools, and it starts [projects](./projects.md) for you too. +The chief of staff is a worker a person talks to about the organization itself. Ask it who works here or who is in a mailbox, and it looks it up. Ask it for another worker, and it hires one of your own. Ask it for one fewer, and it puts the fire in front of you to approve. Nothing is removed until you do. Give it the project tools, and it starts [projects](./projects.md) for you too. -With `refuseRosterAdmin` on, as in the setup below, it is the only seat that hires or fires. Another seat that needs help sends the chief of staff a message and lets it decide. A Lab that doesn't declare one doesn't have one. +A worker it hires belongs to the person it is talking to: it is on their roster and nobody else's, as [Hiring and forking](./durable-hire.md) describes. A Lab that doesn't declare a chief of staff doesn't have one. ## Adding one -You need two things: a `WORKER.md` for the seat, and the `seat-hire` tools on the kind it runs on. +You need two things: a `WORKER.md` for the worker, and the hire and fire tools in the catalog of the flow it runs on. -The file goes under `org/workers/`, beside `teams/`. Its folder name is its id, so `org/workers/chief-of-staff/` is the seat `chief-of-staff`. It runs on the built-in `agent` kind and names the tools it holds: +The file goes under `org/workers/`, beside `teams/`. Its folder name is its id, so `org/workers/chief-of-staff/` is the worker `chief-of-staff`. It runs on the built-in `agent` flow and names the tools it holds: ```md title="workforce/org/workers/chief-of-staff/WORKER.md" --- -description: Who works here, and the one seat that changes it. +description: Who works here, and the one worker that hires more. flow: agent model: openai/gpt-5.4-mini -tools: [hire, fire, rehire, brokenSeats, post-to-mailbox] +tools: [hire, fire, post-to-mailbox] --- You are the chief of staff for this organization. @@ -30,94 +30,115 @@ You are the chief of staff for this organization. When someone asks who works here or who is in a mailbox, look it up with `discover` and answer from what it returns. -To add a seat, call `hire`. It lands at once. To remove one, call `fire`. -The person approves every fire before it happens; if they deny it, say so -and don't try again unless they ask. +To add a worker for the person, call `hire`. It lands at once. To remove one +of theirs, call `fire`. The person approves every fire before it happens; if +they deny it, say so and don't try again unless they ask. -To hire a `coder`, pass `settings: { "document": "teams/eng/feature-brief" }`. +To hire a worker on `coder`, pass `settings: { "document": "teams/eng/feature-brief" }`. -You can't fire yourself or any seat declared in the organization's files. +You can't fire yourself or any worker declared in the organization's files. Those change when someone edits their folder. ``` -Then give the `agent` kind the tools, with `askBefore: ["fire"]` so a fire waits for a person, and `refuseRosterAdmin: true` so a seat it hires can't be handed the same tools: +Then build the tools from `createWorkerHireBlocks` and put them in the `agent` flow's catalog. A catalog key is the tool's own name, so wrap each block in a sequencer carrying the name and what the model reads about it. Here a fire waits for a person's approval first: ```ts title="src/workforce.ts" -import { defineCapability } from "@flow-state-dev/core"; +import { defineCapability, handler, sequencer } from "@flow-state-dev/core"; import { - mailboxPostCapability, - createSeatHireCapability, + createWorkerHireBlocks, + createWorkerInstallation, createWorkforceCapability, defineAgentWorkerFlow, - HIRED_ROSTER_RESOURCE, + defineSeatInventoryCollection, + hireWorkforce, projectWritesMailboxInventory, - SEAT_INVENTORY_RESOURCE, - type HireOptions, + workerMailboxPostCapability, } from "@flow-state-dev/workforce"; +import { z } from "zod"; import { coderFlow } from "./flows/coder"; -import { deskClerkFlow } from "./flows/desk-clerk"; -import { instanceAt, kindAt, registerSeat, releaseSeat } from "./registry-access"; import { roster } from "./roster"; -// Typed as the whole map, so the `agent` entry can be added below. -export const kinds: NonNullable = { "desk-clerk": deskClerkFlow, coder: coderFlow }; - -const seatHire = createSeatHireCapability({ - workerFlows: kinds, - register: registerSeat, - unregister: releaseSeat, - kindAt, - instanceAt, - allowKinds: ["desk-clerk", "coder", "agent"], - askBefore: ["fire"], - refuseRosterAdmin: true, +/** A fire waits for the person: a `human_approval` naming the worker. On Deny, nothing changes. */ +const askFire = handler({ + name: "ask-fire", + inputSchema: z.object({ id: z.string() }).passthrough(), + outputSchema: z.void(), + execute: async (input, ctx) => { + if (ctx.suspend === undefined) { + throw new Error(`firing "${input.id}" waits for a person's approval, and this app can't ask for one. Nothing was changed.`); + } + await ctx.suspend({ reason: "human_approval", message: `Fire worker "${input.id}"?`, data: { worker: input.id }, allow: ["approve", "reject"] }); + }, }); +const installation = createWorkerInstallation({ + standardWorkers: roster.workers, + workerFlows: () => ({ coder: coderFlow, agent }), +}); + +const { hire, fire } = createWorkerHireBlocks(installation); +const rosterTools = { + hire: sequencer({ + name: "hire", + description: "Hire a worker of the person's own: `id`, the `flow` it runs on (`agent` when omitted), and `settings`.", + inputSchema: hire.inputSchema, + outputSchema: hire.outputSchema, + }).step(hire), + fire: sequencer({ + name: "fire", + description: "Fire one of the person's own workers, by id, once the person approves it.", + inputSchema: fire.inputSchema, + outputSchema: fire.outputSchema, + }) + .tap(askFire) + .step(fire), +}; + // `roster.mailboxes` must already be final here (see the order below). -kinds.agent = defineAgentWorkerFlow({ +const agent = defineAgentWorkerFlow({ + installation, + catalog: rosterTools, uses: [ defineCapability({ - name: "mailbox-inventory", - resources: { mailboxInventory: projectWritesMailboxInventory }, + name: "inventory", + resources: { seatInventory: defineSeatInventoryCollection(), mailboxInventory: projectWritesMailboxInventory }, }), createWorkforceCapability({ roster: { workers: roster.workers, mailboxes: roster.mailboxes }, - inventory: { seats: SEAT_INVENTORY_RESOURCE, mailboxes: "mailboxInventory" }, - hiredRoster: HIRED_ROSTER_RESOURCE, + inventory: { seats: "seatInventory", mailboxes: "mailboxInventory" }, }), - mailboxPostCapability, - seatHire, + workerMailboxPostCapability, ], }); -``` -`registerSeat`, `releaseSeat`, `kindAt` and `instanceAt` come from the `registry-access.ts` in [Reaching the `FlowState`](./durable-hire.md#reaching-the-flowstate). The hire tools use `kindAt` to refuse a hire whose name a declared worker already has, and `instanceAt` so that a re-hire interrupted by a restart completes and `fire` releases only the worker it hired. +export const flows = hireWorkforce(installation); +``` -The capabilities on the kind each add one part: +The capabilities on the flow each add one part: -- **Inventory and `discover`.** `createWorkforceCapability` gives every seat on the kind `discover`, which is how the chief of staff answers questions about the roster. The small `mailbox-inventory` capability declares the mailbox inventory on the kind with `projectWritesMailboxInventory`, the declaration the [project tools](#starting-projects) need, so you can add them later without touching it. Passing its key, `mailboxInventory` here, as `inventory.mailboxes` lets `discover` answer who is in a mailbox too. -- **Posting.** `mailboxPostCapability` adds `post-to-mailbox`, so the chief of staff can answer in a mailbox it is a member of. A mailbox counts it as a member only when its `MAILBOX.md` `members:` lists it, by its own name for an org-level worker, as in `members: [eng.em, eng.coder, chief-of-staff]`. A post from a worker the mailbox doesn't list is refused with `author-not-a-member`. -- **Hiring.** `createSeatHireCapability` takes the same options as [`createSeatHireBlocks`](./durable-hire.md#the-ready-made-hire-and-fire-handlers), plus `askBefore`. +- **Inventory and `discover`.** `createWorkforceCapability` gives every worker on the flow `discover`, which is how the chief of staff answers questions about the roster. The small `inventory` capability declares the seat and mailbox inventories on the flow, the mailbox one with `projectWritesMailboxInventory`, the declaration the [project tools](#starting-projects) need, so you can add them later without touching it. Passing the keys as `inventory` lets `discover` answer who works here and who is in a mailbox. +- **Posting.** `workerMailboxPostCapability` adds `post-to-mailbox`, so the chief of staff can answer in a mailbox it is a member of, signed as the worker its turn runs as. A mailbox counts it as a member only when its `MAILBOX.md` `members:` lists it, by its own name for an org-level worker, as in `members: [eng.em, eng.coder, chief-of-staff]`. A post from a worker the mailbox doesn't list is refused with `author-not-a-member`. +- **Hiring.** The catalog holds `hire` and `fire`. Asking first is yours to add, as `askFire` does: the blocks themselves write at once. Build in this order: 1. Finish any edits or additions to the mailbox records. -2. Build the `agent` kind above, which `hireWorkforce(workers, { workerFlows: kinds })` hires the chief of staff onto. -3. Build the mailbox kind with `wakeMemberSeats(seats)`. It comes after `hireWorkforce`, because it takes the hired workers. +2. Build the installation and the `agent` flow above, and call `hireWorkforce`. +3. Build the mailbox kind with `wakeMemberSeats(flows, { installation })`. It comes after `hireWorkforce`, because it takes the flows it returned. 4. Call `mailboxInstances` last. `createWorkforceCapability` keeps the mailbox records it is given, so a record changed after step 2 never reaches `discover`. Pass `createWorkforceCapability` the same mailbox records you pass `mailboxInstances`, so `discover` answers from the mailboxes the app actually opens. -`hire` asks the model for a kind, a seat id, and `settings`, but doesn't say which kinds require which settings. The chief of staff learns that from its `WORKER.md` body, so name each required setting and its value there, as the example file does for a `coder`. A hire missing a required setting is refused with the setting named and nothing written, so the model can call `hire` again with it. +`hire` asks the model for an id, a flow and `settings`, but doesn't say which flows require which settings. The chief of staff learns that from its `WORKER.md` body, so name each required setting and its value there, as the example file does for `coder`. A hire missing a required setting is refused with the setting named and nothing written, so the model can call `hire` again with it. In the snippet above, `coderFlow` requires a `document` setting through its `configSchema`: `workerConfigSchema().extend({ document: z.string().min(1) })`. -Installing the tools on a kind doesn't hand them to every seat of it. A seat holds `hire` or `fire` only when its own `tools:` names it, so keep those names in the chief of staff's file and no other. `refuseRosterAdmin: true` keeps them out of the seats the chief of staff hires, too. Leave it off and a hire may name them like any other tool. +Putting the tools in the catalog doesn't hand them to every worker on the flow. A worker holds `hire` or `fire` only when its own `tools:` names it, so keep those names in the chief of staff's file and no other. -If your Lab has projects, add `chief-of-staff` to the project template's `seats` (or a team `MAILBOX.md` template's `members:`), so the chief of staff is in every project's room. Build the mailbox kind with `wakeMemberSeats(seats)` so a post in the room wakes it, and pass the template to `mailboxInstances` as [Setting up the room](./projects.md#setting-up-the-room) shows, including without `fsdev gen`. +If your Lab has projects, add `chief-of-staff` to the project template's `seats` (or a team `MAILBOX.md` template's `members:`), so the chief of staff is in every project's room. Build the mailbox kind with `wakeMemberSeats(flows, { installation })` so a post in the room wakes it, and pass the template to `mailboxInstances` as [Setting up the room](./projects.md#setting-up-the-room) shows, including without `fsdev gen`. -Read the seats it hired back when the app starts, as in [Reading the roster back at the next start](./durable-hire.md#reading-the-roster-back-at-the-next-start), and serve the app over a store that survives a restart. Otherwise a hire lasts only as long as the process. +A hire is a row in the person's own data, so it is there after a restart on any store that keeps data. Every process sees it on the next turn. ## Starting projects @@ -128,7 +149,7 @@ It needs the two project tools, `createProject` and `setWorkstreams`, in its `to ```md title="workforce/org/workers/chief-of-staff/WORKER.md" --- flow: agent -tools: [hire, fire, rehire, brokenSeats, post-to-mailbox, createProject, setWorkstreams] +tools: [hire, fire, post-to-mailbox, createProject, setWorkstreams] --- ``` @@ -141,7 +162,7 @@ member; put anyone else they name in `members`. Add workstreams only when they name them, by full mailbox id. ``` -The `mailbox-inventory` capability from [Adding one](#adding-one) is the inventory declaration the project tools read. Don't add a second one, such as a `defineMailboxInventoryCollection()` of your own: [Giving the writes to a seat](./projects.md#giving-the-writes-to-a-seat) shows the error the kind throws. +The `inventory` capability from [Adding one](#adding-one) is the inventory declaration the project tools read. Don't add a second one, such as a `defineMailboxInventoryCollection()` of your own: [Giving the writes to a seat](./projects.md#giving-the-writes-to-a-seat) shows the error the kind throws. A workstream belongs to one project at most. When the person asks for one another project holds, the tool is refused, and the chief of staff can tell them which project has it. @@ -149,32 +170,22 @@ A workstream belongs to one project at most. When the person asks for one anothe | Tool | What it does | Asks first | | --- | --- | --- | -| `hire` | Hires a seat on a kind in `allowKinds`, under the id it is given | Only when `askBefore` lists `"hire"` | -| `fire` | Removes a seat this organization hired: its roster row, its address and its inventory row | Only when `askBefore` lists `"fire"` | -| `brokenSeats` | Lists hired seats that would not start, each with its reason. Reads only | Never | -| `rehire` | Keeps a seat that no longer starts at its address, on a kind this app carries | Always | +| `hire` | Hires a worker of the person's own, on a worker flow your app runs, under the id it is given | Only when you wrap it with an ask | +| `fire` | Removes one of the person's own workers. Its sessions stay readable to them | Only when you wrap it with an ask, as above | | `createProject` | Creates a project owned by the person asking, with the members and workstreams they name | Never | | `setWorkstreams` | Replaces a project's workstreams. The person asking must be one of its members | Never | -The seat tools work on the organization's seats. A seat a member hired for only themselves stays with that member, and the chief of staff can't list, repair or fire it. +The roster tools work on the person's own workers. Another member's workers are theirs: the chief of staff can't list or fire them. ## What asks first -`askBefore` lists the changes that wait for a person. It takes `"hire"` and `"fire"`, and any other entry throws when the capability is built: - -```text -askBefore names "promote"; it takes hire and fire. -``` - -`askBefore` covers `hire` and `fire` only. Left out, those two act at once. `rehire` is not on the list because it always asks, whatever `askBefore` says, so a repair needs durable execution even in an app that asks for nothing else. - -A listed tool checks everything that could refuse the change first. A seat id nothing hired, a seat declared in a file, or a kind outside `allowKinds` is refused straight away, and nobody is asked. When the change could go ahead, the tool pauses the request with a `human_approval` suspension: +A fire wrapped as above pauses the request with a `human_approval` suspension before anything changes: ```json { "reason": "human_approval", - "message": "Fire seat \"coder-7\" (kind \"coder\")?", - "data": { "verb": "fire", "seatId": "coder-7", "kind": "coder", "owner": null, "incarnation": "3f9c2a6e-5b1d-4e8a-9c07-2d4e6b8a1f53" }, + "message": "Fire worker \"scribe\"?", + "data": { "worker": "scribe" }, "allow": ["approve", "reject"] } ``` @@ -182,35 +193,27 @@ A listed tool checks everything that could refuse the change first. A seat id no The person answers through the resume route, as for any other [durable suspension](../advanced/durable-execution.md): ```bash -curl -X POST localhost:3000/api/flows/chief-of-staff/requests/$REQUEST_ID/resume \ +curl -X POST localhost:3000/api/flows/agent/requests/$REQUEST_ID/resume \ -H 'content-type: application/json' \ -d '{"suspensionId":"'$SUSPENSION_ID'","action":"approve"}' ``` -`owner` is the member whose own seat it is, or `null` for an organization's seat. `incarnation` names the hire that wrote the row. - -On approve, the tool checks again and makes the change, to that row only. If the seat was fired and hired again under the same id while the person was asked, the approved change is refused, the new seat is left alone, and the model gets this as the tool's error: - -```text -The seat "acme.coder-7" changed while you were asked: it is not the one you approved, so the fire was not made. Ask again if it should be. -``` - -On reject, nothing changes, and the model is told the request was denied. The ask outlives a restart: a person can approve tomorrow what the chief of staff asked today. On a store that keeps a run as it goes, such as SQLite, a process that dies after the approval and before the turn ends makes the change once when the request is recovered. +On approve, the fire runs. On reject, nothing changes, and the model is told the request was denied. The ask outlives a restart: a person can approve tomorrow what the chief of staff asked today. -Asking needs durable execution, so turn it on with `durable: true` on `createFlowState`. Without it, a listed tool refuses rather than acting unasked: +Asking needs durable execution, so turn it on with `durable: true` on `createFlowState`. Without it, the ask above refuses rather than firing unasked: ```text -"fire" waits for a person's approval here, and this app can't ask for one: it runs without durable execution. Nothing was changed. +firing "scribe" waits for a person's approval, and this app can't ask for one. Nothing was changed. ``` -Asking also needs a model with the single-step methods: `generateStep`, and `streamStep` when it streams. Models from the built-in AI SDK adapter have them. On a custom model without them, or a fallback group none of whose models has them, the listed tool can't pause the request: the call fails before anything changes, the model is told the tool failed, and the turn carries on with no approval raised. [Suspending inside generators](../advanced/generator-and-router-suspend-resume.md) covers a pause inside a tool call. +Asking also needs a model with the single-step methods: `generateStep`, and `streamStep` when it streams. Models from the built-in AI SDK adapter have them. On a custom model without them, or a fallback group none of whose models has them, the tool can't pause the request: the call fails before anything changes, the model is told the tool failed, and the turn carries on with no approval raised. [Suspending inside generators](../advanced/generator-and-router-suspend-resume.md) covers a pause inside a tool call. -`askBefore` applies to the tools a model calls. The handlers [`createSeatHireBlocks`](./durable-hire.md#the-ready-made-hire-and-fire-handlers) returns, mounted as actions, never ask. +The roster flow's own `fire` action, which an app sends directly, never asks: an app that sends it already has the person's say-so. ## What it can't do -- **Fire itself, or any declared seat.** `fire` answers that a seat declared in a worker file is removed by editing its folder. -- **Hire under a declared seat's id.** A hire that reuses one is refused, naming the kind already there. -- **Hire a kind outside `allowKinds`.** The refusal lists the kinds it may hire. -- **Hire another seat that can hire, when `refuseRosterAdmin` is on.** A hire or re-hire whose settings name `hire`, `fire`, `rehire` or `brokenSeats` in `tools:`, or pick the `seat-hire` capability under `capabilities:`, is refused, whatever the kind. Roster admin stays with the seats your app declares. +- **Fire itself, or any declared worker.** A worker declared in a worker file is a standard worker; `fire` refuses it, and it changes when someone edits its folder. +- **Hire under a standard worker's id.** A hire that reuses one is refused, suggesting a fork instead. +- **Hire onto a flow your app doesn't run workers on, or keeps for standard workers.** The refusal names the flow. +- **Reach another member's workers.** Their roster is theirs. - **Open, close or rename a mailbox.** Mailboxes are declared on disk. diff --git a/apps/docs/docs/workforce/code-on-disk.md b/apps/docs/docs/workforce/code-on-disk.md index cd2d08896c..2e73f9ab1d 100644 --- a/apps/docs/docs/workforce/code-on-disk.md +++ b/apps/docs/docs/workforce/code-on-disk.md @@ -7,7 +7,7 @@ description: "Put your flow kinds, blocks and capabilities in the workforce tree # Code on disk -A `WORKER.md` says which flow kind a worker runs. The kind itself is TypeScript, and something has to hand it to `hireWorkforce`. +A `WORKER.md` says which flow a worker runs on. The flow itself is TypeScript, and something has to hand it to the installation. You can write that map yourself. You can also put each file where the convention looks for it and let `fsdev gen` write the map, which means adding a kind is adding a file. @@ -41,7 +41,25 @@ workforce/ page-oncall.ts ← a block this one worker may name ``` -Each file default-exports one thing: a flow for the two `flows/` folders, a `BlockDefinition` for a `blocks/` folder, and a capability or a resource for a `resources/` folder. A worker kind needs `cardinality: "collection"`, because a [seat](./workers-on-disk.md#a-workers-identity) — one hired worker — mints its own copy under its own id. A mailbox kind needs the default, `singleton`, because a mailbox is a session on one shared copy. +Each file default-exports one thing: a `workerFlow(...)` builder for `flows/workers/`, a flow for `flows/mailboxes/`, a `BlockDefinition` for a `blocks/` folder, and a capability or a resource for a `resources/` folder. A worker flow is built on the installation that runs its workers, which a file can't import, so it exports a builder and the installation builds it once, with itself: + +```ts +// workforce/flows/workers/request-triage.ts +import { defineFlow } from "@flow-state-dev/core"; +import { workerConfigSchema, workerFlow } from "@flow-state-dev/workforce"; + +export default workerFlow((installation) => + defineFlow({ + kind: "request-triage", + configSchema: workerConfigSchema(), + session: installation.session(), + resources: { ...installation.resources }, + actions: { run: { inputSchema, block: triage(installation), userMessage: (input) => input.message } }, + }), +); +``` + +Every worker on the flow runs on that one copy. A mailbox flow is a plain flow, a session on one shared copy too. `resources/` is the one folder that takes both code and Markdown. A `.ts` file there is what this page covers; a `.md` file is a [document](./documents-on-disk.md), and what a capability in one does for a worker is [Capabilities on disk](./capabilities-on-disk.md). @@ -97,18 +115,19 @@ Each export feeds a parameter that already exists: | Export | Goes to | | --- | --- | -| `kinds` | `hireWorkforce`'s `workerFlows` | +| `kinds` | `createWorkerInstallation`'s `workerFlows` | | `mailboxKinds` | `mailboxInstances` | | `blocks` | a task board's `workers`, or a worker kind's [tool catalog](./built-in-worker.md#tools) | -| `seatBlocks` | `hireWorkforce` again | -| `packageBlocks` | `hireWorkforce`, for the [packages](./packages-on-disk.md) a worker holds | +| `seatBlocks` | `createWorkerInstallation` again | +| `packageBlocks` | `createWorkerInstallation`, for the [packages](./packages-on-disk.md) a worker holds | | `resourceModules` | `splitResourceModules`, whose halves go to the kind's `uses` and the flow's resource map | ```ts -import { hireWorkforce } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, hireWorkforce } from "@flow-state-dev/workforce"; import { kinds, seatBlocks } from "./workforce/workforce.gen"; -const seats = hireWorkforce(workers, { workerFlows: kinds, seatBlocks }); +const installation = createWorkerInstallation({ standardWorkers: workers, workerFlows: kinds, seatBlocks }); +const flows = hireWorkforce(installation); ``` The startup line names no kinds. Adding one means adding a file. @@ -143,7 +162,7 @@ Files that are not TypeScript are skipped: a README, a JSON sample, a note besid **TypeScript files are not.** Every `.ts` and `.tsx` file in one of the code folders is a declaration, so these folders are for declarations only. A `fixture.ts` sitting beside a kind registers a kind called `fixture`. A file whose name carries a second dot — `request-triage.test.ts`, `helpers.fixture.ts` — is refused outright, because the basename becomes the kind name and a dot is not legal in one. Keep tests and fixtures beside the code they exercise, outside every folder on this page: the two `flows/` folders, every `blocks/` folder, and every `resources/` folder. -Not everything is caught by the walk, and what it misses is caught later rather than not at all. A file that exports the wrong shape fails your own `tsc`, naming the generated module and the assignment, because the maps are typed. A flow whose declared `kind` disagrees with its basename is refused at the hire, naming both. +Not everything is caught by the walk, and what it misses is caught later rather than not at all. A file that exports the wrong shape fails your own `tsc`, naming the generated module and the assignment, because the maps are typed. A flow whose declared `kind` disagrees with its basename is refused by `hireWorkforce`, naming both. ## Blocks a worker can call @@ -165,14 +184,18 @@ A name is resolved nearest first: the worker's own folder, then its team's, then The org-level half is one line in your app, on the option the built-in kind already takes: ```ts -import { defineAgentWorkerFlow, hireWorkforce } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, defineAgentWorkerFlow, hireWorkforce } from "@flow-state-dev/workforce"; import { blocks, kinds, seatBlocks } from "./workforce/workforce.gen"; -const agent = defineAgentWorkerFlow({ catalog: blocks }); -const seats = hireWorkforce(workers, { workerFlows: { ...kinds, agent }, seatBlocks }); +const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: () => ({ ...kinds, agent: defineAgentWorkerFlow({ installation, catalog: blocks }) }), + seatBlocks, +}); +const flows = hireWorkforce(installation); ``` -The other two ride `seatBlocks`, which needs no option on the kind: a worker's registered blocks are that worker's, so they travel with the rest of what the hire step already gives one seat at a time. +The other two ride `seatBlocks`, which needs no option on the flow: a worker's registered blocks are that worker's, resolved into its configuration on each turn. Then a worker names what it wants: @@ -185,7 +208,7 @@ tools: [triage, page-oncall] Two rules are checked before any worker runs: -- **One tool has one name.** The file's basename, the map key and the block's own `name` must agree. A worker authorises by the key and the model is handed the block's `name`, so a disagreement is a worker authorising one tool and a model calling another. Refused when the kind is built for the catalog, at the hire for a worker's own folder. +- **One tool has one name.** The file's basename, the map key and the block's own `name` must agree. A worker authorises by the key and the model is handed the block's `name`, so a disagreement is a worker authorising one tool and a model calling another. Refused when the kind is built for the catalog, and by `hireWorkforce` for a worker's own folder. - **A block in a worker's own folder may read a store, not declare one.** Resources belong to the kind, and every worker of a kind shares them, so a store declared from inside one worker's folder would arrive for all of its siblings. Declare the store on the kind — through `defineAgentWorkerFlow`'s `uses` — and the block reads it as usual. The refusal names the block and both fixes. ## A hand-written map @@ -194,7 +217,7 @@ Passing `workerFlows` yourself works, and an app that never runs `fsdev gen` nee ## Related pages -- [Workers on disk](./workers-on-disk.md) — the folder tree, `WORKER.md`, `readWorkforce`, and `hireWorkforce`. +- [Workers on disk](./workers-on-disk.md) — the folder tree, `WORKER.md`, `readWorkforce`, `hireWorkforce`, and talking to a worker. - [Capabilities on disk](./capabilities-on-disk.md) — what a `.ts` file in a `resources/` folder gives a worker, and how a worker's file picks among its presets. - [Documents on disk](./documents-on-disk.md) — the `.md` half of a `resources/` folder. - [The built-in worker](./built-in-worker.md) — the `agent` kind, its catalog, and its tools. diff --git a/apps/docs/docs/workforce/documents-on-disk.md b/apps/docs/docs/workforce/documents-on-disk.md index 8cf30c94e6..09d6f19c8b 100644 --- a/apps/docs/docs/workforce/documents-on-disk.md +++ b/apps/docs/docs/workforce/documents-on-disk.md @@ -192,11 +192,18 @@ A reported file is a document your app was supposed to have. Log a warning and c ## Installing the documents -`resourcesFromDocs` and `referencesFromDocs` each turn records into a resource map keyed by ref. Spread both into the flow's own map: +`resourcesFromDocs` and `referencesFromDocs` each turn records into a resource map keyed by ref. Hand both to the installation, and spread `installation.documents`, which holds both, into the worker flow's own map: ```ts import { defineFlow } from "@flow-state-dev/core"; -import { hireWorkforce, referencesFromDocs, resourcesFromDocs, workerConfigSchema } from "@flow-state-dev/workforce"; +import { + createWorkerInstallation, + hireWorkforce, + referencesFromDocs, + resourcesFromDocs, + workerConfigSchema, + workerFlow, +} from "@flow-state-dev/workforce"; import { readReferencesDirectory, readResourcesDirectory, @@ -213,47 +220,50 @@ for (const { errors } of [roster, references, resources]) { if (errors.length) throw new Error(`workforce: ${errors.length} entries failed to load`); } -const documentMap = resourcesFromDocs(resources.documents); -const referenceMap = referencesFromDocs(references.documents); - -export const supportFlow = defineFlow({ - kind: "support", - cardinality: "collection", - configSchema: workerConfigSchema(), - actions: { - answer: { - inputSchema: z.object({ message: z.string() }), - block: answerQuestion, - userMessage: (input) => input.message, +const supportFlow = workerFlow((installation) => + defineFlow({ + kind: "support", + configSchema: workerConfigSchema(), + session: installation.session(), + resources: { ticket: ticketResource, ...installation.resources, ...installation.documents }, + // Each turn's model reaches only the documents its worker is granted. + resourceVisibility: installation.resourceVisibility, + actions: { + answer: { + inputSchema: z.object({ message: z.string() }), + block: answerQuestion(installation), // loads the turn's worker with installation.resolveWorker + userMessage: (input) => input.message, + }, }, - }, - resources: { ticket: ticketResource, ...documentMap, ...referenceMap }, -}); + }), +); -export const seats = hireWorkforce(roster.workers, { +const installation = createWorkerInstallation({ + standardWorkers: roster.workers, workerFlows: { support: supportFlow }, - documents: documentMap, - references: referenceMap, + documents: resourcesFromDocs(resources.documents), + references: referencesFromDocs(references.documents), }); +export const flows = hireWorkforce(installation); ``` Every file-declared document is installed at `org` scope. A `resources/` entry carries the file's body as its starting content; a `references/` entry points at the file itself, which is read whenever an execution context is built. Editing a reference in your repository reaches agents on the next request, and a read already in flight keeps the body it started with. Every request runs in an organization, so a block reads a document straight off `ctx.resources`. [Authentication](/docs/server/authentication#every-request-runs-in-an-organization) covers where that organization comes from. Each organization gets its own copy of a `resources/` document, so what one organization's agents write is not what another's read. -`documents` and `references` tell the hire which entries on a kind's map are which. [Which seats reach which reference](#who-reaches-what) is worked out against the `references` map, so a kind holding references has to be hired with it. Omit it, or pass one that is missing a reference the kind installed, and `hireWorkforce` throws, naming every reference it was not given. The whole roster is refused, so no seat is hired: +`documents` and `references` tell the installation which entries are which. [Which workers reach which reference](#who-reaches-what) is worked out against the `references` map, so a flow holding references needs it. Omit it, or pass one that is missing a reference the flow declares, and `hireWorkforce` throws, naming every reference it was not given. Nothing is registered: ``` -hireWorkforce refused 1 of 1 worker; nothing was hired: - - worker "engineering.ada" — is hired onto a kind holding 4 reference(s) that hireWorkforce - was not given: "code-of-conduct", "teams/engineering/handbook", +hireWorkforce: 1 standard worker problem(s); nothing was registered: + - worker "engineering.ada" — runs on a flow holding 4 reference(s) its installation was not + given: "code-of-conduct", "teams/engineering/handbook", "teams/engineering/workers/ada/runbook", "teams/support/escalation". … Pass the same map you - installed on the kind: hireWorkforce(workers, { references: referencesFromDocs(refs) }) + declared on the flow: createWorkerInstallation({ references: referencesFromDocs(refs) }) ``` -A kind holding no references needs no map, and a roster hires the same whether you pass one or not. A ref passed in both maps is refused too, naming it. +A flow holding no references needs no map. A ref passed in both maps is refused too, naming it. -Spread the maps rather than passing one on its own. A flow copy created with `supportFlow({ resources })` *replaces* the definition's map instead of merging with it, so a copy handed only `documentMap` loses whatever the flow kind declared. +Every worker on `support` shares its one copy, so the flow declares every document any of them may be granted. The `resourceVisibility` rule narrows each turn: the model reaches the documents its worker's file grants, read-only where the grant is, and every other one answers as if it didn't exist. Your own block code that names a document, as `ctx.resources.handbook`, isn't narrowed. Both functions throw rather than collecting. A record that cannot become a resource stops startup, naming the ref. @@ -288,24 +298,22 @@ const engineering = resourcesFromDocs( ); ``` -A worker's folder is also only part of the name. Putting a `resources/` document under `workers/ada/` addresses it to that seat. It does not keep it from the others. Seats hired into one kind share that kind's flow definition, so by default every one of them reads the same row. +A worker's folder is also only part of the name. Putting a `resources/` document under `workers/ada/` addresses it to that worker. It does not keep it from the others. Every worker on a flow shares that flow's one copy, so by default every one of them reads the same row. -Filtering decides what a whole kind installs. To narrow one seat within a kind, the seat's own file names the documents it may touch under `resources:`, and can take one read-only: see [what a `WORKER.md` says](./workers-on-disk.md#what-a-workermd-says). A seat naming a document its kind was not installed with is refused at the hire, so the filter holds. +Filtering decides what a whole flow installs. To narrow one worker within a flow, the worker's own file names the documents it may touch under `resources:`, and can take one read-only: see [what a `WORKER.md` says](./workers-on-disk.md#what-a-workermd-says). Its model then reaches only those, on every turn: a document it isn't granted answers as one that doesn't exist. A worker naming a document the app didn't declare is refused, so the filter holds. -### Giving one seat a document of its own +### Keeping a document per person -A `resources/` document whose frontmatter carries `flowIsolation: true` gets one row per seat: +A `resources/` document whose frontmatter carries `flowIsolation: true` gets one row per person, per flow, instead of one the person's other flows share: ```md --- -description: This seat's own working notes. +description: Working notes, one copy per person. flowIsolation: true --- ``` -The seat that writes it reads it back. A sibling seat asking for the same document gets its own empty copy, not an error and not the first seat's copy. - -That line is the boundary, not the folder it sits in. A `resources/` document in a worker's folder without it is shared across every seat of the kind, the same as a team's scratchpad. A `references/` file cannot declare it; its boundary is where the file sits. +A person's workers on one flow share that row, since they share the flow's copy. To keep a document to one worker, grant it in that worker's `resources:` and leave it out of the others'. A `references/` file cannot declare `flowIsolation`; its boundary is where the file sits. ### Letting a model read a document @@ -380,4 +388,4 @@ A document that needs a state schema of its own, a `render` function, [reactive - It does not read `WORKER.md` or any `skills/` folder. Those are [Workers on disk](./workers-on-disk.md) and [Skills](../skills/overview.md). It reads a worker folder only to find a document folder inside it. - It does not put a document on an agent's bash mount. A mount carries collections; a document is a single resource, so a shell on the sandbox will not find the handbook as a file. That holds for a reference too, even though its content is a file on your disk. - It does not re-read a reference within a request. The file is read when an execution context is built, so an edit reaches the next request rather than a read already running. -- For a `resources/` document, it does not decide which seat may read which one. `flowIsolation` gives each seat its own copy; nothing there refuses a read. A `references/` document is the exception, and [Who reaches what](#who-reaches-what) is the rule. +- For a `resources/` document, the folder doesn't decide which worker may read which one. A worker's `resources:` list does, for its model. A `references/` document is the exception, and [Who reaches what](#who-reaches-what) is the rule. diff --git a/apps/docs/docs/workforce/durable-hire-store.svg b/apps/docs/docs/workforce/durable-hire-store.svg deleted file mode 100644 index 03ace88075..0000000000 --- a/apps/docs/docs/workforce/durable-hire-store.svg +++ /dev/null @@ -1,88 +0,0 @@ - - Where a hired seat lives - A hired seat is written to the organization's scope in your store as a roster row, and the ready-made hire also writes an inventory row. The running process holds the registered seat, loaded from the roster at start. The roster row lists who is hired now; the inventory row is how the seat is found. Firing deletes both, and a matching incarnation id ties them together. The process copy is lost on restart and rebuilt from the roster. - - - - - - - Where a hired seat lives - Two rows in your store, one seat in each process. Only the roster decides what a start loads. - - - - Your store, organization scope - One copy per organization. Kept across restarts when persistent. - - - Roster row - workforce/roster/support.ada - seatId · flow · instructions - incarnation · settings - The browser reads all but settings. - Who is hired now - Deleted when the seat is fired - User-owned seat: - workforce/roster/~<user>/<seatId> - Only its owner reads it - - - Inventory row - inventory/seats/acme.support.ada - id · kind · door - hired: true · incarnation - Written by the ready-made hire. - A hire you write adds one only - if your handler writes it. - How the seat is found - Deleted on fire, matched by incarnation - - - - Each running process - Gone on restart, rebuilt at start - - - The registered seat - acme.support.ada - Its address: org, then seat id - seatId: "support.ada" - The id it knows itself by - Pinned to its organization - Other callers get 404 - - At start, reloadHiredSeats - reads the roster rows and - hires them. Your app - registers what comes back. - - - - Not a copy - The roster row decides who is hired now. The inventory row is a copy for finding seats; firing deletes both. - The process serves what it loaded at start. A seat hired on another instance answers here after this one restarts. - Firing leaves the sessions, state and resources the seat wrote alone. - Seats declared in WORKER.md files have no roster row. They are read from disk at every start. - diff --git a/apps/docs/docs/workforce/durable-hire.md b/apps/docs/docs/workforce/durable-hire.md index 63e46d115e..2beb6ec70a 100644 --- a/apps/docs/docs/workforce/durable-hire.md +++ b/apps/docs/docs/workforce/durable-hire.md @@ -1,669 +1,102 @@ --- -title: Hiring while the app runs +title: Hiring, forking and firing workers sidebar_position: 11 -sidebar_label: Hiring at runtime -description: "Store a seat hired at runtime, address it per organization, and read the roster back when the app next starts. What the framework gives you, and the admin action you build on top of it." +sidebar_label: Hiring and forking +description: "A user's own workers: hire one, fork a standard worker, edit or fire it. Each is a row in the user's data, seen by every process on the next turn, and nobody else can reach it." --- -# Hiring while the app runs +# Hiring, forking and firing workers -A `WORKER.md` file declares a seat and the app reads it at start. That covers a team you know about when you build the app. Some teams you don't: a customer signs up and needs their own set of workers, or someone adds a seat from a screen rather than from a text editor. +A worker your installation's files declare is a **standard worker**: every user has it, and +nobody can change it while the app runs. Everything else a user adds is a worker of their own, +stored in their data, and nobody else can see it. -For those, you hire while the app is running and write the seat down, so it is still there after a restart, a redeploy, or a crash. +## Hiring a worker -**Hiring at runtime happens over an action you write and guard yourself.** The framework gives you the storage, the address, and the read-back at the next start. The HTTP route that hires, and whatever credential stands in front of it, are yours to build. The `workforce-admin` flow this page walks through is a worked example to copy and adapt, not something the framework ships or that an environment variable switches on. +A hire writes one row to the user's roster, in the organization they're signed in to. Nothing is +registered and nothing restarts: the next turn on any of your processes can use it. -Nothing here changes seats declared in `WORKER.md` files. The app reads them at start, and you remove one by editing its folder. - -## What the framework gives you - -Every seat runs a **flow kind**: one of the flows your app defines, named in a map you pass to `hireWorkforce`, and the same thing a `WORKER.md` names with `flow:`. [Workers on disk](./workers-on-disk.md#when-a-worker-needs-more-than-settings) covers writing one. - -All of these come from `@flow-state-dev/workforce`: - -| Call | What it does | -| --- | --- | -| `defineHiredRosterCollection()` | Declares the stored roster: an organization-scoped resource collection at `workforce/roster/*`, one row per hired seat. Takes no options. | -| `defineHiredRosterPrivateCollection()` | Declares where a [user-owned seat](#hiring-a-seat-only-one-member-can-reach)'s row is written, at `workforce/roster/~/`. Server-side only, and a block that has it in `resources` reaches only the calling user's rows. | -| `seatAddress(orgId, seatId, ownerUserId?)` | The address a hired seat answers on. Org-visible seats are `.`. A user-owned seat is `.~.`, so two people can hire the same seat id. The organization id and the user are percent-escaped, as [The organization has to come from the credential](#the-organization-has-to-come-from-the-credential) spells out. Throws when the organization id is empty, whitespace-only, or not well-formed Unicode (a lone UTF-16 surrogate), or when the seat id is empty or starts with `~`. | -| `hireWorkforce(records, { workerFlows })` | Turns records into configured flow copies, one per record. The same call the file-declared roster goes through. | -| `reloadHiredSeats({ stores, orgIds, workerFlows })` | Reads every stored row back at the next start and hires what it names. Returns `{ seats, problems, byOrg }`. It registers nothing. | -| `createSeatHireBlocks(options)` | Returns `{ hire, fire, brokenSeats, rehire }`: two handlers that run the whole hire and fire sequence, and two that list and [repair a seat whose kind is gone](#repairing-a-seat-whose-kind-is-gone). Mount them as a flow's actions. See [the ready-made handlers](#the-ready-made-hire-and-fire-handlers). | - -`registerHiredSeat` calls your register function with the seat's pin, and refuses a pin that names no organization. `toHiredSeatRow` builds a stored row out of what a hire supplied, and `hiredSeatManifest` turns a row back into the record `hireWorkforce` takes. - -What you write around all of them: the flow that carries the hire action, the credential that decides who may call it and which organization they hire into, the call to `flowstate.register()` that puts a minted seat on the air, and the policy for which organizations a start reloads. - -## The admin flow - -Both ways of hiring on this page run as actions on a flow of your own, here called `workforce-admin`. Whichever you pick, that flow needs a credential that names the organization, and a way to reach the `FlowState` it registers seats on. - -The files on this page go in your app's own source tree, under `src/flows/`, where `fsdev run` looks for flows. None of them belongs in a `workforce/` tree. - -### The organization has to come from the credential - -A hire writes durable state that belongs to an organization, so the organization has to come from something the framework can trust, not from the request body. Configure [`resolvePrincipal`](../server/authentication.md) on the flow and the action's `orgId` comes from there. An `orgId` in the body is ignored, so a caller can't hire into another organization by naming it in the input. - -A hired seat is pinned to that organization, and every request to it is checked against the pin. The principal for that check comes from the seat's own `authentication` when it has one, and from the host's otherwise. With neither, every caller counts as the default organization. That never matches a pin to a real organization, so opening the seat answers `404 Unknown flow` even for the person who hired it. So put the resolver that verified the hire on the seat itself, where you register it, as `registerSeat` [below](#reaching-the-flowstate) does. The seat then answers only callers that resolver accepts. If members should call the seat with their own sign-in, register it with a resolver that verifies them and names the same organization. Don't install it host-wide instead: a host-level resolver applies to every flow the app serves. The exception is a seat hired under the default organization; see [the ready-made handlers](#the-ready-made-hire-and-fire-handlers). - -```ts title="src/flows/workforce-admin/authentication.ts" -import type { AuthenticationConfig } from "@flow-state-dev/core/types"; -import { extractBearerToken, PrincipalResolutionError } from "@flow-state-dev/engine"; - -/** Your own scheme. This one reads `:` pairs out of the environment. */ -const orgByToken = new Map(); -const boundTwice = new Set(); -for (const pair of (process.env.ADMIN_CREDENTIALS ?? "").split(",").filter(Boolean)) { - const at = pair.indexOf(":"); - const [org, token] = [pair.slice(0, at), pair.slice(at + 1)]; - const bound = orgByToken.get(token); - if (bound !== undefined && bound !== org) boundTwice.add(token); - orgByToken.set(token, org); -} -// A token written against two organizations is dropped, not resolved to either. -for (const token of boundTwice) orgByToken.delete(token); - -export const adminAuthentication: AuthenticationConfig = { - requireUser: true, - resolvePrincipal: ({ request }) => { - const token = extractBearerToken(request?.headers?.get("authorization") ?? null); - const orgId = token === null ? undefined : orgByToken.get(token); - if (!orgId) { - throw new PrincipalResolutionError("Invalid admin credential.", { status: 401 }); - } - return { userId: "workforce-admin", orgId }; - }, -}; -``` - -Give each organization its own token. A token written against two organizations would otherwise resolve to whichever one the parser saw last, so a copy-paste in an environment variable would decide which tenant a hire lands in. The sample drops every binding for such a token rather than picking a winner. - -Register the flow only when a usable credential is configured. Then a deployment that has none has no hire route at all, and a call to `/api/flows/workforce-admin/actions/hire` comes back `404 Unknown flow "workforce-admin"` rather than reaching a check that can go wrong. - -`seatAddress` percent-escapes the organization id and the user in a seat's address: lowercase letters, digits and `-` stay, everything else is encoded. `acme` gives `acme.helper`, and `org_pentest_lab` becomes `org%5Fpentest%5Flab.helper`. Build and read addresses with `seatAddress` and `splitSeatAddress(orgId, address)`, which takes the seat id back out, rather than assembling `${orgId}.` prefixes by hand. - -### Reaching the `FlowState` - -Registering a seat needs the `FlowState` the admin flow is itself registered on, and importing that directly is a cycle. Install it instead: - -```ts title="src/flows/workforce-admin/registry-access.ts" -import type { FlowInstance, InstanceOwnerPin } from "@flow-state-dev/core/types"; -import type { FlowState } from "@flow-state-dev/engine"; -import { registerHiredSeat } from "@flow-state-dev/workforce"; - -import { adminAuthentication } from "./authentication"; - -let app: FlowState | undefined; - -/** Call once, immediately after `createFlowState`. */ -export function useFlowState(next: FlowState): void { - app = next; -} - -export function registerSeat(seat: FlowInstance, pin?: InstanceOwnerPin): void { - const state = app; - if (!state) throw new Error("No FlowState to register into."); - registerHiredSeat((instance, owner) => state.register(withAdminResolver(instance), { pin: owner }), seat, pin); -} - -/** The seat answers the credential that hired it. A kind with its own resolver keeps it. */ -function withAdminResolver(seat: FlowInstance): FlowInstance { - const { resolvePrincipal } = adminAuthentication; - if (!resolvePrincipal || seat.authentication?.resolvePrincipal) return seat; - return { ...seat, authentication: { ...seat.authentication, resolvePrincipal } }; -} - -export function releaseSeat(id: string): boolean { - return app?.unregister(id) ?? false; -} - -let registry: Awaited>["registry"] | undefined; - -/** Call once, right after `createFlowState`, alongside `useFlowState`. */ -export async function useRegistry(next: FlowState): Promise { - registry = (await next.getRuntime()).registry; -} - -export const kindAt = (address: string): string | undefined => registry?.get(address)?.kind; -export const instanceAt = (address: string): FlowInstance | undefined => registry?.get(address); -``` - -`kindAt(address)` returns the kind of the flow registered at an address, or `undefined`. `instanceAt(address)` returns the flow instance registered there, or `undefined`. The hire handlers and tools take both as options; [the options table](#the-ready-made-hire-and-fire-handlers) says what each one changes. Both read nothing until `useRegistry` has run, so call it where you call `useFlowState`: +`hireWorkforce` registers a roster flow, `workforce-roster`, beside your worker flows. It carries +four actions: `hire`, `fork`, `edit` and `fire`. Send them as you would any action, in a session +of that flow: ```ts -const app = createFlowState(/* ... */); -useFlowState(app); -await useRegistry(app); -``` - -If a function builds the `FlowState` and runs more than once per process, such as an `openApp()` each test calls, keep the binding in a local `let` so each call registers into its own state. Assign it after `createFlowState`, once the registry exists. The callbacks only run when a hire or fire happens. - -```ts -import { createFlowState, type FlowState, type FlowStateRuntime } from "@flow-state-dev/engine"; -import { - createSeatHireCapability, - defineAgentWorkerFlow, - hireWorkforce, - registerHiredSeat, - type HireOptions, -} from "@flow-state-dev/workforce"; - -export async function openApp(options: AppOptions) { - const kinds: NonNullable = { coder: coderKind }; - let live: { state: FlowState; registry: FlowStateRuntime["registry"] } | undefined; - - const hire = createSeatHireCapability({ - workerFlows: kinds, - register: (worker, pin) => { - if (!live) throw new Error("No FlowState to register into."); - const { state } = live; - registerHiredSeat((instance, owner) => state.register(instance, { pin: owner }), worker, pin); - }, - unregister: (id) => live?.state.unregister(id) ?? false, - kindAt: (address) => live?.registry.get(address)?.kind, - instanceAt: (address) => live?.registry.get(address), - allowKinds: ["coder", "agent"], - }); - kinds.agent = defineAgentWorkerFlow({ uses: [hire] }); - - const hired = hireWorkforce(options.workers, { workerFlows: kinds }); - const state = createFlowState({ - flows: { ...Object.fromEntries(hired.map((worker) => [worker.id, worker])) /* , your other flows */ }, - stores: options.stores, - }); - live = { state, registry: (await state.getRuntime()).registry }; - return state; -} -``` - -If you wrap hired workers with a resolver as `withAdminResolver` does above, apply it to `instance` inside `register`. - -## The ready-made hire and fire handlers - -`createSeatHireBlocks` gives you the whole hire and fire sequence as two handlers you mount as actions. It also returns `brokenSeats` and `rehire`, for [repairing a seat whose kind is gone](#repairing-a-seat-whose-kind-is-gone). Use them when a person or your own code does the hiring, from a screen or an admin route, with no model in front of the call. Mounted as actions, they never ask anyone before they act. +import { createClient, createSessionClient } from "@flow-state-dev/client" -The `seat-hire` capability, `createSeatHireCapability`, gives a seat's kind the same four as tools a model can call. Those can wait for a person's approval first: its `askBefore` option lists the changes that do, and `rehire` always does. [The chief of staff](./chief-of-staff.md#what-asks-first) covers asking. +const sessions = createSessionClient({ baseUrl }) +const { id: sessionId } = await sessions.createSession({ flowKind: "workforce-roster", userId }) -With them, the admin flow needs no `hire.ts` or `fire.ts` of its own: - -```ts title="src/flows/workforce-admin/flow.ts" -import { defineFlow } from "@flow-state-dev/core"; -import { - createSeatHireBlocks, - defineHiredRosterCollection, - defineSeatInventoryCollection, - HIRED_ROSTER_RESOURCE, - SEAT_INVENTORY_RESOURCE, -} from "@flow-state-dev/workforce"; - -import { deskClerkFlow } from "../desk-clerk/flow"; -import { adminAuthentication } from "./authentication"; -import { registerSeat, releaseSeat } from "./registry-access"; - -/** The kinds a hire may name. Pass this same map to `reloadHiredSeats`. */ -export const kinds = { "desk-clerk": deskClerkFlow }; - -const seatHire = createSeatHireBlocks({ - workerFlows: kinds, - register: registerSeat, - unregister: releaseSeat, -}); - -const workforceAdmin = defineFlow({ - kind: "workforce-admin", - requireUser: true, - authentication: adminAuthentication, - // The handlers read both collections under exactly these keys. - resources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection(), - }, - actions: { - hire: { block: seatHire.hire }, - fire: { block: seatHire.fire }, - }, -}); - -export default workforceAdmin(); -``` - -**Declare both collections on the flow, under `HIRED_ROSTER_RESOURCE` and `SEAT_INVENTORY_RESOURCE`.** The handlers look them up by those keys. Without them every hire fails with `Cannot read properties of undefined (reading 'create')`, before a row is written or a seat registered. - -`createSeatHireBlocks` takes these options: - -| Option | What it's for | -| --- | --- | -| `workerFlows` | The worker flows a hire may name, the same map you pass to `hireWorkforce` and `reloadHiredSeats`. The built-in `agent` kind is always hireable too, unless `allowKinds` leaves it out. A flow marked `standardOnly` is kept for declared workers, so a hire onto it is refused. | -| `register(seat, pin)` | Puts a minted seat on the air. `pin` is `{ orgId, userId? }` for the organization the hire ran under. | -| `unregister(address)` | Releases an address in this process and returns whether anything held it. | -| `kindAt?(address)` | The kind serving an address right now, if any. Lets `hire` refuse an address that is already served, or a seat id a declared seat answers on, before writing anything, and lets `fire` leave an address registered when a different kind holds it. | -| `instanceAt?(address)` | The seat serving an address right now, if any. With it, `fire` releases only the seat its roster row minted, and a hire or re-hire stopped part-way by another call releases only its own seat. Without it, `fire` goes by the kind, and a stopped call leaves its seat registered in this process until the next start. | -| `refuseRosterAdmin?` | When `true`, `hire` and `rehire` refuse settings that would give the new seat the roster tools: `hire`, `fire`, `rehire` or `brokenSeats` in `tools:`, or the `seat-hire` capability under `capabilities:`. Default `false`. | -| `allowKinds?` | The subset of `workerFlows` these handlers may mint. | -| `mailboxBoards?` | Mailbox board ids. For each one the new seat doesn't declare, the hire's `warning` names it, since rows filed on that board sit pending until something works them. | - -The seats these handlers and the `seat-hire` tools hire are always org-visible: pinned to the organization and no user, so any caller the seat's resolver places in that organization can call one, and its roster row, `instructions` included, is readable by a browser in that organization. For a seat only one member can reach, write the hire yourself as in [Hiring a seat only one member can reach](#hiring-a-seat-only-one-member-can-reach). - -Both handlers take the organization from the principal your `resolvePrincipal` returns for the session, as [The organization has to come from the credential](#the-organization-has-to-come-from-the-credential) describes. When no `resolvePrincipal` is configured for the request, neither on the flow nor on the host, every session belongs to the framework's default organization, `__fsd_default_org__`. A hire there succeeds. Its seat answers on `%5F%5Ffsd%5Fdefault%5Forg%5F%5F.` and is reloaded at the next start like any other, and it is pinned to the default organization. - -A resolver can't name `__fsd_default_org__`; a request whose resolver does is refused with `401`. A resolver that returns a real organization doesn't match the pin, so its callers get `404 Unknown flow`. A seat hired under the default organization is reachable only when no resolver applies to it, neither on the seat nor on the host. Register it without a seat-level resolver on a host with none, and every caller is treated as unauthenticated and placed in the default organization. That suits a development app with no sign-in. For a deployment that signs people in, hire under a real organization and install the resolver on the seat the way `registerSeat` does in [Reaching the `FlowState`](#reaching-the-flowstate). - -### Hiring - -`hire` takes `{ seatId, flow, settings?, instructions? }`. Any other key is refused, except `orgId`, which is accepted and ignored. Once the flow is registered, a hire is an ordinary action call: - -```bash -# Convenience for the curl commands on this page. Nothing reads it but your shell; -# the app reads ADMIN_CREDENTIALS, above. -export ADMIN_TOKEN=s3cr3t-acme - -curl -X POST localhost:3000/api/flows/workforce-admin/actions/hire \ - -H 'content-type: application/json' \ - -H "authorization: Bearer $ADMIN_TOKEN" \ - -d '{"userId":"you", - "input":{"seatId":"support.ada","flow":"desk-clerk", - "settings":{"desk":"front"}, - "instructions":"You work the front desk."}}' -``` - -It returns the seat id and the address the seat answers on: - -```json -{ "seatId": "support.ada", "address": "acme.support.ada" } -``` - -`warning` is added when the new seat doesn't declare one of the `mailboxBoards`. - -A hire runs in this order: - -1. It refuses a kind that isn't in `workerFlows`, or that `allowKinds` leaves out, and names the kinds it can hire. It refuses a kind marked `standardOnly` in `workerFlows`, since every seat it hires is a [hired worker](./workers-on-disk.md#which-flows-can-run-workers). It refuses an address `kindAt` reports as already served, an address a seat declared in a worker file has an inventory row at, and a seat id `kindAt` reports a declared seat under: `"chief-of-staff" is the id of a seat this app declares (kind "agent"). Hire under another id.` With `refuseRosterAdmin: true`, it also refuses settings that would give the new seat the roster tools: `hire`, `fire`, `rehire` or `brokenSeats` in `tools:`, or the `seat-hire` capability under `capabilities:`. -2. It mints the seat, which runs the kind's settings schema. If the schema refuses the seat, nothing is written and the hire fails with a message that quotes the kind's own refusal. For a kind `coder` whose schema requires `document: z.string().min(1)`, hired as `coder-2` in organization `acme` with no settings, the message is below. The kind's own refusal is quoted after `refused it:`. - - ```text - "acme.coder-2" was not hired, and nothing was written. Kind "coder" refused it: hireWorkforce refused 1 of 1 worker; nothing was hired: - - worker "acme.coder-2" — Flow "coder" instance "acme.coder-2" has an invalid config bag: "document": Required. - If that names a setting, call hire again with it in `settings`. - ``` - - The same call with `settings: { "document": "teams/eng/feature-brief" }` hires the seat. For the `seat-hire` tools a model calls, this message is the tool's result, so the model can correct the call and try again in the same turn. -3. It writes the roster row with `create()`. A second hire of the same seat id fails here with `Resource instance "workforce/roster/support.ada" already exists`, including two hires arriving at once. -4. It calls your `register`. If that throws, the row from step 3 is deleted and the error is passed on. -5. It writes an inventory row at `inventory/seats/
`, replacing only a row left by an earlier hire at that address, and only while its own roster row is still there. If this write fails, the seat is hired and answering but has no inventory row. If the seat is fired or hired again while this hire is finishing, the hire stops and takes back only what is still its own. - -### Firing - -`fire` takes `{ seatId }` (again, `orgId` is accepted and ignored) and returns `{ seatId, address, released }`, plus `alreadyGone: true` in the one case described at the end of this section. - -```bash -curl -X POST localhost:3000/api/flows/workforce-admin/actions/fire \ - -H 'content-type: application/json' \ - -H "authorization: Bearer $ADMIN_TOKEN" \ - -d '{"userId":"you","input":{"seatId":"support.ada"}}' -``` - -It refuses a seat id this organization never hired with `This organization hired no seat "support.ada".` Otherwise it deletes the roster row, then calls your `unregister` on the address (`released` is what that returned), then deletes the seat's row from the [inventory](./inventory.md). If `kindAt` reports a different kind at the address than the row names, the row is still deleted but the address stays registered, its inventory row is left alone, and `released` is `false`. With `instanceAt`, it releases the address only when the seat there was minted from the row it deleted, and removes only the inventory row that seat's hire published; a declared seat's row is never removed. Without `kindAt` or `instanceAt`, `fire` releases whatever holds the address, the same as the [hand-written fire](#firing-a-seat). - -The row is gone straight away. When `released` is `true`, the address also stops answering **on the process that handled the request**; when it is `false`, whatever holds the address keeps answering. Work already running finishes and is saved. Nothing is cancelled and nothing is truncated. - -Firing removes the seat, not its history. Sessions, state and resources it wrote are left alone. If you want those gone, delete them yourself. - -Because firing removes the seat's inventory row, a team list built from the inventory stops showing it. An inventory row can still outlive its roster row, so a list that joins the inventory with the roster hides any row no roster row backs. `listedSeatRows` from `@flow-state-dev/workforce/browser` is that join. A user-owned seat's roster row is readable only by its owner, on the server, so a browser list can't back it and leaves it out. - -If the process dies between the two deletes, the inventory row is left too. Calling `fire` again for that seat removes it, a user-owned one included, and answers with `released: false` and `alreadyGone: true`. It only does that for a row marked `hired: true`. A declared seat can sit at the same address, so a row that doesn't say it was hired is never removed this way. - -## Calling a hired seat - -The seat answers immediately, on the same route as any other flow. Its address carries the organization that hired it. With `registerSeat` as written, it answers any admin token configured for that organization, since each resolves to the same principal the seat is pinned to: - -```bash -curl -X POST localhost:3000/api/flows/acme.support.ada/actions/answer \ - -H 'content-type: application/json' \ - -H "authorization: Bearer $ADMIN_TOKEN" \ - -d '{"userId":"you","input":{"note":"is the printer fixed?"}}' +const roster = createClient({ flowKind: "workforce-roster", userId, baseUrl }) +await roster.sendAction("hire", { id: "scribe", flow: "agent", instructions: "Take short notes." }, { sessionId }) ``` -When you build the URL by hand, pass the address through `encodeURIComponent(address)` and use the result as one path segment. The address `org%5Fpentest%5Flab.helper`, for the organization `org_pentest_lab`, goes out as `/api/flows/org%255Fpentest%255Flab.helper/actions/answer`. Sent as-is, the `%5F` is read as an underscore, which names a different seat, and the seat is not found. `acme.support.ada` has nothing to escape and works as written. `@flow-state-dev/client` and the React hooks encode the address for you. - -The organization is part of the address because two organizations can both want a seat called `support.ada`, and an app serves one flat set of addresses. It identifies the seat. It does not authorize anything: who may call it is decided by the principal on the request. The body does not name the organization. - -## Who can reach a hired seat - -![Two seats hired in the acme organization. The org-visible seat answers at acme.support.ada; its roster row can be listed by any acme member's browser, showing seatId, flow and instructions, and any acme member the resolver admits can use it. The user-owned seat answers at acme.~alice.research; its roster row, at workforce/roster/~alice/research, has no browser read, and only alice signed in to acme can use it, so bob in acme gets 404 Unknown flow. Outside acme, whether globex or alice signed in there, both seats answer 404 Unknown flow and are left out of the flow list; a research seat in globex is hired there and starts empty. The row is not the seat, the address is not a permission, and firing deletes the roster row and the inventory row the hire wrote.](./hired-seat-reach.svg) - -A hired seat answers only the callers its `pin` admits: the organization that hired it, and the one person who hired it when it is user-owned. Anyone else gets `404 Unknown flow`, the same answer as an address your app does not serve, and `GET /api/flows` leaves the seat out. A session opened earlier can't be resumed by them either. Knowing a seat's address grants nothing. - -A task board in another organization can't hand work to the seat either. The task ends errored and unclaimed, with `flow-not-found` and `no flow instance "
" is registered in this process`, as for an address nobody holds. With debug endpoints switched on, the debug listing doesn't show another person's private roster row. - -A caller the seat's resolver refuses, such as a request with no credential, gets that resolver's error before the pin is checked. With the `adminAuthentication` above installed on the seat, that is `401 Invalid admin credential.` +`hire` takes an id, the flow the worker runs on (`agent` when you leave it out), and its +settings, the same keys a `WORKER.md` accepts. The worker's flow checks the settings when the row +is saved. A bad value, a flow your installation doesn't run workers on or keeps for standard +workers, or an id already on the user's roster is refused, and nothing is written. An id can't be +a standard worker's: fork it instead. -**The check is as strong as the principal your resolver returns.** "Who is asking" is the principal your [`resolvePrincipal`](../server/authentication.md) returns: a user and the organization they are signed in to. Use a resolver that verifies both, and install it on each hired seat as well as on the flow that hires it, as `registerSeat` in [Reaching the `FlowState`](#reaching-the-flowstate) does. - -## Reading the roster back at the next start - -`reloadHiredSeats` reads each organization's stored rows and hires what they name. It registers nothing, so you loop over what comes back: +The same four writes are blocks, from `createWorkerHireBlocks(installation)`, if you'd rather +mount them on a flow of your own or hand them to a model as tools: ```ts -// Wherever you build the FlowState, after createFlowState and useFlowState -// (and useRegistry, if you pass kindAt and instanceAt). -const runtime = await flowstate.getRuntime(); - -// Your policy. This one reloads every organization the deployment has a record for. -const orgIds = [...new Set((await runtime.stores.org.list()).map((r) => r.orgId))]; - -const { seats, problems } = await reloadHiredSeats({ - stores: runtime.stores, - orgIds, - workerFlows: kinds, // the map the hire action uses: exported from flow.ts or hire.ts, whichever path you took -}); - -for (const seat of seats) { - try { - registerSeat(seat, seat.ownerPin); - } catch (error) { - problems.push(`${seat.id} — ${String(error)}`); - } -} -``` - -Which organizations a start reloads is your app's policy, so you pass them in. - -`problems` is a list of strings, one per row that did not become a seat, each naming the organization, the row key and the reason. A stored seat on a flow marked `standardOnly` is one of them: it is not hired, its reason names the flow and says it is kept for declared workers, and its row is left as stored. Remove the mark and it comes back at the next start. Handle it rather than logging it: the number of rows in the roster and the number of seats answering are two different numbers, and a warning on stderr is not a report. - -One way to handle it is to put it on screen. `Roster` from `@flow-state-dev/react` lists the seats and takes `problems` alongside them, so both numbers are visible in the same place: - -```tsx -import { Roster } from "@flow-state-dev/react"; - - -``` - -Keep the list from the boot somewhere your app can reach it. `reloadHiredSeats` runs on the server, and nothing carries its result to a browser on its own. - -The same result splits both lists by organization. `byOrg` has one entry per organization you passed in, in that order, each with that organization's `orgId`, `seats` and `problems`. An organization with nothing to report still gets an entry, with empty lists. Store each organization's problems where only that organization reads them, and write the empty ones too, so a problem fixed since the last start stops showing. A seat your registry then refuses belongs in its own organization's list as well. - -The roster collection itself is readable by a browser, so the seats come straight from it. Being organization-scoped, that read resolves against the organization the reading session belongs to, so a `Roster` panel lists the roster of its own session's organization. For a seat to show up on a screen, the screen's session has to resolve the same organization the hire did. A seat crosses as `seatId`, `flow` and `instructions`. The settings bag stays on the server. - -The call is bounded on both sides, and neither bound returns a partial roster: - -- **`maxOrgs`, default 100.** Hand it more organizations than that and it throws before it reads anything, naming both numbers. Raise it with the `maxOrgs` option. -- **`timeoutMs`, default 10000.** One bound over the whole read, not per organization. The error names the organization the read was waiting on. - -A read the store will not complete throws the same way. Nothing is loaded in any of these cases, and instances already running are untouched, so a transient storage failure costs a restart rather than the roster. - -## Repairing a seat whose kind is gone - -Cut a kind from your app and every seat hired into it stops coming back. The start skips each one and names it in `problems`, and keeps doing so on every start, because nothing is deleted at start. The row is the only record of who the seat was, so keeping or removing it is your call. - -`createSeatHireBlocks` gives you two more handlers to make that call with, mounted as actions beside `hire` and `fire`: - -```ts title="src/flows/workforce-admin/flow.ts" - actions: { - hire: { block: seatHire.hire }, - fire: { block: seatHire.fire }, - brokenSeats: { block: seatHire.brokenSeats }, - rehire: { block: seatHire.rehire }, - }, -``` - -`brokenSeats` lists the stored seats in the caller's organization that wouldn't start. It runs the same check the start runs, so the two lists always agree, and it writes nothing. The check mints each seat, healthy ones included, so treat it as an admin read you make when you need it, not something to poll: - -```bash -curl -X POST localhost:3000/api/flows/workforce-admin/actions/brokenSeats \ - -H 'content-type: application/json' \ - -H "authorization: Bearer $ADMIN_TOKEN" \ - -d '{"userId":"you","input":{}}' -``` - -It answers with one entry per seat, `{ seatId, key, owner, kind, reason, detail }`. `key` is the row's storage key, `owner` is whose row it is (`"organization"` or `"me"`), and `detail` is the sentence the start printed for it: - -```json -[{ "seatId": "support.joe", "key": "workforce/roster/support.joe", "owner": "organization", "kind": "desk-clerk", "reason": "kind-gone", - "detail": "hireWorkforce refused 1 of 1 worker; nothing was hired:\n - worker \"acme.support.joe\" — names flow \"desk-clerk\", which is not in the worker flows passed to hireWorkforce. Worker flows passed: \"agent\"" }] -``` - -Each entry has one of three reasons: - -| `reason` | What happened | What you can do | -| --- | --- | --- | -| `kind-gone` | The seat's kind isn't in the map you passed | Retire it, or re-hire it onto a kind you carry | -| `refused` | The kind is there but now refuses the seat's settings | Retire it, or re-hire it with settings the kind accepts | -| `unreadable` | The row can't be read, or doesn't belong to this organization | Retire it. Its `seatId` is the row's key, which is what `fire` takes | - -**To retire a seat, fire it.** `fire` removes the roster row and the inventory row. Nothing was serving the seat, so there's no address to release and `released` is `false`. The next start names nothing for it. An `unreadable` row is deleted by its key and nothing else is touched, so that answer's `address` is `null`. - -**To keep the seat, re-hire it.** `rehire` takes the seat id, the kind to run it on, its settings for that kind, and optionally new instructions and the `owner` `brokenSeats` reported. Pass `owner` when the caller has a seat of their own under the same id as an organization's; without it, `rehire` refuses rather than pick one. The seat keeps its id and its address, so mailboxes that list it and sessions it owns carry on: +import { createWorkerHireBlocks } from "@flow-state-dev/workforce" -```bash -curl -X POST localhost:3000/api/flows/workforce-admin/actions/rehire \ - -H 'content-type: application/json' \ - -H "authorization: Bearer $ADMIN_TOKEN" \ - -d '{"userId":"you","input":{"seatId":"support.joe","flow":"agent", - "instructions":"Answer billing questions. Hand refunds to a person."}}' +const { hire, fork, edit, fire } = createWorkerHireBlocks(installation) ``` -The old kind's settings are not carried over, since they were written for a different kind. The instructions are, unless you pass new ones. `rehire` checks everything before it writes: it refuses a seat that would still start (to change a working seat's kind, fire it and hire it again), an `unreadable` row, a kind your app doesn't carry or `allowKinds` leaves out, and settings the kind refuses. If registering the seat fails after the row was written, the old row is written back and the error is named. If the process dies after the row was written, or the inventory row can't be written once the seat is serving, run the same `rehire` again. The row stays marked as an unfinished repair until the seat is registered and its inventory row written, and the same call finishes a marked row. A working seat with no unfinished repair is refused as above, even when you pass its current kind and settings. If the seat is fired while a re-hire is finishing, the re-hire stops and keeps nothing. If two repairs of one seat arrive at once, one lands and the other is refused. - -Neither handler asks anyone. They are what you run once a person has said yes, so in a flow a model drives, put them behind an approval: raise a `human_approval` suspension with `ctx.suspend`, and fire or re-hire only when it resumes with Approve. Both are safe to run again if the process dies part-way, so a restart between the ask and the answer leaves the seat as it was until someone answers. - -Nothing here picks a kind for you or loads a missing one. If you want the old kind's seats back as they were, ship the kind again. - -**User-owned seats.** The start names a [user-owned seat](#hiring-a-seat-only-one-member-can-reach) whose kind is gone like any other. For the handlers to reach it, declare `defineHiredRosterPrivateCollection()` on the same flow under `HIRED_ROSTER_PRIVATE_RESOURCE`. Then `brokenSeats` lists the caller's own user-owned seats beside the organization's, each with its `owner`. Pass that `owner` to `fire` or `rehire` to act on the same row. Without it, they act on the only row under the seat id, and refuse when the caller has both an organization seat and their own under one id. That collection only ever serves a row to the member it belongs to, so each member lists and repairs their own. Without it, the handlers reach organization-wide seats only. - -## Writing the handlers yourself - -Writing the hire and fire handlers yourself puts every step in your own code. It is also the only way to hire a seat that belongs to one member. - -### Hiring a seat - -A hire is a handler in the admin flow, and the order it works in matters. Refuse what you can refuse before anything is written. Mint the seat, which is where the flow kind's own settings schema runs. Write the row. Register. If registering fails, delete the row you just wrote, so a hire that failed leaves nothing behind. - -```ts title="src/flows/workforce-admin/hire.ts" -import { handler } from "@flow-state-dev/core"; -import type { JsonObject } from "@flow-state-dev/core"; -import type { ResourceCollectionRef } from "@flow-state-dev/core/types"; -import { - hireWorkforce, - hiredSeatManifest, - seatAddress, - toHiredSeatRow, -} from "@flow-state-dev/workforce"; -import { z } from "zod"; - -import { deskClerkFlow } from "../desk-clerk/flow"; -import { registerSeat } from "./registry-access"; - -/** The kinds a hire may name. Pass this same map to `reloadHiredSeats`. */ -export const kinds = { "desk-clerk": deskClerkFlow }; - -export const hireSeat = handler({ - name: "hire-seat", - inputSchema: z.object({ - seatId: z.string().min(1), - flow: z.string().min(1), - settings: z.record(z.unknown()).default({}), - instructions: z.string().optional(), - }), - outputSchema: z.object({ address: z.string(), orgId: z.string() }), - execute: async (input, ctx) => { - // From the verified principal. The request body never decides this. - const orgId = ctx.org?.identity.orgId ?? ctx.org?.identity.id; - if (!orgId) throw new Error("This credential resolves no organization."); +## Forking a worker - const address = seatAddress(orgId, input.seatId); - if (!Object.hasOwn(kinds, input.flow)) { - throw new Error(`This app carries no flow kind "${input.flow}".`); - } - - const row = toHiredSeatRow({ - seatId: input.seatId, - flow: input.flow, - settings: input.settings, - instructions: input.instructions ?? null, - // Lets a reload refuse this row if it is ever read under another organization. - owningOrgId: orgId, - }); - - // Minted from exactly what will be stored, so the row can rebuild the seat - // at the next start. The kind's settings schema runs here, before any write. - const record = hiredSeatManifest(orgId, row); - if ("problem" in record) throw new Error(record.problem); - const [seat] = hireWorkforce([record.manifest], { workerFlows: kinds }); - if (!seat) throw new Error(`"${address}" could not be hired.`); - - const roster = ctx.resources.roster as unknown as ResourceCollectionRef; - - // `create()`, never `upsert()`. Its already-exists throw is what refuses a - // second hire of the same seat, including two arriving at once. - await roster.create(input.seatId, row as unknown as JsonObject); - - try { - registerSeat(seat, record.manifest.ownerPin); - } catch (error) { - await roster.delete(input.seatId); - throw error; - } - - return { address, orgId }; - }, -}); -``` - -A row holds the seat's id within its organization, the flow kind, the settings bag, and the instructions. The settings bag is stored and handed back verbatim, including keys a later version of the kind adds, because it belongs to that kind's schema rather than to the roster's. - -Mount it, and the `fireSeat` handler from [Firing a seat](#firing-a-seat), on the admin flow: - -```ts title="src/flows/workforce-admin/flow.ts" -import { defineFlow } from "@flow-state-dev/core"; -import { defineHiredRosterCollection } from "@flow-state-dev/workforce"; - -import { adminAuthentication } from "./authentication"; -import { fireSeat } from "./fire"; -import { hireSeat } from "./hire"; - -const workforceAdmin = defineFlow({ - kind: "workforce-admin", - requireUser: true, - authentication: adminAuthentication, - resources: { roster: defineHiredRosterCollection() }, - actions: { - hire: { block: hireSeat }, - fire: { block: fireSeat }, - }, -}); - -export default workforceAdmin(); -``` - -Call it with the same request as [the ready-made hire](#hiring). This handler answers with its own output: - -```json -{ "address": "acme.support.ada", "orgId": "acme" } -``` - -### Firing a seat - -Firing is the mirror image: delete the row, then release the address. Inside a `fireSeat` handler taking `{ seatId }`, with `orgId` resolved from the credential the same way: +`fork` starts a new worker of the user's own from another worker's configuration, under a new id: ```ts -const roster = ctx.resources.roster as unknown as ResourceCollectionRef; -const existing = await roster.getOptional(input.seatId); -if (!existing) throw new Error(`This organization hired no seat "${input.seatId}".`); - -await roster.delete(input.seatId); - -// false when nothing in this process was holding the address. -const released = releaseSeat(seatAddress(orgId, input.seatId)); +await roster.sendAction("fork", { from: "researcher", id: "my-researcher" }, { sessionId }) ``` -Call it with the same request as [the ready-made fire](#firing), and what that section says about running work and the seat's history holds here too. The roster is organization-scoped, so that `getOptional` is also the fence. Another organization's seat has no row here, and neither does a seat declared in a `WORKER.md` file; both come back undefined and are refused. +The fork keeps a copy of the standard worker's instructions, and doesn't change when your +installation's files do. Fork again to pick up a change. The standard worker doesn't change, for +this user or anyone else. -**The release step is not fenced the way the row check is.** `releaseSeat` unregisters whatever currently holds the address, whether or not this action is what put it there. If you also declare seats in files, and one of them could end up at an address a hire once used, keep a record of which addresses your hire action registered and release only those. +A fork starts with no conversations. The user's sessions with the worker they forked stay with +that worker. -### Hiring a seat only one member can reach +## Changing or firing a worker -The hire above is org-visible: the seat is pinned to the organization and no user, and its row is one a browser in that organization can read. With `registerSeat` as written, the seat answers any caller holding that organization's admin token. To let members call it with their own sign-in, register it with a resolver that verifies them, as described [above](#the-organization-has-to-come-from-the-credential). To hire a seat that belongs to one member, change the hire like this, in the handler and in `flow.ts`: +`edit` replaces each field you give it. The edit reaches the worker's next turn, in every +session. If the edit moves the worker to a different flow, its earlier sessions stop taking +messages, with both flows named: a session stays on the flow it was created on. Start a new +session to talk to the worker on its new flow. -- **Stamp the owner on the row.** Pass `ownerUserId` to `toHiredSeatRow`, and keep `owningOrgId`, the organization the hire runs under: that stamp is what lets a reload refuse the row if it is ever read under another organization. `hiredSeatManifest` then pins the record to that user as well as the organization, and registering with that pin is what closes the seat to everyone else. -- **Put the owner in the address.** `seatAddress(orgId, seatId, userId)` returns `.~.`, so two members can each hire `research` without colliding. -- **Write the row through the private collection.** Install `defineHiredRosterPrivateCollection()` beside the roster and write with the object key `{ owner, seat }`, where `owner` is `~` followed by the user id passed through `encodeUserSegment` (the same escaping `seatAddress` applies). The row lands at `workforce/roster/~/`, which the browser-readable roster does not list. +`fire` deletes the row. Its past sessions stay readable to their owner. A new message to one is +refused with the worker named as fired. Every process sees the fire on the next turn. -```ts title="src/flows/workforce-admin/hire.ts (the lines that change)" -import { encodeUserSegment } from "@flow-state-dev/workforce"; +## Who can reach a worker -// The owner is the user on the verified principal, never a field in the body. -const userId = ctx.session.identity.userId; -if (!userId) throw new Error("This credential resolves no user."); +Only its owner. A worker belongs to one user in one organization: another member can't list it, +open its sessions, send it a message or create a session with it. Asking for another user's +worker gets the same answer as asking for one that doesn't exist. A user who belongs to two +organizations has a separate roster in each. -const address = seatAddress(orgId, input.seatId, userId); +## What is stored -const row = toHiredSeatRow({ - seatId: input.seatId, - flow: input.flow, - settings: input.settings, - instructions: input.instructions ?? null, - owningOrgId: orgId, - ownerUserId: userId, -}); +Each worker the user hires or forks is one row in their user scope at `workforce/workers/`. +A standard worker isn't stored: it is read from your files each time, so a deploy that changes a +file changes it for everyone. On the built-in `agent` flow, what a worker remembers is kept per +worker, so two of one user's workers never read each other's notes. On a flow you write, that is +up to you: see [Where a worker's data lives](./workers-on-disk.md#where-a-workers-data-lives). -// Mint exactly as before: hiredSeatManifest(orgId, row), then hireWorkforce. +## After a hire, refresh the roster -const owned = ctx.resources.rosterPrivate as unknown as ResourceCollectionRef; -const key = { owner: `~${encodeUserSegment(userId)}`, seat: input.seatId }; -await owned.create(key, row as unknown as JsonObject); +Read the roster again after each turn. A turn that hires, forks or fires changes it, and nothing +tells you which tool ran, so you don't need to watch for a tool's name. -try { - registerSeat(seat, record.manifest.ownerPin); // carries { orgId, userId } -} catch (error) { - await owned.delete(key); - throw error; -} -``` +```ts +import { createWorkforceClient } from "@flow-state-dev/workforce/browser" -```ts title="src/flows/workforce-admin/flow.ts" -resources: { - roster: defineHiredRosterCollection(), - rosterPrivate: defineHiredRosterPrivateCollection(), -}, +const workforce = createWorkforceClient({ userId, baseUrl }) +const workers = await workforce.roster() +// [{ id: "scribe", flow: "agent", standard: false, description: null }, +// { id: "researcher", flow: "agent", standard: true, description: "Finds things out." }] ``` -The owner comes from the credential, so your resolver has to name the member making the call. The example resolver above answers `workforce-admin` for every token, which would make every seat belong to that one user and nobody else. - -The private collection reaches only the calling user's own rows. `create`, `get` and `delete` on a key naming another user throw `A row of an owner-private collection is readable only by the user it belongs to.`, `getOptional` on one returns `undefined`, and `list` leaves such rows out. Firing a user-owned seat reads and deletes through the same collection and key, then releases `seatAddress(orgId, seatId, userId)`. `reloadHiredSeats` needs no change: it reads these rows with the rest, and each seat's `ownerPin` carries the user. - -The private roster collection is an [owner-private collection](../resources/collections.md#owner-private-collections): each row's owner segment is the member who hired the seat. So a row is served only to that member, in every process over the store, and no other collection in your app can list or write it. - -Once a flow declaring the private collection is registered, the app refuses to start if any flow declares an org-scoped collection that could reach a user-owned row: `workforce/roster/**`, `workforce/roster/[owner]/notes`, a copy of `workforce/roster/[owner]/[seat]`, or a wide pattern such as `[tenant]/**`. For the org roster, declare `workforce/roster/*`, which only ever sees org-visible rows. - -Once registered, the seat answers its owner only. Any other member gets `404 Unknown flow`. The row has no browser read at all, so a roster panel reading the browser collection does not show it, not even to its owner. - -## What is stored, and where - -![A hired seat is two rows in the organization's store and one registered seat in each process](./durable-hire-store.svg) - -### The roster - -One row per seat in the organization's scope: at `workforce/roster/`, or at `workforce/roster/~/` for a user-owned seat. It is read through the same storage adapter as everything else the app persists, so a Postgres-backed app keeps its roster in Postgres and an in-memory app keeps it for as long as the process lives. - -The roster is not the [inventory](./inventory.md). An inventory row means *was registered in this organization*, and the start never removes one. A roster row is removed when the seat is fired, and so is a hired seat's inventory row. A seat hired through [`createSeatHireBlocks`](#the-ready-made-hire-and-fire-handlers) or the `seat-hire` tools gets both rows. A seat hired by a handler you wrote gets only the rows it writes: the `hire-seat` handler in [Hiring a seat](#hiring-a-seat) writes a roster row and no inventory row. Anything that wants one list of every seat, declared and hired, joins the two itself. - -### What a seat saves for a person - -![Where a hired seat keeps what it learns about alice. Inside the acme organization: one cell for alice in acme, holding her user record and her shared user-scoped resources, which every flow in acme uses, hired seats included; and one cell per seat for flow-isolated data, such as alice in acme for acme.support.ada. In globex, alice has a separate cell of her own, which nothing in acme reads. A projected resource is stored by your own hooks, so key its rows by the organization too.](./seat-person-data.svg) - -A seat keeps what it learns about a person in the same place every flow in the organization does: one cell for that person in that organization. With flow isolation, it keeps one cell per person per seat, still inside the organization. A resource's own `flowIsolation` decides which applies; a resource that doesn't set it follows the flow's `isolateUserState`. - -A user resource backed by your own hooks (a projected resource) is stored by your app, not the framework. Its hooks receive the person's id and the organization, so key its rows by `orgId` as well, or a person sees in one organization what they saved in another. - -## Limits - -**A new seat is served by the process that hired it. Other processes pick it up when they next start.** If your app runs on several instances, or on a platform that starts a fresh instance per request, a seat hired a moment ago may answer on one and not yet on another. The stored row is the real roster; what a process serves is that row, loaded when it started. Plan for a short window rather than an instant one, or restart after hiring if you need every instance in step. - -**Firing has the same window, and it is the sharper end of it.** A fired seat is gone from storage immediately and will not come back at any start. But a sibling instance that is already serving it keeps serving it until that instance restarts. If you fire a seat because it should stop answering right now, restart the app rather than assuming the fire did it. - -**Inside the organization, an address is not a permission.** An org-visible seat answers every member your resolver admits, and whatever its instructions say can come back in an answer. If only one member should reach a seat, [hire it user-owned](#hiring-a-seat-only-one-member-can-reach). For any other rule about who may call a seat, put your own check in front of it. Outside the organization the seat is closed. [Who can reach a hired seat](#who-can-reach-a-hired-seat) lists every door. - -**A start may serve fewer seats than the roster names.** If a stored seat names a flow kind the current code no longer has, or carries settings that kind no longer accepts, that seat is skipped and named in `problems`. The app starts and every other seat answers. The skipped row is left exactly as it was: nothing is repaired or deleted on your behalf. Fix it by putting the kind back, or by firing the seat. - -**The flow list is public, except for hired seats.** `GET /api/flows` needs no credential. Any caller who can reach your app sees every flow registered without a `pin`, at start or later: every flow your app defines, every seat declared in a `WORKER.md` file, and any flow your code registers after start. A hired seat is listed only to callers who could open it, as described in [Who can reach a hired seat](#who-can-reach-a-hired-seat). A caller your resolver cannot identify sees no hired seats. A flow you register with a `pin` yourself is listed the same way. If those names are sensitive, put your own check in front of the route. - -**A seat hired at runtime skips the webhook start-up check.** [Webhook providers](../server/webhooks.md) are the per-provider mechanics an app configures at mount, and a start refuses when a registered flow subscribes to one the app never configured. That check runs over the flows registered at start, so it does not see a seat hired after it. Until the next start, deliveries to that seat's webhook route come back `404 webhook_not_found`; at the next start the mismatch is raised and the start refuses. +To talk to one, see [Talking to a worker](./workers-on-disk.md#talking-to-a-worker). diff --git a/apps/docs/docs/workforce/hired-seat-reach.svg b/apps/docs/docs/workforce/hired-seat-reach.svg deleted file mode 100644 index 8de793f528..0000000000 --- a/apps/docs/docs/workforce/hired-seat-reach.svg +++ /dev/null @@ -1,95 +0,0 @@ - - - - - Who can see a hired seat, and who can use it - Two seats hired in acme. The address names a seat. The pin it was registered with decides who reaches it. - - - - Organization: acme - Every caller here is a verified acme member - - - - ORG-VISIBLE SEAT - - THE SEAT · SERVED BY THIS PROCESS - acme.support.ada - pinned to org acme - - WHO CAN SEE IT - Any acme member's browser lists - its roster row - workforce/roster/support.ada - seatId, flow, instructions. Settings stay put - - WHO CAN USE IT - Any acme member your resolver - admits - - - - - USER-OWNED SEAT · ALICE'S - - THE SEAT · SERVED BY THIS PROCESS - acme.~alice.research - pinned to org acme and user alice - - WHO CAN SEE IT - No browser. Not even alice's - workforce/roster/~alice/research - Read on the server, and only - by alice's own calls - - WHO CAN USE IT - alice, signed in to acme - bob in acme: 404 Unknown flow - - - - - Outside acme - globex, or alice signed in there - - Both seats answer - 404 Unknown flow - the same answer as an - address nobody serves. - The flow list leaves - them out. - To have a research seat - in globex, hire one there. - It starts empty. - - - - - Not the same thing - The row is not the seat. A process serves a hired seat once it registers it. Another process picks the row up at its next start. - The address is not a permission. Knowing acme.support.ada grants nothing: the caller's verified org and user are checked. - Firing deletes the roster row, and the inventory row the hire wrote. Sessions the seat ran are left alone. - - diff --git a/apps/docs/docs/workforce/inventory.md b/apps/docs/docs/workforce/inventory.md index f478a4cf1f..d38620981f 100644 --- a/apps/docs/docs/workforce/inventory.md +++ b/apps/docs/docs/workforce/inventory.md @@ -13,21 +13,21 @@ The inventory keeps that record as data: three org-scoped resource collections t | Collection | One row per | Key | |------------|-------------|-----| -| Seats | registered seat | `inventory/seats/`; for a seat hired at runtime, `` is its address, such as `acme.support.ada` | +| Seats | registered seat | `inventory/seats/` | | Mailboxes | registered mailbox | `inventory/mailboxes/` | | Memberships | seat-in-mailbox | `inventory/members//` | **A row means registered, not open.** It records that a seat or mailbox was registered in this organization. It says nothing about whether that seat is working or that mailbox is open now. Nothing deletes a row for going missing, so a seat or mailbox a later roster no longer names keeps its row. Label rows that way wherever you show them. -There are two removals. Firing a seat hired at runtime removes its row, and only the row its own hire published (see below). And when a `MAILBOX.md` becomes a project talk template (`mintFor: projects`), it is no longer a mailbox, so the next `openInventory` removes its mailbox row and membership rows through the `seatWriter`. Discovery never lists a template as a mailbox, even before that boot runs. +The seats are the workers your files declare, the standard workers every user has. A user's own workers, hired or forked while the app runs, aren't listed: they are on that user's [roster](./durable-hire.md), which nobody else reads. One removal remains: when a `MAILBOX.md` becomes a project talk template (`mintFor: projects`), it is no longer a mailbox, so the next `openInventory` removes its mailbox row and membership rows through the `seatWriter`. Discovery never lists a template as a mailbox, even before that boot runs. ## When to use which source -![Four records, each answering one question. Your files: what is declared? A WORKER.md or MAILBOX.md, read at every start; a seat hired at runtime has no file. Inventory, in the organization's store: was it registered here? A seat row (id, kind, door, hired, incarnation, where hired says the seat came from a runtime hire rather than a file), a mailbox row with a copy of its members, and a membership row per seat in a mailbox. A declared row is never deleted; firing a seat hired at runtime removes its row. Hired roster, a row at workforce/roster/ plus the seat id: is it hired right now? It holds only seats hired while the app runs, and a row is deleted when its seat is fired. The mailbox's session: will this post be accepted? Its state holds members and instructions, and post and fileTask check the author a post names against those members. The inventory's members is a copy for finding mailboxes, never the check. A seat hired at runtime has its address as its inventory id, such as acme.support.ada, while members name it support.ada.](./seat-mailbox-records.svg) +![Four records, each answering one question. Your files: what is declared? A WORKER.md or MAILBOX.md, read at every start; a user's own worker has no file. Inventory, in the organization's store: was it registered here? A seat row (id, kind, door), a mailbox row with a copy of its members, and a membership row per seat in a mailbox. A declared row is never deleted, and a user's own worker has no row. A user's roster, a row at workforce/workers/ plus the worker's id in that user's own data: whose worker is it? Deleted when the worker is fired. The mailbox's session: will this post be accepted? Its state holds members and instructions, and post and fileTask check the author a post names against those members. The inventory's members is a copy for finding mailboxes, never the check.](./seat-mailbox-records.svg) -Each column answers one question, so ask the record that owns yours. Two are easy to mix up. Whether a seat hired at runtime is hired right now is the [hired roster](./durable-hire.md#the-roster)'s, not the inventory's. Whether a post's `author` is accepted depends on the `members` in the mailbox's session state, not the inventory's copy. +Each column answers one question, so ask the record that owns yours. Whether a post's `author` is accepted depends on the `members` in the mailbox's session state, not the inventory's copy. -The inventory and your files join on the seat's `id`, except for a seat hired at runtime: its inventory `id` is its address, such as `acme.support.ada`, while a mailbox's `members` name it `support.ada`. For a team list, use `listedSeatRows` from `@flow-state-dev/workforce/browser`. It keeps every declared seat's row and a hired seat's row only while the hired roster backs it, so a seat that is no longer hired drops out. +The inventory and your files join on the seat's `id`. ## Wiring the boot @@ -35,16 +35,19 @@ Rows are written by actions that run inside flows, not by a standalone call. So ```ts import { - mailboxInstances, + createWorkerInstallation, hireWorkforce, + inventorySeats, + mailboxInstances, openMailboxes, openInventory, } from "@flow-state-dev/workforce"; -const seats = hireWorkforce(roster.workers); +const installation = createWorkerInstallation({ standardWorkers: roster.workers }); +const flows = hireWorkforce(installation); const instances = mailboxInstances(roster.mailboxes, { inventory: true }); -flowRegistry.registerMany([...seats, ...instances]); +flowRegistry.registerMany([...flows, ...instances]); // server starts here await openMailboxes(roster.mailboxes, { @@ -53,7 +56,7 @@ await openMailboxes(roster.mailboxes, { }); await openInventory( - { seats, mailboxes: roster.mailboxes }, + { seats: inventorySeats(installation), mailboxes: roster.mailboxes }, { run, seatWriter: { flowKind: "mailbox" }, @@ -129,10 +132,6 @@ The rest of the roster is still attempted. Which of these is fatal is yours to d Every write is an upsert keyed by the record's id. Running over the same roster writes the same rows. Nothing duplicates, and a mailbox registered on an earlier boot keeps its original `openedAt`. -Seat rows have one exception. The roster a boot read can be older than the store, because during a rolling deploy another server may have fired a seat and hired it again, or dropped a declared seat and hired the same address. So a boot writes a seat's row only where there was no row when it read the inventory, or where the stored row is the same kind of seat: for a declared seat, a declared seat's row, and for a hired seat, a row carrying the same incarnation. A boot never writes over a runtime hire's row with another hire's or a declared seat's, and it doesn't bring back a row that a fire removed after the boot read it. A row it leaves isn't counted in `seats`, as long as your `run` returns the action's output or a result carrying it as `output`. - -A hire that finds a declared seat's row at its address, written by such a boot while the hire was running, doesn't write over it either. The hire takes back the seat it registered and its roster row, and refuses. - ## 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. @@ -173,11 +172,11 @@ const seatMailboxes = handler({ { id: "engineering.lead", kind: "agent", door: "run", hired: false, incarnation: null } ``` -`hired` says where the seat came from: `true` for a seat hired at runtime, whose id is its address, and `false` for one declared in a worker file. Read it rather than the id's shape, because a declared team can share the organization's name. A row written before the field existed has `hired: null` until the next boot rewrites it. `incarnation` names the hire or repair that published a hired seat's row. Fire removes a row only when it carries the incarnation being fired, so a seat hired again at the same address keeps its own row, and never removes a declared seat's row. A team list shows a hired seat's row only while the roster row at its address carries the same incarnation. +`hired` is `false` and `incarnation` is `null` on every row: the inventory lists only the workers your files declare. -`door` names an action on the seat's flow: the one that takes a person's message for this seat. It is the kind's one public action that declares `userMessage` and takes `{ message }`. The built-in worker's is named `run`, which is unrelated to the `run` callback above. Every worker flow has exactly one: `hireWorkforce` refuses a flow with none, or with two, before it hires anyone ([which flows can run workers](./workers-on-disk.md#which-flows-can-run-workers)). A seat you build by hand with no such action gets `door: null`, and an app should say that seat takes no message rather than guess. +`door` names an action on the seat's flow: the one that takes a person's message for this seat. It is the kind's one public action that declares `userMessage` and takes `{ message }`. The built-in worker's is named `run`, which is unrelated to the `run` callback above. Every worker flow has exactly one: `hireWorkforce` refuses a flow with none, or with two, before it registers anything ([which flows can run workers](./workers-on-disk.md#which-flows-can-run-workers)). A seat you build by hand with no such action gets `door: null`, and an app should say that seat takes no message rather than guess. -`openInventory` reads the door from each seat's `actions`, and `hired` from its settings, so pass it the seats `hireWorkforce` returned. A seat you build by hand needs `actions` too; pass `{}` for one that takes no message. +`openInventory` reads the door from each seat's `actions`, so pass it `inventorySeats(installation)`, which gives each standard worker with its flow's actions. A seat you build by hand needs `actions` too; pass `{}` for one that takes no message. **Mailbox:** @@ -236,7 +235,7 @@ if (mailboxesRef !== undefined) { // mailboxes[0] → { id: "engineering.standup", kind: "mailbox", members: [...], openedAt: "..." } ``` -The patterns are `inventory/seats/*`, `inventory/mailboxes/*` and `inventory/members/**`. A mailbox built with `mailboxInstances(roster.mailboxes, { inventory: true })` declares all three, so any mailbox's session can read the whole inventory. A seat whose kind carries the [`seat-hire` tools](./durable-hire.md) declares only the seat collection. +The patterns are `inventory/seats/*`, `inventory/mailboxes/*` and `inventory/members/**`. A mailbox built with `mailboxInstances(roster.mailboxes, { inventory: true })` declares all three, so any mailbox's session can read the whole inventory. **Which organization:** the session's. The server takes it from the session, and the session took it from your principal resolver when it was created. Nothing in the request can name a different one. diff --git a/apps/docs/docs/workforce/mailboxes.md b/apps/docs/docs/workforce/mailboxes.md index 313ed9ff6a..7d471f409d 100644 --- a/apps/docs/docs/workforce/mailboxes.md +++ b/apps/docs/docs/workforce/mailboxes.md @@ -307,19 +307,22 @@ Your app supplies the addresses. The `notify` slot takes any block, so to reach ### Waking agent seats Most apps want a post to reach the agents in the mailbox and nobody else. Workforce ships that as -one call. Hand `wakeMemberSeats` the seats you hired, and put what it returns in the notify slot: +one call. Hand `wakeMemberSeats` the flows `hireWorkforce` returned and the installation, and put +what it returns in the notify slot: ```ts import { + createWorkerInstallation, mailboxInstances, defineMailboxFlow, hireWorkforce, wakeMemberSeats, } from "@flow-state-dev/workforce"; -const seats = hireWorkforce(workers, { workerFlows: kinds }); // hire first: the wake reaches these seats +const installation = createWorkerInstallation({ standardWorkers: workers, workerFlows: kinds }); +const flows = hireWorkforce(installation); // first: the wake reaches the workers on these flows const mailboxFlows = mailboxInstances(mailboxes, { - kinds: { mailbox: defineMailboxFlow({ notify: wakeMemberSeats(seats) }) }, + kinds: { mailbox: defineMailboxFlow({ notify: wakeMemberSeats(flows, { installation }) }) }, }); ``` @@ -337,15 +340,14 @@ For each post, it decides per member whether that member runs: agents hear a seat's post, write your own notify block and run it when `seatAuthored` is `true`. - **The `fallback` block runs**, or nothing if you passed none, for every other member: one whose - kind can't hear a post, one with no worker in the list you passed, or one the mailbox's caller - can't reach. A worker hired while the app is running isn't in that list until the app restarts - and passes it in. For these members the fallback runs on every post, including a worker's. + flow can't hear a post, or one that names no standard worker on the flows you passed. A user's + own worker is never woken as a member. For these members the fallback runs on every post, + including a worker's. -If the same seat id appears more than once (in several organizations, or owned by several users), -the one the mailbox's caller can reach runs, in this order: their own, the organization's, a shared -one. To wake fewer seats, pass fewer. +To wake fewer workers, pass fewer flows. -Each woken seat keeps one conversation per mailbox. The second post it hears lands in the same +Each woken worker keeps one conversation per mailbox, created naming that worker, so two workers on +one flow woken by the same post each answer in their own. The second post it hears lands in the same conversation, so it remembers the thread. Two posts that arrive together each run once, in no guaranteed order. The conversation is a child of the mailbox's session, so an ordinary session listing does not show it. List with dispatch runs included (`include: "dispatch-runs"`, or @@ -380,20 +382,23 @@ declaration is all `wakeMemberSeats` looks for. ```ts import { defineFlow } from "@flow-state-dev/core"; -import { mailboxNotifyInputSchema, workerConfigSchema } from "@flow-state-dev/workforce"; +import { mailboxNotifyInputSchema, workerConfigSchema, workerFlow } from "@flow-state-dev/workforce"; import { z } from "zod"; -export const triager = defineFlow({ - kind: "triager", - cardinality: "collection", - configSchema: workerConfigSchema(), - actions: { - run: { inputSchema: z.object({ message: z.string() }), block: triage, userMessage: (input) => input.message }, - }, - internal: { - actions: { onMailboxPost: { inputSchema: mailboxNotifyInputSchema, block: triageFromPost } }, - }, -}); +export const triager = workerFlow((installation) => + defineFlow({ + kind: "triager", + configSchema: workerConfigSchema(), + session: installation.session(), + resources: { ...installation.resources }, + actions: { + run: { inputSchema: z.object({ message: z.string() }), block: triage, userMessage: (input) => input.message }, + }, + internal: { + actions: { onMailboxPost: { inputSchema: mailboxNotifyInputSchema, block: triageFromPost } }, + }, + }), +); ``` #### What `author` is @@ -422,14 +427,14 @@ routing: --- ``` -Then give the mailbox kind the route. It needs the seats you hired and a model that can evaluate: +Then give the mailbox kind the route. It needs the flows `hireWorkforce` returned, the installation, and a model that can evaluate: ```ts import { defineMailboxFlow, routeByPurpose, wakeMemberSeats } from "@flow-state-dev/workforce"; defineMailboxFlow({ - notify: wakeMemberSeats(seats), - route: routeByPurpose(seats, { model: "typesafe-ai/jev" }), + notify: wakeMemberSeats(flows, { installation }), + route: routeByPurpose(flows, { model: "typesafe-ai/jev", installation }), }); ``` @@ -438,7 +443,7 @@ of answers and gets one of them back. Not every model can do that; see [Evaluation models](/docs/fundamentals/models#evaluation-models). A mailbox without the `routing:` line is not routed, even on a kind built with a route: a client `post` wakes every agent member. -The fallback has to be a member whose hired seat can hear a post, or the app refuses to start and +The fallback has to be a member whose worker can hear a post, or the app refuses to start and names the mailbox. So does a `routing:` line on a kind built without a route. The line is read from the file each time the app starts, so adding it to a mailbox that is already open routes that mailbox from the next start, with its lines kept. @@ -456,9 +461,7 @@ For each client `post`, in this order: The choices are the members whose seat can hear a post and has a description, each described by the `description:` in its `WORKER.md`. The model also sees the mailbox's recent lines, which is how "it fails right after the password" reaches the specialist who asked about the password. - A seat [hired while the app runs](./durable-hire.md) has no description, because `hire` takes - none, so it is never a choice. It can still take a post as the fallback, and step 1 then sends - it the next client `post`. When no member has a description, there is no call and the fallback + When no member has a description, there is no call and the fallback takes the post. 3. **The fallback.** If the call fails, or answers with anything outside the choices, the fallback member takes the post. A model that can't evaluate fails every call, so every post @@ -538,7 +541,7 @@ its view. A seat woken in an unrouted mailbox, or talked to directly, gets no li it is routed by what it says. - A follow-up after an answer relies on the evaluator call. If that call fails, the follow-up goes to the fallback. -- A member with no `description:`, such as a seat hired while the app runs, is never picked for +- A member with no `description:` is never picked for what a post is about. It gets a post only as the fallback, or as the next post held for it after that. - Cancelling a post's fan-out, the request that picks its member and wakes it, may not stop the @@ -792,7 +795,7 @@ The part after the tool name is the mailbox's id and the board's name, joined, w It is off by default, and that's deliberate. Anyone who can reach the mailbox can then settle or reassign its rows, including one a seat is working on, and the roster check `fileTask` makes on `author` doesn't apply to these. Each action works only in its own mailbox's session, so one mailbox can't reach another's board through them. Turn it on for boards people are meant to work from outside a run, and for development. -A board that no hired worker declares warns at hire, naming the mailbox and the board. Nothing is refused: a mailbox may keep a board that only people read. The warning prints once per server process, so a hot reload under `next dev` doesn't repeat it. +A board that no worker flow declares warns at `hireWorkforce`, naming the mailbox and the board. Nothing is refused: a mailbox may keep a board that only people read. The warning prints once per server process, so a hot reload under `next dev` doesn't repeat it. A board's rows are stored at organization scope, so they sit in [the organization the mailbox runs in](#which-organization-a-mailbox-runs-in). @@ -802,12 +805,13 @@ The rows themselves are [task substrate](../orchestration/task-substrate.md) row ### Handing a row to the worker it names -A board's `workers` map fixes its names when you write it. To let a row name any of your workers instead, including one hired a minute ago, the worker has to be able to take a task, and the board has to ask who a name means when it hands the row over. +A board's `workers` map fixes its names when you write it. To let a row name any of your standard workers instead, the worker has to be able to take a task, and the board has to ask who a name means when it hands the row over. -The built-in `agent` kind takes tasks from the boards you pass it as `taskLists`, and from none without them, which includes the copy you get when you pass no `workerFlows`. Build it with every board your mailboxes hold, hire, and build the **worker lookup** over the live registry: +The built-in `agent` kind takes tasks from the boards you pass it as `taskLists`, and from none without them, which includes the copy you get when you pass no `workerFlows`. Build it with every board your mailboxes hold, and build the **worker lookup** over the installation: ```ts import { + createWorkerInstallation, createWorkerLookup, defineAgentWorkerFlow, defineMailboxFlow, @@ -816,26 +820,26 @@ import { mailboxInstances, } from "@flow-state-dev/workforce"; import { readMailboxesDirectory, readWorkforce } from "@flow-state-dev/workforce/loader"; -import { instanceAt } from "./registry-access"; // Check `errors` on both reads, as in "Treat a non-empty errors as fatal". const { workers } = await readWorkforce("./workforce"); const { mailboxes } = await readMailboxesDirectory("./workforce"); const boardIds = mailboxBoardIds(mailboxes); -const hired = hireWorkforce(workers, { - workerFlows: { agent: defineAgentWorkerFlow({ taskLists: boardIds }) }, - mailboxBoards: boardIds, +const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: () => ({ agent: defineAgentWorkerFlow({ installation, taskLists: boardIds }) }), }); +const flows = hireWorkforce(installation, { mailboxBoards: boardIds }); -const lookup = createWorkerLookup({ instanceAt, declared: hired.map((worker) => worker.id) }); +const lookup = createWorkerLookup({ installation }); const mailboxKinds = mailboxInstances(mailboxes, { kinds: { mailbox: defineMailboxFlow({ checkAssignee: lookup.filingCheck() }) }, }); ``` -`instanceAt(address)` returns the flow registered at an address right now: `registry.get(address)` on the runtime, the same getter the hire tools take. [Reaching the `FlowState`](./durable-hire.md#reaching-the-flowstate) shows it in `registry-access.ts`. The lookup reads it on every call, so a worker hired while the app runs is found the moment it is registered, and a fired one stops being found. +The lookup answers with the flow a worker runs on, and the hand-over opens each task's session on that flow, naming the worker in its starting state. Then give the board that drains the ledger a `defaultWorker` that hands each row to whatever its name means: @@ -856,6 +860,7 @@ const board = taskBoard({ action: WORKER_TASK_ENTRY, // "work" session: "per-task", flowKind: lookup.flowKind, + state: lookup.state, // the task's session is born naming its worker }), }); @@ -865,18 +870,17 @@ export const followupsDesk = defineFlow({ })(); ``` -Register `followupsDesk` alongside the hired workers and mailbox kinds, and run its `drain` the way you would any board's. Each row filed with `fileTask` and an `assignee` then runs on that worker, one run per row. A worker of the built-in kind answers it as one turn, and the answer becomes the row's result. See [Taking a task](./built-in-worker.md#taking-a-task). +Register `followupsDesk` alongside the worker flows and mailbox kinds, and run its `drain` the way you would any board's. Each row filed with `fileTask` and an `assignee` then runs on that worker, one run per row. A worker of the built-in kind answers it as one turn, and the answer becomes the row's result. See [Taking a task](./built-in-worker.md#taking-a-task). `boardId` has to be the ledger's id, `followups.id`. A worker takes a row only from a board whose id is one of its `taskLists`, and refuses any other with `UnknownTaskLedgerError` before reading a row. #### Who a name reaches -The lookup finds a worker your files declare, a worker hired for the organization, or a worker the member hired for themselves. "The member" is always the person who filed the row. The list records who filed it, so when a teammate's drain hands the row over, it still reaches the filer's own worker and never the teammate's. It never finds another organization's workers, or another member's own. +The lookup finds a worker your files declare. A mailbox's board belongs to the organization, and whoever drains it opens the task's session, so it never hands a row to a user's own worker: only that worker's owner can open a session with it. | The name | At `fileTask` | At hand-over | | --- | --- | --- | | Nobody holds it | Refused, nothing written. `MailboxPostRefusedError`, `reason: "unknown-assignee"`, message `unknown-assignee: No worker is named "frontend".` | Refused `flow-not-found`, naming the assignee. The attempt fails. | -| Held by two workers, such as one hired for the organization and one of the member's own | Refused `unknown-assignee`, naming both: `"frontend" names 2 workers: one hired for the organization and one your own. Fire or rename one of them so the name means one worker.` | The attempt fails with an error carrying the same sentence. | | Held by a worker whose kind takes no tasks | Refused `unknown-assignee`, with a message naming the worker and its kind, which declares no `work` task entry. | The attempt fails with an error carrying the same sentence. | A worker fired after its row was filed fails at hand-over, naming it. No other worker runs that row. A row filed with no assignee is refused at hand-over too, since the fallback hands a row over by the name on it. Every failed attempt goes through the board's ordinary error path, so `maxAttempts` and `onError` apply. diff --git a/apps/docs/docs/workforce/overview.md b/apps/docs/docs/workforce/overview.md index 18b71da339..27b23aff81 100644 --- a/apps/docs/docs/workforce/overview.md +++ b/apps/docs/docs/workforce/overview.md @@ -15,15 +15,15 @@ A hired worker is a **seat**: a flow instance with its own id. You open a sessio Reach for Workforce when you want a named roster you address by opening a session. -Reach for [Orchestration](../orchestration/overview) when you want to coordinate units of work on a task board. A board worker is a block that claims tasks. A task's `assignee` can also name any of your hired workers, including one hired while the app runs. See [Giving a task to a worker](#giving-a-task-to-a-worker). +Reach for [Orchestration](../orchestration/overview) when you want to coordinate units of work on a task board. A board worker is a block that claims tasks. A task's `assignee` can also name one of your standard workers. See [Giving a task to a worker](#giving-a-task-to-a-worker). ## What a Workforce app looks like -![A WORKER.md file in your repository is the description. readWorkforce turns files into plain records, hireWorkforce turns each record into a worker, a configured copy of a flow kind with its own id, and your app registers the workers. Sessions, state and resources a worker writes live in your store. A worker hired while the app runs is also written to the store as a roster row. A task's assignee can name any worker that takes tasks: the board runs the list, and Workforce finds the worker.](./workforce-overview.svg) +![A WORKER.md file in your repository is the description. readWorkforce turns files into plain records, and hireWorkforce gives back one copy of each flow a worker runs on, which your app registers. Every worker on a flow shares that copy. Sessions name their worker when they are created, and live in your store with the state and resources a worker writes. A worker a user hires or forks while the app runs is a row in their own data. A task's assignee can name a standard worker that takes tasks: the board runs the list, and Workforce finds the worker.](./workforce-overview.svg) -Workforce reads your files and hires them. Each `WORKER.md` becomes a flow copy with its own address. Each `MAILBOX.md` becomes a named session on a mailbox kind, the built-in one unless the file names another. Sessions, resources and boards work as they do on any flow, and live where they always do. +Workforce reads your files and runs them. Each `WORKER.md` is a standard worker every user has, run by one shared copy of the flow it names. A user can add workers of their own, which nobody else can reach. Each `MAILBOX.md` becomes a named session on a mailbox kind, the built-in one unless the file names another. Sessions, resources and boards work as they do on any flow, and live where they always do. -- **The roster outlives the process.** A team you hire while the app is running is still there after a restart or a redeploy, because the hire is written to the store your app uses. See [Hiring while the app runs](./durable-hire). +- **A user's own workers are data.** A worker a user hires or forks while the app runs is a row in their own data: every process sees it on the next turn, nothing restarts, and no other user can reach it. See [Hiring and forking](./durable-hire). - **A mailbox is what a reader opens.** A mailbox is a named session on a kind the framework ships, and its transcript is the part of that conversation a person or another agent should read. A routed mailbox sends each post to the one member whose job fits it. See [Mailboxes](./mailboxes). - **The screens are importable.** One navigator browses the whole workforce, and the roster and a board, as columns or as a live list, ship beside it as components from `@flow-state-dev/react`. See [Workforce components](./ui). @@ -31,7 +31,7 @@ For a working example, the [kitchen-sink reference app](https://github.com/fixpo ## Hire a roster -A worker on a team lives at `teams//workers//WORKER.md`, so `teams/engineering/workers/lead/` hires as `engineering.lead`. An org seat belongs to no team: it lives at `org/workers//WORKER.md` and hires under its folder name alone, so `org/workers/chief-of-staff/` is `chief-of-staff`. +A worker on a team lives at `teams//workers//WORKER.md`, so `teams/engineering/workers/lead/` is `engineering.lead`. An org seat belongs to no team: it lives at `org/workers//WORKER.md` and goes by its folder name alone, so `org/workers/chief-of-staff/` is `chief-of-staff`. ```md --- @@ -42,7 +42,7 @@ You are the engineering lead. You break work into tasks and report what came bac ``` ```ts -import { hireWorkforce } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, hireWorkforce } from "@flow-state-dev/workforce"; import { readWorkforce } from "@flow-state-dev/workforce/loader"; // `errors` is a worker that failed to load; `skillErrors` is one that loaded @@ -58,14 +58,15 @@ if (errors.length || skillErrors.length || teamErrors.length) { ); } -const seats = hireWorkforce(workers); +const installation = createWorkerInstallation({ standardWorkers: workers }); +const flows = hireWorkforce(installation); -flowRegistry.registerMany(seats); +flowRegistry.registerMany(flows); ``` -That worker file names no `flow:`, so it runs on the built-in worker kind. Its body becomes its instructions, and it talks. It sees the recent turns of the conversation it's in, and nothing it's told there reaches any other conversation. +That worker file names no `flow:`, so it runs on the built-in worker flow, `agent`. `hireWorkforce` gives back one copy of `agent`, however many workers run on it, and the roster flow an app [hires and forks](./durable-hire) through. Its body becomes its instructions, and it talks. It sees the recent turns of the conversation it's in, and nothing it's told there reaches any other conversation. -A **skill** is a folder of instructions a worker can pull into a turn. `readWorkforce` collects the skills sitting beside each worker in the tree, and the built-in reads them. Each person keeps their own copy of a seat's skills. When you call the worker's action, send `userId` beside `input`. The call never names the organization: every request runs in one, and [Authentication](../server/authentication.md#every-request-runs-in-an-organization) covers where it comes from. [The built-in worker](./built-in-worker.md) covers its settings, what your app can configure, and the rest of what it does not do. +A **skill** is a folder of instructions a worker can pull into a turn. `readWorkforce` collects the skills sitting beside each worker in the tree, and the built-in reads them. Each person keeps their own copy of a worker's skills. To talk to a worker, open a session that names it, as [Talking to a worker](./workers-on-disk.md#talking-to-a-worker) shows, and send `userId` beside `input`. The call never names the organization: every request runs in one, and [Authentication](../server/authentication.md#every-request-runs-in-an-organization) covers where it comes from. [The built-in worker](./built-in-worker.md) covers its settings, what your app can configure, and the rest of what it does not do. To run a worker on a flow you wrote yourself, name that flow's kind in the worker's `flow:`. Here is `teams/engineering/workers/triage/WORKER.md`: @@ -77,23 +78,25 @@ flow: request-triage Answer directly when the request is a question about a feature that already shipped. ``` -Then pass the flow under that same kind when you hire: +Then pass the flow under that same kind: ```ts import { requestTriageFlow } from "./flows"; -const seats = hireWorkforce(workers, { +const installation = createWorkerInstallation({ + standardWorkers: workers, workerFlows: { "request-triage": requestTriageFlow }, }); +const flows = hireWorkforce(installation); ``` -`requestTriageFlow` is your own `defineFlow(...)`, and `"request-triage"` is its `kind`. A record that names no `flow:` is hired into the built-in, so one roster can run both. You get back one seat per worker, ordered by id. +`requestTriageFlow` is your own flow, built on the installation, and `"request-triage"` is its `kind`. A record that names no `flow:` runs on the built-in, so one roster can run both. You get back one copy per flow, ordered by kind, and the roster flow. -Pass a flow under a key that is not its own `kind` and the hire is refused. [Workers on disk](./workers-on-disk.md#when-a-worker-needs-more-than-settings) walks through writing a flow kind of your own. +Pass a flow under a key that is not its own `kind` and it is refused. [Workers on disk](./workers-on-disk.md#when-a-worker-needs-more-than-settings) walks through writing a worker flow of your own. -`hireWorkforce` reads no files and registers nothing. A refused hire throws and returns nothing. +`hireWorkforce` reads no files and registers nothing itself. A refusal throws and returns nothing. -`readWorkforce` is Node-only (`@flow-state-dev/workforce/loader`). Import `hireWorkforce` from `@flow-state-dev/workforce`. +`readWorkforce` is Node-only (`@flow-state-dev/workforce/loader`). Import `createWorkerInstallation` and `hireWorkforce` from `@flow-state-dev/workforce`. ## Projects and the chief of staff @@ -101,27 +104,27 @@ A **workstream** is a mailbox and the boards it holds: one place for the convers A **project** groups workstreams. It is a row your organization keeps, not a file: a title, an owner, its members, and the workstreams it groups. Everyone in the organization can see that a project exists. Only its members can read or post in its room, the one conversation they share with the workers your app puts there. See [Projects](./projects). -The **chief of staff** is an org-level worker a person asks about the organization: who works here, who is in a mailbox. Ask it for another worker and it hires one. Ask it for one fewer and it puts the fire in front of you, and nothing is removed until you approve. Given the project tools, it also starts projects for the person who asks. A Lab that doesn't declare one doesn't have one. See [The chief of staff](./chief-of-staff). +The **chief of staff** is an org-level worker a person asks about the organization: who works here, who is in a mailbox. Ask it for another worker and it hires one of your own. Ask it for one fewer and it puts the fire in front of you, and nothing is removed until you approve. Given the project tools, it also starts projects for the person who asks. A Lab that doesn't declare one doesn't have one. See [The chief of staff](./chief-of-staff). ## Giving a task to a worker -A task on a mailbox's board can name any of your workers that takes tasks, by the name `discover` lists: `engineering.lead`, or `frontend`, a worker hired a minute ago. When the board hands the task over, Workforce's worker lookup finds the worker of that name and the task runs on it, one run per task. The lookup reads the live registry, so a coordinator can hire a worker and give it work in the same conversation. +A task on a mailbox's board can name any of your standard workers that takes tasks, by the name `discover` lists: `engineering.lead`. When the board hands the task over, Workforce's worker lookup finds the worker of that name and the task runs in a session of its flow that names it, one run per task. -A worker on the built-in `agent` kind runs a task as one turn: its own instructions and tools, the task's title, goal and context as the message, and its answer as the task's result. A kind you write takes tasks when it declares a `work` task entry. +A worker on the built-in `agent` flow runs a task as one turn: its own instructions and tools, the task's title, goal and context as the message, and its answer as the task's result. A kind you write takes tasks when it declares a `work` task entry. -The name reaches your organization's workers, the ones your files declare, and the ones the member who filed the task hired for themselves, whoever later runs the list. It never reaches another member's own workers or another organization's. A name two of those workers share is refused as ambiguous. With the mailbox's filing check on, a task for a name nobody holds is refused when it is filed, naming it. A task whose worker was fired before it ran fails with the worker's name. No other worker picks it up. +The name reaches the workers your files declare. A mailbox's board is the organization's, and whoever drains it opens the task's session, so it never hands a task to a user's own worker, which only its owner can open a session with. With the mailbox's filing check on, a task for a name nobody holds is refused when it is filed, naming it. A task whose worker was fired before it ran fails with the worker's name. No other worker picks it up. [Handing a row to the worker it names](./mailboxes.md#handing-a-row-to-the-worker-it-names) has the wiring: the lookup, the filing check, and the board that hands tasks over. ## What it will not do - It does not run your task boards. A board drains its rows. Workforce tells the board which worker a name means, and gives workers a way to take a task. -- It does not replace flows, sessions, or resources. Sessions and resources live on the seat you hired. -- Hiring at runtime writes no files. It stores the new seat as a row in the hired roster, which the app reads back at start alongside the seats your files declare, and the tree stays as you wrote it. See [Hiring while the app runs](./durable-hire.md). +- It does not replace flows, sessions, or resources. A worker's sessions are sessions of the flow it runs on. +- Hiring at runtime writes no files. It stores the new worker as a row in the user's data, and the tree stays as you wrote it. See [Hiring and forking](./durable-hire.md). ## Related pages -- [Workers on disk](./workers-on-disk) — the folder tree, `WORKER.md`, `readWorkforce`, and `hireWorkforce`. +- [Workers on disk](./workers-on-disk) — the folder tree, `WORKER.md`, `readWorkforce`, `hireWorkforce`, and talking to a worker. - [The built-in worker](./built-in-worker) — the `agent` kind a record with no `flow:` runs on: its settings, tools, skills, and memory. - [Documents on disk](./documents-on-disk) — a team's shared reference material as Markdown, installed as resources. - [Code on disk](./code-on-disk) — your own flow kinds, blocks and capabilities in the same tree, registered by `fsdev gen`. @@ -130,8 +133,8 @@ The name reaches your organization's workers, the ones your files declare, and t - [Mailboxes](./mailboxes) — several agents on one topic, with one durable transcript and nobody owning a row, optionally routing each post to one member. - [Projects](./projects) — a row that groups workstreams, with one room its members share. - [Inventory](./inventory) — a record of every seat and mailbox registered in an organization, readable by a block. -- [Hiring while the app runs](./durable-hire) — a roster hired at runtime, written to your store, reloaded on the next boot. -- [The chief of staff](./chief-of-staff) — the one seat a person asks to hire or fire, with a fire waiting for their approval. +- [Hiring and forking](./durable-hire) — a user's own workers, hired, forked and fired while the app runs. +- [The chief of staff](./chief-of-staff) — the one worker a person asks to hire or fire workers of their own, with a fire waiting for their approval. - [Workforce components](./ui) — browse your flow kinds, instances and sessions, and render a roster and boards, with React components. - [Orchestration](../orchestration/overview) — the task board and the workers that drain it. - [Agents](../orchestration/agents) — board workers, `definePersona`, and `createWorkforceCapability`. diff --git a/apps/docs/docs/workforce/packages-on-disk.md b/apps/docs/docs/workforce/packages-on-disk.md index eb20ff2c14..8d923a01b0 100644 --- a/apps/docs/docs/workforce/packages-on-disk.md +++ b/apps/docs/docs/workforce/packages-on-disk.md @@ -70,10 +70,10 @@ A package's tools reach only the workers that hold it. They are not in your app' ## In your app -`fsdev gen` writes a `packageBlocks` export onto `workforce.gen.ts`, keyed by each package's folder and then by block name. Pass it to `hireWorkforce` beside `seatBlocks`: +`fsdev gen` writes a `packageBlocks` export onto `workforce.gen.ts`, keyed by each package's folder and then by block name. Pass it to `createWorkerInstallation` beside `seatBlocks`: ```ts -import { hireWorkforce } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, hireWorkforce } from "@flow-state-dev/workforce"; import { readWorkforce } from "@flow-state-dev/workforce/loader"; import { kinds, packageBlocks, seatBlocks } from "./workforce/workforce.gen"; @@ -83,12 +83,13 @@ if (errors.length || packageErrors.length) { throw new Error(`workforce failed to load:\n${reported.join("\n")}`); } -const seats = hireWorkforce(workers, { workerFlows: kinds, seatBlocks, packageBlocks }); +const installation = createWorkerInstallation({ standardWorkers: workers, workerFlows: kinds, seatBlocks, packageBlocks }); +const flows = hireWorkforce(installation); ``` Leave `packageBlocks` out and a held package brings its instructions and no tools. -`readWorkforce` puts the packages in each worker's reach on that worker's record as `packages`: the org's library, its team's library, and its own folder. An org seat has no team, so its reach is the org's library and its own folder. Which of them the worker holds is decided when it is hired, from its `packages:` line. +`readWorkforce` puts the packages in each worker's reach on that worker's record as `packages`: the org's library, its team's library, and its own folder. An org seat has no team, so its reach is the org's library and its own folder. Which of them the worker holds is decided from its `packages:` line, when its configuration is checked. ## When a file is wrong @@ -104,7 +105,7 @@ Reading the tree reports a broken package in `packageErrors`, keyed by its path, `fsdev gen` refuses a package's `blocks/` folder for what it refuses in [any `blocks/` folder](./code-on-disk.md#what-it-checks-and-when), such as a symlink or a basename that breaks the naming rule. -`hireWorkforce` refuses a worker when: +A worker is refused when: - its `packages:` is not a list of names; - it names a package no library in its reach offers. The message names both folders it looked in; @@ -113,10 +114,10 @@ Reading the tree reports a broken package in `packageErrors`, keyed by its path, - a block in a package it holds has a `name` that differs from its file's name, or declares a store; - its own `packages/` folder has a package with blocks that failed to load. The message points at `packageErrors`. -Like every hire refusal, these are collected and thrown together, one message naming every bad worker: +For a standard worker, these are collected and thrown together by `hireWorkforce`, one message naming every bad worker. A user's own worker gets the same refusal when it is hired or edited: ``` -hireWorkforce refused 1 of 3 workers; nothing was hired: +hireWorkforce: 1 standard worker problem(s); nothing was registered: - worker "support.billing" — names package "escalation" in `packages:`, and no library in its reach offers it. Looked in "teams/support/packages/escalation" and "org/packages/escalation". ``` @@ -147,5 +148,5 @@ A seat that holds none doesn't get the key. Compose [`workerConfigSchema()`](./w - [Code on disk](./code-on-disk.md) — `fsdev gen`, and the rules every `blocks/` folder follows. - [The built-in worker](./built-in-worker.md#tools) — how a worker's `tools:` line is resolved. -- [Workers on disk](./workers-on-disk.md) — the folder tree, `WORKER.md`, `readWorkforce` and `hireWorkforce`. +- [Workers on disk](./workers-on-disk.md) — the folder tree, `WORKER.md`, `readWorkforce`, `hireWorkforce`, and talking to a worker. - [Skills](../skills/overview.md) — Markdown guidance that loads when it's relevant. diff --git a/apps/docs/docs/workforce/seat-mailbox-records.svg b/apps/docs/docs/workforce/seat-mailbox-records.svg index 90dad79754..b0fd41998a 100644 --- a/apps/docs/docs/workforce/seat-mailbox-records.svg +++ b/apps/docs/docs/workforce/seat-mailbox-records.svg @@ -40,7 +40,7 @@ teams/engineering/ mailboxes/standup/ Read at every start. - A seat hired at runtime + A user's own worker has no file here. @@ -60,22 +60,22 @@ MEMBERSHIP ROW One per seat in a mailbox A declared row is never - deleted. Firing a hired - seat removes its row. + deleted. A user's own + worker has no row. - Hired roster - Is it hired right now? + A user's roster + Whose worker is it? ROSTER ROW - workforce/roster/ - support.ada - seatId · flow - Only seats hired while - the app runs. - Deleted when the seat + workforce/workers/ + scribe + flow · settings + In the user's own data; + nobody else reads it. + Deleted when the worker is fired. @@ -98,7 +98,7 @@ Not a copy The inventory's members is a copy for finding mailboxes. The mailbox's session is the check on a post. - A seat hired at runtime has its address as its inventory id, acme.support.ada; members name it support.ada. - The roster says who is hired now. The inventory says what was registered, and keeps every declared row. + The inventory lists the workers your files declare. A user's own workers are on their roster only. + The roster says whose workers they are. The inventory says what was registered, and keeps every declared row. diff --git a/apps/docs/docs/workforce/seat-person-data.svg b/apps/docs/docs/workforce/seat-person-data.svg deleted file mode 100644 index 009469be56..0000000000 --- a/apps/docs/docs/workforce/seat-person-data.svg +++ /dev/null @@ -1,70 +0,0 @@ - - - - - What a seat saves for alice, and where - One person, two kinds of place in each organization. Every flow in an organization uses the same ones. - - - - Organization: acme - Every flow in acme, hired seats included - - SHARED · ONE CELL FOR ALICE IN ACME - ctx.user.state and user-scoped resources - that are not flow-isolated - Shared by every flow in acme, hired seats included - - FLOW-ISOLATED - alice · acme · - acme.support.ada - One cell per seat. - Other flows - don't read it. - - alice · acme · - acme.~alice.research - Another isolated seat, - another cell - - - - - Organization: globex - Every flow in globex - - ALICE IN GLOBEX - Her own cell here, empty until a flow - in globex writes it - Nothing in acme reads it, and nothing - in globex reads acme's. - - - - - Not a copy - Nothing moves between organizations, and no setting makes it move. A flow in globex starts without what acme's flows saved. - A resource's own flowIsolation decides which acme cell it uses; one that doesn't set it follows the flow's isolateUserState. - A projected resource is stored by your hooks, not by these cells. Key its rows by orgId too. - - diff --git a/apps/docs/docs/workforce/ui.md b/apps/docs/docs/workforce/ui.md index a302e3a617..0fc9c848b0 100644 --- a/apps/docs/docs/workforce/ui.md +++ b/apps/docs/docs/workforce/ui.md @@ -90,7 +90,7 @@ export function ShellPanels({ sessionId, bootProblems, getToken }: ShellPanelsPr Pass the same `resourceClient` to both, built once. Leave it out and each panel builds its own client with the plain browser `fetch`. That sends a same-origin cookie but no `Authorization` header, so once your [resolver](../server/authentication.md) expects a bearer token, the panels' reads get a 401. -`problems` is the list of seats your last boot could not bring back. It comes from `reloadHiredSeats` on the server, so your app has to hand it to the browser itself, for example by writing it to an organization-scoped collection the same flow declares. See [Hiring while the app runs](./durable-hire). +`problems` is an optional list of seats your app wants flagged, such as ones it couldn't start, which your app hands to the browser itself. Workforce writes none: a standard worker that can't run stops `hireWorkforce` at startup, and a user's own worker that stops resolving refuses its next turn, naming why. A board column is grouped by task status. An empty board says so, and names the usual reason: no seat drains it. @@ -176,6 +176,6 @@ These components render; they don't administer. There is no create-mailbox or in The roster and the board columns are scoped to an organization, because the collections behind them are. **The navigator is not.** It shows the flow kinds your server has registered, the instances under them, and the sessions the caller can see, with no organization filter. The flow list is answered without authentication, so every caller sees every flow your app defines and every seat declared in a `WORKER.md` file. -A hired seat is listed only to callers who could open it, as [Who can reach a hired seat](./durable-hire.md#who-can-reach-a-hired-seat) describes. For a person's own hired seats to appear, the navigator's `client` has to carry their credential. In a multi-organization deployment, don't show end users a seats section that includes file-declared seats, because those are listed to everyone. +A user's own workers aren't flows, so the navigator doesn't list them: read them with `createWorkforceClient(...).roster()`, as [Hiring and forking](./durable-hire.md#after-a-hire-refresh-the-roster) shows. In a multi-organization deployment, don't show end users a seats section that includes file-declared seats, because those are listed to everyone. **Which organization the panels show depends on how your deployment signs people in.** A session is bound to the organization of the identity your server resolves for the request. With no sign-in configured there is one organization, and you see it. If you hire into real organizations but have not given the app a way to identify the person viewing it, the panels read the default organization and come up empty. [Authentication](../server/authentication.md#every-request-runs-in-an-organization) covers how a request gets its organization. diff --git a/apps/docs/docs/workforce/workers-on-disk.md b/apps/docs/docs/workforce/workers-on-disk.md index 0a1e20aec1..2880a46680 100644 --- a/apps/docs/docs/workforce/workers-on-disk.md +++ b/apps/docs/docs/workforce/workers-on-disk.md @@ -2,14 +2,14 @@ title: Workers on disk sidebar_position: 2 sidebar_label: Workers on disk -description: "Workforce convention: describe each worker in a folder, read the tree at startup, and hire what it describes as addressable flow copies." +description: "Workforce convention: describe each worker in a folder, read the tree at startup, and run every worker on one shared copy of the flow it names." --- # Workers on disk -Workforce is how you describe a roster of workers and hire it as addressable flow copies. You can write each worker in TypeScript, or put each one in a folder and read the folder at startup. +Workforce is how you describe a roster of workers and run them. You can write each worker in TypeScript, or put each one in a folder and read the folder at startup. -`readWorkforce` turns a folder tree into plain records. `hireWorkforce` turns those records into flow copies you register. +`readWorkforce` turns a folder tree into plain records. `createWorkerInstallation` takes them as the standard workers every user has, and `hireWorkforce` gives back the flows to register: one copy of each flow a worker runs on, shared by every worker on it. ## The tree @@ -70,7 +70,7 @@ You are the engineering lead. You do not write code yourself. You break the request into tasks, assign them, and report what came back. ``` -`description` is the only key the file itself requires. In a [routed mailbox](./mailboxes.md#routing-a-mailbox), it is also what the route reads to decide whether a post is this worker's. The file refuses `persona:`, `seatSkills:`, `seatTools:`, `seatPackages:`, `seatId:` and `teamInstructions:` outright. A seat's skills and the blocks it can reach come from where its folders sit, and its team's instructions from that team's [`TEAM.md`](#what-a-teammd-says). `flow` names which of your flow kinds this worker runs. Leave it out and the worker is hired into [the built-in worker kind](./built-in-worker.md), which needs no flow of yours. +`description` is the only key the file itself requires. In a [routed mailbox](./mailboxes.md#routing-a-mailbox), it is also what the route reads to decide whether a post is this worker's. The file refuses `persona:`, `seatSkills:`, `seatTools:`, `seatPackages:`, `seatId:` and `teamInstructions:` outright. A seat's skills and the blocks it can reach come from where its folders sit, and its team's instructions from that team's [`TEAM.md`](#what-a-teammd-says). `flow` names which of your flow kinds this worker runs. Leave it out and the worker runs on [the built-in worker flow](./built-in-worker.md), which needs no flow of yours. `resources:` is a list of the [documents](./documents-on-disk.md) this worker may touch, chosen from the ones its kind holds. Each entry is a document's [ref](./documents-on-disk.md#a-documents-ref), the name it gets from where its file sits. A ref on its own is read-only. `: rw` grants writes, and `: ro` spells the default out. Leave the key out and the worker reaches every document its kind installed, and writes the ones that allow writes; `resources: []` is how you say it gets none. @@ -141,7 +141,7 @@ A worker's id is its team folder and its own folder joined with a dot. `teams/en An org seat's id is its folder name alone, with no dot: `org/workers/chief-of-staff/` is `chief-of-staff`. Since a team seat's id always has a dot, the two can't collide. `chief-of-staff` and `engineering.chief-of-staff` are two different seats. -The team qualifier means every team can have a `lead` without checking what the other teams called theirs. The dot matters because the id is also the address: a hired worker is a flow instance, reached at `POST /api/flows/engineering.lead/actions/run`, and an id containing a `/` registers fine and then fails to route. +The team qualifier means every team can have a `lead` without checking what the other teams called theirs. The id is how everything else names the worker: a session's `workerId`, a mailbox's `members:`, a task handed to it. Its sessions run on the flow it names, so `engineering.lead` on `agent` is talked to in a session of `agent` created with `state: { workerId: "engineering.lead" }`. ### Names in the tree {#names-in-the-tree} @@ -260,76 +260,100 @@ Inside a worker slot the opposite holds. A folder there that produces no worker ## Hiring the roster -`hireWorkforce` takes the records and the flow kinds your app defined, and hands back one configured copy of a flow per worker. A **seat** is what comes back: a flow copy with its own id and its own settings. +Every `WORKER.md` is a **standard worker**. Every user of every organization in the installation +has it, configured exactly as the file says, and nobody can edit it while the app runs. To change +one for yourself, [fork it](./durable-hire.md#forking-a-worker). + +Each flow a worker names runs as one copy, shared by every worker that names it. A hundred +workers on `agent` are one registered flow, not a hundred. What makes them different is their +configuration, which the flow reads on each turn, and, on `agent`, their memory, which is kept per +worker. + +Hand the records to an installation, then ask `hireWorkforce` for the flows to register: ```ts -import { hireWorkforce } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, hireWorkforce } from "@flow-state-dev/workforce"; import { customAgentFlow, intakeFlow } from "./flows"; -const seats = hireWorkforce(workers, { +const installation = createWorkerInstallation({ + standardWorkers: workers, workerFlows: { "custom-agent": customAgentFlow, intake: intakeFlow }, }); -flowRegistry.registerMany(seats); +const flows = hireWorkforce(installation); +flowRegistry.registerMany(flows); -seats.map((seat) => seat.id); -// ["engineering.analyst", "engineering.lead", "support.intake"] — ordered by id +flows.map((flow) => flow.id); +// ["agent", "custom-agent", "intake", "workforce-roster"] ``` -Pass `defineFlow(...)` results directly as `workerFlows`. The call reads no files and builds no flow graph; your flows already exist, and a record only says which one a worker runs and how that copy is configured. It registers nothing either. You register what comes back. +One copy per flow, at the flow's own kind, plus `workforce-roster`, the flow an app +[hires, forks and fires](./durable-hire.md) through. The call reads no files and registers +nothing itself: you register what comes back. -`workerFlows` is optional. A record that names no `flow:` is hired into [the built-in worker kind](./built-in-worker.md), which ships with the framework, so one roster can mix workers running your flows with workers running that one. +`workerFlows` is optional. A record that names no `flow:` runs on +[the built-in worker flow](./built-in-worker.md), which the installation adds for you, so one +roster can mix workers on your flows with workers on that one. ### The flow decides what a worker may declare -A flow kind declares its settings with `configSchema`. A kind you want to hire workers into starts -from `workerConfigSchema()` and extends it: +A worker flow declares its settings with `configSchema`, starting from `workerConfigSchema()` and +extending it. It is built on the installation that runs its workers, so a flow in its own module +exports a `workerFlow(...)` builder, which the installation builds once, with itself: ```ts -import { workerConfigSchema } from "@flow-state-dev/workforce"; - -export const customAgentFlow = defineFlow({ - kind: "custom-agent", - cardinality: "collection", - configSchema: workerConfigSchema().extend({ - instructions: z.string(), // the contract's own is optional; this kind requires one - model: z.string().default("openai/gpt-5.4-mini"), - tools: z.array(z.string()).default([]), +import { defineFlow } from "@flow-state-dev/core"; +import { workerConfigSchema, workerFlow } from "@flow-state-dev/workforce"; + +export const customAgentFlow = workerFlow((installation) => + defineFlow({ + kind: "custom-agent", + configSchema: workerConfigSchema().extend({ + instructions: z.string(), // the contract's own is optional; this flow requires one + model: z.string().default("openai/gpt-5.4-mini"), + tools: z.array(z.string()).default([]), + }), + session: installation.session(), // the session's worker, checked when it is created + resources: { ...installation.resources }, // the user's workers, and the standard ones + actions: { run: { inputSchema, block: runTurn(installation), userMessage: (input) => input.message } }, }), - actions: { run: { inputSchema, block: runTurn, userMessage: (input) => input.message } }, -}); - -export const intakeFlow = defineFlow({ - kind: "intake", - cardinality: "collection", - configSchema: workerConfigSchema().extend({ desk: z.string().default("front") }), - actions: { run: { inputSchema, block: greet, userMessage: (input) => input.message } }, -}); +); + +export const intakeFlow = workerFlow((installation) => + defineFlow({ + kind: "intake", + configSchema: workerConfigSchema().extend({ desk: z.string().default("front") }), + session: installation.session(), + resources: { ...installation.resources }, + actions: { run: { inputSchema, block: greet(installation), userMessage: (input) => input.message } }, + }), +); ``` -`workerConfigSchema()` is the set of settings every seat's bag may carry, whatever kind it is: the +`workerConfigSchema()` is the set of settings every worker may carry, whatever flow it runs on: the worker's own instructions, the skills its folders resolved, the blocks its own folders registered and its `tools:` named, the [packages](./packages-on-disk.md#in-a-kind-of-your-own) it holds, and `teamInstructions` — what its team's [`TEAM.md`](#what-a-teammd-says) -said, when its team wrote one. Your kind's settings go on top with `.extend()`, at the same level, and the +said, when its team wrote one. Your flow's settings go on top with `.extend()`, at the same level, and the schema stays closed around all of them. -You do not have to read any of it. A kind that composes the contract and never looks at the skills -runs exactly as it would otherwise. A kind with nowhere to put them stops hiring: the seat factory -hands every worker the same settings, and a schema that cannot take them refuses at startup, naming -the flow and the line to add. +You do not have to read any of it. A flow that composes the contract and never looks at the skills +runs exactly as it would otherwise. A flow with nowhere to put them refuses at startup, naming the +flow and the line to add. -What hiring checks is what your schema accepts, not which function built it, so declaring those -keys by hand works too. Composing is how you stay current: a key added to the contract reaches a -composed kind for free, and makes a hand-rolled one refuse at startup until you add it as well. +What is checked is what your schema accepts, not which function built it, so declaring those keys +by hand works too. Composing is how you stay current: a key added to the contract reaches a +composed flow for free, and makes a hand-rolled one refuse at startup until you add it as well. -`cardinality: "collection"` is what lets one definition have many copies. A roster is exactly that: one copy per worker, each with its own id and its own settings. [Copies that differ by settings](../fundamentals/flows.md#copies-that-differ-by-settings) covers how a copy is configured, and [how an instance is addressed](../fundamentals/flows.md#how-an-instance-is-addressed) covers the URL each one answers on. +The installation reads keys of its own: `flow` to pick the flow, `description` as a label for the roster, [`resources`](#supplying-the-documents-a-seat-may-name) and `references` to decide which documents the worker reaches, and [`packages`](./packages-on-disk.md#giving-one-to-a-worker) to decide which library packages it holds. Everything else becomes that worker's settings and is parsed against the flow's `configSchema`, which is closed. So the flow's author, not the framework, decides what a worker on that flow may say about itself. -`hireWorkforce` reads keys of its own: `flow` to pick the kind, `description` as a label for the roster, [`resources`](#supplying-the-documents-a-seat-may-name) and `references` to decide which documents the copy is minted with, and [`packages`](./packages-on-disk.md#giving-one-to-a-worker) to decide which library packages it holds. Everything else becomes that copy's settings and is parsed against the flow's `configSchema`, which is closed. So the flow's author, not the framework, decides what a worker of that kind may say about itself. +A turn reads its worker's settings by loading the worker. `ctx.flow.config` is the shared copy's +own, the same for every worker on it, so don't read a worker's settings there: ```ts -const lead = seats.find((seat) => seat.id === "engineering.lead")!; +// inside runTurn, a block on the custom-agent flow +const worker = await installation.resolveWorker(ctx, "custom-agent"); -lead.config; +worker.config; // { instructions: "You are the engineering lead. …", // seatSkills: [], // seatTools: [], @@ -338,31 +362,33 @@ lead.config; // tools: ["board", "search"] } ``` -`seatSkills` and `seatTools` are on every seat hiring produces. This roster's folders held no skills for the lead and registered no blocks for it, so both come back empty. +`seatSkills` and `seatTools` are on every worker's configuration. This roster's folders held no skills for the lead and registered no blocks for it, so both come back empty. Schema defaults fill in. `support.intake` declared no settings beyond its `flow` and `description`, so it gets the `intake` flow's default `desk`: ```ts -const intake = seats.find((seat) => seat.id === "support.intake")!; - -intake.config; // { seatSkills: [], seatTools: [], seatId: "support.intake", desk: "front" } +worker.config; // { seatSkills: [], seatTools: [], seatId: "support.intake", desk: "front" } ``` -Every `config` is frozen. A worker asking for something its flow never declared does not quietly run without it: +Every `config` is frozen. A worker asking for something its flow never declared does not quietly +run without it. A standard worker is refused when you call `hireWorkforce`, and nothing is +registered: ``` -hireWorkforce refused 1 of 3 workers; nothing was hired: +hireWorkforce: 1 standard worker problem(s); nothing was registered: - worker "engineering.lead" — Flow "custom-agent" instance "engineering.lead" has an invalid config bag: "temperature" is not a declared setting. ``` +A user's own worker is checked the same way when it is hired or edited, and again on every turn. + Settings are spelled the way the flow declares them. ### Which flows can run workers A worker runs on a flow. The flows you pass in `workerFlows`, with the built-in `agent` -underneath, are your app's worker flows. `hireWorkforce` checks each one before it hires anyone, -and a worker that names a flow your app didn't pass is refused, by name. +underneath, are your app's worker flows. `hireWorkforce` checks each one before it registers +anything, and a worker that names a flow your app didn't pass is refused, by name. A worker flow must: @@ -372,21 +398,24 @@ A worker flow must: transform that replaces it is refused. - **Have one door.** Exactly one public action declares `userMessage` and takes `{ message }`, so an app can talk to any worker without knowing which flow it runs on. +- **Declare the installation's session.** `session: installation.session()` gives every session a + readonly `workerId`, checked when the session is created. A flow without it is refused, because + its sessions would run no checked worker. Load the worker with `installation.resolveWorker` on + every turn: in the flow's `request.onStarted`, or in the block that reads it. - **Declare any resource with `writtenBy` through `sharedResource()`.** A resource that has a `writtenBy` field is declared with [`sharedResource()`](#sharing-something-from-a-worker), which adds the field itself. A resource you define by hand with a `writtenBy` field is refused, even when its shape is right. -A worker is either **declared** or **hired**. A declared worker is one a `WORKER.md` file defines. -A hired worker is one hired while the app runs, through the [`hire` handler or tool](./durable-hire.md) -or a hire you write yourself, and every worker `reloadHiredSeats` brings back from the stored -roster, whether it is visible to the whole organization or to one member. To `hireWorkforce`, a -hired worker is a record that carries an owner pin. +A worker is either **standard** or **a user's own**. A standard worker is one a `WORKER.md` file +defines. A user's own worker is one they [hired or forked](./durable-hire.md), stored on their +roster. -To keep a flow for declared workers, so that no hired worker runs on it, mark the entry: +To keep a flow for standard workers, so that no user's own worker runs on it, mark the entry: ```ts -const workforce = hireWorkforce(workers, { +const installation = createWorkerInstallation({ + standardWorkers: workers, workerFlows: { triage: triageFlow, coordinator: { flow: coordinatorFlow, standardOnly: true }, @@ -395,13 +424,17 @@ const workforce = hireWorkforce(workers, { ``` A worker that names no flow runs on `agent`, and the mark is checked after that. To keep `agent` -for declared workers, pass it with the mark, either the built-in or your replacement: +for standard workers, pass it with the mark. The built-in is built on the installation, so pass +`workerFlows` as a function, which is read when first needed: ```ts -workerFlows: { agent: { flow: defineAgentWorkerFlow(), standardOnly: true } } +const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: () => ({ agent: { flow: defineAgentWorkerFlow({ installation }), standardOnly: true } }), +}); ``` -A hired worker that names no flow is then refused, and the message names `agent`. +A user's own worker that names no flow is then refused, and the message names `agent`. Writing a library of worker flows? Check each one in your own tests, without an app: @@ -420,13 +453,50 @@ when that is what it's built to do, and nothing stops it. The built-in `agent` keeps its own working state, such as its skills, in its user's scope. Write your own worker flows the same way, and put what you mean to share in a shared resource. +When one registered flow runs many workers, each loading its worker with +[`resolveWorker`](https://github.com/fixpoint-labs/flow-state-dev/blob/main/packages/workforce/README.md#workers-as-data), +a user's workers on that flow share the user's scope. The built-in `agent` keeps each worker's +skills apart for you. A worker flow you write doesn't: anything it keeps at user scope is read by +every one of that user's workers on the flow. It never reaches another user, whose data is kept +apart. + +If each worker should keep its own, put the worker in the key. Load the worker at the start of the +turn, then use its id: + +```ts +import { defineResourceCollection } from "@flow-state-dev/core"; +import { z } from "zod"; + +// One row per worker, in the user's scope. +const workerNotes = defineResourceCollection({ + pattern: "worker-notes/*", + scope: "user", + stateSchema: z.object({ text: z.string().default("") }), +}); + +// inside your flow's block, which declares `resources: { workerNotes, ...installation.resources }` +const worker = await installation.resolveWorker(ctx, "research"); +await ctx.resources.workerNotes.upsert(worker.id, { text: "Prefers short answers." }); +``` + +Use the id `resolveWorker` returns rather than one from the turn's input: it is the worker the +session was created with, checked on this turn. For skills, give your skills library a +`partitionBy` that returns the session's `workerId`: + +```ts +createSkillsLibrary({ scope: "user", partitionBy: (ctx) => ctx.session.state.workerId }); +``` + +A session's `workerId` can't change after it is created, so each session reads one worker's +skills. A run that `partitionBy` returns nothing for gets an empty catalog it can't write to, so a +session with no worker never reads every worker's skills. + #### Sharing something from a worker To let a worker write something every member can read, declare a shared resource and write -through the helper. What the entry records depends on how the worker runs: - -- A seat hired with `hireWorkforce`, from your tree or at runtime, records `{ userId }` only. -- A worker loaded with [`resolveWorker`](https://github.com/fixpoint-labs/flow-state-dev/blob/main/packages/workforce/README.md#workers-as-data) records `{ userId, workerId }`. +through the helper. The entry records the user and the worker the turn loaded with +[`resolveWorker`](https://github.com/fixpoint-labs/flow-state-dev/blob/main/packages/workforce/README.md#workers-as-data), +as `{ userId, workerId }`. A turn that loaded no worker records `{ userId }` only. ```ts import { sharedResource, writeShared } from "@flow-state-dev/workforce"; @@ -437,8 +507,6 @@ const notes = sharedResource("team-notes/*", { text: z.string() }); await writeShared(ctx, "notes", "launch", { text: "Launch moved to Friday." }); // stored, from a turn that loaded the worker "researcher" with resolveWorker: // { text: "Launch moved to Friday.", writtenBy: { userId: "alice", workerId: "researcher" } } -// stored, from a seat hired with hireWorkforce: -// { text: "Launch moved to Friday.", writtenBy: { userId: "alice" } } ``` `writeShared` sets `writtenBy` from the session and ignores any `writtenBy` in its input, so @@ -455,31 +523,25 @@ from the resource's scope and its ownership rules. A record's `body` is the worker's instructions, and it reaches the flow as one setting named `instructions`, alongside everything the record declared. Hiring imposes `instructions` when the body is not empty, `seatSkills`, `seatTools` and `seatId` always, `teamInstructions` when the record carries what its team's [`TEAM.md`](#what-a-teammd-says) said, and `seatPackages` when the worker holds a package. -Every hired seat knows its own id. It arrives as the `seatId` setting, the same id the team's `members:` lists, so a block running inside the seat can read who it is without being told. A worker file can't set it. `writeShared` doesn't sign with it: a seat hired with `hireWorkforce` records its user only, as above. +Every worker knows its own id. It arrives as the `seatId` setting, the same id the team's `members:` lists, so a block that loaded the worker can read who it is without being told. A worker file can't set it. `writeShared` doesn't sign with it: it signs with the worker the turn loaded, as above. -What the refusals cover is what a **file** declares. No frontmatter may set `teamInstructions`, `seatSkills`, `seatTools` or `seatId`: they are refused in a `WORKER.md`, and at hiring for a record you built by hand. A `TEAM.md` refuses `teamInstructions` too. On a record you build yourself, the *fields* of the same name are yours to set, and hiring uses them. `skills` works the same way: whatever a record carries there arrives as the seat's `seatSkills`. +What the refusals cover is what a **file** declares. No frontmatter may set `teamInstructions`, `seatSkills`, `seatTools` or `seatId`: they are refused in a `WORKER.md`, and by `hireWorkforce` for a record you built by hand. A `TEAM.md` refuses `teamInstructions` too. On a record you build yourself, the *fields* of the same name are yours to set, and hiring uses them. `skills` works the same way: whatever a record carries there arrives as the seat's `seatSkills`. The two instruction settings stay apart. A worker's own text is never merged into its team's, so a kind can read one without the other. On the [built-in worker kind](./built-in-worker.md) both go into the prompt, the team's first and the worker's own last. That order is fixed, and it is an order rather than a ranking: nothing resolves a contradiction between the two, so a team rule and a worker rule that disagree are left to the model that reads them. -Every hireable kind has that setting, because `workerConfigSchema()` declares it — so a worker's body always has somewhere to arrive, and no worker flow has to check for one. A kind whose schema will not take what hiring imposes is the one that refuses, and it refuses every record on the roster rather than just the ones with a body: +Every worker flow has that setting, because `workerConfigSchema()` declares it — so a worker's body always has somewhere to arrive, and no worker flow has to check for one. A flow whose schema will not take those settings is refused by `hireWorkforce` before anything is registered, whatever workers it holds: ``` -hireWorkforce refused 1 of 3 workers; nothing was hired: - - worker "support.intake" — Flow "intake" instance "support.intake" - has an invalid config bag: "instructions", "seatSkills", "seatTools" - is not a declared setting. Those keys are the framework's: every - hireable kind admits `instructions`, `seatSkills`, `seatTools` by - composing `workerConfigSchema()`, which is where everything the hire - step imposes on a seat arrives. - Wrap this kind's settings: `configSchema: - workerConfigSchema().extend({ ...its own settings })`. +hireWorkforce refused 1 worker flow ("intake"); nothing was hired: + - worker flow "intake" doesn't accept `instructions`, `seatSkills`, `seatTools`, … + Compose it: `configSchema: workerConfigSchema().extend({ ...its own settings })`. ``` -The instructions are available at `config.instructions`. What the flow does with them is the flow's business: a worker flow usually hands them to its generator as the system prompt. A flow that never reads them hires cleanly and ignores what the file said. +The instructions are available at `worker.config.instructions`, on the worker `resolveWorker` loaded. What the flow does with them is the flow's business: a worker flow usually hands them to its generator as the system prompt. A flow that never reads them hires cleanly and ignores what the file said. -A kind that wants instructions to be mandatory says so itself, by making the key required when it extends the contract — `workerConfigSchema().extend({ instructions: z.string() })`. Then a worker of that kind with no body is a failed hire. +A flow that wants instructions to be mandatory says so itself, by making the key required when it extends the contract — `workerConfigSchema().extend({ instructions: z.string() })`. Then a worker on that flow with no body is refused. -A worker with no body is still fully addressable. It just carries no instructions: a body that is empty, or only whitespace, contributes no `instructions` key at all. A body that has content reaches the flow verbatim, leading and trailing whitespace included. +A worker with no body still runs. It just carries no instructions: a body that is empty, or only whitespace, contributes no `instructions` key at all. A body that has content reaches the flow verbatim, leading and trailing whitespace included. Declaring `instructions:` in the frontmatter *and* writing a body is refused, naming both sources. There is no precedence rule between them. Whitespace is not a body: a `WORKER.md` that sets `instructions:` in its frontmatter and leaves nothing but a blank line below the fences hires fine, on the frontmatter value. @@ -487,55 +549,84 @@ Declaring `instructions:` in the frontmatter *and* writing a body is refused, na ### Supplying the documents a seat may name -A worker's `resources:` list selects from the documents its kind was installed with, so the hire step has to be told which entries in a kind's resource map are documents. Pass it the same map you spread into the flow. Here is [the `custom-agent` kind](#the-flow-decides-what-a-worker-may-declare) again with its documents installed — the action's `inputSchema` and `runTurn`, and the `workers` you loaded, are the same ones as there: +A worker's `resources:` list selects from the documents your app declared, so the installation +has to be told which they are. Pass it the map `resourcesFromDocs` returned, as `documents`: ```ts -import { defineFlow } from "@flow-state-dev/core"; -import { hireWorkforce, resourcesFromDocs, workerConfigSchema } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, hireWorkforce, resourcesFromDocs } from "@flow-state-dev/workforce"; import { readResourcesDirectory } from "@flow-state-dev/workforce/loader"; -import { boardResource } from "./resources"; +import { customAgentFlow } from "./flows"; const { documents } = await readResourcesDirectory("./workforce"); -const catalog = resourcesFromDocs(documents); - -export const customAgentFlow = defineFlow({ - kind: "custom-agent", - cardinality: "collection", - configSchema: workerConfigSchema().extend({ - instructions: z.string(), - model: z.string().default("openai/gpt-5.4-mini"), - tools: z.array(z.string()).default([]), - }), - resources: { board: boardResource, ...catalog }, - actions: { run: { inputSchema, block: runTurn, userMessage: (input) => input.message } }, -}); -const seats = hireWorkforce(workers, { +const installation = createWorkerInstallation({ + standardWorkers: workers, workerFlows: { "custom-agent": customAgentFlow }, - documents: catalog, + documents: resourcesFromDocs(documents), }); +const flows = hireWorkforce(installation); ``` -One catalog, spread into the flow and handed to the hire. Which entries in that map are documents is what the `documents` option answers: `board` above is not one, and no worker's list governs it. +Every worker on a flow shares its one copy, so the flow declares every document any of its workers +might be granted, and narrows what each turn's model reaches with the installation's +`resourceVisibility` rule. Here is [the `custom-agent` flow](#the-flow-decides-what-a-worker-may-declare) +again with its documents: -`documents` is consulted only for a worker that declares `resources:`. A roster where none does hires the same whether you pass it or not. A worker that does declare one while `documents` is absent is refused, naming what is missing. +```ts +import { defineFlow, handler } from "@flow-state-dev/core"; +import { workerConfigSchema, workerFlow } from "@flow-state-dev/workforce"; +import { boardResource } from "./resources"; -References go under a `references` option holding the map `referencesFromDocs` returned, and that one works the other way round: which references each worker reaches is worked out against it, so a kind holding references has to be hired with it. Leave it out, or pass a map missing one of them, and the whole roster is refused, naming every reference the hire was not given. [Installing the documents](./documents-on-disk.md#installing-the-documents) has the call with both maps. +export const customAgentFlow = workerFlow((installation) => { + // The turn's worker, loaded on every run of a request, a resumed one included. + const loadWorker = handler({ + name: "load-worker", + inputSchema: z.unknown(), + resources: { ...installation.resources }, + execute: async (_input, ctx) => ({ worker: (await installation.resolveWorker(ctx, "custom-agent")).id }), + }); + return defineFlow({ + kind: "custom-agent", + configSchema: workerConfigSchema().extend({ + instructions: z.string(), + model: z.string().default("openai/gpt-5.4-mini"), + tools: z.array(z.string()).default([]), + }), + session: installation.session(), + resources: { ...installation.resources, ...installation.documents, board: boardResource }, + resourceVisibility: installation.resourceVisibility, + request: { onStarted: loadWorker }, + actions: { run: { inputSchema, block: runTurn(installation), userMessage: (input) => input.message } }, + }); +}); +``` -A list the hire step cannot resolve refuses the whole roster, naming the worker and what was wrong. The message calls one entry a grant and quotes the ref as the file spelled it, which here is `handbook` with two letters swapped: +On each turn, the model's resource tools reach a document only when the worker loaded on that +turn is granted it: read and written for an `rw` grant, read only for a bare one. Every other +document answers exactly as one that doesn't exist, in listings, searches, reads and writes, and +through any tool you build on core's resource tools. A turn that loaded no worker reaches no +document. `board` is not a document, so no worker's list governs it. Your own block code that +names a document directly, as `ctx.resources.handbook`, isn't narrowed: that is your code, not +the model's reach. + +`documents` is consulted only for a worker that declares `resources:`. A worker that does declare +one while `documents` is absent is refused, naming what is missing. + +References go under a `references` option holding the map `referencesFromDocs` returned, and that one works the other way round: which references each worker reaches is worked out against it, so a flow holding references needs it. Leave it out, or pass a map missing one of them, and the roster is refused, naming every reference the installation was not given. [Installing the documents](./documents-on-disk.md#installing-the-documents) has the call with both maps. + +A list that can't be resolved refuses the whole roster at `hireWorkforce`, naming the worker and what was wrong. The message calls one entry a grant and quotes the ref as the file spelled it, which here is `handbook` with two letters swapped: ``` -hireWorkforce refused 1 of 3 workers; nothing was hired: +hireWorkforce: 1 standard worker problem(s); nothing was registered: - worker "engineering.lead" — grants "teams/engineering/hanbdook", which is - not a document this app declared. A grant selects from the documents passed - to hireWorkforce as `documents`; it cannot declare one. + not a document this app declared. … ``` ### When a hire is refused -Every problem here is a startup misconfiguration, so every problem throws. They are collected first, so one run names all of them and you fix them in one pass, and nothing is returned, so a bad record cannot leave you with a half-hired roster. +For a standard worker, every problem here is a startup misconfiguration, so `hireWorkforce` throws. Problems are collected first, so one run names all of them and you fix them in one pass, and nothing is returned, so a bad file cannot leave you with a short roster. A user's own worker is checked the same way when it is hired or edited, and that write is refused, naming the problem. -A record is refused when it: +A worker is refused when it: - declares a `flow` that is present but empty, or only whitespace — that names no kind. Leave the key out entirely to get the built-in `agent` kind; - names a flow that was not passed in `workerFlows`; the message lists the worker flows that were, including `agent`; @@ -548,54 +639,61 @@ A record is refused when it: - reaches a reference it did not name, the same way a document can come back through one of its kind's blocks; - declares a `resources:` list the hire step cannot resolve: a `resources:` that is not a list at all, an entry that is neither a ref nor a one-key `ref: mode` mapping, a ref no document matches, a ref naming a document the app declared but did not install on this worker's kind, a mode that is neither `ro` nor `rw`, the same ref twice, `rw` on a document whose own frontmatter says `writable: false`, a ref colliding with a name the kind's own blocks declare, a ref the kind does declare at flow level while what it holds there is not that document, or the key at all when no `documents` were passed; - reaches a document it never named, because one of its kind's blocks declares that document and a block's declaration merges back in after the worker's narrowed list is applied. Keep the document at flow level and let the block reach it there, or grant it to the worker deliberately; -- shares an id with another record in the same call, which is two workers claiming one address; -- is a hired worker naming a flow kept for declared workers, or naming no flow when `agent` is - kept. +- shares an id with another standard worker, which `createWorkerInstallation` refuses; +- is a user's own worker naming a flow kept for standard workers, or naming no flow when `agent` + is kept. -`hireWorkforce` checks each flow in `workerFlows` too, before it hires anyone. A flow is refused -when it is passed under a key that is not its own `kind`, has no door or more than one, doesn't -accept a worker's configuration, or has a resource with `writtenBy` that `sharedResource()` -didn't build. One run names every problem with every flow, and nothing is hired. +`hireWorkforce` checks each flow in `workerFlows` too, before it registers anything. A flow is +refused when it is passed under a key that is not its own `kind`, has no door or more than one, +doesn't accept a worker's configuration, doesn't declare the installation's session, or has a +resource with `writtenBy` that `sharedResource()` didn't build. One run names every problem with +every flow, and nothing is registered. -A stored worker refused at startup is handled by `reloadHiredSeats`, not thrown: see -[Reading the roster back at the next start](./durable-hire.md#reading-the-roster-back-at-the-next-start). +A user's own worker that stops resolving after it was saved, because a tool it names was removed +or its flow is now kept for standard workers, isn't dropped: its next turn is refused, naming the +problem, and an `edit` fixes it. ## When a worker needs more than settings -A `WORKER.md` is data: a description, the flow kind the worker runs, and that kind's settings. Behavior lives in the flow it names. So a worker that has to *do* something no kind on your roster does is a flow you define in your app, pass to `hireWorkforce` in `workerFlows`, and name in that worker's `flow:`. +A `WORKER.md` is data: a description, the flow the worker runs on, and that flow's settings. Behavior lives in the flow it names. So a worker that has to *do* something no flow on your roster does is a flow you define in your app, pass to the installation in `workerFlows`, and name in that worker's `flow:`. Say the engineering team wants a worker that routes an incoming request in code, rather than asking a model where it should go. That is a flow kind of its own: ```ts import { defineFlow, router } from "@flow-state-dev/core"; -import { workerConfigSchema } from "@flow-state-dev/workforce"; +import { workerConfigSchema, workerFlow } from "@flow-state-dev/workforce"; import { z } from "zod"; import { answer, escalate } from "./triage-blocks"; const requestSchema = z.object({ message: z.string(), priority: z.number().default(0) }); -// The decision is the flow's graph: a router block picks the branch from the -// request itself. `answer` is a generator; `escalate` hands off to a person. -// `flowConfigSchema` declares the slice of the flow's settings this block -// reads, and they arrive as `ctx.flow.config`. -const triage = router({ - name: "triage", - inputSchema: requestSchema, - flowConfigSchema: z.object({ escalateAbove: z.number() }), - routes: [answer, escalate], - execute: (input, ctx) => - input.priority >= ctx.flow.config.escalateAbove ? escalate : answer, -}); - -export const requestTriageFlow = defineFlow({ - kind: "request-triage", - cardinality: "collection", - configSchema: workerConfigSchema().extend({ - instructions: z.string(), - model: z.string().default("openai/gpt-5.4-mini"), - escalateAbove: z.number().default(3), - }), - actions: { run: { inputSchema: requestSchema, block: triage, userMessage: (input) => input.message } }, +export const requestTriageFlow = workerFlow((installation) => { + // The decision is the flow's graph: a router block picks the branch from the + // request itself. `answer` is a generator; `escalate` hands off to a person. + // The threshold is the worker's own setting, read from the worker this turn + // runs as: every worker on the flow shares one copy, and `ctx.flow.config`. + const triage = router({ + name: "triage", + inputSchema: requestSchema, + resources: { ...installation.resources }, + routes: [answer, escalate], + execute: async (input, ctx) => { + const worker = await installation.resolveWorker(ctx, "request-triage"); + return input.priority >= Number(worker.config.escalateAbove) ? escalate : answer; + }, + }); + + return defineFlow({ + kind: "request-triage", + configSchema: workerConfigSchema().extend({ + instructions: z.string(), + model: z.string().default("openai/gpt-5.4-mini"), + escalateAbove: z.number().default(3), + }), + session: installation.session(), + resources: { ...installation.resources }, + actions: { run: { inputSchema: requestSchema, block: triage, userMessage: (input) => input.message } }, + }); }); ``` @@ -612,14 +710,16 @@ Answer directly when the request is a question about a feature that already shipped. Keep it to a paragraph, and name the page you took the answer from. ``` -And at startup, the new kind goes in `workerFlows` beside the ones the rest of the roster runs: +And at startup, the new flow goes in `workerFlows` beside the ones the rest of the roster runs: ```ts -import { hireWorkforce } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, hireWorkforce } from "@flow-state-dev/workforce"; -const seats = hireWorkforce(workers, { +const installation = createWorkerInstallation({ + standardWorkers: workers, workerFlows: { "custom-agent": customAgentFlow, "request-triage": requestTriageFlow }, }); +const flows = hireWorkforce(installation); ``` `WORKER.md` is the only filename a worker slot is read for. A file of code sitting beside it changes nothing about the seat. @@ -628,22 +728,91 @@ const seats = hireWorkforce(workers, { The snippet above names `request-triage` twice: once in the flow, once in the `workerFlows` map at startup. Add a third kind and you edit two places. Forget the second, and the app boots and then refuses every worker that named it. -There is a file convention for the code half too. Put a flow kind in `workforce/flows/workers/`, a block in a `blocks/` folder, and run `fsdev gen`: it writes a module of static imports that your app passes straight to `hireWorkforce`. Adding a kind becomes adding a file. +There is a file convention for the code half too. Put a flow kind in `workforce/flows/workers/`, a block in a `blocks/` folder, and run `fsdev gen`: it writes a module of static imports that your app passes straight to `createWorkerInstallation`. Adding a flow becomes adding a file. [Code on disk](./code-on-disk.md) covers that tree, the command, what it generates, and where a `blocks/` folder may sit. +## Talking to a worker + +A conversation with a worker is a session, and a session runs one worker for its whole life. +You name the worker when the session is created. Messages after that never name it. + +**1. Pick the worker.** The user's roster lists their own workers and the standard ones. Each +entry names the flow it runs on, as `flow` (most run on `agent`). + +**2. Find or start the session.** + +```ts +import { createWorkforceClient } from "@flow-state-dev/workforce/browser" + +const workforce = createWorkforceClient({ userId, baseUrl }) +const session = await workforce.ensureWorkerSession({ worker: "researcher" }) +``` + +`createWorkforceClient` takes the same options as `createSessionClient`. Its +`ensureWorkerSession` returns the user's most recent session with that worker, and creates one +if there isn't one. It looks up the worker's flow for you. Two calls at once get the same +session, not two. If you move a worker to another flow, the next call starts a new session +there. When you only want to check, `findWorkerSession` takes the same argument and returns the +session or nothing. + +Both are built on the session client, which you can call directly. Use it to start a second +conversation with the same worker: + +```ts +import { createSessionClient } from "@flow-state-dev/client" + +const sessions = createSessionClient({ baseUrl }) +const mine = await sessions.listSessions({ flowKind: "agent", userId, state: { workerId: "researcher" } }) +const fresh = await sessions.createSession({ flowKind: "agent", userId, state: { workerId: "researcher" } }) +``` + +The server checks the worker when the session is created: it must be yours or a standard +one, and it must run on this flow. A worker that isn't yours is refused with the same answer +as one that doesn't exist. A session created without a worker is refused. `workerId` is a +readonly field of the session's state: nothing can change it after the create. It works the way +a project does in [Example: one session per project](../fundamentals/state-and-scopes.md#example-one-session-per-project). + +**3. Talk to it.** An ordinary action on that session: + +```ts +import { createClient } from "@flow-state-dev/client" + +const agent = createClient({ flowKind: session.flowKind, userId, baseUrl }) +await agent.sendAction("run", { message }, { sessionId: session.id }) +``` + +A message that names a worker is refused. So is a turn on a session whose worker was fired, or +moved to another flow since the session was created. + +In React, build the client once per user with `useMemo`. `useFlow` creates sessions with no +starting state, so a worker's flow refuses them: find or start the session with the client, then +make it the hook's active session. + +```tsx +const workforce = useMemo(() => createWorkforceClient({ userId, baseUrl }), [userId, baseUrl]) +const flow = useFlow({ flowKind: "agent" }) + +const session = await workforce.ensureWorkerSession({ worker: "researcher" }) +flow.selectSession(session.id) +``` + +Tasks and messages your other workers hand to this one open sessions the same way, naming the +worker when the session is created. + ## What this does not do - Reading the **Markdown** does not resolve tool or capability names. `tools: [board, search]` comes off the file as two strings; whether anything backs those names is checked at the hire, by the kind the worker runs on. The code walk is what registers the names a worker's list can resolve to. The built-in checks them [against its catalog](./built-in-worker.md#tools). A kind you write decides for itself. - It does not read the whole tree. `readWorkforceDirectory` opens worker slots only, `org/workers//` and `teams//workers//`; `readWorkforce` opens those plus the skills folders each worker draws from ([Skills](./built-in-worker.md#skills)) and each worker's packages ([Packages on disk](./packages-on-disk.md)). A team's `resources/` documents are read by a separate loader at startup, [`readResourcesDirectory`](./documents-on-disk.md). Its `blocks/` folder is not read at startup at all — that folder is scanned when you build, by [`fsdev gen`](./code-on-disk.md). A `tools/` folder is not a slot this convention reads, and `fsdev gen` says so rather than passing it over. - It does not follow symlinks inside the tree. A team, a worker slot, a `WORKER.md`, a skill folder — any of these that is a shortcut to somewhere else is refused rather than read. The root you hand it is refused too, with or without a trailing slash. It does not cover a root named through a `.` segment, or anything above the root, so a path that passes through a shortcut on its way in still reads. If you keep the tree behind a symlink on purpose, hand over the path it points at. - It does not watch the tree. Read it once, at startup, and re-run `fsdev gen` when the code folders change. -- It does not run a [task board](../orchestration/task-board.md). A hired worker is an address you open a session against, and a name a board can hand a task to: see [Giving a task to a worker](./overview.md#giving-a-task-to-a-worker). A board's own workers are in-process and claim tasks from a collection. -- It does not describe a mailbox. A `WORKER.md` mints one flow copy per record; a mailbox is a session on a shared kind, which is a different binding with a different reason. See [Mailboxes](./mailboxes.md). +- It does not run a [task board](../orchestration/task-board.md). A worker is someone you open a session with, and a name a board can hand a task to: see [Giving a task to a worker](./overview.md#giving-a-task-to-a-worker). A board's own workers are in-process and claim tasks from a collection. +- It does not describe a mailbox. A `WORKER.md` is one worker on its flow's shared copy; a mailbox is a session on a shared kind, which is a different binding with a different reason. See [Mailboxes](./mailboxes.md). ## Related pages -- [Workforce](./overview) — what a hired roster is, and when to reach for it instead of a task board. +- [Workforce](./overview) — what a roster is, and when to reach for it instead of a task board. +- [Hiring and forking](./durable-hire.md) — a user's own workers, hired, forked, edited and fired while the app runs. - [The built-in worker](./built-in-worker.md) — the `agent` kind a record with no `flow:` runs on, its tools, its skills, and its memory. - [Code on disk](./code-on-disk.md) — your own flow kinds, blocks and capabilities in the same tree, registered by `fsdev gen`. - [Skills](../skills/overview) — what a `SKILL.md` is and what goes in one. diff --git a/apps/docs/docs/workforce/workforce-overview.svg b/apps/docs/docs/workforce/workforce-overview.svg index a3fd9e76d4..859fa38499 100644 --- a/apps/docs/docs/workforce/workforce-overview.svg +++ b/apps/docs/docs/workforce/workforce-overview.svg @@ -33,8 +33,8 @@ - Worker file, seat, session: where each lives - A worker file describes a worker; the seat you hire from it is what runs. + Worker file, worker, session: where each lives + A worker file describes a worker; one shared copy of its flow runs it. @@ -64,9 +64,9 @@ readWorkforce: reads the files - Seat engineering.lead - hireWorkforce: a flow kind, configured, - with its own id. Reads no files. + One copy per flow + hireWorkforce: agent, once, for every + worker on it. Reads no files. Registry @@ -82,23 +82,23 @@ Kept across restarts when persistent - Sessions on the seat + Sessions naming a worker Each person's conversation, its state and resources Never written into the file - Roster row - Only for a seat hired while - the app runs. Read back at - the next start. - See Hiring at runtime + A user's own worker + A row in their own data, + hired or forked while the + app runs. Nobody else's. + See Hiring and forking - Not a copy - A seat is the flow kind plus an id and settings. The kind is unchanged, and many seats can run on it. - You open a session against a seat the way you open one against any flow. Its sessions belong to the seat, not to the file. - A mailbox is a session on the shared mailbox kind. Its members are seats; the mailbox is not one. - A task's assignee can name any worker that takes tasks. The board runs the list; Workforce finds the worker. + One copy, many workers + A worker is an id and settings. Every worker on a flow shares its one registered copy. + A session names its worker when it is created, and nothing changes it. It runs on the worker's flow. + A mailbox is a session on the shared mailbox kind. Its members are workers; the mailbox is not one. + A task's assignee can name a standard worker that takes tasks. The board runs the list; Workforce finds the worker. diff --git a/packages/cli/README.md b/packages/cli/README.md index 0fbd3c2f83..4fe0e5fda1 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -273,7 +273,7 @@ Output is a JSON object with execution results, schema validation status, and ti Walks `workforce/flows/workers/`, `workforce/flows/mailboxes/` and `workforce/blocks/`, and writes `workforce/workforce.gen.ts` beside them. The generated module exports `kinds`, `mailboxKinds` and -`blocks`: the maps `hireWorkforce`, `mailboxInstances` and a task board already take. Each discovered +`blocks`: the maps `createWorkerInstallation`, `mailboxInstances` and a task board already take. Each discovered file registers under its basename. It also walks every `resources/` folder the workforce convention reads — the organisation's, each diff --git a/packages/workforce/README.md b/packages/workforce/README.md index 2d961ae71f..fc4259941a 100644 --- a/packages/workforce/README.md +++ b/packages/workforce/README.md @@ -2,11 +2,14 @@ The seat factory for flow-state-dev. -A **worker** is a flow kind plus its instructions. Describe each one as a `WORKER.md` record, then hire the roster: `hireWorkforce` turns those records into one configured, addressable flow copy per worker, which you register. +A **worker** is a configuration plus an owner, run by one shared copy of the flow it names. Describe +each standard worker as a `WORKER.md` record; every user has those. Users hire or fork workers of +their own while the app runs, as rows in their own data. `createWorkerInstallation` holds both, and +`hireWorkforce` gives back the flows to register: one copy of each worker flow, and the roster flow. ## Quick Start -Describe the roster on disk, read it, hire it, register what comes back. +Describe the roster on disk, read it, build the installation, register what comes back. ``` workforce/teams/engineering/workers/lead/WORKER.md @@ -25,33 +28,51 @@ and lists whatever failed to load on `problems`. ```ts import { readDeclaredRoster } from "@flow-state-dev/workforce/loader"; -import { hireWorkforce } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, hireWorkforce } from "@flow-state-dev/workforce"; const roster = await readDeclaredRoster("./workforce"); if (roster.problems.length) { throw new Error(`workforce: ${roster.problems.map((p) => `${p.layer} ${p.path}`).join(", ")}`); } -const seats = hireWorkforce(roster.workers); -flowRegistry.registerMany(seats); // FlowInstance[], ordered by id +const installation = createWorkerInstallation({ standardWorkers: roster.workers }); +const flows = hireWorkforce(installation); +flowRegistry.registerMany(flows); // ["agent", "workforce-roster"] ``` -That record names no `flow:`, so it is hired into the built-in `agent` kind and needs no -`workerFlows` argument. Its body becomes its instructions and steers its answers. +That record names no `flow:`, so it runs on the built-in `agent` flow and needs no `workerFlows` +option. Its body becomes its instructions and steers its answers. Every worker on `agent` shares +its one copy; a session names its worker when it is created, and each turn loads it. -The built-in keeps each worker's skills in the scope of the user it runs for, so two people never -share one worker's copy. +The built-in keeps each worker's skills apart, per user, so two workers never share a drawer and +two people never share one worker's. + +To talk to it, find or start a session with the worker, then send to the flow it names: + +```ts +import { createClient } from "@flow-state-dev/client"; +import { createWorkforceClient } from "@flow-state-dev/workforce/browser"; + +const workforce = createWorkforceClient({ userId, baseUrl }); +const session = await workforce.ensureWorkerSession({ worker: "engineering.lead" }); +await createClient({ flowKind: session.flowKind, userId, baseUrl }).sendAction("run", { message }, { sessionId: session.id }); +``` To run a worker on a flow you wrote, name that flow's `kind` in the record's `flow:` and pass the -flow under the same key: +flow under the same key. A worker flow is built on the installation, so a flow in its own module +exports a `workerFlow(...)` builder: ```ts -const seats = hireWorkforce(workers, { workerFlows: { "custom-agent": customAgentFlow } }); +const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: { "custom-agent": customAgentFlow }, // workerFlow((installation) => defineFlow({ ... })) +}); ``` -`customAgentFlow` is your own `defineFlow(...)`. The record's frontmatter becomes that flow's config -and its body arrives as `config.instructions`, so the flow's `configSchema` — not this package — -decides what a worker may declare. One roster can mix both. +The record's frontmatter becomes that worker's configuration, parsed by the flow's `configSchema`, +and its body arrives as `instructions`, so the flow — not this package — decides what a worker may +declare. A turn reads it from `installation.resolveWorker(ctx, kind).config`. One roster can mix +both. [Workers as data](#workers-as-data) has the whole contract. ## Personas @@ -261,12 +282,12 @@ back everything declared in it, plus one list of what failed to load. import { readDeclaredRoster } from "@flow-state-dev/workforce/loader"; const roster = await readDeclaredRoster("./workforce"); -const seats = hireWorkforce(roster.workers); +const flows = hireWorkforce(createWorkerInstallation({ standardWorkers: roster.workers })); ``` | Field | What it holds | |-------|---------------| -| `workers` | One `WorkerManifest` per worker, each carrying its own resolved skills. The records `hireWorkforce` takes. | +| `workers` | One `WorkerManifest` per worker, each carrying its own resolved skills. The standard workers `createWorkerInstallation` takes. | | `teams` | One `TeamManifest` per team that wrote a [`TEAM.md`](#the-optional-team-file). A team without one is absent, not present-and-empty. | | `documents` | One `ResourceDoc` per [document](#reading-documents-from-files), from every `resources/` folder the convention reads. | | `references` | One `ResourceDoc` per [reference](#reading-documents-from-files), from every `references/` folder, each carrying the `filePath` it was read from. | @@ -335,12 +356,14 @@ whose name breaks the naming rules. ## Hiring a workforce -`hireWorkforce` turns worker records into **seats**: one configured, addressable flow copy per worker. -It reads no files, builds no flow graph, and registers nothing. You pass the worker flows your app -defined, as `workerFlows`, and you register what comes back. +`createWorkerInstallation` takes the standard workers and the worker flows your app defined, and +`hireWorkforce` gives back the flows to register: **one copy of each worker flow**, at the flow's own +kind, and the roster flow (`workforce-roster`). Every worker on a flow shares its one copy. Nothing +is minted per worker and nothing is pinned to an owner, so a hire, fork or fire while the app runs +is a write to the user's data, seen by every process on the next turn. ```ts -import { hireWorkforce, type WorkerManifest } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, hireWorkforce, type WorkerManifest } from "@flow-state-dev/workforce"; const workers: WorkerManifest[] = [ { @@ -351,25 +374,35 @@ const workers: WorkerManifest[] = [ { id: "engineering.intake", declared: { flow: "intake", description: "The front door." }, body: "" }, ]; -const seats = hireWorkforce(workers, { workerFlows: { "custom-agent": customAgentFlow, intake: intakeFlow } }); -flowRegistry.registerMany(seats); // FlowInstance[], ordered by id +const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: { "custom-agent": customAgentFlow, intake: intakeFlow }, // workerFlow(...) builders +}); +const flows = hireWorkforce(installation); +flowRegistry.registerMany(flows); // agent, custom-agent, intake, workforce-roster ``` -The factory reads three keys of its own: **`flow`**, which names the kind to instantiate, +The installation reads three keys of its own: **`flow`**, which names the flow the worker runs on, **`description`**, the roster label, and **[`resources`](#the-documents-a-seat-may-touch)**, the -documents this seat may touch. Everything else is that worker's settings, handed to the flow -verbatim and parsed against its `configSchema`. That schema is closed, so a setting the flow never -declared is refused by name at the hire. +documents this worker may touch. Everything else is that worker's settings, parsed against the +flow's `configSchema`. That schema is closed, so a setting the flow never declared is refused by +name: for a standard worker by `hireWorkforce`, before anything is registered, and for a user's +own worker when it is hired or edited. + +A worker flow declares the installation's session (`session: installation.session()`), so every +session names its worker in a readonly `workerId`, checked when the session is created, and loads +that worker on every turn with `installation.resolveWorker(ctx, kind)`. `hireWorkforce` refuses a +worker flow that doesn't declare it. -A seat takes a person's message through its **door**, which names an action on the seat's flow: -the one public action its kind declares with `userMessage` and a `{ message }` input. The hire finds it, and `openInventory` writes it on the -seat's [inventory row](#the-inventory) as `door`. Every worker flow has exactly one: a flow with -none, or with two, is refused when `hireWorkforce` checks its worker flows, naming the flow. +A worker takes a person's message through its flow's **door**: the one public action the flow +declares with `userMessage` and a `{ message }` input. `openInventory` writes it on the worker's +[inventory row](#the-inventory) as `door`. Every worker flow has exactly one: a flow with none, or +with two, is refused when `hireWorkforce` checks its worker flows, naming the flow. ### The documents a seat may touch -A `WORKER.md` may list the [file-declared documents](#reading-documents-from-files) that seat is -allowed to reach, chosen from the ones its kind was installed with: +A `WORKER.md` may list the [file-declared documents](#reading-documents-from-files) that worker is +allowed to reach, chosen from the ones the app declared: ```md --- @@ -381,68 +414,73 @@ resources: --- ``` -A ref on its own is read-only: the seat reads the document, and a write is refused both at the -resource handle and through the model's own write tool. `: rw` grants writes, and -`: ro` spells the default out. +A ref on its own is read-only: the worker's model reads the document, and a write through its +resource tools is refused. `: rw` grants writes, and `: ro` spells the default out. A +document the worker isn't granted answers its model exactly as one that doesn't exist, through +core's resource tools and any tool built on them. That is the flow's `resourceVisibility` rule, +which the installation supplies: block code that names a document directly is not narrowed. -**Absent and empty are different answers.** A seat whose file has no `resources:` key reaches every -document its kind installed, and writes the ones that allow writes. `resources: []` is how a file -says a seat gets none. +**Absent and empty are different answers.** A worker whose file has no `resources:` key reaches every +document the app declared, and writes the ones that allow writes. `resources: []` is how a file +says a worker gets none. -**Only documents are narrowed.** The stores, boards and anything else the kind declares at flow -level stay reachable and writable whatever a seat's list says, and so do the resources the kind's -own blocks declare. +**Only documents are narrowed.** The stores, boards and anything else the flow declares stay +reachable and writable whatever a worker's list says. -For a ref to resolve, the hire step has to be told which entries in the kind's map are documents. -Hand it the same catalog you spread into the flow: +For a ref to resolve, the installation has to be told which documents the app declared. Hand it the +map `resourcesFromDocs` returned, and declare `installation.documents` and the installation's +`resourceVisibility` on the flow: ```ts import { defineFlow } from "@flow-state-dev/core"; -import { hireWorkforce, resourcesFromDocs, workerConfigSchema } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, resourcesFromDocs, workerConfigSchema, workerFlow } from "@flow-state-dev/workforce"; import { readResourcesDirectory } from "@flow-state-dev/workforce/loader"; -import { inputSchema, runTurn } from "./blocks"; +import { inputSchema, loadWorker, runTurn } from "./blocks"; import { boardResource } from "./resources"; const { documents } = await readResourcesDirectory("./workforce"); -const catalog = resourcesFromDocs(documents); -const customAgentFlow = defineFlow({ - kind: "custom-agent", - cardinality: "collection", - configSchema: workerConfigSchema(), - resources: { board: boardResource, ...catalog }, - actions: { run: { inputSchema, block: runTurn } }, -}); +const customAgentFlow = workerFlow((installation) => + defineFlow({ + kind: "custom-agent", + configSchema: workerConfigSchema(), + session: installation.session(), + resources: { board: boardResource, ...installation.resources, ...installation.documents }, + resourceVisibility: installation.resourceVisibility, + request: { onStarted: loadWorker(installation) }, // installation.resolveWorker(ctx, "custom-agent") + actions: { run: { inputSchema, block: runTurn, userMessage: (input) => input.message } }, + }), +); -const seats = hireWorkforce(workers, { +const installation = createWorkerInstallation({ + standardWorkers: workers, workerFlows: { "custom-agent": customAgentFlow }, - documents: catalog, + documents: resourcesFromDocs(documents), }); ``` -One catalog, spread into the flow and passed to the hire. Which entries in that map are documents -is what the `documents` option answers: `board` above is not one, and no seat's list governs it. +The flow declares every document any of its workers may be granted, and the rule narrows each +turn's model to its own worker's: a turn that loaded no worker reaches no document. `board` above +is not a document, and no worker's list governs it. -`documents` is consulted only for a seat that declares `resources:`. A roster where none does hires -the same whether it is passed or not, and a seat that does declare one while `documents` is absent -is refused, naming what is missing. +`documents` is consulted only for a worker that declares `resources:`. A worker that does declare +one while `documents` is absent is refused, naming what is missing. -Every problem with a list refuses the whole roster, naming the seat: a `resources:` that is not a +Every problem with a list refuses the worker, naming it: a `resources:` that is not a list at all, an entry that is neither a ref nor a one-key `ref: mode` mapping, a ref no document -matches, a ref naming a document the app declared but did not install on this seat's kind, a mode +matches, a ref naming a document the app declared but did not install on this worker's flow, a mode that is neither `ro` nor `rw`, the same ref twice, `rw` on a document whose own frontmatter says `writable: false`, a ref colliding with a name the kind's own blocks already declare, and a ref the kind does declare at flow level while what it holds there is not the document the app passed — the -two cannot be told apart, so the hire refuses rather than guessing. +two cannot be told apart, so it is refused rather than guessed. -One more is checked on the seat after it is built rather than on the list: if a document the seat -did **not** name is reachable anyway — because one of the kind's blocks declares that same document, -and a block's declaration is merged back in after a seat's narrowed map replaces the flow-level one -— the hire refuses, naming the ref and the kind. Keep such a document at flow level and let the -block reach it from there, or grant it to the seat deliberately. +One more is checked on the worker's configuration rather than on the list: if a document the worker +did **not** name is reachable anyway — because one of the flow's blocks declares that same +document — it is refused, naming the ref and the flow. Keep such a document at flow level and let +the block reach it from there, or grant it to the worker deliberately. -`resources:` never reaches the kind's settings. It is the factory's key, like `flow` and -`description`, so a kind that declares a `resources` setting of its own does not receive one from a +`resources:` never reaches the flow's settings. It is the installation's key, like `flow` and +`description`, so a flow that declares a `resources` setting of its own does not receive one from a file. `references:` is the sibling key, over the documents in `references/` folders. It narrows within a @@ -461,7 +499,7 @@ A worker kind is an ordinary flow. What makes it *hireable* is that its `configS | `seatSkills` | The skills its folders resolved for it, in level order. Imposed on every seat, present and empty when there are none. | | `seatTools` | The blocks this seat's `tools:` resolved to from its own folders and the packages it holds, already resolved. Imposed on every seat, present and empty when there are none. Live blocks, not names — names that resolved to the kind's catalog stay on the kind's own `tools` setting. | | `seatPackages?` | The [packages](#packages-from-files) this seat holds, in the order it holds them: `{ name, path, instructions?, tools }[]`, where `tools` is the package's blocks. Imposed when the seat holds at least one, absent otherwise. | -| `seatId` | The seat's own id — the one a mailbox's `members:` lists and checks an author against. For a runtime-hired seat it is the roster's seat id, not its `.` address. Imposed on every seat. A block inside the seat reads it from `ctx.flow.config.seatId` to sign what it files or posts. | +| `seatId` | The worker's own id — the one a mailbox's `members:` lists and checks an author against. Imposed on every worker. A block reads it from the worker the turn loaded (`installation.resolveWorker(ctx, kind).config.seatId`), never from `ctx.flow.config`, which the shared copy holds once for every worker. | So hiring imposes `instructions` when the body is not empty, `seatSkills`, `seatTools` and `seatId` always, `teamInstructions` when the seat's team wrote a `TEAM.md`, and `seatPackages` when the seat @@ -475,16 +513,19 @@ the same value in the bag. Add your kind's own settings on top, at the same level: ```ts -import { workerConfigSchema } from "@flow-state-dev/workforce"; - -const triage = defineFlow({ - kind: "request-triage", - cardinality: "collection", - configSchema: workerConfigSchema().extend({ desk: z.string().default("front") }), - actions: { - run: { inputSchema: z.object({ message: z.string() }), block: triageWork, userMessage: (input) => input.message }, - }, -}); +import { workerConfigSchema, workerFlow } from "@flow-state-dev/workforce"; + +const triage = workerFlow((installation) => + defineFlow({ + kind: "request-triage", + configSchema: workerConfigSchema().extend({ desk: z.string().default("front") }), + session: installation.session(), + resources: { ...installation.resources }, + actions: { + run: { inputSchema: z.object({ message: z.string() }), block: triageWork(installation), userMessage: (input) => input.message }, + }, + }), +); ``` `desk` sits at the top level beside the contract's keys, where the schema closes it: a worker file that writes @@ -494,9 +535,9 @@ did name. Reading any of it is optional. A kind that composes the contract and never looks at `seatSkills` is not an error. What is not optional is that your schema can take the bag: `hireWorkforce` checks -every flow in `workerFlows`, and the built-in `agent`, before it hires anyone, and a flow whose -schema refuses a key of the contract, or the value a hire supplies for one, refuses the whole call -with a message naming the flow and the fix. +every flow in `workerFlows`, and the built-in `agent`, before it registers anything, and a flow +whose schema refuses a key of the contract, or the value a worker supplies for one, refuses the +whole call with a message naming the flow and the fix. What is checked is what your schema accepts, not which function built it — so a kind that declares these keys by hand hires just the same, as long as each key takes the value a hire supplies @@ -504,8 +545,8 @@ these keys by hand hires just the same, as long as each key takes the value a hi composed kind picks it up, and a hand-rolled one refuses at boot naming the new key until you add it. -The same check also requires one door, and that any resource with `writtenBy` comes from -`sharedResource()`. The door is exactly one public action that declares `userMessage` and takes +The same check also requires one door, that the flow declares the installation's session, and +that any resource with `writtenBy` comes from `sharedResource()`. The door is exactly one public action that declares `userMessage` and takes `{ message }`, so an app can talk to any worker without knowing its flow; none, or two, refuses. A resource with a `writtenBy` field is declared with `sharedResource()`, which adds the field; one defined by hand is refused, even with the right shape. @@ -513,29 +554,31 @@ defined by hand is refused, even with the right shape. tests. [Which flows can run workers](https://flow-state.dev/docs/workforce/workers-on-disk#which-flows-can-run-workers) has the whole contract. Only `instructions` is ever authored. A worker file that writes `seatSkills:`, `seatTools:`, -`seatPackages:`, `seatId:` or `teamInstructions:` is refused by name, at the loader and at the hire: a seat's +`seatPackages:`, `seatId:` or `teamInstructions:` is refused by name, at the loader and by the installation: a seat's skills, its own blocks and its packages are the folders it can see, its id is its record's, and a team's instructions come from its team's `TEAM.md` body. That last key is refused in a `TEAM.md` too — the file an author would most reasonably try it in — so all three doors refuse it, from one exported constant rather than a literal spelled into each. -**A record that leaves `flow:` out is hired into the built-in `agent` kind** — it talks, its body +**A record that leaves `flow:` out runs on the built-in `agent` flow** — it talks, its body arrives as its instructions, and it reads the skills its own folders hold plus any the app seeded through `defineAgentWorkerFlow({ skills })`. It sees the earlier turns of the conversation it is in, up to the session's history window (the last 50 by default), and nothing from any other conversation. `workerFlows` is therefore optional. A `flow:` that is present but empty or whitespace-only refuses, because it names no kind — only an absent key means the built-in. -A seat on the `agent` kind is talked to through its `run` action, which takes `{ message }`. The -message a seat is sent is kept as the caller's turn in that seat's conversation, so a conversation -reads as both sides. +A worker on `agent` is talked to through the flow's `run` action, which takes `{ message }`, in a +session that names the worker. A message that names a worker is refused: the session already does. +The message is kept as the caller's turn in that conversation, so a conversation reads as both +sides. -Configure that kind by replacing it. Build the flow with `defineAgentWorkerFlow` and pass it under -`agent` (`workerFlows: { agent: defineAgentWorkerFlow({ catalog, skills }) }`). It takes over for every -seat that runs on the `agent` kind — the records that leave `flow:` out, and any that name `agent` -— and leaves a worker on any other kind alone. A flow of your own registered under `agent` must -declare `kind: "agent"` and `cardinality: "collection"`; without the second, each seat mints and is -then refused when you register it, because a singleton's id is its kind. +Configure that flow by replacing it. Build it with `defineAgentWorkerFlow({ installation, ... })` +and pass it under `agent`, with `workerFlows` as a function, since the flow is built on the +installation: +`workerFlows: () => ({ agent: defineAgentWorkerFlow({ installation, catalog, skills }) })`. It takes +over for every worker that runs on `agent` — the records that leave `flow:` out, and any that name +`agent` — and leaves a worker on any other flow alone. A flow of your own registered under `agent` +must declare `kind: "agent"`. A worker record declares data: a description, the kind it runs, and that kind's settings. Behavior lives in the flow the kind names, so a worker that has to do something none of your kinds do is a @@ -544,14 +587,14 @@ flow you define in your app and pass in `workerFlows`, named by that worker's `f A record's **`body` reaches its flow as one setting, `instructions`**. Every hireable kind declares that setting by composing `workerConfigSchema()`, so a body always has somewhere to arrive and no worker flow has to check for one; the instructions are available at `config.instructions`, and what -the flow does with them is the flow's business. A kind that wants instructions to be mandatory makes +the flow does with them is the flow's business. A flow that wants instructions to be mandatory makes the key required when it extends the contract — `workerConfigSchema().extend({ instructions: -z.string() })` — and a worker of that kind with no body is then a failed hire. +z.string() })` — and a worker on it with no body is then refused. A body that is empty or only whitespace contributes no `instructions` key at all; a body with content is handed over verbatim, leading and trailing whitespace included. A record that declares `instructions:` *and* carries a body is refused naming both sources. Whitespace is not a body, so a -record that declares `instructions:` and carries an empty or blank one hires on the frontmatter value. +record that declares `instructions:` and carries an empty or blank one runs on the frontmatter value. A `WORKER.md` has no `persona` setting: declaring it lands the worker in `readWorkforceDirectory`'s `errors`, or is refused by `hireWorkforce` for a hand-built record. @@ -567,7 +610,7 @@ worker. | --- | --- | | `uses` | Capabilities attached to every worker's answer generator. The skills binding stays first and is never displaced. A capability passed as a plain ref brings its own storage with it; one passed as a `(ctx) => refs` resolver brings none, so anything it needs has to be declared statically somewhere. | | `afterAnswer` | A block run after the answer as a side-chain. It receives the reply text as a string, it cannot change the answer, and a failure in it does not fail the turn. Absent, nothing runs after the answer. | -| `isolateUserState` | Forwarded to `defineFlow`. Gives each worker its own user-scoped storage, keyed on the worker's id, instead of one cell shared across the roster. Default `false`. | +| `isolateUserState` | Forwarded to `defineFlow`. Keys the flow's user-scoped storage by its copy, apart from the person's other flows. Every worker on `agent` shares the one copy, so a person's workers on it still share one cell. Default `false`. | **The tools fence.** A worker that writes a `tools:` line can call exactly the tools it lists, whatever it selected under `capabilities:`. The kind maps those names against the catalog and hands @@ -601,7 +644,7 @@ Memory is one thing you can pass through these options. Install `@flow-state-dev separately: ```ts -import { AGENT_KIND, defineAgentWorkerFlow, hireWorkforce } from "@flow-state-dev/workforce"; +import { AGENT_KIND, createWorkerInstallation, defineAgentWorkerFlow, hireWorkforce } from "@flow-state-dev/workforce"; import { system } from "@flow-state-dev/memory"; const mem = system({ @@ -611,7 +654,13 @@ const mem = system({ semantic: true, }); +const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: () => ({ [AGENT_KIND]: remembers }), +}); + const remembers = defineAgentWorkerFlow({ + installation, catalog: appTools, uses: [ mem.capability.presets({ @@ -621,11 +670,10 @@ const remembers = defineAgentWorkerFlow({ episodic: true, // context injection; OFF by default }), ], - isolateUserState: true, afterAnswer: mem.captureFromItems, }); -const seats = hireWorkforce(workers, { workerFlows: { [AGENT_KIND]: remembers } }); +const flows = hireWorkforce(installation); ``` Each of these fails quietly if you skip it: @@ -644,20 +692,18 @@ select it (`capabilities: { memory: [recall] }`) with no `tools:` line. A worker lists `memory/recall` in its `tools:`. The key has to match the tool's own name; a catalog key that doesn't is refused when the kind is built. -Isolation is a decision for the whole kind: a roster is all-isolated or all-shared. +Memory is kept in the person's user scope, so it never reaches another person or organization. Every +worker on `agent` shares the one copy, so one person's workers on it share what it remembers; only +the skills drawer is kept per worker. Keeping a capability's data apart per worker is the app's, +as for any data a worker flow keeps per user ([Workers as data](#workers-as-data)). -`isolateUserState` decides **where** a worker's user-scoped data is keyed, so anything that -changes the key leaves the old data behind. Two ways that happens, both with no migration: -**renaming a worker** (the key is its id), and **flipping the flag on a roster already in use** -(shared and isolated are different cells). Decide it before the roster carries anything worth -keeping. - -Every problem is a startup misconfiguration: problems are collected and thrown as one error naming -every bad worker, and nothing is returned, so a bad record cannot leave a half-hired roster. +Every problem with a standard worker is a startup misconfiguration: `hireWorkforce` collects them +and throws one error naming every bad worker, and registers nothing, so a bad record cannot leave a +short roster. ## Kinds and blocks from files -The `workerFlows` map above names each kind a second time, after the flow already declared it. There is a +The `workerFlows` map above names each flow a second time, after the flow already declared it. There is a file convention for that half too: put a flow under `workforce/flows/workers/` or `workforce/flows/mailboxes/`, or a block under `workforce/blocks/`, and the basename is the name it registers under. @@ -665,7 +711,7 @@ registers under. ``` workforce/ flows/ - workers/request-triage.ts ← default-exports a flow, cardinality: "collection" + workers/request-triage.ts ← default-exports a workerFlow(...) builder mailboxes/standup.ts ← default-exports a flow, singleton (the default) blocks/triage.ts ← a block any worker may name teams/engineering/blocks/build-status.ts ← a block this team's workers may name @@ -675,16 +721,22 @@ workforce/ ``` `fsdev gen` walks those folders and writes `workforce/workforce.gen.ts` beside them, exporting -`kinds`, `mailboxKinds`, `blocks`, `seatBlocks` and `packageBlocks` — parameters `hireWorkforce`, -`mailboxInstances`, a task board and a worker kind's tool catalog already take. The same file +`kinds`, `mailboxKinds`, `blocks`, `seatBlocks` and `packageBlocks` — parameters +`createWorkerInstallation`, `mailboxInstances`, a task board and a worker flow's tool catalog +already take. The same file carries `resourceModules`, covered in [Resource modules from files](#resource-modules-from-files). ```ts -import { defineAgentWorkerFlow, hireWorkforce } from "@flow-state-dev/workforce"; +import { createWorkerInstallation, defineAgentWorkerFlow, hireWorkforce } from "@flow-state-dev/workforce"; import { blocks, kinds, packageBlocks, seatBlocks } from "./workforce/workforce.gen"; -const agent = defineAgentWorkerFlow({ catalog: blocks }); -const seats = hireWorkforce(workers, { workerFlows: { ...kinds, agent }, seatBlocks, packageBlocks }); +const installation = createWorkerInstallation({ + standardWorkers: workers, + workerFlows: () => ({ ...kinds, agent: defineAgentWorkerFlow({ installation, catalog: blocks }) }), + seatBlocks, + packageBlocks, +}); +const flows = hireWorkforce(installation); ``` A `blocks/` folder **registers** a name: `workforce/blocks/` for every worker, a team's for that @@ -819,8 +871,8 @@ it; `tools: []` gets the text and no tools. (`PackageManifest[]`: the org's library, its team's, and its own folder; an org seat has no team's) and reports refused package folders on `packageErrors`. `readDeclaredRoster` reports the same entries on its `package` layer. The blocks come from `fsdev gen`'s `packageBlocks` export, keyed by package path and then block -name; pass it to `hireWorkforce`, which decides from each worker's folder and `packages:` line which -packages it holds. Leave `packageBlocks` out and a held package brings its instructions and no tools. +name; pass it to `createWorkerInstallation`, which decides from each worker's folder and `packages:` +line which packages it holds. Leave `packageBlocks` out and a held package brings its instructions and no tools. ```ts import { readWorkforce } from "@flow-state-dev/workforce/loader"; @@ -829,10 +881,11 @@ import { kinds, packageBlocks, seatBlocks } from "./workforce/workforce.gen"; const { workers, errors, packageErrors } = await readWorkforce("./workforce"); if (errors.length || packageErrors.length) throw new Error("workforce: failed to load"); -const seats = hireWorkforce(workers, { workerFlows: kinds, seatBlocks, packageBlocks }); +const installation = createWorkerInstallation({ standardWorkers: workers, workerFlows: kinds, seatBlocks, packageBlocks }); +const flows = hireWorkforce(installation); ``` -A kind of your own receives what a seat holds on `seatPackages`, and only when it holds at least one; +A flow of your own receives what a worker holds on `seatPackages`, and only when it holds at least one; composing `workerConfigSchema()` is what lets its schema accept the key. Reported by the loader, on `packageErrors`: a `PACKAGE.md` that is missing, has no frontmatter or @@ -899,12 +952,19 @@ Escalate anything customer-visible within 15 minutes. `readResourcesDirectory` walks all four and returns one record per document; `resourcesFromDocs` turns those records into the resource map you already pass to a flow. `readReferencesDirectory` and -`referencesFromDocs` are the same pair over `references/`. Both maps spread into one flow, and both -are passed to `hireWorkforce`: +`referencesFromDocs` are the same pair over `references/`. Both maps are passed to +`createWorkerInstallation`, and a worker flow spreads `installation.documents`, which holds both: ```ts import { defineFlow } from "@flow-state-dev/core"; -import { hireWorkforce, referencesFromDocs, resourcesFromDocs } from "@flow-state-dev/workforce"; +import { + createWorkerInstallation, + hireWorkforce, + referencesFromDocs, + resourcesFromDocs, + workerConfigSchema, + workerFlow, +} from "@flow-state-dev/workforce"; import { readReferencesDirectory, readResourcesDirectory } from "@flow-state-dev/workforce/loader"; import { answerQuestion } from "./blocks"; import { ticketResource } from "./resources"; @@ -915,26 +975,30 @@ for (const { errors } of [references, resources]) { if (errors.length) throw new Error(`workforce: ${errors.length} document(s) failed to load`); } -const documents = resourcesFromDocs(resources.documents); -const referenceMap = referencesFromDocs(references.documents); - -export const supportFlow = defineFlow({ - kind: "support", - actions: { answer: { block: answerQuestion } }, - resources: { ticket: ticketResource, ...documents, ...referenceMap }, -}); +const supportFlow = workerFlow((installation) => + defineFlow({ + kind: "support", + configSchema: workerConfigSchema(), + session: installation.session(), + resources: { ticket: ticketResource, ...installation.resources, ...installation.documents }, + resourceVisibility: installation.resourceVisibility, + actions: { answer: { inputSchema, block: answerQuestion(installation), userMessage: (input) => input.message } }, + }), +); -const seats = hireWorkforce(workers, { +const installation = createWorkerInstallation({ + standardWorkers: workers, workerFlows: { support: supportFlow }, - documents, - references: referenceMap, + documents: resourcesFromDocs(resources.documents), + references: referencesFromDocs(references.documents), }); +const flows = hireWorkforce(installation); ``` -`references` is what tells the hire which entries on a kind's map are references, and -[which seats reach which reference](#what-a-seat-reaches) is decided only for the entries it names. -So once a kind holds references, the option is required: omit it, or pass a map that is missing one of them, and `hireWorkforce` throws, naming every reference it -was not given. A kind that holds none needs no map. A ref passed in both maps is refused as well, +`references` is what tells the installation which entries are references, and +[which workers reach which reference](#what-a-seat-reaches) is decided only for the entries it names. +So once a flow holds references, the option is required: omit it, or pass a map that is missing one of them, and `hireWorkforce` throws, naming every reference it +was not given. A flow that holds none needs no map. A ref passed in both maps is refused as well, naming it. **Every file-declared document is org-scoped, and nothing needs declaring for that.** Organization @@ -1095,7 +1159,7 @@ errors; Neither reader sees the other's slot, so neither reports a basename claimed by both. `readDeclaredRoster` reads the whole tree and puts that collision in its `problems`, naming both -files; `hireWorkforce` throws on the same collision for a catalog that never passed a loader. +files; `createWorkerInstallation` throws on the same collision for a catalog that never passed a loader. `resourcesFromDocs` and `referencesFromDocs` throw instead of collecting, because a record that cannot become a resource is a startup misconfiguration. @@ -1324,10 +1388,10 @@ nor fence them out. A narrower set is a different capability. Compose it once per board; a seat holding two boards holds sixteen tools and the names say which board each writes to. A mailbox board is org-scoped, so it cannot be declared by a block colocated -in a seat's own folder; that refuses at hire. +in a seat's own folder; that refuses at `hireWorkforce`. Pass `hireWorkforce` the roster's minted ids as `mailboxBoards` and it warns on stderr for any board -no hired seat declares, naming the mailbox and the board. It never refuses: a mailbox may keep a +no registered flow declares, naming the mailbox and the board. It never refuses: a mailbox may keep a board that only people read. Each warning prints once per process, so a dev server that re-runs the hire on every hot reload says it once, and only a board that newly goes unattended prints again. @@ -1338,14 +1402,17 @@ that moved. ### Handing a row to the worker it names -A row's `assignee` can name any worker, by the name `discover` lists, including one hired while the -app runs, when the board draining the ledger asks the worker lookup who the name means. +A row's `assignee` can name any standard worker, by the name `discover` lists, when the board +draining the ledger asks the worker lookup who the name means. A mailbox's board is the +organization's, and whoever drains it opens the task's session, so it never reaches a user's own +worker: only that worker's owner can open a session with it. ```ts import { defineFlow, dispatcher } from "@flow-state-dev/core"; import { taskBoard } from "@flow-state-dev/orchestration/task-board"; import { WORKER_TASK_ENTRY, + createWorkerInstallation, createWorkerLookup, defineAgentWorkerFlow, defineMailboxFlow, @@ -1356,15 +1423,14 @@ import { } from "@flow-state-dev/workforce"; const boardIds = mailboxBoardIds(mailboxes); -const hired = hireWorkforce(workers, { - workerFlows: { agent: defineAgentWorkerFlow({ taskLists: boardIds }) }, // gives the agent kind a `work` task entry - mailboxBoards: boardIds, +const installation = createWorkerInstallation({ + standardWorkers: workers, + // gives the agent flow a `work` task entry + workerFlows: () => ({ agent: defineAgentWorkerFlow({ installation, taskLists: boardIds }) }), }); +const flows = hireWorkforce(installation, { mailboxBoards: boardIds }); -const lookup = createWorkerLookup({ - instanceAt: (id) => runtime.registry.get(id), // read on every lookup, never copied - declared: hired.map((worker) => worker.id), -}); +const lookup = createWorkerLookup({ installation }); const mailboxKinds = mailboxInstances(mailboxes, { kinds: { mailbox: defineMailboxFlow({ checkAssignee: lookup.filingCheck() }) }, @@ -1376,24 +1442,26 @@ const board = taskBoard({ boardId: followups.id, // hand off under the ledger's id collection: followups, workers: {}, - defaultWorker: dispatcher({ name: "hand-to-named-worker", action: WORKER_TASK_ENTRY, session: "per-task", flowKind: lookup.flowKind }), + defaultWorker: dispatcher({ + name: "hand-to-named-worker", + action: WORKER_TASK_ENTRY, + session: "per-task", + flowKind: lookup.flowKind, + state: lookup.state, // the task's session is born naming its worker + }), }); const desk = defineFlow({ kind: "followups-desk", actions: { drain: { block: board.drain } } })(); ``` -`createWorkerLookup({ instanceAt, declared })` returns `{ find(name, ctx, member?), flowKind, filingCheck(aliases?) }`. -`declared` may be a getter, read on every lookup, for a lookup built before the workers are hired. +`createWorkerLookup({ installation })` returns `{ find(name), flowKind, state, filingCheck(aliases?) }`. `find` answers `{ found: true, flowId }` or `{ found: false, reason, message }`, `reason` being -`not-found`, `ambiguous` or `takes-no-tasks`. It finds a worker the files declare (an id in -`declared` with a flow registered there), one hired for the request's organization, or one the -member who filed the task hired for themselves: the session owner at filing (or the `member` passed -to `find`), and at hand-over the filer the ledger recorded on the row, whoever runs the drain. A -row with no recorded filer reaches no member's own worker. Another organization's workers and another member's own are never found. A name held -by more than one of those is `ambiguous`, naming each; a worker whose kind declares no `work` task -entry is `takes-no-tasks`, which still carries the `flowId` the name means. +`not-found` or `takes-no-tasks`. It finds a standard worker, read from the installation on every +call; a worker whose flow declares no `work` task entry is `takes-no-tasks`, which still carries the +`flowId` the name means. `state` gives each task's session its starting state, naming the worker +the row names, so the flow's create check confirms it. `flowKind` is the `TaskFlowTarget` for a board's `defaultWorker`: `not-found` answers nothing, which -refuses the hand-over `flow-not-found` naming the assignee; `ambiguous` and `takes-no-tasks` throw +refuses the hand-over `flow-not-found` naming the assignee; `takes-no-tasks` throws `[workforce] task "" could not be handed over: `. Either way the attempt fails through the board's error path. `filingCheck(aliases?)` is `defineMailboxFlow`'s `checkAssignee`: it returns `undefined` for a name the lookup finds, else the message, which `fileTask` throws as @@ -1432,13 +1500,14 @@ nobody is woken. The framework carries the policy and your app supplies the addresses: the framework will not pick a dispatch target out of stored data, so a notify block declares its own recipients. -`wakeMemberSeats(seats, { fallback? })` is the notify block for `defineMailboxFlow({ notify })`. -It wakes each member whose hired seat declares the internal `onMailboxPost` entry, once per post, -in one conversation per seat per mailbox. A seat's line (`seatAuthored: true`) wakes nobody. A +`wakeMemberSeats(flows, { installation, fallback? })` is the notify block for +`defineMailboxFlow({ notify })`. It wakes each member that names a standard worker on a flow that +declares the internal `onMailboxPost` entry, once per post, in one conversation per worker per +mailbox, created naming that worker. A user's own worker isn't woken as a member. A seat's line (`seatAuthored: true`) wakes nobody. A client `post` wakes each hearing member whether or not it sets `author`. Members whose seat can't hear a post get `fallback`, or nothing, including on a seat's line. The fallback is not sent to a -member who would have been woken. Pass the seats -`hireWorkforce` returned, and hire before you build mailboxes. The built-in `agent` kind declares +member who would have been woken. Pass the flows +`hireWorkforce` returned, and call it before you build mailboxes. The built-in `agent` kind declares `onMailboxPost`; a kind of your own hears posts by declaring it too. See the mailboxes guide, "Waking agent seats". @@ -1451,19 +1520,18 @@ with a route: ```ts defineMailboxFlow({ - notify: wakeMemberSeats(seats), - route: routeByPurpose(seats, { model: "typesafe-ai/jev" }), + notify: wakeMemberSeats(flows, { installation }), + route: routeByPurpose(flows, { model: "typesafe-ai/jev", installation }), }); ``` -`routeByPurpose(seats, { model })` places each client `post` in this order: the member the last +`routeByPurpose(flows, { model, installation })` places each client `post` in this order: the member the last client `post` was routed to by the evaluator or the fallback, until it answers (a post held this way holds nothing, and neither does one whose route isn't recorded yet); else one evaluator call (block name `mailbox-route`) choosing among the members whose seat hears posts and has a description, each described by its `WORKER.md` `description:`; else the `fallback:` member, when that call fails or -answers outside the options, or when no member has a description and there is no call. A seat hired -at runtime has no description, since `hire` takes none, so it gets a post only as the fallback, or -as the next post held for it after that. The model must be able to evaluate. Only the chosen member +answers outside the options, or when no member has a description and there is no call. The model +must be able to evaluate. Only the chosen member is notified, with `routed: true` and `recent` (the mailbox's last 20 lines) on its delivery, and each decision is kept as one `mailbox-route` item on the mailbox's session, never as a line. The two fallbacks differ: `routing: fallback:` names a member who takes a post the route can't place, @@ -1540,306 +1608,50 @@ Mailboxes used to be called channels, everywhere, and the old names are not read from an empty store. Old conversations, and the inventory rows that listed old channels, are not carried over. -## Hiring at runtime, and reloading at boot - -`hireWorkforce` turns records into flow instances, whether those records came from files or from -somewhere else. To keep a runtime hire across restarts, store it and read it back. - -```ts -import { defineHiredRosterCollection, reloadHiredSeats } from "@flow-state-dev/workforce"; -``` - -`defineHiredRosterCollection()` is an org-scoped resource collection at `workforce/roster/*`, one -row per hired seat. Install it under the block that does the hiring, and write the row with -`create()` before you register the seat. `create()` throws when the key already exists, and that -throw is what refuses a second hire of the same seat, including two arriving at once — so you need -no lock and no check of your own. Reach for `upsert()` here and you lose the refusal without any -sign that you did. +## Hire, fork and fire as tools -If registration then fails, delete the row you just created before reporting the failure. A hire -that did not take should not leave a seat waiting at the next start. +A user's own workers are rows on their roster ([Workers as data](#workers-as-data)), written by the +roster flow's `hire`, `fork`, `edit` and `fire` actions, which `hireWorkforce` registers. Nothing +is registered per hire, nothing restarts, and nothing is read back at boot: every process reads the +row on the next turn. -The collection is readable by a browser, so a roster panel can name the seats without an action in -between. Because it is org-scoped, that read resolves against the reading session's own -organization. What crosses is `seatId`, `flow` and `instructions`. The settings bag stays -on the server. - -A row holds the seat's id within its organization, the flow kind, the settings bag and the -instructions. The envelope is this package's to version; the settings bag is handed back to the -kind untouched, including keys this version has never heard of, because that bag belongs to the -kind's own schema. - -`reloadHiredSeats` reads those rows back when the app starts: +To let a worker hire or fire for the person it talks to, hand the same blocks to a model as tools. +A catalog key is the tool's own name, so wrap each block in a sequencer that carries the name and +what the model reads about it, and put the pair in the worker flow's catalog: ```ts -const { seats, problems } = await reloadHiredSeats({ - stores, // the runtime's resolved stores - orgIds, // which organizations to reload; you decide the policy - workerFlows, // the same map you pass to hireWorkforce -}); - -for (const seat of seats) { - try { flowstate.register(seat, { pin: seat.ownerPin }); } - catch (err) { problems.push(`${seat.id} — ${String(err)}`); } -} -``` - -A reloaded seat is addressed `.`, so two organizations can both hold a seat called -`support.ada`. The organization id is percent-escaped in the address: lowercase letters, digits and -`-` stay, everything else is encoded, so `org_pentest_lab` becomes `org%5Fpentest%5Flab.`. Use `seatAddress` and `splitSeatAddress` instead of building -`${orgId}.` prefixes by hand. - -Register the seats yourself, one at a time, with each seat's `ownerPin`, and add any refusal to -`problems`. The other seats still start. - -You pass the organizations to reload; `reloadHiredSeats` does not discover them. - -`problems` is the part to handle rather than log, the same shape `openInventory` returns. A row naming a kind you no longer ship, or carrying a -setting that kind no longer accepts, comes back here with its reason instead of throwing. The other -seats still hire, the app still starts, and the row is left exactly as it was — nothing is repaired -or deleted on your behalf. - -`byOrg` is the same result split by organization: one `{ orgId, seats, problems }` per organization -you passed in, in that order, with empty lists where there was nothing to report. Use it when each -organization's report goes somewhere only that organization reads, and loop its `seats` rather than -the flat list so a registry refusal lands in the right organization's `problems`. - -A read the store will not complete rejects, and a set of organizations larger than the cap rejects -too, naming both numbers. The cap is `maxOrgs`, 100 by default; the read's own bound is `timeoutMs`, -10000ms by default, and it covers the whole set rather than each organization. Neither returns a -partial roster. - -The roster and the inventory are different collections. A roster row at -`workforce/roster/` is the durable hire: `hire` writes it, `fire` deletes it. An -inventory row at `inventory/seats/
` means *was registered in this organization*. A -declared seat's row is never removed; a runtime-hired seat's row is removed by `fire`, and only -while it carries the incarnation fired. - -`createSeatHireCapability`'s `hire` tool writes both. `discover` lists a seat when it is still -hired or still declared in a worker file, and has been registered in this organization. Pass -`hiredRoster` on `createWorkforceCapability` so a runtime hire is listed the same way a -file-declared seat is. A file-declared description wins over a same-id hire. After `fire`, a -hired seat's roster row and its inventory row are both gone, so `discover` does not list it. A -fire that stopped between the two leaves the inventory row; `discover` withholds the seat, since -no roster row backs it. - -### Hire and fire as catalog tools - -`createSeatHireCapability` puts `hire`, `fire`, `brokenSeats` and `rehire` on a worker kind's -catalog. Install it with `defineAgentWorkerFlow({ uses: [seatHire] })`. A seat with no `tools:` -line calls them by selecting the preset (`capabilities: { seat-hire: [tools] }`); a seat that -writes a `tools:` line names them there. An empty `tools:` list means the seat cannot call them. - -The seat is hired in the caller's organization. A body `orgId` is ignored. -Hire will not register a seat without an owner pin `{ orgId, userId? }` taken -from the hire row's roster owner — not from the address. - -```ts -import { - createSeatHireCapability, - createWorkforceCapability, - defineAgentWorkerFlow, - hireWorkforce, - HIRED_ROSTER_RESOURCE, - SEAT_INVENTORY_RESOURCE, - type HireOptions, -} from "@flow-state-dev/workforce"; -import type { FlowInstance } from "@flow-state-dev/core"; - -const workerFlows: NonNullable = {}; -const roster = { workers: [], mailboxes: [] }; -const held = new Map(); -const live = { - register: (seat: FlowInstance, _pin: { orgId: string; userId?: string }) => { - held.set(seat.id, seat); - }, - unregister: (id: string) => held.delete(id), - kindAt: (id: string) => held.get(id)?.kind, +import { sequencer } from "@flow-state-dev/core"; +import { createWorkerHireBlocks, defineAgentWorkerFlow } from "@flow-state-dev/workforce"; + +const { hire, fire } = createWorkerHireBlocks(installation); +const rosterTools = { + hire: sequencer({ name: "hire", description: "Hire a worker of the person's own.", inputSchema: hire.inputSchema, outputSchema: hire.outputSchema }).step(hire), + fire: sequencer({ name: "fire", description: "Fire one of the person's own workers.", inputSchema: fire.inputSchema, outputSchema: fire.outputSchema }) + .tap(askFire) // your own `human_approval` suspension, if a fire should wait for the person + .step(fire), }; -const seatHire = createSeatHireCapability({ - workerFlows, - register: live.register, - unregister: live.unregister, - kindAt: live.kindAt, -}); - -const workforce = createWorkforceCapability({ - roster, // or readDeclaredRoster(...)'s result - inventory: { seats: SEAT_INVENTORY_RESOURCE }, - hiredRoster: HIRED_ROSTER_RESOURCE, -}); - -workerFlows.agent = defineAgentWorkerFlow({ uses: [seatHire, workforce] }); - -const [manager] = hireWorkforce( - [{ id: "eng.manager", declared: { tools: ["hire", "fire"] }, body: "Expands the roster." }], - { workerFlows }, -); -``` - -Pass the same `workerFlows` object you pass to `hireWorkforce`. A kind you add on that object after -the factory runs is hireable. - -| Option | Role | -|--------|------| -| `workerFlows` | The same map `hireWorkforce` takes. Omit it and only built-in `agent` is hireable, unless `allowKinds` excludes it. Every seat these tools hire is a hired worker: it is visible to the whole organization and carries an owner pin. So a flow marked `standardOnly` refuses it, before anything is written. | -| `register(seat, pin)` | Admit the minted flow at its address. `pin` is `{ orgId, userId? }` from the hire row's roster owner. Hire refuses rather than omit it. | -| `unregister(id)` | Release the address in this process. Returns whether it was held. | -| `kindAt?(id)` | Kind serving an address right now. Hire uses it to refuse a second hire of a live seat, and a seat id a file-declared seat answers on. Fire uses it to refuse a file-declared seat. Omit it and a duplicate seat is still refused. | -| `allowKinds?` | Subset of `workerFlows` this tool may mint. | -| `refuseRosterAdmin?` | When `true`, `hire` and `rehire` refuse settings that would give the new seat the roster tools: `hire`, `fire`, `rehire` or `brokenSeats` in `tools:`, or the `seat-hire` capability under `capabilities:`. Default `false`. | -| `mailboxBoards?` | Ledger ids forwarded so an unattended board warns. Hire does not attach boards. | -| `askBefore?` | `"hire"` and/or `"fire"`: those tools wait for a person's approval before they change anything. `rehire` always waits. Omitted, `hire` and `fire` act at once. Any other entry throws when the capability is built. | - -**`hire`** takes `{ seatId, flow, settings?, instructions?, orgId? }` (extra keys are refused) -and returns `{ seatId, address, warning? }`. `address` is `.`. - -A successful hire leaves a roster row and an inventory row. A thrown `register` leaves neither. -A duplicate seat is refused. It does not invent a kind. It does not attach boards. `warning` -is present when a named mailbox board is unattended. - -It refuses an unknown kind or one outside `allowKinds` (and lists the hireable ones), an -address already served, a seat id a file-declared seat answers on, an address a declared -seat's inventory row sits at (`hired: false`), and a request with no organization. - -It also refuses when the kind's settings schema refuses the seat, before anything is written, with -`"
" was not hired, and nothing was written. Kind "" refused it: ` -and a last line, ``If that names a setting, call hire again with it in `settings`.`` A model calling -the tool gets this as the tool's result and can call again with the setting. - -**`fire`** takes `{ seatId, owner?, orgId? }` (extra keys are refused) and returns -`{ seatId, address, released, alreadyGone? }`. It deletes the roster row, unregisters the -address when the live kind matches the stored kind, and deletes the seat's inventory row. When -a different kind holds the address, the roster row is deleted, the address and its inventory -row are left alone, and `released` is `false`. Called for a seat whose roster row is already -gone but whose inventory row is left (a crash between the two deletes), it removes that row -when the row says `hired: true` and returns `released: false` with `alreadyGone: true`; a row -that doesn't say so is left, and the call refused as for a seat never hired. A roster row that can't be read is deleted by its key and nothing else is -touched (`address: null`). After `fire`, `discover` withholds the seat. `removeHiredSeat` is -this removal on its own, for an app whose fire is its own handler, and `resolveHiredSeatLocation({ seatId, owner?, roster, privateRoster?, userId?, leftoverAt })` picks the row it removes, as `fire` does. `leftoverAt` is required: a fire passes `{ orgId, inventory }` so that a retry after a fire that stopped past the caller's own row stays on that seat; a caller acting only on a row that exists passes `null`. - -It refuses when this organization hired no seat, or when a live file-declared seat sits at that -address (removed by editing its folder, not by firing it). - -**Asking first.** A tool `askBefore` lists runs every refusal above first, then suspends the -request with `reason: "human_approval"`, `data: { verb, seatId, kind, owner, incarnation }` and -`allow: ["approve", "reject"]`. `owner` is the member whose own seat it is (`null` for an -org-visible seat or a hire); `incarnation` names the hire that wrote the row (`null` for a hire). -Approve makes the change to that row only: if the seat id names another row by then (fired and -hired again), the change is refused with "changed while you were asked". Reject changes nothing -and the model gets `{ denied: true, reason }` as the tool result. A refusal raises no ask. -`askBefore` covers `hire` and `fire`; `rehire` always asks. Asking needs durable -execution (`durable: true` on `createFlowState`); without it a listed tool throws, naming -itself, and changes nothing. The ask survives a restart, and a request recovered after the -approval landed makes the change once on a store that keeps a run's items as it goes. - -**Pairing with `discover`.** Compose both capabilities on the kind and pass -`inventory: { seats: SEAT_INVENTORY_RESOURCE }` plus `hiredRoster: HIRED_ROSTER_RESOURCE`. -Pass both keys so `discover` lists a runtime hire the same way it lists a file-declared seat. -Omit `hiredRoster` and it lists only file-declared seats. - -### The same handlers, as actions - -`createSeatHireBlocks` takes the same options as `createSeatHireCapability` and returns -`{ hire, fire, brokenSeats, rehire }`. `hire` and `fire` are the handlers behind its catalog -tools. Mount them as a flow's actions when a person or your own code does the hiring and no -model should be in front of it. Inputs, outputs and refusals are the ones described above for -the tools. - -**`brokenSeats`** takes `{}` and returns the caller's organization's stored seats that would -not start, each `{ seatId, key, owner, kind, reason, detail }`, with `reason` one of `kind-gone`, -`refused`, `unreadable`. It reads through the start's own per-row check, so `detail` is the -sentence `reloadHiredSeats` puts in `problems`, and it writes nothing. For an `unreadable` row, -`seatId` is the row's key, which `fire` retires it by. `owner` is `"organization"` or `"me"`, -whose row it is; pass it to `fire` or `rehire` to reach that row. It runs the full check on every row, a -mint included, so it is an admin read made on demand, not something to poll. - -User-owned seats: mount `defineHiredRosterPrivateCollection()` under -`HIRED_ROSTER_PRIVATE_RESOURCE` on the same flow, and `brokenSeats` lists the caller's own -user-owned rows beside the org's. `fire` and `rehire` take `owner: "organization" | "me"` to -name which row; without it they act on the only row under the seat id, and refuse, naming both, -when the caller has an org row and a user-owned row under it. `resolveHiredSeatLocation` is that -choice, exported for an app's own fire. That collection serves a row only to the member it belongs to, so a -member lists and repairs only their own; the start still names every member's. Without it, the -four reach org-visible seats only. - -**`rehire`** takes `{ seatId, flow, settings?, instructions?, owner?, orgId? }` and returns -`{ seatId, address, warning? }`. It keeps the seat's id and address and runs it on `flow`, with -`settings` for that kind; the stored instructions carry over unless replaced. It refuses a seat -that would start, an `unreadable` row, a kind this app doesn't carry or `allowKinds` excludes, -and settings the kind refuses, all before writing anything. The row is replaced in one -version-checked write, so of two repairs of one seat arriving together one is refused. A failed -registration writes the old row back. If the process dies after the row is written, or the -inventory write fails after the seat is serving, the same call run again finishes it. The row -write marks the row `pendingRepair` until the seat is registered and published, and only a marked -row is finished. A seat the registry already holds at the address counts as registered only when -`instanceAt` shows it was minted from that row; any other holder is a refusal. Any -other re-hire of a working seat is refused. Each step re-reads the row first: if `fire` removed it -meanwhile, the re-hire stops and takes back what it registered or published. - -None of the four asks for approval. Mount `brokenSeats` and `rehire` behind one. - -Declare the roster and seat-inventory collections on that flow, under `HIRED_ROSTER_RESOURCE` -and `SEAT_INVENTORY_RESOURCE`. The handlers read them by those keys, and without them every -hire fails before anything is written. - -```ts -import { defineFlow } from "@flow-state-dev/core"; -import { - createSeatHireBlocks, - defineHiredRosterCollection, - defineSeatInventoryCollection, - HIRED_ROSTER_RESOURCE, - SEAT_INVENTORY_RESOURCE, -} from "@flow-state-dev/workforce"; - -// `workerFlows` and `live` as in the example above. -const hireActions = createSeatHireBlocks({ - workerFlows, - register: live.register, - unregister: live.unregister, - kindAt: live.kindAt, -}); - -const workforceAdmin = defineFlow({ - kind: "workforce-admin", - requireUser: true, - // Your AuthenticationConfig. Its resolvePrincipal must return an orgId. - authentication: adminAuthentication, - resources: { - [HIRED_ROSTER_RESOURCE]: defineHiredRosterCollection(), - [SEAT_INVENTORY_RESOURCE]: defineSeatInventoryCollection(), - }, - actions: { - hire: { block: hireActions.hire }, - fire: { block: hireActions.fire }, - }, -}); +const agent = defineAgentWorkerFlow({ installation, catalog: rosterTools }); ``` -The organization comes from the session's principal; an `orgId` in the input is ignored. A -session whose principal names no organization belongs to the default organization, and a hire -there lands under `%5F%5Ffsd%5Fdefault%5Forg%5F%5F.` and reloads at the next start like any -other. Configure a `resolvePrincipal` that returns an `orgId` on the flow that mounts these to hire -into a real organization. +A worker holds `hire` or `fire` only when its own `tools:` names them. Each write goes to the roster +of the person whose turn it is: a worker can't hire for anyone else. The blocks write at once; an +approval before a fire is yours to add as a step before it, as the chief of staff guide shows. ### Posting to a mailbox from a seat -`mailboxPostCapability` puts one tool, `post-to-mailbox`, on a worker kind's catalog. Install it -with `defineAgentWorkerFlow({ uses: [mailboxPostCapability] })`, and a seat names the tool in -`tools:` to use it. Its input is `{ mailbox, body }` and nothing else, so an `author` from the -model is refused. - -Outside a routed turn (below), the tool posts through the built-in mailbox kind with the seat's -`seatId` (its record id, as `members:` lists it) as `author`, so the mailbox's member check applies. -The line has `seatAuthored: true`, so `wakeMemberSeats` wakes nobody for it. A client `post` that -sets `author` to the same seat id wakes hearing members. `hireWorkforce` -writes `seatId` on every -seat it mints. A seat minted without one is refused, and the error names `seatId`. Every seat of -the built-in `agent` kind is refused when its flow is built, whether or not it names the tool. A -seat of any other kind carrying the capability is refused when a turn would offer the tool, before -the model is called. Either way it posts nothing. +`workerMailboxPostCapability` puts one tool, `post-to-mailbox`, on a worker flow's catalog. Install +it with `defineAgentWorkerFlow({ installation, uses: [workerMailboxPostCapability] })`, or in your +own worker flow's `uses`, and a worker names the tool in `tools:` to use it. Its input is +`{ mailbox, body }` and nothing else, so an `author` from the model is refused. + +Outside a routed turn (below), the tool posts through the built-in mailbox kind with the id of the +worker the turn loaded (as `members:` lists it) as `author`, so the mailbox's member check applies. +The worker comes from the session, never from the input or a setting. The line has +`seatAuthored: true`, so `wakeMemberSeats` wakes nobody for it. A client `post` that sets `author` +to the same worker id wakes hearing members. A turn that loaded no worker posts nothing. +`mailboxPostCapability` is the same tool for a flow copy minted for one worker, which signs with its +`seatId` setting. The tool returns once the post is handed to the mailbox, as `{ handedTo, note }`. A refusal by the mailbox, such as an author who is not a member, lands on the mailbox's request, not in the seat's @@ -1889,7 +1701,7 @@ when it registered. | Factory | One row per | Fields | |---------|-------------|--------| -| `defineSeatInventoryCollection()` | registered seat, at `inventory/seats/` | `id`, `kind` (the worker kind the seat was hired into), `door` (the action that takes a person's message, or `null`), `hired` (`true` for a seat hired at runtime, `false` for a declared one, `null` on a row written before the field), `incarnation` (the hire or repair that published it; `null` on a declared seat's row and an older row) | +| `defineSeatInventoryCollection()` | registered seat, at `inventory/seats/` | `id`, `kind` (the worker flow the standard worker runs on), `door` (the action that takes a person's message, or `null`), `hired` (`false`: only standard workers are listed), `incarnation` (`null`) | | `defineMailboxInventoryCollection()` | registered mailbox, at `inventory/mailboxes/` | `id`, `kind` (the mailbox kind that opened it), `members` (seat ids, `[]` when absent), `openedAt` (ISO string, or `null` when absent) | | `defineMembershipIndexCollection()` | seat-in-mailbox, at `inventory/members//` | `seatId`, `mailboxId` | @@ -1910,7 +1722,7 @@ import { openInventory, } from "@flow-state-dev/workforce"; -const seats = hireWorkforce(roster.workers); +const flows = hireWorkforce(createWorkerInstallation({ standardWorkers: roster.workers })); const instances = mailboxInstances(roster.mailboxes, { inventory: true }); flowRegistry.registerMany([...seats, ...instances]); @@ -1969,16 +1781,12 @@ the mailbox's session state, not the inventory; the row is a copy for finding th **Running it twice.** Every write is an upsert keyed by the record's id. Nothing duplicates, and a mailbox registered on an earlier boot keeps its original `openedAt`. A row stays where it is when a -later roster no longer names the seat or mailbox. Seat rows are the exception to the upsert: the -roster a boot read can be older than the store, so the boot creates a seat's row only where there was -none when it read the inventory, and otherwise replaces it only while the stored row is the same kind -of seat — a declared row for a declared seat, and for a hired seat a hired row carrying the same -incarnation. A runtime hire's row is never replaced by another hire's or a declared seat's, and a row -a fire removed after the boot read it is not written back. +later roster no longer names the seat or mailbox. The seats are the standard workers +(`inventorySeats(installation)`); a user's own workers are on their roster, never in the inventory. **What lands in `problems`.** `openInventory` returns `{ seats, mailboxes, problems }`. `seats` counts the seat rows that landed, as the seat action reports it when `run` returns the action's output (or a -run result carrying it as `output`); a row the boot left for a newer hire isn't counted. A mailbox +run result carrying it as `output`). A mailbox 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. @@ -2212,19 +2020,14 @@ restart. ## Workers as data -A worker can also be data rather than a registered copy: a row its owner holds in their user -scope, or a standard worker your files declare, run by one registered copy of the flow it names. -A session names its worker once, when it is created, and each turn loads it. This runs beside -`hireWorkforce`: nothing here mints a copy or sets a pin. +A worker is data rather than a registered copy: a row its owner holds in their user scope, or a +standard worker your files declare, run by one registered copy of the flow it names. A session +names its worker once, when it is created, and each turn loads it. Nothing mints a copy per worker +or sets a pin. ```ts import { defineFlow } from "@flow-state-dev/core"; -import { - createWorkerHireBlocks, - createWorkerInstallation, - defineWorkerRosterFlow, - workerConfigSchema, -} from "@flow-state-dev/workforce"; +import { createWorkerInstallation, hireWorkforce, workerConfigSchema } from "@flow-state-dev/workforce"; const installation = createWorkerInstallation({ standardWorkers: roster, // readWorkforce(...)'s workers @@ -2244,16 +2047,13 @@ const worker = await installation.resolveWorker(ctx, "research"); worker.config.instructions; // the worker's own, as the flow's configSchema parsed them worker.reaches("handbook"); // its document grants, applied on this turn -const { hire, fork, edit, fire } = createWorkerHireBlocks(installation); -const rosterFlow = defineWorkerRosterFlow(installation, { - hire: { inputSchema: hire.inputSchema, block: hire }, - fork: { inputSchema: fork.inputSchema, block: fork }, - edit: { inputSchema: edit.inputSchema, block: edit }, - fire: { inputSchema: fire.inputSchema, block: fire }, -}); +const flows = hireWorkforce(installation); // research, agent, and the roster flow ``` -Register `researchFlow()` and `rosterFlow()`. +Register every flow `hireWorkforce` returns: one copy of each worker flow, and the roster flow, +`workforce-roster`, which carries the `hire`, `fork`, `edit` and `fire` actions below. +`createWorkerHireBlocks(installation)` returns the same four as blocks, to mount elsewhere or hand +to a model as [tools](#hire-fork-and-fire-as-tools). - **Creating a session.** A session of a worker flow is created with `state: { workerId }`. The worker must be the creating user's own or a standard one. Asking for another user's worker @@ -2264,6 +2064,10 @@ Register `researchFlow()` and `rosterFlow()`. - **Each turn.** `resolveWorker(ctx, flowKind)` loads the session's worker and resolves its tools, skills and packages against what the installation registers. Read the worker's settings from `worker.config`: `ctx.flow.config` is the flow's own config, the same for every worker on it. + Load it in the flow's `request.onStarted`, or in the block that reads it. A request that waited + for a person runs again when the answer arrives, and a step that already finished isn't run + again: its recorded output is reused, so a worker loaded in an earlier step is gone on the + resumed run. The built-in `agent` loads it in `request.onStarted`. When the turn can't run, `resolveWorker` throws `WorkerTurnRefusedError` and nothing is written: - the worker was fired: its sessions stay readable; start a session with another worker; - the worker now runs on another flow: call `ensureWorkerSession` again, which starts a session @@ -2274,10 +2078,22 @@ Register `researchFlow()` and `rosterFlow()`. flow. - **A worker's own data.** Data a flow keeps per user is shared by all of that user's workers on the flow, and never reaches another user. Keeping one worker's data apart from the user's other - workers is the flow author's job: key a collection by the session's readonly `workerId`, or use a - skills library with `partitionBy` reading it + workers is the flow author's job: key a collection by the worker the turn loaded, or use a + skills library with `partitionBy` reading the session's readonly `workerId` ([Partitioning a library](../orchestration/README.md#partitioning-a-library)). The framework - neither refuses nor partitions it for you. + neither refuses nor partitions it for you. The built-in `agent` keeps each worker's skills apart. + + ```ts + // a user-scoped collection `worker-notes/*`, declared on the block beside `installation.resources` + const worker = await installation.resolveWorker(ctx, "research"); + await ctx.resources.workerNotes.upsert(worker.id, { text: "Prefers short answers." }); + ``` +- **What a worker's model reaches.** A worker flow declares every document any of its workers may be + granted (`...installation.documents`) and sets `resourceVisibility: installation.resourceVisibility`. + Each turn's model then reaches only the documents the turn's worker is granted, read-only where + its grant is, through core's resource tools and the `discover` door; every other document answers + as one that doesn't exist. A turn that loaded no worker reaches no document. Block code that names + a document directly is not narrowed. The built-in `agent` sets this for you. - **The roster.** Each worker the user hires or forks is a row at `workforce/workers/` in their user scope, one roster per organization. Every write is checked the way a turn would check it, and a standard worker's id is refused with a suggestion to fork it: @@ -2310,6 +2126,10 @@ Register `researchFlow()` and `rosterFlow()`. }); ``` + In React, build the client once with `useMemo` over the same options. `useFlow` creates sessions + with no starting state, which a worker flow refuses, so find or start the session with the client + and select it on the hook (`flow.selectSession(session.id)`). + `ensureWorkerSession` returns the user's most recent session with the worker, or creates one. Two calls at once get the same session. `findWorkerSession` takes the same argument and returns the session or `undefined`, creating nothing. The roster flow keeps one session per user, of the @@ -2327,42 +2147,28 @@ drop. A client component imports the few names a panel reads with from the `./br "use client"; import { MAILBOX_POST_COMPONENT, - HIRED_ROSTER_RESOURCE, - splitSeatAddress, + createWorkforceClient, type MailboxTranscriptLine, } from "@flow-state-dev/workforce/browser"; ``` -It also exports `createWorkforceClient`, `deriveWorkerSessionId`, `isDerivedWorkerSessionId`, -`ROSTER_FLOW_KIND` and `WORKER_ID_STATE_KEY`. - -It exports `HIRED_ROSTER_RESOURCE`, `SEAT_INVENTORY_RESOURCE`, `HIRED_ROSTER_BROWSER_PATTERN`, `splitSeatAddress`, -`MAILBOX_POST_COMPONENT`, `mailboxTranscriptLineSchema` and `MailboxTranscriptLine`, the same values -the root exports, and reaches no Node built-in. It also exports `listedSeatRows(orgId, rows, roster, owned?)`, -the team-list rule: of the seat inventory rows, a hired seat's is kept only while a roster row -names its address (pass `undefined` when the roster didn't load, and no hired seat is kept), and -every other row is kept as it is. A row says which it is in `hired`; one written before that field -is read by its id's shape, which `isHiredSeatRow(orgId, row)` also answers. A hired row is kept only when the roster -row at its address carries the same `incarnation`; rows from before incarnations match only each -other (`null` on both sides). The org roster publishes `incarnation` to browsers for this. A -user-owned hire's row (`.~.`) is kept only when `owned`, the reader's own -user-owned roster rows read on the server, has a row at that address with the same `incarnation`. The roster that would back -it is owner-private, so a browser reader has no `owned` and keeps no user-owned hire. An -`incarnation` on the inventory row says which hire published it, not that the hire is still there. A hired seat fired -before fire removed inventory rows is left out that way. +It exports `createWorkforceClient`, `deriveWorkerSessionId`, `isDerivedWorkerSessionId`, +`ROSTER_FLOW_KIND`, `WORKER_ID_STATE_KEY`, `MAILBOX_POST_COMPONENT`, `mailboxTranscriptLineSchema` +and `MailboxTranscriptLine`, the same values the root exports, and reaches no Node built-in. ## Exports | Export | Description | |--------|-------------| -| `defineAgentWorkerFlow(options?)` | Build the flow behind the `agent` worker kind — `agent` is one kind of worker, and this is the flow it resolves to. Called with no arguments it *is* the built-in a record with no `flow:` is hired into; called with factory options (`AgentWorkerFlowOptions`) it is the replacement you register under `agent`. Its flow declares `run` (public) and `onMailboxPost` (internal, for a mailbox's notify block), and with `taskLists` a `work` task entry. | +| `defineAgentWorkerFlow(options?)` | Build the flow behind the `agent` worker kind — `agent` is one kind of worker, and this is the flow it resolves to. With `installation` it is the copy every worker on `agent` shares: it declares the installation's session and documents, loads the turn's worker in `request.onStarted`, and refuses a turn whose input names a worker; called with factory options (`AgentWorkerFlowOptions`) it is the replacement you register under `agent`. Its flow declares `run` (public) and `onMailboxPost` (internal, for a mailbox's notify block), and with `taskLists` a `work` task entry. | | `AGENT_KIND` | The kind name (`"agent"`) the hire step defaults to, and the key a replacement registers under. | | `definePersona(config)` | Declare a persona resource or collection. | -| `createWorkforceCapability({ roster, inventory, hiredRoster?, sources? })` | The discovery door. Installs the seat and mailbox sources plus whatever other domains' sources you pass, and contributes one control tool, `discover`. Pass `hiredRoster` so a runtime hire is listed the same way a file-declared seat is. Omit it and `discover` lists only file-declared seats. | -| `workforceManifestSources({ roster, inventory, hiredRoster? })` | The seat and mailbox sources on their own, for an app assembling its own manifest registry. Same `hiredRoster?` meaning as `createWorkforceCapability`. | -| `createSeatHireCapability({ workerFlows, register, unregister, kindAt?, instanceAt?, allowKinds?, refuseRosterAdmin?, mailboxBoards?, askBefore? })` | Puts catalog tools `hire`, `fire`, `brokenSeats` and `rehire` on a worker kind; `askBefore` puts `hire` and/or `fire` behind a person's approval, and `rehire` is always behind one. Compose it into `defineAgentWorkerFlow({ uses })`. A seat calls them by selecting `seat-hire: [tools]` with no `tools:` line, or by naming them in `tools:`; `tools: []` withholds them. Writes the hired roster and `inventory/seats/*`. The seat is hired in the caller's organization; a body `orgId` is ignored. The roster row carries that organization as `owningOrgId`, so a copy read under another organization is a reload problem rather than a seat. `register` receives `{ orgId, userId? }` from the hire row's roster owner; hire refuses rather than omit it. | -| `createSeatHireBlocks({ workerFlows, register, unregister, kindAt?, instanceAt?, allowKinds?, refuseRosterAdmin?, mailboxBoards? })` | Returns `{ hire, fire, brokenSeats, rehire }`; `hire` and `fire` are the handlers behind `createSeatHireCapability`'s catalog tools, for mounting as a flow's actions, where they never ask for approval. Same options, inputs, outputs and refusals. Declare `defineHiredRosterCollection()` under `HIRED_ROSTER_RESOURCE` and `defineSeatInventoryCollection()` under `SEAT_INVENTORY_RESOURCE` on that flow. The organization comes from the session's principal; a body `orgId` is ignored, and with no resolver in play the session is in the default organization, so the hire lands there. Each hire and re-hire stamps a fresh `incarnation` on its roster row, its inventory row and the seat it mints; `fire` deletes only that incarnation's inventory row and, given `instanceAt` (the registry's instance at an address), releases only the seat minted from the row. Without `instanceAt` those checks fall back to the kind, and a `rehire` retry that finds the address already served is refused. `refuseRosterAdmin: true` refuses a hire or re-hire whose settings would give the seat the roster tools; off by default. | +| `createWorkforceCapability({ roster, inventory, sources? })` | The discovery door. Installs the seat and mailbox sources plus whatever other domains' sources you pass, and contributes one control tool, `discover`, which lists the standard workers the files declare and the mailboxes. | +| `workforceManifestSources({ roster, inventory })` | The seat and mailbox sources on their own, for an app assembling its own manifest registry. | | `createWorkerInstallation({ standardWorkers?, workerFlows?, seatBlocks?, packageBlocks?, documents?, references?, skills?, packages? })` | The worker model's one module (see [Workers as data](#workers-as-data)). Returns `resources` and `session()` for a worker flow to spread in, the `createCheck` that names a session's worker at create, `resolveWorker(ctx, flowKind)` for each turn, `standardWorker(id)`, `workerFlows()` and `configurationProblems(id, row)`. `workerFlows` may be a function, read when first needed. | +| `workerFlow(build, { standardOnly? })` | A worker flow built on its installation, for a flow in its own file: the installation calls `build(installation)` once. Goes in `workerFlows`, and is what `fsdev gen`'s `kinds` holds. | +| `inventorySeats(installation)` | The standard workers as `openInventory` takes seats: each worker's id, its flow and that flow's actions. | +| `workerConfigOf(ctx)` | The configuration of the worker the turn loaded, synchronously, for a prompt, a tool list or a step condition. Throws when the turn loaded no worker: call `installation.resolveWorker` in the flow's `request.onStarted`. | | `createWorkerHireBlocks(installation)` | `{ hire, fork, edit, fire }`: writes to the caller's own roster, each checked as a turn would check it before anything is written, each refusing a standard worker's id. | | `defineWorkerRosterFlow(installation, actions?)` | The roster flow (`workforce-roster`), which declares the two worker collections so a client reads a user's roster through one session of it. Mount the hire blocks on it as actions. | | `createWorkforceClient({ userId, baseUrl?, apiPath?, fetcher? })` | `roster()`, `findWorkerSession({ worker })` and `ensureWorkerSession({ worker })`, over the session and resource clients. From `./browser` only. | @@ -2370,12 +2176,7 @@ before fire removed inventory rows is left out that way. | `WorkerTurnRefusedError` | What `resolveWorker` throws when a turn can't run as the session's worker; nothing is written. | | `defineWorkerCollection()` / `workerRowSchema` / `parseWorkerRow(value)` | The user's worker collection at `workforce/workers/*`, user scope, and its row. | | `WORKER_ID_STATE_KEY`, `WORKERS_RESOURCE`, `STANDARD_WORKERS_RESOURCE`, `ROSTER_FLOW_KIND` | The readonly session-state field naming a session's worker (`"workerId"`), the accessors the two worker collections are declared under, and the roster flow's kind. | -| `registerHiredSeat(register, seat, pin)` | The hire writer's register path. Refuses when `pin` has no `orgId`. The pin is the hire row's roster owner, not the address. | | `HiredSeatOwnerPin` | Another name for core's `InstanceOwnerPin`: `{ orgId, userId? }`, with `userId` present only for a user-owned hire row. Either name works wherever the other is expected. | -| `SEAT_HIRE_CAPABILITY` | The capability name, `"seat-hire"`. | -| `HIRED_ROSTER_RESOURCE` | Registry key the seat-hire capability installs the hired roster under, `"hiredRoster"`. Pass it as `hiredRoster` on `createWorkforceCapability` so `discover` reads the same collection. | -| `SEAT_INVENTORY_RESOURCE` | Registry key the seat-hire capability installs the seat inventory under, `"seatInventory"`. Pass it as `inventory.seats` on `createWorkforceCapability`. | -| `HIRED_ROSTER_PRIVATE_RESOURCE` | Registry key, `"hiredRosterPrivate"`, a flow mounts `defineHiredRosterPrivateCollection()` under so `createSeatHireBlocks`' `fire`, `brokenSeats` and `rehire` reach the caller's own user-owned seats. The capability does not install it. | | `SEAT_DISCOVER_KEY` | The pinned worker-file key, `"discover"` — the domains one seat sees, out of what its scope carries. Narrows only: a seat can never reach a domain the app did not install. | | `readDeclaredRoster(root)` | Read the whole tree in one call — workers with their skills and packages in reach, teams, documents and mailboxes — plus one list of everything that failed to load, each entry tagged with the layer that reported it. Collects rather than throws, so the boot policy stays yours. Ships from the `./loader` subpath (Node only). | | `readWorkforce(root)` | Read the tree into worker records that already carry their own skills and the packages in their reach — `readWorkforceDirectory` joined with `readSeatSkills` per seat and `readPackagesDirectory`. Returns `{ workers, errors, skillErrors, teams, teamErrors, packageErrors }`. Reach for it when seats are all you need. Ships from the `./loader` subpath (Node only). | @@ -2392,8 +2193,8 @@ before fire removed inventory rows is left out that way. | `describePreRenameMarks(marks)` | The marks above as one clause for a boot message ("written before … : mailbox "…" (…)"). The host adds what to do about it. | | `PRE_RENAME_NAMES` | The names the rename retired, frozen: record file and folder, kinds folder, kind, item components, inventory prefix and discovery domain. For recognising old data and seeding tests, never for reading it. | | `renderWorkforceCode(files, modules, seatBlocks?, packageBlocks?)` | Render a discovery's `files`, `resourceModules`, `seatBlocks` and `packageBlocks` as a module of static imports exporting `kinds`, `mailboxKinds`, `blocks`, `resourceModules`, `seatBlocks` and `packageBlocks`. Pass all four: the last two default to `[]`, so omitting one renders an empty map and reports nothing. Deterministic: the same tree renders the same bytes. `fsdev gen` is a thin command over this and the call above. Ships from the `./codegen` subpath. | -| `hireWorkforce(manifests, { workerFlows, seatBlocks, packageBlocks, mailboxBoards, documents, references })` | Turn worker records into one configured flow copy each, ordered by id. Pass `defineFlow(...)` results directly as `workerFlows`, each a flow or `{ flow, standardOnly: true }` for a flow kept for declared workers (a hired worker, one carrying an owner pin: hired at runtime or reloaded from the roster, org-visible or private, is refused on it; a worker naming no flow is checked as an `agent` worker). Every worker flow, the built-in `agent` with them, is checked against the [worker contract](https://flow-state.dev/docs/workforce/workers-on-disk#which-flows-can-run-workers) before any worker is hired, and one problem refuses the whole call. Pass `workforce.gen.ts`'s `seatBlocks` and `packageBlocks` exports under the same names, and, when any seat file declares `resources:`, the map `resourcesFromDocs` returns as `documents`. Pass the map `referencesFromDocs` returns as `references` whenever a kind installs any: it is what marks those entries as references, which references each seat reaches is worked out against it, and a kind holding references it was not given refuses the whole roster. `mailboxBoards` is optional and advisory: give it the roster's minted board ids and unattended boards are warned about on stderr. | -| `mergeSeatFlows(flows, seats)` | Add the hired seats to your app's flows record under their ids, for `createFlowState({ flows })`. Throws, naming the id, when a seat's id is already one of `flows`' keys (an org seat's id is its bare folder name, so a folder named `mailbox` would otherwise replace the mailbox flow) or when two seats share an id. Returns a new record; `flows` is not changed. | +| `hireWorkforce(installation, { mailboxBoards? })` | The flows to register for an installation: one copy of each worker flow, at its kind, and the roster flow (`workforce-roster`) with `hire`, `fork`, `edit` and `fire`. Throws, naming every problem, when a worker flow misses the contract or doesn't declare the installation's session, or when a standard worker would be refused on its first turn; nothing is registered. With `mailboxBoards`, warns once per process for a board no registered flow declares. | +| `mergeSeatFlows(flows, seats)` | Add the flows `hireWorkforce` returned to your app's flows record under their ids, for `createFlowState({ flows })`. Throws, naming the id, when one is already in `flows`. | | `unattendedBoardWarnings(boardIds, seats)` | The unattended-board warning strings `hireWorkforce` prints. The `hire` tool puts the same sentences on `warning` when a named board has no seat that declares it. | | `workerFlowProblems(name, flow)` | Every way `flow`, registered as `name`, misses the worker contract: a name that is not its `kind`, a configuration it refuses by key or by value, or takes but rewrites, no door or two, a resource with `writtenBy` that `sharedResource()` didn't build. An empty list for a worker flow. The check `hireWorkforce` runs, exported for a library's own tests. | | `sharedResource(pattern, shape)` | An org-scoped collection whose every entry carries a required `writtenBy: { userId, workerId? }` beside the fields of `shape`. An entry written without it is refused by the resource's own schema. The only way to declare a resource with `writtenBy` on a worker flow: the contract refuses one defined by hand, or a copy of this one with its schema replaced. | @@ -2417,7 +2218,7 @@ before fire removed inventory rows is left out that way. | `ResourceModuleExport` / `WorkerResourceModuleExport` | What a module in the organisation's or a team's `resources/` folder may be — a capability or a resource — and the narrower type a worker's own folder is held to: a resource, never a capability. | | `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. | | `defineMailboxFlow(options?)` | Build a mailbox kind. `options.notify` is the per-member fan-out block. `options.route` is the route from `routeByPurpose`. `options.checkAssignee(assignee, listId, ctx)` runs before `fileTask` files a row naming an assignee: return `undefined` to file it, or the sentence to refuse with (`unknown-assignee`). Pass `createWorkerLookup(...).filingCheck(aliases)`. | -| `wakeMemberSeats(seats, options?)` | The notify block for `defineMailboxFlow({ notify })`. Wakes each member whose hired seat declares `onMailboxPost`, once per post, and never on a seat's line (`seatAuthored: true`). A client `post` wakes hearing members whether or not it sets `author`. `options.fallback` runs for members whose seat can't hear a post, including on a seat's line. | +| `wakeMemberSeats(flows, { installation?, fallback? })` | The notify block for `defineMailboxFlow({ notify })`. Wakes each member that names a standard worker on a flow declaring `onMailboxPost`, once per post, in that worker's own conversation per mailbox, and never on a worker's line. | | `routeByPurpose(seats, { model })` | The route a mailbox kind takes as `defineMailboxFlow({ route })`. For a mailbox that declares `routing:`, each client `post` goes to one member: the member the last client `post` was routed to, until it answers (a held post holds nothing), else one evaluator call's pick among the members with a description (block name `mailbox-route`), else the declared fallback. A seat's line (`seatAuthored: true`) is not routed. A member of the built-in `agent` kind answers with the mailbox's last 20 lines in view, and its reply is posted into the mailbox as its line, once per post. Needs in-process dispatch or queue workers that share a lease backend. Throws without a `model`. | | `mailboxRouteRecordSchema` / `MailboxRouteRecord` / `MAILBOX_ROUTE_COMPONENT` / `MAILBOX_ROUTE_EVALUATOR` | One route decision as it is kept on the mailbox's session (`{ postId, by, member?, reason? }`, where `by` is `held`, `evaluated`, `fallback` or `failed`), the component name it is kept under, and the route evaluator's block name. Both names are `"mailbox-route"`. | | `MailboxRoute` / `MailboxRouting` | What `routeByPurpose` returns, and a mailbox file's `routing:` as read (`{ fallback }`). | @@ -2434,7 +2235,7 @@ before fire removed inventory rows is left out that way. | `mailboxBoardTaskTools(board)` | Capability granting a seat all eight task tools over one mailbox board, board-qualified by name. List it in the seat kind's `uses`; it declares the ledger too. | | `mailboxBoardIds(manifests)` | Every minted id across a roster, sorted and deduped — what `hireWorkforce`'s `mailboxBoards` and `defineAgentWorkerFlow`'s `taskLists` take. | | `mailboxTaskLists(boardIds, { allowSessionState? })` | A `TaskBinding` for a task entry's `from`: the entry takes tasks from any of these mailbox boards, resolved in the running organization. A board id outside the list is refused `UnknownTaskLedgerError`. | -| `createWorkerLookup({ instanceAt, declared })` | Which worker a task's name means. Returns `{ find, flowKind, filingCheck }`; see [Handing a row to the worker it names](#handing-a-row-to-the-worker-it-names). Types `WorkerLookup`, `WorkerLookupAnswer`, `WorkerLookupOptions`. | +| `createWorkerLookup({ installation })` | Which standard worker a task's name means. Returns `{ find, flowKind, state, filingCheck }`; see [Handing a row to the worker it names](#handing-a-row-to-the-worker-it-names). | | `WORKER_TASK_ENTRY` | `"work"`, the task entry a worker kind takes tasks through. | | `MailboxBoardCollection` | A `DefinedTaskCollection` carrying its minted `id`. | | `mailboxBoardRowSchema` | One row as `readBoard` publishes it: the board's facts and the `run` working the task, without the claim's coordinates (`claimedBy`, the lease) or write provenance. | @@ -2443,20 +2244,6 @@ before fire removed inventory rows is left out that way. | `mailboxPostInputSchema` / `mailboxReadOutputSchema` / `mailboxNotifyInputSchema` | The post, read and notify contracts. | | `mailboxSessionStateSchema` / `mailboxTranscriptLineSchema` | A mailbox session's state, and one transcript line. On a kind built with a route, a mailbox's state also carries `mailboxRouteLedger`, which this schema does not describe. | | `MAILBOX_POST_COMPONENT` / `emitMailboxPostLine(ctx, line)` / `readMailboxPostLines(ctx, schema)` | The component name a post's line is kept under; keep a line as that item, resolving once it is stored and rejecting if the write fails; read the posted lines in the history window back, parsed by the kind's own line schema. For a mailbox kind of your own. | -| `defineHiredRosterCollection()` | The hired roster's browser collection: one org-scoped row per org-visible seat, at `workforce/roster/`. One segment, so a user-owned row is not listed. Takes no options. Write org-visible rows with `create()` — its already-exists throw is what refuses a duplicate hire, and `upsert()` loses that refusal silently. | -| `defineHiredRosterPrivateCollection()` | The server-side writer for a user-owned row, at `workforce/roster/~/`. No browser read. It is an owner-private collection (`ownerPrivate: { param: "owner" }`): a row is served only to the member it belongs to, and any other collection whose pattern can reach those rows is refused at startup. Declare `workforce/roster/*` for the org roster. | -| `hiredSeatRowSchema` / `HiredSeatRow` | One roster row — `{ seatId, flow, settings, instructions, owningOrgId, ownerUserId, pendingRepair, incarnation }`. `owningOrgId`, `ownerUserId`, `pendingRepair` (set only while a `rehire` is unfinished) and `incarnation` (the hire or re-hire that wrote it) are nullable and default to `null`. `pendingRepair` is server-only; `incarnation` is published to browsers by `defineHiredRosterCollection`, beside `seatId`, `flow` and `instructions`, so a browser can join a roster row to its inventory row. The envelope is closed when parsed; the roster collections store it with unknown keys kept, so a key a newer version wrote survives this version's rewrite of the row (a re-hire). `settings` is a passthrough bag belonging to the kind's own schema. | -| `HIRED_ROSTER_PREFIX` | The roster's storage prefix, `"workforce/roster/"`. Moving it strands every roster already written. | -| `HIRED_ROSTER_BROWSER_PATTERN` / `HIRED_ROSTER_PRIVATE_PATTERN` | The two roster collections' patterns, `"workforce/roster/*"` and `"workforce/roster/[owner]/[seat]"`. Like the prefix, they spell stored keys. | -| `seatAddress(orgId, seatId, ownerUserId?)` / `splitSeatAddress(orgId, address)` | Join an organization and a seat id into the address a hired seat answers on, and take the seat id back out. Org-visible is `.`. User-owned is `.~.`, with the user escaped. The organization is percent-escaped like the user (`seatAddress("org_pentest_lab", "helper")` is `org%5Fpentest%5Flab.helper`). The pin is the hire row, not the address. `seatAddress` throws when the organization id is empty, whitespace-only, or not well-formed Unicode (a lone UTF-16 surrogate), or when the seat id is empty or starts with `~`. `splitSeatAddress` returns `undefined` when the address isn't under that organization. Both are also exported from `@flow-state-dev/workforce/browser`. | -| `newIncarnation()` / `tagIncarnation(seat, incarnation)` | For a host that writes roster rows itself rather than through `createSeatHireCapability`. Stamp each hire's row with `toHiredSeatRow({ ..., incarnation: newIncarnation() })` and tag the seat minted from it with the same id. A fire then removes only the inventory row carrying that id, so a replacement hired at the same address keeps its own. A row written with no incarnation can't be told from a replacement written the same way. | -| `toHiredSeatRow(input)` / `parseHiredSeatRow(value)` | Build a row from what a hire supplied, and read a stored value back into one. `parseHiredSeatRow` returns `{ row }` or `{ problem }` — it never throws and never rewrites the stored value. | -| `hiredRosterStorageKey(row)` | `seatId` for an org-visible row, `~/` for a user-owned one. The user id is escaped, so a `/` in it stays one segment. | -| `hiredSeatManifest(orgId, row)` / `hiredSeatRowFromManifest(orgId, manifest)` | Turn a row into the record `hireWorkforce` mints from, and back. Each returns `{ ... }` or `{ problem }`. A row whose `owningOrgId` disagrees with `orgId` is a problem and is not minted. A legacy row (`owningOrgId` null) binds `orgId`. The manifest's `ownerPin` is `{ orgId, userId? }`. | -| `hiredSeatOwnerPin(orgId, row)` / `hiredSeatOwnerPinFromRosterOwner({ orgId, userId? })` | The pin a hired seat registers under, built from a stored row, or from an owner `{ orgId, userId? }` you already hold. An org-visible row (`ownerUserId` null) gets `{ orgId }`, and a user-owned row gets `{ orgId, userId }`. `userId` is kept only when it is a non-empty string. The organization comes from `orgId`; the row's `owningOrgId` is not checked, so validate the row first (for example with `hiredSeatManifest`). Throws when `orgId` is missing or empty. | -| `registerHiredSeat(register, seat, pin)` | The hire writer's register. Calls `register(seat, pin)` only when `pin.orgId` is present. Omitting the pin throws, and `register` is not called. Wrap the engine door as `(seat, pin) => state.register(seat, { pin })`. App and kind flows do not use this. | -| `reloadHiredSeats(options)` | Read each organization's stored roster at boot and hire what it names. Takes `{ stores, orgIds, workerFlows?, maxOrgs?, timeoutMs? }` and returns `{ seats, problems, byOrg }`, where `byOrg` is one `{ orgId, seats, problems }` per organization passed in, in that order, empty ones included. **It registers nothing** — loop the seats and `register(seat, { pin: seat.ownerPin })` one at a time, folding refusals into `problems`. Rejects (loading nothing) past the org cap (`maxOrgs`, default 100) or when the whole read does not complete in its bound (`timeoutMs`, default 10000). | -| `DEFAULT_MAX_RELOAD_ORGS` / `DEFAULT_ROSTER_READ_TIMEOUT_MS` | The two bounds' defaults: 100 organizations, and 10000 ms for the whole read. | | `HiredRosterReload` / `HiredRosterOrgReload` / `HiredRosterStores` / `ReloadHiredSeatsOptions` / `RowProblem` | What the reload returns, one organization's share of it, the slice of the runtime's stores it reads through, its options, and the `{ problem }` shape a row that could not be read comes back as. | | `defineSeatInventoryCollection()` | The seat inventory: one org-scoped row per registered seat, at `inventory/seats/`. Takes no options; install what it returns under a block's `resources`. | | `defineMailboxInventoryCollection()` | The mailbox inventory: one org-scoped row per registered mailbox, at `inventory/mailboxes/`, carrying the mailbox's `members` and `openedAt`. Takes no options. | @@ -2493,8 +2280,10 @@ before fire removed inventory rows is left out that way. | Symlinked `skills/` folder at a level | Collected in `readSeatSkills`'s `errors` as `kind: "refused-symlinked-level"`, keyed by the level's path — never followed | | One skill name at more than one of a seat's levels | Collected in `readSeatSkills`'s `errors` as `kind: "duplicate-skill-name"`, keyed by the level the name was first seen at, with every colliding path on the entry's `paths`; the name is left out of `skills` | | `scope:` in a `SKILL.md` | Collected in `readSeatSkills`'s `errors` as `kind: "refused-scope-key"`, keyed by the skill's path | -| Worker flow misses the contract | `hireWorkforce`, before any worker — a flow passed under a key that is not its own kind, a configuration it refuses by key or by value, or takes but rewrites (composing `workerConfigSchema()` is the fix), no door or two, or a resource with `writtenBy` that `sharedResource()` didn't build. Collected: one error names every problem with every flow, and nothing is hired | -| Worker cannot be hired | `hireWorkforce` — an empty or whitespace-only `flow`, an unknown kind, a hired worker (one carrying an owner pin) naming a flow marked `standardOnly` (or naming none, when `agent` is marked), a duplicate id, a setting or body the flow never declared, a `tools:` name nothing registers for that seat, a registered block whose key and own `name` disagree, a block in a worker's own folder that declares a resource, a skill name reaching one seat from both the app's `skills` and its own folders, a `resources:` list the hire step cannot resolve (a `resources:` that is not a list, an entry that is neither a ref nor a one-key `ref: mode` mapping, a ref no document matches, a ref naming a document the app declared but did not install on this seat's kind, a mode other than `ro` or `rw`, the same ref twice, `rw` on a document declaring itself `writable: false`, a ref colliding with a name the kind's own blocks declare, a ref the kind declares at flow level while what it holds there is not that document, or the key itself with no `documents` passed), a document a seat did not name that its minted flow reaches anyway because one of the kind's blocks declares it, a `references:` list the hire step cannot resolve (a `references:` that is not a list, an entry that is not a ref, the same ref twice, or a ref naming a reference this seat cannot reach from its place in the tree — including every ref when no `references` map was passed), a seat id that names no place in the tree while its kind holds references, a reference the seat did not name that its minted flow reaches anyway, `instructions` given both in the frontmatter and as a body, a `packages:` list the hire step cannot resolve (not a list of names, a name no library in reach offers, or a name both its own folder and a library offer), a held package's block that clashes with another tool the seat can call, registers under a name other than its own, or declares a store, a package with blocks in its own folder that failed to load, or a `persona:`, `seatSkills:`, `seatTools:`, `seatPackages:`, `seatId:` or `teamInstructions:` key. Collected: one error names every bad worker | +| Worker flow misses the contract | `hireWorkforce`, before anything is registered — a flow passed under a key that is not its own kind, a configuration it refuses by key or by value, or takes but rewrites (composing `workerConfigSchema()` is the fix), no door or two, no installation session, or a resource with `writtenBy` that `sharedResource()` didn't build. Collected: one error names every problem with every flow, and nothing is hired | +| Worker cannot run | For a standard worker, `hireWorkforce`; for a user's own worker, the `hire`, `fork` or `edit` that saves it, and its turn — an empty or whitespace-only `flow`, an unknown flow, a user's own worker naming a flow marked `standardOnly` (or naming none, when `agent` is marked), a duplicate standard id (`createWorkerInstallation`), a setting or body the flow never declared, a `tools:` name nothing registers for that seat, a registered block whose key and own `name` disagree, a block in a worker's own folder that declares a resource, a skill name reaching one seat from both the app's `skills` and its own folders, a `resources:` list the hire step cannot resolve (a `resources:` that is not a list, an entry that is neither a ref nor a one-key `ref: mode` mapping, a ref no document matches, a ref naming a document the app declared but did not install on this worker's flow, a mode other than `ro` or `rw`, the same ref twice, `rw` on a document declaring itself `writable: false`, a ref colliding with a name the kind's own blocks declare, a ref the kind declares at flow level while what it holds there is not that document, or the key itself with no `documents` passed), a document a seat did not name that its minted flow reaches anyway because one of the kind's blocks declares it, a `references:` list the hire step cannot resolve (a `references:` that is not a list, an entry that is not a ref, the same ref twice, or a ref naming a reference this seat cannot reach from its place in the tree — including every ref when no `references` map was passed), a seat id that names no place in the tree while its kind holds references, a reference the seat did not name that its minted flow reaches anyway, `instructions` given both in the frontmatter and as a body, a `packages:` list the hire step cannot resolve (not a list of names, a name no library in reach offers, or a name both its own folder and a library offer), a held package's block that clashes with another tool the seat can call, registers under a name other than its own, or declares a store, a package with blocks in its own folder that failed to load, or a `persona:`, `seatSkills:`, `seatTools:`, `seatPackages:`, `seatId:` or `teamInstructions:` key. Collected: one error names every bad worker | +| A roster write refused | The `hire`, `fork`, `edit` or `fire` block: a standard worker's id (suggesting a fork), an id already on the caller's roster, a worker that isn't the caller's, a flow that isn't a worker flow or is kept for standard workers, or a configuration its flow refuses. Nothing is written. | +| A turn on a session whose worker can't run | `resolveWorker` throws `WorkerTurnRefusedError`, naming the worker: fired, moved to another flow, a name that no longer resolves, or a flow now kept for standard workers. Nothing is written; the session stays readable. | | Package folder fails to load | Collected in `readPackagesDirectory`'s and `readWorkforce`'s `packageErrors` as `kind: "package-load-failed"` (a symlinked or badly named folder, or a missing, unreadable or malformed `PACKAGE.md`), `"refused-entry"` (a file in `packages/`, or a documents, skills or packages folder or a symlink inside a package), or `"unreadable-slot"`, keyed by the path. The package is left out whole | | Package block clashes with a preset tool built per turn | That turn fails with a "two tools named" error | | A `resources/` slot, `org/`, `teams/`, a team folder, a `workers/` level or a worker folder unreadable or symlinked | Collected in `readResourcesDirectory`'s `errors` as `kind: "unreadable-slot"`, keyed by that folder's path — an absent folder is empty instead | @@ -2507,7 +2296,7 @@ before fire removed inventory rows is left out that way. | `writable`, `llmWritable`, `render` or `flowIsolation` in a reference file | Collected in `readReferencesDirectory`'s `errors` as `kind: "refused-declaration"`, keyed by the file's path — at either value | | One basename claimed by a `references/` and a `resources/` file at one level | Collected in `readDeclaredRoster`'s `problems` on the `reference` layer, naming both files. Neither single-folder reader sees it | | Reference cannot become a resource | `referencesFromDocs` throws naming the ref — a setting the convention derives, a lazy `prefetchMode`, a record with no `filePath`, or frontmatter `defineResource` itself rejects | -| One ref passed to `hireWorkforce` as both a document and a reference | `hireWorkforce` throws before hiring anything, naming every ref in both maps | +| One ref passed to `createWorkerInstallation` as both a document and a reference | Refused before anything is registered, naming every ref in both maps | | A reference row cannot be addressed | `clearShadowedReferences` throws when the org id — or, for a flow that isolates its org scope, the flow id — contains `:` or a backslash | | A `mailboxes/` slot, `teams/` or a team folder unreadable or symlinked | Collected in `readMailboxesDirectory`'s `errors` as `kind: "unreadable-slot"`, keyed by that folder's path — an absent folder is empty instead | | Mailbox folder fails to load | Collected in `readMailboxesDirectory`'s `errors` as `kind: "mailbox-load-failed"`, keyed by the folder's path — an unusable name, a symlink, or a missing, unreadable or malformed `MAILBOX.md` | @@ -2522,10 +2311,6 @@ before fire removed inventory rows is left out that way. | `unknown-assignee` | A `fileTask` naming an assignee the mailbox kind's `checkAssignee` refuses: no worker holds the name, two do, or its kind takes no tasks. Per-request; nothing is written | | `external-dispatcher` | A flow-to-flow post into an opened mailbox on a host whose dispatcher hands work to an external queue and shares no lease backend. A post through the public action route is written, but its notify block never runs: no member is woken and a routed mailbox doesn't answer | | Inventory id is not one path segment | `membershipKey` and `membershipPrefix` throw, naming the offending argument: an empty id, one containing `/` or `\`, or `.` and `..` | -| Unknown kind on `hire` | The tool, listing the hireable kinds. Writes nothing. | -| Address already served | The `hire` tool, naming the address and the live kind. Writes nothing. | -| Hire or fire with no organization | The tool. The verified principal carries no org, and the roster is org-scoped. | -| `fire` names no roster row | The tool. "This organization hired no seat" when nothing is live at that address. A live file-declared seat is refused as removed by editing its folder, not by firing it. | | 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 | | Mailbox or seat registration failed | Collected in `openInventory`'s `problems`: a mailbox 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 | From 605c1dbbb676ad27cda30ab27e15d7aebcf78afa Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 01:42:58 +0000 Subject: [PATCH 08/12] test(goals): VG and the grants goal at 9ea11deff, with their controls (FIX-1788 P4) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- .../keeps-each-users-workers-their-own/goal.md | 3 +++ .../a-seat-reaches-the-documents-its-file-names/goal.md | 2 ++ 2 files changed, 5 insertions(+) diff --git a/goals/workers-as-resources/keeps-each-users-workers-their-own/goal.md b/goals/workers-as-resources/keeps-each-users-workers-their-own/goal.md index c94345987d..ad4f902099 100644 --- a/goals/workers-as-resources/keeps-each-users-workers-their-own/goal.md +++ b/goals/workers-as-resources/keeps-each-users-workers-their-own/goal.md @@ -14,6 +14,9 @@ ## Verdict log | Date | Commit | Model | Verdict | Notes | |------|--------|-------|---------|-------| +| 2026-10-08 | `9ea11deff` (P4, regrouped on main `ea91beb49`) | scripted | PASS | a: Alice forked `my-desk` and hired `scribe`; four workers answered as their own configuration on one copy per flow, `scribe` through the second process with no restart, and read no other worker's skill. b: every reach for Alice's workers, and every way to run a session as another worker, refused. | +| 2026-10-08 | `9ea11deff`, `GOAL_CONTROL=org-scoped-workers` | scripted | FAIL (expected) | `b:reads-worker`: Bob reads `my-desk`, `scribe` on his roster; `b:create` with it. Leg a passed. | +| 2026-10-08 | `9ea11deff`, `GOAL_CONTROL=no-create-check` | scripted | FAIL (expected) | `b:create`: Bob's create naming Alice's `scribe` wrote a session; `b:other-flow` with it. Leg a passed. | | 2026-10-07 | fix/FIX-1788-p4 (pre-PR) | scripted | PASS | a: Alice forked `my-desk` and hired `scribe`; four workers answered as their own configuration on one copy per flow (`agent`, `research`, `workforce-roster`), `scribe` through the second process with no restart, and read no other worker's skill. b: every reach for Alice's workers, and every way to run a session as another worker, refused. | | 2026-10-07 | fix/FIX-1788-p4 (pre-PR), `GOAL_CONTROL=org-scoped-workers` | scripted | FAIL (expected) | `b:reads-worker` — Bob reads `my-desk`, `scribe` on his roster; `b:create` with it. Leg a passed. | | 2026-10-07 | fix/FIX-1788-p4 (pre-PR), `GOAL_CONTROL=no-create-check` | scripted | FAIL (expected) | `b:create` — Bob's create naming Alice's `scribe` wrote a session; `b:other-flow` with it. Leg a passed. | diff --git a/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/goal.md b/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/goal.md index 78a4edb88e..e5fd2838d5 100644 --- a/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/goal.md +++ b/goals/workforce-seats/a-seat-reaches-the-documents-its-file-names/goal.md @@ -59,6 +59,8 @@ rule and nothing else. | Date | Commit | Model | Verdict | Notes | |------|--------|-------|---------|-------| +| 2026-10-08 | `9ea11deff` (P4, regrouped on main `ea91beb49`) | n/a | PASS | Same as below: three workers on one `desk` copy, each reaching only its own grants; another worker's document answered as a missing one; the typo tree registered nothing. | +| 2026-10-08 | `9ea11deff`, `GOAL_CONTROL=no-visibility-rule` | n/a | FAIL (expected) | `the first worker's model lists the second's document: engineering.lead lists ["payroll"]`, with (b) to (e) red beside it. | | 2026-10-08 | `865abc573` + this change | n/a | PASS | One `desk` copy ran three workers: `engineering.lead` lists `["handbook"]` and writes nothing, `engineering.cfo` lists and writes `["payroll"]`, `engineering.chief` lists and writes both, through read, glob, grep, discover and the app's `peek`. Another worker's document read, wrote and was looked up as a missing one. The typo tree registered nothing, naming `engineering.typo`. | | 2026-10-08 | `865abc573` + this change, `GOAL_CONTROL=no-visibility-rule` | n/a | FAIL (expected) | `the first worker's model lists the second's document: engineering.lead lists ["payroll"]`, with every worker listing both documents, reading and writing the other's, and the three sets equal. | | 2026-09-19 | claude/fix-1381-l4c9yh | n/a | PASS | All six legs. The lead reached `handbook` and wrote nothing; the CFO reached and wrote `payroll`; the seat declaring nothing reached and wrote both. All three kept `audit-log`. The typo tree refused the whole roster naming `engineering.typo` and `hanbdook`, and the good seat's address 404'd afterwards. | From 11a048b6c9698a60a12936dec0adb3ee7482b0db Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 02:07:47 +0000 Subject: [PATCH 09/12] test(shift-manager): wait for a failed read's text, not the first blocked composer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The composer is blocked from the first render ("Reading the conversation first…"), so findByTestId could return before the failed read re-rendered it. Ported from 166599349 on fix/FIX-1791-coordinator-flow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- packages/shift-manager/test/conversation.test.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/shift-manager/test/conversation.test.tsx b/packages/shift-manager/test/conversation.test.tsx index a742f70689..52c9a8dd88 100644 --- a/packages/shift-manager/test/conversation.test.tsx +++ b/packages/shift-manager/test/conversation.test.tsx @@ -125,7 +125,9 @@ describe("when a line may go", () => { it("holds it when the conversation failed to load", async () => { read.mockRejectedValue(new Error("down")); drawn([session("s1")]); - expect((await screen.findByTestId("rev-composer-blocked")).textContent).toContain("didn't load"); + // The composer is blocked from the first render ("Reading the conversation first…"), so a + // findByTestId would return before the failed read re-renders it; wait for the failure's text. + await waitFor(() => expect(screen.getByTestId("rev-composer-blocked").textContent).toContain("didn't load")); }); }); From dd34c202871918c7caef358c581fdaf6f8a76ef9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 02:07:47 +0000 Subject: [PATCH 10/12] fix(kitchen-sink): name the woken worker in a mailbox's working row; E2E on the worker model (FIX-1788 P4) Every worker runs on the one agent copy, so a run's flowId is agent for all of them; the working row now names the worker the wake ran, read off its key. The rail and talk specs move to the worker model: the rail opens the agent kind into its one copy, a conversation starts from the roster panel's Talk, and which worker a conversation belongs to is read by the session's workerId. The rail's per-seat leaf detail is gone from the app, so its layout check goes with it; the VG check reads the roster panel. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- .../components/picked-session-panel.tsx | 9 +- apps/kitchen-sink/e2e/talk-from-page.spec.ts | 127 ++++++++----- apps/kitchen-sink/e2e/workforce-shell.spec.ts | 170 ++++++++---------- apps/kitchen-sink/lib/workforce-shell.ts | 11 ++ .../kitchen-sink/test/workforce-shell.test.ts | 11 ++ 5 files changed, 177 insertions(+), 151 deletions(-) diff --git a/apps/kitchen-sink/components/picked-session-panel.tsx b/apps/kitchen-sink/components/picked-session-panel.tsx index 8c3d5a9e86..9450cbc3f1 100644 --- a/apps/kitchen-sink/components/picked-session-panel.tsx +++ b/apps/kitchen-sink/components/picked-session-panel.tsx @@ -29,7 +29,7 @@ import type { useSession } from "@flow-state-dev/react"; import { MAILBOX_POST_COMPONENT, type MailboxTranscriptLine } from "@flow-state-dev/workforce/browser"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; -import { isMailboxKind, seatAskFor } from "@/lib/workforce-shell"; +import { isMailboxKind, seatAskFor, wokenWorkerOf } from "@/lib/workforce-shell"; type Session = ReturnType; @@ -140,8 +140,9 @@ function MailboxTranscript({ session }: { session: Session }) { } /** - * One row per run under the session that hasn't finished, named by the run's - * flow; a run with no recorded flow is background work, not a seat. A run + * One row per run under the session that hasn't finished, named by the worker + * a mailbox woke for it, or else by the run's flow; a run with no recorded + * flow is background work, not a seat. A run * waiting on an approval reads as working until it ends. * * While the list is stale (`childSessionsStale`: the last re-read failed, and @@ -158,7 +159,7 @@ function WorkingRows({ session }: { session: Session }) {
  • {run.flowId === undefined ? `Background work ${stale ? "was running at the last check" : "is running"}` - : `${run.flowId} ${stale ? "was working at the last check" : "is working"}`} + : `${wokenWorkerOf(run) ?? run.flowId} ${stale ? "was working at the last check" : "is working"}`}
  • ))} diff --git a/apps/kitchen-sink/e2e/talk-from-page.spec.ts b/apps/kitchen-sink/e2e/talk-from-page.spec.ts index f2549a7ccd..82a6fca771 100644 --- a/apps/kitchen-sink/e2e/talk-from-page.spec.ts +++ b/apps/kitchen-sink/e2e/talk-from-page.spec.ts @@ -28,8 +28,8 @@ * * And, re-pointed at this roster, by `specs/issues/FIX-1585/BUSINESS-RULES.md`: * BR-1 and BR-2 (a line labelled `devuser` survives a reload), BR-17 (a failed - * "New conversation" shows in the seat's row, opens nothing, and can be - * pressed again). FIX-1585's BR-15 (a seat of a kind with no action takes no + * "Talk" shows in the worker's roster row, opens nothing, and can be pressed + * again). FIX-1585's BR-15 (a seat of a kind with no action takes no * messages) is checked on the panel itself, in `test/picked-session-panel`: * the rail lists only the kinds the shell names, so a seat of any other kind * never reaches the page. @@ -50,6 +50,15 @@ import type { Locator, Page } from "@playwright/test"; import { test, expect } from "./fixtures"; +/* + * Workers as data (FIX-1788): every specialist runs on the one `agent` copy, + * and a conversation with one is a session of that copy that names the worker + * when it is created. A person starts one with "Talk" on the roster panel. The + * rail lists the copy's conversations, so which worker a conversation belongs + * to is read from the server, by the session's `workerId`, and the + * conversation itself is opened and read on the page. + */ + // One at a time, in file order: see the header. test.describe.configure({ mode: "default" }); @@ -72,9 +81,40 @@ async function open(page: Page, name: string): Promise { if ((await button.getAttribute("aria-expanded")) !== "true") await button.click(); } -/** The actions drawn on a seat's own row. */ -const seatRow = (page: Page, address: string): Locator => - rail(page).locator(`[data-instance-id="${address}"]`).locator("xpath=.."); +/** The flow every specialist runs on, registered as one copy at its kind. */ +const WORKER_FLOW = "agent"; + +/** A worker's row on the roster panel, with its "Talk". */ +const rosterRow = (page: Page, worker: string): Locator => + page.locator(`[data-testid="roster"]:visible [data-worker-id="${worker}"]`); + +/** Open the worker flow's kind and its one copy in the rail, unless already open. */ +async function openWorkerCopy(page: Page): Promise { + for (const button of [ + rail(page).locator(`button[data-kind="${WORKER_FLOW}"]`), + rail(page).locator(`button[data-instance-id="${WORKER_FLOW}"]`), + ]) { + if ((await button.getAttribute("aria-expanded")) !== "true") await button.click(); + } + const leaf = rail(page).locator(`ul[data-leaf="${WORKER_FLOW}"]`); + // The list is loaded once it shows a row or says it has none. + await expect(leaf.locator("[data-session-id]").or(leaf.getByText("No sessions yet")).first()).toBeVisible(); + return leaf; +} + +type WorkerSession = { id: string; parentSessionId?: string | null }; + +/** + * The person's sessions with `worker`, as the server lists them by the + * session's readonly `workerId`; with `runs`, the conversations a mailbox + * started for it too. Not graded on its own: what each holds is read on the page. + */ +async function sessionsOf(page: Page, worker: string, runs = false): Promise { + const query = `flowId=${WORKER_FLOW}&userId=devuser&state.workerId=${encodeURIComponent(worker)}&limit=100${runs ? "&include=dispatch-runs" : ""}`; + const res = await page.request.get(`/api/flows/sessions?${query}`); + expect(res.ok(), await res.text()).toBe(true); + return ((await res.json()) as { sessions: WorkerSession[] }).sessions; +} const token = () => `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; @@ -149,31 +189,26 @@ function answersTo(drawn: Array<{ label: string; text: string }>, mark: string) return next === -1 ? rest : rest.slice(0, next); } -/** A seat's conversation for a mailbox: the run the mailbox started, listed under the seat. */ -const mailboxRun = (page: Page, seat: string, mailbox: string): Locator => - rail(page).locator(`ul[data-leaf="${seat}"] [data-dispatch-run-of="${mailbox}"]`); - /** * `seat`'s conversation for the mailbox, opened and drawn, or `undefined` when - * it has none. A seat keeps one conversation per mailbox. + * it has none. A worker keeps one conversation per mailbox: the run the + * mailbox started, created naming the worker. * - * Reloads first, so nothing is picked, then waits for the seat's list to load + * Reloads first, so nothing is picked, then waits for the copy's list to load * and the conversation to draw its first turn: a turn counted as missing is * read off a loaded conversation, never off one still fetching. */ async function mailboxConversationOf(page: Page, seat: string): Promise { await page.reload(); await expect(page.locator('[data-testid="message-input"]:visible')).toBeEnabled(); - await open(page, "agent"); - await open(page, seat); - const leaf = rail(page).locator(`ul[data-leaf="${seat}"]`); - // The list is loaded once it shows a row or says it has none. - await expect(leaf.locator("[data-session-id]").or(leaf.getByText("No sessions yet")).first()).toBeVisible(); - const runs = mailboxRun(page, seat, MAILBOX); - const count = await runs.count(); - expect(count, `${seat} lists ${count} conversations for ${MAILBOX}`).toBeLessThanOrEqual(1); - if (count === 0) return undefined; - await runs.click(); + const runs = (await sessionsOf(page, seat, true)).filter((s) => s.parentSessionId === MAILBOX); + expect(runs.length, `${seat} has ${runs.length} conversations for ${MAILBOX}`).toBeLessThanOrEqual(1); + if (runs.length === 0) return undefined; + const leaf = await openWorkerCopy(page); + const run = leaf.locator(`[data-session-id="${runs[0]!.id}"]`); + // Listed as the run the mailbox started. + await expect(run).toHaveAttribute("data-dispatch-run-of", MAILBOX); + await run.click(); const conversation = picked(page); // A conversation for the mailbox opens on a person's post. await expect(conversation.locator('[data-message-role="user"]').first()).toBeVisible(); @@ -206,9 +241,7 @@ test("a new support.devices conversation keeps the message and the reply across }) => { const message = `[scenario:talk-to-seat] where is order ${token()}?`; await openShell(page); - await open(page, "agent"); - await open(page, "support.devices"); - await seatRow(page, "support.devices").getByRole("button", { name: "New conversation" }).click(); + await rosterRow(page, "support.devices").getByTestId("roster-talk").click(); const panel = picked(page); await panel.getByLabel("Message this seat").fill(message); @@ -218,47 +251,48 @@ test("a new support.devices conversation keeps the message and the reply across await expect(panel.getByRole("log").getByText(message, { exact: true })).toBeVisible(); await expect(panel.getByText(/\[reply:talk-to-seat\]/)).toBeVisible(); - // The conversation that was opened, so the reload can come back to it. - const sessionId = await rail(page) - .locator('ul[data-leaf="support.devices"] [aria-current="true"]') - .getAttribute("data-session-id"); + // The conversation that was opened, so the reload can come back to it. It + // is a session the server lists as the person's with the worker. + const sessionId = await (await openWorkerCopy(page)).locator('[aria-current="true"]').getAttribute("data-session-id"); expect(sessionId).toBeTruthy(); + expect((await sessionsOf(page, "support.devices")).map((s) => s.id)).toContain(sessionId); await page.reload(); await expect(page.locator('[data-testid="message-input"]:visible')).toBeEnabled(); - await open(page, "agent"); - await open(page, "support.devices"); - await rail(page).locator(`[data-session-id="${sessionId}"]`).click(); + await (await openWorkerCopy(page)).locator(`[data-session-id="${sessionId}"]`).click(); const kept = picked(page); await expect(kept.getByText(message, { exact: true })).toBeVisible(); await expect(kept.getByText(/\[reply:talk-to-seat\]/)).toBeVisible(); }); -test("a failed New conversation shows in the seat's row, opens nothing, and can be pressed again", async ({ +test("a failed Talk shows in the worker's roster row, opens nothing, and can be pressed again", async ({ page, consoleErrors, }) => { let refuse = true; + // "Talk" finds the person's session with the worker, or creates one. Refuse + // both, so the press fails whichever it would have done. await page.route( - (url) => url.pathname === "/api/flows/support.accounts/sessions", + (url) => + url.pathname === `/api/flows/${WORKER_FLOW}/sessions` || + (url.pathname === "/api/flows/sessions" && url.searchParams.get("state.workerId") === "support.accounts"), async (route) => { - if (route.request().method() !== "POST" || !refuse) return route.fallback(); + if (!refuse) return route.fallback(); await route.fulfill({ status: 503, json: { error: { message: "store unavailable" } } }); }, ); await openShell(page); - await open(page, "agent"); - await open(page, "support.accounts"); - const button = seatRow(page, "support.accounts").getByRole("button", { name: "New conversation" }); + const worker = rosterRow(page, "support.accounts"); + const button = worker.getByTestId("roster-talk"); await button.click(); - await expect(rail(page).getByTestId("seat-create-error")).toContainText("Could not start a conversation"); + await expect(worker.getByTestId("roster-talk-error")).toContainText("Could not open a conversation"); await expect(picked(page)).toHaveCount(0); refuse = false; await button.click(); await expect(picked(page).getByLabel("Message this seat")).toBeVisible(); - await expect(rail(page).getByTestId("seat-create-error")).toHaveCount(0); + await expect(worker.getByTestId("roster-talk-error")).toHaveCount(0); // The refused create's own 503 is the one console error this scenario causes. consoleErrors.splice(0, consoleErrors.length, ...consoleErrors.filter((e) => !e.includes("503"))); }); @@ -337,20 +371,15 @@ test("a post to support.help runs the specialist it was routed to once, in its o // Time for a wrongly woken seat to run, so its absence below is not a race. await page.waitForTimeout(1_500); - await page.reload(); - await expect(page.locator('[data-testid="message-input"]:visible')).toBeEnabled(); - await open(page, "agent"); - await open(page, "support.fsd"); - // One conversation for the mailbox, whatever else the seat holds. - await expect(mailboxRun(page, "support.fsd", MAILBOX)).toHaveCount(1); - await mailboxRun(page, "support.fsd", MAILBOX).click(); - const conversation = picked(page); + // One conversation for the mailbox, whatever else the worker holds. + const conversation = await mailboxConversationOf(page, "support.fsd"); + expect(conversation, `support.fsd has no conversation for ${MAILBOX}`).toBeDefined(); for (const line of [first, second]) { - const heard = conversation.locator('[data-message-role="user"]').filter({ hasText: line }); + const heard = conversation!.locator('[data-message-role="user"]').filter({ hasText: line }); await expect(heard).toHaveCount(1); await expect(heard).toContainText(`in ${MAILBOX}: ${line}`); } - await expect(conversation.locator('[data-message-role="assistant"]').filter({ hasText: "[reply:wake]" })).not.toHaveCount(0); + await expect(conversation!.locator('[data-message-role="assistant"]').filter({ hasText: "[reply:wake]" })).not.toHaveCount(0); // The other specialists never heard either post. for (const seat of SPECIALISTS.filter((s) => s !== "support.fsd")) { diff --git a/apps/kitchen-sink/e2e/workforce-shell.spec.ts b/apps/kitchen-sink/e2e/workforce-shell.spec.ts index b64f23a4e2..def5e502ca 100644 --- a/apps/kitchen-sink/e2e/workforce-shell.spec.ts +++ b/apps/kitchen-sink/e2e/workforce-shell.spec.ts @@ -1,8 +1,13 @@ /** * The rebuilt shell, against the built app: the rail browses mailboxes and - * seats to the depth each flow declares, a seat opens into its kind, what it - * handles and its instructions, the panel stands beside the stream, and the - * three regions give way in the right order as the window narrows. + * the worker flow to the depth each flow declares, the roster panel lists each + * worker with its flow and what it handles, the panel stands beside the + * stream, and the three regions give way in the right order as the window + * narrows. + * + * Every worker runs on one copy of the flow it names, so the rail's worker + * section is the `agent` kind, its one copy, and that copy's conversations: + * each one a session that names its worker when it is created. * * These open the app as `devuser`, not a per-test user, because that is who * the boot opens the mailboxes for: a fresh user would see no mailbox @@ -23,7 +28,10 @@ import type { Browser, Locator, Page, Request } from "@playwright/test"; import { test, expect, openKitchenSink } from "./fixtures"; +/** A standard worker on `agent`, declared in the app's workforce tree. */ const SEAT = "support.devices"; +/** The flow every worker in this app runs on, registered as one copy at its kind. */ +const WORKER_FLOW = "agent"; /** A mailbox the old roster declared and this one does not. */ const RETIRED_MAILBOX = "support.desk"; @@ -59,10 +67,13 @@ async function seedRetiredMailbox(page: Page): Promise { expect([200, 201, 409], await response.text()).toContain(response.status()); } -/** Give the seat one conversation, so it has something to open into. */ +/** + * Give the worker one conversation: a session of its flow's one copy, created + * naming it, so the copy has something to open into. + */ async function seedSeatSession(page: Page, title?: string): Promise { - const response = await page.request.post(`/api/flows/${SEAT}/sessions`, { - data: { userId: "devuser", ...(title === undefined ? {} : { title }) }, + const response = await page.request.post(`/api/flows/${WORKER_FLOW}/sessions`, { + data: { userId: "devuser", state: { workerId: SEAT }, ...(title === undefined ? {} : { title }) }, }); expect(response.ok(), await response.text()).toBe(true); const json = (await response.json()) as { session?: { id: string }; id?: string }; @@ -76,8 +87,12 @@ async function openShell(page: Page): Promise { const rail = (page: Page) => page.getByTestId("rail"); const row = (page: Page, name: string) => rail(page).getByRole("button", { name, exact: true }); +/** A kind's own row. The worker flow's kind and its one copy share the name `agent`. */ +const kindRow = (page: Page, kind: string) => rail(page).locator(`button[data-kind="${kind}"]`); +/** A copy's row under its kind. */ +const copyRow = (page: Page, id: string) => rail(page).locator(`button[data-instance-id="${id}"]`); -test("the rail opens a mailbox kind into conversations and a seat kind into seats, reading only leaves", async ({ +test("the rail opens a mailbox kind into conversations and the worker flow into its one copy, reading only leaves", async ({ page, consoleErrors: _consoleErrors, }) => { @@ -86,15 +101,18 @@ test("the rail opens a mailbox kind into conversations and a seat kind into seat const requests = sessionListRequests(page); await openShell(page); await expect(rail(page).getByRole("list", { name: "Mailboxes" })).toBeVisible(); - await expect(rail(page).getByRole("list", { name: "Seats" })).toBeVisible(); - // Drawing the rail reads no session list of its own. The one read at load - // is the assistant's, for the conversation the stream opens on. The team - // panel's live board holds its mailbox's stream open, so the page never goes - // network-idle: wait for the board's first read, then the half-second quiet - // that network-idle means. + await expect(rail(page).getByRole("list", { name: "Workers" })).toBeVisible(); + // Drawing the rail reads no session list of its own. The reads at load are + // the assistant's, for the conversation the stream opens on, and the roster + // panel's, for the person's roster session. The team panel's live board + // holds its mailbox's stream open, so the page never goes network-idle: + // wait for the board's first read, then the half-second quiet that + // network-idle means. await expect(page.getByTestId("board-support.help.escalations").locator('[data-panel="board"]')).toBeVisible(); await page.waitForTimeout(500); - expect(requests.take().filter((url) => !url.includes("flowKind=chat-agent"))).toEqual([]); + expect( + requests.take().filter((url) => !url.includes("flowKind=chat-agent") && !url.includes("flowKind=workforce-roster")), + ).toEqual([]); // A mailbox kind is a singleton: its row is the leaf, so opening it lands // straight on the mailbox conversations. It is ONE read, of the mailbox the @@ -107,18 +125,21 @@ test("the rail opens a mailbox kind into conversations and a seat kind into seat expect(mailboxReads.take()).toHaveLength(1); expect(requests.take()).toEqual([]); - // A seat kind is a collection: opening it lists the seats and reads nothing. - await row(page, "agent").click(); - await expect(row(page, SEAT)).toBeVisible(); + // The worker flow is a collection with one copy: opening its kind lists the + // copy and reads nothing. No copy is drawn per worker. + await kindRow(page, WORKER_FLOW).click(); + await expect(copyRow(page, WORKER_FLOW)).toBeVisible(); + await expect(copyRow(page, SEAT)).toHaveCount(0); await page.waitForTimeout(300); expect(requests.take()).toEqual([]); - // Opening one seat is one read, for that seat, and shows its conversation. - await row(page, SEAT).click(); + // Opening the copy is one read, for that copy, and shows the conversation + // created naming the worker. + await copyRow(page, WORKER_FLOW).click(); await expect(rail(page).locator(`[data-session-id="${seatSessionId}"]`)).toBeVisible(); const seatReads = requests.take(); expect(seatReads).toHaveLength(1); - expect(seatReads[0]).toContain(`flowId=${encodeURIComponent(SEAT)}`); + expect(seatReads[0]).toContain(`flowId=${encodeURIComponent(WORKER_FLOW)}`); }); /** @@ -141,16 +162,16 @@ test("the header names the assistant's model on the assistant only, never on a m await expect(headerModel).toBeVisible(); await expect(headerModel).not.toHaveText(""); - const expand = async (name: string) => { - if ((await row(page, name).getAttribute("aria-expanded")) !== "true") await row(page, name).click(); + const expand = async (button: Locator) => { + if ((await button.getAttribute("aria-expanded")) !== "true") await button.click(); }; - await expand("mailbox"); + await expand(row(page, "mailbox")); await row(page, "support.help").click(); await expect(page.locator('[data-testid="picked-session"]:visible')).toBeVisible(); await expect(headerModel).toHaveCount(0); - await expand("agent"); - await expand(SEAT); + await expand(kindRow(page, WORKER_FLOW)); + await expand(copyRow(page, WORKER_FLOW)); await rail(page).locator(`[data-session-id="${seatSessionId}"]`).click(); await expect(page.locator('[data-testid="picked-session"]:visible')).toBeVisible(); await expect(headerModel).toHaveCount(0); @@ -164,10 +185,10 @@ const LONG_SEAT = "support.escalations-overnight-weekend-queue"; const LONG_TITLE = "Refund escalation for order 4417 and both of its linked chargebacks"; /** - * Serve this page the real flow list plus one agent seat whose name is - * too long for the rail. The roster is the app's workforce tree, which has no - * name this long, and hiring one would leave it in every other scenario's - * rail. Its session read goes to the real server, which has none for it. + * Serve this page the real flow list plus one more `agent` copy whose name is + * too long for the rail. The app registers one copy per worker flow, none + * with a name this long. Its session read goes to the real server, which has + * none for it. */ async function withLongSeat(page: Page): Promise { await page.route( @@ -553,52 +574,6 @@ async function checkRail( await test.info().attach(shot.file, { path, contentType: "image/png" }); } -/** - * G9: an open seat's detail sits under its row, not on it. The open seat's row - * stays one line, the height of a closed seat's, every detail starts below its - * row, and neither the rows nor the details run past the rail. - */ -async function checkLeafDetail(nav: Locator, name: string, openSeat: string, closedSeat: string): Promise { - // The detail is on the open row's line when it isn't under it, so the two - // rows are measured as they are drawn: one open, one closed. - await nav.locator(`[data-instance-id="${closedSeat}"][aria-expanded="true"]`).click(); - const m = await nav.evaluate( - (root, seats) => { - const frameOf = (address: string) => - root.querySelector(`[data-instance-id="${CSS.escape(address)}"]`)!.parentElement!.getBoundingClientRect(); - const railRect = root.getBoundingClientRect(); - const details = [...root.querySelectorAll("[data-leaf-detail]")].map((detail) => { - const frame = detail.previousElementSibling!.getBoundingClientRect(); - const box = detail.getBoundingClientRect(); - return { - address: detail.dataset.leafDetail!, - below: box.top >= frame.bottom - 0.5, - inside: - box.left >= railRect.left - 0.5 && - box.right <= railRect.right + 0.5 && - frame.right <= railRect.right + 0.5 && - detail.scrollWidth <= detail.clientWidth + 1, - }; - }); - return { - openHeight: frameOf(seats.open).height, - closedHeight: frameOf(seats.closed).height, - details, - railOverflows: root.scrollWidth > root.clientWidth + 1, - }; - }, - { open: openSeat, closed: closedSeat }, - ); - const misplaced = m.details.filter((d) => !d.below || !d.inside); - const ok = - m.details.some((d) => d.address === openSeat) && - Math.abs(m.openHeight - m.closedHeight) <= 0.5 && - misplaced.length === 0 && - !m.railOverflows; - const line = `${name} · G9 an open seat's row stays one line and its detail sits below it, inside the rail — open ${openSeat} row ${m.openHeight.toFixed(1)}px vs closed ${closedSeat} ${m.closedHeight.toFixed(1)}px; ${m.details.length - misplaced.length} of ${m.details.length} details below their row and inside the rail${misplaced.length ? ` (not: ${misplaced.map((d) => d.address).join(", ")})` : ""}; rail overflows: ${m.railOverflows}`; - test.info().annotations.push({ type: ok ? "pass" : "fail", description: line }); - expect.soft(ok, line).toBe(true); -} /** G8's last clause: a screen with no hover pointer shows every row's actions. */ async function checkTouch( @@ -632,8 +607,10 @@ test("the rail, fully expanded in both hosts, draws each action on its row, one consoleErrors: _consoleErrors, }) => { test.setTimeout(180_000); - // A seat with a conversation that has no title, one with a title too long - // for the rail, a seat with none, and the singleton mailboxes the boot opens. + // The worker flow's copy holding a conversation with no title and one with a + // title too long for the rail, a copy with none, and the singleton mailboxes + // the boot opens. The app draws no detail under a copy: a worker's flow and + // what it handles are on the roster panel, which the VG test below reads. await seedSeatSession(page); await seedSeatSession(page, LONG_TITLE); @@ -655,7 +632,6 @@ test("the rail, fully expanded in both hosts, draws each action on its row, one container: rail(page), file: "rail-kitchen-sink.png", }); - await checkLeafDetail(shellNav, "/", SEAT, "support.accounts"); await checkTouch(browser, openShellRail, "/"); // The developer tool's rail, narrowed to the same 256px. @@ -677,7 +653,7 @@ test("the rail, fully expanded in both hosts, draws each action on its row, one await page.mouse.up(); expect((await aside.boundingBox())!.width).toBe(256); await checkRail(page, toolNav, "/devtool", { - hoverRow: `[data-instance-id="${SEAT}"]`, + hoverRow: `[data-instance-id="${WORKER_FLOW}"]`, quietRow: '[data-kind="agent"]', container: aside, file: "rail-devtool.png", @@ -686,20 +662,22 @@ test("the rail, fully expanded in both hosts, draws each action on its row, one }); /** - * VG, the completion gate for opening a seat from the rail (`specs/issues/FIX-1500`), - * re-pointed at this roster (`specs/issues/FIX-1611`, D3). + * VG, the completion gate for a declared worker on the page (`specs/issues/FIX-1500`), + * re-pointed at this roster (`specs/issues/FIX-1611`, D3) and at workers as + * data (`specs/issues/FIX-1788`): the roster panel lists each worker with the + * flow it runs on and what it handles. * - * `support.devices` is declared in a worker file, so opening it proves the - * kind comes from the row the rail already holds, and that a seat with no - * roster row reads no instructions. Its hire half left with the page's - * "Hire another" (FIX-1611 D3); FIX-1415 brings both back. + * `support.devices` is declared in a worker file, so it is a standard worker: + * the roster lists it from the person's roster read, and its instructions, + * the file's body, never reach the page. Hiring is the roster flow's, not a + * button on the page. * * Red states produced before this was trusted: - * - Serve the detail from an app-private route: the API-surface assertion fails. - * - Leave "Hire another" on the seat: the no-hire assertion fails. - * - Drop the description from the seat's detail: the description assertion fails. + * - Serve the roster from an app-private route: the API-surface assertion fails. + * - Put "Hire another" back on the page: the no-hire assertion fails. + * - Drop the description from the worker's row: the description assertion fails. */ -test("VG · open a declared seat: its kind and what it handles, no instructions read, and no hire button", async ({ +test("VG · a declared worker: its flow and what it handles, no instructions read, and no hire button", async ({ page, sessionId, consoleErrors: _consoleErrors, @@ -710,15 +688,11 @@ test("VG · open a declared seat: its kind and what it handles, no instructions await openKitchenSink(page, sessionId); - // A declared seat: its kind, what it handles, and no roster row to read instructions from. - await row(page, "agent").click(); - await row(page, DECLARED).click(); - const declared = rail(page).locator(`[data-leaf-detail="${DECLARED}"]`); - await expect(declared.locator("[data-seat-kind]")).toHaveText("agent"); - await expect(declared.getByTestId("seat-description")).toHaveText( - "Printers, laptops, phones, wifi and anything else with a power button.", - ); - await expect(declared.locator('[data-state="not-published"]')).toBeVisible(); + // A standard worker: its flow, what it handles, and none of its instructions. + const declared = page.locator(`[data-testid="roster"]:visible [data-worker-id="${DECLARED}"]`); + await expect(declared).toContainText(WORKER_FLOW); + await expect(declared).toContainText("Printers, laptops, phones, wifi and anything else with a power button."); + await expect(page.getByText("devices specialist")).toHaveCount(0); await expect(page.getByRole("button", { name: "Hire another" })).toHaveCount(0); // No data request went to a developer-tool route or an app-private API: diff --git a/apps/kitchen-sink/lib/workforce-shell.ts b/apps/kitchen-sink/lib/workforce-shell.ts index e0d8683547..a5db6a2e9a 100644 --- a/apps/kitchen-sink/lib/workforce-shell.ts +++ b/apps/kitchen-sink/lib/workforce-shell.ts @@ -65,6 +65,17 @@ export const SEAT_ASKS = { agent: { action: "run", field: "message" }, } as const satisfies Record<(typeof SEAT_KINDS)[number], SeatAsk>; +/** + * The worker a mailbox woke, read off the run's `topic`: the key Workforce's + * wake derives each worker's conversation from, `mailbox::`. + * Every worker on a flow shares its copy, so the run's `flowId` names the + * flow (`agent`), not the worker. `undefined` for any other run. + */ +export function wokenWorkerOf(run: { readonly topic?: string }): string | undefined { + const match = /^mailbox:[^:]+:(.+)$/.exec(run.topic ?? ""); + return match?.[1]; +} + /** A seat kind's answer, or `undefined` for a kind the shell does not know. */ export function seatAskFor(kind: string): SeatAsk | undefined { return (SEAT_ASKS as Record)[kind]; diff --git a/apps/kitchen-sink/test/workforce-shell.test.ts b/apps/kitchen-sink/test/workforce-shell.test.ts index 6751a846a6..35d73f5475 100644 --- a/apps/kitchen-sink/test/workforce-shell.test.ts +++ b/apps/kitchen-sink/test/workforce-shell.test.ts @@ -32,6 +32,7 @@ import { SHELL_BOARDS, SHELL_MAILBOXES, seatAskFor, + wokenWorkerOf, } from "../lib/workforce-shell"; describe("the shell's names match the workforce tree", () => { @@ -159,3 +160,13 @@ describe("the conversation the page opens on", () => { expect(defaultConversation([])).toBeUndefined(); }); }); + +describe("a mailbox's working row names the worker it woke", () => { + // Every worker runs on the one `agent` copy, so a run's flow id is `agent` + // for all of them; only the wake's key says which worker it is. + it("reads the worker off the wake's key, and nothing off any other run", () => { + expect(wokenWorkerOf({ topic: "mailbox:support.help:support.devices" })).toBe("support.devices"); + expect(wokenWorkerOf({ topic: "brief:billing" })).toBeUndefined(); + expect(wokenWorkerOf({})).toBeUndefined(); + }); +}); From 6cb3ae91e15345852f080937ccf12e3c60ef795f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 02:07:52 +0000 Subject: [PATCH 11/12] docs(workforce): the docs editor's pass on P4 (FIX-1788 P4 S16) Plainer intros, refusal shapes on Hiring and forking, an approval step that is optional where it is, no undefined owner pins, a React example without await in render, what fork copies, what a worker with no resources: reaches on a shared copy, and the glossary's workforce rows. The memory wording waits on the product owner's call. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- apps/docs/docs/cli/configuration.md | 4 -- apps/docs/docs/glossary.md | 10 ++--- apps/docs/docs/resources/overview.md | 2 +- apps/docs/docs/server/background-work.md | 2 +- apps/docs/docs/workforce/built-in-worker.md | 2 +- apps/docs/docs/workforce/chief-of-staff.md | 10 ++--- apps/docs/docs/workforce/documents-on-disk.md | 2 +- apps/docs/docs/workforce/durable-hire.md | 25 ++++++++++--- apps/docs/docs/workforce/overview.md | 6 +-- apps/docs/docs/workforce/workers-on-disk.md | 21 +++++++---- packages/core/README.md | 2 +- packages/workforce/README.md | 37 +++++++++---------- 12 files changed, 69 insertions(+), 54 deletions(-) diff --git a/apps/docs/docs/cli/configuration.md b/apps/docs/docs/cli/configuration.md index 14e18605f6..d254f87f1c 100644 --- a/apps/docs/docs/cli/configuration.md +++ b/apps/docs/docs/cli/configuration.md @@ -167,10 +167,6 @@ anything is written: - A session belongs to the user and organization it was created with. Resuming one with `--session` as anyone else is refused, as it would be over HTTP. Use a new session id. -- A flow copy registered with an owner pin runs only for the owner it's pinned to. A run whose - user or organization falls outside that pin is refused, whether the identity came from your - resolver or from `--user` and `--org`. Name the owner with `--org`, plus `--user` for a copy - pinned to one member. - A session with no organization recorded on it is refused and left unchanged. The message points to the upgrade steps in [Which organization a record belongs to](/docs/persistence/overview#which-organization-a-record-belongs-to). diff --git a/apps/docs/docs/glossary.md b/apps/docs/docs/glossary.md index 2a1a0d5a7f..7e80dddd98 100644 --- a/apps/docs/docs/glossary.md +++ b/apps/docs/docs/glossary.md @@ -100,14 +100,14 @@ These sit beside Orchestration on Core and don't use a task board. | Term | Package | What it is | Built from | |---|---|---|---| -| **Worker** | workforce | One worker record, usually from a `WORKER.md` and sometimes built in code, hired into a flow instance with its own address. You open sessions against it like any flow. See [Workers on disk](./workforce/workers-on-disk.md). | Flow instance | -| **Address** | workforce | A worker's id: `team.name` for a team worker, the bare name for an org worker. A worker hired while the app runs is addressed `.`, or `.~.` when one person owns it. | None | +| **Worker** | workforce | A configuration run by one shared copy of the flow it names: a `WORKER.md` (a standard worker every user has) or a row a user hired or forked for themselves. A session names its worker when it is created. See [Workers on disk](./workforce/workers-on-disk.md). | Flow, session state | +| **Address** | workforce | A worker's id: `team.name` for a team worker, the bare name for an org worker. A user's own worker is addressed by the id it was hired or forked under, on that user's roster. | None | | **Team** | workforce | A folder of workers under `teams//`, with an optional `TEAM.md` whose body every worker on the team reads. A team is not a flow and has no address. | Workers | | **Org worker** | workforce | A worker under `org/workers//`. It belongs to no team. | Worker | | **Built-in worker** | workforce | The `agent` kind every worker runs on unless its file names another `flow:`. See [The built-in worker](./workforce/built-in-worker.md). | Flow (collection), generator, skills | -| **Hire** | workforce | A user adds a worker of their own, as a row in their data. `hireWorkforce` gives back one copy of each worker flow, which your app registers. | Flow instance | -| **Roster** | workforce | A user's workers: their own, and the standard ones your files declare. See [Hiring and forking](./workforce/durable-hire.md). | Org resource collection | -| **Fire** | workforce | Removes a worker hired while the app runs. A worker declared in a file leaves when its folder is deleted. | Roster row, inventory row | +| **Hire** | workforce | A user adds a worker of their own, as a row in their data. `hireWorkforce` gives back one copy of each worker flow, which your app registers. | Roster row | +| **Roster** | workforce | A user's workers: their own, and the standard ones your files declare. See [Hiring and forking](./workforce/durable-hire.md). | User-scoped resource collection, standard workers from files | +| **Fire** | workforce | Removes one of a user's own workers from their roster. A worker declared in a file leaves when its folder is deleted. | Roster row | | **Mailbox** | workforce | One `MAILBOX.md`: a named session on the shared `mailbox` flow, with members, a charter and a transcript. See [Mailboxes](./workforce/mailboxes.md). | Session, flow | | **Member** | workforce | A worker id on a mailbox's member list. A post wakes each member whose flow kind handles posts, or only the chosen one on a routed mailbox. | Worker address | | **Transcript** | workforce | The posts in a mailbox, rebuilt from the post items. | Items | diff --git a/apps/docs/docs/resources/overview.md b/apps/docs/docs/resources/overview.md index aa2e4bb6ff..1a4a370c5c 100644 --- a/apps/docs/docs/resources/overview.md +++ b/apps/docs/docs/resources/overview.md @@ -289,7 +289,7 @@ Resource collections take the same flags, declared once on the collection and ap The generic tools address resources by their scope-qualified uri (for example `session/files/readme.md`), the same handle the [search tools](/docs/resources/searching) return — so a result from `globResources` or `grepResourceContent` feeds straight into `readResourceContentTool`. -A flow can also narrow what the model reaches on a single turn. Give it a `resourceVisibility` rule, and the built-in resource tools, the `discover` door, and any tool you build on them treat a resource the rule hides as one that doesn't exist: it isn't listed, searched, read or written, and asking for it by its uri gets the same answer as asking for a missing one. A resource the rule marks read-only is read but not written. With no rule, the model reaches what it reaches today. +A flow can also narrow what the model reaches on a single turn. Give it a `resourceVisibility` rule: a function that returns `"visible"`, `"read-only"` or `"hidden"` for each resource. The built-in resource tools, the `discover` tool, and any tool you build on them treat a resource the rule hides as one that doesn't exist: it isn't listed, searched, read or written, and asking for it by its uri gets the same answer as asking for a missing one. A resource the rule marks read-only is read but not written. With no rule, the model reaches every resource the flow declares, as its `llmReadable` and `llmWritable` flags allow. ```ts defineFlow({ diff --git a/apps/docs/docs/server/background-work.md b/apps/docs/docs/server/background-work.md index 660b9edce8..a083977252 100644 --- a/apps/docs/docs/server/background-work.md +++ b/apps/docs/docs/server/background-work.md @@ -117,7 +117,7 @@ A refusal at run time throws `DispatchRefusedError`, with `code: | `refused` | Meaning | |---|---| | `no-entry` | The addressed flow declares no entry at that address | -| `flow-not-found` | A `flowKind` names a flow this server has not registered, or a flow copy registered with an owner pin the sending session may not open: one pinned to another organization, or to another user. The refusal is the same in both cases, so `flow-not-found` doesn't tell you which one you hit | +| `flow-not-found` | A `flowKind` names a flow this server has not registered | | `session-not-found` | An `id` names a session that does not exist, or one that belongs to another user | | `session-not-addressable` | An `id` names a session on a flow other than the one addressed | | `key-occupied` | The `key` derived a session id already held by a record that is not this conversation's run | diff --git a/apps/docs/docs/workforce/built-in-worker.md b/apps/docs/docs/workforce/built-in-worker.md index 3b2c6eacdd..341a4cc2a9 100644 --- a/apps/docs/docs/workforce/built-in-worker.md +++ b/apps/docs/docs/workforce/built-in-worker.md @@ -88,7 +88,7 @@ const flows = hireWorkforce(installation); | `taskLists` | The mailbox boards this kind's workers take tasks from, by id (`mailboxBoardIds(mailboxes)`). Left out, the kind takes no tasks. See [Taking a task](#taking-a-task). | | `uses` | Capabilities every worker of this kind carries, attached to the generator that answers. | | `afterAnswer` | A block that runs after the worker answers, without changing the reply. | -| `isolateUserState` | Keep this flow's user-scoped storage apart from other flows'. Every worker on `agent` shares one copy, so a user's workers on it still share one cell. | +| `isolateUserState` | Keep this flow's user-scoped storage apart from other flows'. Every worker on `agent` shares one copy, so a user's workers on it still share the same user-scoped storage. | `classifierModel` and `confidenceThreshold` belong to the kind: nothing reads either until a worker turns `skills.enableLlmClassifier` on, and a `WORKER.md` that names one is refused at the hire, by name, along with any other setting the kind does not declare. `uses` and `afterAnswer` are what [Giving workers memory](#giving-workers-memory) uses. diff --git a/apps/docs/docs/workforce/chief-of-staff.md b/apps/docs/docs/workforce/chief-of-staff.md index 50673122e5..d74d156e20 100644 --- a/apps/docs/docs/workforce/chief-of-staff.md +++ b/apps/docs/docs/workforce/chief-of-staff.md @@ -2,18 +2,18 @@ title: The chief of staff sidebar_position: 12 sidebar_label: Chief of staff -description: "One worker a person asks who works here, and asks for workers of their own. Hires land at once; a fire waits for the person's approval. It can also start projects." +description: "One worker a person asks who works here, and asks for workers of their own. Hires land at once; with the approval step below, a fire waits for the person's approval. It can also start projects." --- # The chief of staff -The chief of staff is a worker a person talks to about the organization itself. Ask it who works here or who is in a mailbox, and it looks it up. Ask it for another worker, and it hires one of your own. Ask it for one fewer, and it puts the fire in front of you to approve. Nothing is removed until you do. Give it the project tools, and it starts [projects](./projects.md) for you too. +The chief of staff is a worker a person talks to about the organization itself. Ask it who works here or who is in a mailbox, and it looks it up. Ask it for another worker, and it hires one of your own. Ask it for one fewer, and, with the approval step shown below, it puts the fire in front of you to approve; nothing is removed until you do. Give it the project tools, and it starts [projects](./projects.md) for you too. A worker it hires belongs to the person it is talking to: it is on their roster and nobody else's, as [Hiring and forking](./durable-hire.md) describes. A Lab that doesn't declare a chief of staff doesn't have one. ## Adding one -You need two things: a `WORKER.md` for the worker, and the hire and fire tools in the catalog of the flow it runs on. +Add a `WORKER.md` for the worker, and put the hire and fire tools in the catalog of the flow it runs on. The file goes under `org/workers/`, beside `teams/`. Its folder name is its id, so `org/workers/chief-of-staff/` is the worker `chief-of-staff`. It runs on the built-in `agent` flow and names the tools it holds: @@ -117,7 +117,7 @@ export const flows = hireWorkforce(installation); The capabilities on the flow each add one part: -- **Inventory and `discover`.** `createWorkforceCapability` gives every worker on the flow `discover`, which is how the chief of staff answers questions about the roster. The small `inventory` capability declares the seat and mailbox inventories on the flow, the mailbox one with `projectWritesMailboxInventory`, the declaration the [project tools](#starting-projects) need, so you can add them later without touching it. Passing the keys as `inventory` lets `discover` answer who works here and who is in a mailbox. +- **Inventory and `discover`.** `createWorkforceCapability` gives every worker on the flow `discover`, which is how the chief of staff answers questions about the roster. The small `inventory` capability declares the seat and mailbox inventories on the flow. The mailbox one uses `projectWritesMailboxInventory`, the declaration the [project tools](#starting-projects) need, so you can add them later without touching it. Passing the keys as `inventory` lets `discover` answer who works here and who is in a mailbox. - **Posting.** `workerMailboxPostCapability` adds `post-to-mailbox`, so the chief of staff can answer in a mailbox it is a member of, signed as the worker its turn runs as. A mailbox counts it as a member only when its `MAILBOX.md` `members:` lists it, by its own name for an org-level worker, as in `members: [eng.em, eng.coder, chief-of-staff]`. A post from a worker the mailbox doesn't list is refused with `author-not-a-member`. - **Hiring.** The catalog holds `hire` and `fire`. Asking first is yours to add, as `askFire` does: the blocks themselves write at once. @@ -208,7 +208,7 @@ firing "scribe" waits for a person's approval, and this app can't ask for one. N Asking also needs a model with the single-step methods: `generateStep`, and `streamStep` when it streams. Models from the built-in AI SDK adapter have them. On a custom model without them, or a fallback group none of whose models has them, the tool can't pause the request: the call fails before anything changes, the model is told the tool failed, and the turn carries on with no approval raised. [Suspending inside generators](../advanced/generator-and-router-suspend-resume.md) covers a pause inside a tool call. -The roster flow's own `fire` action, which an app sends directly, never asks: an app that sends it already has the person's say-so. +The roster flow's own `fire` action, which an app sends directly, never asks. Get the person's approval before you send it. ## What it can't do diff --git a/apps/docs/docs/workforce/documents-on-disk.md b/apps/docs/docs/workforce/documents-on-disk.md index 09d6f19c8b..2ef73e4fc1 100644 --- a/apps/docs/docs/workforce/documents-on-disk.md +++ b/apps/docs/docs/workforce/documents-on-disk.md @@ -300,7 +300,7 @@ const engineering = resourcesFromDocs( A worker's folder is also only part of the name. Putting a `resources/` document under `workers/ada/` addresses it to that worker. It does not keep it from the others. Every worker on a flow shares that flow's one copy, so by default every one of them reads the same row. -Filtering decides what a whole flow installs. To narrow one worker within a flow, the worker's own file names the documents it may touch under `resources:`, and can take one read-only: see [what a `WORKER.md` says](./workers-on-disk.md#what-a-workermd-says). Its model then reaches only those, on every turn: a document it isn't granted answers as one that doesn't exist. A worker naming a document the app didn't declare is refused, so the filter holds. +Filtering decides what a whole flow installs. To narrow one worker within a flow, the worker's own file names the documents it may touch under `resources:`, and can take one read-only: see [what a `WORKER.md` says](./workers-on-disk.md#what-a-workermd-says). Its model then reaches only those, on every turn: a document it isn't granted answers as one that doesn't exist. A worker whose file has no `resources:` key reaches every document the app passed as `documents`, and writes the ones that allow writes. A worker naming a document the app didn't declare is refused, so the filter holds. ### Keeping a document per person diff --git a/apps/docs/docs/workforce/durable-hire.md b/apps/docs/docs/workforce/durable-hire.md index 2beb6ec70a..6211bbc9bd 100644 --- a/apps/docs/docs/workforce/durable-hire.md +++ b/apps/docs/docs/workforce/durable-hire.md @@ -13,8 +13,8 @@ stored in their data, and nobody else can see it. ## Hiring a worker -A hire writes one row to the user's roster, in the organization they're signed in to. Nothing is -registered and nothing restarts: the next turn on any of your processes can use it. +A hire writes one row to the user's roster, in the organization they're signed in to. A hire +takes effect on the user's next turn, on any of your processes. No restart. `hireWorkforce` registers a roster flow, `workforce-roster`, beside your worker flows. It carries four actions: `hire`, `fork`, `edit` and `fire`. Send them as you would any action, in a session @@ -53,8 +53,9 @@ const { hire, fork, edit, fire } = createWorkerHireBlocks(installation) await roster.sendAction("fork", { from: "researcher", id: "my-researcher" }, { sessionId }) ``` -The fork keeps a copy of the standard worker's instructions, and doesn't change when your -installation's files do. Fork again to pick up a change. The standard worker doesn't change, for +The fork copies what the worker it forks from runs with: its flow, its description, its own +instructions (a `WORKER.md` body), its team's instructions (the `TEAM.md` body), the names of its +skills, and its settings. The copy doesn't change when your installation's files do. Fork again to pick up a change. The standard worker doesn't change, for this user or anyone else. A fork starts with no conversations. The user's sessions with the worker they forked stay with @@ -70,6 +71,19 @@ session to talk to the worker on its new flow. `fire` deletes the row. Its past sessions stay readable to their owner. A new message to one is refused with the worker named as fired. Every process sees the fire on the next turn. +## When something is refused + +A refused write or turn changes nothing. The action's request ends `failed`, and its error says +why; your app reads it the way it reads any failed request. + +| What happened | The error | +| --- | --- | +| A hire under an id already on the user's roster | `"scribe" is already on your roster. Pick another id. Nothing was written.` | +| An edit of a standard worker (a hire, fork onto or fire of one is refused the same way) | `"researcher" is a standard worker, which nobody can edit. Fork it to get a worker of your own.` | +| A hire whose settings its flow refuses | `Worker "scribe" …the flow's own reason…. Nothing was written.` | +| A turn on a session whose worker moved to another flow | `Worker "scribe" now runs on flow "research", and this session runs on "agent". A session stays on the flow it was created on: start a new session to talk to it on "research".` | +| A turn on a session whose worker was fired | `Worker "scribe" was fired. This session stays readable; a new turn can't run as it.` | + ## Who can reach a worker Only its owner. A worker belongs to one user in one organization: another member can't list it, @@ -87,8 +101,7 @@ up to you: see [Where a worker's data lives](./workers-on-disk.md#where-a-worker ## After a hire, refresh the roster -Read the roster again after each turn. A turn that hires, forks or fires changes it, and nothing -tells you which tool ran, so you don't need to watch for a tool's name. +Read the roster again after any turn, since a turn may have hired, forked or fired. ```ts import { createWorkforceClient } from "@flow-state-dev/workforce/browser" diff --git a/apps/docs/docs/workforce/overview.md b/apps/docs/docs/workforce/overview.md index 27b23aff81..6a9565dcae 100644 --- a/apps/docs/docs/workforce/overview.md +++ b/apps/docs/docs/workforce/overview.md @@ -2,14 +2,14 @@ title: Workforce sidebar_position: 1 sidebar_label: Overview -description: Describe a roster of workers, hire them as addressable flow copies, and register what comes back. +description: Describe a roster of workers, run each on one shared copy of the flow it names, and talk to a worker in a session that names it. --- # Workforce -`@flow-state-dev/workforce` turns a roster of workers into configured, addressable copies of flows you already defined. Describe each worker (usually as a `WORKER.md`), hire the roster, and register the copies that come back. +`@flow-state-dev/workforce` runs a roster of workers on flows you already defined. A worker is a configuration: a `WORKER.md` your files declare, or one a user hires or forks for themselves. Each flow a worker names is registered once, as one shared copy, and every worker on it runs there. -A hired worker is a **seat**: a flow instance with its own id. You open a session against it the way you open one against any other flow. +A conversation with a worker is a session of its flow that names the worker when it is created. One session, one worker, for the session's whole life. ## Workforce or orchestration diff --git a/apps/docs/docs/workforce/workers-on-disk.md b/apps/docs/docs/workforce/workers-on-disk.md index 2880a46680..7f6a04898c 100644 --- a/apps/docs/docs/workforce/workers-on-disk.md +++ b/apps/docs/docs/workforce/workers-on-disk.md @@ -72,7 +72,7 @@ request into tasks, assign them, and report what came back. `description` is the only key the file itself requires. In a [routed mailbox](./mailboxes.md#routing-a-mailbox), it is also what the route reads to decide whether a post is this worker's. The file refuses `persona:`, `seatSkills:`, `seatTools:`, `seatPackages:`, `seatId:` and `teamInstructions:` outright. A seat's skills and the blocks it can reach come from where its folders sit, and its team's instructions from that team's [`TEAM.md`](#what-a-teammd-says). `flow` names which of your flow kinds this worker runs. Leave it out and the worker runs on [the built-in worker flow](./built-in-worker.md), which needs no flow of yours. -`resources:` is a list of the [documents](./documents-on-disk.md) this worker may touch, chosen from the ones its kind holds. Each entry is a document's [ref](./documents-on-disk.md#a-documents-ref), the name it gets from where its file sits. A ref on its own is read-only. `: rw` grants writes, and `: ro` spells the default out. Leave the key out and the worker reaches every document its kind installed, and writes the ones that allow writes; `resources: []` is how you say it gets none. +`resources:` is a list of the [documents](./documents-on-disk.md) this worker may touch, chosen from the ones the app passed to the installation as `documents`. Each entry is a document's [ref](./documents-on-disk.md#a-documents-ref), the name it gets from where its file sits. A ref on its own is read-only. `: rw` grants writes, and `: ro` spells the default out. Leave the key out and the worker reaches every document the app passed as `documents`, on the flow's shared copy, and writes the ones that allow writes; `resources: []` is how you say it gets none. Only documents are narrowed. The stores and boards its kind declares stay reachable and writable whatever the list says, and so do the resources the kind's own blocks declare. Where the documents come from is [below](#supplying-the-documents-a-seat-may-name). @@ -399,8 +399,7 @@ A worker flow must: - **Have one door.** Exactly one public action declares `userMessage` and takes `{ message }`, so an app can talk to any worker without knowing which flow it runs on. - **Declare the installation's session.** `session: installation.session()` gives every session a - readonly `workerId`, checked when the session is created. A flow without it is refused, because - its sessions would run no checked worker. Load the worker with `installation.resolveWorker` on + readonly `workerId`, checked when the session is created. A flow without it is refused. Load the worker with `installation.resolveWorker` on every turn: in the flow's `request.onStarted`, or in the block that reads it. - **Declare any resource with `writtenBy` through `sharedResource()`.** A resource that has a `writtenBy` field is declared with [`sharedResource()`](#sharing-something-from-a-worker), which @@ -529,7 +528,7 @@ What the refusals cover is what a **file** declares. No frontmatter may set `tea The two instruction settings stay apart. A worker's own text is never merged into its team's, so a kind can read one without the other. On the [built-in worker kind](./built-in-worker.md) both go into the prompt, the team's first and the worker's own last. That order is fixed, and it is an order rather than a ranking: nothing resolves a contradiction between the two, so a team rule and a worker rule that disagree are left to the model that reads them. -Every worker flow has that setting, because `workerConfigSchema()` declares it — so a worker's body always has somewhere to arrive, and no worker flow has to check for one. A flow whose schema will not take those settings is refused by `hireWorkforce` before anything is registered, whatever workers it holds: +Every worker flow has that setting, because `workerConfigSchema()` declares it — so a worker's body always has somewhere to arrive, and no worker flow has to check for one. A flow whose schema will not take those settings is refused by `hireWorkforce` before anything is registered: ``` hireWorkforce refused 1 worker flow ("intake"); nothing was hired: @@ -671,7 +670,8 @@ export const requestTriageFlow = workerFlow((installation) => { // The decision is the flow's graph: a router block picks the branch from the // request itself. `answer` is a generator; `escalate` hands off to a person. // The threshold is the worker's own setting, read from the worker this turn - // runs as: every worker on the flow shares one copy, and `ctx.flow.config`. + // runs as. Every worker on the flow shares one copy, so `ctx.flow.config` is + // the same for all of them. const triage = router({ name: "triage", inputSchema: requestSchema, @@ -793,8 +793,15 @@ make it the hook's active session. const workforce = useMemo(() => createWorkforceClient({ userId, baseUrl }), [userId, baseUrl]) const flow = useFlow({ flowKind: "agent" }) -const session = await workforce.ensureWorkerSession({ worker: "researcher" }) -flow.selectSession(session.id) +useEffect(() => { + let current = true + workforce.ensureWorkerSession({ worker: "researcher" }).then((session) => { + if (current) flow.selectSession(session.id) + }) + return () => { + current = false + } +}, [workforce]) ``` Tasks and messages your other workers hand to this one open sessions the same way, naming the diff --git a/packages/core/README.md b/packages/core/README.md index ab00a4ce78..30ebc0fc92 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -718,7 +718,7 @@ At run time a refused dispatch throws `DispatchRefusedError` (`code: "dispatch-r | `refused` | Meaning | |---|---| | `no-entry` | The addressed flow declares no entry at `(type, action)`. | -| `flow-not-found` | A `flowKind` names a flow instance this process has not registered, or an [owner-pinned instance](https://flow-state.dev/docs/workforce/durable-hire) the sending session may not open (one pinned to another organization, or to another user). The refusal is the same in both cases, so `flow-not-found` doesn't tell you which one you hit. | +| `flow-not-found` | A `flowKind` names a flow instance this process has not registered, or an instance registered with an owner pin the sending session may not open (one pinned to another organization, or to another user). The refusal is the same in both cases, so `flow-not-found` doesn't tell you which one you hit. | | `session-not-found` | An `id` names a session that does not exist, or that belongs to another principal or another tenant. | | `session-not-addressable` | An `id` (or `{ from: true }`) names a session on a flow other than the one addressed, or one bound to a different org. | | `key-occupied` | A `key` derived a child id already held by a record that is not this request's child. | diff --git a/packages/workforce/README.md b/packages/workforce/README.md index fc4259941a..4d95987c18 100644 --- a/packages/workforce/README.md +++ b/packages/workforce/README.md @@ -44,7 +44,7 @@ That record names no `flow:`, so it runs on the built-in `agent` flow and needs option. Its body becomes its instructions and steers its answers. Every worker on `agent` shares its one copy; a session names its worker when it is created, and each turn loads it. -The built-in keeps each worker's skills apart, per user, so two workers never share a drawer and +The built-in keeps each worker's skills apart, per user, so two workers never share skills and two people never share one worker's. To talk to it, find or start a session with the worker, then send to the flow it names: @@ -358,9 +358,8 @@ whose name breaks the naming rules. `createWorkerInstallation` takes the standard workers and the worker flows your app defined, and `hireWorkforce` gives back the flows to register: **one copy of each worker flow**, at the flow's own -kind, and the roster flow (`workforce-roster`). Every worker on a flow shares its one copy. Nothing -is minted per worker and nothing is pinned to an owner, so a hire, fork or fire while the app runs -is a write to the user's data, seen by every process on the next turn. +kind, and the roster flow (`workforce-roster`). Every worker on a flow shares its one copy. A hire, +fork or fire is a write to the user's data. Every process sees it on the next turn. ```ts import { createWorkerInstallation, hireWorkforce, type WorkerManifest } from "@flow-state-dev/workforce"; @@ -421,7 +420,8 @@ core's resource tools and any tool built on them. That is the flow's `resourceVi which the installation supplies: block code that names a document directly is not narrowed. **Absent and empty are different answers.** A worker whose file has no `resources:` key reaches every -document the app declared, and writes the ones that allow writes. `resources: []` is how a file +document the app passed to the installation as `documents`, on the flow's shared copy, and writes +the ones that allow writes. `resources: []` is how a file says a worker gets none. **Only documents are narrowed.** The stores, boards and anything else the flow declares stay @@ -471,8 +471,7 @@ list at all, an entry that is neither a ref nor a one-key `ref: mode` mapping, a matches, a ref naming a document the app declared but did not install on this worker's flow, a mode that is neither `ro` nor `rw`, the same ref twice, `rw` on a document whose own frontmatter says `writable: false`, a ref colliding with a name the kind's own blocks already declare, and a ref the -kind does declare at flow level while what it holds there is not the document the app passed — the -two cannot be told apart, so it is refused rather than guessed. +kind does declare at flow level while what it holds there is not the document the app passed. One more is checked on the worker's configuration rather than on the list: if a document the worker did **not** name is reachable anyway — because one of the flow's blocks declares that same @@ -610,7 +609,7 @@ worker. | --- | --- | | `uses` | Capabilities attached to every worker's answer generator. The skills binding stays first and is never displaced. A capability passed as a plain ref brings its own storage with it; one passed as a `(ctx) => refs` resolver brings none, so anything it needs has to be declared statically somewhere. | | `afterAnswer` | A block run after the answer as a side-chain. It receives the reply text as a string, it cannot change the answer, and a failure in it does not fail the turn. Absent, nothing runs after the answer. | -| `isolateUserState` | Forwarded to `defineFlow`. Keys the flow's user-scoped storage by its copy, apart from the person's other flows. Every worker on `agent` shares the one copy, so a person's workers on it still share one cell. Default `false`. | +| `isolateUserState` | Forwarded to `defineFlow`. Keys the flow's user-scoped storage by its copy, apart from the person's other flows. Every worker on `agent` shares the one copy, so a person's workers on it still share the same user-scoped storage. Default `false`. | **The tools fence.** A worker that writes a `tools:` line can call exactly the tools it lists, whatever it selected under `capabilities:`. The kind maps those names against the catalog and hands @@ -1611,9 +1610,8 @@ Mailboxes used to be called channels, everywhere, and the old names are not read ## Hire, fork and fire as tools A user's own workers are rows on their roster ([Workers as data](#workers-as-data)), written by the -roster flow's `hire`, `fork`, `edit` and `fire` actions, which `hireWorkforce` registers. Nothing -is registered per hire, nothing restarts, and nothing is read back at boot: every process reads the -row on the next turn. +roster flow's `hire`, `fork`, `edit` and `fire` actions, which `hireWorkforce` registers. A hire, +fork or fire is a write to the user's data. Every process sees it on the next turn. To let a worker hire or fire for the person it talks to, hand the same blocks to a model as tools. A catalog key is the tool's own name, so wrap each block in a sequencer that carries the name and @@ -1650,8 +1648,8 @@ worker the turn loaded (as `members:` lists it) as `author`, so the mailbox's me The worker comes from the session, never from the input or a setting. The line has `seatAuthored: true`, so `wakeMemberSeats` wakes nobody for it. A client `post` that sets `author` to the same worker id wakes hearing members. A turn that loaded no worker posts nothing. -`mailboxPostCapability` is the same tool for a flow copy minted for one worker, which signs with its -`seatId` setting. +Passing `mailboxPostCapability` to `defineAgentWorkerFlow({ installation })` puts this one in its +place. The tool returns once the post is handed to the mailbox, as `{ handedTo, note }`. A refusal by the mailbox, such as an author who is not a member, lands on the mailbox's request, not in the seat's @@ -2020,10 +2018,10 @@ restart. ## Workers as data -A worker is data rather than a registered copy: a row its owner holds in their user scope, or a -standard worker your files declare, run by one registered copy of the flow it names. A session -names its worker once, when it is created, and each turn loads it. Nothing mints a copy per worker -or sets a pin. +A worker is data: a row its owner holds in their user scope, or a standard worker your files +declare, run by one registered copy of the flow it names. A session names its worker once, when it +is created, and each turn loads it. A hire, fork or fire is a write to the user's data. Every +process sees it on the next turn. ```ts import { defineFlow } from "@flow-state-dev/core"; @@ -2100,7 +2098,8 @@ to a model as [tools](#hire-fork-and-fire-as-tools). - `hire({ id, flow?, description?, instructions?, skills?, settings? })` returns `{ id, flow }`; `flow` defaults to `agent`, and `settings` takes the keys a `WORKER.md` frontmatter accepts; - `fork({ from, id })` returns `{ id, flow }`, copying a standard worker's, or one of the user's - own, configuration and shared instructions; a later edit to the files doesn't reach the fork; + own, configuration: its flow, description, instructions, team instructions, skill names and + settings; a later edit to the files doesn't reach the fork; - `edit({ id, flow?, description?, instructions?, skills?, settings? })` returns `{ id, flow }`, replacing each field given; - `fire({ id })` returns `{ id }` and deletes the row. @@ -2281,7 +2280,7 @@ and `MailboxTranscriptLine`, the same values the root exports, and reaches no No | One skill name at more than one of a seat's levels | Collected in `readSeatSkills`'s `errors` as `kind: "duplicate-skill-name"`, keyed by the level the name was first seen at, with every colliding path on the entry's `paths`; the name is left out of `skills` | | `scope:` in a `SKILL.md` | Collected in `readSeatSkills`'s `errors` as `kind: "refused-scope-key"`, keyed by the skill's path | | Worker flow misses the contract | `hireWorkforce`, before anything is registered — a flow passed under a key that is not its own kind, a configuration it refuses by key or by value, or takes but rewrites (composing `workerConfigSchema()` is the fix), no door or two, no installation session, or a resource with `writtenBy` that `sharedResource()` didn't build. Collected: one error names every problem with every flow, and nothing is hired | -| Worker cannot run | For a standard worker, `hireWorkforce`; for a user's own worker, the `hire`, `fork` or `edit` that saves it, and its turn — an empty or whitespace-only `flow`, an unknown flow, a user's own worker naming a flow marked `standardOnly` (or naming none, when `agent` is marked), a duplicate standard id (`createWorkerInstallation`), a setting or body the flow never declared, a `tools:` name nothing registers for that seat, a registered block whose key and own `name` disagree, a block in a worker's own folder that declares a resource, a skill name reaching one seat from both the app's `skills` and its own folders, a `resources:` list the hire step cannot resolve (a `resources:` that is not a list, an entry that is neither a ref nor a one-key `ref: mode` mapping, a ref no document matches, a ref naming a document the app declared but did not install on this worker's flow, a mode other than `ro` or `rw`, the same ref twice, `rw` on a document declaring itself `writable: false`, a ref colliding with a name the kind's own blocks declare, a ref the kind declares at flow level while what it holds there is not that document, or the key itself with no `documents` passed), a document a seat did not name that its minted flow reaches anyway because one of the kind's blocks declares it, a `references:` list the hire step cannot resolve (a `references:` that is not a list, an entry that is not a ref, the same ref twice, or a ref naming a reference this seat cannot reach from its place in the tree — including every ref when no `references` map was passed), a seat id that names no place in the tree while its kind holds references, a reference the seat did not name that its minted flow reaches anyway, `instructions` given both in the frontmatter and as a body, a `packages:` list the hire step cannot resolve (not a list of names, a name no library in reach offers, or a name both its own folder and a library offer), a held package's block that clashes with another tool the seat can call, registers under a name other than its own, or declares a store, a package with blocks in its own folder that failed to load, or a `persona:`, `seatSkills:`, `seatTools:`, `seatPackages:`, `seatId:` or `teamInstructions:` key. Collected: one error names every bad worker | +| Worker cannot run | For a standard worker, `hireWorkforce`; for a user's own worker, the `hire`, `fork` or `edit` that saves it, and its turn — an empty or whitespace-only `flow`, an unknown flow, a user's own worker naming a flow marked `standardOnly` (or naming none, when `agent` is marked), a duplicate standard id (`createWorkerInstallation`), a setting or body the flow never declared, a `tools:` name nothing registers for that seat, a registered block whose key and own `name` disagree, a block in a worker's own folder that declares a resource, a skill name reaching one seat from both the app's `skills` and its own folders, a `resources:` list the hire step cannot resolve (a `resources:` that is not a list, an entry that is neither a ref nor a one-key `ref: mode` mapping, a ref no document matches, a ref naming a document the app declared but did not install on this worker's flow, a mode other than `ro` or `rw`, the same ref twice, `rw` on a document declaring itself `writable: false`, a ref colliding with a name the kind's own blocks declare, a ref the kind declares at flow level while what it holds there is not that document, or the key itself with no `documents` passed), a document a worker did not name that the worker's flow reaches anyway because one of the kind's blocks declares it, a `references:` list the hire step cannot resolve (a `references:` that is not a list, an entry that is not a ref, the same ref twice, or a ref naming a reference this seat cannot reach from its place in the tree — including every ref when no `references` map was passed), a seat id that names no place in the tree while its kind holds references, a reference the worker did not name that the worker's flow reaches anyway, `instructions` given both in the frontmatter and as a body, a `packages:` list the hire step cannot resolve (not a list of names, a name no library in reach offers, or a name both its own folder and a library offer), a held package's block that clashes with another tool the seat can call, registers under a name other than its own, or declares a store, a package with blocks in its own folder that failed to load, or a `persona:`, `seatSkills:`, `seatTools:`, `seatPackages:`, `seatId:` or `teamInstructions:` key. Collected: one error names every bad worker | | A roster write refused | The `hire`, `fork`, `edit` or `fire` block: a standard worker's id (suggesting a fork), an id already on the caller's roster, a worker that isn't the caller's, a flow that isn't a worker flow or is kept for standard workers, or a configuration its flow refuses. Nothing is written. | | A turn on a session whose worker can't run | `resolveWorker` throws `WorkerTurnRefusedError`, naming the worker: fired, moved to another flow, a name that no longer resolves, or a flow now kept for standard workers. Nothing is written; the session stays readable. | | Package folder fails to load | Collected in `readPackagesDirectory`'s and `readWorkforce`'s `packageErrors` as `kind: "package-load-failed"` (a symlinked or badly named folder, or a missing, unreadable or malformed `PACKAGE.md`), `"refused-entry"` (a file in `packages/`, or a documents, skills or packages folder or a symlink inside a package), or `"unreadable-slot"`, keyed by the path. The package is left out whole | From 4f477d81e3dbcef2881b1a4770784a11eac12e81 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 11:55:46 +0000 Subject: [PATCH 12/12] docs(workforce): long-term memory on agent is per person; skills and working memory per worker (FIX-1788 P4) The product owner's call on BR-23: on the shared agent copy, long-term memory (episodic, semantic, digest) is kept per person and shared by that person's workers, never across people; skills are kept per worker and working memory per conversation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV --- apps/docs/docs/workforce/built-in-worker.md | 16 +++++++++++----- apps/docs/docs/workforce/durable-hire.md | 8 +++++--- apps/docs/docs/workforce/workers-on-disk.md | 5 +++-- packages/workforce/README.md | 7 ++++--- 4 files changed, 23 insertions(+), 13 deletions(-) diff --git a/apps/docs/docs/workforce/built-in-worker.md b/apps/docs/docs/workforce/built-in-worker.md index 341a4cc2a9..3d2a448cf0 100644 --- a/apps/docs/docs/workforce/built-in-worker.md +++ b/apps/docs/docs/workforce/built-in-worker.md @@ -116,7 +116,7 @@ A board hands tasks to standard workers only: whoever drains it opens the task's ## What a worker keeps -A conversation keeps its recent turns, each worker keeps its own skills for each person, and memory, once you add it, is kept per person. +A conversation keeps its recent turns, each worker keeps its own skills for each person, and long-term memory, once you add it, is kept per person and shared by that person's workers. ![A conversation holds recent turns, a worker's skills are kept per person, and memory is kept per person](./built-in-worker-memory.svg) @@ -276,10 +276,16 @@ tools: [memory/recall] ### Whose memory it is -Memory is stored in the person's user scope, in the organization they're signed in to, so it never -reaches another person or another organization. Every worker on `agent` runs on one shared copy, -so one person's workers on it share that memory: tell one of them something and another may -recall it. Their skills are the exception, kept apart per worker by the built-in itself. +Every worker on `agent` runs on one shared copy, so what a worker remembers depends on the tier: + +- **Long-term memory** (episodic, semantic and digest) is kept per person, in their user scope in + the organization they're signed in to. One person's workers on `agent` share it: tell one of + them something and another may recall it. It never crosses people: another person's workers + can't read it. That is at the tiers' default `user` scope; a tier you set to `org` scope is + shared with the whole organization. +- **Working memory** is kept per conversation. A conversation runs one worker for its whole life, + so it is that worker's own. +- **Skills** are kept per worker, for each person, by the built-in itself. `isolateUserState: true` keeps the `agent` flow's user-scoped storage apart from every other flow's. It doesn't separate workers on `agent`: they share the one copy it keys on. diff --git a/apps/docs/docs/workforce/durable-hire.md b/apps/docs/docs/workforce/durable-hire.md index 6211bbc9bd..630cb23a6d 100644 --- a/apps/docs/docs/workforce/durable-hire.md +++ b/apps/docs/docs/workforce/durable-hire.md @@ -95,9 +95,11 @@ organizations has a separate roster in each. Each worker the user hires or forks is one row in their user scope at `workforce/workers/`. A standard worker isn't stored: it is read from your files each time, so a deploy that changes a -file changes it for everyone. On the built-in `agent` flow, what a worker remembers is kept per -worker, so two of one user's workers never read each other's notes. On a flow you write, that is -up to you: see [Where a worker's data lives](./workers-on-disk.md#where-a-workers-data-lives). +file changes it for everyone. On the built-in `agent` flow, each worker has its own skills, and +its own working memory in each conversation. Long-term memory, if your app adds it, is kept per +person: one person's workers on `agent` share it, and another person's workers can't read it. On a +flow you write, that is up to you: see +[Where a worker's data lives](./workers-on-disk.md#where-a-workers-data-lives). ## After a hire, refresh the roster diff --git a/apps/docs/docs/workforce/workers-on-disk.md b/apps/docs/docs/workforce/workers-on-disk.md index 7f6a04898c..4ae0b8bddb 100644 --- a/apps/docs/docs/workforce/workers-on-disk.md +++ b/apps/docs/docs/workforce/workers-on-disk.md @@ -266,8 +266,9 @@ one for yourself, [fork it](./durable-hire.md#forking-a-worker). Each flow a worker names runs as one copy, shared by every worker that names it. A hundred workers on `agent` are one registered flow, not a hundred. What makes them different is their -configuration, which the flow reads on each turn, and, on `agent`, their memory, which is kept per -worker. +configuration, which the flow reads on each turn, and, on `agent`, their skills, which are kept +per worker. Long-term memory on `agent` is kept per person and shared by that person's workers on +it; it never reaches another person. Hand the records to an installation, then ask `hireWorkforce` for the flows to register: diff --git a/packages/workforce/README.md b/packages/workforce/README.md index 4d95987c18..7da25ae748 100644 --- a/packages/workforce/README.md +++ b/packages/workforce/README.md @@ -691,9 +691,10 @@ select it (`capabilities: { memory: [recall] }`) with no `tools:` line. A worker lists `memory/recall` in its `tools:`. The key has to match the tool's own name; a catalog key that doesn't is refused when the kind is built. -Memory is kept in the person's user scope, so it never reaches another person or organization. Every -worker on `agent` shares the one copy, so one person's workers on it share what it remembers; only -the skills drawer is kept per worker. Keeping a capability's data apart per worker is the app's, +Every worker on `agent` shares the one copy. Long-term memory (episodic, semantic and digest) is +kept in the person's user scope, so one person's workers on `agent` share it, and it never reaches +another person or organization. Working memory is kept per conversation, and each conversation runs +one worker. Skills are kept per worker. Keeping a capability's data apart per worker is the app's, as for any data a worker flow keeps per user ([Workers as data](#workers-as-data)). Every problem with a standard worker is a startup misconfiguration: `hireWorkforce` collects them