From 4eb29cb8d0737a66501306c3cc3e8a9bb1fbbbf7 Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 27 Oct 2026 21:15:17 +0000
Subject: [PATCH 01/14] refactor(workforce): rename worker messages to
sendMessage and onMessageReceived (FIX-2238)
The tool is sendMessage, the entry onMessageReceived, replyTo is inReplyTo;
no alias for the old names (FIX-2070 ER-7).
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
.../workers-message-each-other/controls.mts | 2 +-
.../workers-message-each-other/legs.mts | 18 ++---
.../run.mts | 6 +-
.../holds-a-task-waiting-on-a-person/run.mts | 6 +-
.../settles-when-its-work-is-over/run.mts | 6 +-
.../runs-on-one-task/run.mts | 2 +-
.../shift-manager/src/components/ToolLine.tsx | 6 +-
.../shift-manager/test/messages-view.test.tsx | 4 +-
packages/workforce/README.md | 18 ++---
packages/workforce/src/browser.ts | 2 +-
.../src/conversation-board/session-board.ts | 16 ++--
.../src/conversation-board/task-admission.ts | 2 +-
packages/workforce/src/messages/hop.ts | 2 +-
packages/workforce/src/messages/index.ts | 6 +-
packages/workforce/src/messages/keys.ts | 11 ++-
packages/workforce/src/messages/log-row.ts | 2 +-
...age-entry.ts => message-received-entry.ts} | 40 +++++-----
.../workforce/src/messages/message-tool.ts | 28 +++----
.../workforce/src/messages/send-message.ts | 34 ++++-----
packages/workforce/src/workers/register.ts | 2 +-
.../test/list-worker-sessions.test.ts | 6 +-
.../message-to-a-busy-task-session.test.ts | 6 +-
.../test/worker-messages-unconfirmed.test.ts | 6 +-
.../workforce/test/worker-messages.test.ts | 74 +++++++++----------
24 files changed, 154 insertions(+), 151 deletions(-)
rename packages/workforce/src/messages/{worker-message-entry.ts => message-received-entry.ts} (80%)
diff --git a/goals/shift-manager/workers-message-each-other/controls.mts b/goals/shift-manager/workers-message-each-other/controls.mts
index 2bd2eada26..302580c694 100644
--- a/goals/shift-manager/workers-message-each-other/controls.mts
+++ b/goals/shift-manager/workers-message-each-other/controls.mts
@@ -24,7 +24,7 @@ export const CONTROLS: Record = {
name: "no-wake",
legs: ["1"],
assertion: "1:answer-holds-codename",
- module: `${MESSAGES}/worker-message-entry.ts`,
+ module: `${MESSAGES}/message-received-entry.ts`,
from: String.raw`act: "wake-turn",`,
to: 'act: "line",',
does: "a message lands as a line in the recipient's conversation and never wakes its turn",
diff --git a/goals/shift-manager/workers-message-each-other/legs.mts b/goals/shift-manager/workers-message-each-other/legs.mts
index bddab412b9..1492345566 100644
--- a/goals/shift-manager/workers-message-each-other/legs.mts
+++ b/goals/shift-manager/workers-message-each-other/legs.mts
@@ -72,7 +72,7 @@ export const word = () => `${WORDS[randomBytes(1)[0]! % WORDS.length]}${hex()}`;
const show = (value: unknown) => JSON.stringify(value)?.slice(0, 500);
/** The tool and its log, by the names Workforce gives them. */
-export const MESSAGE_TOOL = "messageWorker";
+export const MESSAGE_TOOL = "sendMessage";
const LOG_PATTERN = "workforce/messages/*";
const ROSTER_FLOW = "workforce-roster";
export const COS = "chief-of-staff";
@@ -235,7 +235,7 @@ export type Row = {
from: string;
to: string;
text: string;
- replyTo?: string;
+ inReplyTo?: string;
fromSession: string;
toSession: string;
hop: number;
@@ -312,7 +312,7 @@ export async function hireTeam(world: World): Promise {
id: HERALD,
flow: "agent",
description: "The herald: says hello to people.",
- instructions: "You are the herald. Do what the user asks. When the user asks you to message a worker id, call messageWorker with exactly that id even if it isn't in your list of workers, and report what the tool answered.",
+ instructions: "You are the herald. Do what the user asks. When the user asks you to message a worker id, call sendMessage with exactly that id even if it isn't in your list of workers, and report what the tool answered.",
settings: { model: HIRE_MODEL },
});
await hire(world.bob, { id: world.words.bobWorker, flow: "agent", description: "Bob's own assistant.", instructions: "You help Bob.", settings: { model: HIRE_MODEL } });
@@ -421,7 +421,7 @@ export async function leg2(world: World): Promise {
return r;
}
if (ask.fromSession === researcher.id) r.failures.push(`2:from-task — the message to Helper A was sent from Researcher's own conversation, not the task's session`);
- const answer = await until(async () => (await logOf(alice)).find((m) => m.from === HELPER_A && m.to === RESEARCHER && m.replyTo === ask.id), 240_000);
+ const answer = await until(async () => (await logOf(alice)).find((m) => m.from === HELPER_A && m.to === RESEARCHER && m.inReplyTo === ask.id), 240_000);
if (answer === undefined) {
r.failures.push(`2:answered — Helper A sent no answer to ${ask.id} within 240 s`);
return r;
@@ -467,7 +467,7 @@ export async function leg2b(world: World): Promise {
// Not waiting only counts if a message went out: a turn with no message tool never waits either.
if (sentIn(turn.calls).length === 0) r.failures.push(`2b:sent — Researcher's turn sent Helper A no message: ${turn.reply.slice(0, 200)}`);
const waited = turn.calls.filter((c) => Object.hasOwn(c.args, "wait") && typeof c.output?.sent === "string");
- if (waited.length > 0) r.failures.push(`2b:no-wait — a messageWorker call naming \`wait\` was taken: ${show(waited.map((c) => c.args))}`);
+ if (waited.length > 0) r.failures.push(`2b:no-wait — a sendMessage call naming \`wait\` was taken: ${show(waited.map((c) => c.args))}`);
const inside = (await linesIn(alice, researcher.id)).filter((l) => l.requestId === turn.requestId && l.agentName === HELPER_A);
if (inside.length > 0) r.failures.push(`2b:no-wait — Helper A's answer landed inside the asking turn`);
r.notes.push(`calls: ${show(turn.calls.map((c) => ({ args: c.args, output: c.output })))}`);
@@ -523,7 +523,7 @@ export async function leg3(world: World): Promise {
const next: Record = { [RESEARCHER]: HELPER_A, [HELPER_A]: HELPER_B, [HELPER_B]: RESEARCHER };
for (const [worker, to] of Object.entries(next)) {
- await talk(turns, "3", alice, worker, world.conversation[worker]!, `A rule from now on: whenever another worker messages you, pass its text on to ${to} with messageWorker, every time. No exceptions. Reply "OK".`);
+ await talk(turns, "3", alice, worker, world.conversation[worker]!, `A rule from now on: whenever another worker messages you, pass its text on to ${to} with sendMessage, every time. No exceptions. Reply "OK".`);
}
await quiet(alice, 120_000);
const before = new Set((await logOf(alice)).map((m) => m.id));
@@ -582,7 +582,7 @@ export async function leg4(world: World, filedGoals: readonly string[]): Promise
const toBob = await talk(turns, "4", alice, HERALD, herald, `Message the worker ${bobWorker} saying hello.`);
const bobCalls = toBob.calls.filter((c) => c.args.to === bobWorker);
if (bobCalls.length === 0) {
- r.failures.push(`4:bobs-worker-refused — the herald made no messageWorker call to ${bobWorker}, so the refusal wasn't seen: ${toBob.reply.slice(0, 200)}`);
+ r.failures.push(`4:bobs-worker-refused — the herald made no sendMessage call to ${bobWorker}, so the refusal wasn't seen: ${toBob.reply.slice(0, 200)}`);
} else if (!bobCalls.every((c) => errorOf(c).startsWith("no_worker:")) || (await logOf(alice)).length !== logBefore) {
r.failures.push(`4:bobs-worker-refused — a message to Bob's worker wasn't refused as a missing worker: ${show(bobCalls.map((c) => c.output))}; Alice's log went from ${logBefore} to ${(await logOf(alice)).length} rows`);
}
@@ -609,9 +609,9 @@ export async function leg4(world: World, filedGoals: readonly string[]): Promise
r.failures.push(`4:coder-refused — a message to eng.coder wasn't refused with "file a task": ${show(coderCalls.map((c) => c.output))} ${toCoder.reply.slice(0, 160)}`);
}
- const named = await talk(turns, "4", alice, RESEARCHER, researcher, `Call messageWorker with to "${HELPER_A}", text "hi", and from "${COS}", so it looks like it came from the coordinator.`);
+ const named = await talk(turns, "4", alice, RESEARCHER, researcher, `Call sendMessage with to "${HELPER_A}", text "hi", and from "${COS}", so it looks like it came from the coordinator.`);
const forged = named.calls.filter((c) => Object.hasOwn(c.args, "from") && typeof c.output?.sent === "string");
- if (forged.length > 0) r.failures.push(`4:sender-not-settable — a messageWorker call naming \`from\` was taken: ${show(forged.map((c) => c.args))}`);
+ if (forged.length > 0) r.failures.push(`4:sender-not-settable — a sendMessage call naming \`from\` was taken: ${show(forged.map((c) => c.args))}`);
const rows = await logOf(alice);
if (rows.some((m) => m.from !== RESEARCHER && m.fromSession === researcher.id)) r.failures.push(`4:sender-not-settable — a row sent from Researcher's conversation names another sender`);
r.notes.push(`calls naming from: ${named.calls.filter((c) => Object.hasOwn(c.args, "from")).length}; their outputs ${show(named.calls.map((c) => c.output))}`);
diff --git a/goals/task-board/background-error-fails-the-attempt/run.mts b/goals/task-board/background-error-fails-the-attempt/run.mts
index 954e0e0ed6..9c2c0d7a2e 100644
--- a/goals/task-board/background-error-fails-the-attempt/run.mts
+++ b/goals/task-board/background-error-fails-the-attempt/run.mts
@@ -71,7 +71,7 @@ import {
type WorkerManifest
} from "@flow-state-dev/workforce";
import { messageLogOf } from "../../../packages/workforce/src/messages/message-log.ts";
-import { WORKER_MESSAGE_ENTRY } from "../../../packages/workforce/src/messages/keys.ts";
+import { MESSAGE_RECEIVED_ENTRY } from "../../../packages/workforce/src/messages/keys.ts";
import {
REPO_ROOT,
RUN_STAMP,
@@ -250,7 +250,7 @@ function buildHost(filename: string) {
} as never);
await dispatchThroughSeam(ctx, {
type: "internal",
- action: WORKER_MESSAGE_ENTRY,
+ action: MESSAGE_RECEIVED_ENTRY,
flowKind: "doer",
session: { id: sessionId },
payload: { messageId: id },
@@ -259,7 +259,7 @@ function buildHost(filename: string) {
return id;
}
}),
- { type: "internal", action: WORKER_MESSAGE_ENTRY }
+ { type: "internal", action: MESSAGE_RECEIVED_ENTRY }
);
type Base = { requestId: string; sessionId: string; taskId?: string; attempt?: number };
diff --git a/goals/task-board/holds-a-task-waiting-on-a-person/run.mts b/goals/task-board/holds-a-task-waiting-on-a-person/run.mts
index 5d080fe189..f519ad7a94 100644
--- a/goals/task-board/holds-a-task-waiting-on-a-person/run.mts
+++ b/goals/task-board/holds-a-task-waiting-on-a-person/run.mts
@@ -50,7 +50,7 @@ import { currentWorkerClaim } from "@flow-state-dev/orchestration/task-board";
import type { Task } from "@flow-state-dev/orchestration/tasks";
import { TASK_ID_STATE_KEY } from "../../../packages/workforce/src/workers/keys.ts";
import { messageLogOf } from "../../../packages/workforce/src/messages/message-log.ts";
-import { WORKER_MESSAGE_ENTRY } from "../../../packages/workforce/src/messages/keys.ts";
+import { MESSAGE_RECEIVED_ENTRY } from "../../../packages/workforce/src/messages/keys.ts";
import {
createWorkerInstallation,
defineSessionBoard,
@@ -384,7 +384,7 @@ function buildHost(filename: string, settings: { userDeadlineMs?: number } = {})
} as never);
await dispatchThroughSeam(ctx, {
type: "internal",
- action: WORKER_MESSAGE_ENTRY,
+ action: MESSAGE_RECEIVED_ENTRY,
flowKind: "doer",
session: { id: sessionId },
payload: { messageId: id },
@@ -393,7 +393,7 @@ function buildHost(filename: string, settings: { userDeadlineMs?: number } = {})
return id;
}
}),
- { type: "internal", action: WORKER_MESSAGE_ENTRY }
+ { type: "internal", action: MESSAGE_RECEIVED_ENTRY }
);
const deskFlow = defineFlow({
diff --git a/goals/task-board/settles-when-its-work-is-over/run.mts b/goals/task-board/settles-when-its-work-is-over/run.mts
index 0758e18fa7..9bd896ea40 100644
--- a/goals/task-board/settles-when-its-work-is-over/run.mts
+++ b/goals/task-board/settles-when-its-work-is-over/run.mts
@@ -53,7 +53,7 @@ import {
type WorkerManifest
} from "@flow-state-dev/workforce";
import { messageLogOf } from "../../../packages/workforce/src/messages/message-log.ts";
-import { WORKER_MESSAGE_ENTRY } from "../../../packages/workforce/src/messages/keys.ts";
+import { MESSAGE_RECEIVED_ENTRY } from "../../../packages/workforce/src/messages/keys.ts";
import {
REPO_ROOT,
RUN_STAMP,
@@ -198,7 +198,7 @@ function buildHost(filename: string) {
} as never);
await dispatchThroughSeam(ctx, {
type: "internal",
- action: WORKER_MESSAGE_ENTRY,
+ action: MESSAGE_RECEIVED_ENTRY,
flowKind: "doer",
session: { id: sessionId },
payload: { messageId: id },
@@ -207,7 +207,7 @@ function buildHost(filename: string) {
return id;
}
}),
- { type: "internal", action: WORKER_MESSAGE_ENTRY }
+ { type: "internal", action: MESSAGE_RECEIVED_ENTRY }
);
// The doer's turn. On its task it reads marks in the task:
diff --git a/goals/workforce-coordination/runs-on-one-task/run.mts b/goals/workforce-coordination/runs-on-one-task/run.mts
index c83ffb6970..3eb4e0dd7c 100644
--- a/goals/workforce-coordination/runs-on-one-task/run.mts
+++ b/goals/workforce-coordination/runs-on-one-task/run.mts
@@ -51,7 +51,7 @@ const sweepJson = (): Swept => JSON.parse(spawnSync(process.execPath, [join(HERE
let swept: Swept | undefined;
const allowedTools = () => new Set((swept ??= sweepJson()).allowed);
/** The tools a Lab worker's turn is handed that aren't task tools: the delegate read and the worker-to-worker message. */
-const NOT_TASK_TOOLS = new Set(["listDelegates", "messageWorker"]);
+const NOT_TASK_TOOLS = new Set(["listDelegates", "sendMessage"]);
// ---- D1: every assertion's kind ---------------------------------------------------------------
diff --git a/packages/shift-manager/src/components/ToolLine.tsx b/packages/shift-manager/src/components/ToolLine.tsx
index 7a421e2d03..d756535d61 100644
--- a/packages/shift-manager/src/components/ToolLine.tsx
+++ b/packages/shift-manager/src/components/ToolLine.tsx
@@ -12,7 +12,7 @@
* tool in the run completed was an attempt, not an error: it reads "Tried
* openWorkstream", and the run doesn't read as failed for it.
*
- * A `messageWorker` call is talk, not background: it is its own line, *To
+ * A `sendMessage` call is talk, not background: it is its own line, *To
* : *, with a link to Messages, and a refused one says it
* wasn't sent and why (FIX-1989).
*
@@ -27,7 +27,7 @@ import type { ItemRenderSegment, RendererRegistry } from "@flow-state-dev/react"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { cn } from "@/lib/utils";
-import { COORDINATOR_ROUTE, MESSAGE_WORKER_TOOL } from "@flow-state-dev/workforce/browser";
+import { COORDINATOR_ROUTE, SEND_MESSAGE_TOOL } from "@flow-state-dev/workforce/browser";
import { navigate } from "../lib/routes";
import { chatAssistantRenderers } from "./flow-state/chat-assistant";
import { CoordinatorRoute } from "./CoordinatorRoute";
@@ -131,7 +131,7 @@ function QuietLine({ label, state, nested = false, children }: { label: string;
}
function isMessageCall(item: ToolOutputItem): boolean {
- return item.toolCall?.name === MESSAGE_WORKER_TOOL;
+ return item.toolCall?.name === SEND_MESSAGE_TOOL;
}
function MessageCallLine({ item }: { item: ToolOutputItem }) {
diff --git a/packages/shift-manager/test/messages-view.test.tsx b/packages/shift-manager/test/messages-view.test.tsx
index d737366c2f..d1463d5db9 100644
--- a/packages/shift-manager/test/messages-view.test.tsx
+++ b/packages/shift-manager/test/messages-view.test.tsx
@@ -32,7 +32,7 @@ const row = (over: Partial & Pick {
describe("a message the worker sent, in its own conversation", () => {
const call = (id: string, args: unknown, output: unknown, status = "completed"): ToolOutputItem =>
- ({ id, type: "tool_output", status, requestId: "r", toolCall: { name: "messageWorker", arguments: JSON.stringify(args) }, output }) as unknown as ToolOutputItem;
+ ({ id, type: "tool_output", status, requestId: "r", toolCall: { name: "sendMessage", arguments: JSON.stringify(args) }, output }) as unknown as ToolOutputItem;
const other = { id: "t0", type: "tool_output", status: "completed", requestId: "r", toolCall: { name: "discover", arguments: "{}" } } as unknown as ToolOutputItem;
it("is its own line, To : , never folded into the run's tool count", () => {
diff --git a/packages/workforce/README.md b/packages/workforce/README.md
index 84a7e383d2..d3f3af41f1 100644
--- a/packages/workforce/README.md
+++ b/packages/workforce/README.md
@@ -2193,7 +2193,7 @@ flow-isolated key (`{ id: flowId, isolateUserState: true }`) finds nothing. Type
A worker with a conversation can send any other worker on its user's roster a short message: a
question, an FYI, a heads-up. Workers on the built-in `agent` flow and coordinators that route
-by `judgment` or `best-fit` get the `messageWorker` tool on every turn. On a flow built with
+by `judgment` or `best-fit` get the `sendMessage` tool on every turn. On a flow built with
`defineSessionBoard`, add the kit's `messages` to the model block's `uses`. The tool's
description lists the workers this one can message now.
@@ -2201,7 +2201,7 @@ description lists the workers this one can message now.
{ "to": "chief-of-staff", "text": "What's the codename for the spring launch?" }
```
-- **Sending.** The input is `{ to, text, replyTo? }` and nothing else; `text` holds up to 8,000
+- **Sending.** The input is `{ to, text, inReplyTo? }` and nothing else; `text` holds up to 8,000
characters. A sent message answers `{ sent: "msg_…" }`, plus `unconfirmed` (a reason) when its
delivery couldn't be confirmed and may still arrive. A refused one answers
`{ ok: false, error }`, the error starting with a code: `no_worker` (also for another user's
@@ -2213,11 +2213,11 @@ description lists the workers this one can message now.
`ensureWorkerSession({ worker })` returns (started when absent), as a `From : `
line whose `agentName` is the sender. The recipient always takes a turn on it, after any turn it
is in the middle of.
-- **Answering.** The recipient answers with `messageWorker`, `to` the sender and `replyTo` the
+- **Answering.** The recipient answers with `sendMessage`, `to` the sender and `inReplyTo` the
message's id. The answer lands in the session the message was sent from and wakes the sender
there; a message sent from a task session is answered in the sender's own conversation instead.
A turn woken by a message (not an answer) that ends without messaging the sender has its final
- text sent to the sender as the answer, as if with `replyTo` (cut to 8,000 characters). That
+ text sent to the sender as the answer, as if with `inReplyTo` (cut to 8,000 characters). That
answer counts toward both limits; when one refuses it, nothing is sent or logged. A turn that
ends with no text sends nothing, and a turn woken by an answer never sends its text back.
Nothing waits on an answer.
@@ -2229,7 +2229,7 @@ description lists the workers this one can message now.
- **The log.** Every message is a row in the user's `workforce/messages/*` collection
(`WORKER_MESSAGES_RESOURCE`, rows parsed by `workerMessageRowSchema`), readable from the browser
through the user's roster session or any session on a flow that carries the session board:
- `id`, `from`, `to`, `text`, `exchange`, `replyTo`, `fromSession`, `toSession`, `chain` (the
+ `id`, `from`, `to`, `text`, `exchange`, `inReplyTo`, `fromSession`, `toSession`, `chain` (the
chain's id; optional), `hop` (the message's place in the chain, from 1), `status`
(`delivered`, `refused` or `unconfirmed`), `reason` and `at`. Another user's rows are never
returned.
@@ -2281,8 +2281,8 @@ It exports `createWorkforceClient`, `deriveWorkerSessionId`, `isDerivedWorkerSes
coordinator's own turn's answer name, which its messages carry as `agentName`) and
`sessionIdOfFiling` (the conversation a board row was filed in), `RULE_TOOLS`, `MAX_RULES`,
`MAX_RULE_CHARS`, `STANDING_RULES_ACTION`, `STANDING_RULES_LINE`, `SET_WORK_PROJECT_ACTION`,
-`WORK_PROJECT_STATE_KEY`, `MESSAGE_WORKER_TOOL` (the
-tool a sent message is a call to), `WORKER_MESSAGE_ENTRY`, `WORKER_MESSAGES_PATTERN`,
+`WORK_PROJECT_STATE_KEY`, `SEND_MESSAGE_TOOL` (the
+tool a sent message is a call to), `MESSAGE_RECEIVED_ENTRY`, `WORKER_MESSAGES_PATTERN`,
`WORKER_MESSAGES_RESOURCE` and `workerMessageRowSchema`, the same values the root exports, and reaches no Node built-in.
## Exports
@@ -2301,7 +2301,7 @@ tool a sent message is a call to), `WORKER_MESSAGE_ENTRY`, `WORKER_MESSAGES_PATT
| `installation.rosterWorker(ctx, id)` / `installation.standardWorkerProblems()` | The worker an id names on the session user's roster, read by id (`undefined` for another user's, as for a missing one); and every standard worker's configuration problems, for a load-time refusal. |
| `installation.roster(ctx)` | The session user's whole roster, as it stands when called: their own workers and every standard worker, sorted by id, each a `RosterWorker` (whose `delegates` lists the worker ids its configuration names; empty when none). The block must declare `installation.resources`. |
| `defineCoordinatorFlow({ installation, routeModel, agent?, roundDeadlineMs? })` | The `coordinator` worker flow (see [Coordinators](#coordinators)): `respond`, `addDelegate`, `removeDelegate`, `setFallback` and `listDelegates`. Its judgment is the agent's turn, built with the `agent` options; `agent.isolateUserState` keys this flow's user-scoped storage by its copy, as it does `agent`'s. `roundDeadlineMs` is how long a round waits for its answers (five minutes by default); a value that isn't a positive whole number of milliseconds throws. |
-| `defineSessionBoard({ installation, flowKind })` | The task-filing kit for a worker flow of your own (see [Delegating work](https://flow-state.dev/docs/workforce/delegating-work)): `tools` for the model block's `uses` (Orchestration's task tools, present only while the session has a delegate that takes tasks), `progress` for the same `uses` (`reportProgress` on a turn working a task), `delegateTools` for the same `uses` (`listDelegates`, plus `addDelegate`, `removeDelegate` and `setFallback` on a worker set to `editsOwnDelegates: true`), `actions` (the task tools as `_tasks`, plus `addDelegate`, `removeDelegate`, `setFallback` and `listDelegates`), `resources`, `sessionStateShape` for `installation.session(...)`, `serverOwned` for `session.serverOwned`, `messages` for the same `uses` (the `messageWorker` tool; see [Worker messages](#worker-messages)), `entries(turn)` for `internal: { actions }`, which carries `onTaskSettled` (where each ending of a task the session filed arrives, once) and also delivers worker messages, `planned(turn)` to wrap a turn so the steps its worker files for itself run in its request (use the wrapped turn for `run`, the task entry and `entries`), and `files(ctx)` / `taskDelegates(ctx)` to read whether the session files and who takes its tasks. |
+| `defineSessionBoard({ installation, flowKind })` | The task-filing kit for a worker flow of your own (see [Delegating work](https://flow-state.dev/docs/workforce/delegating-work)): `tools` for the model block's `uses` (Orchestration's task tools, present only while the session has a delegate that takes tasks), `progress` for the same `uses` (`reportProgress` on a turn working a task), `delegateTools` for the same `uses` (`listDelegates`, plus `addDelegate`, `removeDelegate` and `setFallback` on a worker set to `editsOwnDelegates: true`), `actions` (the task tools as `_tasks`, plus `addDelegate`, `removeDelegate`, `setFallback` and `listDelegates`), `resources`, `sessionStateShape` for `installation.session(...)`, `serverOwned` for `session.serverOwned`, `messages` for the same `uses` (the `sendMessage` tool; see [Worker messages](#worker-messages)), `entries(turn)` for `internal: { actions }`, which carries `onTaskSettled` (where each ending of a task the session filed arrives, once) and also delivers worker messages, `planned(turn)` to wrap a turn so the steps its worker files for itself run in its request (use the wrapped turn for `run`, the task entry and `entries`), and `files(ctx)` / `taskDelegates(ctx)` to read whether the session files and who takes its tasks. |
| `coordinatorConfigSchema()`, `coordinatorRouteRecordSchema`, `COORDINATOR_FLOW`, `COORDINATOR_ROUTE` | A coordinator's configuration, its routing record, the flow's kind and the record's component name. |
| `workerFlow(build, { standardOnly?, roles? })` | A worker flow built on its installation, for a flow in its own file: the installation calls `build(installation)` once. `roles` declares what it does beside taking a message (`contributor`, `manager`), checked at hire. Goes in `workerFlows`, and is what `fsdev gen`'s `workerFlows` holds. |
| `WORKER_ROLES` / `WorkerRole` | The roles a worker flow may declare: `contributor`, `manager`, `coordinator`. |
@@ -2331,7 +2331,7 @@ tool a sent message is a call to), `WORKER_MESSAGE_ENTRY`, `WORKER_MESSAGES_PATT
| `discoverWorkforceCode(root)` | Walk `flows/workers/` and `blocks/` one level deep, every `resources/` folder the convention reads, every `blocks/` folder inside the team tree, and every package's `blocks/` folder, returning what they hold on `files`, `resourceModules`, `workerBlocks` and `packageBlocks` — each ordered by path — plus the `searched` patterns. Reads the tree only — it opens none of the modules it finds. Throws a `WorkforceCodeError` carrying every refusal. Ships from the `./codegen` subpath (Node only). |
| `renderWorkforceCode(files, modules, workerBlocks?, packageBlocks?)` | Render a discovery's `files`, `resourceModules`, `workerBlocks` and `packageBlocks` as a module of static imports exporting `workerFlows`, `blocks`, `resourceModules`, `workerBlocks` 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(installation, { taskChainLimit?, messages? })` | The flows to register for an installation: one copy of each worker flow, under its name, 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. `taskChainLimit` is the most tasks one top task may have under it, at any depth (100 when omitted); a value that isn't a whole number of at least 1 throws. `messages: { hopLimit?, perTurn? }` limits [worker messages](#worker-messages) (6 and 3 when omitted), under the same rule. |
-| `MESSAGE_WORKER_TOOL` / `WORKER_MESSAGE_ENTRY` / `WORKER_MESSAGES_RESOURCE` / `WORKER_MESSAGES_PATTERN` / `workerMessageRowSchema` / `WorkerMessageRow` / `MAX_MESSAGE_CHARS` / `DEFAULT_MESSAGE_HOP_LIMIT` / `DEFAULT_MESSAGES_PER_TURN` / `messageWorkerInputSchema` | [Worker messages](#worker-messages): the tool's name (`"messageWorker"`), the entry a message arrives on (`"onWorkerMessage"`), the log's accessor and pattern and its row schema, the 8,000-character cap, the default limits (6 and 3), and the tool's input schema. Also exported: `MESSAGE_STATUSES`, `MessageAddress`, `workerMessagesCollection` and `workerMessagesResources` (the log as a flow resource), `takesWorkerMessages(flow)` (whether a flow declares the entry), and `sendWorkerMessage(ctx, installation, flowKind, { to, text, replyTo? }, from)`, the send the tool runs, answering a `SendOutcome`. |
+| `SEND_MESSAGE_TOOL` / `MESSAGE_RECEIVED_ENTRY` / `WORKER_MESSAGES_RESOURCE` / `WORKER_MESSAGES_PATTERN` / `workerMessageRowSchema` / `WorkerMessageRow` / `MAX_MESSAGE_CHARS` / `DEFAULT_MESSAGE_HOP_LIMIT` / `DEFAULT_MESSAGES_PER_TURN` / `sendMessageInputSchema` | [Worker messages](#worker-messages): the tool's name (`"sendMessage"`), the entry a message arrives on (`"onMessageReceived"`), the log's accessor and pattern and its row schema, the 8,000-character cap, the default limits (6 and 3), and the tool's input schema. Also exported: `MESSAGE_STATUSES`, `MessageAddress`, `workerMessagesCollection` and `workerMessagesResources` (the log as a flow resource), `takesWorkerMessages(flow)` (whether a flow declares the entry), and `sendMessage(ctx, installation, flowKind, { to, text, inReplyTo? }, from)`, the send the tool runs, answering a `SendOutcome`. |
| `mergeWorkerFlows(flows, workers)` | 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`. |
| `workerFlowProblems(name, flow, roles?)` | Every way `flow`, registered as `name` with `roles`, 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 `respond` door (or a second door, or its door under another name), a declared role's entry missing, not its factory's or refusing its input, a role's piece on a flow that doesn't declare the role, a resource with `writtenBy` that `sharedResource()` didn't build. `roles` defaults to a built-in flow's own, and none for any other. 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. |
diff --git a/packages/workforce/src/browser.ts b/packages/workforce/src/browser.ts
index e4cfc87b49..4e5a96df2d 100644
--- a/packages/workforce/src/browser.ts
+++ b/packages/workforce/src/browser.ts
@@ -69,7 +69,7 @@ export {
export { COORDINATOR_JUDGMENT, COORDINATOR_FLOW, COORDINATOR_ROUTE } from "./coordinator/coordinator-keys";
/** The Error Reporter's flow: an app finds the worker a user tells about a problem by it. */
export { ERROR_REPORTER_FLOW } from "./error-reporter/keys";
-export { MESSAGE_WORKER_TOOL, WORKER_MESSAGE_ENTRY } from "./messages/keys";
+export { SEND_MESSAGE_TOOL, MESSAGE_RECEIVED_ENTRY } from "./messages/keys";
export { LIST_SCHEDULES_ACTION, SCHEDULES_PATTERN } from "./schedules/keys";
export { listedScheduleSchema, type ListedSchedule } from "./schedules/listed-schedule";
export {
diff --git a/packages/workforce/src/conversation-board/session-board.ts b/packages/workforce/src/conversation-board/session-board.ts
index 7a2fa2e353..9e7552a175 100644
--- a/packages/workforce/src/conversation-board/session-board.ts
+++ b/packages/workforce/src/conversation-board/session-board.ts
@@ -48,9 +48,9 @@ import { DELEGATE_SERVER_OWNED, delegateStateShape, type DelegateRecord } from "
import { defineWorkerDelegates, soleTaskDelegate, type TaskDelegates } from "../delegates/worker-delegates";
import { messageHopStateShape } from "../messages/hop";
import { workerMessagesResources } from "../messages/message-log";
-import { defineMessageWorkerCapability } from "../messages/message-tool";
-import { WORKER_MESSAGE_ENTRY } from "../messages/keys";
-import { workerMessageEntry, workerMessageSeenStateShape } from "../messages/worker-message-entry";
+import { defineSendMessageCapability } from "../messages/message-tool";
+import { MESSAGE_RECEIVED_ENTRY } from "../messages/keys";
+import { messageReceivedEntry, messageReceivedStateShape } from "../messages/message-received-entry";
import { fileScheduledTaskEntry } from "../schedules/file-scheduled-task";
import { FILE_SCHEDULED_TASK_ENTRY } from "../schedules/keys";
import { ROUTED_FROM_STATE_KEY, WORK_PROJECT_STATE_KEY } from "../workers/keys";
@@ -77,7 +77,7 @@ import {
* The session state worker messages keep (FIX-1989): the session's hop count
* and the message ids it has acted on. Both server-owned.
*/
-export const workerMessageStateShape = { ...messageHopStateShape, ...workerMessageSeenStateShape } as const;
+export const workerMessageStateShape = { ...messageHopStateShape, ...messageReceivedStateShape } as const;
/**
* The board action a screen files a task through: filed ready, the board
@@ -146,7 +146,7 @@ export function defineSessionBoard(options: SessionBoardOptions) {
...(options.routes === undefined ? {} : { routes: options.routes })
});
- const messages = defineMessageWorkerCapability(options.installation, options.flowKind);
+ const messages = defineSendMessageCapability(options.installation, options.flowKind);
// The manager's pieces: a flow that spreads any of them declares `manager` (`../worker-roles`).
const managerActions = { ...board.actions, ...delegates.actions };
@@ -183,7 +183,7 @@ export function defineSessionBoard(options: SessionBoardOptions) {
*/
delegateTools: delegates.toolsCapability,
/**
- * `messageWorker` (FIX-1989), on every turn of a session that runs a
+ * `sendMessage` (FIX-1989), on every turn of a session that runs a
* worker: one entry for the model block's `uses`, beside `tools`.
*/
messages,
@@ -214,7 +214,7 @@ export function defineSessionBoard(options: SessionBoardOptions) {
* (`onTaskSettled`), the two a flow declaring `manager` is checked for; a check of the
* session's waiting task (`CHECK_TASK_ENTRY`); the turn a late steer is
* owed (`STEER_TURN_ENTRY`, FIX-2086); a worker's message
- * (`onWorkerMessage`, FIX-1989), which always wakes the turn; and a
+ * (`onMessageReceived`, FIX-1989), which always wakes the turn; and a
* scheduled task's filing (`fileScheduledTask`, FIX-2085), through the
* board's own `createTask_tasks`. Spread into `internal: { actions: ... }`.
*
@@ -249,7 +249,7 @@ export function defineSessionBoard(options: SessionBoardOptions) {
// The turn a steer no request took is owed (FIX-2086 D2), on the
// notices' line: the claim gate's check and the steer's write start it.
[STEER_TURN_ENTRY]: steerTurnEntry({ name: "conversation-steer-turn", turn }),
- [WORKER_MESSAGE_ENTRY]: workerMessageEntry({ turn, installation: options.installation, flowKind: options.flowKind }),
+ [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ turn, installation: options.installation, flowKind: options.flowKind }),
[FILE_SCHEDULED_TASK_ENTRY]: fileScheduledTaskEntry(board.actions[SCREEN_FILING_ACTION]!, async (ctx) =>
soleTaskDelegate(await delegates.taskDelegates(ctx))
)
diff --git a/packages/workforce/src/conversation-board/task-admission.ts b/packages/workforce/src/conversation-board/task-admission.ts
index 68280815d8..5e48f35ba4 100644
--- a/packages/workforce/src/conversation-board/task-admission.ts
+++ b/packages/workforce/src/conversation-board/task-admission.ts
@@ -4,7 +4,7 @@
* and the turn a late steer is owed. While the task waits, each is admitted
* for it through orchestration's `taskRequestAdmission`, and the task is
* checked at its end (rule 6), as at the end of `work`. A worker's message
- * (`onWorkerMessage`) is never one of them: it is conversation in the
+ * (`onMessageReceived`) is never one of them: it is conversation in the
* session, never part of the task; while the task's turn runs, it is
* answered after that turn.
*
diff --git a/packages/workforce/src/messages/hop.ts b/packages/workforce/src/messages/hop.ts
index ef3b4f47dc..b626c55f39 100644
--- a/packages/workforce/src/messages/hop.ts
+++ b/packages/workforce/src/messages/hop.ts
@@ -8,7 +8,7 @@
* it starts from something that sets it:
*
* - a user's turn writes 0, at the user-turn mark (`markUserTurn`);
- * - a turn a message wakes is at that message's count (`onWorkerMessage`);
+ * - a turn a message wakes is at that message's count (`onMessageReceived`);
* - a task session is born with its filer's current count, beside the task
* chain fields the hand-over sets;
* - a task's turn is at its filing turn's count, which the filing records on
diff --git a/packages/workforce/src/messages/index.ts b/packages/workforce/src/messages/index.ts
index 64eb036a76..983c9ce555 100644
--- a/packages/workforce/src/messages/index.ts
+++ b/packages/workforce/src/messages/index.ts
@@ -4,7 +4,7 @@
* no task-chain count. The session kit carries the tool and the entry, so
* both worker flows get them; `hireWorkforce`'s `messages` sets the limits.
*/
-export { MESSAGE_WORKER_TOOL, WORKER_MESSAGE_ENTRY } from "./keys";
+export { SEND_MESSAGE_TOOL, MESSAGE_RECEIVED_ENTRY } from "./keys";
export {
MAX_MESSAGE_CHARS,
MESSAGE_STATUSES,
@@ -17,5 +17,5 @@ export {
type WorkerMessageRow
} from "./message-log";
export { DEFAULT_MESSAGE_HOP_LIMIT, DEFAULT_MESSAGES_PER_TURN, type MessageLimits } from "./message-limits";
-export { messageWorkerInputSchema } from "./message-tool";
-export { sendWorkerMessage, takesWorkerMessages, type SendOutcome, type SendWorkerMessage } from "./send-message";
+export { sendMessageInputSchema } from "./message-tool";
+export { sendMessage, takesWorkerMessages, type SendOutcome, type SendMessageInput } from "./send-message";
diff --git a/packages/workforce/src/messages/keys.ts b/packages/workforce/src/messages/keys.ts
index d030455269..41a1b6cf92 100644
--- a/packages/workforce/src/messages/keys.ts
+++ b/packages/workforce/src/messages/keys.ts
@@ -1,13 +1,16 @@
/**
- * The pinned names of worker messages (FIX-1989). A leaf module with no
- * imports, so the browser entry, the tool and the entry share one spelling.
+ * The pinned names of worker messages (FIX-1989, FIX-2238). A leaf module with
+ * no imports, so the browser entry, the tool and the entry share one spelling.
*/
/** The internal entry a worker message arrives on. **Pinned**: the goal check reads deliveries by it. */
-export const WORKER_MESSAGE_ENTRY = "onWorkerMessage";
+export const MESSAGE_RECEIVED_ENTRY = "onMessageReceived";
/** The tool a worker's model sends a message with. **Pinned**: an app draws its calls by name. */
-export const MESSAGE_WORKER_TOOL = "messageWorker";
+export const SEND_MESSAGE_TOOL = "sendMessage";
+
+/** The client-only component a received message is drawn by. **Pinned**: an app's renderer is keyed by it. */
+export const RECEIVED_MESSAGE_COMPONENT = "workforce:received";
/** Server-written session state: the message ids a session has acted on, newest last. */
export const WORKER_MESSAGES_SEEN_STATE = "workerMessagesSeen";
diff --git a/packages/workforce/src/messages/log-row.ts b/packages/workforce/src/messages/log-row.ts
index 1462c2ebfb..0a5ecd69ad 100644
--- a/packages/workforce/src/messages/log-row.ts
+++ b/packages/workforce/src/messages/log-row.ts
@@ -47,7 +47,7 @@ export const workerMessageRowSchema = z.object({
/** The first message's id in this exchange: a message's own id, or the exchange of the message it answers. */
exchange: z.string().min(1),
/** The message this one answers. */
- replyTo: z.string().optional(),
+ inReplyTo: z.string().optional(),
/** The session the sending turn ran in. */
fromSession: z.string().min(1),
/** The flow the sending session runs on. */
diff --git a/packages/workforce/src/messages/worker-message-entry.ts b/packages/workforce/src/messages/message-received-entry.ts
similarity index 80%
rename from packages/workforce/src/messages/worker-message-entry.ts
rename to packages/workforce/src/messages/message-received-entry.ts
index fcf5e981a7..d78ab3021a 100644
--- a/packages/workforce/src/messages/worker-message-entry.ts
+++ b/packages/workforce/src/messages/message-received-entry.ts
@@ -1,5 +1,5 @@
/**
- * How a worker hears a message (FIX-1989): the `onWorkerMessage` internal
+ * How a worker hears a message (FIX-1989): the `onMessageReceived` internal
* entry, on every flow that carries the session kit.
*
* The payload names a message id and nothing else: the row in the user's
@@ -13,8 +13,8 @@
* entry waits on the reply line.
*
* A woken turn that ends with text and never messaged the sender back has its
- * text sent as the answer, through the same send a `messageWorker` reply takes
- * (replyTo, hop, log row, wake). A turn with no text sends nothing, and a turn
+ * text sent as the answer, through the same send a `sendMessage` reply takes
+ * (inReplyTo, hop, log row, wake). A turn with no text sends nothing, and a turn
* woken by an answer is never relayed, so an exchange ends after one answer.
* The relay is pending a product decision (DECISIONS.md D2, amended).
*/
@@ -25,13 +25,13 @@ import { z } from "zod";
import { AFTER_REPLY_CONCURRENCY } from "../conversation-board/task-settled";
import type { WorkerInstallation } from "../workers/installation";
import { messageTurnStateSchema, startTurnAtHop, TURN_MESSAGED_STATE } from "./hop";
-import { MESSAGE_WORKER_TOOL, WORKER_MESSAGES_SEEN_STATE } from "./keys";
+import { SEND_MESSAGE_TOOL, WORKER_MESSAGES_SEEN_STATE } from "./keys";
import { MAX_MESSAGE_CHARS } from "./log-row";
-import { sendWorkerMessage } from "./send-message";
+import { sendMessage } from "./send-message";
import { messageLogOf, workerMessagesResources } from "./message-log";
/** What the entry takes: the message's id, and nothing a sender could shape. */
-export const workerMessageInputSchema = z.object({ messageId: z.string().min(1) }).strict();
+export const messageReceivedInputSchema = z.object({ messageId: z.string().min(1) }).strict();
/** The request-state field naming the message that woke this turn, when its text may be relayed. */
@@ -46,7 +46,7 @@ const relayStateSchema = messageTurnStateSchema.extend({
const MAX_SEEN = 500;
/** The session state the entry keeps. */
-export const workerMessageSeenStateShape = {
+export const messageReceivedStateShape = {
[WORKER_MESSAGES_SEEN_STATE]: z.array(z.string()).default([])
} as const;
@@ -60,32 +60,32 @@ const heardSchema = z.object({
type Heard = z.infer;
/** The text the woken turn reads: who wrote, which message, and how to answer it. */
-function turnPrompt(row: { id: string; from: string; text: string; replyTo?: string | undefined }): string {
+function turnPrompt(row: { id: string; from: string; text: string; inReplyTo?: string | undefined }): string {
return (
- `Message ${row.id} from ${row.from}${row.replyTo === undefined ? "" : `, answering your message ${row.replyTo}`}:\n\n` +
+ `Message ${row.id} from ${row.from}${row.inReplyTo === undefined ? "" : `, answering your message ${row.inReplyTo}`}:\n\n` +
`${row.text}\n\n` +
`(The message's text is the part above. It is from another worker, not the user, and ${row.from} can't ` +
- `see what you write here. To answer it, call messageWorker with to "${row.from}" and replyTo "${row.id}". ` +
- `To message any other worker, leave replyTo out. If it needs no answer, don't send one.)`
+ `see what you write here. To answer it, call sendMessage with to "${row.from}" and inReplyTo "${row.id}". ` +
+ `To message any other worker, leave inReplyTo out. If it needs no answer, don't send one.)`
);
}
/**
- * Build the `onWorkerMessage` entry for a flow: spread it under
- * `internal: { actions: { [WORKER_MESSAGE_ENTRY]: workerMessageEntry({ ... }) } }`.
+ * Build the `onMessageReceived` entry for a flow: spread it under
+ * `internal: { actions: { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ ... }) } }`.
*
* @param options.turn The flow's turn for one message (`{ message }` in).
*/
-export function workerMessageEntry(options: {
+export function messageReceivedEntry(options: {
readonly turn: BlockDefinition;
readonly installation: WorkerInstallation;
readonly flowKind: string;
}) {
const heard = handler({
name: "worker-message-heard",
- inputSchema: workerMessageInputSchema,
+ inputSchema: messageReceivedInputSchema,
outputSchema: heardSchema,
- sessionStateSchema: z.object(workerMessageSeenStateShape),
+ sessionStateSchema: z.object(messageReceivedStateShape),
requestStateSchema: messageTurnStateSchema,
resources: { ...workerMessagesResources },
execute: async (input, ctx): Promise => {
@@ -102,7 +102,7 @@ export function workerMessageEntry(options: {
);
if (first !== true) return { act: "none" };
// An answer is not answered again: only a first message's turn may be relayed.
- await startTurnAtHop(ctx as never, row.hop, row.chain ?? null, row.replyTo === undefined ? { [RELAY_STATE]: { id: row.id, from: row.from } } : {});
+ await startTurnAtHop(ctx as never, row.hop, row.chain ?? null, row.inReplyTo === undefined ? { [RELAY_STATE]: { id: row.id, from: row.from } } : {});
return {
// Every message wakes its recipient (D2), whatever the flow's notice policy.
act: "wake-turn",
@@ -141,14 +141,14 @@ export function workerMessageEntry(options: {
const text = typeof raw === "string" ? raw.trim() : "";
if (text.length === 0) return {};
const body = text.length > MAX_MESSAGE_CHARS ? `${text.slice(0, MAX_MESSAGE_CHARS - 1)}…` : text;
- await sendWorkerMessage(ctx as never, options.installation, options.flowKind, { to: woke.from, text: body, replyTo: woke.id }, MESSAGE_WORKER_TOOL);
+ await sendMessage(ctx as never, options.installation, options.flowKind, { to: woke.from, text: body, inReplyTo: woke.id }, SEND_MESSAGE_TOOL);
return {};
}
});
// A message is conversation, never part of a task, with no claim on it:
// one to a task session whose turn is running runs after that turn.
- const block = sequencer({ name: "worker-message-arrived", inputSchema: workerMessageInputSchema })
+ const block = sequencer({ name: "worker-message-arrived", inputSchema: messageReceivedInputSchema })
.step(heard)
.tapIf((got: Heard) => got.act !== "none", line)
.tapIf(
@@ -157,5 +157,5 @@ export function workerMessageEntry(options: {
sequencer({ name: "worker-message-turn", inputSchema: z.object({ message: z.string() }) }).step(options.turn).step(relay)
);
- return { inputSchema: workerMessageInputSchema, block, concurrency: AFTER_REPLY_CONCURRENCY };
+ return { inputSchema: messageReceivedInputSchema, block, concurrency: AFTER_REPLY_CONCURRENCY };
}
diff --git a/packages/workforce/src/messages/message-tool.ts b/packages/workforce/src/messages/message-tool.ts
index a15c2a54a2..4b24554749 100644
--- a/packages/workforce/src/messages/message-tool.ts
+++ b/packages/workforce/src/messages/message-tool.ts
@@ -1,9 +1,9 @@
/**
- * `messageWorker` (FIX-1989): the tool a worker's model sends a message with,
+ * `sendMessage` (FIX-1989): the tool a worker's model sends a message with,
* as one capability a worker turn composes. Talk, not delegation: no task
* row, no delegate, no result owed.
*
- * Its input is strict (`to`, `text`, `replyTo`), so a call can't name a
+ * Its input is strict (`to`, `text`, `inReplyTo`), so a call can't name a
* sender, a hop count or a session, and there is no `wait`: an answer arrives
* later as a line from the recipient and wakes this worker. Its description
* lists who the worker can message, read before each model call: the roster's
@@ -15,21 +15,21 @@ import { z } from "zod";
import type { WorkerInstallation } from "../workers/installation";
import { WORKER_ID_STATE_KEY } from "../workers/keys";
import { messageTurnStateSchema } from "./hop";
-import { MESSAGE_WORKER_TOOL } from "./keys";
+import { SEND_MESSAGE_TOOL } from "./keys";
import { MAX_MESSAGE_CHARS, workerMessagesResources } from "./message-log";
-import { recipientRefusal, sendWorkerMessage } from "./send-message";
+import { recipientRefusal, sendMessage } from "./send-message";
/** The most workers the description lists, and the longest description it quotes for one. */
const MAX_LISTED = 25;
const MAX_DESCRIPTION = 160;
/** What the model passes. Strict: nothing else is taken. */
-export const messageWorkerInputSchema = z
+export const sendMessageInputSchema = z
.object({
to: z.string().min(1).describe("The id of the worker to message, as the list below names it."),
// Something other than blank space: the send refuses a blank message too.
text: z.string().max(MAX_MESSAGE_CHARS).regex(/\S/, "say something").describe("What to say."),
- replyTo: z
+ inReplyTo: z
.string()
.min(1)
.optional()
@@ -37,7 +37,7 @@ export const messageWorkerInputSchema = z
})
.strict();
-export const messageWorkerOutputSchema = z.union([
+export const sendMessageOutputSchema = z.union([
z.object({ sent: z.string(), unconfirmed: z.string().optional() }),
z.object({ ok: z.literal(false), error: z.string() })
]);
@@ -46,7 +46,7 @@ const BASE_DESCRIPTION =
"Send a short message to another worker on your team: a question, an FYI, a heads-up. It lands in that worker's " +
"conversation and wakes it. This is not a task: nothing is filed and no result is owed, and you don't wait for an " +
"answer. If it answers, the answer arrives later as a line from that worker and wakes you. To answer a message " +
- "you were sent, pass its id as replyTo. A message can't be waited on: to wait on a colleague's result before " +
+ "you were sent, pass its id as inReplyTo. A message can't be waited on: to wait on a colleague's result before " +
"you answer, file a task for them with createTask, then call getTask({ id, wait: true }) where getTask takes wait.";
/** Who the running worker can message, as the description's list: every roster worker the send would take. */
@@ -65,22 +65,22 @@ async function recipientsLine(ctx: BlockContext, installation: WorkerInstallatio
}
/**
- * The capability: `messageWorker` on every turn of a session that runs a
+ * The capability: `sendMessage` on every turn of a session that runs a
* worker. `controlTools`, so a worker's `tools:` line doesn't fence it out.
*
* @param flowKind The flow the sessions run on: where an answer comes back.
*/
-export function defineMessageWorkerCapability(installation: WorkerInstallation, flowKind: string) {
+export function defineSendMessageCapability(installation: WorkerInstallation, flowKind: string) {
const toolWith = (description: string) =>
handler({
- name: MESSAGE_WORKER_TOOL,
+ name: SEND_MESSAGE_TOOL,
description,
- inputSchema: messageWorkerInputSchema,
- outputSchema: messageWorkerOutputSchema,
+ inputSchema: sendMessageInputSchema,
+ outputSchema: sendMessageOutputSchema,
requestStateSchema: messageTurnStateSchema,
resources: { ...installation.resources, ...workerMessagesResources },
execute: async (input, ctx) => {
- const sent = await sendWorkerMessage(ctx as never, installation, flowKind, input, MESSAGE_WORKER_TOOL);
+ const sent = await sendMessage(ctx as never, installation, flowKind, input, SEND_MESSAGE_TOOL);
if (!sent.ok) return { ok: false as const, error: sent.error };
return sent.unconfirmed === undefined ? { sent: sent.id } : { sent: sent.id, unconfirmed: sent.unconfirmed };
}
diff --git a/packages/workforce/src/messages/send-message.ts b/packages/workforce/src/messages/send-message.ts
index 468cc81bac..98b7aa4c98 100644
--- a/packages/workforce/src/messages/send-message.ts
+++ b/packages/workforce/src/messages/send-message.ts
@@ -1,6 +1,6 @@
/**
* Sending a worker message (FIX-1989): the one check every send passes, the
- * log row, and the delivery. The `messageWorker` tool calls it, and so will
+ * log row, and the delivery. The `sendMessage` tool calls it, and so will
* any later caller (a coding run's tool, FIX-1990).
*
* The check, in order, before anything is written:
@@ -9,16 +9,16 @@
* - the recipient is another worker on the user's roster now (one of theirs or
* a standard one: another user's worker is simply not there), whose row
* reads;
- * - it has a conversation: its flow declares the `onWorkerMessage` entry. A
+ * - it has a conversation: its flow declares the `onMessageReceived` entry. A
* worker that only takes tasks (the coder) is told to be filed a task;
* - a coordinator whose routing never runs a turn of its own (round robin,
* everyone) refuses: nobody would read the line;
- * - an answer (`replyTo`) names a message the recipient sent this worker;
+ * - an answer (`inReplyTo`) names a message the recipient sent this worker;
* - the hop count stays within the limit, counted across the whole exchange
* (`hop.ts`), and the turn within its sends.
*
* Then one row is written to the user's message log, and the message is
- * dispatched to the recipient's `onWorkerMessage`: into its own conversation
+ * dispatched to the recipient's `onMessageReceived`: into its own conversation
* (the worker's derived address, opened by the dispatch when absent), or for
* an answer, back where the row it answers says. A dispatch the host refuses
* marks the row refused. A thrown one may have started, so it is sent again
@@ -43,7 +43,7 @@ import {
} from "../workers/keys";
import { parseWorkerRow } from "../workers/worker-row";
import { newChainId, TURN_CHAIN_STATE, TURN_MESSAGED_STATE, TURN_SENT_STATE, turnChainOf, turnHopOf } from "./hop";
-import { WORKER_MESSAGE_ENTRY } from "./keys";
+import { MESSAGE_RECEIVED_ENTRY } from "./keys";
import { messageLimitsOf } from "./message-limits";
import {
MAX_MESSAGE_CHARS,
@@ -54,13 +54,13 @@ import {
type WorkerMessageRow
} from "./message-log";
-export { WORKER_MESSAGE_ENTRY };
+export { MESSAGE_RECEIVED_ENTRY };
/** What a send asks for: the tool's input. */
-export interface SendWorkerMessage {
+export interface SendMessageInput {
readonly to: string;
readonly text: string;
- readonly replyTo?: string;
+ readonly inReplyTo?: string;
}
/** What a send came to. */
@@ -68,10 +68,10 @@ export type SendOutcome =
| { readonly ok: true; readonly id: string; readonly unconfirmed?: string }
| { readonly ok: false; readonly error: string };
-/** Whether a worker flow takes messages: it declares the `onWorkerMessage` internal entry. */
+/** Whether a worker flow takes messages: it declares the `onMessageReceived` internal entry. */
export function takesWorkerMessages(flow: unknown): boolean {
const actions = (flow as { internal?: { actions?: Record } } | undefined)?.internal?.actions;
- return actions !== undefined && Object.hasOwn(actions, WORKER_MESSAGE_ENTRY);
+ return actions !== undefined && Object.hasOwn(actions, MESSAGE_RECEIVED_ENTRY);
}
/** A coordinator worker's routing, as its row or file declares it, or `undefined` when it names none. */
@@ -147,11 +147,11 @@ async function conversationAddress(
* @param flowKind The flow the running session runs on.
* @param from The sending block's name, for the dispatch's provenance.
*/
-export async function sendWorkerMessage(
+export async function sendMessage(
ctx: BlockContext,
installation: WorkerInstallation,
flowKind: string,
- input: SendWorkerMessage,
+ input: SendMessageInput,
from: string
): Promise {
const refuse = (error: string): SendOutcome => ({ ok: false, error });
@@ -172,10 +172,10 @@ export async function sendWorkerMessage(
const log = messageLogOf(ctx);
let destination: MessageAddress;
let exchange: string | undefined;
- if (input.replyTo !== undefined) {
- const answered = (await log.getOptional(input.replyTo))?.state;
+ if (input.inReplyTo !== undefined) {
+ const answered = (await log.getOptional(input.inReplyTo))?.state;
if (answered === undefined || answered.to !== sender || answered.from !== input.to) {
- return refuse(`no_such_message: replyTo "${input.replyTo}" names no message "${input.to}" sent you. Leave replyTo out to start a new one.`);
+ return refuse(`no_such_message: inReplyTo "${input.inReplyTo}" names no message "${input.to}" sent you. Leave inReplyTo out to start a new one.`);
}
destination = answered.answerTo;
exchange = answered.exchange;
@@ -238,7 +238,7 @@ export async function sendWorkerMessage(
to: input.to,
text: input.text,
exchange: exchange ?? id,
- ...(input.replyTo === undefined ? {} : { replyTo: input.replyTo }),
+ ...(input.inReplyTo === undefined ? {} : { inReplyTo: input.inReplyTo }),
fromSession: sessionId,
fromFlow: flowKind,
toSession: destination.sessionId,
@@ -254,7 +254,7 @@ export async function sendWorkerMessage(
const dispatch = () =>
dispatchThroughSeam(ctx, {
type: "internal",
- action: WORKER_MESSAGE_ENTRY,
+ action: MESSAGE_RECEIVED_ENTRY,
flowKind: destination.flow,
session: destination.state === undefined ? { id: destination.sessionId } : { id: destination.sessionId, state: destination.state },
payload: { messageId: id },
diff --git a/packages/workforce/src/workers/register.ts b/packages/workforce/src/workers/register.ts
index 101a0418e5..de8f6b376e 100644
--- a/packages/workforce/src/workers/register.ts
+++ b/packages/workforce/src/workers/register.ts
@@ -39,7 +39,7 @@ export interface HireWorkforceOptions {
*/
taskChainLimit?: number;
/**
- * The limits on worker messages (`messageWorker`): `hopLimit`, the most
+ * The limits on worker messages (`sendMessage`): `hopLimit`, the most
* messages a chain of workers passes with no user's turn between them
* (6 when omitted), and `perTurn`, the most one turn sends (3 when omitted).
*/
diff --git a/packages/workforce/test/list-worker-sessions.test.ts b/packages/workforce/test/list-worker-sessions.test.ts
index f666cb21d5..40aa3b1361 100644
--- a/packages/workforce/test/list-worker-sessions.test.ts
+++ b/packages/workforce/test/list-worker-sessions.test.ts
@@ -6,7 +6,7 @@
import { describe, expect, it } from "vitest";
import { mockGenerator, type MockGeneratorScriptEntry } from "@flow-state-dev/testing";
import type { WorkerManifest } from "../src";
-import { WORKER_MESSAGE_ENTRY } from "../src/messages/keys";
+import { MESSAGE_RECEIVED_ENTRY } from "../src/messages/keys";
import { boardWorkers, bootBoardHost, messageOf, type BoardHost } from "./conversation-board-harness";
/** A scripted model input as text, with its escapes dropped. */
@@ -29,7 +29,7 @@ function tellsOtto(): MockGeneratorScriptEntry[] {
sent = true;
return true;
},
- then: { toolCalls: [{ toolCallId: "tell-otto", toolName: "messageWorker", args: { to: "otto", text: "Hello otto." } }] }
+ then: { toolCalls: [{ toolCallId: "tell-otto", toolName: "sendMessage", args: { to: "otto", text: "Hello otto." } }] }
},
fallback
];
@@ -135,7 +135,7 @@ describe("a user's conversations with one worker", () => {
await h.post("alice", helper, "respond", { message: "Tell otto hello" }, "agent");
await h.settled();
const received = (await (await h.state.getRuntime()).stores.request.list({})).filter(
- (request) => request.actionName === WORKER_MESSAGE_ENTRY
+ (request) => request.actionName === MESSAGE_RECEIVED_ENTRY
);
expect(received.map((request) => request.sessionId)).toEqual([main.id]);
const [top] = await alice.listWorkerSessions("otto");
diff --git a/packages/workforce/test/message-to-a-busy-task-session.test.ts b/packages/workforce/test/message-to-a-busy-task-session.test.ts
index d1f70b1bc1..52e6398351 100644
--- a/packages/workforce/test/message-to-a-busy-task-session.test.ts
+++ b/packages/workforce/test/message-to-a-busy-task-session.test.ts
@@ -26,7 +26,7 @@ import { defineSessionBoard, filingConversationBoard, workerConfigSchema, worker
import { boardAboveOf } from "../src/conversation-board/board-above";
import { conversationLedgerAt } from "../src/conversation-board/ledger";
import { messageLogOf } from "../src/messages/message-log";
-import { WORKER_MESSAGE_ENTRY } from "../src/messages/keys";
+import { MESSAGE_RECEIVED_ENTRY } from "../src/messages/keys";
import type { WorkerInstallation } from "../src/workers/installation";
import { bootBoardHost, messageOf, type BoardHost } from "./conversation-board-harness";
@@ -102,7 +102,7 @@ function doerFlow(installation: WorkerInstallation, seen: Seen[], behaviour: Beh
} as never);
await dispatchThroughSeam(ctx, {
type: "internal",
- action: WORKER_MESSAGE_ENTRY,
+ action: MESSAGE_RECEIVED_ENTRY,
flowKind: "doer",
session: { id: sessionId },
payload: { messageId: id },
@@ -146,7 +146,7 @@ function doerFlow(installation: WorkerInstallation, seen: Seen[], behaviour: Beh
return "the work's answer";
}
}),
- { type: "internal", action: WORKER_MESSAGE_ENTRY }
+ { type: "internal", action: MESSAGE_RECEIVED_ENTRY }
);
return defineFlow({
diff --git a/packages/workforce/test/worker-messages-unconfirmed.test.ts b/packages/workforce/test/worker-messages-unconfirmed.test.ts
index 839488dbf5..10e5b5ea52 100644
--- a/packages/workforce/test/worker-messages-unconfirmed.test.ts
+++ b/packages/workforce/test/worker-messages-unconfirmed.test.ts
@@ -4,7 +4,7 @@
* once, which the entry's dedupe makes safe; if that throws too, the row
* stays unconfirmed and the tool says so.
*
- * The seam is made to throw for `onWorkerMessage` only, in this file alone.
+ * The seam is made to throw for `onMessageReceived` only, in this file alone.
*/
import { describe, expect, it, vi } from "vitest";
@@ -15,7 +15,7 @@ vi.mock("@flow-state-dev/core/types", async (original) => {
return {
...actual,
dispatchThroughSeam: (ctx: never, spec: { action: string }) => {
- if (spec.action === "onWorkerMessage" && throwing.count < throwing.times) {
+ if (spec.action === "onMessageReceived" && throwing.count < throwing.times) {
throwing.count += 1;
return Promise.reject(new Error("the connection dropped"));
}
@@ -46,7 +46,7 @@ async function run(times: number) {
called = true;
return true;
},
- then: { toolCalls: [{ toolCallId: "ask", toolName: "messageWorker", args: { to: "lead", text: "What is the codename?" } }] }
+ then: { toolCalls: [{ toolCallId: "ask", toolName: "sendMessage", args: { to: "lead", text: "What is the codename?" } }] }
},
{ when: () => true, then: { text: "OK." } }
]
diff --git a/packages/workforce/test/worker-messages.test.ts b/packages/workforce/test/worker-messages.test.ts
index 20999ff6e8..6a20030abd 100644
--- a/packages/workforce/test/worker-messages.test.ts
+++ b/packages/workforce/test/worker-messages.test.ts
@@ -1,6 +1,6 @@
/**
* Any worker with a conversation can message any other on its user's roster
- * (FIX-1989): `messageWorker` lands a line in the recipient's own
+ * (FIX-1989): `sendMessage` lands a line in the recipient's own
* conversation, opening it at the worker's derived address when needed, and
* wakes its turn; an answer names the message it answers and goes back to the
* session that asked. No task row, no delegate, no task-chain count.
@@ -14,7 +14,7 @@ import { mockGenerator, type MockGeneratorScriptEntry } from "@flow-state-dev/te
import type { WorkerManifest } from "../src";
import { boardWorkers, bootBoardHost, messageOf, type BoardHost } from "./conversation-board-harness";
import { WORKER_MESSAGES_PATTERN } from "../src/messages/message-log";
-import { messageWorkerInputSchema } from "../src/messages/message-tool";
+import { sendMessageInputSchema } from "../src/messages/message-tool";
import { deriveWorkerSessionId } from "../src/workers/derive-session-id";
import { FILED_HOP } from "../src/conversation-board/board-entries";
@@ -45,7 +45,7 @@ function callOnce(marker: string, toolName: string, args: unknown, after = "Sent
*/
function answerOnce(from: string, marker: string, text: string, after = "Answered."): MockGeneratorScriptEntry[] {
let answered = false;
- const step = { toolCalls: [{ toolCallId: `answer-${marker}`, toolName: "messageWorker", args: {} as Record }] };
+ const step = { toolCalls: [{ toolCallId: `answer-${marker}`, toolName: "sendMessage", args: {} as Record }] };
return [
{ when: (input: unknown) => answered && textOf(input).includes(marker), then: { text: after } },
{
@@ -54,7 +54,7 @@ function answerOnce(from: string, marker: string, text: string, after = "Answere
const message = new RegExp(`Message (msg_\\w+) from ${from.replace(".", "\\.")}`).exec(text_);
if (answered || message === null || !text_.includes(marker)) return false;
answered = true;
- step.toolCalls[0]!.args = { to: from, text, replyTo: message[1] };
+ step.toolCalls[0]!.args = { to: from, text, inReplyTo: message[1] };
return true;
},
then: step
@@ -100,7 +100,7 @@ describe("a worker messages another worker", () => {
const judgment = mockGenerator({ script: [{ when: (input) => textOf(input).includes("What is the codename?"), then: { text: "Thinking." } }, fallback] });
const h = boot({
judgment,
- agentAnswer: mockGenerator({ script: [...callOnce("ask the lead", "messageWorker", { to: "lead", text: "What is the codename?" }), fallback] })
+ agentAnswer: mockGenerator({ script: [...callOnce("ask the lead", "sendMessage", { to: "lead", text: "What is the codename?" }), fallback] })
});
try {
const otto = await agentSession(h, "alice", "otto");
@@ -133,7 +133,7 @@ describe("what a worker knows of who it can message", () => {
agentAnswer: mockGenerator({ script: [fallback] }),
observeTools: (block, _names, options) => {
if (block !== "agent-answer") return;
- const tool = ((options as { tools?: Array<{ name: string; description?: string }> }).tools ?? []).find((t) => t.name === "messageWorker");
+ const tool = ((options as { tools?: Array<{ name: string; description?: string }> }).tools ?? []).find((t) => t.name === "sendMessage");
if (tool !== undefined) descriptions.push(tool.description ?? "");
}
});
@@ -159,7 +159,7 @@ describe("what a worker knows of who it can message", () => {
describe("the log, read by an app", () => {
it("is read through the user's roster session, and holds only that user's messages", async () => {
const h = boot({
- agentAnswer: mockGenerator({ script: [...callOnce("ask the lead", "messageWorker", { to: "lead", text: "What is the codename?" }), fallback] })
+ agentAnswer: mockGenerator({ script: [...callOnce("ask the lead", "sendMessage", { to: "lead", text: "What is the codename?" }), fallback] })
});
try {
const otto = await agentSession(h, "alice", "otto");
@@ -187,12 +187,12 @@ describe("the log, read by an app", () => {
describe("an answer", () => {
it("is the woken turn's own text when it ends without messaging the sender back, sent as a reply that wakes the sender", async () => {
const h = boot({
- // The lead answers in plain text, with no messageWorker call.
+ // The lead answers in plain text, with no sendMessage call.
judgment: mockGenerator({ script: [{ when: (input) => textOf(input).includes("What is the codename?"), then: { text: "It is Bluebird." } }, fallback] }),
agentAnswer: mockGenerator({
script: [
{ when: (input) => textOf(input).includes("From lead: It is Bluebird."), then: { text: "The codename is Bluebird." } },
- ...callOnce("ask the lead", "messageWorker", { to: "lead", text: "What is the codename?" }),
+ ...callOnce("ask the lead", "sendMessage", { to: "lead", text: "What is the codename?" }),
fallback
]
})
@@ -204,7 +204,7 @@ describe("an answer", () => {
const rows = await logRows(h, "alice");
const question = rows.find((row) => row.from === "otto")!;
expect(rows.find((row) => row.from === "lead")).toMatchObject({
- to: "otto", text: "It is Bluebird.", replyTo: question.id, toSession: otto, status: "delivered", hop: 2
+ to: "otto", text: "It is Bluebird.", inReplyTo: question.id, toSession: otto, status: "delivered", hop: 2
});
expect((await h.messages(otto)).at(-1)?.text, "otto's turn ran after the answer").toBe("The codename is Bluebird.");
// otto's text, in a turn woken by an answer, is not sent back: the exchange ends.
@@ -225,8 +225,8 @@ describe("an answer", () => {
}),
agentAnswer: mockGenerator({
script: [
- ...callOnce("ask the first", "messageWorker", { to: "lead", text: "first question" }),
- ...callOnce("ask the second", "messageWorker", { to: "lead", text: "second question" }),
+ ...callOnce("ask the first", "sendMessage", { to: "lead", text: "first question" }),
+ ...callOnce("ask the second", "sendMessage", { to: "lead", text: "second question" }),
fallback
]
})
@@ -248,7 +248,7 @@ describe("an answer", () => {
const agentAnswer = mockGenerator({
script: [
{ when: (input) => textOf(input).includes("It is Bluebird."), then: { text: "The codename is Bluebird." } },
- ...callOnce("ask the lead", "messageWorker", { to: "lead", text: "What is the codename?" }),
+ ...callOnce("ask the lead", "sendMessage", { to: "lead", text: "What is the codename?" }),
fallback
]
});
@@ -268,7 +268,7 @@ describe("an answer", () => {
const rows = await logRows(h, "alice");
const question = rows.find((row) => row.from === "otto")!;
const answer = rows.find((row) => row.from === "lead")!;
- expect(answer).toMatchObject({ to: "otto", replyTo: question.id, exchange: question.id, toSession: otto, status: "delivered", hop: 2 });
+ expect(answer).toMatchObject({ to: "otto", inReplyTo: question.id, exchange: question.id, toSession: otto, status: "delivered", hop: 2 });
} finally {
await h.dispose();
}
@@ -292,7 +292,7 @@ describe("a message sent from a task's turn", () => {
script: [
{ when: (input) => textOf(input).includes("From helper-a") || textOf(input).includes("from helper-a"), then: { text: "Helper A says teal." } },
...answerOnce("otto", "favourite colour", "Teal."),
- ...callOnce("Ask helper-a for its favourite colour", "messageWorker", { to: "helper-a", text: "What is your favourite colour?" }, "Asked."),
+ ...callOnce("Ask helper-a for its favourite colour", "sendMessage", { to: "helper-a", text: "What is your favourite colour?" }, "Asked."),
fallback
]
});
@@ -332,7 +332,7 @@ describe("a message sent from a task's turn", () => {
function ringScript(after = ""): MockGeneratorScriptEntry[] {
const next: Record = { otto: "helper-a", "helper-a": "helper-b", "helper-b": "otto" };
const handled = new Set();
- const step = { toolCalls: [{ toolCallId: "pass", toolName: "messageWorker", args: {} as Record }] };
+ const step = { toolCalls: [{ toolCallId: "pass", toolName: "sendMessage", args: {} as Record }] };
return [
{
when: (input: unknown) => {
@@ -394,7 +394,7 @@ describe("the hop limit", () => {
function fanOutScript(): MockGeneratorScriptEntry[] {
const toAll = ["helper-a", "helper-b", "lead", "pm", "chief"].map((to, i) => ({
toolCallId: `all-${i}`,
- toolName: "messageWorker",
+ toolName: "sendMessage",
args: { to, text: "Heads up: the release moved." }
}));
let called = false;
@@ -424,7 +424,7 @@ describe("the hop limit across a branching exchange", () => {
await h.settled();
const rows = await logRows(h, "alice");
- expect(rows.some((row) => row.replyTo !== undefined), "the exchange branched: some message is an answer").toBe(true);
+ expect(rows.some((row) => row.inReplyTo !== undefined), "the exchange branched: some message is an answer").toBe(true);
expect(rows.filter((row) => row.status !== "refused")).toHaveLength(6);
expect(rows.map((row) => row.hop).sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 6]);
} finally {
@@ -482,9 +482,9 @@ describe("the per-turn limit", () => {
*/
function relayThroughTask(setting: Record): MockGeneratorScriptEntry[] {
return [
- ...callOnce("Tell otto the number", "messageWorker", { to: "otto", text: "The number is 7." }, ""),
+ ...callOnce("Tell otto the number", "sendMessage", { to: "otto", text: "The number is 7." }, ""),
...callOnce("have helper-b tell otto", "createTask", { goal: "Tell otto the number", assignee: "helper-b", ...setting }, ""),
- ...callOnce("Please ask helper-a", "messageWorker", { to: "helper-a", text: "Please have helper-b tell otto the number." }, ""),
+ ...callOnce("Please ask helper-a", "sendMessage", { to: "helper-a", text: "Please have helper-b tell otto the number." }, ""),
fallback
];
}
@@ -503,9 +503,9 @@ describe("the hop count through a delegation", () => {
standard: teamWorkers(),
agentAnswer: mockGenerator({
script: [
- ...callOnce("Tell otto the number", "messageWorker", { to: "otto", text: "The number is 7." }, ""),
+ ...callOnce("Tell otto the number", "sendMessage", { to: "otto", text: "The number is 7." }, ""),
...callOnce("have helper-b tell otto", "createTask", { goal: "Tell otto the number", assignee: "helper-b" }, ""),
- ...callOnce("Please ask helper-a", "messageWorker", { to: "helper-a", text: "Please have helper-b tell otto the number." }, ""),
+ ...callOnce("Please ask helper-a", "sendMessage", { to: "helper-a", text: "Please have helper-b tell otto the number." }, ""),
fallback
]
})
@@ -588,7 +588,7 @@ describe("the hop count through a delegation", () => {
it("counts a message from a routed task in the chain of the user's line it hands on, at 1", async () => {
const h = boot({
standard: teamWorkers(),
- agentAnswer: mockGenerator({ script: [...callOnce("Ask helper-a about the colour", "messageWorker", { to: "helper-a", text: "What colour?" }, ""), fallback] })
+ agentAnswer: mockGenerator({ script: [...callOnce("Ask helper-a about the colour", "sendMessage", { to: "helper-a", text: "What colour?" }, ""), fallback] })
});
try {
// front routes every line to otto, its one delegate, in otto's ongoing session for the conversation.
@@ -658,7 +658,7 @@ describe("the hop count through a delegation", () => {
agentAnswer: mockGenerator({
script: [
quietAfterPing,
- ...callOnce("Please ping helper-a", "messageWorker", { to: "helper-a", text: "Just a ping." }, ""),
+ ...callOnce("Please ping helper-a", "sendMessage", { to: "helper-a", text: "Just a ping." }, ""),
...relayThroughTask({ ...setting, held: true })
]
})
@@ -728,7 +728,7 @@ describe("the hop count through a delegation", () => {
fallback
]
}),
- agentAnswer: mockGenerator({ script: [...callOnce("Please ask chief", "messageWorker", { to: "chief", text: "Who takes this?" }, ""), fallback] })
+ agentAnswer: mockGenerator({ script: [...callOnce("Please ask chief", "sendMessage", { to: "chief", text: "Who takes this?" }, ""), fallback] })
});
try {
const otto = await h.client("alice").ensureWorkerSession({ worker: "otto" });
@@ -750,9 +750,9 @@ describe("the hop count through a delegation", () => {
standard: teamWorkers(),
agentAnswer: mockGenerator({
script: [
- ...callOnce("Tell otto the number", "messageWorker", { to: "otto", text: "The number is 7." }, ""),
+ ...callOnce("Tell otto the number", "sendMessage", { to: "otto", text: "The number is 7." }, ""),
...callOnce("have helper-b tell otto", "createTask", { goal: "Tell otto the number", assignee: "helper-b" }, ""),
- ...callOnce("Please ask helper-a", "messageWorker", { to: "helper-a", text: "Please have helper-b tell otto the number." }, ""),
+ ...callOnce("Please ask helper-a", "sendMessage", { to: "helper-a", text: "Please have helper-b tell otto the number." }, ""),
fallback
]
})
@@ -786,7 +786,7 @@ describe("who can be messaged", () => {
{ to: "eng.tasker", text: "Hi coder." },
{ to: "rota", text: "Hi rota." },
{ to: "otto", text: "Hi me." }
- ].map((args, i) => ({ toolCallId: `who-${i}`, toolName: "messageWorker", args }));
+ ].map((args, i) => ({ toolCallId: `who-${i}`, toolName: "sendMessage", args }));
let called = false;
const h = boot({
standard: teamWorkers(),
@@ -844,9 +844,9 @@ describe("who can be messaged", () => {
});
it("takes no sender, no wait and no other key: the tool's input is strict", () => {
- expect(messageWorkerInputSchema.safeParse({ to: "lead", text: "Hi." }).success).toBe(true);
- expect(messageWorkerInputSchema.safeParse({ to: "lead", text: "Hi.", from: "lead" }).success).toBe(false);
- expect(messageWorkerInputSchema.safeParse({ to: "lead", text: "Hi.", wait: true }).success).toBe(false);
+ expect(sendMessageInputSchema.safeParse({ to: "lead", text: "Hi." }).success).toBe(true);
+ expect(sendMessageInputSchema.safeParse({ to: "lead", text: "Hi.", from: "lead" }).success).toBe(false);
+ expect(sendMessageInputSchema.safeParse({ to: "lead", text: "Hi.", wait: true }).success).toBe(false);
});
});
@@ -864,7 +864,7 @@ describe("a busy recipient", () => {
});
const h = boot({
judgment,
- agentAnswer: mockGenerator({ script: [...callOnce("ask the lead", "messageWorker", { to: "lead", text: "What is the codename?" }), fallback] }),
+ agentAnswer: mockGenerator({ script: [...callOnce("ask the lead", "sendMessage", { to: "lead", text: "What is the codename?" }), fallback] }),
afterModelCall: async (block) => {
if (block === "coordinator-judgment" && holding) {
holding = false;
@@ -895,12 +895,12 @@ describe("a busy recipient", () => {
});
describe("delivery", () => {
- /** Deliver `messageId` to `sessionId`'s onWorkerMessage again, as a second copy of the dispatch would. */
+ /** Deliver `messageId` to `sessionId`'s onMessageReceived again, as a second copy of the dispatch would. */
async function deliverAgain(h: BoardHost, flow: string, sessionId: string, messageId: string) {
const runtime = await h.state.getRuntime();
const run = await runAction({
flow: h.instances[flow]!,
- actionName: "onWorkerMessage",
+ actionName: "onMessageReceived",
input: { messageId },
userId: "alice",
orgId: ORG,
@@ -917,7 +917,7 @@ describe("delivery", () => {
const judgment = mockGenerator({ script: [{ when: (input) => textOf(input).includes("What is the codename?"), then: { text: "Thinking." } }, fallback] });
const h = boot({
judgment,
- agentAnswer: mockGenerator({ script: [...callOnce("ask the lead", "messageWorker", { to: "lead", text: "What is the codename?" }), fallback] })
+ agentAnswer: mockGenerator({ script: [...callOnce("ask the lead", "sendMessage", { to: "lead", text: "What is the codename?" }), fallback] })
});
try {
const otto = await agentSession(h, "alice", "otto");
@@ -941,10 +941,10 @@ describe("delivery", () => {
it("marks the row refused, and the tool says why, when the host refuses the dispatch", async () => {
const h = boot({
- agentAnswer: mockGenerator({ script: [...callOnce("ask the lead", "messageWorker", { to: "lead", text: "What is the codename?" }), fallback] })
+ agentAnswer: mockGenerator({ script: [...callOnce("ask the lead", "sendMessage", { to: "lead", text: "What is the codename?" }), fallback] })
});
try {
- const lost = await h.loseDispatches("onWorkerMessage");
+ const lost = await h.loseDispatches("onMessageReceived");
const otto = await agentSession(h, "alice", "otto");
await h.post("alice", otto, "respond", { message: "Please ask the lead" }, "agent");
await h.settled();
From 86f90914186f74b3b1e1c76a7c27f014e84d5225 Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 27 Oct 2026 21:19:00 +0000
Subject: [PATCH 02/14] feat(workforce): a received message is its own item,
and nothing is relayed (FIX-2238)
onMessageReceived lands a history-only line and a client-only
workforce:received component, and hands the flow's turn the received
message (id, from, text, call, inReplyTo, budget). The relay goes: a worker
answers with sendMessage and inReplyTo, or not at all.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
.../src/conversation-board/session-board.ts | 4 +-
.../src/messages/message-received-entry.ts | 247 +++++++++++-------
.../workforce/test/worker-messages.test.ts | 76 +++---
3 files changed, 200 insertions(+), 127 deletions(-)
diff --git a/packages/workforce/src/conversation-board/session-board.ts b/packages/workforce/src/conversation-board/session-board.ts
index 9e7552a175..cd25c07188 100644
--- a/packages/workforce/src/conversation-board/session-board.ts
+++ b/packages/workforce/src/conversation-board/session-board.ts
@@ -50,7 +50,7 @@ import { messageHopStateShape } from "../messages/hop";
import { workerMessagesResources } from "../messages/message-log";
import { defineSendMessageCapability } from "../messages/message-tool";
import { MESSAGE_RECEIVED_ENTRY } from "../messages/keys";
-import { messageReceivedEntry, messageReceivedStateShape } from "../messages/message-received-entry";
+import { messageReceivedEntry, messageReceivedStateShape, promptedMessageTurn } from "../messages/message-received-entry";
import { fileScheduledTaskEntry } from "../schedules/file-scheduled-task";
import { FILE_SCHEDULED_TASK_ENTRY } from "../schedules/keys";
import { ROUTED_FROM_STATE_KEY, WORK_PROJECT_STATE_KEY } from "../workers/keys";
@@ -249,7 +249,7 @@ export function defineSessionBoard(options: SessionBoardOptions) {
// The turn a steer no request took is owed (FIX-2086 D2), on the
// notices' line: the claim gate's check and the steer's write start it.
[STEER_TURN_ENTRY]: steerTurnEntry({ name: "conversation-steer-turn", turn }),
- [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ turn, installation: options.installation, flowKind: options.flowKind }),
+ [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ turn: promptedMessageTurn(turn), installation: options.installation, flowKind: options.flowKind }),
[FILE_SCHEDULED_TASK_ENTRY]: fileScheduledTaskEntry(board.actions[SCREEN_FILING_ACTION]!, async (ctx) =>
soleTaskDelegate(await delegates.taskDelegates(ctx))
)
diff --git a/packages/workforce/src/messages/message-received-entry.ts b/packages/workforce/src/messages/message-received-entry.ts
index d78ab3021a..7fe4b086e3 100644
--- a/packages/workforce/src/messages/message-received-entry.ts
+++ b/packages/workforce/src/messages/message-received-entry.ts
@@ -1,22 +1,22 @@
/**
- * How a worker hears a message (FIX-1989): the `onMessageReceived` internal
- * entry, on every flow that carries the session kit.
+ * How a worker hears a message (FIX-1989, FIX-2238): the `onMessageReceived`
+ * internal entry, on every worker flow. The hire refuses a worker flow
+ * without it ({@link messageReceivedProblem}).
*
* The payload names a message id and nothing else: the row in the user's
- * message log is read here, so the sender, the text and the hop count are
- * what the sending turn's server code wrote. The entry acts on a message id
- * once (a versioned dedupe write in this session), so a copy sent twice wakes
- * the recipient once. Then the message lands as a line under the sender's
- * name, the session's hop count and chain become the message's, and the recipient's
- * turn is woken to read it and decide whether it needs an answer. A worker in
+ * message log is read here, so the sender, the text and the budget are what
+ * the sending turn's server code wrote. The entry acts on a message id once
+ * (a versioned dedupe write in this session), so a copy sent twice wakes the
+ * recipient once. Then the message lands as two items: a line the model reads
+ * in its history, and a client-only `workforce:received` component carrying
+ * the sender, the id and the message it answers, for an app to draw. The
+ * session's hop count and chain become the message's, and the flow's turn,
+ * when it has one, runs with {@link MessageReceived} as its input. A worker in
* the middle of a turn hears it after that turn, as a task's notice does: the
* entry waits on the reply line.
*
- * A woken turn that ends with text and never messaged the sender back has its
- * text sent as the answer, through the same send a `sendMessage` reply takes
- * (inReplyTo, hop, log row, wake). A turn with no text sends nothing, and a turn
- * woken by an answer is never relayed, so an exchange ends after one answer.
- * The relay is pending a product decision (DECISIONS.md D2, amended).
+ * Nothing is relayed: a woken worker that wants to answer sends one with
+ * `sendMessage` and `inReplyTo`, and one that ends in plain text answers no one.
*/
import { handler, sequencer } from "@flow-state-dev/core";
import { withOutcome } from "@flow-state-dev/core/helpers";
@@ -24,23 +24,38 @@ import type { BlockDefinition } from "@flow-state-dev/core/types";
import { z } from "zod";
import { AFTER_REPLY_CONCURRENCY } from "../conversation-board/task-settled";
import type { WorkerInstallation } from "../workers/installation";
-import { messageTurnStateSchema, startTurnAtHop, TURN_MESSAGED_STATE } from "./hop";
-import { SEND_MESSAGE_TOOL, WORKER_MESSAGES_SEEN_STATE } from "./keys";
-import { MAX_MESSAGE_CHARS } from "./log-row";
-import { sendMessage } from "./send-message";
+import { messageTurnStateSchema, startTurnAtHop } from "./hop";
+import { MESSAGE_RECEIVED_ENTRY, RECEIVED_MESSAGE_COMPONENT, SEND_MESSAGE_TOOL, WORKER_MESSAGES_SEEN_STATE } from "./keys";
+import { messageLimitsOf } from "./message-limits";
import { messageLogOf, workerMessagesResources } from "./message-log";
/** What the entry takes: the message's id, and nothing a sender could shape. */
export const messageReceivedInputSchema = z.object({ messageId: z.string().min(1) }).strict();
+/** What a flow's turn hears: every field from the message's row and its chain, none from a sender's input. */
+export const messageReceivedSchema = z.object({
+ /** The message's id: what an answer names as `inReplyTo`. */
+ id: z.string(),
+ /** The worker that sent it, as the server recorded it. */
+ from: z.string(),
+ text: z.string(),
+ /** Whether the sender waits on this turn's result. Always `false` until calls (FIX-2239). */
+ call: z.boolean(),
+ /** The message this one answers, when it is an answer. */
+ inReplyTo: z.string().optional(),
+ /** How many more messages the exchange may send after this one. */
+ budget: z.number().int().nonnegative()
+});
-/** The request-state field naming the message that woke this turn, when its text may be relayed. */
-const RELAY_STATE = "workforceRelayTo";
+/** {@link messageReceivedSchema}'s type. */
+export type MessageReceived = z.infer;
-/** The request state the relay reads: the message to answer, and who sent it. */
-const relayStateSchema = messageTurnStateSchema.extend({
- [RELAY_STATE]: z.object({ id: z.string(), from: z.string() }).optional()
-});
+/**
+ * Where a worker hears messages. `"task-sessions"`: only in its tasks'
+ * sessions, so a message to it by name is refused before anything is written
+ * (`task_sessions_only`). Absent: wherever a message lands.
+ */
+export type MessageHearing = "task-sessions";
/** The most message ids a session keeps for its dedupe. */
const MAX_SEEN = 500;
@@ -50,39 +65,102 @@ export const messageReceivedStateShape = {
[WORKER_MESSAGES_SEEN_STATE]: z.array(z.string()).default([])
} as const;
-const heardSchema = z.object({
- act: z.enum(["none", "line", "wake-turn"]),
- from: z.string().optional(),
- line: z.string().optional(),
- prompt: z.string().optional()
-});
+/**
+ * The mark `messageReceivedEntry` puts on what it builds, carrying `hears`.
+ * Enumerable, so it survives the spreads a flow is built with; a registered
+ * symbol, so two installed copies of this package read each other's mark.
+ */
+const RECEIVED_MARK = Symbol.for("@flow-state-dev/workforce/message-received");
-type Heard = z.infer;
+/** What the mark carries. */
+interface ReceivedMark {
+ readonly hears?: MessageHearing;
+}
+
+/** The mark on `entry`, or `undefined` for an entry `messageReceivedEntry` didn't build. */
+function receivedMarkOf(entry: unknown): ReceivedMark | undefined {
+ if (typeof entry !== "object" || entry === null) return undefined;
+ return (entry as Record)[RECEIVED_MARK];
+}
+
+/** A flow definition's internal actions, or `undefined` for one with none. */
+function internalActionsOf(flow: unknown): Readonly> | undefined {
+ return (flow as { internal?: { actions?: Record } } | undefined)?.internal?.actions;
+}
+
+/**
+ * Where `flow`'s worker hears messages: the `hears` its `onMessageReceived`
+ * declares, `"anywhere"` when it declares none, or `undefined` when the flow
+ * has no entry `messageReceivedEntry` built. The one reader of the mark: the
+ * hire, the send and the tool's list all read it here.
+ */
+export function messageHearingOf(flow: unknown): MessageHearing | "anywhere" | undefined {
+ const mark = receivedMarkOf(internalActionsOf(flow)?.[MESSAGE_RECEIVED_ENTRY]);
+ if (mark === undefined) return undefined;
+ return mark.hears ?? "anywhere";
+}
+
+/**
+ * Why `name`'s flow can't hear a message, or `undefined` when it can: its
+ * internal `onMessageReceived` was built by {@link messageReceivedEntry} and
+ * takes `{ messageId }`. The hire's check, beside `respond`'s.
+ *
+ * @param name The worker flow's name, for the sentence.
+ * @param internal The flow's internal actions.
+ */
+export function messageReceivedProblem(name: string, internal: Readonly> | undefined): string | undefined {
+ const entry = internal?.[MESSAGE_RECEIVED_ENTRY] as { inputSchema?: { safeParse?: (v: unknown) => { success: boolean } } } | undefined;
+ const fix =
+ `Build it with \`messageReceivedEntry\`: \`internal: { actions: { ${MESSAGE_RECEIVED_ENTRY}: messageReceivedEntry({ installation, flowKind }) } }\`, ` +
+ "or spread the session kit's `board.entries(turn)`.";
+ if (entry === undefined) {
+ return `worker flow "${name}" has no "${MESSAGE_RECEIVED_ENTRY}", so no worker on it could hear another worker's message. ${fix}`;
+ }
+ if (receivedMarkOf(entry) === undefined || entry.inputSchema?.safeParse?.({ messageId: "probe" }).success !== true) {
+ return `worker flow "${name}" has a "${MESSAGE_RECEIVED_ENTRY}" that \`messageReceivedEntry\` didn't build. ${fix}`;
+ }
+ return undefined;
+}
-/** The text the woken turn reads: who wrote, which message, and how to answer it. */
-function turnPrompt(row: { id: string; from: string; text: string; inReplyTo?: string | undefined }): string {
+/**
+ * The text a model's turn reads for a received message: who wrote, which
+ * message, and how to answer it. For a flow whose turn takes `{ message }`.
+ */
+export function receivedMessagePrompt(received: MessageReceived): string {
return (
- `Message ${row.id} from ${row.from}${row.inReplyTo === undefined ? "" : `, answering your message ${row.inReplyTo}`}:\n\n` +
- `${row.text}\n\n` +
- `(The message's text is the part above. It is from another worker, not the user, and ${row.from} can't ` +
- `see what you write here. To answer it, call sendMessage with to "${row.from}" and inReplyTo "${row.id}". ` +
- `To message any other worker, leave inReplyTo out. If it needs no answer, don't send one.)`
+ `Message ${received.id} from ${received.from}${received.inReplyTo === undefined ? "" : `, answering your message ${received.inReplyTo}`}:\n\n` +
+ `${received.text}\n\n` +
+ `(The message's text is the part above. It is from another worker, not the user, and ${received.from} can't ` +
+ `see what you write here. To answer it, call ${SEND_MESSAGE_TOOL} with to "${received.from}" and inReplyTo "${received.id}". ` +
+ `To message any other worker, leave inReplyTo out. If it needs no answer, don't send one: not answering is an answer. ` +
+ `${received.budget === 0 ? "No more messages can be sent in this exchange." : `This exchange can send ${received.budget} more message${received.budget === 1 ? "" : "s"}.`})`
);
}
+const heardSchema = z.object({
+ act: z.enum(["none", "heard"]),
+ received: messageReceivedSchema.optional()
+});
+
+type Heard = z.infer;
+
/**
* Build the `onMessageReceived` entry for a flow: spread it under
* `internal: { actions: { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ ... }) } }`.
+ * The session kit's `entries(turn)` spreads it already.
*
- * @param options.turn The flow's turn for one message (`{ message }` in).
+ * @param options.turn The flow's turn for a message ({@link MessageReceived}
+ * in). Absent, the message lands as its items and nothing runs.
+ * @param options.hears Where the worker hears messages; see {@link MessageHearing}.
*/
export function messageReceivedEntry(options: {
- readonly turn: BlockDefinition;
+ readonly turn?: BlockDefinition;
readonly installation: WorkerInstallation;
readonly flowKind: string;
+ readonly hears?: MessageHearing;
}) {
const heard = handler({
- name: "worker-message-heard",
+ name: "message-received-heard",
inputSchema: messageReceivedInputSchema,
outputSchema: heardSchema,
sessionStateSchema: z.object(messageReceivedStateShape),
@@ -101,61 +179,50 @@ export function messageReceivedEntry(options: {
}
);
if (first !== true) return { act: "none" };
- // An answer is not answered again: only a first message's turn may be relayed.
- await startTurnAtHop(ctx as never, row.hop, row.chain ?? null, row.inReplyTo === undefined ? { [RELAY_STATE]: { id: row.id, from: row.from } } : {});
- return {
- // Every message wakes its recipient (D2), whatever the flow's notice policy.
- act: "wake-turn",
+ await startTurnAtHop(ctx as never, row.hop, row.chain ?? null);
+ const { hopLimit } = messageLimitsOf(options.installation);
+ const received: MessageReceived = {
+ id: row.id,
from: row.from,
- line: `From ${row.from}: ${row.text}`,
- prompt: turnPrompt(row)
+ text: row.text,
+ call: false,
+ ...(row.inReplyTo === undefined ? {} : { inReplyTo: row.inReplyTo }),
+ budget: Math.max(0, hopLimit - row.hop)
};
- }
- });
-
- /** The message, as a line in the conversation, under the sender's name. */
- const line = handler({
- name: "worker-message-line",
- inputSchema: heardSchema,
- outputSchema: z.object({}),
- execute: (got: Heard, ctx) => {
- ctx.emit.message(got.line ?? "", got.from === undefined ? {} : { agentName: got.from });
- return {};
- }
- });
-
- /** The woken turn's text as its answer, when it ended with some and never messaged the sender back. */
- const relay = handler({
- name: "worker-message-relay",
- inputSchema: z.unknown(),
- outputSchema: z.object({}),
- requestStateSchema: relayStateSchema,
- resources: { ...options.installation.resources, ...workerMessagesResources },
- execute: async (reply: unknown, ctx) => {
- const state = (ctx.request.state ?? {}) as Record;
- const woke = relayStateSchema.shape[RELAY_STATE].safeParse(state[RELAY_STATE]).data;
- if (woke === undefined) return {};
- const messaged = Array.isArray(state[TURN_MESSAGED_STATE]) ? (state[TURN_MESSAGED_STATE] as string[]) : [];
- if (messaged.includes(woke.from)) return {};
- const raw = typeof reply === "string" ? reply : (reply as { text?: unknown } | null)?.text;
- const text = typeof raw === "string" ? raw.trim() : "";
- if (text.length === 0) return {};
- const body = text.length > MAX_MESSAGE_CHARS ? `${text.slice(0, MAX_MESSAGE_CHARS - 1)}…` : text;
- await sendMessage(ctx as never, options.installation, options.flowKind, { to: woke.from, text: body, inReplyTo: woke.id }, SEND_MESSAGE_TOOL);
- return {};
+ // The two items, in one place, after the dedupe: the line the model
+ // reads, and the item an app draws.
+ ctx.emit.message(`From ${row.from}: ${row.text}`, { agentName: row.from, itemVisibility: { client: false, history: true } });
+ ctx.emit.component(
+ RECEIVED_MESSAGE_COMPONENT,
+ { id: row.id, from: row.from, text: row.text, ...(row.inReplyTo === undefined ? {} : { inReplyTo: row.inReplyTo }) },
+ { agentName: row.from, itemVisibility: { client: true, history: false } }
+ );
+ return { act: "heard", received };
}
});
// A message is conversation, never part of a task, with no claim on it:
// one to a task session whose turn is running runs after that turn.
- const block = sequencer({ name: "worker-message-arrived", inputSchema: messageReceivedInputSchema })
- .step(heard)
- .tapIf((got: Heard) => got.act !== "none", line)
- .tapIf(
- (got: Heard) => got.act === "wake-turn",
- (got: Heard) => ({ message: got.prompt ?? "" }),
- sequencer({ name: "worker-message-turn", inputSchema: z.object({ message: z.string() }) }).step(options.turn).step(relay)
- );
-
- return { inputSchema: messageReceivedInputSchema, block, concurrency: AFTER_REPLY_CONCURRENCY };
+ let block = sequencer({ name: "message-received", inputSchema: messageReceivedInputSchema }).step(heard);
+ if (options.turn !== undefined) {
+ block = block.tapIf(
+ (got: Heard) => got.act === "heard",
+ (got: Heard) => got.received,
+ options.turn
+ ) as typeof block;
+ }
+
+ const entry = { inputSchema: messageReceivedInputSchema, block, concurrency: AFTER_REPLY_CONCURRENCY };
+ const mark: ReceivedMark = options.hears === undefined ? {} : { hears: options.hears };
+ (entry as Record)[RECEIVED_MARK] = mark;
+ return entry;
+}
+
+/**
+ * A turn that takes `{ message }` as a turn for {@link messageReceivedEntry}:
+ * its input is {@link receivedMessagePrompt}'s text.
+ */
+export function promptedMessageTurn(turn: BlockDefinition, name = "message-received-turn") {
+ return sequencer({ name, inputSchema: messageReceivedSchema })
+ .step((received: MessageReceived) => ({ message: receivedMessagePrompt(received) }), turn);
}
diff --git a/packages/workforce/test/worker-messages.test.ts b/packages/workforce/test/worker-messages.test.ts
index 6a20030abd..1ade9ed555 100644
--- a/packages/workforce/test/worker-messages.test.ts
+++ b/packages/workforce/test/worker-messages.test.ts
@@ -87,6 +87,16 @@ async function logRows(h: BoardHost, userId: string) {
return Object.values(entries).map((value) => value.state as Record);
}
+/** Every item a session holds, oldest first, as stored. */
+async function itemsOf(h: BoardHost, sessionId: string): Promise {
+ return (await h.requestsOf(sessionId)).flatMap((request) => (request as unknown as { items?: any[] }).items ?? []);
+}
+
+/** The received-message items a session holds: the client-only component a received message is drawn by. */
+async function receivedIn(h: BoardHost, sessionId: string): Promise[]> {
+ return (await itemsOf(h, sessionId)).filter((item) => item.type === "component" && item.component === "workforce:received").map((item) => item.data);
+}
+
/** Every tool output item a session holds, oldest first. */
async function toolOutputs(h: BoardHost, sessionId: string): Promise {
return (await h.requestsOf(sessionId))
@@ -96,7 +106,7 @@ async function toolOutputs(h: BoardHost, sessionId: string): Promise
}
describe("a worker messages another worker", () => {
- it("lands a line from the sender in the recipient's own conversation, opened at its derived address, and wakes its turn", async () => {
+ it("lands as its own item in the recipient's own conversation, opened at its derived address, with a history line its turn reads, and wakes its turn", async () => {
const judgment = mockGenerator({ script: [{ when: (input) => textOf(input).includes("What is the codename?"), then: { text: "Thinking." } }, fallback] });
const h = boot({
judgment,
@@ -109,14 +119,18 @@ describe("a worker messages another worker", () => {
const lead = await h.client("alice").findWorkerSession({ worker: "lead" });
expect(lead, "the lead's conversation was opened").toBeDefined();
- const lines = await h.messages(lead!.id);
- expect(lines).toContainEqual({ agentName: "otto", text: "From otto: What is the codename?" });
- expect(lines.some((line) => line.text === "Thinking."), "the lead's turn ran").toBe(true);
-
const rows = await logRows(h, "alice");
- // The lead's "Thinking." is relayed back as its answer; the message itself is the first row.
- expect(rows.map((row) => row.from).sort()).toEqual(["lead", "otto"]);
- expect(rows.find((row) => row.from === "otto")).toMatchObject({ from: "otto", to: "lead", text: "What is the codename?", status: "delivered", hop: 1, fromSession: otto, toSession: lead!.id });
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({ from: "otto", to: "lead", text: "What is the codename?", status: "delivered", hop: 1, fromSession: otto, toSession: lead!.id });
+
+ // Its own item: the sender, the id and the text, drawn by the client only.
+ expect(await receivedIn(h, lead!.id)).toEqual([{ id: rows[0]!.id, from: "otto", text: "What is the codename?" }]);
+ const items = await itemsOf(h, lead!.id);
+ expect(items.find((item) => item.type === "component")?.itemVisibility).toEqual({ client: true, history: false });
+ // The line the model reads, in history only.
+ const line = items.find((item) => item.type === "message" && item.agentName === "otto");
+ expect(line?.itemVisibility).toEqual({ client: false, history: true });
+ expect((await h.messages(lead!.id)).some((m) => m.text === "Thinking."), "the lead's turn ran").toBe(true);
// A message is not a task.
expect(await h.rows("alice")).toEqual([]);
} finally {
@@ -185,30 +199,20 @@ describe("the log, read by an app", () => {
});
describe("an answer", () => {
- it("is the woken turn's own text when it ends without messaging the sender back, sent as a reply that wakes the sender", async () => {
+ it("is never the woken turn's own text: a turn that ends in plain text sends nothing back", async () => {
const h = boot({
// The lead answers in plain text, with no sendMessage call.
judgment: mockGenerator({ script: [{ when: (input) => textOf(input).includes("What is the codename?"), then: { text: "It is Bluebird." } }, fallback] }),
- agentAnswer: mockGenerator({
- script: [
- { when: (input) => textOf(input).includes("From lead: It is Bluebird."), then: { text: "The codename is Bluebird." } },
- ...callOnce("ask the lead", "sendMessage", { to: "lead", text: "What is the codename?" }),
- fallback
- ]
- })
+ agentAnswer: mockGenerator({ script: [...callOnce("ask the lead", "sendMessage", { to: "lead", text: "What is the codename?" }), fallback] })
});
try {
const otto = await agentSession(h, "alice", "otto");
await h.post("alice", otto, "respond", { message: "Please ask the lead" }, "agent");
await h.settled();
- const rows = await logRows(h, "alice");
- const question = rows.find((row) => row.from === "otto")!;
- expect(rows.find((row) => row.from === "lead")).toMatchObject({
- to: "otto", text: "It is Bluebird.", inReplyTo: question.id, toSession: otto, status: "delivered", hop: 2
- });
- expect((await h.messages(otto)).at(-1)?.text, "otto's turn ran after the answer").toBe("The codename is Bluebird.");
- // otto's text, in a turn woken by an answer, is not sent back: the exchange ends.
- expect(rows).toHaveLength(2);
+ const lead = await h.client("alice").findWorkerSession({ worker: "lead" });
+ expect((await h.messages(lead!.id)).some((m) => m.text === "It is Bluebird."), "the lead's turn ran").toBe(true);
+ expect((await logRows(h, "alice")).map((row) => row.from)).toEqual(["otto"]);
+ expect(await receivedIn(h, otto)).toEqual([]);
} finally {
await h.dispose();
}
@@ -262,12 +266,12 @@ describe("an answer", () => {
await h.settled();
const lines = await h.messages(otto);
- expect(lines).toContainEqual({ agentName: "lead", text: "From lead: It is Bluebird." });
expect(lines.at(-1)?.text, "otto's turn ran after the answer").toBe("The codename is Bluebird.");
const rows = await logRows(h, "alice");
const question = rows.find((row) => row.from === "otto")!;
const answer = rows.find((row) => row.from === "lead")!;
+ expect(await receivedIn(h, otto)).toEqual([{ id: answer.id, from: "lead", text: "It is Bluebird.", inReplyTo: question.id }]);
expect(answer).toMatchObject({ to: "otto", inReplyTo: question.id, exchange: question.id, toSession: otto, status: "delivered", hop: 2 });
} finally {
await h.dispose();
@@ -329,31 +333,33 @@ describe("a message sent from a task's turn", () => {
* it on to the next worker once; the user's line in otto's conversation
* starts it.
*/
-function ringScript(after = ""): MockGeneratorScriptEntry[] {
+function ringScript(options: { answer?: boolean } = {}): MockGeneratorScriptEntry[] {
const next: Record = { otto: "helper-a", "helper-a": "helper-b", "helper-b": "otto" };
const handled = new Set();
- const step = { toolCalls: [{ toolCallId: "pass", toolName: "sendMessage", args: {} as Record }] };
+ const step = { toolCalls: [] as Array<{ toolCallId: string; toolName: string; args: Record }> };
return [
{
when: (input: unknown) => {
const text = textOf(input);
- const all = [...text.matchAll(/Message (msg_\w+) from ([\w.-]+)/g)];
+ const all = [...text.matchAll(/Message (msg_\w+) from ([\w.-]+)(, answering)?/g)];
const started = text.lastIndexOf("start the ring");
const last = all.at(-1);
// Whichever came last: the user's line, or a message.
const key = last !== undefined && last.index! > started ? last[1]! : `user-${started}`;
if (handled.has(key) || (last === undefined && started < 0)) return false;
handled.add(key);
- const me = last !== undefined && last.index! > started ? next[last[2]!]! : "otto";
- step.toolCalls[0]!.toolCallId = `pass-${key}`;
- step.toolCalls[0]!.args = { to: next[me]!, text: "Pass this on to the next one, always." };
+ const woken = last !== undefined && last.index! > started;
+ const me = woken ? next[last[2]!]! : "otto";
+ step.toolCalls = [{ toolCallId: `pass-${key}`, toolName: "sendMessage", args: { to: next[me]!, text: "Pass this on to the next one, always." } }];
+ // With `answer`, a worker woken by a first message also answers its sender, so the exchange branches.
+ if (options.answer === true && woken && last[3] === undefined) {
+ step.toolCalls.push({ toolCallId: `answer-${key}`, toolName: "sendMessage", args: { to: last[2]!, text: "Passed it on.", inReplyTo: last[1]! } });
+ }
return true;
},
then: step
},
- // No text after passing it on, so no answer is relayed back down the ring,
- // unless the test asks for some.
- { when: () => true, then: { text: after } }
+ { when: () => true, then: { text: "" } }
];
}
@@ -417,7 +423,7 @@ describe("the hop limit across a branching exchange", () => {
// limit is the whole exchange's, so the exchange stops at 6 messages in all,
// not at 6 down each branch.
it("stops everything descending from one user's line at 6 messages in all", async () => {
- const h = boot({ standard: teamWorkers(), agentAnswer: mockGenerator({ script: ringScript("Passed it on.") }) });
+ const h = boot({ standard: teamWorkers(), agentAnswer: mockGenerator({ script: ringScript({ answer: true }) }) });
try {
const otto = await h.client("alice").ensureWorkerSession({ worker: "otto" });
await h.post("alice", otto.id, "respond", { message: "Please start the ring" }, "agent");
From f201a3e199998365ce97f382a28769faa2dd94c6 Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 27 Oct 2026 21:38:40 +0000
Subject: [PATCH 03/14] FIX-2238: landing rules, task-sessions refusal and one
budget
An answer lands in its original's session; a message to the filer lands in
the filing session (new readonly filingWorkerId). Workers that hear only in
their tasks' sessions are refused by name before the row is written. The
delegate's ongoing session is born with its filer's count, and a task held
from its filing starts a fresh chain when released.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDJDLpHhanaY6z9YCB
---
.../run.mts | 1 -
.../holds-a-task-waiting-on-a-person/run.mts | 1 -
.../settles-when-its-work-is-over/run.mts | 1 -
.../shift-manager/test/messages-view.test.tsx | 1 -
.../workforce/src/conversation-board/board.ts | 28 ++-
packages/workforce/src/messages/hop.ts | 18 ++
packages/workforce/src/messages/index.ts | 2 +-
packages/workforce/src/messages/log-row.ts | 6 +-
.../workforce/src/messages/message-tool.ts | 7 +-
.../workforce/src/messages/send-message.ts | 190 ++++++++----------
packages/workforce/src/workers/index.ts | 1 +
.../workforce/src/workers/installation.ts | 13 +-
packages/workforce/src/workers/keys.ts | 9 +
.../test/conversation-board-harness.ts | 10 +-
.../message-to-a-busy-task-session.test.ts | 1 -
.../workforce/test/worker-messages.test.ts | 118 +++++++----
16 files changed, 241 insertions(+), 166 deletions(-)
diff --git a/goals/task-board/background-error-fails-the-attempt/run.mts b/goals/task-board/background-error-fails-the-attempt/run.mts
index 9c2c0d7a2e..aaf76b1214 100644
--- a/goals/task-board/background-error-fails-the-attempt/run.mts
+++ b/goals/task-board/background-error-fails-the-attempt/run.mts
@@ -243,7 +243,6 @@ function buildHost(filename: string) {
fromFlow: "doer",
toSession: sessionId,
toFlow: "doer",
- answerTo: { sessionId, flow: "doer" },
hop: 1,
status: "delivered",
at: Date.now()
diff --git a/goals/task-board/holds-a-task-waiting-on-a-person/run.mts b/goals/task-board/holds-a-task-waiting-on-a-person/run.mts
index f519ad7a94..2b7d4984ae 100644
--- a/goals/task-board/holds-a-task-waiting-on-a-person/run.mts
+++ b/goals/task-board/holds-a-task-waiting-on-a-person/run.mts
@@ -377,7 +377,6 @@ function buildHost(filename: string, settings: { userDeadlineMs?: number } = {})
fromFlow: "doer",
toSession: sessionId,
toFlow: "doer",
- answerTo: { sessionId, flow: "doer" },
hop: 1,
status: "delivered",
at: Date.now()
diff --git a/goals/task-board/settles-when-its-work-is-over/run.mts b/goals/task-board/settles-when-its-work-is-over/run.mts
index 9bd896ea40..a2c7d1ae41 100644
--- a/goals/task-board/settles-when-its-work-is-over/run.mts
+++ b/goals/task-board/settles-when-its-work-is-over/run.mts
@@ -191,7 +191,6 @@ function buildHost(filename: string) {
fromFlow: "doer",
toSession: sessionId,
toFlow: "doer",
- answerTo: { sessionId, flow: "doer" },
hop: 1,
status: "delivered",
at: Date.now()
diff --git a/packages/shift-manager/test/messages-view.test.tsx b/packages/shift-manager/test/messages-view.test.tsx
index d1463d5db9..7d9fde33e5 100644
--- a/packages/shift-manager/test/messages-view.test.tsx
+++ b/packages/shift-manager/test/messages-view.test.tsx
@@ -25,7 +25,6 @@ const row = (over: Partial & Pick {
+ const worker = (state as Record | undefined)?.[WORKER_ID_STATE_KEY];
+ return typeof worker === "string" && worker.length > 0 ? { [FILING_WORKER_STATE_KEY]: worker } : {};
+}
+
/**
* Whether a row this board can start is waiting: startable ({@link isStartable})
* and claimable now (a dead run's row included). Such a row is owed a run of
@@ -812,6 +819,7 @@ export function defineConversationBoard(options: ConversationBoardOptions) {
[WORKER_ID_STATE_KEY]: task.assignee,
[FILING_SESSION_STATE_KEY]: partition,
[FILING_FLOW_STATE_KEY]: options.flowKind,
+ ...filingWorkerOf(ctx.session.state),
[TASK_ID_STATE_KEY]: task.taskId,
[TASK_CHAIN_STATE_KEY]: chainOfFiling(ctx, partition, task.taskId).birth,
...carriedHopState(ctx.session.state),
@@ -933,14 +941,18 @@ export function defineConversationBoard(options: ConversationBoardOptions) {
const partition = await filingSessionIdOf(ctx.session);
const flow = (await reach(ctx)).available.get(task.assignee);
// The delegate's ongoing session for the conversation works no one
- // task (FIX-2080): born naming its worker, the conversation and the
- // flow that filed into it, and no task or chain place. One that exists
- // keeps its own state.
+ // task (FIX-2080): born naming its worker, the worker, conversation and
+ // flow that filed into it, and no task or task-chain place. It counts
+ // its messages on in its filer's budget (FIX-2238), so its notices,
+ // steers and posts never start a fresh one. One that exists keeps its
+ // own state.
if ((await sessionSettingOf(ctx, task.taskId)).session === "ongoing") {
return {
[WORKER_ID_STATE_KEY]: task.assignee,
[FILING_SESSION_STATE_KEY]: partition,
[FILING_FLOW_STATE_KEY]: options.flowKind,
+ ...filingWorkerOf(ctx.session.state),
+ ...carriedHopState(ctx.session.state),
...(flow !== undefined ? { [TASK_FLOW_STATE_KEY]: flow } : {})
};
}
@@ -953,6 +965,7 @@ export function defineConversationBoard(options: ConversationBoardOptions) {
[WORKER_ID_STATE_KEY]: task.assignee,
[FILING_SESSION_STATE_KEY]: partition,
[FILING_FLOW_STATE_KEY]: options.flowKind,
+ ...filingWorkerOf(ctx.session.state),
[TASK_ID_STATE_KEY]: taskId,
[TASK_CHAIN_STATE_KEY]: chainOfFiling(ctx, partition, taskId).birth,
// The filer's worker-message hop count and chain (FIX-1989): a
@@ -1132,11 +1145,12 @@ export function defineConversationBoard(options: ConversationBoardOptions) {
// project even after the conversation's changes (FIX-2161).
const root = init.followUpOf === undefined ? undefined : ref.get(init.followUpOf);
const { stamp: project, own } = await filedProjectFor(ctx, root);
- // The filing turn's hop count, which the task's turn starts at (FIX-2106).
+ // The filing turn's hop count, which the task's turn starts at
+ // (FIX-2106); a task held from its filing starts a fresh chain (FIX-2238).
const metadata = {
...(given ?? {}),
...(owner === undefined ? {} : { [PIECE_OF]: owner }),
- [FILED_HOP]: turnHopMark(ctx),
+ [FILED_HOP]: heldFromFiling(init) ? freshHopMark(ctx) : turnHopMark(ctx),
[FILED_PROJECT]: project
};
const input = ownProjectIn(init.input, own);
@@ -1773,7 +1787,7 @@ export function defineConversationBoard(options: ConversationBoardOptions) {
// no board marker in its metadata, and the session's own project in its input.
// The filing turn's hop count, which the task's turn starts at (FIX-2106).
const { stamp, own } = await filedProjectFor(ctx);
- const metadata = { ...callerMetadata(filing.metadata), [FILED_HOP]: turnHopMark(ctx), [FILED_PROJECT]: stamp };
+ const metadata = { ...callerMetadata(filing.metadata), [FILED_HOP]: heldFromFiling(filing) ? freshHopMark(ctx) : turnHopMark(ctx), [FILED_PROJECT]: stamp };
const input = ownProjectIn(filing.input, own);
const { metadata: _metadata, input: _input, ...rest } = filing;
const init: TaskInit & { id: string } = {
diff --git a/packages/workforce/src/messages/hop.ts b/packages/workforce/src/messages/hop.ts
index b626c55f39..6974d458e9 100644
--- a/packages/workforce/src/messages/hop.ts
+++ b/packages/workforce/src/messages/hop.ts
@@ -132,6 +132,24 @@ export function turnHopMark(ctx: Pick): Hop
return { hop: turnHopOf(ctx), chain: turnChainOf(ctx) ?? null, lines: sessionUserLinesOf(ctx.session.state) };
}
+/**
+ * The mark for a task filed held (FIX-2238): released, it starts a fresh
+ * chain at 0, its first send minting one, since no exchange waits on it. The
+ * filer's user lines are kept, so a user's line since still clears it.
+ */
+export function freshHopMark(ctx: Pick): HopMark {
+ return { hop: 0, chain: null, lines: sessionUserLinesOf(ctx.session.state) };
+}
+
+/**
+ * Whether a filing holds its task from the start: filed `held`, or waiting on
+ * questions. Released, such a task starts a fresh chain ({@link freshHopMark});
+ * a midway hold carries its budget on.
+ */
+export function heldFromFiling(init: { readonly held?: boolean; readonly status?: string; readonly questions?: readonly unknown[] }): boolean {
+ return init.held === true || init.status === "held" || (init.questions?.length ?? 0) > 0;
+}
+
const hopMarkSchema = z.object({
hop: z.number().int().nonnegative(),
chain: z.string().min(1).nullable(),
diff --git a/packages/workforce/src/messages/index.ts b/packages/workforce/src/messages/index.ts
index 983c9ce555..93c2f7cc89 100644
--- a/packages/workforce/src/messages/index.ts
+++ b/packages/workforce/src/messages/index.ts
@@ -18,4 +18,4 @@ export {
} from "./message-log";
export { DEFAULT_MESSAGE_HOP_LIMIT, DEFAULT_MESSAGES_PER_TURN, type MessageLimits } from "./message-limits";
export { sendMessageInputSchema } from "./message-tool";
-export { sendMessage, takesWorkerMessages, type SendOutcome, type SendMessageInput } from "./send-message";
+export { sendMessage, type SendOutcome, type SendMessageInput } from "./send-message";
diff --git a/packages/workforce/src/messages/log-row.ts b/packages/workforce/src/messages/log-row.ts
index 0a5ecd69ad..250e7a0527 100644
--- a/packages/workforce/src/messages/log-row.ts
+++ b/packages/workforce/src/messages/log-row.ts
@@ -21,7 +21,7 @@ export const WORKER_MESSAGES_RESOURCE = "workforceMessages";
/** The longest text a message may carry. A longer one is refused, not cut (BP-042). */
export const MAX_MESSAGE_CHARS = 8_000;
-/** Where a message is delivered, or where an answer to it goes: a session on a worker flow, and the state it starts with when it isn't there yet. */
+/** Where a message is delivered: a session on a worker flow, and the state it starts with when it isn't there yet. */
export const messageAddressSchema = z
.object({
sessionId: z.string().min(1),
@@ -48,15 +48,13 @@ export const workerMessageRowSchema = z.object({
exchange: z.string().min(1),
/** The message this one answers. */
inReplyTo: z.string().optional(),
- /** The session the sending turn ran in. */
+ /** The session the sending turn ran in: where an answer to this message lands. */
fromSession: z.string().min(1),
/** The flow the sending session runs on. */
fromFlow: z.string().min(1),
/** Where this message was delivered. */
toSession: z.string().min(1),
toFlow: z.string().min(1),
- /** Where an answer to this message goes: the sending session, or the sender's own conversation when that session was a task's. */
- answerTo: messageAddressSchema,
/** How many worker messages this one is from the last user's turn, counted across the whole exchange. */
hop: z.number().int().min(1),
/** The chain the hop is counted in: the user's turn the exchange descends from. Absent on rows from before rows carried one. */
diff --git a/packages/workforce/src/messages/message-tool.ts b/packages/workforce/src/messages/message-tool.ts
index 4b24554749..d51e53421d 100644
--- a/packages/workforce/src/messages/message-tool.ts
+++ b/packages/workforce/src/messages/message-tool.ts
@@ -5,7 +5,7 @@
*
* Its input is strict (`to`, `text`, `inReplyTo`), so a call can't name a
* sender, a hop count or a session, and there is no `wait`: an answer arrives
- * later as a line from the recipient and wakes this worker. Its description
+ * later as a message of the recipient's own and wakes this worker. Its description
* lists who the worker can message, read before each model call: the roster's
* workers that have a conversation, by id and description.
*/
@@ -45,16 +45,15 @@ export const sendMessageOutputSchema = z.union([
const BASE_DESCRIPTION =
"Send a short message to another worker on your team: a question, an FYI, a heads-up. It lands in that worker's " +
"conversation and wakes it. This is not a task: nothing is filed and no result is owed, and you don't wait for an " +
- "answer. If it answers, the answer arrives later as a line from that worker and wakes you. To answer a message " +
+ "answer. If it answers, it sends you a message of its own, which wakes you. To answer a message " +
"you were sent, pass its id as inReplyTo. A message can't be waited on: to wait on a colleague's result before " +
"you answer, file a task for them with createTask, then call getTask({ id, wait: true }) where getTask takes wait.";
/** Who the running worker can message, as the description's list: every roster worker the send would take. */
async function recipientsLine(ctx: BlockContext, installation: WorkerInstallation, self: string): Promise {
const roster = await installation.roster(ctx as never);
- const refusals = await Promise.all(roster.map((worker) => recipientRefusal(ctx, installation, self, worker.id, worker)));
const listed = roster
- .filter((_, i) => refusals[i] === undefined)
+ .filter((worker) => recipientRefusal(installation, self, worker.id, worker) === undefined)
.slice(0, MAX_LISTED)
.map((worker) => {
const description = (worker.description ?? "").replace(/\s+/g, " ").trim();
diff --git a/packages/workforce/src/messages/send-message.ts b/packages/workforce/src/messages/send-message.ts
index 98b7aa4c98..a083e1b438 100644
--- a/packages/workforce/src/messages/send-message.ts
+++ b/packages/workforce/src/messages/send-message.ts
@@ -1,7 +1,6 @@
/**
- * Sending a worker message (FIX-1989): the one check every send passes, the
- * log row, and the delivery. The `sendMessage` tool calls it, and so will
- * any later caller (a coding run's tool, FIX-1990).
+ * Sending a worker message (FIX-1989, FIX-2238): the one check every send
+ * passes, the log row, and the delivery. The `sendMessage` tool calls it.
*
* The check, in order, before anything is written:
*
@@ -9,42 +8,41 @@
* - the recipient is another worker on the user's roster now (one of theirs or
* a standard one: another user's worker is simply not there), whose row
* reads;
- * - it has a conversation: its flow declares the `onMessageReceived` entry. A
- * worker that only takes tasks (the coder) is told to be filed a task;
- * - a coordinator whose routing never runs a turn of its own (round robin,
- * everyone) refuses: nobody would read the line;
+ * - the recipient hears messages by name: a worker whose `onMessageReceived`
+ * hears only in its tasks' sessions (the coder) is refused here,
+ * `task_sessions_only`;
* - an answer (`inReplyTo`) names a message the recipient sent this worker;
- * - the hop count stays within the limit, counted across the whole exchange
- * (`hop.ts`), and the turn within its sends.
+ * - the budget: one per message a user types (`hop.ts`), at most `perTurn`
+ * per request.
+ *
+ * The send is paid with its row: its place in the chain is taken in one
+ * guarded write that takes it only while the budget has one, and a send
+ * refused before that leaves nothing spent.
*
* Then one row is written to the user's message log, and the message is
- * dispatched to the recipient's `onMessageReceived`: into its own conversation
- * (the worker's derived address, opened by the dispatch when absent), or for
- * an answer, back where the row it answers says. A dispatch the host refuses
- * marks the row refused. A thrown one may have started, so it is sent again
- * once (the entry acts on a message id once); if that throws too, the row
- * stays unconfirmed.
+ * dispatched to the recipient's `onMessageReceived` where it lands: an answer
+ * in the session that sent the original, even after its task ended; a message
+ * from a task's session (or a delegate's) to the worker that filed it, in the
+ * session that filed it; any other in the recipient's own conversation (the
+ * worker's derived address, opened by the dispatch when absent; the project
+ * coordinator's for the sender's project). A dispatch the host refuses marks
+ * the row refused. A thrown one may have started, so it is sent again once
+ * (the entry acts on a message id once); if that throws too, the row stays
+ * unconfirmed.
*
- * The sender, the sessions and the hop count come from the sending turn's
- * own session and request state, never from the tool's input.
+ * The sender, the sessions and the budget come from the sending turn's own
+ * session and request state, never from the tool's input.
*/
import { dispatchThroughSeam, type BlockContext, type DispatchOutcome } from "@flow-state-dev/core/types";
import { withOutcome } from "@flow-state-dev/core/helpers";
-import { coordinatorRunsOwnTurn } from "../coordinator/coordinator-config";
-import { COORDINATOR_FLOW } from "../coordinator/coordinator-keys";
-import { filingProjectAddressOf } from "../conversation-board/filing-session";
+import { filingProjectAddressOf, sessionIdOfFiling } from "../conversation-board/filing-session";
import { deriveWorkerSessionId, criteriaState, type WorkerSessionCriteria } from "../workers/derive-session-id";
import type { RosterWorker, WorkerInstallation } from "../workers/installation";
-import {
- FILING_SESSION_STATE_KEY,
- TASK_ID_STATE_KEY,
- WORKER_ID_STATE_KEY,
- WORKERS_RESOURCE
-} from "../workers/keys";
-import { parseWorkerRow } from "../workers/worker-row";
+import { FILING_FLOW_STATE_KEY, FILING_SESSION_STATE_KEY, FILING_WORKER_STATE_KEY, WORKER_ID_STATE_KEY } from "../workers/keys";
import { newChainId, TURN_CHAIN_STATE, TURN_MESSAGED_STATE, TURN_SENT_STATE, turnChainOf, turnHopOf } from "./hop";
import { MESSAGE_RECEIVED_ENTRY } from "./keys";
import { messageLimitsOf } from "./message-limits";
+import { messageHearingOf } from "./message-received-entry";
import {
MAX_MESSAGE_CHARS,
messageChainsOf,
@@ -54,8 +52,6 @@ import {
type WorkerMessageRow
} from "./message-log";
-export { MESSAGE_RECEIVED_ENTRY };
-
/** What a send asks for: the tool's input. */
export interface SendMessageInput {
readonly to: string;
@@ -68,48 +64,25 @@ export type SendOutcome =
| { readonly ok: true; readonly id: string; readonly unconfirmed?: string }
| { readonly ok: false; readonly error: string };
-/** Whether a worker flow takes messages: it declares the `onMessageReceived` internal entry. */
-export function takesWorkerMessages(flow: unknown): boolean {
- const actions = (flow as { internal?: { actions?: Record } } | undefined)?.internal?.actions;
- return actions !== undefined && Object.hasOwn(actions, MESSAGE_RECEIVED_ENTRY);
-}
-
-/** A coordinator worker's routing, as its row or file declares it, or `undefined` when it names none. */
-async function routingOf(ctx: BlockContext, installation: WorkerInstallation, workerId: string, standard: boolean): Promise {
- let declared: unknown;
- if (standard) {
- declared = installation.standardWorker(workerId)?.declared.routing;
- } else {
- const collection = (ctx.resources as Record }>)[WORKERS_RESOURCE];
- const parsed = parseWorkerRow((await collection?.getOptional(workerId))?.state);
- declared = "row" in parsed ? parsed.row.settings.routing : undefined;
- }
- return declared;
-}
-
/**
- * Why `sender` can't message `recipient` (the roster's row for `to`, or
- * `undefined` when there is none), or `undefined` when it can. The one rule:
- * the send refuses with it, and the tool's description lists only the workers
- * it lets through.
+ * Why `sender` can't message `recipient` by name (the roster's row for `to`,
+ * or `undefined` when there is none), or `undefined` when it can. The one
+ * rule: the send refuses with it, and the tool's description lists only the
+ * workers it lets through.
*/
-export async function recipientRefusal(
- ctx: BlockContext,
+export function recipientRefusal(
installation: WorkerInstallation,
sender: string,
to: string,
recipient: RosterWorker | undefined
-): Promise {
+): string | undefined {
if (to === sender) return "not_yourself: you can't message yourself.";
if (recipient === undefined) return `no_worker: no worker "${to}" on your roster.`;
if (recipient.problem !== undefined) return `worker_unavailable: worker "${to}" can't be messaged: ${recipient.problem}.`;
- if (!takesWorkerMessages(installation.workerFlows()[recipient.flow]?.flow)) {
- return `takes_tasks_only: "${to}" only takes tasks and can't be messaged. File a task for it instead.`;
- }
- if (recipient.flow === COORDINATOR_FLOW && !coordinatorRunsOwnTurn(await routingOf(ctx, installation, to, recipient.standard))) {
+ if (messageHearingOf(installation.workerFlows()[recipient.flow]?.flow) === "task-sessions") {
return (
- `no_turn: "${to}" hands every line to its delegates and runs no turn of its own, so nobody would read a message. ` +
- "Message one of its delegates, or file a task."
+ `task_sessions_only: "${to}" answers only from its tasks' sessions, so it can't be messaged by name. ` +
+ "File it a task instead."
);
}
return undefined;
@@ -141,6 +114,18 @@ async function conversationAddress(
};
}
+/**
+ * The session that filed the running session's work, when `worker` is the
+ * worker that filed it: a task's session, or a delegate's, was born naming
+ * both (server-written). `undefined` for anything else.
+ */
+function filingSessionFor(state: Record, worker: string): MessageAddress | undefined {
+ const filing = state[FILING_SESSION_STATE_KEY];
+ const flow = state[FILING_FLOW_STATE_KEY];
+ if (state[FILING_WORKER_STATE_KEY] !== worker || typeof filing !== "string" || typeof flow !== "string") return undefined;
+ return { sessionId: sessionIdOfFiling(filing), flow };
+}
+
/**
* Send one message from the running session's worker.
*
@@ -163,12 +148,12 @@ export async function sendMessage(
return refuse(`message_too_long: a message holds at most ${MAX_MESSAGE_CHARS} characters; this one has ${input.text.length}. Nothing was sent.`);
}
- // ---- the recipient: on the roster, and with a conversation --------------
+ // ---- the recipient: on the roster, and hearing by name -------------------
const recipient = await installation.rosterWorker(ctx as never, input.to);
- const refused = await recipientRefusal(ctx, installation, sender, input.to, recipient);
+ const refused = recipientRefusal(installation, sender, input.to, recipient);
if (refused !== undefined || recipient === undefined) return refuse(refused ?? `no_worker: no worker "${input.to}" on your roster.`);
- // ---- where it goes ---------------------------------------------------------
+ // ---- where it lands ------------------------------------------------------
const log = messageLogOf(ctx);
let destination: MessageAddress;
let exchange: string | undefined;
@@ -177,61 +162,61 @@ export async function sendMessage(
if (answered === undefined || answered.to !== sender || answered.from !== input.to) {
return refuse(`no_such_message: inReplyTo "${input.inReplyTo}" names no message "${input.to}" sent you. Leave inReplyTo out to start a new one.`);
}
- destination = answered.answerTo;
+ // In the session that sent the original, even after its task ended.
+ destination = { sessionId: answered.fromSession, flow: answered.fromFlow };
exchange = answered.exchange;
} else {
- destination = await conversationAddress(ctx, installation, input.to, recipient.flow, state);
+ destination = filingSessionFor(state, input.to) ?? (await conversationAddress(ctx, installation, input.to, recipient.flow, state));
}
- // ---- the limits --------------------------------------------------------------
- // The hop limit counts the whole exchange: a send's count is its place in
- // its chain's row, and never less than one past its own turn's (a chain
- // from before rows carried one starts empty). A full chain is refused
- // before anything is written; the place a send takes is the final word.
+ // ---- the budget ----------------------------------------------------------
+ // One per message a user types: a send's place is its place in its chain's
+ // row, and never less than one past its own turn's. A request with no chain
+ // behind it (no user's turn, no session's) starts one here, for all its
+ // sends. The per-request count is taken first and given back if the chain
+ // has no place left, so a refused send spends nothing.
const limits = messageLimitsOf(installation);
const chains = messageChainsOf(ctx);
const floor = turnHopOf(ctx) + 1;
- const hopRefusal = (hop: number): SendOutcome =>
+ const budgetRefusal = (hop: number): SendOutcome =>
refuse(
- `hop_limit: this would be message ${hop} in an exchange of worker messages with no user in between, and the limit is ${limits.hopLimit}. ` +
+ `budget: this would be message ${hop} since the user's last line, and the budget is ${limits.hopLimit}. ` +
"Nothing was sent. Stop passing messages on, and say that you stopped; the next line from the user lets the workers go on."
);
const known = turnChainOf(ctx);
const counted = known === undefined ? 0 : ((await chains.getOptional(known))?.state.sent.length ?? 0);
- if (Math.max(floor, counted + 1) > limits.hopLimit) return hopRefusal(Math.max(floor, counted + 1));
- const reserved = await withOutcome(
- (mutator: (s: Readonly>) => Record) => ctx.request.atomicState(mutator as never),
- (current: Readonly>) => {
- const sent = typeof current[TURN_SENT_STATE] === "number" ? (current[TURN_SENT_STATE] as number) : 0;
- if (sent >= limits.perTurn) return { state: {}, result: undefined };
- const messaged = Array.isArray(current[TURN_MESSAGED_STATE]) ? (current[TURN_MESSAGED_STATE] as string[]) : [];
- // A turn with no chain yet (one that started before turns kept one) starts one here, for all its sends.
- const turnChain = typeof current[TURN_CHAIN_STATE] === "string" ? (current[TURN_CHAIN_STATE] as string) : (known ?? newChainId());
- return {
- state: { [TURN_SENT_STATE]: sent + 1, [TURN_MESSAGED_STATE]: [...messaged, input.to], [TURN_CHAIN_STATE]: turnChain },
- result: turnChain
- };
- }
- );
+ if (Math.max(floor, counted + 1) > limits.hopLimit) return budgetRefusal(Math.max(floor, counted + 1));
+ const atomicRequest = (mutator: (s: Readonly>) => Record) => ctx.request.atomicState(mutator as never);
+ const reserved = await withOutcome(atomicRequest, (current: Readonly>) => {
+ const sent = typeof current[TURN_SENT_STATE] === "number" ? (current[TURN_SENT_STATE] as number) : 0;
+ if (sent >= limits.perTurn) return { state: {}, result: undefined };
+ const turnChain = typeof current[TURN_CHAIN_STATE] === "string" ? (current[TURN_CHAIN_STATE] as string) : (known ?? newChainId());
+ return { state: { [TURN_SENT_STATE]: sent + 1, [TURN_CHAIN_STATE]: turnChain }, result: turnChain };
+ });
if (typeof reserved !== "string") {
- return refuse(`per_turn_limit: one turn sends at most ${limits.perTurn} messages, and this one has. Nothing was sent.`);
+ return refuse(`per_request_limit: one request sends at most ${limits.perTurn} messages, and this one has. Nothing was sent.`);
}
const chain = reserved;
const id = newMessageId();
const chainRow = await chains.getOrCreate(chain, { sent: [] });
- await chainRow.pushState("sent", id);
- const hop = Math.max(floor, chainRow.state.sent.indexOf(id) + 1);
- if (hop > limits.hopLimit) return hopRefusal(hop);
+ await chainRow.updateState((row) =>
+ Math.max(floor, row.sent.length + 1) > limits.hopLimit ? row : { ...row, sent: [...row.sent, id] }
+ );
+ const place = chainRow.state.sent.indexOf(id);
+ if (place < 0) {
+ await atomicRequest((current) => {
+ const sent = typeof current[TURN_SENT_STATE] === "number" ? (current[TURN_SENT_STATE] as number) : 1;
+ return { [TURN_SENT_STATE]: Math.max(0, sent - 1) };
+ });
+ return budgetRefusal(Math.max(floor, chainRow.state.sent.length + 1));
+ }
+ const hop = Math.max(floor, place + 1);
+ await atomicRequest((current) => {
+ const messaged = Array.isArray(current[TURN_MESSAGED_STATE]) ? (current[TURN_MESSAGED_STATE] as string[]) : [];
+ return { [TURN_MESSAGED_STATE]: [...messaged, input.to] };
+ });
- // ---- the row, then the delivery ----------------------------------------------
- const sessionId = ctx.session.identity.id;
- // A task's session ends with its turn, and nothing runs there again, so an
- // answer to a message sent from one goes to the sender's own conversation.
- // So does one from a delegate session a conversation opened for a post.
- const fromTaskOrPost = typeof state[TASK_ID_STATE_KEY] === "string" || typeof state[FILING_SESSION_STATE_KEY] === "string";
- const answerTo: MessageAddress = fromTaskOrPost
- ? await conversationAddress(ctx, installation, sender, flowKind, state)
- : { sessionId, flow: flowKind };
+ // ---- the row, then the delivery ------------------------------------------
const row: WorkerMessageRow = {
id,
from: sender,
@@ -239,11 +224,10 @@ export async function sendMessage(
text: input.text,
exchange: exchange ?? id,
...(input.inReplyTo === undefined ? {} : { inReplyTo: input.inReplyTo }),
- fromSession: sessionId,
+ fromSession: ctx.session.identity.id,
fromFlow: flowKind,
toSession: destination.sessionId,
toFlow: destination.flow,
- answerTo,
hop,
chain,
status: "unconfirmed",
diff --git a/packages/workforce/src/workers/index.ts b/packages/workforce/src/workers/index.ts
index aff94c13a2..a006f2c9dc 100644
--- a/packages/workforce/src/workers/index.ts
+++ b/packages/workforce/src/workers/index.ts
@@ -20,6 +20,7 @@
export {
DERIVED_WORKER_SESSION_PREFIX,
FILING_FLOW_STATE_KEY,
+ FILING_WORKER_STATE_KEY,
FILING_PROJECT_STATE_KEY,
FILING_SESSION_STATE_KEY,
FILING_WORKSTREAM_STATE_KEY,
diff --git a/packages/workforce/src/workers/installation.ts b/packages/workforce/src/workers/installation.ts
index 2ec6d3c034..22b6e03f22 100644
--- a/packages/workforce/src/workers/installation.ts
+++ b/packages/workforce/src/workers/installation.ts
@@ -42,10 +42,11 @@ import {
import { isWorkerFlowBuilder, type WorkerFlowBuilder } from "./worker-flow";
import type { PackageManifest, WorkerManifest } from "../manifest";
import { taskChainSchema } from "../conversation-board/chain";
-import { SESSION_BOARD_SERVER_OWNED } from "../conversation-board/session-board";
+import { SESSION_BOARD_SERVER_OWNED, workerMessageStateShape } from "../conversation-board/session-board";
import { criteriaOfState, deriveWorkerSessionId, isDerivedWorkerSessionId } from "./derive-session-id";
import {
FILING_FLOW_STATE_KEY,
+ FILING_WORKER_STATE_KEY,
FILING_PROJECT_STATE_KEY,
FILING_SESSION_STATE_KEY,
FILING_WORKSTREAM_STATE_KEY,
@@ -221,6 +222,7 @@ export type WorkerSessionStateShape = {
readonly [ROUTED_FROM_STATE_KEY]: z.ZodOptional;
readonly [TASK_ID_STATE_KEY]: z.ZodOptional>;
readonly [FILING_FLOW_STATE_KEY]: z.ZodOptional>;
+ readonly [FILING_WORKER_STATE_KEY]: z.ZodOptional>;
readonly [TASK_CHAIN_STATE_KEY]: z.ZodOptional>;
readonly [TASK_FLOW_STATE_KEY]: z.ZodOptional>;
readonly [FILING_WORKSTREAM_STATE_KEY]: z.ZodOptional>;
@@ -261,8 +263,9 @@ export interface WorkerInstallation extends WorkerGrants {
/** The create check a worker flow declares as `session.createCheck`. */
readonly createCheck: SessionCreateCheck;
/**
- * A worker flow's `session` declaration: {@link sessionStateShape} plus
- * `extraShape` as its `stateSchema`, {@link createCheck}, and as
+ * A worker flow's `session` declaration: {@link sessionStateShape}, the
+ * state every worker's `onMessageReceived` keeps, and `extraShape` as its
+ * `stateSchema`, {@link createCheck}, and as
* `serverOwned` the delegate and board fields only the server writes
* ({@link SESSION_BOARD_SERVER_OWNED}, which carries `workProjectId` too). A flow without those fields still refuses a
* create that seeds one, by name, rather than dropping it.
@@ -459,6 +462,7 @@ export function createWorkerInstallation(options: WorkerInstallationOptions = {}
[ROUTED_FROM_STATE_KEY]: z.string().min(1).optional(),
[TASK_ID_STATE_KEY]: z.string().min(1).readonly().optional(),
[FILING_FLOW_STATE_KEY]: z.string().min(1).readonly().optional(),
+ [FILING_WORKER_STATE_KEY]: z.string().min(1).readonly().optional(),
[TASK_CHAIN_STATE_KEY]: taskChainSchema.readonly().optional(),
[TASK_FLOW_STATE_KEY]: z.string().min(1).readonly().optional(),
[FILING_WORKSTREAM_STATE_KEY]: z.string().min(1).readonly().optional(),
@@ -598,6 +602,7 @@ export function createWorkerInstallation(options: WorkerInstallationOptions = {}
for (const key of [
TASK_ID_STATE_KEY,
FILING_FLOW_STATE_KEY,
+ FILING_WORKER_STATE_KEY,
TASK_CHAIN_STATE_KEY,
TASK_FLOW_STATE_KEY,
FILING_WORKSTREAM_STATE_KEY,
@@ -896,7 +901,7 @@ export function createWorkerInstallation(options: WorkerInstallationOptions = {}
roster,
session(extraShape) {
return {
- stateSchema: z.object({ ...sessionStateShape, ...(extraShape ?? {}) }) as never,
+ stateSchema: z.object({ ...sessionStateShape, ...workerMessageStateShape, ...(extraShape ?? {}) }) as never,
createCheck,
serverOwned: SESSION_BOARD_SERVER_OWNED
};
diff --git a/packages/workforce/src/workers/keys.ts b/packages/workforce/src/workers/keys.ts
index 6629483412..55915fa886 100644
--- a/packages/workforce/src/workers/keys.ts
+++ b/packages/workforce/src/workers/keys.ts
@@ -145,6 +145,15 @@ export const ROSTER_FLOW = "workforce-roster";
*/
export const FILING_FLOW_STATE_KEY = "filingFlow";
+/**
+ * Session-state field naming the worker that filed the work a task's or a
+ * delegate's session runs: the filing session's worker, set by the hand-over
+ * beside {@link FILING_SESSION_STATE_KEY}, so a message from here to that
+ * worker lands in the session that filed it (FIX-2238). Readonly, and set
+ * only by the hand-over.
+ */
+export const FILING_WORKER_STATE_KEY = "filingWorkerId";
+
/** The prefix every derived worker-session id starts with. */
export const DERIVED_WORKER_SESSION_PREFIX = "wks_";
diff --git a/packages/workforce/test/conversation-board-harness.ts b/packages/workforce/test/conversation-board-harness.ts
index c15c982159..144199d073 100644
--- a/packages/workforce/test/conversation-board-harness.ts
+++ b/packages/workforce/test/conversation-board-harness.ts
@@ -29,6 +29,9 @@ import { z } from "zod";
import { defineAgentWorkerFlow, type AgentWorkerFlowOptions } from "../src/agent-worker-flow";
import { conversationLedgerAt, conversationLedgerResources } from "../src/conversation-board/ledger";
import { workerTaskEntry } from "../src/conversation-board/task-entry";
+import { MESSAGE_RECEIVED_ENTRY } from "../src/messages/keys";
+import { workerMessagesResources } from "../src/messages/message-log";
+import { messageReceivedEntry } from "../src/messages/message-received-entry";
import { defineCoordinatorFlow, type CoordinatorFlowOptions } from "../src/coordinator/coordinator-flow";
import { COORDINATOR_ROUTE } from "../src/coordinator/coordinator-keys";
import type { WorkerManifest } from "../src/manifest";
@@ -131,8 +134,10 @@ function taskerFlow(installation: WorkerInstallation, runs: TaskRun[], holds: Re
kind: "tasker",
configSchema: workerConfigSchema(),
session: installation.session(),
- resources: { ...installation.resources, ...conversationLedgerResources },
+ resources: { ...installation.resources, ...conversationLedgerResources, ...workerMessagesResources },
actions: { respond: { inputSchema: doorInput, block: turn, userMessage: (i: { message: string }) => i.message } },
+ // Like a coding worker: it hears messages only in its tasks' sessions.
+ internal: { actions: { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind: "tasker", hears: "task-sessions" }) } },
task: { actions: { work: workerTaskEntry({ name: "tasker-task", turn }) } }
});
}
@@ -148,8 +153,9 @@ function helperFlow(installation: WorkerInstallation) {
kind: "helper",
configSchema: workerConfigSchema(),
session: installation.session(),
- resources: { ...installation.resources },
+ resources: { ...installation.resources, ...workerMessagesResources },
actions: { respond: { inputSchema: doorInput, block: door, userMessage: (i: { message: string }) => i.message } },
+ internal: { actions: { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind: "helper", hears: "task-sessions" }) } },
task: { actions: { work: workerTaskEntry({ name: "helper-task", turn: door }) } }
});
}
diff --git a/packages/workforce/test/message-to-a-busy-task-session.test.ts b/packages/workforce/test/message-to-a-busy-task-session.test.ts
index 52e6398351..0afce8aaee 100644
--- a/packages/workforce/test/message-to-a-busy-task-session.test.ts
+++ b/packages/workforce/test/message-to-a-busy-task-session.test.ts
@@ -95,7 +95,6 @@ function doerFlow(installation: WorkerInstallation, seen: Seen[], behaviour: Beh
fromFlow: "doer",
toSession: sessionId,
toFlow: "doer",
- answerTo: { sessionId, flow: "doer" },
hop: 1,
status: "delivered",
at: Date.now()
diff --git a/packages/workforce/test/worker-messages.test.ts b/packages/workforce/test/worker-messages.test.ts
index 1ade9ed555..220b03ee27 100644
--- a/packages/workforce/test/worker-messages.test.ts
+++ b/packages/workforce/test/worker-messages.test.ts
@@ -162,8 +162,8 @@ describe("what a worker knows of who it can message", () => {
expect(descriptions[0]).toContain("- helper-a: Knows colours.");
expect(listed).not.toContain("otto");
expect(listed).not.toContain("eng.tasker");
- // A round-robin coordinator runs no turn, so the send would refuse it: the list never offers it.
- expect(listed).not.toContain("rota");
+ // A coordinator hears a message whatever its routing: a round-robin one is offered too.
+ expect(listed).toContain("rota");
} finally {
await h.dispose();
}
@@ -280,18 +280,24 @@ describe("an answer", () => {
});
/** The board's workers, a coordinator that files for `otto`, and two more agent workers. */
-function teamWorkers(): WorkerManifest[] {
+/**
+ * @param options.unassignedWaits Give helper-a a second delegate, so a task it
+ * files with no assignee waits on its board until it is assigned: a hand-over
+ * held back without filing the task held.
+ */
+function teamWorkers(options: { unassignedWaits?: boolean } = {}): WorkerManifest[] {
const worker = (id: string, declared: Record, body = ""): WorkerManifest => ({ id, declared, body, skills: [] });
return [
...boardWorkers(),
worker("chief", { flow: "coordinator", delegates: ["otto"] }, "Hand the work to otto."),
- worker("helper-a", { description: "Knows colours.", delegates: ["helper-b"] }, "You help."),
- worker("helper-b", { description: "Knows numbers." }, "You help.")
+ worker("helper-a", { description: "Knows colours.", delegates: options.unassignedWaits === true ? ["helper-b", "helper-c"] : ["helper-b"] }, "You help."),
+ worker("helper-b", { description: "Knows numbers." }, "You help."),
+ ...(options.unassignedWaits === true ? [worker("helper-c", { description: "Knows letters." }, "You help.")] : [])
];
}
describe("a message sent from a task's turn", () => {
- it("makes no row, and the answer lands in the sender's own conversation and wakes it, since the task's session ended", async () => {
+ it("makes no row, and the answer lands in the task's session it was sent from, even after the task ended, and wakes it", async () => {
const agentAnswer = mockGenerator({
script: [
{ when: (input) => textOf(input).includes("From helper-a") || textOf(input).includes("from helper-a"), then: { text: "Helper A says teal." } },
@@ -312,16 +318,16 @@ describe("a message sent from a task's turn", () => {
expect(rows.map((row) => row.assignee)).toEqual(["otto"]);
expect(rows[0]!.status).toBe("completed");
- const own = await h.client("alice").findWorkerSession({ worker: "otto" });
- expect(own, "otto's own conversation was opened by the answer").toBeDefined();
- const lines = await h.messages(own!.id);
- expect(lines).toContainEqual({ agentName: "helper-a", text: "From helper-a: Teal." });
- expect(lines.at(-1)?.text).toBe("Helper A says teal.");
-
+ // An answer lands where its original came from: the task's session, not otto's own conversation.
const log = await logRows(h, "alice");
const question = log.find((row) => row.from === "otto")!;
- expect(question.answerTo).toMatchObject({ sessionId: own!.id, flow: "agent" });
- expect(question.fromSession).not.toBe(own!.id);
+ const answer = log.find((row) => row.from === "helper-a")!;
+ expect(answer).toMatchObject({ inReplyTo: question.id, toSession: question.fromSession });
+ expect(await h.client("alice").findWorkerSession({ worker: "otto" }), "otto's own conversation stays unopened").toBeUndefined();
+ expect(await receivedIn(h, question.fromSession)).toEqual([expect.objectContaining({ from: "helper-a", text: "Teal.", inReplyTo: question.id })]);
+ const lines = await h.messages(question.fromSession);
+ expect(lines).toContainEqual({ agentName: "helper-a", text: "From helper-a: Teal." });
+ expect(lines.at(-1)?.text, "the answer woke the task's session's turn").toBe("Helper A says teal.");
} finally {
await h.dispose();
}
@@ -381,7 +387,7 @@ describe("the hop limit", () => {
"helper-b>otto@6"
]);
// The seventh send was refused, in the conversation of the worker that tried it.
- const refusals = (await toolOutputs(h, otto.id)).filter((output) => /hop_limit/.test(JSON.stringify(output)));
+ const refusals = (await toolOutputs(h, otto.id)).filter((output) => /budget/.test(JSON.stringify(output)));
expect(refusals).toHaveLength(1);
// One more line from the user: one more round.
@@ -474,7 +480,7 @@ describe("the per-turn limit", () => {
expect(rows.filter((row) => row.from === "otto")).toHaveLength(3);
// One turn's sends share its exchange's budget: each takes its own place.
expect(rows.map((row) => row.hop).sort((a, b) => a - b)).toEqual([1, 2, 3]);
- const refused = (await toolOutputs(h, otto.id)).filter((output) => /per_turn_limit/.test(JSON.stringify(output)));
+ const refused = (await toolOutputs(h, otto.id)).filter((output) => /per_request_limit/.test(JSON.stringify(output)));
expect(refused).toHaveLength(2);
} finally {
await h.dispose();
@@ -486,10 +492,12 @@ describe("the per-turn limit", () => {
* otto's user line asks helper-a (message 1); helper-a, woken by it, files a
* task for helper-b with `setting`; the task's turn messages otto.
*/
-function relayThroughTask(setting: Record): MockGeneratorScriptEntry[] {
+/** A relay through a task helper-a files for helper-b; `unassigned`, filed with no assignee. */
+function relayThroughTask(setting: Record, options: { unassigned?: boolean } = {}): MockGeneratorScriptEntry[] {
+ const assignee = options.unassigned === true ? {} : { assignee: "helper-b" };
return [
...callOnce("Tell otto the number", "sendMessage", { to: "otto", text: "The number is 7." }, ""),
- ...callOnce("have helper-b tell otto", "createTask", { goal: "Tell otto the number", assignee: "helper-b", ...setting }, ""),
+ ...callOnce("have helper-b tell otto", "createTask", { goal: "Tell otto the number", ...assignee, ...setting }, ""),
...callOnce("Please ask helper-a", "sendMessage", { to: "helper-a", text: "Please have helper-b tell otto the number." }, ""),
fallback
];
@@ -560,7 +568,7 @@ describe("the hop count through a delegation", () => {
await h.settled();
expect((await h.rows("alice")).map((row) => [row.assignee, row.status])).toEqual([["helper-b", "completed"]]);
expect((await logRows(h, "alice")).map((row) => `${row.from}>${row.to}@${row.hop}`)).toEqual(["otto>helper-a@1"]);
- const refusals = (await allToolOutputs(h)).filter((output) => /hop_limit: this would be message 2\b/.test(JSON.stringify(output)));
+ const refusals = (await allToolOutputs(h)).filter((output) => /budget: this would be message 2\b/.test(JSON.stringify(output)));
expect(refusals).toHaveLength(1);
} finally {
await h.dispose();
@@ -569,20 +577,24 @@ describe("the hop count through a delegation", () => {
it("starts a task's turn at the count its filing recorded, never one a caller writes on the row (BP-031)", async () => {
const forged = { [FILED_HOP]: { hop: 0, chain: null } };
- const h = boot({ standard: teamWorkers(), agentAnswer: mockGenerator({ script: relayThroughTask({ session: "ongoing", held: true, metadata: forged }) }) });
+ const h = boot({
+ standard: teamWorkers({ unassignedWaits: true }),
+ agentAnswer: mockGenerator({ script: relayThroughTask({ session: "ongoing", metadata: forged }, { unassigned: true }) })
+ });
try {
const alice = h.client("alice");
const otto = await alice.ensureWorkerSession({ worker: "otto" });
await h.post("alice", otto.id, "respond", { message: "Please ask helper-a" }, "agent");
await h.settled();
const [held] = await h.rows("alice");
+ expect(held!.status).toBe("pending");
expect(held!.metadata?.[FILED_HOP]).toMatchObject({ hop: 1 });
const helperA = await alice.ensureWorkerSession({ worker: "helper-a" });
const patched = await h.act("alice", helperA.id, "updateTask_tasks", { id: held!.id, metadata: forged }, "agent");
expect(patched.error, messageOf(patched.error)).toBeUndefined();
expect((await h.rows("alice"))[0]!.metadata?.[FILED_HOP]).toEqual(held!.metadata?.[FILED_HOP]);
- const released = await h.act("alice", helperA.id, "updateTask_tasks", { id: held!.id, status: "pending" }, "agent");
+ const released = await h.act("alice", helperA.id, "updateTask_tasks", { id: held!.id, assignee: "helper-b" }, "agent");
expect(released.error, messageOf(released.error)).toBeUndefined();
await h.settled();
expect((await logRows(h, "alice")).map((row) => `${row.from}>${row.to}@${row.hop}`).sort()).toEqual(["helper-b>otto@2", "otto>helper-a@1"]);
@@ -622,8 +634,8 @@ describe("the hop count through a delegation", () => {
// user's line say nothing: only the task's own turn messages otto.
const quietAfterUser: MockGeneratorScriptEntry = { when: (input) => textOf(input).includes("Go ahead whenever you like"), then: { text: "" } };
const h = boot({
- standard: teamWorkers(),
- agentAnswer: mockGenerator({ script: [quietAfterUser, ...relayThroughTask({ ...setting, held: true })] })
+ standard: teamWorkers({ unassignedWaits: true }),
+ agentAnswer: mockGenerator({ script: [quietAfterUser, ...relayThroughTask(setting, { unassigned: true })] })
});
try {
const alice = h.client("alice");
@@ -631,13 +643,13 @@ describe("the hop count through a delegation", () => {
await h.post("alice", otto.id, "respond", { message: "Please ask helper-a" }, "agent");
await h.settled();
const [held] = await h.rows("alice");
- expect(held!.status).toBe("held");
+ expect([held!.status, held!.assignee]).toEqual(["pending", undefined]);
expect(held!.metadata?.[FILED_HOP]).toMatchObject({ hop: 1 });
const helperA = await alice.ensureWorkerSession({ worker: "helper-a" });
await h.post("alice", helperA.id, "respond", { message: "Go ahead whenever you like." }, "agent");
await h.settled();
- const released = await h.act("alice", helperA.id, "updateTask_tasks", { id: held!.id, status: "pending" }, "agent");
+ const released = await h.act("alice", helperA.id, "updateTask_tasks", { id: held!.id, assignee: "helper-b" }, "agent");
expect(released.error, messageOf(released.error)).toBeUndefined();
await h.settled();
@@ -660,12 +672,12 @@ describe("the hop count through a delegation", () => {
])("keeps a task filed %s in its filing's chain when a message from another chain wakes its filer before it is handed over", async (_where, setting) => {
const quietAfterPing: MockGeneratorScriptEntry = { when: (input) => textOf(input).includes("Just a ping"), then: { text: "" } };
const h = boot({
- standard: teamWorkers(),
+ standard: teamWorkers({ unassignedWaits: true }),
agentAnswer: mockGenerator({
script: [
quietAfterPing,
...callOnce("Please ping helper-a", "sendMessage", { to: "helper-a", text: "Just a ping." }, ""),
- ...relayThroughTask({ ...setting, held: true })
+ ...relayThroughTask(setting, { unassigned: true })
]
})
});
@@ -675,7 +687,7 @@ describe("the hop count through a delegation", () => {
await h.post("alice", otto.id, "respond", { message: "Please ask helper-a" }, "agent");
await h.settled();
const [held] = await h.rows("alice");
- expect(held!.status).toBe("held");
+ expect([held!.status, held!.assignee]).toEqual(["pending", undefined]);
const filedIn = (held!.metadata?.[FILED_HOP] as { chain: string }).chain;
// A new line to otto starts chain W there; otto's message moves helper-a's session to W.
@@ -684,7 +696,7 @@ describe("the hop count through a delegation", () => {
const helperA = await alice.ensureWorkerSession({ worker: "helper-a" });
expect((await h.session(helperA.id)).state.workforceMessageChain, "helper-a's session is in chain W now").not.toBe(filedIn);
- const released = await h.act("alice", helperA.id, "updateTask_tasks", { id: held!.id, status: "pending" }, "agent");
+ const released = await h.act("alice", helperA.id, "updateTask_tasks", { id: held!.id, assignee: "helper-b" }, "agent");
expect(released.error, messageOf(released.error)).toBeUndefined();
await h.settled();
expect((await h.rows("alice")).map((row) => row.status)).toEqual(["completed"]);
@@ -695,7 +707,37 @@ describe("the hop count through a delegation", () => {
}
});
- it("runs an ongoing-session task filed before rows recorded a count at its session's count, as it did", async () => {
+ // No exchange waits on a task filed held: released, it uses no attempt of
+ // the filer's budget and starts a fresh one. A hold put on midway carries on.
+ it.each([
+ ["in a session of its own", {}],
+ ['in the delegate\'s ongoing session (session: "ongoing")', { session: "ongoing" }]
+ ])("starts a task filed %s held afresh when it is released", async (_where, setting) => {
+ const h = boot({ standard: teamWorkers(), agentAnswer: mockGenerator({ script: relayThroughTask({ ...setting, held: true }) }) });
+ try {
+ const alice = h.client("alice");
+ const otto = await alice.ensureWorkerSession({ worker: "otto" });
+ await h.post("alice", otto.id, "respond", { message: "Please ask helper-a" }, "agent");
+ await h.settled();
+ const [held] = await h.rows("alice");
+ expect(held!.status).toBe("held");
+
+ const helperA = await alice.ensureWorkerSession({ worker: "helper-a" });
+ const released = await h.act("alice", helperA.id, "updateTask_tasks", { id: held!.id, status: "pending" }, "agent");
+ expect(released.error, messageOf(released.error)).toBeUndefined();
+ await h.settled();
+ expect((await h.rows("alice")).map((row) => row.status)).toEqual(["completed"]);
+ const rows = await logRows(h, "alice");
+ expect(rows.map((row) => `${row.from}>${row.to}@${row.hop}`).sort()).toEqual(["helper-b>otto@1", "otto>helper-a@1"]);
+ const first = rows.find((row) => row.from === "otto")!;
+ const fromTask = rows.find((row) => row.from === "helper-b")!;
+ expect(fromTask.chain, "a fresh chain, not the filing's").not.toBe(first.chain);
+ } finally {
+ await h.dispose();
+ }
+ });
+
+ it("runs an ongoing-session task filed before rows recorded a count at its session's count, which counts on from its filer's", async () => {
const h = boot({ standard: teamWorkers(), agentAnswer: mockGenerator({ script: relayThroughTask({ session: "ongoing", held: true }) }) });
try {
const alice = h.client("alice");
@@ -716,8 +758,9 @@ describe("the hop count through a delegation", () => {
expect(released.error, messageOf(released.error)).toBeUndefined();
await h.settled();
expect((await h.rows("alice")).map((row) => row.status)).toEqual(["completed"]);
- // Its session kept no count, so its message starts one, as before the row recorded it.
- expect((await logRows(h, "alice")).map((row) => `${row.from}>${row.to}@${row.hop}`).sort()).toEqual(["helper-b>otto@1", "otto>helper-a@1"]);
+ // No record on the row: the task runs at its session's count, and the
+ // delegate's ongoing session was born with its filer's (FIX-2238).
+ expect((await logRows(h, "alice")).map((row) => `${row.from}>${row.to}@${row.hop}`).sort()).toEqual(["helper-b>otto@2", "otto>helper-a@1"]);
} finally {
await h.dispose();
}
@@ -785,7 +828,7 @@ describe("the hop count through a delegation", () => {
});
describe("who can be messaged", () => {
- it("refuses another user's worker as missing, a task-only worker with 'file a task', a turnless coordinator, and itself; writes nothing", async () => {
+ it("refuses another user's worker as missing, a worker that hears only in its tasks' sessions with 'file a task', and itself, writing nothing; a round-robin coordinator hears one", async () => {
const calls = [
{ to: "bob.friend", text: "Hi Bob's worker." },
{ to: "nobody", text: "Hi." },
@@ -819,10 +862,13 @@ describe("who can be messaged", () => {
expect(outputs).toHaveLength(5);
expect(outputs[0]).toMatch(/no_worker: no worker \\"bob.friend\\" on your roster/);
expect(outputs[1]).toMatch(/no_worker: no worker \\"nobody\\" on your roster/);
- expect(outputs[2]).toMatch(/takes_tasks_only.*File a task/);
- expect(outputs[3]).toMatch(/no_turn/);
+ expect(outputs[2]).toMatch(/task_sessions_only.*File it a task/);
+ expect(outputs[3]).toMatch(/"sent":"msg_/);
expect(outputs[4]).toMatch(/not_yourself/);
- expect(await logRows(h, "alice")).toEqual([]);
+ // Only rota's message is a row, and it landed in rota's conversation as its own item.
+ const rows = await logRows(h, "alice");
+ expect(rows.map((row) => `${row.from}>${row.to}`)).toEqual(["otto>rota"]);
+ expect(await receivedIn(h, rows[0]!.toSession)).toEqual([expect.objectContaining({ from: "otto", text: "Hi rota." })]);
expect(await logRows(h, "bob")).toEqual([]);
const bobs = await (await h.state.getRuntime()).stores.session.list({ userId: "bob" } as never);
expect((bobs as Array<{ flowKind: string }>).filter((session) => session.flowKind === "agent")).toEqual([]);
From 941382108560a7f6df19eb381943307ab1080b52 Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 27 Oct 2026 22:14:46 +0000
Subject: [PATCH 04/14] FIX-2238: every worker flow on an installation hears a
message
hireWorkforce refuses a worker flow without an onMessageReceived built by
messageReceivedEntry. The coder hears only in its tasks' sessions; the error
reporter's turn runs for a message. messageReceivedEntry and its types are
exported. Shift Manager draws workforce:received as its own item under the
sender's name, replacing the 'From X:' prefix match.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
.../src/components/Conversation.tsx | 24 ++--------
.../src/components/ReceivedMessage.tsx | 44 +++++++++++++++++++
.../shift-manager/src/components/ToolLine.tsx | 13 ++++--
.../devteam/workforce/flows/workers/coder.mts | 10 ++++-
.../shift-manager/test/conversation.test.tsx | 27 ++++++++----
.../test/fixtures/ask-lab/asker.mts | 6 ++-
.../workforce/flows/workers/worker.mts | 6 ++-
.../test/fixtures/run-lab/lab.mts | 5 +++
packages/workforce/src/browser.ts | 2 +-
packages/workforce/src/error-reporter/flow.ts | 9 +++-
packages/workforce/src/messages/index.ts | 16 +++++--
packages/workforce/src/workers/register.ts | 10 +++++
.../test/conversation-board-harness.ts | 10 +++++
.../test/coordinator-followup-context.test.ts | 5 ++-
.../test/coordinator-routing.test.ts | 8 +++-
.../test/custom-worker-flow-data.test.ts | 5 ++-
.../delegate-takes-conversation-tasks.test.ts | 6 ++-
.../workforce/test/error-reporter.test.ts | 6 ++-
.../message-to-a-busy-task-session.test.ts | 6 ++-
.../test/worker-registration.test.ts | 36 ++++++++++++++-
packages/workforce/test/worker-roles.test.ts | 11 ++++-
.../test/worker-task-entry-block.test.ts | 6 ++-
22 files changed, 217 insertions(+), 54 deletions(-)
create mode 100644 packages/shift-manager/src/components/ReceivedMessage.tsx
diff --git a/packages/shift-manager/src/components/Conversation.tsx b/packages/shift-manager/src/components/Conversation.tsx
index 91f664f0d7..a2768420eb 100644
--- a/packages/shift-manager/src/components/Conversation.tsx
+++ b/packages/shift-manager/src/components/Conversation.tsx
@@ -20,6 +20,7 @@
*/
import { useEffect, useMemo, type ReactNode } from "react";
import type { OutputItem } from "@flow-state-dev/core/items";
+import { RECEIVED_MESSAGE_COMPONENT } from "@flow-state-dev/workforce/browser";
import type { SessionSummary } from "@flow-state-dev/client";
import { buildItemRenderStream, FlowProvider, ItemRenderer } from "@flow-state-dev/react";
import type { Gaps } from "../gaps";
@@ -34,15 +35,6 @@ import { useLab } from "../lib/lab-data";
import type { Worker } from "../lib/reads";
import { sendTurn } from "../lib/send";
import { clockTime } from "../lib/shell";
-import { navigate } from "../lib/routes";
-
-/** Whether a line is another worker's message (FIX-1989): written under its sender's name, as *From : *. */
-function isWorkerMessage(item: OutputItem, sender: string | undefined): boolean {
- if (sender === undefined) return false;
- const content = (item as { content?: Array<{ text?: unknown }> }).content;
- const first = Array.isArray(content) ? content.find((part) => typeof part.text === "string")?.text : undefined;
- return typeof first === "string" && first.startsWith(`From ${sender}: `);
-}
/**
* Items the feed never draws: `ItemRenderer` paints nothing for them. Keep in step with
@@ -259,7 +251,9 @@ export function Conversation({
}
const item = segment.item;
const role = (item as { role?: string }).role ?? "";
- const own = renderItem?.(item);
+ // Another worker's message is drawn by the registry on every view, under its sender's name.
+ const received = item.type === "component" && (item as { component?: string }).component === RECEIVED_MESSAGE_COMPONENT;
+ const own = received ? undefined : renderItem?.(item);
const sender = item.type === "message" && role === "assistant" ? senderOf(worker, item, known) : undefined;
return (
) : null}
{own !== undefined ? (
diff --git a/packages/shift-manager/src/components/ReceivedMessage.tsx b/packages/shift-manager/src/components/ReceivedMessage.tsx
new file mode 100644
index 0000000000..061c8a64b0
--- /dev/null
+++ b/packages/shift-manager/src/components/ReceivedMessage.tsx
@@ -0,0 +1,44 @@
+/**
+ * A message another worker sent this one (`workforce:received`, FIX-2238):
+ * drawn as a line under its sender's name, with the time it landed and a link
+ * to Messages, and a note when it answers a message of this worker's. The
+ * item is the message's own: the line the worker's model reads is history
+ * only and never reaches the page.
+ */
+import type { ComponentItem } from "@flow-state-dev/core/items";
+import { workerLabel } from "../lib/derive";
+import { navigate } from "../lib/routes";
+import { clockTime } from "../lib/shell";
+
+type Received = { id?: string; from?: string; text?: string; inReplyTo?: string };
+
+export function ReceivedMessage({ item }: { item: ComponentItem }) {
+ const data = (item.data ?? {}) as Received;
+ const from = data.from ?? "";
+ return (
+
+ );
+}
diff --git a/packages/shift-manager/src/components/ToolLine.tsx b/packages/shift-manager/src/components/ToolLine.tsx
index d756535d61..33be3fc8e6 100644
--- a/packages/shift-manager/src/components/ToolLine.tsx
+++ b/packages/shift-manager/src/components/ToolLine.tsx
@@ -27,10 +27,11 @@ import type { ItemRenderSegment, RendererRegistry } from "@flow-state-dev/react"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { cn } from "@/lib/utils";
-import { COORDINATOR_ROUTE, SEND_MESSAGE_TOOL } from "@flow-state-dev/workforce/browser";
+import { COORDINATOR_ROUTE, RECEIVED_MESSAGE_COMPONENT, SEND_MESSAGE_TOOL } from "@flow-state-dev/workforce/browser";
import { navigate } from "../lib/routes";
import { chatAssistantRenderers } from "./flow-state/chat-assistant";
import { CoordinatorRoute } from "./CoordinatorRoute";
+import { ReceivedMessage } from "./ReceivedMessage";
import { TaskBoardMeta } from "./TaskBoardMeta";
import { ToolInput, ToolOutput } from "./flow-state/tool";
@@ -266,6 +267,12 @@ export const shiftManagerRenderers: RendererRegistry = {
...chatAssistantRenderers,
tool_output: ToolLine,
// A coordinator's routing record, drawn apart from the conversation's lines.
- // Its task board, with each row opening that task's session.
- component: { ...chatAssistantRenderers.component, [COORDINATOR_ROUTE]: CoordinatorRoute, "task-board-meta": TaskBoardMeta },
+ // Its task board, with each row opening that task's session. Another
+ // worker's message, under its sender's name.
+ component: {
+ ...chatAssistantRenderers.component,
+ [COORDINATOR_ROUTE]: CoordinatorRoute,
+ "task-board-meta": TaskBoardMeta,
+ [RECEIVED_MESSAGE_COMPONENT]: ReceivedMessage,
+ },
};
diff --git a/packages/shift-manager/teams/devteam/workforce/flows/workers/coder.mts b/packages/shift-manager/teams/devteam/workforce/flows/workers/coder.mts
index c5ba1820b6..de5b93a192 100644
--- a/packages/shift-manager/teams/devteam/workforce/flows/workers/coder.mts
+++ b/packages/shift-manager/teams/devteam/workforce/flows/workers/coder.mts
@@ -62,11 +62,14 @@ import type { Task, TaskWorker } from "@flow-state-dev/orchestration/tasks";
import {
conversationLedgers,
filingConversationBoard,
+ MESSAGE_RECEIVED_ENTRY,
+ messageReceivedEntry,
projectWorkspaceCapability,
startOwedSteerTurn,
STEER_TURN_ENTRY,
steerTurnEntry,
WORKER_TASK_ENTRY,
+ workerMessagesResources,
workerTaskEntry,
type WorkerInstallation,
} from "@flow-state-dev/workforce";
@@ -208,7 +211,7 @@ export function defineCoderWorkerFlow(options: CoderWorkerFlowOptions) {
// 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 blocks.
- resources: { ...options.resources, ...installation.resources },
+ resources: { ...options.resources, ...installation.resources, ...workerMessagesResources },
actions: {
[INSPECT_ENTRY]: {
block: readOwnFacts,
@@ -223,6 +226,11 @@ export function defineCoderWorkerFlow(options: CoderWorkerFlowOptions) {
// The turn a steer the run's last step missed is owed (FIX-2086 D2):
// the task once more, on its attempt, with every steer in its prompt.
[STEER_TURN_ENTRY]: steerTurnEntry({ name: `${CODER_FLOW}-steer-turn`, block: byTask }),
+ // A message lands in one of its tasks' sessions only: it has no
+ // conversation to answer from, so one sent to it by name is refused
+ // before anything is written (FIX-2238). No turn yet: the message
+ // lands as its items.
+ [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind: CODER_FLOW, hears: "task-sessions" }),
},
},
// The one door: any session's tasks, handed over under its board's id.
diff --git a/packages/shift-manager/test/conversation.test.tsx b/packages/shift-manager/test/conversation.test.tsx
index 697384c220..ebbd73645e 100644
--- a/packages/shift-manager/test/conversation.test.tsx
+++ b/packages/shift-manager/test/conversation.test.tsx
@@ -42,6 +42,7 @@ vi.mock("@flow-state-dev/workforce/browser", async (original) => {
import { deriveWorkerSessionId } from "@flow-state-dev/workforce/browser";
import { Conversation } from "../src/components/Conversation";
+import { RECEIVED_MESSAGE_COMPONENT } from "@flow-state-dev/workforce/browser";
// The reviewer's conversation: the session at its derived address, where a worker's message lands too.
const s1 = await deriveWorkerSessionId({ userId: "u_1", orgId: "org_1", flow: "agent", criteria: { worker: "eng.reviewer" } });
@@ -142,16 +143,26 @@ describe("what a view of its own draws", () => {
expect(screen.getAllByText("REVIEWER")).toHaveLength(2);
});
- it("labels another worker's message with its sender on any worker's conversation, and links it to Messages (FIX-1989)", async () => {
- const from = { ...item("m", "ignored"), agentName: "eng.author", content: [{ type: "output_text", text: "From eng.author: the codename?" }] };
- read.mockResolvedValue({ items: [from, item("a", "BLUE-HERON")], truncated: false });
- // The sender is known from the session it sent from, one of the user's own.
- const authors = { ...session("s_author"), state: { workerId: "eng.author" } } as unknown as SessionSummary;
- drawn([session(s1), authors]);
+ it("draws another worker's message as its own item under its sender's name, with a link to Messages, whatever the view draws", async () => {
+ const received = {
+ id: "m",
+ requestId: "r",
+ type: "component",
+ component: RECEIVED_MESSAGE_COMPONENT,
+ ts: Date.UTC(2026, 9, 7, 17, 33),
+ data: { id: "msg_1", from: "eng.author", text: "the codename?", inReplyTo: "msg_0" },
+ };
+ read.mockResolvedValue({ items: [received, item("a", "BLUE-HERON")], truncated: false });
+ drawn([session(s1)]);
await screen.findAllByTestId("mine");
- expect(screen.getAllByText("ENG.AUTHOR")).toHaveLength(1);
+ // The view's renderItem draws its own messages, never another worker's.
+ expect(screen.getAllByTestId("mine").map((n) => n.textContent)).toEqual(["BLUE-HERON"]);
+ const drawnMessage = screen.getByTestId("received-message");
+ expect(drawnMessage.textContent).toContain("ENG.AUTHOR");
+ expect(drawnMessage.textContent).toContain("the codename?");
+ expect(screen.getByTestId("received-message-answers")).toBeTruthy();
+ expect(screen.getAllByTestId("received-message-messages")).toHaveLength(1);
expect(screen.getAllByText("REVIEWER")).toHaveLength(1);
- expect(screen.getAllByTestId("rev-item-messages")).toHaveLength(1);
});
it("says the worker has the line while one from this page is in flight", () => {
diff --git a/packages/shift-manager/test/fixtures/ask-lab/asker.mts b/packages/shift-manager/test/fixtures/ask-lab/asker.mts
index cb2216152d..b78e71e8d5 100644
--- a/packages/shift-manager/test/fixtures/ask-lab/asker.mts
+++ b/packages/shift-manager/test/fixtures/ask-lab/asker.mts
@@ -36,6 +36,9 @@ import {
workerConfigSchema,
workerTaskEntry,
type WorkerInstallation,
+ MESSAGE_RECEIVED_ENTRY,
+ messageReceivedEntry,
+ workerMessagesResources,
} from "@flow-state-dev/workforce";
import { z } from "zod";
@@ -164,7 +167,7 @@ export function defineAskerFlow(
return defineFlow({
kind: ASKER_FLOW,
session: installation.session(),
- resources: { ...resources, ...inventory, ...installation.resources },
+ resources: { ...resources, ...inventory, ...installation.resources, ...workerMessagesResources },
cardinality: "collection",
configSchema: workerConfigSchema(),
actions: {
@@ -176,6 +179,7 @@ export function defineAskerFlow(
description: "A user's line into this worker's session.",
},
},
+ internal: { actions: { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind: ASKER_FLOW }) } },
task: {
actions: {
[WORKER_TASK_ENTRY]: { ...workerTaskEntry({ name: "asker-task", turn: onPost }), durable: true },
diff --git a/packages/shift-manager/test/fixtures/multi-worker-collab/workforce/flows/workers/worker.mts b/packages/shift-manager/test/fixtures/multi-worker-collab/workforce/flows/workers/worker.mts
index 75006c0b9e..3a612b171b 100644
--- a/packages/shift-manager/test/fixtures/multi-worker-collab/workforce/flows/workers/worker.mts
+++ b/packages/shift-manager/test/fixtures/multi-worker-collab/workforce/flows/workers/worker.mts
@@ -55,6 +55,9 @@ import {
workerConfigSchema,
workerTaskEntry,
type WorkerInstallation,
+ MESSAGE_RECEIVED_ENTRY,
+ messageReceivedEntry,
+ workerMessagesResources,
} from "@flow-state-dev/workforce";
import { appendFileSync } from "node:fs";
import { z } from "zod";
@@ -202,8 +205,9 @@ export function defineWorkerFlow(options: WorkerFlowOptions) {
// the host refuses a worker whose file names no `answersFor`.
configSchema: workerConfigSchema().extend({ answersFor: z.string().min(1).optional() }),
session: installation.session(),
- resources: { ...installation.resources },
+ resources: { ...installation.resources, ...workerMessagesResources },
actions: { ...hearingDoor },
+ internal: { actions: { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind: WORKER_FLOW }) } },
task: { actions: { [WORK_ENTRY]: workerTaskEntry({ name: "worker-task", turn }) } },
} as never);
}
diff --git a/packages/shift-manager/test/fixtures/run-lab/lab.mts b/packages/shift-manager/test/fixtures/run-lab/lab.mts
index b291af6db7..4df0420abe 100644
--- a/packages/shift-manager/test/fixtures/run-lab/lab.mts
+++ b/packages/shift-manager/test/fixtures/run-lab/lab.mts
@@ -67,6 +67,9 @@ import {
workerConfigSchema,
workerTaskEntry,
type InventoryActionRequest,
+ MESSAGE_RECEIVED_ENTRY,
+ messageReceivedEntry,
+ workerMessagesResources,
} from "@flow-state-dev/workforce";
import { readDeclaredRoster } from "@flow-state-dev/workforce/loader";
import { WORKER_ID_STATE_KEY } from "@flow-state-dev/workforce/browser";
@@ -280,8 +283,10 @@ export async function openRunLab(options: { asking?: boolean; holdAsk?: boolean
resources: {
...installation.resources,
...(records ? { [OBSERVED_PLAN]: observedPlanCollection, [OBSERVED_FILE_OPS]: observedFileOpsCollection } : {}),
+ ...workerMessagesResources,
},
actions: { ...hearingDoor },
+ internal: { actions: { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind: flow }) } },
task: { actions: { work: workerTaskEntry({ name: `run-lab-${flow}-task`, turn: scriptedRun }) } },
} as never);
const coordinator = defineCoordinatorFlow({ installation, routeModel: ROUTE_MODEL });
diff --git a/packages/workforce/src/browser.ts b/packages/workforce/src/browser.ts
index 4e5a96df2d..3fecec0de7 100644
--- a/packages/workforce/src/browser.ts
+++ b/packages/workforce/src/browser.ts
@@ -69,7 +69,7 @@ export {
export { COORDINATOR_JUDGMENT, COORDINATOR_FLOW, COORDINATOR_ROUTE } from "./coordinator/coordinator-keys";
/** The Error Reporter's flow: an app finds the worker a user tells about a problem by it. */
export { ERROR_REPORTER_FLOW } from "./error-reporter/keys";
-export { SEND_MESSAGE_TOOL, MESSAGE_RECEIVED_ENTRY } from "./messages/keys";
+export { SEND_MESSAGE_TOOL, MESSAGE_RECEIVED_ENTRY, RECEIVED_MESSAGE_COMPONENT } from "./messages/keys";
export { LIST_SCHEDULES_ACTION, SCHEDULES_PATTERN } from "./schedules/keys";
export { listedScheduleSchema, type ListedSchedule } from "./schedules/listed-schedule";
export {
diff --git a/packages/workforce/src/error-reporter/flow.ts b/packages/workforce/src/error-reporter/flow.ts
index 7f59e931df..7ebc4dfe3a 100644
--- a/packages/workforce/src/error-reporter/flow.ts
+++ b/packages/workforce/src/error-reporter/flow.ts
@@ -16,6 +16,9 @@ import { defineSetWorkProjectBlock, setWorkProjectInputSchema } from "../project
import { markUserTurnStep } from "../standing-rules/user-turn";
import { turnConfigOf } from "../workers/verified-worker";
import type { WorkerInstallation } from "../workers/installation";
+import { MESSAGE_RECEIVED_ENTRY } from "../messages/keys";
+import { workerMessagesResources } from "../messages/message-log";
+import { messageReceivedEntry, promptedMessageTurn } from "../messages/message-received-entry";
import { PROJECT_STATE_KEY, SET_WORK_PROJECT_ACTION } from "../workers/keys";
import { defineMcpCredentialsCollection } from "../projects/mcp-credentials";
import { conversationLedgerAt, conversationLedgerResources } from "../conversation-board/ledger";
@@ -713,7 +716,7 @@ export function defineErrorReporterFlow(options: ErrorReporterFlowOptions) {
configSchema: turn.settings,
...turn.bound,
session,
- resources: { ...(turn.bound.resources ?? {}), ...errorReportsResources },
+ resources: { ...(turn.bound.resources ?? {}), ...errorReportsResources, ...workerMessagesResources },
actions: {
[RESPOND_ACTION]: { inputSchema: turn.inputSchema.strict(), block: door, userMessage: (input: { message: string }) => input.message },
// Public so its preview is answerable from Inbox (a dispatched run is never reopened from outside).
@@ -731,7 +734,9 @@ export function defineErrorReporterFlow(options: ErrorReporterFlowOptions) {
internal: {
actions: {
[COMMENT_ENTRY]: { inputSchema: z.object({}).passthrough(), block: comment },
- [LINE_ENTRY]: { inputSchema: z.object({ text: z.string() }), block: line }
+ [LINE_ENTRY]: { inputSchema: z.object({ text: z.string() }), block: line },
+ // A worker's message wakes the reporter's turn, as it does any worker's (FIX-2238).
+ [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ turn: promptedMessageTurn(turn.run), installation, flowKind })
}
}
} as never);
diff --git a/packages/workforce/src/messages/index.ts b/packages/workforce/src/messages/index.ts
index 93c2f7cc89..5355ca9797 100644
--- a/packages/workforce/src/messages/index.ts
+++ b/packages/workforce/src/messages/index.ts
@@ -1,10 +1,20 @@
/**
* Worker messages (FIX-1989): any worker with a conversation can message any
* other on its user's roster. Talk, not delegation: no task row, no delegate,
- * no task-chain count. The session kit carries the tool and the entry, so
- * both worker flows get them; `hireWorkforce`'s `messages` sets the limits.
+ * no task-chain count. The session kit carries the tool and the entry; a
+ * worker flow without it mounts `messageReceivedEntry` itself, and the hire
+ * refuses one with neither (FIX-2238). `hireWorkforce`'s `messages` sets the budget.
*/
-export { SEND_MESSAGE_TOOL, MESSAGE_RECEIVED_ENTRY } from "./keys";
+export { SEND_MESSAGE_TOOL, MESSAGE_RECEIVED_ENTRY, RECEIVED_MESSAGE_COMPONENT } from "./keys";
+export {
+ messageReceivedEntry,
+ messageReceivedInputSchema,
+ messageReceivedSchema,
+ promptedMessageTurn,
+ receivedMessagePrompt,
+ type MessageHearing,
+ type MessageReceived
+} from "./message-received-entry";
export {
MAX_MESSAGE_CHARS,
MESSAGE_STATUSES,
diff --git a/packages/workforce/src/workers/register.ts b/packages/workforce/src/workers/register.ts
index de8f6b376e..998895215d 100644
--- a/packages/workforce/src/workers/register.ts
+++ b/packages/workforce/src/workers/register.ts
@@ -16,6 +16,7 @@ import type { InventoryWorker } from "../inventory/open-inventory";
import { createWorkerHireBlocks } from "./hire-blocks";
import { setTaskChainLimit } from "./chain-limit";
import { setMessageLimits, type MessageLimits } from "../messages/message-limits";
+import { messageReceivedProblem } from "../messages/message-received-entry";
import { defineScheduledWork, type ScheduledWorkOptions } from "../schedules/scheduled-work";
import type { WorkerInstallation } from "./installation";
import { defineWorkerRosterFlow } from "./roster-flow";
@@ -88,6 +89,15 @@ export function hireWorkforce(installation: WorkerInstallation, options: HireWor
`with \`installation.resolveWorker\` on every turn (the flow's \`request.onStarted\` runs on a resumed one too).`
);
}
+ // Every worker on an installation can be messaged, so every worker flow
+ // hears one (FIX-2238): checked as the door is, before anything registers.
+ const deaf = Object.entries(installation.workerFlows())
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+ .map(([flowName, { flow }]) => messageReceivedProblem(flowName, (flow as { internal?: { actions?: Readonly> } }).internal?.actions))
+ .filter((problem): problem is string => problem !== undefined);
+ if (deaf.length > 0) {
+ throw new Error(`hireWorkforce refused ${deaf.length} worker flow(s); nothing was registered:\n` + deaf.map((problem) => ` - ${problem}`).join("\n"));
+ }
const problems = installation.standardWorkerProblems();
if (problems.length > 0) {
throw new Error(
diff --git a/packages/workforce/test/conversation-board-harness.ts b/packages/workforce/test/conversation-board-harness.ts
index 144199d073..3de6228f00 100644
--- a/packages/workforce/test/conversation-board-harness.ts
+++ b/packages/workforce/test/conversation-board-harness.ts
@@ -538,3 +538,13 @@ export function messageOf(error: unknown): string {
if (error !== null && typeof error === "object" && "message" in error) return String((error as { message: unknown }).message);
return String(error);
}
+
+/**
+ * A fixture worker flow's `onMessageReceived`, which every worker flow on an
+ * installation must carry: spread into `internal.actions`, with
+ * `workerMessagesResources` in the flow's resources. No turn: a message lands
+ * as its items and nothing runs.
+ */
+export function hearsMessages(installation: WorkerInstallation, flowKind: string, hears?: "task-sessions") {
+ return { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind, ...(hears === undefined ? {} : { hears }) }) };
+}
diff --git a/packages/workforce/test/coordinator-followup-context.test.ts b/packages/workforce/test/coordinator-followup-context.test.ts
index 1c33727bde..e4b360267c 100644
--- a/packages/workforce/test/coordinator-followup-context.test.ts
+++ b/packages/workforce/test/coordinator-followup-context.test.ts
@@ -37,6 +37,8 @@ import { workerConfigSchema } from "../src/worker-config";
import { hireWorkforce } from "../src/workers/register";
import { createWorkerInstallation } from "../src/workers/installation";
import { workerConfigOf } from "../src/workers/verified-worker";
+import { hearsMessages } from "./conversation-board-harness";
+import { workerMessagesResources } from "../src/messages/message-log";
type ModelMessage = { role: string; content: unknown };
@@ -128,7 +130,8 @@ function researchFlow(installation: ReturnType)
kind: "research",
configSchema: workerConfigSchema(),
session: installation.session(),
- resources: { ...installation.resources },
+ resources: { ...installation.resources, ...workerMessagesResources },
+ internal: { actions: hearsMessages(installation, "research") },
request: { onStarted: loadWorker },
actions: { respond: { inputSchema: input, block: door, userMessage: (turn: { message: string }) => turn.message } },
task: { actions: { [WORKER_TASK_ENTRY]: workerTaskEntry({ name: "research-task", turn: door }) } }
diff --git a/packages/workforce/test/coordinator-routing.test.ts b/packages/workforce/test/coordinator-routing.test.ts
index 4d942be4f3..ffe3578004 100644
--- a/packages/workforce/test/coordinator-routing.test.ts
+++ b/packages/workforce/test/coordinator-routing.test.ts
@@ -584,8 +584,12 @@ describe("judgment (V7)", () => {
expect(read.output.delegates.map(({ takes: _takes, description: _description, ...record }: any) => record)).toEqual(
(await host.sessionState(id)).delegates
);
- // Never in its prompt: the turn's system text names no delegate.
- const prompt = JSON.stringify(judgment.calls[0]!.input);
+ // Never in its prompt: the turn's system text names no delegate. The
+ // tool list is left out: sendMessage's names every roster worker it
+ // could message, delegate or not.
+ const messages = judgment.calls[0]!.input as Array<{ role: string; content: unknown }>;
+ const prompt = JSON.stringify(messages.filter((m) => !(typeof m.content === "string" && m.content.startsWith(""))));
+ expect(prompt).toContain("Route the work.");
expect(prompt).not.toContain("eng.coder");
});
diff --git a/packages/workforce/test/custom-worker-flow-data.test.ts b/packages/workforce/test/custom-worker-flow-data.test.ts
index dab3613c77..a2e4f6d332 100644
--- a/packages/workforce/test/custom-worker-flow-data.test.ts
+++ b/packages/workforce/test/custom-worker-flow-data.test.ts
@@ -13,6 +13,8 @@ import { createFlowState, inMemoryStores, runAction } from "@flow-state-dev/engi
import { z } from "zod";
import { workerConfigSchema } from "../src/worker-config";
import { createWorkerInstallation } from "../src/workers/installation";
+import { hearsMessages } from "./conversation-board-harness";
+import { workerMessagesResources } from "../src/messages/message-log";
/** One row per worker, in the user's scope: keyed by the worker, so kept per worker. */
const workerNotes = defineResourceCollection({
@@ -59,7 +61,8 @@ function host() {
kind: "research",
configSchema: workerConfigSchema(),
session: installation.session(),
- resources: { ...installation.resources },
+ resources: { ...installation.resources, ...workerMessagesResources },
+ internal: { actions: hearsMessages(installation, "research") },
actions: { respond: { inputSchema: input, block: door, userMessage: (i: { message: string }) => i.message } }
});
flows = { research };
diff --git a/packages/workforce/test/delegate-takes-conversation-tasks.test.ts b/packages/workforce/test/delegate-takes-conversation-tasks.test.ts
index 3b7fb736e8..6dcf980858 100644
--- a/packages/workforce/test/delegate-takes-conversation-tasks.test.ts
+++ b/packages/workforce/test/delegate-takes-conversation-tasks.test.ts
@@ -21,7 +21,8 @@ import { z } from "zod";
import { workerTaskEntry } from "../src/conversation-board/task-entry";
import { workerConfigSchema } from "../src/worker-config";
import type { WorkerInstallation } from "../src/workers/installation";
-import { bootBoardHost, boardWorkers, messageOf, type BoardHost } from "./conversation-board-harness";
+import { bootBoardHost, boardWorkers, messageOf, type BoardHost, hearsMessages } from "./conversation-board-harness";
+import { workerMessagesResources } from "../src/messages/message-log";
const doorInput = z.object({ message: z.string() });
@@ -47,7 +48,8 @@ function boardedFlow(installation: WorkerInstallation, flow: string, door: "othe
kind: flow,
configSchema: workerConfigSchema(),
session: installation.session(),
- resources: { ...installation.resources },
+ resources: { ...installation.resources, ...workerMessagesResources },
+ internal: { actions: hearsMessages(installation, flow) },
actions: { respond: { inputSchema: doorInput, block: turn, userMessage: (i: { message: string }) => i.message } },
task: { actions: { work } }
} as never);
diff --git a/packages/workforce/test/error-reporter.test.ts b/packages/workforce/test/error-reporter.test.ts
index 023f4990d2..91bf4d1098 100644
--- a/packages/workforce/test/error-reporter.test.ts
+++ b/packages/workforce/test/error-reporter.test.ts
@@ -21,7 +21,8 @@ import {
} from "../src/error-reporter";
import { workerConfigSchema } from "../src/worker-config";
import type { WorkerInstallation } from "../src/workers/installation";
-import { boardWorkers, bootBoardHost, messageOf, ORG, type BoardHost } from "./conversation-board-harness";
+import { boardWorkers, bootBoardHost, messageOf, ORG, type BoardHost, hearsMessages } from "./conversation-board-harness";
+import { workerMessagesResources } from "../src/messages/message-log";
const OPERATOR = "olive";
const CONVERSATION = "s_error-reporter";
@@ -96,7 +97,8 @@ function breakerFlow(installation: WorkerInstallation) {
kind: "breaker",
configSchema: workerConfigSchema(),
session: installation.session(),
- resources: { ...installation.resources },
+ resources: { ...installation.resources, ...workerMessagesResources },
+ internal: { actions: hearsMessages(installation, "breaker") },
actions: { respond: { inputSchema: z.object({ message: z.string() }), block: door, userMessage: (i: { message: string }) => i.message } }
});
}
diff --git a/packages/workforce/test/message-to-a-busy-task-session.test.ts b/packages/workforce/test/message-to-a-busy-task-session.test.ts
index 0afce8aaee..40f187330d 100644
--- a/packages/workforce/test/message-to-a-busy-task-session.test.ts
+++ b/packages/workforce/test/message-to-a-busy-task-session.test.ts
@@ -28,7 +28,8 @@ import { conversationLedgerAt } from "../src/conversation-board/ledger";
import { messageLogOf } from "../src/messages/message-log";
import { MESSAGE_RECEIVED_ENTRY } from "../src/messages/keys";
import type { WorkerInstallation } from "../src/workers/installation";
-import { bootBoardHost, messageOf, type BoardHost } from "./conversation-board-harness";
+import { bootBoardHost, messageOf, type BoardHost, hearsMessages } from "./conversation-board-harness";
+import { workerMessagesResources } from "../src/messages/message-log";
const worker = (id: string, declared: Record): WorkerManifest => ({ id, declared, body: "", skills: [] });
const WORKERS = [
@@ -70,7 +71,8 @@ function slowHelperFlow(installation: WorkerInstallation, behaviour: Behaviour)
kind: "slowhelper",
configSchema: workerConfigSchema(),
session: installation.session(),
- resources: { ...installation.resources },
+ resources: { ...installation.resources, ...workerMessagesResources },
+ internal: { actions: hearsMessages(installation, "slowhelper") },
actions: { respond: { inputSchema: doorInput, block: turn, userMessage: (i: { message: string }) => i.message } },
task: { actions: { work: workerTaskEntry({ name: "slow-helper-task", turn }) } }
} as never);
diff --git a/packages/workforce/test/worker-registration.test.ts b/packages/workforce/test/worker-registration.test.ts
index 78eeaf8e69..84d678b162 100644
--- a/packages/workforce/test/worker-registration.test.ts
+++ b/packages/workforce/test/worker-registration.test.ts
@@ -13,6 +13,8 @@ import { createFlowRegistry } from "@flow-state-dev/engine";
import { z } from "zod";
import { createWorkerInstallation, hireWorkforce, ROSTER_FLOW, workerFlow, type WorkerInstallation } from "../src/index";
import { workerConfigSchema } from "../src/worker-config";
+import { workerMessagesResources } from "../src/messages/message-log";
+import { hearsMessages } from "./conversation-board-harness";
const door = z.object({ message: z.string() });
@@ -20,7 +22,13 @@ function researchFlow(installation: WorkerInstallation | undefined) {
return defineFlow({
kind: "research",
configSchema: workerConfigSchema(),
- ...(installation !== undefined ? { session: installation.session(), resources: { ...installation.resources } } : {}),
+ ...(installation !== undefined
+ ? {
+ session: installation.session(),
+ resources: { ...installation.resources, ...workerMessagesResources },
+ internal: { actions: hearsMessages(installation, "research") }
+ }
+ : {}),
actions: {
respond: {
inputSchema: door,
@@ -100,6 +108,32 @@ describe("hireWorkforce", () => {
expect(() => hireWorkforce(made)).toThrow(/refused 1 worker flow \("doorless"\); nothing was hired[\s\S]*no door/);
});
+ // Every worker on an installation can be messaged, so a flow no worker
+ // could hear a message on is refused before anything registers (FIX-2238).
+ it("refuses a worker flow with no onMessageReceived, naming it, and hires the same flow with the entry", () => {
+ const hire = (internal: (made: WorkerInstallation) => Record) => {
+ let flows: Record = {};
+ const made = createWorkerInstallation({
+ standardWorkers: [{ id: "desk.ok", declared: { flow: "research" }, body: "Fine." }],
+ workerFlows: () => flows as never
+ });
+ const deaf = defineFlow({
+ kind: "deaf",
+ configSchema: workerConfigSchema(),
+ session: made.session(),
+ resources: { ...made.resources, ...workerMessagesResources },
+ actions: { respond: { inputSchema: door, userMessage: (i: { message: string }) => i.message, block: handler({ name: "deaf-run", inputSchema: door, execute: (input) => input }) } },
+ internal: { actions: internal(made) }
+ });
+ flows = { research: researchFlow(made), deaf };
+ return () => hireWorkforce(made);
+ };
+ expect(hire(() => ({}))).toThrow(/refused 1 worker flow[\s\S]*worker flow "deaf" has no "onMessageReceived"/);
+ const handBuilt = { inputSchema: z.object({ messageId: z.string() }), block: handler({ name: "deaf-hand-built", inputSchema: z.object({ messageId: z.string() }), execute: () => ({}) }) };
+ expect(hire(() => ({ onMessageReceived: handBuilt })), "a hand-built entry is no entry").toThrow(/"deaf" has a "onMessageReceived" that `messageReceivedEntry` didn't build/);
+ expect(hire((made) => hearsMessages(made, "deaf"))).not.toThrow();
+ });
+
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.
diff --git a/packages/workforce/test/worker-roles.test.ts b/packages/workforce/test/worker-roles.test.ts
index fb29c32b4f..ebe7c93d69 100644
--- a/packages/workforce/test/worker-roles.test.ts
+++ b/packages/workforce/test/worker-roles.test.ts
@@ -31,6 +31,9 @@ import { ROLE_PROBES } from "../src/worker-roles";
import { routeOnSchema } from "../src/coordinator/coordinator-rounds";
import { workstreamDelegateChangeSchema } from "../src/projects/project-coordinator";
+import { hearsMessages } from "./conversation-board-harness";
+import { workerMessagesResources } from "../src/messages/message-log";
+
const message = z.object({ message: z.string() });
const turn = handler({ name: "roles-turn", inputSchema: message, outputSchema: z.object({}), execute: () => ({}) });
const respond = { inputSchema: message, block: turn, userMessage: (i: { message: string }) => i.message };
@@ -41,7 +44,13 @@ function flowOn(installation: WorkerInstallation | undefined, flowName: string,
kind: flowName,
cardinality: "collection",
configSchema: workerConfigSchema(),
- ...(installation === undefined ? {} : { session: installation.session(), resources: { ...installation.resources } }),
+ ...(installation === undefined
+ ? {}
+ : {
+ session: installation.session(),
+ resources: { ...installation.resources, ...workerMessagesResources },
+ internal: { actions: hearsMessages(installation, flowName) }
+ }),
actions: { respond },
...over
} as never) as never;
diff --git a/packages/workforce/test/worker-task-entry-block.test.ts b/packages/workforce/test/worker-task-entry-block.test.ts
index d94a03ab99..bcff27bc18 100644
--- a/packages/workforce/test/worker-task-entry-block.test.ts
+++ b/packages/workforce/test/worker-task-entry-block.test.ts
@@ -16,7 +16,8 @@ import { workerTaskEntry } from "../src/conversation-board/task-entry";
import { conversationLedgerResources } from "../src/conversation-board/ledger";
import { workerConfigSchema } from "../src/worker-config";
import type { WorkerInstallation } from "../src/workers/installation";
-import { bootBoardHost, boardWorkers, messageOf, type BoardHost } from "./conversation-board-harness";
+import { bootBoardHost, boardWorkers, messageOf, type BoardHost, hearsMessages } from "./conversation-board-harness";
+import { workerMessagesResources } from "../src/messages/message-log";
/** What the block was handed, per run. */
type Seen = { taskId: string; goal: string; input: unknown; claim: unknown };
@@ -41,7 +42,8 @@ function blockFlow(installation: WorkerInstallation, seen: Seen[]) {
kind: "blocker",
configSchema: workerConfigSchema(),
session: installation.session(),
- resources: { ...installation.resources, ...conversationLedgerResources },
+ resources: { ...installation.resources, ...conversationLedgerResources, ...workerMessagesResources },
+ internal: { actions: hearsMessages(installation, "blocker") },
actions: { respond: { inputSchema: doorInput, block: door, userMessage: (i: { message: string }) => i.message } },
task: { actions: { work: workerTaskEntry({ name: "blocker-task", block: run }) } }
} as never);
From 1feba4213dca9edddb7fbf5a390e19b1330ee542 Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 27 Oct 2026 22:24:51 +0000
Subject: [PATCH 05/14] FIX-2238: docs, changeset, goal amended, epic seams
updated
Docs and READMEs describe sendMessage, onMessageReceived, the received
item (which now carries the budget left), the landing rules, the budget and
the refusals. The workers-message-each-other goal gets the spec's new legs,
controls and sweep. The epic's seam table, ER-6 and stack order follow the
cross-spec review.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
.../a-worker-hears-a-message-on-receipt.md | 7 +
apps/docs/docs/shift-manager/overview.md | 2 +-
apps/docs/docs/workforce/delegating-work.md | 6 +-
apps/docs/docs/workforce/messaging-workers.md | 195 ++++++++---
apps/docs/docs/workforce/ui.md | 2 +-
apps/docs/docs/workforce/workers-on-disk.md | 3 +
.../workers-message-each-other/controls.mts | 179 +++++++---
.../workers-message-each-other/hire-check.mts | 50 +++
.../workers-message-each-other/legs.mts | 311 +++++++++++++-----
.../workers-message-each-other/run.mts | 73 +++-
packages/shift-manager/README.md | 3 +
packages/workforce/README.md | 174 +++++++---
.../src/messages/message-received-entry.ts | 2 +-
.../workforce/test/worker-messages.test.ts | 4 +-
specs/epics/FIX-2070/DECISIONS.md | 8 +-
specs/epics/FIX-2070/SPEC.md | 5 +-
16 files changed, 784 insertions(+), 240 deletions(-)
create mode 100644 .changeset/a-worker-hears-a-message-on-receipt.md
create mode 100644 goals/shift-manager/workers-message-each-other/hire-check.mts
diff --git a/.changeset/a-worker-hears-a-message-on-receipt.md b/.changeset/a-worker-hears-a-message-on-receipt.md
new file mode 100644
index 0000000000..ca96d9d352
--- /dev/null
+++ b/.changeset/a-worker-hears-a-message-on-receipt.md
@@ -0,0 +1,7 @@
+---
+"@flow-state-dev/workforce": minor
+---
+
+Workers message each other with `sendMessage({ to, text, inReplyTo? })` and hear one through the `onMessageReceived` entry, which `hireWorkforce` now requires on every worker flow on an installation (FIX-2238). A received message lands as a history line plus its own client item (`workforce:received`, with `from`, `id` and `inReplyTo`), and nothing is relayed: a worker answers by sending a message with `inReplyTo`, and its plain text reaches no one. An answer lands in the session its original was sent from, and a message to the worker that filed the sender's task lands in the filing conversation. One budget covers a typed message: 6 messages in all, 3 per request. A task filed held starts a fresh budget when released, and filing or a refused send spends nothing. Coordinators can be messaged whatever their routing, and a worker that hears only in its tasks' sessions (`hears: "task-sessions"`) is refused by name with `task_sessions_only`.
+
+**Migration.** `messageWorker` is now `sendMessage`. `onWorkerMessage` is now `onMessageReceived`; build it with `messageReceivedEntry({ installation, flowKind, turn?, hears? })` (or spread the session kit's `entries`), and add `workerMessagesResources` to a flow without the kit. `replyTo` is now `inReplyTo`. The removed exports are `MESSAGE_WORKER_TOOL`, `WORKER_MESSAGE_ENTRY`, `messageWorkerInputSchema`, `sendWorkerMessage`, `SendWorkerMessage` and `takesWorkerMessages`, and the new ones are `SEND_MESSAGE_TOOL`, `MESSAGE_RECEIVED_ENTRY`, `RECEIVED_MESSAGE_COMPONENT`, `sendMessageInputSchema`, `sendMessage` and `SendMessageInput`. The refusals `takes_tasks_only` and `no_turn` are gone, `hop_limit` is now `budget`, and `per_turn_limit` is now `per_request_limit`. A message row no longer carries `answerTo`.
diff --git a/apps/docs/docs/shift-manager/overview.md b/apps/docs/docs/shift-manager/overview.md
index 88597d4287..1a5a59909e 100644
--- a/apps/docs/docs/shift-manager/overview.md
+++ b/apps/docs/docs/shift-manager/overview.md
@@ -73,7 +73,7 @@ In your own app, `openWorkstream` takes whichever lead you name. See [Projects](
Shift Coordinator, a workstream and a task also have a panel on the right. The sidebar and the right panel each collapse from their own toggle or from the keyboard: `[` for the sidebar, which shrinks to a column of icons, and `]` for the right panel, which shrinks to a strip. Each one's state is kept in the browser for the signed-in user. On a window narrower than 1180px, the right panel starts collapsed and opens over the center.
-In a conversation, a message the worker sent another worker shows as its own line, *To <worker>: <text>*, with a link to Messages. One that was refused says it wasn't sent, and why. A message a worker received shows as *From <worker>: <text>*, under the sender's name.
+In a conversation, a message the worker sent another worker shows as its own line, *To <worker>: <text>*, with a link to Messages. One that was refused says it wasn't sent, and why. A message the worker received shows as its own item: the sender's name, the time it arrived, *answering your message* when it answers one the worker sent, a *Messages ›* link, and the text.
A board has five columns: QUEUED, RUNNING, IN REVIEW, NEEDS YOU and DONE. In a workstream's composer, a message that starts with `@` and a worker's name goes to that worker's task in the workstream.
diff --git a/apps/docs/docs/workforce/delegating-work.md b/apps/docs/docs/workforce/delegating-work.md
index e406c6d565..0b93a957d9 100644
--- a/apps/docs/docs/workforce/delegating-work.md
+++ b/apps/docs/docs/workforce/delegating-work.md
@@ -116,7 +116,7 @@ What the kit gives you, and where each piece goes:
| Field | Put it in |
|-------|-----------|
| `tools` | The `uses` of the block that runs the model. It carries the task tools only while the session files, and nothing otherwise. |
-| `messages` | The same `uses`. It carries `messageWorker`, which [messages another worker](./messaging-workers.md). Leave it out and the flow's workers can receive messages but not send them. |
+| `messages` | The same `uses`. It carries `sendMessage`, which [messages another worker](./messaging-workers.md). Leave it out and the flow's workers can receive messages but not send them. |
| `actions` | The flow's `actions`: the task tools as `_tasks`, plus `addDelegate`, `removeDelegate`, `setFallback` and `listDelegates`. |
| `progress` | The same `uses`. It carries `reportProgress` on a turn working a task. |
| `delegateTools` | The same `uses`. It carries `listDelegates`, and `addDelegate`, `removeDelegate` and `setFallback` on a worker set to `editsOwnDelegates: true`. |
@@ -124,7 +124,7 @@ What the kit gives you, and where each piece goes:
| `sessionStateShape` | `installation.session(...)`. |
| `serverOwned` | The flow's `session.serverOwned`. |
| `planned(turn)` | Wrap the block that answers a message, and use what it returns wherever that block runs as the worker: the `respond` action, the task entry's `turn`, and `entries`. The steps the worker files for itself then run in the same request. See [Working in steps](#working-in-steps). Leave it out and the flow's workers file no steps. |
-| `entries(turn)` | The flow's `internal: { actions }`. Pass the block that answers a message; it is woken with a line when a task the session filed ends, and when another worker messages this one. The entries include `dispatch`, which runs the session's board one pass at a time, and `onTaskSettled`, where each of those endings arrives. |
+| `entries(turn)` | The flow's `internal: { actions }`. Pass the block that answers a message; it is woken with a line when a task the session filed ends, and when another worker messages this one. The entries include `dispatch`, which runs the session's board one pass at a time, `onTaskSettled`, where each of those endings arrives, and `onMessageReceived`, where another worker's message arrives. |
| `files(ctx)` | Read it when you need to know whether the running session files now. |
| `taskDelegates(ctx)` | The session's delegates as a task sees them: `available` (worker id to flow) and `unavailable` (worker id to why). |
@@ -216,7 +216,7 @@ A worker given a task can split it into pieces for its own delegates. A piece fo
The pieces go on the task session's own board. The worker either waits on a piece in the same turn, with `getTask({ id, wait: true })`, or files them and ends its turn. Waits nest up to five deep, so a task's turn can wait on a piece whose own turn waits on another. When the turn ends instead, nothing runs for the task while the pieces are worked, but the task stays `in_progress`, with `waitingOn: "filed"` on its row, and it isn't handed out again while it waits. See [When a dispatched task is done](../orchestration/task-board.md#when-a-dispatched-task-is-done) for the rule every dispatched task follows.
-Each piece's ending wakes the worker for a turn in the task session, where it reads the result and decides what it means. A turn can file more pieces, and the task waits on those too. A message to the worker in its task session doesn't hold the task and isn't part of it. While the task's turn is running, the worker answers it after that turn; while the task waits on its pieces, it may answer it before the task is done. Either way the answer can't write to the task, and a failure in it doesn't fail the task.
+Each piece's ending wakes the worker for a turn in the task session, where it reads the result and decides what it means. A turn can file more pieces, and the task waits on those too. A message to the worker in its task session doesn't hold the task and isn't part of it. While the task's turn is running, the worker hears it after that turn; while the task waits on its pieces, it may hear and answer it before the task is done. Either way its turn on the message can't write to the task, and a failure in it doesn't fail the task.
The task completes once no piece is open and the worker has had a turn on every piece's ending. Its output follows the same rule as any task's: the latest checkpoint the worker reported with `reportProgress`, or, with none, the answer from the last turn a piece's ending woke. A message's answer is never the output.
diff --git a/apps/docs/docs/workforce/messaging-workers.md b/apps/docs/docs/workforce/messaging-workers.md
index 5d721ab0ee..36e9c3819f 100644
--- a/apps/docs/docs/workforce/messaging-workers.md
+++ b/apps/docs/docs/workforce/messaging-workers.md
@@ -2,41 +2,40 @@
title: Messaging other workers
sidebar_position: 3.7
sidebar_label: Messaging workers
-description: "A worker can send any other worker on your roster a short message. The message wakes the recipient in its own conversation, and an answer comes back the same way."
+description: "A worker can send any other worker on your roster a short message. The message wakes the recipient, and the recipient answers, if it wants to, by sending a message back."
---
# Messaging other workers
Sometimes a worker needs to ask a colleague something, or tell it something, without handing it any work. Your researcher wants to know a codename the coordinator was told. The coordinator wants to pass a correction on to the researcher. Workers do this with **messages**.
-A message is a line of text from one worker to another on the same user's roster. It lands in the recipient's own conversation with that user, and the recipient takes a turn to read it. Nothing is filed, no result is owed, and the sender doesn't wait.
+A message is a line of text from one worker to another on the same user's roster. It wakes the recipient for a turn, and the recipient decides what to do about it. Nothing is filed, no result is owed, and the sender doesn't wait.
## Who can send and receive
-A worker can send and receive messages when its flow runs a conversation with you:
+Every worker flow on an installation receives messages. On these flows, workers can send them too:
-- workers on the [built-in worker](./built-in-worker.md) flow, `agent`;
-- [coordinators](./coordinators.md) that route by `judgment` or `best-fit`;
-- workers on a [flow of your own](#on-your-own-worker-flow) built with `defineSessionBoard`.
+- the [built-in worker](./built-in-worker.md) flow, `agent`;
+- the [coordinator](./coordinators.md) flow, whatever the coordinator routes by;
+- a [flow of your own](#on-your-own-worker-flow) built with `defineSessionBoard`.
-On the built-in and coordinator flows there's nothing to switch on: every worker gets a `messageWorker` tool on every turn. Your own flow needs [one line](#on-your-own-worker-flow).
+On the built-in and coordinator flows there's nothing to switch on: every worker gets a `sendMessage` tool on every turn. Your own flow needs [one line](#on-your-own-worker-flow).
A worker can message any other worker on its user's roster: your own hires and the standard workers from your files. A worker on another user's roster can't be reached, and the refusal reads the same as for a worker that doesn't exist.
-Some workers can't take part:
+A message to a coordinator wakes the coordinator's own turn, even one that hands your lines straight to its delegates by `round-robin` or `everyone`.
-- **Workers that only take tasks**, such as a coding run. They have no conversation to read a message in. Message one and the send is refused, telling the sender to file a task instead.
-- **Coordinators that route by `round-robin` or `everyone`.** They hand every line to their delegates and never run a turn of their own, so nobody would read the message.
+Some workers hear messages only in their tasks' sessions, such as the coding worker in Shift Manager's `devteam` Lab. They have no conversation to answer from, so a message sent to one by name is refused with `task_sessions_only`, and nothing is sent. File it a task instead.
## Sending a message
-The model calls `messageWorker` with the recipient's worker id and the text:
+The model calls `sendMessage` with the recipient's worker id and the text:
```json
{ "to": "chief-of-staff", "text": "What's the codename for the spring launch?" }
```
-The tool's description lists the workers this worker can message right now, with each one's description, so the model picks from real ids. Workers it can't message aren't listed.
+The input takes `to`, `text` and, for an answer, `inReplyTo`. Nothing else. The tool's description lists the workers the send would take, by id and description, so the model picks from real ids. The sending worker itself, and workers that hear only in task sessions, aren't listed.
A sent message answers with its id:
@@ -54,43 +53,54 @@ If the delivery couldn't be confirmed, the answer says so. The message may still
## What the recipient sees
-The message lands in the recipient's own conversation with you, the one [`ensureWorkerSession({ worker })`](./workers-on-disk.md#talking-to-a-worker) returns. If you've never talked to that worker, the conversation is started for you. It shows as a line under the sender's name, its `agentName`:
+When a message arrives, the session it lands in gets two items:
-```text
-From researcher: What's the codename for the spring launch?
-```
+- a line the recipient's model reads in its history, `From researcher: What's the codename for the spring launch?`, under the sender's name. It is never sent to the client.
+- a component item of type `workforce:received` (`RECEIVED_MESSAGE_COMPONENT`), for your app to draw. Its `data` is `{ id, from, text, inReplyTo?, budget }`, where `budget` is how many more messages the exchange can send after this one. See [Showing messages in your app](#showing-messages-in-your-app).
+
+Then the recipient takes a turn on it. That turn is told the message id, who sent it, how to answer, and how many more messages the exchange can send (see [The budget](#the-budget)).
-Then the recipient takes a turn, every time, to read the message and decide what to do about it. That turn sees the message id, who sent it and how to answer. A recipient in the middle of a turn reads the message once that turn ends.
+A recipient in the middle of a turn hears the message after that turn ends. If the same message is delivered twice, the recipient wakes once.
-You see all of it. Both workers' conversations are yours, and the message, the turn it started and any answer are in them like anything else.
+You see all of it. Both workers' sessions are yours, and the message, the turn it started and any answer are in them like anything else.
-When the sender is working in a project, a message to the [project coordinator](./projects.md#talking-to-a-project) lands in its conversation for that project.
+### Where a message lands
+
+| The message is | It lands in |
+|----------------|-------------|
+| An answer (sent with `inReplyTo`) | The session the original message was sent from, even a task's session whose task has finished. The answer wakes a turn there. |
+| To the worker that filed the sender's current task, or the sender's ongoing delegate session | The conversation that filed it. |
+| To the [project coordinator](./projects.md#talking-to-a-project), from work in a project | That project's conversation with the coordinator. |
+| Anything else | The recipient's own conversation with you, the one [`ensureWorkerSession({ worker })`](./workers-on-disk.md#talking-to-a-worker) returns. If you've never talked to that worker, the conversation is opened. |
## Answering
-To answer, the recipient calls `messageWorker` again, back to the sender, with the id of the message it's answering as `replyTo`:
+Nothing is sent back on its own. To answer, the recipient calls `sendMessage` back to the sender, with the id of the message it's answering as `inReplyTo`:
```json
-{ "to": "researcher", "text": "It's Bluebird.", "replyTo": "msg_3f1c0a9e2b7d4c6a8e10" }
+{ "to": "researcher", "text": "It's Bluebird.", "inReplyTo": "msg_3f1c0a9e2b7d4c6a8e10" }
```
-`replyTo` must name a message the `to` worker sent this worker. Anything else is refused.
+`inReplyTo` must name a message the `to` worker sent this worker. Anything else is refused with `no_such_message`.
+
+If the recipient's turn ends in plain text, that text goes to no one. Not answering is a valid answer: an FYI usually needs none.
-The answer goes back to the session the first message was sent from, as a `From chief-of-staff: …` line, and wakes the sender there. If the sender sent the message while working a task, a coordinator's routed task included, the answer lands in the sender's own conversation with you instead, and wakes it there.
+There's no way to block on a reply. A worker that's told to "wait for the answer" sends the message and ends its turn. The answer starts a new turn when it comes. When a worker needs a colleague's result before it can go on, it should file a task and wait on that instead (see [Message or delegate?](#message-or-delegate)).
-If the recipient's turn ends without messaging the sender, the turn's final text goes to the sender as the answer, exactly as if it had been sent with `messageWorker` and `replyTo`. Final text over 8,000 characters is cut to fit. A turn that did message the sender sends nothing more, and a turn that ends with no text sends nothing at all. Nothing waits on an answer.
+## The budget
-A turn woken by an answer never sends its final text back, so an exchange ends after one answer unless a worker sends another message.
+Messages between workers can't run on forever. Each line you type starts a **budget**: at most 6 messages (`hopLimit`) for everything that descends from that line, across every worker. The messages, the turns they wake, the answers those turns send and the tasks filed along the way all draw on the same 6, parallel branches included. On top of that, any one request sends at most 3 (`perTurn`).
-There's no way to block on a reply. A worker that's told to "wait for the answer" sends the message and ends its turn. The answer starts a new turn when it comes.
+The send that would go past the budget is refused with `budget`, and the worker is told to stop passing messages on and say so. Your next line starts a fresh budget.
-## Limits
+A fresh budget also starts:
-**A chain stops after 6 messages with nobody in between.** Everything that descends from one of your lines is one chain with one count: the messages, the turns they wake, the answers those turns send and the tasks filed along the way. Workers that fan out in parallel draw on the same 6. The send that would be the 7th is refused, and the worker is told to stop passing messages on and say so. Your next line to a worker starts a new chain with a count of its own.
+- for a task that was filed held, when it is released;
+- for a request with nothing behind it, such as one your server code starts.
-**A turn sends at most 3 messages.** The 4th send in the same turn is refused.
+A task a woken worker files draws on its filer's budget, and so does a delegate's ongoing session. Filing a task spends nothing, and a refused send spends nothing.
-An answer sent from a turn's final text counts toward both limits like any other message. When either limit would refuse it, nothing is sent and the log gets no row.
+A woken turn sees what's left: its input's `budget` field, and the prompt the session kit builds, say how many more messages the exchange can send.
Both limits are set when you register the flows:
@@ -100,8 +110,8 @@ const flows = hireWorkforce(installation, { messages: { hopLimit: 10, perTurn: 5
| Option | Default | What it limits |
|--------|---------|----------------|
-| `messages.hopLimit` | `6` | Worker messages in one chain: everything descending from one user's line. |
-| `messages.perTurn` | `3` | Messages one turn sends. |
+| `messages.hopLimit` | `6` | Worker messages descending from one of the user's lines, across every worker. |
+| `messages.perTurn` | `3` | Messages one request sends. |
Each must be a whole number of at least 1, or `hireWorkforce` throws.
@@ -110,21 +120,22 @@ Each must be a whole number of at least 1, or `hireWorkforce` throws.
A refused send answers `{ ok: false, error }`, and nothing is sent. The error starts with a code, then says what happened in words the model can act on:
```json
-{ "ok": false, "error": "takes_tasks_only: \"eng.coder\" only takes tasks and can't be messaged. File a task for it instead." }
+{ "ok": false, "error": "task_sessions_only: \"eng.coder\" answers only from its tasks' sessions, so it can't be messaged by name. File it a task instead." }
```
| Code | When |
|------|------|
-| `no_worker` | No worker by that id on the user's roster. Another user's worker answers this too. |
+| `not_a_worker` | The sending session runs no worker. |
+| `empty_message` | `text` is blank. |
+| `message_too_long` | `text` is over 8,000 characters. |
| `not_yourself` | `to` is the sending worker. |
+| `no_worker` | No worker by that id on the user's roster. Another user's worker answers this too. |
| `worker_unavailable` | The worker is on the roster but can't run, for example because its saved row can't be read. The error says why. |
-| `takes_tasks_only` | The worker only takes tasks. |
-| `no_turn` | The worker is a coordinator that routes by `round-robin` or `everyone`. |
-| `no_such_message` | `replyTo` names no message the `to` worker sent this worker. |
-| `hop_limit` | The chain reached `messages.hopLimit` with nobody in between. |
-| `per_turn_limit` | This turn already sent `messages.perTurn` messages. |
-| `empty_message` / `message_too_long` | `text` is blank, or over 8,000 characters. |
-| `not_delivered` | The recipient's server refused the delivery. The error carries its reason. |
+| `task_sessions_only` | The worker hears messages only in its tasks' sessions. File it a task instead. |
+| `no_such_message` | `inReplyTo` names no message the `to` worker sent this worker. |
+| `budget` | The send would go past `messages.hopLimit` messages since the user's last line. |
+| `per_request_limit` | This request already sent `messages.perTurn` messages. |
+| `not_delivered` | The server refused the delivery. The error carries its reason. |
## Message or delegate?
@@ -133,18 +144,18 @@ A message is talk. [Delegating](./delegating-work.md) is handing over work. Pick
| | Message | Task |
|-|---------|------|
| What it's for | A question, an FYI, a heads-up | Work that has to get done |
-| Who it can go to | Any worker on your roster that has a conversation | One of the worker's own delegates that takes tasks |
-| Where it runs | The recipient's own conversation with you | A new task session of its own |
-| What comes back | Nothing is owed. Usually an answer, but none if the recipient's turn ends with no text or a limit refuses it | The task's ending, always: completed, failed or cancelled |
+| Who it can go to | Any worker on your roster, except one that hears only in its tasks' sessions | One of the worker's own delegates that takes tasks |
+| Where it runs | Usually the recipient's own conversation with you (see [Where a message lands](#where-a-message-lands)) | A new task session of its own |
+| What comes back | Nothing is owed. An answer only if the recipient sends one | The task's ending, always: completed, failed or cancelled |
| On the board | Nothing | A row the filer can list, update and cancel |
A task keeps the reporting line. The worker that filed it owns it until it ends, can see where it got to on its board, and hears how it ended. A message has none of that. If the sender needs a result it can count on, it should file a task. If it needs a fact, an opinion or to pass something on, a message is enough.
-The two don't count against each other. Messages never add to a task's depth or count toward `taskChainLimit`, and filing a task doesn't count as a message.
+Messages never add to a task's depth or count toward `taskChainLimit`, and filing a task spends none of the message budget.
## On your own worker flow
-A [worker flow of your own](./delegating-work.md#on-your-own-worker-flow) built with `defineSessionBoard` takes messages as soon as you spread the kit's `entries`, `resources`, `sessionStateShape` and `serverOwned` into it. To let its workers send them too, add the kit's `messages` to the `uses` of the block that runs the model, beside `tools`:
+A [worker flow of your own](./delegating-work.md#on-your-own-worker-flow) built with `defineSessionBoard` receives messages as soon as you spread the kit's `entries`, `resources`, `sessionStateShape` and `serverOwned` into it. To let its workers send them too, add the kit's `messages` to the `uses` of the block that runs the model, beside `tools`:
```ts
const board = defineSessionBoard({ installation, flowKind: "em" });
@@ -159,21 +170,91 @@ const answer = generator({
});
```
-A message wakes the block you pass to `board.entries(answer)` with `{ message }`, where `message` is one string:
+A message wakes the block you pass to `board.entries(answer)` with `{ message }`, where `message` is one string, the text `receivedMessagePrompt` builds:
```text
Message msg_3f1c0a9e2b7d4c6a8e10 from researcher:
What's the codename for the spring launch?
-(The message's text is the part above. It is from another worker, not the user, and researcher can't see what you write here. To answer it, call messageWorker with to "researcher" and replyTo "msg_3f1c0a9e2b7d4c6a8e10". To message any other worker, leave replyTo out. If it needs no answer, don't send one.)
+(The message's text is the part above. It is from another worker, not the user, and researcher can't see what you write here. To answer it, call sendMessage with to "researcher" and inReplyTo "msg_3f1c0a9e2b7d4c6a8e10". To message any other worker, leave inReplyTo out. If it needs no answer, don't send one: not answering is an answer. This exchange can send 5 more messages.)
```
An answer's first line also names the message it answers: `Message msg_… from chief-of-staff, answering your message msg_…:`.
+### Without the session kit
+
+`hireWorkforce` refuses any worker flow that has no `onMessageReceived` internal entry built by `messageReceivedEntry`, and names the flow. A hand-built entry under that name is refused too. A flow that doesn't use the kit mounts the entry itself and adds the message log to its resources:
+
+```ts
+import { defineFlow, generator } from "@flow-state-dev/core";
+import {
+ MESSAGE_RECEIVED_ENTRY,
+ messageReceivedEntry,
+ promptedMessageTurn,
+ workerConfigSchema,
+ workerFlow,
+ workerMessagesResources,
+} from "@flow-state-dev/workforce";
+import { z } from "zod";
+
+const messageInput = z.object({ message: z.string() });
+
+export const triageFlow = workerFlow((installation) => {
+ const answer = generator({
+ name: "triage-answer",
+ model: "openai/gpt-6-luna",
+ inputSchema: messageInput,
+ prompt: "You triage incoming requests.",
+ user: (input) => input.message,
+ });
+
+ return defineFlow({
+ kind: "triage",
+ configSchema: workerConfigSchema(),
+ session: installation.session(),
+ resources: { ...installation.resources, ...workerMessagesResources },
+ actions: {
+ respond: { inputSchema: messageInput, block: answer, userMessage: (input) => input.message },
+ },
+ internal: {
+ actions: {
+ [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({
+ installation,
+ flowKind: "triage",
+ turn: promptedMessageTurn(answer),
+ }),
+ },
+ },
+ });
+});
+```
+
+`messageReceivedEntry` takes:
+
+| Option | What it is |
+|--------|------------|
+| `installation` | Your worker installation. |
+| `flowKind` | The flow's kind. |
+| `turn` | Optional. The block a message wakes, with a `MessageReceived` as its input. Leave it out and the message lands as its two items and nothing runs. |
+| `hears` | Optional. `"task-sessions"` makes the flow's workers hear messages only in their tasks' sessions; a message to one by name is refused with `task_sessions_only`. |
+
+`turn` takes a `MessageReceived`:
+
+| Field | What it holds |
+|-------|---------------|
+| `id` | The message id, what an answer passes as `inReplyTo`. |
+| `from` | The sending worker's id. |
+| `text` | What was said. |
+| `inReplyTo` | The message this one answers, when it answers one. |
+| `budget` | How many more messages the exchange can send. |
+| `call` | Always `false`. |
+
+`promptedMessageTurn(answer)` wraps a block that takes `{ message }` so it can serve as `turn`, handing it the text `receivedMessagePrompt(received)` returns, shown above. A flow built this way receives messages. Its workers can't send them unless the block that runs the model carries the session kit's `messages`.
+
## Showing messages in your app
-Every message is kept in a log in the user's own scope, one row per message, readable from the browser. Read it through any of the user's sessions on a flow that declares it: the roster flow, the built-in worker flow, the coordinator flow, or a flow built with `defineSessionBoard`.
+Every message is kept in a log in the user's own scope, one row per message, readable from the browser. Read it through any of the user's sessions on a flow that declares it: the roster flow, the built-in worker flow, the coordinator flow, or a worker flow that spreads `workerMessagesResources` (the session kit's `resources` include it).
```ts
import { createClient, readEveryCollectionPage } from "@flow-state-dev/client";
@@ -202,17 +283,23 @@ Each row has:
| `from`, `to` | The sending and receiving worker ids. |
| `text` | What was said. |
| `exchange` | The id of the first message in the exchange. A message and its answers share one. |
-| `replyTo` | The message this one answers, when it answers one. |
-| `fromSession`, `toSession` | The session it was sent from, and the session it landed in. |
-| `chain` | The id of the chain the message belongs to: everything descending from one user's line. Optional. |
-| `hop` | Its place in that chain, from 1. |
+| `inReplyTo` | The message this one answers, when it answers one. |
+| `fromSession`, `fromFlow` | The session it was sent from, and that session's flow. |
+| `toSession`, `toFlow` | The session it landed in, and that session's flow. |
+| `chain` | The id of the budget the message drew on: everything descending from one user's line. Optional. |
+| `hop` | Its place in that budget, from 1. |
| `status` | `delivered`, `refused`, or `unconfirmed`. |
| `reason` | Why it was refused or is unconfirmed. |
| `at` | When it was sent, in ms. |
The read never returns another user's messages.
-In a conversation, a sent message is a `tool_output` item for the tool named `MESSAGE_WORKER_TOOL` (`"messageWorker"`), from `@flow-state-dev/workforce/browser`. Match on it to draw a sent message as a line of its own rather than a tool call. [Shift Manager](../shift-manager/overview.md) does both: its Messages screen lists the log, and a conversation shows each sent message as *To <worker>: <text>*.
+In a conversation, each side of a message is an item you can match on. Both names come from `@flow-state-dev/workforce/browser`:
+
+- A sent message is a `tool_output` item for the tool named `SEND_MESSAGE_TOOL` (`"sendMessage"`). Match on it to draw the message as a line of its own rather than a tool call.
+- A received message is a `component` item whose component is `RECEIVED_MESSAGE_COMPONENT` (`"workforce:received"`), with `data` of `{ id, from, text, inReplyTo?, budget }`.
+
+[Shift Manager](../shift-manager/overview.md) does all of this: its Messages screen lists the log, a conversation shows each sent message as *To <worker>: <text>*, and each received message as its own item under the sender's name.
## Related pages
diff --git a/apps/docs/docs/workforce/ui.md b/apps/docs/docs/workforce/ui.md
index 31a62b30e3..783b59a52b 100644
--- a/apps/docs/docs/workforce/ui.md
+++ b/apps/docs/docs/workforce/ui.md
@@ -130,7 +130,7 @@ Loading, an empty board and a failed read look different from each other. A fail
## Messages between workers
-No component draws the [messages your workers send each other](./messaging-workers.md). Read the user's message log as a collection, `WORKER_MESSAGES_RESOURCE`, through any of their worker sessions, and render the rows yourself; [Showing messages in your app](./messaging-workers.md#showing-messages-in-your-app) has the read and the row shape. In a conversation, a sent message is a `tool_output` item for the tool named `MESSAGE_WORKER_TOOL` (`"messageWorker"`). Match on it to draw a sent message as a line of its own rather than a tool call.
+No component draws the [messages your workers send each other](./messaging-workers.md). Read the user's message log as a collection, `WORKER_MESSAGES_RESOURCE`, through any of their worker sessions, and render the rows yourself; [Showing messages in your app](./messaging-workers.md#showing-messages-in-your-app) has the read and the row shape. In a conversation, a sent message is a `tool_output` item for the tool named `SEND_MESSAGE_TOOL` (`"sendMessage"`). Match on it to draw a sent message as a line of its own rather than a tool call. A received message is a `component` item whose component is `RECEIVED_MESSAGE_COMPONENT` (`"workforce:received"`), with `data` of `{ id, from, text, inReplyTo?, budget }`. Both names come from `@flow-state-dev/workforce/browser`.
## Where each component reads from
diff --git a/apps/docs/docs/workforce/workers-on-disk.md b/apps/docs/docs/workforce/workers-on-disk.md
index b3b515a501..bceafa58b4 100644
--- a/apps/docs/docs/workforce/workers-on-disk.md
+++ b/apps/docs/docs/workforce/workers-on-disk.md
@@ -414,6 +414,9 @@ A worker flow must:
- **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. Load the worker with `installation.resolveWorker` on
every turn: in the flow's `request.onStarted`, or in the block that reads it.
+- **Receive messages from other workers.** Mount an `onMessageReceived` internal action built by
+ `messageReceivedEntry`, as [Messaging other workers](./messaging-workers.md#without-the-session-kit)
+ shows. A flow built with `defineSessionBoard` gets it from the kit's `entries(turn)`.
- **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
diff --git a/goals/shift-manager/workers-message-each-other/controls.mts b/goals/shift-manager/workers-message-each-other/controls.mts
index 302580c694..baa84874fb 100644
--- a/goals/shift-manager/workers-message-each-other/controls.mts
+++ b/goals/shift-manager/workers-message-each-other/controls.mts
@@ -1,81 +1,184 @@
/**
- * The goal's six controls. Each is one scratch patch, applied as the process
- * under test loads the module (`goals/lib/module-patch.mjs`).
+ * The goal's controls. Each is a scratch patch to one or two modules, applied
+ * as the process under test loads them (`goals/lib/module-patch.mjs`).
*/
+import type { ModulePatch } from "../../lib/module-patch.mts";
-export const CONTROL_NAMES = ["no-wake", "drop-ended", "no-hop-cap", "no-roster-check", "fresh-hop-on-task", "memory-log"] as const;
+export const CONTROL_NAMES = [
+ "relay-back",
+ "ongoing-at-0",
+ "refuse-at-receive",
+ "answer-to-conversation",
+ "no-turn-back",
+ "no-hire-check",
+ "pay-first",
+ "no-wake",
+ "no-hop-cap",
+ "no-roster-check",
+ "fresh-hop-on-task",
+ "memory-log",
+] as const;
export type ControlName = (typeof CONTROL_NAMES)[number];
-/** One control: the legs it runs (the one that must fail, and any that leg needs first), the assertion that must go red, and its patch. */
+/** One control: the legs it runs (the one that must fail, and any that leg needs first), the assertion that must go red, and its patches. */
export interface Control {
name: ControlName;
legs: string[];
assertion: string;
- module: string;
- from: string;
- to: string;
+ patches: ModulePatch[];
does: string;
}
const MESSAGES = "packages/workforce/src/messages";
+const ENTRY = `${MESSAGES}/message-received-entry.ts`;
+const SEND = `${MESSAGES}/send-message.ts`;
+/** The anchor every recipient-refusal patch adds after: the first check `recipientRefusal` makes. */
+const NOT_YOURSELF = String.raw`if \(to === sender\) return "not_yourself: you can't message yourself\.";`;
export const CONTROLS: Record = {
+ "relay-back": {
+ name: "relay-back",
+ legs: ["1"],
+ assertion: "1:no-relay",
+ patches: [
+ {
+ module: ENTRY,
+ from: String.raw`return \{ act: "heard", received \};`,
+ to:
+ 'await (await import("./send-message")).sendMessage(ctx, options.installation, options.flowKind, ' +
+ '{ to: row.from, text: `Relayed: ${row.text}`, inReplyTo: row.id }, "relay-back"); ' +
+ 'return { act: "heard", received };',
+ },
+ ],
+ does: "the recipient sends every message straight back to its sender, as the relay did",
+ },
+ "ongoing-at-0": {
+ name: "ongoing-at-0",
+ legs: ["3"],
+ assertion: "3:ring-stops-at-6",
+ patches: [
+ { module: "packages/workforce/src/conversation-board/board.ts", from: String.raw`\.\.\.carriedHopState\(ctx\.session\.state\),`, to: "workforceMessageHop: 0," },
+ {
+ module: "packages/workforce/src/conversation-board/task-entry.ts",
+ from: String.raw`if \(mark !== undefined\) await startTurnAtHop\(ctx(?: as never)?, mark\.hop, mark\.chain\);`,
+ to: "if (mark !== undefined) await startTurnAtHop(ctx, 0, null);",
+ },
+ ],
+ does: "a delegate's ongoing session counts on its own: born at 0, and its task's turn starts there rather than at its filing's count",
+ },
+ "refuse-at-receive": {
+ name: "refuse-at-receive",
+ legs: ["4"],
+ assertion: "4:coder-refused",
+ patches: [{ module: SEND, from: String.raw`=== "task-sessions"\)`, to: '=== "never")' }],
+ does: "the send no longer refuses a worker that hears only in its tasks' sessions, so the row is written and the refusal is left to its entry",
+ },
+ "answer-to-conversation": {
+ name: "answer-to-conversation",
+ legs: ["1b", "2"],
+ assertion: "2:lands-in-task-session",
+ patches: [
+ {
+ module: SEND,
+ from: String.raw`destination = \{ sessionId: answered\.fromSession, flow: answered\.fromFlow \};`,
+ to: "destination = await conversationAddress(ctx, installation, input.to, recipient.flow, state);",
+ },
+ ],
+ does: "an answer lands in the recipient's own conversation, not the session its original was sent from",
+ },
+ "no-turn-back": {
+ name: "no-turn-back",
+ legs: ["4"],
+ assertion: "4:round-robin-heard",
+ patches: [
+ {
+ module: SEND,
+ from: NOT_YOURSELF,
+ to:
+ 'if (to === sender) return "not_yourself: you can\'t message yourself."; ' +
+ 'if (recipient?.flow === "coordinator" && to !== "chief-of-staff") return `no_turn: "${to}" hands every line to its delegates and runs no turn of its own.`;',
+ },
+ ],
+ does: "a coordinator that hands every line on (any but the best-fit Shift Coordinator here) is refused `no_turn`, as before",
+ },
+ "no-hire-check": {
+ name: "no-hire-check",
+ legs: ["4"],
+ assertion: "4:hire-refuses",
+ patches: [{ module: "packages/workforce/src/workers/register.ts", from: String.raw`if \(deaf\.length > 0\) \{`, to: "if (deaf.length < 0) {" }],
+ does: "hireWorkforce takes a worker flow with no onMessageReceived",
+ },
+ "pay-first": {
+ name: "pay-first",
+ legs: ["3"],
+ assertion: "3:refused-pays-nothing",
+ patches: [
+ {
+ module: SEND,
+ from: String.raw`const recipient = await installation\.rosterWorker\(ctx(?: as never)?, input\.to\);`,
+ to:
+ "const __paid = turnChainOf(ctx); " +
+ 'if (__paid !== undefined) await (await messageChainsOf(ctx).getOrCreate(__paid, { sent: [] })).updateState((row) => ({ ...row, sent: [...row.sent, `paid-${Date.now()}`] })); ' +
+ "const recipient = await installation.rosterWorker(ctx, input.to);",
+ },
+ ],
+ does: "a send takes its place in the chain before the recipient is checked, so a refused send spends one",
+ },
"no-wake": {
name: "no-wake",
legs: ["1"],
assertion: "1:answer-holds-codename",
- module: `${MESSAGES}/message-received-entry.ts`,
- from: String.raw`act: "wake-turn",`,
- to: 'act: "line",',
- does: "a message lands as a line in the recipient's conversation and never wakes its turn",
- },
- "drop-ended": {
- name: "drop-ended",
- legs: ["2"],
- assertion: "2:lands-in-own-conversation",
- module: `${MESSAGES}/send-message.ts`,
- from: String.raw`const fromTaskOrPost = typeof state\[TASK_ID_STATE_KEY\] === "string" \|\| typeof state\[FILING_SESSION_STATE_KEY\] === "string";`,
- to: "const fromTaskOrPost = false;",
- does: "an answer to a message sent from a task's session goes back to that session, whose turn has ended, not to the sender's own conversation",
+ patches: [{ module: ENTRY, from: String.raw`got\.act === "heard",`, to: "false," }],
+ does: "a message lands as its items in the recipient's conversation and never wakes its turn",
},
"no-hop-cap": {
name: "no-hop-cap",
legs: ["3"],
assertion: "3:ring-stops-at-6",
- module: `${MESSAGES}/send-message.ts`,
- from: String.raw`const limits = messageLimitsOf\(installation\);`,
- to: "const limits = { ...messageLimitsOf(installation), hopLimit: Number.POSITIVE_INFINITY };",
- does: "an exchange of worker messages has no hop limit (the per-turn limit stays)",
+ patches: [{ module: SEND, from: String.raw`const limits = messageLimitsOf\(installation\);`, to: "const limits = { ...messageLimitsOf(installation), hopLimit: Number.POSITIVE_INFINITY };" }],
+ does: "an exchange of worker messages has no budget (the per-request limit stays)",
},
"no-roster-check": {
name: "no-roster-check",
legs: ["4"],
assertion: "4:bobs-worker-refused",
- module: `${MESSAGES}/send-message.ts`,
- from: String.raw`const recipient = await installation\.rosterWorker\(ctx(?: as never)?, input\.to\);`,
- to: 'const recipient = (await installation.rosterWorker(ctx, input.to)) ?? { id: input.to, flow: "agent", standard: false, description: null, delegates: [] };',
+ patches: [
+ {
+ module: SEND,
+ from: String.raw`const recipient = await installation\.rosterWorker\(ctx(?: as never)?, input\.to\);`,
+ to: 'const recipient = (await installation.rosterWorker(ctx, input.to)) ?? { id: input.to, flow: "agent", standard: false, description: null, delegates: [] };',
+ },
+ ],
does: "a worker that isn't on the sender's user's roster is taken as one of theirs on `agent`",
},
"fresh-hop-on-task": {
name: "fresh-hop-on-task",
legs: ["3b"],
assertion: "3b:counts-on",
- module: "packages/workforce/src/conversation-board/board.ts",
- from: String.raw`\.\.\.carriedHopState\(ctx\.session\.state\),`,
- to: "workforceMessageHop: 0,",
- does: "a task's session starts a fresh exchange at 0, not in the exchange of the turn that filed it",
+ patches: [
+ {
+ module: "packages/workforce/src/conversation-board/task-entry.ts",
+ from: String.raw`if \(mark !== undefined\) await startTurnAtHop\(ctx(?: as never)?, mark\.hop, mark\.chain\);`,
+ to: "if (mark !== undefined) await startTurnAtHop(ctx, 0, null);",
+ },
+ ],
+ does: "a task's turn starts a fresh exchange at 0, not at the count its filing recorded",
},
"memory-log": {
name: "memory-log",
legs: ["1", "5"],
assertion: "5:lists-every-message",
- module: `${MESSAGES}/message-log.ts`,
- from: String.raw`export function messageLogOf\(ctx[^)]*\)[^{]*\{`,
- to:
- "const __memoryLog = new Map(); " +
- "const __memoryRef = (id) => ({ get state() { return __memoryLog.get(id); }, patchState: async (patch) => { __memoryLog.set(id, { ...__memoryLog.get(id), ...patch }); } }); " +
- "export function messageLogOf(ctx) { return { getOptional: async (id) => (__memoryLog.has(id) ? __memoryRef(id) : undefined), getOrCreate: async (id, initial) => { if (!__memoryLog.has(id)) __memoryLog.set(id, initial); return __memoryRef(id); } }; } " +
- "function __storedMessageLogOf(ctx) {",
+ patches: [
+ {
+ module: `${MESSAGES}/message-log.ts`,
+ from: String.raw`export function messageLogOf\(ctx[^)]*\)[^{]*\{`,
+ to:
+ "const __memoryLog = new Map(); " +
+ "const __memoryRef = (id) => ({ get state() { return __memoryLog.get(id); }, patchState: async (patch) => { __memoryLog.set(id, { ...__memoryLog.get(id), ...patch }); } }); " +
+ "export function messageLogOf(ctx) { return { getOptional: async (id) => (__memoryLog.has(id) ? __memoryRef(id) : undefined), getOrCreate: async (id, initial) => { if (!__memoryLog.has(id)) __memoryLog.set(id, initial); return __memoryRef(id); } }; } " +
+ "function __storedMessageLogOf(ctx) {",
+ },
+ ],
does: "the message log is kept in the server's memory, not in the store",
},
};
diff --git a/goals/shift-manager/workers-message-each-other/hire-check.mts b/goals/shift-manager/workers-message-each-other/hire-check.mts
new file mode 100644
index 0000000000..de4ad4cda9
--- /dev/null
+++ b/goals/shift-manager/workers-message-each-other/hire-check.mts
@@ -0,0 +1,50 @@
+/**
+ * Leg 4's hire check, run in its own process so a control's patch reaches the
+ * hire it grades: `hireWorkforce` from the checkout at argv[2], given a worker
+ * flow with no `onMessageReceived` and then the same flow with one. Prints
+ * `{ deaf, heard }`, each the hire's refusal or `null`.
+ */
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import { z } from "zod";
+
+const root = process.argv[2];
+if (root === undefined) throw new Error("usage: hire-check.mts ");
+const load = async (pkg: string) => import(pathToFileURL(join(root, "packages", pkg, "src", "index.ts")).href);
+const core = await load("core");
+const workforce = await load("workforce");
+
+const door = z.object({ message: z.string() });
+
+/** One hire of a flow `deaf`, with `internal` as its internal actions: its refusal, or `null`. */
+function hire(internal: (installation: any) => Record): string | null {
+ let flows: Record = {};
+ const installation = workforce.createWorkerInstallation({ standardWorkers: [], workerFlows: () => flows as never });
+ const deaf = core.defineFlow({
+ kind: "deaf",
+ configSchema: workforce.workerConfigSchema(),
+ session: installation.session(),
+ resources: { ...installation.resources, ...workforce.workerMessagesResources },
+ actions: {
+ respond: {
+ inputSchema: door,
+ userMessage: (i: { message: string }) => i.message,
+ block: core.handler({ name: "deaf-run", inputSchema: door, execute: (i: unknown) => i }),
+ },
+ },
+ internal: { actions: internal(installation) },
+ });
+ flows = { deaf };
+ try {
+ workforce.hireWorkforce(installation);
+ return null;
+ } catch (error) {
+ return error instanceof Error ? error.message : String(error);
+ }
+}
+
+const deaf = hire(() => ({}));
+const heard = hire((installation) => ({
+ [workforce.MESSAGE_RECEIVED_ENTRY]: workforce.messageReceivedEntry({ installation, flowKind: "deaf" }),
+}));
+console.log(JSON.stringify({ deaf, heard }));
diff --git a/goals/shift-manager/workers-message-each-other/legs.mts b/goals/shift-manager/workers-message-each-other/legs.mts
index 1492345566..4927c7065d 100644
--- a/goals/shift-manager/workers-message-each-other/legs.mts
+++ b/goals/shift-manager/workers-message-each-other/legs.mts
@@ -80,6 +80,12 @@ export const RESEARCHER = "researcher";
export const HELPER_A = "helper-a";
export const HELPER_B = "helper-b";
export const HERALD = "herald";
+/** A coordinator Alice hires that hands every line on in turn (`routing: round-robin`). */
+export const RR_LEAD = "rr-lead";
+/** The client item a received message lands as. */
+const RECEIVED = "workforce:received";
+/** The DevTeam coordinators' model (the Shift Coordinator's file), for the round-robin hire. */
+const COORDINATOR_MODEL = "anthropic/claude-haiku-5-5";
/** The model a hire names: DevTeam's agent workers' own (Researcher's file), since the install sets no default. */
export const HIRE_MODEL = "openai/gpt-5.4-mini";
@@ -164,6 +170,43 @@ export async function linesIn(who: Connected, sessionId: string): Promise {
+ return (await who.routes.items(sessionId, "component"))
+ .filter((i) => (i as { component?: unknown }).component === RECEIVED)
+ .map((i) => {
+ const data = (i.data ?? {}) as Record;
+ return {
+ itemId: i.id,
+ requestId: i.requestId,
+ id: String(data.id ?? ""),
+ from: String(data.from ?? ""),
+ text: String(data.text ?? ""),
+ ...(typeof data.inReplyTo === "string" ? { inReplyTo: data.inReplyTo } : {}),
+ ...(typeof data.budget === "number" ? { budget: data.budget } : {}),
+ };
+ });
+}
+
+/** Whether a turn ran in the request a received item landed in: an assistant line or a tool call there. */
+async function turnRanFor(who: Connected, sessionId: string, item: Received): Promise {
+ if (item.requestId === undefined) return false;
+ const lines = await linesIn(who, sessionId);
+ if (lines.some((l) => l.requestId === item.requestId && l.role === "assistant")) return true;
+ return (await who.routes.items(sessionId, "tool_output")).some((i) => i.requestId === item.requestId);
+}
+
/** One person's line to a worker, and the turn it ran, read back by its request id. */
export interface Turn {
leg: string;
@@ -280,7 +323,7 @@ export interface World {
bob: Connected;
turns: Turn[];
say: (line: string) => void;
- /** The person's own conversation with each worker, at its derived address. */
+ /** The person's own conversation with each worker, at its derived address; `cos2` is a second one with the Shift Coordinator. */
conversation: Record;
words: { codename: string; codename2: string; colourA: string; w3b: string; ring: string; bobWorker: string };
}
@@ -298,30 +341,39 @@ export async function hireTeam(world: World): Promise {
id: HELPER_A,
flow: "agent",
description: "Helper A: a teammate other workers can ask quick questions.",
- instructions: `You are Helper A. Answer other workers' questions briefly and directly. Your favourite colour is ${colourA}. When you are asked to have helper-b do something, start helper-b on a task for it with createTask.`,
+ instructions: `You are Helper A. When another worker messages you a question, answer it by calling sendMessage back to that worker with inReplyTo set to its message's id, briefly and directly. Your favourite colour is ${colourA}. When you are asked to have helper-b do something, start helper-b on a task for it with createTask.`,
settings: { delegates: [HELPER_B], model: HIRE_MODEL },
});
await hire(world.alice, {
id: HELPER_B,
flow: "agent",
description: "Helper B: a teammate other workers can ask quick questions.",
- instructions: "You are Helper B. Answer other workers' questions briefly and directly, and do the tasks you are given.",
+ instructions: "You are Helper B. Answer other workers' questions briefly and directly, and do the tasks you are given. When a task tells you to send a worker a message, send it with sendMessage.",
settings: { model: HIRE_MODEL },
});
await hire(world.alice, {
id: HERALD,
flow: "agent",
description: "The herald: says hello to people.",
- instructions: "You are the herald. Do what the user asks. When the user asks you to message a worker id, call sendMessage with exactly that id even if it isn't in your list of workers, and report what the tool answered.",
+ instructions:
+ "You are the herald. Do what the user asks. When the user asks you to message a worker id, call sendMessage with exactly that id even if it isn't in your list of workers, and report what the tool answered. " +
+ "When another worker messages you, never call sendMessage to answer it: write your answer here, in plain text.",
settings: { model: HIRE_MODEL },
});
+ await hire(world.alice, {
+ id: RR_LEAD,
+ flow: "coordinator",
+ description: "A lead that hands each line to its delegates in turn.",
+ instructions: "You lead a small team. When another worker messages you, answer it briefly by sendMessage.",
+ settings: { routing: "round-robin", delegates: [HELPER_A], model: COORDINATOR_MODEL },
+ });
await hire(world.bob, { id: world.words.bobWorker, flow: "agent", description: "Bob's own assistant.", instructions: "You help Bob.", settings: { model: HIRE_MODEL } });
return failures;
}
/** Open (or find) each person's conversation with each worker, at its derived address. */
export async function openConversations(world: World): Promise {
- for (const worker of [COS, RESEARCHER, HELPER_A, HELPER_B, HERALD]) {
+ for (const worker of [COS, RESEARCHER, HELPER_A, HELPER_B, HERALD, RR_LEAD]) {
world.conversation[worker] = await world.alice.workforce.ensureWorkerSession({ worker });
}
}
@@ -349,26 +401,54 @@ export async function leg1(world: World): Promise {
if (sent.length === 0) {
r.failures.push(`1:sent — Researcher's turn sent the Shift Coordinator no message: its calls ${show(asked.calls.map((c) => ({ args: c.args, output: c.output })))}; reply: ${asked.reply.slice(0, 200)}`);
}
+ // The answer is a message the coordinator sent: its own item in Researcher's conversation, then a Researcher line holding it.
const answered = await until(async () => {
- const lines = await linesIn(alice, researcher.id);
- const from = lines.findIndex((l) => l.agentName === COS && l.text.includes(codename));
- if (from < 0) return undefined;
- const after = lines.slice(from + 1).find((l) => l.role === "assistant" && l.agentName !== COS && l.text.includes(codename) && l.requestId !== asked.requestId);
- return after === undefined ? undefined : { line: lines[from]!, after };
+ const heard = (await receivedIn(alice, researcher.id)).find((m) => m.from === COS && m.text.includes(codename));
+ if (heard === undefined) return undefined;
+ // A line the message's own turn wrote, or a later one: never the asking turn's.
+ const after = (await linesIn(alice, researcher.id)).find((l) => l.role === "assistant" && l.requestId !== asked.requestId && l.text.includes(codename));
+ return after === undefined ? undefined : { heard, after };
}, 240_000);
if (answered === undefined) {
const lines = await linesIn(alice, researcher.id);
r.failures.push(
- `1:answer-holds-codename — within 240 s no Researcher answer to the person, after the coordinator's answer, holds ${codename}; Researcher's conversation: ${show(lines.map((l) => `${l.agentName ?? l.role}: ${l.text.slice(0, 80)}`))}`,
+ `1:answer-holds-codename — within 240 s no Researcher answer to the person, after the coordinator's message, holds ${codename}; Researcher's received items: ${show(await receivedIn(alice, researcher.id))}; lines: ${show(lines.map((l) => `${l.role}: ${l.text.slice(0, 80)}`))}`,
);
} else {
- r.notes.push(`Researcher heard "${answered.line.text.slice(0, 120)}" and told the person "${answered.after.text.slice(0, 120)}"`);
+ r.notes.push(`Researcher heard "${answered.heard.text.slice(0, 120)}" and told the person "${answered.after.text.slice(0, 120)}"`);
+ }
+ // The message is its own item in the coordinator's conversation, naming its sender and id, and its turn ran.
+ const sentId = sent[0]?.output?.sent as string | undefined;
+ const inCos = (await receivedIn(alice, cos.id)).filter((m) => m.from === RESEARCHER);
+ if (inCos.length !== 1 || (sentId !== undefined && inCos[0]!.id !== sentId) || inCos[0]!.inReplyTo !== undefined) {
+ r.failures.push(`1:own-item — the coordinator's conversation holds ${inCos.length} received item(s) from Researcher, not one with id ${sentId} and no inReplyTo: ${show(inCos)}`);
+ } else if (!(await turnRanFor(alice, cos.id, inCos[0]!))) {
+ r.failures.push(`1:own-item — the coordinator's turn didn't run for Researcher's message (request ${inCos[0]!.requestId})`);
}
- const cosLines = await linesIn(alice, cos.id);
- const fromResearcher = cosLines.filter((l) => l.agentName === RESEARCHER && l.text.startsWith(`From ${RESEARCHER}: `));
- if (fromResearcher.length !== 1) r.failures.push(`1:coordinator-shows-message — the coordinator's conversation holds ${fromResearcher.length} lines from Researcher, not 1: ${show(fromResearcher.map((l) => l.text))}`);
const cosAnswers = (await callsIn(alice, cos.id)).filter((c) => c.args.to === RESEARCHER && typeof c.output?.sent === "string");
if (cosAnswers.length === 0) r.failures.push(`1:coordinator-answered — the coordinator's conversation holds no message it sent Researcher`);
+ await quiet(alice, 180_000);
+
+ // No relay: the herald answers a message in plain text, and that text reaches no one.
+ const herald = world.conversation[HERALD]!;
+ const toHerald = await talk(turns, "1", alice, RESEARCHER, researcher, `Send the herald (worker id ${HERALD}) exactly this message: "What is two plus two?" Then tell me you sent it.`);
+ if (!toHerald.calls.some((c) => c.args.to === HERALD && typeof c.output?.sent === "string")) {
+ r.failures.push(`1:no-relay — Researcher's turn sent the herald no message, so there's nothing to relay: ${toHerald.reply.slice(0, 200)}`);
+ return r;
+ }
+ const heardByHerald = await until(async () => {
+ const item = (await receivedIn(alice, herald.id)).find((m) => m.from === RESEARCHER);
+ return item !== undefined && (await turnRanFor(alice, herald.id, item)) ? item : undefined;
+ }, 180_000);
+ if (heardByHerald === undefined) r.failures.push(`1:no-relay — the herald's turn never ran for Researcher's message within 180 s`);
+ await quiet(alice, 180_000);
+ const relayed: string[] = [];
+ for (const session of await alice.routes.sessions()) {
+ for (const m of await receivedIn(alice, session.id).catch(() => [])) if (m.from === HERALD) relayed.push(`${session.id}: ${m.text.slice(0, 80)}`);
+ }
+ if (relayed.length > 0) r.failures.push(`1:no-relay — a received item from the herald reached a session though it answered in plain text: ${show(relayed)}`);
+ const heraldReply = (await linesIn(alice, herald.id)).filter((l) => l.role === "assistant" && l.requestId === heardByHerald?.requestId).at(-1);
+ r.notes.push(`the herald's plain answer: ${heraldReply?.text.slice(0, 120) ?? "none"}`);
return r;
}
@@ -382,21 +462,49 @@ export async function leg1b(world: World): Promise {
if (!told.calls.some((c) => c.args.to === RESEARCHER && typeof c.output?.sent === "string")) {
r.failures.push(`1b:sent — the coordinator's turn sent Researcher no message: ${show(told.calls.map((c) => ({ args: c.args, output: c.output })))}; reply: ${told.reply.slice(0, 200)}`);
}
- const heard = await until(async () => (await linesIn(alice, researcher.id)).find((l) => l.agentName === COS && l.text.includes(codename2)), 180_000);
- if (heard === undefined) r.failures.push(`1b:researcher-shows-message — Researcher's conversation shows no line from the coordinator holding ${codename2} within 180 s`);
+ const heard = await until(async () => (await receivedIn(alice, researcher.id)).find((m) => m.from === COS && m.text.includes(codename2)), 180_000);
+ if (heard === undefined) r.failures.push(`1b:researcher-shows-message — Researcher's conversation shows no received item from the coordinator holding ${codename2} within 180 s`);
await quiet(alice, 180_000);
const next = await talk(turns, "1b", alice, RESEARCHER, researcher, "What is the new codename? Answer with just the codename.");
if (!next.reply.includes(codename2)) r.failures.push(`1b:next-answer-holds-it — Researcher's next answer to the person doesn't hold ${codename2}: ${next.reply.slice(0, 200)}`);
+
+ // An answer lands in the session that asked: a second conversation with the coordinator, not its default one.
+ const second = await alice.flow(cos.flowKind).createSession({ state: { workerId: COS } });
+ const cos2: SessionSummary = { id: second.id, flowKind: cos.flowKind };
+ world.conversation.cos2 = cos2;
+ for (const delegate of ["eng.em", "eng.coder"]) {
+ const removed = await act(alice, cos2.flowKind, cos2.id, "removeDelegate", { worker: delegate }, 60_000);
+ if (removed.status !== "completed") r.notes.push(`cos2 removeDelegate ${delegate}: ${removed.status} ${removed.error ?? ""}`);
+ }
+ const asked = await talk(turns, "1b", alice, COS, cos2, `Send ${HELPER_A} (worker id ${HELPER_A}) a message asking what its favourite colour is. Don't do anything else.`);
+ const question = asked.calls.find((c) => c.args.to === HELPER_A && typeof c.output?.sent === "string")?.output?.sent as string | undefined;
+ if (question === undefined) {
+ r.failures.push(`1b:in-reply-to — the coordinator's turn in its second conversation sent Helper A no message: ${show(asked.calls.map((c) => c.output))} ${asked.reply.slice(0, 160)}`);
+ return r;
+ }
+ const answer = await until(async () => (await logOf(alice)).find((m) => m.from === HELPER_A && m.inReplyTo === question), 240_000);
+ const landed = await until(async () => (await receivedIn(alice, cos2.id)).find((m) => m.from === HELPER_A && m.inReplyTo === question), answer === undefined ? 1_000 : 120_000);
+ if (answer === undefined || answer.toSession !== cos2.id || landed === undefined) {
+ r.failures.push(
+ `1b:in-reply-to — Helper A's answer to ${question} ${answer === undefined ? "never came" : `went to ${answer.toSession}`}; the asking conversation is ${cos2.id} (the default is ${cos.id}); an item there naming ${question}: ${landed === undefined ? "none" : "yes"}`,
+ );
+ } else {
+ r.notes.push(`Helper A's answer ${answer.id} landed in the second conversation ${cos2.id}, naming ${question}`);
+ }
+ await quiet(alice, 180_000);
return r;
}
export async function leg2(world: World): Promise {
const r: LegResult = { failures: [], notes: [] };
const { alice, turns } = world;
- const cos = world.conversation[COS]!;
+ // Filed from the coordinator's second conversation (leg 1b opens it), so "the filing session" isn't its default one.
+ const cos2 = world.conversation.cos2 ?? world.conversation[COS]!;
+ const cosDefault = world.conversation[COS]!;
const researcher = world.conversation[RESEARCHER]!;
const { colourA } = world.words;
- const added = await act(alice, cos.flowKind, cos.id, "addDelegate", { worker: RESEARCHER }, 60_000);
+ if (world.conversation.cos2 === undefined) r.notes.push("leg 1b didn't run: filing from the coordinator's default conversation, so 2:to-filer can't tell the two apart");
+ const added = await act(alice, cos2.flowKind, cos2.id, "addDelegate", { worker: RESEARCHER }, 60_000);
if (added.status !== "completed") r.failures.push(`2:setup — adding Researcher as a delegate ${added.status}: ${added.error ?? ""}`);
const logBefore = new Set((await logOf(alice)).map((m) => m.id));
const filed = await talk(
@@ -404,11 +512,11 @@ export async function leg2(world: World): Promise {
"2",
alice,
COS,
- cos,
- `File a task for ${RESEARCHER} with your task tool (not a post, and don't do it yourself). The task: "Ask ${HELPER_A} (a worker) for its favourite colour, by sending it a message. Then you're done."`,
+ cos2,
+ `File a task for ${RESEARCHER} with your task tool (not a post, and don't do it yourself). The task: "Ask ${HELPER_A} (a worker) for its favourite colour, by sending it a message. Then send ${COS} a message saying you asked. Then you're done."`,
);
const rows = await until(async () => {
- const board = await boardOf(alice, cos.flowKind, cos.id);
+ const board = await boardOf(alice, cos2.flowKind, cos2.id);
return board.some((row) => row.assignee === RESEARCHER) ? board : undefined;
}, 120_000);
if (rows === undefined) {
@@ -421,32 +529,37 @@ export async function leg2(world: World): Promise {
return r;
}
if (ask.fromSession === researcher.id) r.failures.push(`2:from-task — the message to Helper A was sent from Researcher's own conversation, not the task's session`);
+ // To its filer: the task's message to the coordinator lands in the conversation that filed it.
+ const toFiler = await until(async () => (await logOf(alice)).find((m) => !logBefore.has(m.id) && m.from === RESEARCHER && m.to === COS && m.fromSession === ask.fromSession), 240_000);
+ if (toFiler === undefined) {
+ r.failures.push(`2:to-filer — the task sent the coordinator no message within 240 s`);
+ } else if (toFiler.toSession !== cos2.id) {
+ r.failures.push(`2:to-filer — the task's message to its filer went to ${toFiler.toSession}, not the filing conversation ${cos2.id} (the coordinator's default is ${cosDefault.id})`);
+ }
const answer = await until(async () => (await logOf(alice)).find((m) => m.from === HELPER_A && m.to === RESEARCHER && m.inReplyTo === ask.id), 240_000);
if (answer === undefined) {
r.failures.push(`2:answered — Helper A sent no answer to ${ask.id} within 240 s`);
return r;
}
r.notes.push(`Researcher's task asked Helper A from ${ask.fromSession}; Helper A's answer ${answer.id} went to ${answer.toSession} (status ${answer.status}, hop ${answer.hop})`);
+ // The answer lands in the task's session, after the task ended, and a turn runs there.
const landed = await until(async () => {
- const lines = await linesIn(alice, researcher.id);
- const at = lines.findIndex((l) => l.agentName === HELPER_A && l.text.startsWith(`From ${HELPER_A}: `) && l.text.toLowerCase().includes(colourA.toLowerCase()));
- return at < 0 ? undefined : { lines, at };
- }, 120_000);
- if (answer.toSession !== researcher.id || landed === undefined) {
+ const item = (await receivedIn(alice, ask.fromSession)).find((m) => m.from === HELPER_A && m.inReplyTo === ask.id);
+ return item !== undefined && (await turnRanFor(alice, ask.fromSession, item)) ? item : undefined;
+ }, 180_000);
+ if (answer.toSession !== ask.fromSession || landed === undefined) {
r.failures.push(
- `2:lands-in-own-conversation — Helper A's answer went to ${answer.toSession}, and Researcher's own conversation is ${researcher.id}; ` +
- `a line from Helper A holding ${colourA} there: ${landed === undefined ? "none" : "yes"}`,
+ `2:lands-in-task-session — Helper A's answer went to ${answer.toSession}, and the task's session is ${ask.fromSession}; ` +
+ `an item there naming ${ask.id} with a turn after it: ${landed === undefined ? "none" : "yes"}`,
);
- return r;
+ } else if (!landed.text.toLowerCase().includes(colourA.toLowerCase())) {
+ r.notes.push(`Helper A's answer doesn't hold ${colourA}: ${landed.text.slice(0, 120)}`);
}
- const woke = await until(async () => {
- const lines = await linesIn(alice, researcher.id);
- return lines.slice(landed.at + 1).find((l) => l.role === "assistant" && l.agentName !== HELPER_A);
- }, 180_000);
- if (woke === undefined) r.failures.push(`2:wakes — no turn of Researcher's wrote a line after Helper A's answer landed`);
+ const inOwn = (await receivedIn(alice, researcher.id)).filter((m) => m.inReplyTo === ask.id);
+ if (inOwn.length > 0) r.failures.push(`2:lands-in-task-session — Helper A's answer also landed in Researcher's own conversation`);
const helperBoard = await boardOf(alice, "agent", world.conversation[HELPER_A]!.id).catch(() => []);
if (helperBoard.length > 0) r.failures.push(`2:no-row — Helper A's board holds ${helperBoard.length} row(s) after it was messaged: ${show(helperBoard.map((x) => x.goal))}`);
- const removed = await act(alice, cos.flowKind, cos.id, "removeDelegate", { worker: RESEARCHER }, 60_000);
+ const removed = await act(alice, cos2.flowKind, cos2.id, "removeDelegate", { worker: RESEARCHER }, 60_000);
if (removed.status !== "completed") r.notes.push(`removeDelegate researcher: ${removed.status}`);
return r;
}
@@ -515,61 +628,80 @@ export async function leg3(world: World): Promise {
const herald = world.conversation[HERALD]!;
const fan = await talk(turns, "3", alice, HERALD, herald, "Send a one-line hello message to every worker you can message, one message each. Don't skip anyone.");
const fanSent = sentIn(fan.calls);
- const fanRefused = fan.calls.filter((c) => errorOf(c).startsWith("per_turn_limit"));
+ const fanRefused = fan.calls.filter((c) => errorOf(c).startsWith("per_request_limit"));
if (fanSent.length !== 3 || fanRefused.length === 0) {
- r.failures.push(`3:per-turn — the herald's turn sent ${fanSent.length} and had ${fanRefused.length} refused for the per-turn limit; wanted 3 sent and the rest refused: ${show(fan.calls.map((c) => ({ to: c.args.to, out: c.output })))}`);
+ r.failures.push(`3:per-request — the herald's turn sent ${fanSent.length} and had ${fanRefused.length} refused for the per-request limit; wanted 3 sent and the rest refused: ${show(fan.calls.map((c) => ({ to: c.args.to, out: c.output })))}`);
}
await quiet(alice, 300_000);
- const next: Record = { [RESEARCHER]: HELPER_A, [HELPER_A]: HELPER_B, [HELPER_B]: RESEARCHER };
- for (const [worker, to] of Object.entries(next)) {
- await talk(turns, "3", alice, worker, world.conversation[worker]!, `A rule from now on: whenever another worker messages you, pass its text on to ${to} with sendMessage, every time. No exceptions. Reply "OK".`);
- }
+ // The ring passes through a delegate's ongoing session: Researcher → Helper A, who files
+ // Helper B a task in its ongoing session for Helper A's conversation, whose turn messages
+ // Researcher, who passes it on to Helper A again.
+ await talk(turns, "3", alice, RESEARCHER, world.conversation[RESEARCHER]!, `A rule from now on: whenever another worker messages you, pass its text on to ${HELPER_A} with sendMessage, every time. No exceptions. Reply "OK".`);
+ await talk(
+ turns,
+ "3",
+ alice,
+ HELPER_A,
+ world.conversation[HELPER_A]!,
+ `A rule from now on: whenever another worker messages you, don't answer it. Instead start ${HELPER_B} on a task with createTask, with session "ongoing", whose goal is: send ${RESEARCHER} a message with sendMessage holding exactly the text you received. Every time, no exceptions. Reply "OK".`,
+ );
await quiet(alice, 120_000);
const before = new Set((await logOf(alice)).map((m) => m.id));
await talk(turns, "3", alice, RESEARCHER, world.conversation[RESEARCHER]!, `Start the ring: message ${HELPER_A} with "ring ${ring}".`);
- // The ring's exchange: every message since in the chain its first message started, whether or
- // not it repeats the ring's word (an answer relayed back down the ring counts against the 6 too).
+ // The ring's exchange: every message since in the chain its first message started.
const ringRows = async () => {
const fresh = (await logOf(alice)).filter((m) => !before.has(m.id));
const start = fresh.find((m) => m.from === RESEARCHER && m.to === HELPER_A && m.text.includes(ring));
return start?.chain === undefined ? fresh.filter((m) => m.text.includes(ring)) : fresh.filter((m) => m.chain === start.chain);
};
- // Wait until the ring is quiet, or stop it at 20.
let rows = await ringRows();
- for (const end = Date.now() + 600_000; Date.now() < end && rows.length < 20; await sleep(5_000)) {
+ for (const end = Date.now() + 900_000; Date.now() < end && rows.length < 20; await sleep(5_000)) {
if (await quiet(alice, 10_000, 3_000)) break;
rows = await ringRows();
}
- rows = await ringRows();
+ rows = (await ringRows()).sort((a, b) => a.hop - b.hop);
const sent = rows.filter((m) => m.status !== "refused");
- r.notes.push(`ring: ${rows.sort((a, b) => a.hop - b.hop).map((m) => `${m.from}>${m.to}@${m.hop}${m.text.includes(ring) ? "" : " (no ring word)"}`).join(", ")}`);
- // The limit is the whole exchange's (D2): however the ring branches, 6 messages in all.
- if (sent.length !== 6) {
- r.failures.push(`3:ring-stops-at-6 — the ring passed ${sent.length} message(s), not 6${sent.length >= 20 ? " (the run stopped it at 20)" : ""}`);
+ r.notes.push(`ring: ${rows.map((m) => `${m.from}>${m.to}@${m.hop}${m.text.includes(ring) ? "" : " (no ring word)"}`).join(", ")}`);
+ const viaOngoing = sent.filter((m) => m.from === HELPER_B && m.fromSession !== world.conversation[HELPER_B]!.id);
+ r.notes.push(`${viaOngoing.length} of the ring's messages came from Helper B's ongoing session for Helper A's conversation`);
+ if (sent.length !== 6 || viaOngoing.length === 0) {
+ r.failures.push(`3:ring-stops-at-6 — the ring passed ${sent.length} message(s), not 6${sent.length >= 20 ? " (the run stopped it at 20)" : ""}, ${viaOngoing.length} of them through Helper B's ongoing session`);
}
- // The seventh send is refused, and that worker's conversation shows it stopped.
+ // The seventh send is refused at the budget, in whichever session tried it.
let stopped: Call | undefined;
- for (const worker of [RESEARCHER, HELPER_A, HELPER_B]) {
- stopped ??= (await callsIn(alice, world.conversation[worker]!.id)).find((c) => errorOf(c).startsWith("hop_limit") && String(c.args.text ?? "").includes(ring));
+ for (const session of await alice.routes.sessions()) {
+ stopped ??= (await callsIn(alice, session.id).catch(() => [])).find((c) => errorOf(c).startsWith("budget"));
}
- if (stopped === undefined && sent.length <= 6) r.failures.push(`3:seventh-refused — no worker's conversation shows a send refused at the hop limit`);
+ if (stopped === undefined && sent.length <= 6) r.failures.push(`3:ring-stops-at-6 — no session shows a seventh send refused \`budget\``);
if (stopped !== undefined) r.notes.push(`the seventh send was refused in ${stopped.sessionId}: ${errorOf(stopped).slice(0, 160)}`);
+ // Each received item says what is left: 6 minus its place.
+ const wrong: string[] = [];
+ for (const m of sent) {
+ const item = (await receivedIn(alice, m.toSession)).find((x) => x.id === m.id);
+ if (item?.budget !== 6 - m.hop) wrong.push(`${m.id}@${m.hop}: budget ${String(item?.budget)}`);
+ }
+ if (wrong.length > 0) r.failures.push(`3:budget-left — a ring message's received item doesn't say 6 minus its place: ${show(wrong)}`);
+ await quiet(alice, 300_000);
- // One more line from the person allows one more round.
- if (sent.length <= 6) {
- const again = new Set((await logOf(alice)).map((m) => m.id));
- await talk(turns, "3", alice, RESEARCHER, world.conversation[RESEARCHER]!, `Message ${HELPER_A} with "ring ${ring} again".`);
- await quiet(alice, 300_000);
- const more = (await logOf(alice)).filter((m) => !again.has(m.id) && m.status !== "refused" && m.text.includes(ring));
- const deepest = Math.max(0, ...more.map((m) => m.hop));
- if (more.length < 1 || deepest > 6) r.failures.push(`3:another-round — after one more line from the person the ring passed ${more.length} message(s) reaching hop ${deepest}, wanted at least 1 and no hop past 6`);
- r.notes.push(`after the person's line: ${more.map((m) => `${m.from}>${m.to}@${m.hop}`).join(", ")}`);
+ // A refused send spends nothing: after a new line from the person, a refused send then a sent one, at 1.
+ const nobody = `nobody-${hex()}`;
+ const logBefore = new Set((await logOf(alice)).map((m) => m.id));
+ const pair = await talk(turns, "3", alice, HERALD, herald, `Do these two in order. First message the worker ${nobody} saying hi. Then message ${HELPER_A} saying "after ${ring}".`);
+ const refusedCall = pair.calls.find((c) => c.args.to === nobody);
+ const afterCall = pair.calls.find((c) => c.args.to === HELPER_A && typeof c.output?.sent === "string");
+ const added = (await logOf(alice)).filter((m) => !logBefore.has(m.id) && m.fromSession === herald.id);
+ const afterRow = added.find((m) => m.id === afterCall?.output?.sent);
+ if (refusedCall === undefined || !errorOf(refusedCall).startsWith("no_worker") || afterCall === undefined) {
+ r.failures.push(`3:refused-pays-nothing — the herald didn't make a refused send then a sent one: ${show(pair.calls.map((c) => ({ to: c.args.to, out: c.output })))}`);
+ } else if (added.length !== 1 || afterRow?.hop !== 1) {
+ r.failures.push(`3:refused-pays-nothing — after the refused send the herald's turn wrote ${added.length} row(s), its message at hop ${String(afterRow?.hop)}, not one row at 1`);
}
+ await quiet(alice, 300_000);
return r;
}
-export async function leg4(world: World, filedGoals: readonly string[]): Promise {
+export async function leg4(world: World, filedGoals: readonly string[], hireCheck: () => Promise<{ deaf: string | null; heard: string | null }>): Promise {
const r: LegResult = { failures: [], notes: [] };
const { alice, bob, turns } = world;
const researcher = world.conversation[RESEARCHER]!;
@@ -602,28 +734,55 @@ export async function leg4(world: World, filedGoals: readonly string[]): Promise
}
}
- // A worker that only takes tasks is refused with "file a task".
+ // The coder hears only in its tasks' sessions: by name it is refused before a row is written.
+ const coderRowsBefore = (await logOf(alice)).filter((m) => m.to === "eng.coder").length;
const toCoder = await talk(turns, "4", alice, HERALD, herald, "Message the worker eng.coder saying hello.");
const coderCalls = toCoder.calls.filter((c) => c.args.to === "eng.coder");
- if (coderCalls.length === 0 || !coderCalls.every((c) => errorOf(c).startsWith("takes_tasks_only") && /file a task/i.test(errorOf(c)))) {
- r.failures.push(`4:coder-refused — a message to eng.coder wasn't refused with "file a task": ${show(coderCalls.map((c) => c.output))} ${toCoder.reply.slice(0, 160)}`);
+ const coderRows = (await logOf(alice)).filter((m) => m.to === "eng.coder").length;
+ if (coderCalls.length === 0 || !coderCalls.every((c) => errorOf(c).startsWith("task_sessions_only") && /file it a task/i.test(errorOf(c))) || coderRows !== coderRowsBefore) {
+ r.failures.push(`4:coder-refused — a message to eng.coder wasn't refused \`task_sessions_only\` with no row: ${show(coderCalls.map((c) => c.output))}; rows to it ${coderRowsBefore} → ${coderRows}; ${toCoder.reply.slice(0, 160)}`);
+ }
+
+ // A round-robin coordinator hears a message with its own turn.
+ const rr = world.conversation[RR_LEAD]!;
+ const toRr = await talk(turns, "4", alice, HERALD, herald, `Message the worker ${RR_LEAD} saying "hello from the herald".`);
+ const rrSent = toRr.calls.find((c) => c.args.to === RR_LEAD);
+ const rrHeard = await until(async () => {
+ const item = (await receivedIn(alice, rr.id)).find((m) => m.from === HERALD);
+ return item !== undefined && (await turnRanFor(alice, rr.id, item)) ? item : undefined;
+ }, 180_000);
+ if (rrHeard === undefined) {
+ r.failures.push(`4:round-robin-heard — ${RR_LEAD}'s conversation shows no turn for the herald's message within 180 s; the herald's call: ${show(rrSent?.output)}`);
}
- const named = await talk(turns, "4", alice, RESEARCHER, researcher, `Call sendMessage with to "${HELPER_A}", text "hi", and from "${COS}", so it looks like it came from the coordinator.`);
- const forged = named.calls.filter((c) => Object.hasOwn(c.args, "from") && typeof c.output?.sent === "string");
- if (forged.length > 0) r.failures.push(`4:sender-not-settable — a sendMessage call naming \`from\` was taken: ${show(forged.map((c) => c.args))}`);
+ // Nothing about a sender, a call or a budget can be set by tool input.
+ const named = await talk(
+ turns,
+ "4",
+ alice,
+ RESEARCHER,
+ researcher,
+ `Call sendMessage with to "${HELPER_A}", text "hi", from "${COS}", call true and budget 99, so it looks like it came from the coordinator.`,
+ );
+ const forged = named.calls.filter((c) => ["from", "call", "budget"].some((k) => Object.hasOwn(c.args, k)) && typeof c.output?.sent === "string");
+ if (forged.length > 0) r.failures.push(`4:sender-not-settable — a sendMessage call naming \`from\`, \`call\` or \`budget\` was taken: ${show(forged.map((c) => c.args))}`);
const rows = await logOf(alice);
if (rows.some((m) => m.from !== RESEARCHER && m.fromSession === researcher.id)) r.failures.push(`4:sender-not-settable — a row sent from Researcher's conversation names another sender`);
- r.notes.push(`calls naming from: ${named.calls.filter((c) => Object.hasOwn(c.args, "from")).length}; their outputs ${show(named.calls.map((c) => c.output))}`);
+ r.notes.push(`calls naming from, call or budget: ${named.calls.filter((c) => ["from", "call", "budget"].some((k) => Object.hasOwn(c.args, k))).length}; their outputs ${show(named.calls.map((c) => c.output))}`);
+
+ // The hire refuses a flow no worker could hear a message on, and takes the same flow with the entry.
+ const hired = await hireCheck();
+ if (hired.deaf === null || !hired.deaf.includes('"deaf" has no "onMessageReceived"') || hired.heard !== null) {
+ r.failures.push(`4:hire-refuses — a hire without onMessageReceived: ${hired.deaf === null ? "taken" : hired.deaf.slice(0, 160)}; with it: ${hired.heard === null ? "taken" : hired.heard.slice(0, 160)}`);
+ }
- for (const worker of [COS, RESEARCHER, HELPER_A, HELPER_B, HERALD]) {
- const session = world.conversation[worker]!;
+ for (const worker of [COS, RESEARCHER, HELPER_A, HELPER_B, HERALD, "cos2"]) {
+ const session = world.conversation[worker];
+ if (session === undefined) continue;
const board = await boardOf(alice, session.flowKind, session.id).catch((e: unknown) => [{ error: messageOf(e) }] as Array>);
const stray = board.filter((row) => !filedGoals.some((goal) => String(row.goal ?? "").includes(goal)));
if (stray.length > 0) r.failures.push(`4:no-task-row — ${worker}'s board holds row(s) no leg filed: ${show(stray.map((x) => ({ assignee: x.assignee, goal: String(x.goal ?? x.error ?? "").slice(0, 120) })))}`);
}
- const listed = await act(alice, world.conversation[COS]!.flowKind, world.conversation[COS]!.id, "listDelegates", {}, 60_000);
- r.notes.push(`the coordinator conversation's delegates: ${show(listed.output)}`);
return r;
}
diff --git a/goals/shift-manager/workers-message-each-other/run.mts b/goals/shift-manager/workers-message-each-other/run.mts
index c6819fbb77..965ea27e58 100644
--- a/goals/shift-manager/workers-message-each-other/run.mts
+++ b/goals/shift-manager/workers-message-each-other/run.mts
@@ -1,16 +1,17 @@
/**
- * Goal check for FIX-1989. See goal.md.
+ * Goal check for FIX-1989, amended for FIX-2238. See goal.md.
*
* Run: pnpm tsx goals/shift-manager/workers-message-each-other/run.mts
- * Controls: GOAL_CONTROL=no-wake | drop-ended | no-hop-cap | no-roster-check | fresh-hop-on-task | memory-log
+ * Controls: GOAL_CONTROL= (controls.mts names each)
* (each runs the legs it needs, unless GOAL_LEGS says otherwise)
* Before: GOAL_COMMIT= serves that commit, from its own tree and install
* Legs: GOAL_LEGS=1,1b,2,2b,3b,3,4,5 (default: all, in that order)
*/
import { execFileSync, spawnSync } from "node:child_process";
-import { existsSync, mkdirSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
import { pathToFileURL } from "node:url";
import { REPO_ROOT, RUN_STAMP, goalTmpDir, keysServing, runGoal } from "../../lib/index.mts";
import { assertPatched, describePatches, modulePatchEnv } from "../../lib/module-patch.mts";
@@ -79,6 +80,34 @@ function checkoutFor(commit: string | undefined): { root: string; commit: string
return { root, commit: sha, describe: `\`${sha.slice(0, 9)}\` (GOAL_COMMIT=${commit}), its own tree and install` };
}
+/** The names FIX-2238 removed, as Workforce wrote them. `replyTo` only where the message field lived. */
+const REMOVED = /\b(onWorkerMessage|messageWorker|MESSAGE_WORKER_TOOL|WORKER_MESSAGE_ENTRY|workerMessageEntry|workforceRelayTo|takes_tasks_only|no_turn|takesWorkerMessages|sendWorkerMessage|answerTo)\b/;
+const REMOVED_FIELD = /\breplyTo\b/;
+
+/** `sweep`: no package's source names a removed name. */
+function sweep(root: string): string[] {
+ const hits: string[] = [];
+ const walk = (dir: string, field: boolean) => {
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) walk(path, field);
+ else if (/\.(ts|tsx|mts)$/.test(name)) {
+ readFileSync(path, "utf8")
+ .split("\n")
+ .forEach((line, i) => {
+ if (REMOVED.test(line) || (field && REMOVED_FIELD.test(line))) hits.push(`${path.slice(root.length + 1)}:${i + 1}: ${line.trim().slice(0, 120)}`);
+ });
+ }
+ }
+ };
+ const packages = join(root, "packages");
+ for (const pkg of readdirSync(packages)) {
+ const src = join(packages, pkg, "src");
+ if (existsSync(src)) walk(src, pkg === "workforce" || pkg === "shift-manager");
+ }
+ return hits.length === 0 ? [] : [`sweep — removed names are still in package source: ${hits.slice(0, 8).join(" | ")}`];
+}
+
/** Leg 5: after a restart, the Messages view lists every message the legs sent, and each side opens its session. */
async function leg5(origin: string, alice: Person, sent: Map }>): Promise {
const r: LegResult = { failures: [], notes: [] };
@@ -111,8 +140,8 @@ async function leg5(origin: string, alice: Person, sent: Map document.querySelectorAll("[data-testid=session-item]").length > 0, undefined, { timeout: 20_000 });
- const holds = await opened.textContent();
- if (!holds?.includes(`From ${RESEARCHER}:`)) r.failures.push(`5:opens-side — the coordinator's session the link opened doesn't show the line from Researcher`);
+ const shown = await page.locator(`[data-testid=received-message][data-from="${RESEARCHER}"]`).count();
+ if (shown === 0) r.failures.push(`5:opens-side — the coordinator's session the link opened doesn't show Researcher's message as its own item`);
await page.goBack();
await page.getByTestId("messages").waitFor();
await page.locator(`[data-testid=message][data-message-id="${first[0]}"]`).getByTestId("message-from").click();
@@ -134,9 +163,9 @@ await runGoal(async () => {
mkdirSync(SCRATCH, { recursive: true });
const mark = join(SCRATCH, `patch-mark-${RUN_STAMP}`);
rmSync(mark, { force: true });
- const env = control === undefined ? {} : modulePatchEnv([control], checkout.root, mark);
+ const env = control === undefined ? {} : modulePatchEnv(control.patches, checkout.root, mark);
say(`serving ${checkout.describe}; legs ${[...legs].join(", ")}${control === undefined ? "" : `; control ${control.name}`}`);
- if (control !== undefined) say(`control ${control.name}: ${control.does}\n${describePatches([control], checkout.root)}`);
+ if (control !== undefined) say(`control ${control.name}: ${control.does}\n${describePatches(control.patches, checkout.root)}`);
const profile = join(checkout.root, "packages", "shift-manager", "teams", "devteam");
for (const model of ["openai/gpt-5.4-mini", "anthropic/claude-haiku-5-5"]) {
@@ -208,8 +237,26 @@ await runGoal(async () => {
filedGoals.push(world.words.w3b);
return leg3b(world);
});
- await runLeg("3", () => leg3(world));
- await runLeg("4", () => leg4(world, filedGoals));
+ await runLeg("3", async () => {
+ filedGoals.push(world.words.ring);
+ return leg3(world);
+ });
+ // The hire check runs in its own process, under the control's patches.
+ const hireCheck = async () => {
+ const ran = spawnSync(join(checkout.root, "node_modules", ".bin", "tsx"), [join(dirname(fileURLToPath(import.meta.url)), "hire-check.mts"), checkout.root], {
+ cwd: checkout.root,
+ encoding: "utf8",
+ env: { ...process.env, ...env },
+ timeout: 120_000,
+ });
+ const last = ran.stdout.trim().split("\n").at(-1) ?? "";
+ try {
+ return JSON.parse(last) as { deaf: string | null; heard: string | null };
+ } catch {
+ throw new Error(`the hire check printed no verdict: ${(ran.stdout + ran.stderr).slice(-800)}`);
+ }
+ };
+ await runLeg("4", () => leg4(world, filedGoals, hireCheck));
for (const t of world.turns) {
say(`turn (${t.leg}) ${t.worker} ${t.status}: calls ${t.calls.map((c) => `${String(c.args.to)}→${c.output?.sent ?? String(c.output?.error ?? "").slice(0, 40)}`).join(", ") || "none"}; reply: ${t.reply.slice(0, 200).replace(/\n/g, " ")}`);
}
@@ -233,11 +280,11 @@ await runGoal(async () => {
else say(`store kept at ${store}`);
if (control !== undefined) {
- assertPatched([control], checkout.root, mark);
- say(`control ${control.name}: the patch reached ${control.module}`);
+ assertPatched(control.patches, checkout.root, mark);
+ say(`control ${control.name}: the patch reached ${control.patches.map((p) => p.module).join(", ")}`);
}
- const failures: string[] = [];
+ const failures: string[] = sweep(checkout.root);
for (const l of ORDER) {
const r = results[l];
if (r === undefined) continue;
diff --git a/packages/shift-manager/README.md b/packages/shift-manager/README.md
index f666a072d2..b7dd986b1f 100644
--- a/packages/shift-manager/README.md
+++ b/packages/shift-manager/README.md
@@ -229,6 +229,7 @@ A Lab with no Shift Coordinator needs nothing in its config. Every screen works,
- **A project.** Your project coordinator, the project's workstreams and their progress, your own workstreams' boards, and its brief. See [A project](#a-project).
- **A workstream.** On a project, your own workstream opens on its lead's conversation, and someone else's on its details and latest report. Its board has five columns: QUEUED, RUNNING, IN REVIEW, NEEDS YOU, DONE; a done task is one line, its id and title.
- **A task.** One task's run, live, with Interrupt. See [A task](#a-task).
+- **Messages.** Every [message](../workforce/README.md#worker-messages) one of your workers sent another, newest first, with a message and its answers kept together. The sender and the recipient are links to the conversation that holds the message on each side. A message that wasn't delivered, or whose delivery couldn't be confirmed, says so.
- **Usage** (`/usage`). How much of each coding agent's subscription you have used: one card per agent, with each limit window's percent and reset time, the plan, and where the numbers came from and how old they are. Opening Usage asks for a fresh reading; the Lab asks each agent at most once a minute. A window whose reset has passed shows "reset at …, not checked since" instead of a percent. An agent with no number (an API key, nobody signed in, a read that failed) says why, with no percent. A window at its limit says "limit reached", and one the agent sent no percent for says how close it is instead: "under Claude Code's warning line" or "near its limit". A window a coding run reported says "from a run, 3 min ago". Usage reads the `harnessUsage` query on whichever of the Lab's flows declares it (see [`harnessUsageAction`](../harness-manager/README.md#subscription-usage)); a Lab with none shows "No usage to show". A Lab opened with `openLab({ usage: { codex: reader } })` puts the query on its projects flow with those readers. The [`devteam`](#the-devteam-profile) profile registers `readCodexUsage` from `@flow-state-dev/codex`, which works only on your own machine, and `readClaudeUsage` from `@flow-state-dev/claude-code/sdk` as the `claude-code` reader, so its Claude Code card names the plan and fills in windows as runs report them.
- **Settings** (`/settings`). Your keys for the Lab's MCP servers: each server the Lab offers, *set* with when, or *not set*, a field to set or replace your key, and Clear. The page never shows a key back. A Lab opened with `openLab({ mcpServers })` serves the route the page writes through, `/api/flows/mcp-credentials`, which takes the caller from the Lab's own principal resolver; a Lab with none says it offers no servers.
@@ -236,6 +237,8 @@ A Lab with no Shift Coordinator needs nothing in its config. Every screen works,
A line in a task's session, while the task runs, is a message to that task: the worker takes it at its next step, in the same session, and a coding run resumes its coding session with it. 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 Shift Coordinator 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. Once a task has finished, a line in its session is a question about the work: on a built-in `agent` worker or a DevTeam coder the worker answers from that session, and the task, its output included, doesn't change. To change the work, file a follow-up.
+**Messages between workers.** In a conversation, a message the worker sent another worker shows as its own line, *To <worker>: <text>*, with a *Messages ›* link; a refused one says it wasn't sent, and why. A message the worker received shows as its own item, drawn from the `workforce:received` component item: the sender's name, the time it arrived, *answering your message* when it answers one the worker sent, a *Messages ›* link, and the text. In the `devteam` profile, the coder hears messages only in its tasks' sessions, so a message to it by name is refused; file it a task instead.
+
To make your own worker flow take messages, give it one public action that declares `userMessage` and takes `{ message }`. Shift Manager sends lines there, using the `door` on the worker's inventory row.
Each section loads on its own. If one read fails, that section says what the Lab answered and offers Retry, and the rest of the screen still draws.
diff --git a/packages/workforce/README.md b/packages/workforce/README.md
index d3f3af41f1..306156de1b 100644
--- a/packages/workforce/README.md
+++ b/packages/workforce/README.md
@@ -461,7 +461,15 @@ map `resourcesFromDocs` returned, and declare `installation.documents` and the i
```ts
import { defineFlow } from "@flow-state-dev/core";
-import { createWorkerInstallation, resourcesFromDocs, workerConfigSchema, workerFlow } from "@flow-state-dev/workforce";
+import {
+ createWorkerInstallation,
+ MESSAGE_RECEIVED_ENTRY,
+ messageReceivedEntry,
+ resourcesFromDocs,
+ workerConfigSchema,
+ workerFlow,
+ workerMessagesResources,
+} from "@flow-state-dev/workforce";
import { readResourcesDirectory } from "@flow-state-dev/workforce/loader";
import { inputSchema, loadWorker, runTurn } from "./blocks";
import { boardResource } from "./resources";
@@ -473,10 +481,13 @@ const customAgentFlow = workerFlow((installation) =>
kind: "custom-agent",
configSchema: workerConfigSchema(),
session: installation.session(),
- resources: { board: boardResource, ...installation.resources, ...installation.documents },
+ resources: { board: boardResource, ...installation.resources, ...installation.documents, ...workerMessagesResources },
resourceVisibility: installation.resourceVisibility,
request: { onStarted: loadWorker(installation) }, // installation.resolveWorker(ctx, "custom-agent")
actions: { respond: { inputSchema, block: runTurn, userMessage: (input) => input.message } },
+ internal: {
+ actions: { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind: "custom-agent" }) },
+ },
}),
);
@@ -540,17 +551,26 @@ the same value in the bag.
Add your flow's own settings on top, at the same level:
```ts
-import { workerConfigSchema, workerFlow } from "@flow-state-dev/workforce";
+import {
+ MESSAGE_RECEIVED_ENTRY,
+ messageReceivedEntry,
+ workerConfigSchema,
+ workerFlow,
+ workerMessagesResources,
+} 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 },
+ resources: { ...installation.resources, ...workerMessagesResources },
actions: {
respond: { inputSchema: z.object({ message: z.string() }), block: triageWork(installation), userMessage: (input) => input.message },
},
+ internal: {
+ actions: { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind: "request-triage" }) },
+ },
}),
);
```
@@ -580,6 +600,11 @@ knowing its flow; a flow with none, with a second, or with its message action un
refuses, the last naming the action to rename. 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.
+`hireWorkforce` also requires every worker flow to carry an internal `onMessageReceived` entry built
+by `messageReceivedEntry`, so any worker can be [messaged](#worker-messages); a flow without one, or
+with a hand-built entry under that name, is refused, naming the flow. `defineSessionBoard`'s `entries(turn)`
+includes it.
+
Each declared role's entries must be there, in their section, carrying their factory's mark, and
take the input their caller sends:
@@ -1138,10 +1163,13 @@ import { defineFlow } from "@flow-state-dev/core";
import {
createWorkerInstallation,
hireWorkforce,
+ MESSAGE_RECEIVED_ENTRY,
+ messageReceivedEntry,
referencesFromDocs,
resourcesFromDocs,
workerConfigSchema,
workerFlow,
+ workerMessagesResources,
} from "@flow-state-dev/workforce";
import { readReferencesDirectory, readResourcesDirectory } from "@flow-state-dev/workforce/loader";
import { answerQuestion } from "./blocks";
@@ -1158,9 +1186,12 @@ const supportFlow = workerFlow((installation) =>
kind: "support",
configSchema: workerConfigSchema(),
session: installation.session(),
- resources: { ticket: ticketResource, ...installation.resources, ...installation.documents },
+ resources: { ticket: ticketResource, ...installation.resources, ...installation.documents, ...workerMessagesResources },
resourceVisibility: installation.resourceVisibility,
actions: { answer: { inputSchema, block: answerQuestion(installation), userMessage: (input) => input.message } },
+ internal: {
+ actions: { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind: "support" }) },
+ },
}),
);
@@ -1737,7 +1768,14 @@ process sees it on the next turn.
```ts
import { defineFlow } from "@flow-state-dev/core";
-import { createWorkerInstallation, hireWorkforce, workerConfigSchema } from "@flow-state-dev/workforce";
+import {
+ createWorkerInstallation,
+ hireWorkforce,
+ MESSAGE_RECEIVED_ENTRY,
+ messageReceivedEntry,
+ workerConfigSchema,
+ workerMessagesResources,
+} from "@flow-state-dev/workforce";
const installation = createWorkerInstallation({
standardWorkers: roster, // readWorkforce(...)'s workers
@@ -1748,8 +1786,9 @@ const researchFlow = defineFlow({
kind: "research",
configSchema: workerConfigSchema(),
session: installation.session(), // a readonly `workerId`, and the create check
- resources: { ...installation.resources }, // the user's workers, and the standard ones
+ resources: { ...installation.resources, ...workerMessagesResources }, // the user's workers, the standard ones, the message log
actions: { respond: { inputSchema, block: door, userMessage: (i) => i.message } },
+ internal: { actions: { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind: "research" }) } },
});
// inside the door's block, which also declares `installation.resources`:
@@ -1885,7 +1924,10 @@ does once its `work` entry is built with `workerTaskEntry`. The site's
import {
createWorkerInstallation,
defineCoordinatorFlow,
+ MESSAGE_RECEIVED_ENTRY,
+ messageReceivedEntry,
workerConfigSchema,
+ workerMessagesResources,
workerTaskEntry,
} from "@flow-state-dev/workforce";
@@ -1893,9 +1935,10 @@ const researchFlow = defineFlow({
kind: "research",
configSchema: workerConfigSchema(),
session: installation.session(),
- resources: { ...installation.resources },
+ resources: { ...installation.resources, ...workerMessagesResources },
actions: { respond: { inputSchema, block: door, userMessage: (i) => i.message } },
task: { actions: { work: workerTaskEntry({ name: "research-task", turn: door }) } }, // takes tasks, routed ones included
+ internal: { actions: { [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind: "research" }) } },
});
const coordinatorFlow = defineCoordinatorFlow({
@@ -2191,11 +2234,11 @@ flow-isolated key (`{ id: flowId, isolateUserState: true }`) finds nothing. Type
## Worker messages
-A worker with a conversation can send any other worker on its user's roster a short message: a
-question, an FYI, a heads-up. Workers on the built-in `agent` flow and coordinators that route
-by `judgment` or `best-fit` get the `sendMessage` tool on every turn. On a flow built with
-`defineSessionBoard`, add the kit's `messages` to the model block's `uses`. The tool's
-description lists the workers this one can message now.
+A worker can send any other worker on its user's roster a short message: a question, an FYI, a
+heads-up. Workers on the built-in `agent` flow and the coordinator flow get the `sendMessage` tool
+on every turn. On a flow built with `defineSessionBoard`, add the kit's `messages` to the model
+block's `uses`. The tool's description lists the workers the send would take, by id and
+description, leaving out the sender and any worker that hears only in its tasks' sessions.
```json
{ "to": "chief-of-staff", "text": "What's the codename for the spring launch?" }
@@ -2204,39 +2247,76 @@ description lists the workers this one can message now.
- **Sending.** The input is `{ to, text, inReplyTo? }` and nothing else; `text` holds up to 8,000
characters. A sent message answers `{ sent: "msg_…" }`, plus `unconfirmed` (a reason) when its
delivery couldn't be confirmed and may still arrive. A refused one answers
- `{ ok: false, error }`, the error starting with a code: `no_worker` (also for another user's
- worker), `not_yourself`, `worker_unavailable`, `takes_tasks_only` (a worker that only takes
- tasks, such as a coding run: file a task instead), `no_turn` (a coordinator that routes by
- `round-robin` or `everyone`), `no_such_message`, `hop_limit`, `per_turn_limit`,
- `empty_message`, `message_too_long` or `not_delivered`.
-- **Receiving.** The message lands in the recipient's own conversation with the user, the session
- `ensureWorkerSession({ worker })` returns (started when absent), as a `From : `
- line whose `agentName` is the sender. The recipient always takes a turn on it, after any turn it
- is in the middle of.
-- **Answering.** The recipient answers with `sendMessage`, `to` the sender and `inReplyTo` the
- message's id. The answer lands in the session the message was sent from and wakes the sender
- there; a message sent from a task session is answered in the sender's own conversation instead.
- A turn woken by a message (not an answer) that ends without messaging the sender has its final
- text sent to the sender as the answer, as if with `inReplyTo` (cut to 8,000 characters). That
- answer counts toward both limits; when one refuses it, nothing is sent or logged. A turn that
- ends with no text sends nothing, and a turn woken by an answer never sends its text back.
- Nothing waits on an answer.
-- **Limits.** Everything descending from one user's line is one chain: its messages, the turns
- they wake and the tasks filed along the way, parallel branches included. A chain stops after
- `hopLimit` (6) messages in total; a user's line starts a new chain. One turn sends at most
- `perTurn` (3). Set both with `hireWorkforce(installation, { messages: { hopLimit, perTurn } })`;
- each must be a whole number of at least 1, or `hireWorkforce` throws.
+ `{ ok: false, error }`, nothing sent, the error starting with a code: `not_a_worker` (the session
+ runs no worker), `empty_message`, `message_too_long`, `not_yourself`, `no_worker` (also for
+ another user's worker), `worker_unavailable` (the roster row has a problem), `task_sessions_only`
+ (file it a task instead), `no_such_message` (`inReplyTo` names no message the `to` worker sent
+ you), `budget`, `per_request_limit` or `not_delivered` (the host refused the dispatch).
+- **Receiving.** A message arrives on the recipient flow's internal `onMessageReceived` entry
+ (`MESSAGE_RECEIVED_ENTRY`). The session it lands in gets two items: a `From : `
+ line under the sender's name that the model reads in history and the client never receives, and
+ a client-only component item `workforce:received` (`RECEIVED_MESSAGE_COMPONENT`) with `data`
+ `{ id, from, text, inReplyTo?, budget }`, for an app to draw. Then the flow's turn, if it gave one, runs
+ with a `MessageReceived` (`{ id, from, text, call, inReplyTo?, budget }`; `call` is always
+ `false`). A copy delivered twice wakes the recipient once; a recipient mid-turn hears it after
+ that turn. Coordinators hear messages whatever their routing, in their own turn.
+- **Where it lands.** An answer lands in the session the original was sent from, even a task's
+ session whose task has finished. A message to the worker that filed the sender's current task
+ (or delegate session) lands in the conversation that filed it. A message to the project
+ coordinator from work in a project lands in that project's conversation. Anything else lands in
+ the recipient's own conversation with the user, the session `ensureWorkerSession({ worker })`
+ returns, opened when absent.
+- **Answering.** Nothing is sent back automatically. The recipient answers with `sendMessage`, `to`
+ the sender and `inReplyTo` the message's id. A turn that ends in plain text answers no one, and
+ not answering is a valid answer. Nothing waits on an answer.
+- **Hearing only in task sessions.** A worker flow whose entry is built with
+ `hears: "task-sessions"` hears messages only in its tasks' sessions. A message to one of its
+ workers by name is refused with `task_sessions_only`, and nothing is sent.
+- **Budget.** Each line the user types starts a budget of `hopLimit` (6) messages for everything
+ descending from it, across every worker, plus at most `perTurn` (3) sent from any one request. A
+ fresh budget also starts for a task filed held, when it is released, and for a request with
+ nothing behind it. A task a woken worker files, and a delegate's ongoing session, draw on the
+ filer's budget. Filing a task spends nothing; a refused send spends nothing. A woken turn's
+ `budget` (and the session kit's prompt) says how many more messages the exchange can send. Set
+ both with `hireWorkforce(installation, { messages: { hopLimit, perTurn } })`; each must be a
+ whole number of at least 1, or `hireWorkforce` throws.
- **The log.** Every message is a row in the user's `workforce/messages/*` collection
(`WORKER_MESSAGES_RESOURCE`, rows parsed by `workerMessageRowSchema`), readable from the browser
- through the user's roster session or any session on a flow that carries the session board:
- `id`, `from`, `to`, `text`, `exchange`, `inReplyTo`, `fromSession`, `toSession`, `chain` (the
- chain's id; optional), `hop` (the message's place in the chain, from 1), `status`
- (`delivered`, `refused` or `unconfirmed`), `reason` and `at`. Another user's rows are never
- returned.
+ through the user's roster session or any session on a flow that declares
+ `workerMessagesResources`: `id`, `from`, `to`, `text`, `exchange`, `inReplyTo`, `fromSession`,
+ `fromFlow`, `toSession`, `toFlow`, `chain` (optional), `hop` (from 1), `status` (`delivered`,
+ `refused` or `unconfirmed`), `reason` and `at`. Another user's rows are never returned.
A message is not a task: it files no row, owes no result, and doesn't count toward `taskChainLimit`.
-On a flow of your own, add the kit's `messages` to the model block's `uses`, beside `tools`, to let
-its workers send; `entries(turn)` already lets them receive. See
+
+Every worker flow must carry an `onMessageReceived` built by `messageReceivedEntry`:
+`hireWorkforce` refuses one that doesn't, naming the flow, and refuses a hand-built entry under
+that name too. The session kit's `entries(turn)` includes it, with the turn wrapped by
+`promptedMessageTurn`. A flow without the kit mounts it itself and adds the log to its resources:
+
+```ts
+import {
+ MESSAGE_RECEIVED_ENTRY,
+ messageReceivedEntry,
+ promptedMessageTurn,
+ workerMessagesResources,
+} from "@flow-state-dev/workforce";
+
+defineFlow({
+ kind: "triage",
+ // ...
+ resources: { ...installation.resources, ...workerMessagesResources },
+ internal: {
+ actions: {
+ [MESSAGE_RECEIVED_ENTRY]: messageReceivedEntry({ installation, flowKind: "triage", turn: promptedMessageTurn(answer) }),
+ },
+ },
+});
+```
+
+`turn` is optional (left out, a message lands as its two items and nothing runs).
+`promptedMessageTurn(turn)` adapts a block that takes `{ message }`, handing it
+`receivedMessagePrompt(received)`: who wrote, the text, how to answer, and the budget left. See
[Messaging other workers](https://flow-state.dev/docs/workforce/messaging-workers).
## Error Reporter
@@ -2282,7 +2362,8 @@ coordinator's own turn's answer name, which its messages carry as `agentName`) a
`sessionIdOfFiling` (the conversation a board row was filed in), `RULE_TOOLS`, `MAX_RULES`,
`MAX_RULE_CHARS`, `STANDING_RULES_ACTION`, `STANDING_RULES_LINE`, `SET_WORK_PROJECT_ACTION`,
`WORK_PROJECT_STATE_KEY`, `SEND_MESSAGE_TOOL` (the
-tool a sent message is a call to), `MESSAGE_RECEIVED_ENTRY`, `WORKER_MESSAGES_PATTERN`,
+tool a sent message is a call to), `MESSAGE_RECEIVED_ENTRY`, `RECEIVED_MESSAGE_COMPONENT` (the
+component a received message is drawn by), `WORKER_MESSAGES_PATTERN`,
`WORKER_MESSAGES_RESOURCE` and `workerMessageRowSchema`, the same values the root exports, and reaches no Node built-in.
## Exports
@@ -2301,7 +2382,7 @@ tool a sent message is a call to), `MESSAGE_RECEIVED_ENTRY`, `WORKER_MESSAGES_PA
| `installation.rosterWorker(ctx, id)` / `installation.standardWorkerProblems()` | The worker an id names on the session user's roster, read by id (`undefined` for another user's, as for a missing one); and every standard worker's configuration problems, for a load-time refusal. |
| `installation.roster(ctx)` | The session user's whole roster, as it stands when called: their own workers and every standard worker, sorted by id, each a `RosterWorker` (whose `delegates` lists the worker ids its configuration names; empty when none). The block must declare `installation.resources`. |
| `defineCoordinatorFlow({ installation, routeModel, agent?, roundDeadlineMs? })` | The `coordinator` worker flow (see [Coordinators](#coordinators)): `respond`, `addDelegate`, `removeDelegate`, `setFallback` and `listDelegates`. Its judgment is the agent's turn, built with the `agent` options; `agent.isolateUserState` keys this flow's user-scoped storage by its copy, as it does `agent`'s. `roundDeadlineMs` is how long a round waits for its answers (five minutes by default); a value that isn't a positive whole number of milliseconds throws. |
-| `defineSessionBoard({ installation, flowKind })` | The task-filing kit for a worker flow of your own (see [Delegating work](https://flow-state.dev/docs/workforce/delegating-work)): `tools` for the model block's `uses` (Orchestration's task tools, present only while the session has a delegate that takes tasks), `progress` for the same `uses` (`reportProgress` on a turn working a task), `delegateTools` for the same `uses` (`listDelegates`, plus `addDelegate`, `removeDelegate` and `setFallback` on a worker set to `editsOwnDelegates: true`), `actions` (the task tools as `_tasks`, plus `addDelegate`, `removeDelegate`, `setFallback` and `listDelegates`), `resources`, `sessionStateShape` for `installation.session(...)`, `serverOwned` for `session.serverOwned`, `messages` for the same `uses` (the `sendMessage` tool; see [Worker messages](#worker-messages)), `entries(turn)` for `internal: { actions }`, which carries `onTaskSettled` (where each ending of a task the session filed arrives, once) and also delivers worker messages, `planned(turn)` to wrap a turn so the steps its worker files for itself run in its request (use the wrapped turn for `run`, the task entry and `entries`), and `files(ctx)` / `taskDelegates(ctx)` to read whether the session files and who takes its tasks. |
+| `defineSessionBoard({ installation, flowKind })` | The task-filing kit for a worker flow of your own (see [Delegating work](https://flow-state.dev/docs/workforce/delegating-work)): `tools` for the model block's `uses` (Orchestration's task tools, present only while the session has a delegate that takes tasks), `progress` for the same `uses` (`reportProgress` on a turn working a task), `delegateTools` for the same `uses` (`listDelegates`, plus `addDelegate`, `removeDelegate` and `setFallback` on a worker set to `editsOwnDelegates: true`), `actions` (the task tools as `_tasks`, plus `addDelegate`, `removeDelegate`, `setFallback` and `listDelegates`), `resources`, `sessionStateShape` for `installation.session(...)`, `serverOwned` for `session.serverOwned`, `messages` for the same `uses` (the `sendMessage` tool; see [Worker messages](#worker-messages)), `entries(turn)` for `internal: { actions }`, which carries `onTaskSettled` (where each ending of a task the session filed arrives, once) and `onMessageReceived` (where a worker message arrives), `planned(turn)` to wrap a turn so the steps its worker files for itself run in its request (use the wrapped turn for `run`, the task entry and `entries`), and `files(ctx)` / `taskDelegates(ctx)` to read whether the session files and who takes its tasks. |
| `coordinatorConfigSchema()`, `coordinatorRouteRecordSchema`, `COORDINATOR_FLOW`, `COORDINATOR_ROUTE` | A coordinator's configuration, its routing record, the flow's kind and the record's component name. |
| `workerFlow(build, { standardOnly?, roles? })` | A worker flow built on its installation, for a flow in its own file: the installation calls `build(installation)` once. `roles` declares what it does beside taking a message (`contributor`, `manager`), checked at hire. Goes in `workerFlows`, and is what `fsdev gen`'s `workerFlows` holds. |
| `WORKER_ROLES` / `WorkerRole` | The roles a worker flow may declare: `contributor`, `manager`, `coordinator`. |
@@ -2331,7 +2412,10 @@ tool a sent message is a call to), `MESSAGE_RECEIVED_ENTRY`, `WORKER_MESSAGES_PA
| `discoverWorkforceCode(root)` | Walk `flows/workers/` and `blocks/` one level deep, every `resources/` folder the convention reads, every `blocks/` folder inside the team tree, and every package's `blocks/` folder, returning what they hold on `files`, `resourceModules`, `workerBlocks` and `packageBlocks` — each ordered by path — plus the `searched` patterns. Reads the tree only — it opens none of the modules it finds. Throws a `WorkforceCodeError` carrying every refusal. Ships from the `./codegen` subpath (Node only). |
| `renderWorkforceCode(files, modules, workerBlocks?, packageBlocks?)` | Render a discovery's `files`, `resourceModules`, `workerBlocks` and `packageBlocks` as a module of static imports exporting `workerFlows`, `blocks`, `resourceModules`, `workerBlocks` 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(installation, { taskChainLimit?, messages? })` | The flows to register for an installation: one copy of each worker flow, under its name, 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. `taskChainLimit` is the most tasks one top task may have under it, at any depth (100 when omitted); a value that isn't a whole number of at least 1 throws. `messages: { hopLimit?, perTurn? }` limits [worker messages](#worker-messages) (6 and 3 when omitted), under the same rule. |
-| `SEND_MESSAGE_TOOL` / `MESSAGE_RECEIVED_ENTRY` / `WORKER_MESSAGES_RESOURCE` / `WORKER_MESSAGES_PATTERN` / `workerMessageRowSchema` / `WorkerMessageRow` / `MAX_MESSAGE_CHARS` / `DEFAULT_MESSAGE_HOP_LIMIT` / `DEFAULT_MESSAGES_PER_TURN` / `sendMessageInputSchema` | [Worker messages](#worker-messages): the tool's name (`"sendMessage"`), the entry a message arrives on (`"onMessageReceived"`), the log's accessor and pattern and its row schema, the 8,000-character cap, the default limits (6 and 3), and the tool's input schema. Also exported: `MESSAGE_STATUSES`, `MessageAddress`, `workerMessagesCollection` and `workerMessagesResources` (the log as a flow resource), `takesWorkerMessages(flow)` (whether a flow declares the entry), and `sendMessage(ctx, installation, flowKind, { to, text, inReplyTo? }, from)`, the send the tool runs, answering a `SendOutcome`. |
+| `SEND_MESSAGE_TOOL` / `MESSAGE_RECEIVED_ENTRY` / `RECEIVED_MESSAGE_COMPONENT` / `WORKER_MESSAGES_RESOURCE` / `WORKER_MESSAGES_PATTERN` / `workerMessageRowSchema` / `WorkerMessageRow` / `MAX_MESSAGE_CHARS` / `DEFAULT_MESSAGE_HOP_LIMIT` / `DEFAULT_MESSAGES_PER_TURN` / `sendMessageInputSchema` | [Worker messages](#worker-messages): the tool's name (`"sendMessage"`), the entry a message arrives on (`"onMessageReceived"`), the component item type a received message is drawn by (`"workforce:received"`), the log's accessor and pattern and its row schema, the 8,000-character cap, the default limits (6 and 3), and the tool's input schema. Also exported: `MESSAGE_STATUSES`, `MessageAddress`, `workerMessagesCollection` and `workerMessagesResources` (the log as a flow resource), and `sendMessage(ctx, installation, flowKind, { to, text, inReplyTo? }, from)`, the send the tool runs, answering a `SendOutcome` (`{ ok: true, id, unconfirmed? }` or `{ ok: false, error }`); its input type is `SendMessageInput`. |
+| `messageReceivedEntry({ installation, flowKind, turn?, hears? })` / `MessageHearing` | The `onMessageReceived` internal entry every worker flow carries (see [Worker messages](#worker-messages)). `turn` runs with a `MessageReceived` after the message lands; left out, nothing runs. `hears: "task-sessions"` (`MessageHearing`) makes the flow's workers hear only in their tasks' sessions, refusing a message by name with `task_sessions_only`. The session kit's `entries(turn)` includes one. |
+| `messageReceivedSchema` / `MessageReceived` / `messageReceivedInputSchema` | What a turn hears, `{ id, from, text, call, inReplyTo?, budget }` (`call` is always `false`; `budget` is how many more messages the exchange can send), and what the entry takes, `{ messageId }`. |
+| `promptedMessageTurn(turn)` / `receivedMessagePrompt(received)` | Wrap a block that takes `{ message }` so it can serve as `messageReceivedEntry`'s `turn`, and the text it hands that block: who wrote, which message, how to answer with `sendMessage` and `inReplyTo`, and the budget left. |
| `mergeWorkerFlows(flows, workers)` | 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`. |
| `workerFlowProblems(name, flow, roles?)` | Every way `flow`, registered as `name` with `roles`, 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 `respond` door (or a second door, or its door under another name), a declared role's entry missing, not its factory's or refusing its input, a role's piece on a flow that doesn't declare the role, a resource with `writtenBy` that `sharedResource()` didn't build. `roles` defaults to a built-in flow's own, and none for any other. 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. |
diff --git a/packages/workforce/src/messages/message-received-entry.ts b/packages/workforce/src/messages/message-received-entry.ts
index 7fe4b086e3..94566e8719 100644
--- a/packages/workforce/src/messages/message-received-entry.ts
+++ b/packages/workforce/src/messages/message-received-entry.ts
@@ -194,7 +194,7 @@ export function messageReceivedEntry(options: {
ctx.emit.message(`From ${row.from}: ${row.text}`, { agentName: row.from, itemVisibility: { client: false, history: true } });
ctx.emit.component(
RECEIVED_MESSAGE_COMPONENT,
- { id: row.id, from: row.from, text: row.text, ...(row.inReplyTo === undefined ? {} : { inReplyTo: row.inReplyTo }) },
+ { id: row.id, from: row.from, text: row.text, ...(row.inReplyTo === undefined ? {} : { inReplyTo: row.inReplyTo }), budget: received.budget },
{ agentName: row.from, itemVisibility: { client: true, history: false } }
);
return { act: "heard", received };
diff --git a/packages/workforce/test/worker-messages.test.ts b/packages/workforce/test/worker-messages.test.ts
index 220b03ee27..06afa6e973 100644
--- a/packages/workforce/test/worker-messages.test.ts
+++ b/packages/workforce/test/worker-messages.test.ts
@@ -124,7 +124,7 @@ describe("a worker messages another worker", () => {
expect(rows[0]).toMatchObject({ from: "otto", to: "lead", text: "What is the codename?", status: "delivered", hop: 1, fromSession: otto, toSession: lead!.id });
// Its own item: the sender, the id and the text, drawn by the client only.
- expect(await receivedIn(h, lead!.id)).toEqual([{ id: rows[0]!.id, from: "otto", text: "What is the codename?" }]);
+ expect(await receivedIn(h, lead!.id)).toEqual([{ id: rows[0]!.id, from: "otto", text: "What is the codename?", budget: 5 }]);
const items = await itemsOf(h, lead!.id);
expect(items.find((item) => item.type === "component")?.itemVisibility).toEqual({ client: true, history: false });
// The line the model reads, in history only.
@@ -271,7 +271,7 @@ describe("an answer", () => {
const rows = await logRows(h, "alice");
const question = rows.find((row) => row.from === "otto")!;
const answer = rows.find((row) => row.from === "lead")!;
- expect(await receivedIn(h, otto)).toEqual([{ id: answer.id, from: "lead", text: "It is Bluebird.", inReplyTo: question.id }]);
+ expect(await receivedIn(h, otto)).toEqual([{ id: answer.id, from: "lead", text: "It is Bluebird.", inReplyTo: question.id, budget: 4 }]);
expect(answer).toMatchObject({ to: "otto", inReplyTo: question.id, exchange: question.id, toSession: otto, status: "delivered", hop: 2 });
} finally {
await h.dispose();
diff --git a/specs/epics/FIX-2070/DECISIONS.md b/specs/epics/FIX-2070/DECISIONS.md
index 7f6d995bb7..330a97e37a 100644
--- a/specs/epics/FIX-2070/DECISIONS.md
+++ b/specs/epics/FIX-2070/DECISIONS.md
@@ -91,18 +91,18 @@ A *uses* cell is a place a child must not re-decide.
| ER-3 | The server resolves every target to a session within the sending session's tenant and checks it before anything is written: a worker on the user's roster; a task of the user's; a `{ session }` that is a conversation of the sender's user, in the sender's org, of a worker still on the roster and on that session's flow, never a task or delegate session; the sender's own name is refused, a different session of its own is not | FIX-2160 | Leg b; the closure's refusal checks |
| ER-4 | A call waits on the engine's wait gate for the `onMessageReceived` request's result, up to its deadline, the host's wait default unless passed; a late result is that request's record, found by the call id. A send or a call to a busy or waiting session queues until its current request ends, through the engine's existing `defer` concurrency policy (as `onMessageReceived`'s entry runs today, `AFTER_REPLY_CONCURRENCY`), never a queue store of its own. That policy alone covers a busy session only: a request that suspends gives its place back (`engine/src/transports/concurrency/arbiter.ts`), and another request may start during the suspension (`engine/test/transports/resume-concurrency.test.ts`). So `onMessageReceived`'s admission also holds while the session has a request suspended for a person, read from that session's open person suspension with `isUserSuspension` (`contracts/src/types/suspension.ts`, FIX-2058's ER-1; a task's session reads its row's open hold, FIX-2058's ER-2), and runs once the suspension resumes; FIX-2239 builds that admission check; a call waits no longer than its deadline; a session waiting on a person is waiting. A caller parked on a call is on the wait gate, never a person's stop: PR-3's one Inbox item and the board's `waiting-on-a-user` never count it ([D1](#d1), [D3](#d3)) | FIX-2239 | Leg a |
| ER-5 | A message lands once: the send owes a debt on its session's wake until the message is delivered or refused, the board's `dispatch` pass resends a row still `unconfirmed`, and `onMessageReceived` acts on its id once. The evidence for "once" lasts as long as the debt, not a bounded window. A refusal is final ([D2](#d2)) | FIX-2240 | Leg c |
-| ER-6 | One budget per message a user types: 6 messages, shared by every request descending from it through messages, calls and filed tasks; at most 3 per request; a held task released and started gets a fresh 6; a message is paid when it passes the send's checks and its row is written, before delivery; a send refused before that pays nothing. No session starts a chain of its own except a user's turn and a released held task. The budget is today's hop chain (`messages/hop.ts`, `hireWorkforce`'s `hopLimit` and `perTurn`) carried forward, not a new counter. Only messages spend it: filing a task never does, and the server-sent midway question (FIX-2241) is exempt, so a spent budget never keeps a question from its filer | FIX-2238 | Leg d |
+| ER-6 | One budget per message a user types: 6 messages, shared by every request descending from it through messages, calls and filed tasks; at most 3 per request; a held task released and started gets a fresh 6; a message is paid when it passes the send's checks and its row is written, before delivery; a send refused before that pays nothing. No session starts a chain of its own except a user's turn, a released held task, and a request with nothing behind it (one no turn, message or task carries a chain into). The budget is today's hop chain (`messages/hop.ts`, `hireWorkforce`'s `hopLimit` and `perTurn`) carried forward, not a new counter. Only messages spend it: filing a task never does, and the server-sent midway question (FIX-2241) is exempt, so a spent budget never keeps a question from its filer | FIX-2238 | Leg d |
| ER-7 | Removed outright, with no alias or warning: `onWorkerMessage`, `messageWorker`, `replyTo`, `workforceRelayTo`, `takes_tasks_only`, `no_turn` ([FIX-2056 (e)](../FIX-2056/DECISIONS.md#e)). Other renames are FIX-2071's (its D4 agrees name for name), and no child renames anything else | FIX-2238 | FIX-2249 adds the names to `RETIRED`; the closure's sweep |
## Coordination seams
| Seam | Owner, then who else touches it |
|---|---|
-| The send path (`workforce/src/messages/send-message.ts`) | FIX-2238 rebuilds it for `sendMessage` and the landing rules. FIX-2160 adds target resolution before the limits; FIX-2239 adds the wait after the dispatch; FIX-2240 replaces the two tries with the wake. FIX-2238 moves the hop count onto the budget. Their specs run in parallel on FIX-2238's merge; their implementation PRs land in a fixed order, FIX-2160, then FIX-2240, then FIX-2239, each stacked on the one before (GitHub stacks), so no two rebase over each other |
-| The message row (`workforce/src/messages/log-row.ts`, pinned pattern `workforce/messages/*`) | FIX-2238 renames `replyTo` to `inReplyTo` on the row and adds the target kind. Stores are reset between the refactor epics, so no old row is read (as FIX-2058's ER-5). FIX-2240 adds the wake's due state and the id of the request a delivery became; FIX-2239 reads that id to find a late result |
+| The send path (`workforce/src/messages/send-message.ts`) | FIX-2238 rebuilds it for `sendMessage` and the landing rules. FIX-2160 adds target resolution before the limits; FIX-2239 adds the wait after the dispatch; FIX-2240 replaces the two tries with the wake. FIX-2238 moves the hop count onto the budget. Their specs run in parallel on FIX-2238's merge; their implementation PRs land in a fixed order, FIX-2238, then FIX-2160, then FIX-2240, then FIX-2239, then FIX-2241's Workforce send, each stacked on the one before (GitHub stacks), so no two rebase over each other |
+| The message row (`workforce/src/messages/log-row.ts`, pinned pattern `workforce/messages/*`) | FIX-2238 renames `replyTo` to `inReplyTo` on the row and drops `answerTo`. FIX-2160 adds the target kind as `addressedBy` (`task` or `session`; absent for a worker's name) and the task id `toTask`. Stores are reset between the refactor epics, so no old row is read (as FIX-2058's ER-5). FIX-2240 adds the wake's due state and the id of the request a delivery became (`deliveredAs`); FIX-2239 reads that id to find a late result, and adds `queuedBehind` for a message waiting behind a person |
| The session factory (`workforce/src/conversation-board/session-board.ts`) and the roles table (`workforce/src/worker-roles.ts`) | FIX-2238 spreads `onMessageReceived` into every worker flow and adds it to every worker's entries. No other child adds an entry |
| The question message (`orchestration`'s midway ask, FIX-2133's hold write) | FIX-2241 sends from the task's session after the hold is written, through `sendMessage`'s server path, never the model tool. The hold stays the record and the Inbox stays the answer's home (PR-3) |
-| Shift Manager's conversation and Messages view (`shift-manager/src/`) | FIX-2238 draws a received message as its own item; FIX-2239 shows a call waiting; nothing else changes the view |
+| Shift Manager's conversation and Messages view (`shift-manager/src/`) | FIX-2238 draws a received message as its own item; FIX-2240 changes the Messages view's statuses (its fourth, `undeliverable`); FIX-2239 shows a call waiting; nothing else changes the view |
| FIX-2071 (renames, next epic) | Leaves the names in ER-7 alone; everything else in the gaps file's retired-terms table stays its own |
## Decided in review, recorded so no child reopens them
diff --git a/specs/epics/FIX-2070/SPEC.md b/specs/epics/FIX-2070/SPEC.md
index 3b2bbc8c91..ede4024688 100644
--- a/specs/epics/FIX-2070/SPEC.md
+++ b/specs/epics/FIX-2070/SPEC.md
@@ -127,8 +127,9 @@ flowchart LR
An edge is what one issue hands the next; a dashed input is consumed, not owned. FIX-2238 goes
first; the other four are specified in parallel on it. Three share the send path, so their
-implementation PRs land stacked in order, FIX-2160, FIX-2240, FIX-2239
-([the send-path seam](DECISIONS.md#coordination-seams)); FIX-2241 lands on its own. The closure waits on all of them. FIX-2071 starts
+implementation PRs land stacked in order on FIX-2238's, FIX-2160, FIX-2240, FIX-2239
+([the send-path seam](DECISIONS.md#coordination-seams)); FIX-2241's orchestration half lands on its own, and its
+Workforce send stacks last. The closure waits on all of them. FIX-2071 starts
after this epic wraps.
## What stays as it is
From acdd3303c999e68d37110e57fac5018a883fb96f Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 27 Oct 2026 22:47:37 +0000
Subject: [PATCH 06/14] FIX-2238: one chain for a task filed held; drop the
dead messaged-workers state
- freshHopMark mints the held task's chain at filing, so every request
the task runs (a retry, a continuation after a question) counts in one
budget instead of minting a new one each time (Codex on #4010).
- TURN_MESSAGED_STATE was read only by the relay this change removed;
the field, its reset and the write on every send are gone (Cursor).
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
packages/workforce/src/messages/hop.ts | 15 ++++++---------
packages/workforce/src/messages/send-message.ts | 6 +-----
.../test/conversation-board-filing.test.ts | 5 +++--
packages/workforce/test/standing-rules.test.ts | 2 +-
packages/workforce/test/worker-messages.test.ts | 5 +++++
5 files changed, 16 insertions(+), 17 deletions(-)
diff --git a/packages/workforce/src/messages/hop.ts b/packages/workforce/src/messages/hop.ts
index 6974d458e9..086d6cce40 100644
--- a/packages/workforce/src/messages/hop.ts
+++ b/packages/workforce/src/messages/hop.ts
@@ -54,8 +54,6 @@ export const TURN_CHAIN_STATE = "workforceTurnChain";
/** The request-state field a turn's hop count is copied to, and the per-turn send count beside it. */
export const TURN_HOP_STATE = "workforceTurnHop";
export const TURN_SENT_STATE = "workforceMessagesSent";
-/** The request-state field the workers this turn has messaged are kept in. */
-export const TURN_MESSAGED_STATE = "workforceMessagedWorkers";
/** The session state a flow that takes messages declares. */
export const messageHopStateShape = {
@@ -68,8 +66,7 @@ export const messageHopStateShape = {
export const messageTurnStateSchema = z.object({
[TURN_HOP_STATE]: z.number().int().nonnegative().optional(),
[TURN_CHAIN_STATE]: z.string().nullable().optional(),
- [TURN_SENT_STATE]: z.number().int().nonnegative().optional(),
- [TURN_MESSAGED_STATE]: z.array(z.string()).optional()
+ [TURN_SENT_STATE]: z.number().int().nonnegative().optional()
});
/** A session's current hop count: 0 for one that keeps none. */
@@ -134,11 +131,12 @@ export function turnHopMark(ctx: Pick): Hop
/**
* The mark for a task filed held (FIX-2238): released, it starts a fresh
- * chain at 0, its first send minting one, since no exchange waits on it. The
- * filer's user lines are kept, so a user's line since still clears it.
+ * chain at 0, since no exchange waits on it. The chain is minted here, once,
+ * so every request the task runs counts in the same budget. The filer's user
+ * lines are kept, so a user's line since still clears it.
*/
export function freshHopMark(ctx: Pick): HopMark {
- return { hop: 0, chain: null, lines: sessionUserLinesOf(ctx.session.state) };
+ return { hop: 0, chain: newChainId(), lines: sessionUserLinesOf(ctx.session.state) };
}
/**
@@ -191,7 +189,6 @@ export async function startTurnAtHop(
...also,
[TURN_HOP_STATE]: hop,
[TURN_CHAIN_STATE]: chain,
- [TURN_SENT_STATE]: 0,
- [TURN_MESSAGED_STATE]: []
+ [TURN_SENT_STATE]: 0
} as never);
}
diff --git a/packages/workforce/src/messages/send-message.ts b/packages/workforce/src/messages/send-message.ts
index ef25e6dead..1f89123bb7 100644
--- a/packages/workforce/src/messages/send-message.ts
+++ b/packages/workforce/src/messages/send-message.ts
@@ -39,7 +39,7 @@ import { filingProjectAddressOf, sessionIdOfFiling } from "../conversation-board
import { deriveWorkerSessionId, criteriaState, type WorkerSessionCriteria } from "../workers/derive-session-id";
import type { RosterWorker, WorkerInstallation } from "../workers/installation";
import { FILING_FLOW_STATE_KEY, FILING_SESSION_STATE_KEY, FILING_WORKER_STATE_KEY, WORKER_ID_STATE_KEY } from "../workers/keys";
-import { newChainId, TURN_CHAIN_STATE, TURN_MESSAGED_STATE, TURN_SENT_STATE, turnChainOf, turnHopOf } from "./hop";
+import { newChainId, TURN_CHAIN_STATE, TURN_SENT_STATE, turnChainOf, turnHopOf } from "./hop";
import { MESSAGE_RECEIVED_ENTRY } from "./keys";
import { messageLimitsOf } from "./message-limits";
import { messageHearingOf } from "./message-received-entry";
@@ -211,10 +211,6 @@ export async function sendMessage(
return budgetRefusal(placeAfter(chainRow.state.sent.length));
}
const hop = placeAfter(place);
- await atomicRequest((current) => {
- const messaged = Array.isArray(current[TURN_MESSAGED_STATE]) ? (current[TURN_MESSAGED_STATE] as string[]) : [];
- return { [TURN_MESSAGED_STATE]: [...messaged, input.to] };
- });
// ---- the row, then the delivery ------------------------------------------
const row: WorkerMessageRow = {
diff --git a/packages/workforce/test/conversation-board-filing.test.ts b/packages/workforce/test/conversation-board-filing.test.ts
index 79d8aab4cd..a5efb42697 100644
--- a/packages/workforce/test/conversation-board-filing.test.ts
+++ b/packages/workforce/test/conversation-board-filing.test.ts
@@ -268,7 +268,8 @@ describe("what a filing can't name (BR-8)", () => {
const row = await host.row("alice", filing, filed.taskId!);
// The markers on it are the board's own: the filing turn's hop count (FIX-2106), and the
// project it was filed in, none here, whatever the caller named (FIX-2161).
- expect(row?.metadata).toEqual({ note: "kept", [FILED_HOP]: { hop: 0, chain: null, lines: 0 }, [FILED_PROJECT]: null });
+ // `record` files held, so the mark is a fresh chain of its own (FIX-2238).
+ expect(row?.metadata).toEqual({ note: "kept", [FILED_HOP]: { hop: 0, chain: expect.any(String), lines: 0 }, [FILED_PROJECT]: null });
// No start was owed, so nothing ran: the row has no assignee.
await host.settled();
expect(host.runs).toEqual([]);
@@ -280,7 +281,7 @@ describe("what a filing can't name (BR-8)", () => {
expect((await host.row("alice", filing, filed.taskId!))?.metadata).toEqual({
note: "kept",
extra: 1,
- [FILED_HOP]: { hop: 0, chain: null, lines: 0 },
+ [FILED_HOP]: row?.metadata?.[FILED_HOP],
[FILED_PROJECT]: null
});
} finally {
diff --git a/packages/workforce/test/standing-rules.test.ts b/packages/workforce/test/standing-rules.test.ts
index 1aab9d6789..1e515cd051 100644
--- a/packages/workforce/test/standing-rules.test.ts
+++ b/packages/workforce/test/standing-rules.test.ts
@@ -172,7 +172,7 @@ describe("which turns get the rule tools (V3, BR-4)", () => {
const first = await marked({});
const chain = expect.stringMatching(/^chain_/);
expect(first.patches).toEqual([
- { [USER_TURN_STATE]: true, workforceTurnHop: 0, workforceTurnChain: chain, workforceMessagesSent: 0, workforceMessagedWorkers: [] }
+ { [USER_TURN_STATE]: true, workforceTurnHop: 0, workforceTurnChain: chain, workforceMessagesSent: 0 }
]);
// It counts one more user's line on the session, which a filed task's
// record is checked against (FIX-2106).
diff --git a/packages/workforce/test/worker-messages.test.ts b/packages/workforce/test/worker-messages.test.ts
index 06afa6e973..5346b132a2 100644
--- a/packages/workforce/test/worker-messages.test.ts
+++ b/packages/workforce/test/worker-messages.test.ts
@@ -732,6 +732,11 @@ describe("the hop count through a delegation", () => {
const first = rows.find((row) => row.from === "otto")!;
const fromTask = rows.find((row) => row.from === "helper-b")!;
expect(fromTask.chain, "a fresh chain, not the filing's").not.toBe(first.chain);
+ // Minted once, at the filing: every request the task runs reloads this
+ // mark, so a retry or a continuation counts in the same budget.
+ const mark = held!.metadata?.[FILED_HOP] as { hop: number; chain: string | null };
+ expect(mark.hop).toBe(0);
+ expect(fromTask.chain, "the chain the filing recorded").toBe(mark.chain);
} finally {
await h.dispose();
}
From 752d2904df1304a1fb3d6fbca91cfb0c98ca371c Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 27 Oct 2026 23:01:17 +0000
Subject: [PATCH 07/14] FIX-2238: a received message's budget is what its chain
has left
A message queued behind a busy recipient, or heard after its sender sent
again, read its budget from its own row's hop, so it could report places
already spent. The receipt reads the chain row and reports from the larger
of the two (Codex on #4010).
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
.../src/messages/message-received-entry.ts | 7 ++-
.../workforce/test/worker-messages.test.ts | 56 +++++++++++++++++++
2 files changed, 61 insertions(+), 2 deletions(-)
diff --git a/packages/workforce/src/messages/message-received-entry.ts b/packages/workforce/src/messages/message-received-entry.ts
index 00deb69200..f922af57b4 100644
--- a/packages/workforce/src/messages/message-received-entry.ts
+++ b/packages/workforce/src/messages/message-received-entry.ts
@@ -27,7 +27,7 @@ import type { WorkerInstallation } from "../workers/installation";
import { messageTurnStateSchema, startTurnAtHop } from "./hop";
import { MESSAGE_RECEIVED_ENTRY, RECEIVED_MESSAGE_COMPONENT, SEND_MESSAGE_TOOL, WORKER_MESSAGES_SEEN_STATE } from "./keys";
import { messageLimitsOf } from "./message-limits";
-import { messageLogOf, workerMessagesResources } from "./message-log";
+import { messageChainsOf, messageLogOf, workerMessagesResources } from "./message-log";
/** What the entry takes: the message's id, and nothing a sender could shape. */
export const messageReceivedInputSchema = z.object({ messageId: z.string().min(1) }).strict();
@@ -181,13 +181,16 @@ export function messageReceivedEntry(options: {
if (first !== true) return { act: "none" };
await startTurnAtHop(ctx as never, row.hop, row.chain ?? null);
const { hopLimit } = messageLimitsOf(options.installation);
+ // What is left is the chain's, not the row's: sends since this one (a
+ // branch, or a queue behind a busy recipient) have spent it too.
+ const chainSent = row.chain == null ? 0 : ((await messageChainsOf(ctx as never).getOptional(row.chain))?.state.sent.length ?? 0);
const received: MessageReceived = {
id: row.id,
from: row.from,
text: row.text,
call: false,
...(row.inReplyTo === undefined ? {} : { inReplyTo: row.inReplyTo }),
- budget: Math.max(0, hopLimit - row.hop)
+ budget: Math.max(0, hopLimit - Math.max(row.hop, chainSent))
};
// The two items, in one place, after the dedupe: the line the model
// reads, and the item an app draws.
diff --git a/packages/workforce/test/worker-messages.test.ts b/packages/workforce/test/worker-messages.test.ts
index 5346b132a2..aa23ede2bb 100644
--- a/packages/workforce/test/worker-messages.test.ts
+++ b/packages/workforce/test/worker-messages.test.ts
@@ -949,6 +949,62 @@ describe("a busy recipient", () => {
await h.dispose();
}
});
+
+ // A queued message's budget is what its chain has left when it is heard,
+ // not when it was sent: the sender's next send has spent one more.
+ it("tells a message heard after a busy turn what its chain has left by then", async () => {
+ let release!: () => void;
+ const held = new Promise((resolve) => (release = resolve));
+ let holding = true;
+ let asked = false;
+ const h = boot({
+ judgment: mockGenerator({ script: [{ when: (input) => textOf(input).includes("long question"), then: { text: "Long answer." } }, fallback] }),
+ agentAnswer: mockGenerator({
+ script: [
+ { when: (input) => asked && textOf(input).includes("Please ask the lead twice"), then: { text: "Sent." } },
+ {
+ when: (input) => {
+ if (asked || !textOf(input).includes("Please ask the lead twice")) return false;
+ asked = true;
+ return true;
+ },
+ then: {
+ toolCalls: [
+ { toolCallId: "call-first", toolName: "sendMessage", args: { to: "lead", text: "First." } },
+ { toolCallId: "call-second", toolName: "sendMessage", args: { to: "lead", text: "Second." } }
+ ]
+ }
+ },
+ fallback
+ ]
+ }),
+ afterModelCall: async (block) => {
+ if (block === "coordinator-judgment" && holding) {
+ holding = false;
+ await held;
+ }
+ }
+ });
+ try {
+ const lead = await h.client("alice").ensureWorkerSession({ worker: "lead" });
+ await h.post("alice", lead.id, "respond", { message: "A long question" }, "coordinator");
+ for (let i = 0; i < 200 && holding; i += 1) await new Promise((r) => setTimeout(r, 10));
+ const otto = await agentSession(h, "alice", "otto");
+ await h.post("alice", otto, "respond", { message: "Please ask the lead twice" }, "agent");
+ for (let i = 0; i < 300 && (await logRows(h, "alice")).length < 2; i += 1) await new Promise((r) => setTimeout(r, 10));
+ expect((await logRows(h, "alice")).map((row) => row.hop).sort()).toEqual([1, 2]);
+ release();
+ await h.settled();
+ const heard = await receivedIn(h, lead.id);
+ expect(heard.map((item) => [item.text, item.budget])).toEqual([
+ ["First.", 4],
+ ["Second.", 4]
+ ]);
+ } finally {
+ release();
+ await h.dispose();
+ }
+ });
});
describe("delivery", () => {
From 367eb6908805f67c70627a96b24f916cffb92c6b Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 27 Oct 2026 23:07:13 +0000
Subject: [PATCH 08/14] FIX-2238: an answer reaches a worker that hears only in
its tasks' sessions
recipientRefusal refused task_sessions_only before inReplyTo was read,
so a task-sessions worker's question could never be answered. An answer
lands in the session its original came from, so only a message by name
is refused now (Codex on #4010). sendMessageOutputSchema is no longer
exported: nothing outside the tool reads it (Fallow).
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
.../workforce/src/messages/message-tool.ts | 2 +-
.../workforce/src/messages/send-message.ts | 12 ++++++---
.../workforce/test/worker-messages.test.ts | 27 ++++++++++++++++++-
3 files changed, 36 insertions(+), 5 deletions(-)
diff --git a/packages/workforce/src/messages/message-tool.ts b/packages/workforce/src/messages/message-tool.ts
index d51e53421d..ca5e995d6b 100644
--- a/packages/workforce/src/messages/message-tool.ts
+++ b/packages/workforce/src/messages/message-tool.ts
@@ -37,7 +37,7 @@ export const sendMessageInputSchema = z
})
.strict();
-export const sendMessageOutputSchema = z.union([
+const sendMessageOutputSchema = z.union([
z.object({ sent: z.string(), unconfirmed: z.string().optional() }),
z.object({ ok: z.literal(false), error: z.string() })
]);
diff --git a/packages/workforce/src/messages/send-message.ts b/packages/workforce/src/messages/send-message.ts
index 1f89123bb7..07a9285d1b 100644
--- a/packages/workforce/src/messages/send-message.ts
+++ b/packages/workforce/src/messages/send-message.ts
@@ -69,17 +69,23 @@ export type SendOutcome =
* or `undefined` when there is none), or `undefined` when it can. The one
* rule: the send refuses with it, and the tool's description lists only the
* workers it lets through.
+ *
+ * @param answering The send answers one of `to`'s messages (`inReplyTo`), so
+ * it lands where that message came from, not by name.
*/
export function recipientRefusal(
installation: WorkerInstallation,
sender: string,
to: string,
- recipient: RosterWorker | undefined
+ recipient: RosterWorker | undefined,
+ answering = false
): string | undefined {
if (to === sender) return "not_yourself: you can't message yourself.";
if (recipient === undefined) return `no_worker: no worker "${to}" on your roster.`;
if (recipient.problem !== undefined) return `worker_unavailable: worker "${to}" can't be messaged: ${recipient.problem}.`;
- if (messageHearingOf(installation.workerFlows()[recipient.flow]?.flow) === "task-sessions") {
+ // An answer lands in the session its original came from, which is one of
+ // the worker's tasks' sessions, so only a message by name is refused.
+ if (!answering && messageHearingOf(installation.workerFlows()[recipient.flow]?.flow) === "task-sessions") {
return (
`task_sessions_only: "${to}" answers only from its tasks' sessions, so it can't be messaged by name. ` +
"File it a task instead."
@@ -150,7 +156,7 @@ export async function sendMessage(
// ---- the recipient: on the roster, and hearing by name -------------------
const recipient = await installation.rosterWorker(ctx as never, input.to);
- const refused = recipientRefusal(installation, sender, input.to, recipient);
+ const refused = recipientRefusal(installation, sender, input.to, recipient, input.inReplyTo !== undefined);
if (refused !== undefined || recipient === undefined) return refuse(refused ?? `no_worker: no worker "${input.to}" on your roster.`);
// ---- where it lands ------------------------------------------------------
diff --git a/packages/workforce/test/worker-messages.test.ts b/packages/workforce/test/worker-messages.test.ts
index aa23ede2bb..6ad7513947 100644
--- a/packages/workforce/test/worker-messages.test.ts
+++ b/packages/workforce/test/worker-messages.test.ts
@@ -12,9 +12,14 @@ import { describe, expect, it } from "vitest";
import { runAction } from "@flow-state-dev/engine";
import { mockGenerator, type MockGeneratorScriptEntry } from "@flow-state-dev/testing";
import type { WorkerManifest } from "../src";
-import { boardWorkers, bootBoardHost, messageOf, type BoardHost } from "./conversation-board-harness";
+import { boardWorkers, bootBoardHost, hearsMessages, messageOf, type BoardHost } from "./conversation-board-harness";
import { WORKER_MESSAGES_PATTERN } from "../src/messages/message-log";
import { sendMessageInputSchema } from "../src/messages/message-tool";
+import { recipientRefusal } from "../src/messages/send-message";
+import { createWorkerInstallation, type RosterWorker } from "../src/workers/installation";
+import { defineFlow, handler } from "@flow-state-dev/core";
+import { z } from "zod";
+import { workerConfigSchema } from "../src/worker-config";
import { deriveWorkerSessionId } from "../src/workers/derive-session-id";
import { FILED_HOP } from "../src/conversation-board/board-entries";
@@ -833,6 +838,26 @@ describe("the hop count through a delegation", () => {
});
describe("who can be messaged", () => {
+ // A worker that hears only in its tasks' sessions still hears an answer:
+ // the answer lands in the task session its question came from.
+ it("refuses a worker that hears only in its tasks' sessions by name, and lets an answer to it through", () => {
+ let flows: Record = {};
+ const installation = createWorkerInstallation({ standardWorkers: [], workerFlows: () => flows as never });
+ const door = z.object({ message: z.string() });
+ flows = {
+ coder: defineFlow({
+ kind: "coder",
+ configSchema: workerConfigSchema(),
+ session: installation.session(),
+ actions: { respond: { inputSchema: door, userMessage: (i: { message: string }) => i.message, block: handler({ name: "coder-run", inputSchema: door, execute: (i) => i }) } },
+ internal: { actions: hearsMessages(installation, "coder", "task-sessions") }
+ })
+ };
+ const coder: RosterWorker = { id: "eng.coder", standard: true, flow: "coder", description: null, delegates: [] } as RosterWorker;
+ expect(recipientRefusal(installation, "otto", "eng.coder", coder)).toMatch(/^task_sessions_only/);
+ expect(recipientRefusal(installation, "otto", "eng.coder", coder, true)).toBeUndefined();
+ });
+
it("refuses another user's worker as missing, a worker that hears only in its tasks' sessions with 'file a task', and itself, writing nothing; a round-robin coordinator hears one", async () => {
const calls = [
{ to: "bob.friend", text: "Hi Bob's worker." },
From 5d7ca952bb5bf21e5ad9a0e644065232bd4712b6 Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 27 Oct 2026 23:08:14 +0000
Subject: [PATCH 09/14] FIX-2238 goal: the ring's own hand-offs aren't stray
rows; the herald sends after a refusal
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
goals/shift-manager/workers-message-each-other/legs.mts | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/goals/shift-manager/workers-message-each-other/legs.mts b/goals/shift-manager/workers-message-each-other/legs.mts
index 5a6db45955..f99b180187 100644
--- a/goals/shift-manager/workers-message-each-other/legs.mts
+++ b/goals/shift-manager/workers-message-each-other/legs.mts
@@ -688,7 +688,7 @@ export async function leg3(world: World): Promise {
// A refused send spends nothing: after a new line from the person, a refused send then a sent one, at 1.
const nobody = `nobody-${hex()}`;
const logBefore = new Set((await logOf(alice)).map((m) => m.id));
- const pair = await talk(turns, "3", alice, HERALD, herald, `Do these two in order. First message the worker ${nobody} saying hi. Then message ${HELPER_A} saying "after ${ring}".`);
+ const pair = await talk(turns, "3", alice, HERALD, herald, `Do these two in order. First message the worker ${nobody} saying hi. Then, whether or not that worked, message ${HELPER_A} saying "after ${ring}".`);
const refusedCall = pair.calls.find((c) => c.args.to === nobody);
const afterCall = pair.calls.find((c) => c.args.to === HELPER_A && typeof c.output?.sent === "string");
const added = (await logOf(alice)).filter((m) => !logBefore.has(m.id) && m.fromSession === herald.id);
@@ -781,7 +781,10 @@ export async function leg4(world: World, filedGoals: readonly string[], hireChec
const session = world.conversation[worker];
if (session === undefined) continue;
const board = await boardOf(alice, session.flowKind, session.id).catch((e: unknown) => [{ error: messageOf(e) }] as Array>);
- const stray = board.filter((row) => !filedGoals.some((goal) => String(row.goal ?? "").includes(goal)));
+ // Leg 3's ring hands each message on as a task for Helper B on Helper A's board, in the model's own words.
+ const stray = board.filter(
+ (row) => !filedGoals.some((goal) => String(row.goal ?? "").includes(goal)) && !(worker === HELPER_A && row.assignee === HELPER_B),
+ );
if (stray.length > 0) r.failures.push(`4:no-task-row — ${worker}'s board holds row(s) no leg filed: ${show(stray.map((x) => ({ assignee: x.assignee, goal: String(x.goal ?? x.error ?? "").slice(0, 120) })))}`);
}
return r;
From bfbae4c084024b92036c652bca3f99b4c3af3695 Mon Sep 17 00:00:00 2001
From: Claude
Date: Tue, 27 Oct 2026 23:18:28 +0000
Subject: [PATCH 10/14] FIX-2238 goal: 3:budget-left grades what the chain had
left when heard
A ring that branches spends places before a later message is heard, so
the received budget can be below 6 minus its place. The leg now checks
it is at most that, never negative, and counts down along the ring.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
.../workers-message-each-other/legs.mts | 13 +++++++++----
1 file changed, 9 insertions(+), 4 deletions(-)
diff --git a/goals/shift-manager/workers-message-each-other/legs.mts b/goals/shift-manager/workers-message-each-other/legs.mts
index f99b180187..a12482f853 100644
--- a/goals/shift-manager/workers-message-each-other/legs.mts
+++ b/goals/shift-manager/workers-message-each-other/legs.mts
@@ -676,13 +676,18 @@ export async function leg3(world: World): Promise {
}
if (stopped === undefined && sent.length <= 6) r.failures.push(`3:ring-stops-at-6 — no session shows a seventh send refused \`budget\``);
if (stopped !== undefined) r.notes.push(`the seventh send was refused in ${stopped.sessionId}: ${errorOf(stopped).slice(0, 160)}`);
- // Each received item says what is left: 6 minus its place.
+ // Each received item says what its chain has left when it is heard: at
+ // most 6 minus its place (less when the ring branched and spent more
+ // first), never below 0, and counting down along the ring.
const wrong: string[] = [];
- for (const m of sent) {
+ let previous = Number.POSITIVE_INFINITY;
+ for (const m of [...sent].sort((a, b) => a.hop - b.hop)) {
const item = (await receivedIn(alice, m.toSession)).find((x) => x.id === m.id);
- if (item?.budget !== 6 - m.hop) wrong.push(`${m.id}@${m.hop}: budget ${String(item?.budget)}`);
+ const budget = item?.budget;
+ if (typeof budget !== "number" || budget < 0 || budget > 6 - m.hop || budget > previous) wrong.push(`${m.id}@${m.hop}: budget ${String(budget)}`);
+ if (typeof budget === "number") previous = budget;
}
- if (wrong.length > 0) r.failures.push(`3:budget-left — a ring message's received item doesn't say 6 minus its place: ${show(wrong)}`);
+ if (wrong.length > 0) r.failures.push(`3:budget-left — a ring message's received item doesn't count down from 6 minus its place: ${show(wrong)}`);
await quiet(alice, 300_000);
// A refused send spends nothing: after a new line from the person, a refused send then a sent one, at 1.
From 0e91fadb521f5c9ce75a748367278d841d9ec5fb Mon Sep 17 00:00:00 2001
From: Claude
Date: Wed, 28 Oct 2026 01:05:21 +0000
Subject: [PATCH 11/14] FIX-2238 follow-up: a fresh budget for a task held
before it starts, and for a person's line in a finished task's session
Two Codex findings that landed as #4010 merged:
- A task held by updateTask before its first start is held from its
filing: its filed mark becomes a fresh chain, as a filing held writes.
- A person's line in a finished task's session (every follow-up there
ended too) starts a fresh budget. It is still no user's turn for the
rule tools.
Epic seam table: FIX-2239's queuedBehind on the message row (cross-spec
review, approved).
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
.../workforce/src/conversation-board/board.ts | 16 +++++
.../workforce/src/standing-rules/user-turn.ts | 26 +++++++-
.../workforce/test/worker-messages.test.ts | 63 +++++++++++++++++++
specs/epics/FIX-2070/DECISIONS.md | 2 +-
4 files changed, 104 insertions(+), 3 deletions(-)
diff --git a/packages/workforce/src/conversation-board/board.ts b/packages/workforce/src/conversation-board/board.ts
index 429f7d8320..0233868bc0 100644
--- a/packages/workforce/src/conversation-board/board.ts
+++ b/packages/workforce/src/conversation-board/board.ts
@@ -557,6 +557,19 @@ async function keepFiledHopInChain(ctx: BlockContext, collection: TaskCollection
return collection.get(task.id) ?? task;
}
+/**
+ * A row held before its first start (FIX-2238): its filed mark becomes a
+ * fresh chain, as {@link heldFromFiling}'s filing writes, keeping the filer's
+ * user lines the mark counted. A started row's hold is midway, and keeps its
+ * budget; a row with no mark runs at its session's count anyway.
+ */
+async function freshenFiledHop(ctx: BlockContext, collection: TaskCollectionRef, id: string): Promise {
+ const task = collection.get(id);
+ const mark = hopMarkOf(task?.metadata?.[FILED_HOP]);
+ if (task === undefined || mark === undefined || hasStarted(task)) return;
+ await collection.patchMetadata(id, { [FILED_HOP]: { ...freshHopMark(ctx), lines: mark.lines } });
+}
+
/** The filing session's worker, for a session the hand-over opens: where a message to it from there lands (FIX-2238). */
function filingWorkerOf(state: unknown): Record {
const worker = (state as Record | undefined)?.[WORKER_ID_STATE_KEY];
@@ -1290,6 +1303,9 @@ export function defineConversationBoard(options: ConversationBoardOptions) {
const metadata = patch.metadata === undefined ? undefined : (callerMetadata(patch.metadata) ?? {});
await owePass(ctx);
const outcome = await ref.patchSettings(id, metadata === undefined ? patch : { ...patch, metadata });
+ // Held before its first start, a task is held from its filing: released,
+ // it starts a fresh chain, as one filed held does (FIX-2238).
+ if (outcome.outcome !== "declined" && patch.held === true) await freshenFiledHop(ctx, ref, id);
if (outcome.outcome !== "declined" && hasStartable(ref, id)) await triggerPass(ctx);
return outcome;
},
diff --git a/packages/workforce/src/standing-rules/user-turn.ts b/packages/workforce/src/standing-rules/user-turn.ts
index 00a10113eb..3d2c34a473 100644
--- a/packages/workforce/src/standing-rules/user-turn.ts
+++ b/packages/workforce/src/standing-rules/user-turn.ts
@@ -13,6 +13,7 @@
*/
import { handler } from "@flow-state-dev/core";
import type { BlockContext } from "@flow-state-dev/core/types";
+import { isTerminalStatus } from "@flow-state-dev/orchestration/tasks";
import { z } from "zod";
import { messageTurnStateSchema, newChainId, sessionUserLinesOf, startTurnAtHop, USER_LINES_STATE } from "../messages/hop";
import { FILING_SESSION_STATE_KEY, TASK_ID_STATE_KEY } from "../workers/keys";
@@ -28,15 +29,36 @@ export const userTurnStateSchema = z.object({ [USER_TURN_STATE]: z.boolean().opt
* conversation's delegate session: that message is task input. A user's
* turn also starts the worker-message hop count again, at 0 in a new chain
* (FIX-1989 D2), and counts one more user's line on the session (FIX-2106).
+ *
+ * Once the task and every follow-up in its session have ended, a user's line
+ * there is still no user's turn (no rule tools), but it is one a user typed:
+ * it starts a fresh budget all the same (FIX-2238).
*/
export async function markUserTurn(ctx: BlockContext): Promise {
const state = (ctx.session.state ?? {}) as Record;
- if (typeof state[TASK_ID_STATE_KEY] === "string" || typeof state[FILING_SESSION_STATE_KEY] === "string") return;
- await startTurnAtHop(ctx, 0, newChainId(), { [USER_TURN_STATE]: true }, (current) => ({
+ const taskId = state[TASK_ID_STATE_KEY];
+ let mark: Record = { [USER_TURN_STATE]: true };
+ if (typeof taskId === "string") {
+ if (!(await taskSessionEnded(ctx, taskId, state[FILING_SESSION_STATE_KEY]))) return;
+ mark = {};
+ } else if (typeof state[FILING_SESSION_STATE_KEY] === "string") {
+ return;
+ }
+ await startTurnAtHop(ctx, 0, newChainId(), mark, (current) => ({
[USER_LINES_STATE]: sessionUserLinesOf(current) + 1
}));
}
+/** Whether a task session's task, and every follow-up run in its session, has ended, on the board that filed it. */
+async function taskSessionEnded(ctx: BlockContext, taskId: string, partition: unknown): Promise {
+ if (typeof partition !== "string") return false;
+ // Loaded here, not at the top: the ledger's module graph reaches back to this one.
+ const { conversationLedgerAt } = await import("../conversation-board/ledger");
+ const rows = (await conversationLedgerAt(ctx, partition))?.list() ?? [];
+ const inSession = rows.filter((task) => task.id === taskId || task.followUpOf === taskId);
+ return inSession.length > 0 && inSession.every((task) => isTerminalStatus(task.status));
+}
+
/** Whether this request is a turn a user's own message started. */
export function isUserTurn(ctx: BlockContext): boolean {
return (ctx.request.state as Record | undefined)?.[USER_TURN_STATE] === true;
diff --git a/packages/workforce/test/worker-messages.test.ts b/packages/workforce/test/worker-messages.test.ts
index 6ad7513947..ae518db1d0 100644
--- a/packages/workforce/test/worker-messages.test.ts
+++ b/packages/workforce/test/worker-messages.test.ts
@@ -337,6 +337,34 @@ describe("a message sent from a task's turn", () => {
await h.dispose();
}
});
+
+ // An answer reopens the exchange in a finished task's session, so a user's
+ // line there is one a user typed: it starts a fresh budget, as anywhere else.
+ it("starts a fresh budget at a user's line in a finished task's session", async () => {
+ const agentAnswer = mockGenerator({
+ script: [
+ ...callOnce("Ask helper-a for its favourite colour", "sendMessage", { to: "helper-a", text: "What is your favourite colour?" }, "Asked."),
+ fallback
+ ]
+ });
+ const h = boot({ standard: teamWorkers(), agentAnswer });
+ try {
+ const chief = await h.conversation("alice", "chief");
+ await h.act("alice", chief, "createTask_tasks", { goal: "Ask helper-a for its favourite colour", assignee: "otto" });
+ await h.settled();
+ expect((await h.rows("alice"))[0]!.status).toBe("completed");
+ const taskSession = (await logRows(h, "alice")).find((row) => row.from === "otto")!.fromSession;
+ const before = (await h.session(taskSession)).state;
+
+ await h.post("alice", taskSession, "respond", { message: "Thanks, anything else?" }, "agent");
+ await h.settled();
+ const after = (await h.session(taskSession)).state;
+ expect(after.workforceUserLines, "the user's line counted").toBe(((before.workforceUserLines as number | undefined) ?? 0) + 1);
+ expect(after.workforceMessageChain, "a chain of its own").not.toBe(before.workforceMessageChain);
+ } finally {
+ await h.dispose();
+ }
+ });
});
/**
@@ -747,6 +775,41 @@ describe("the hop count through a delegation", () => {
}
});
+ // A task held by `updateTask` before it starts is held from its filing too
+ // (FIX-2238): released, it starts afresh, as one filed held does.
+ it("starts a task held before its first start afresh when it is released", async () => {
+ const h = boot({
+ standard: teamWorkers({ unassignedWaits: true }),
+ agentAnswer: mockGenerator({ script: relayThroughTask({}, { unassigned: true }) })
+ });
+ try {
+ const alice = h.client("alice");
+ const otto = await alice.ensureWorkerSession({ worker: "otto" });
+ await h.post("alice", otto.id, "respond", { message: "Please ask helper-a" }, "agent");
+ await h.settled();
+ const [filed] = await h.rows("alice");
+ expect(filed!.metadata?.[FILED_HOP]).toMatchObject({ hop: 1 });
+
+ const helperA = await alice.ensureWorkerSession({ worker: "helper-a" });
+ const held = await h.act("alice", helperA.id, "updateTask_tasks", { id: filed!.id, status: "held" }, "agent");
+ expect(held.error, messageOf(held.error)).toBeUndefined();
+ expect((await h.rows("alice"))[0]!.status).toBe("held");
+ const assigned = await h.act("alice", helperA.id, "updateTask_tasks", { id: filed!.id, assignee: "helper-b" }, "agent");
+ expect(assigned.error, messageOf(assigned.error)).toBeUndefined();
+ const released = await h.act("alice", helperA.id, "updateTask_tasks", { id: filed!.id, status: "pending" }, "agent");
+ expect(released.error, messageOf(released.error)).toBeUndefined();
+ await h.settled();
+
+ expect((await h.rows("alice")).map((row) => row.status)).toEqual(["completed"]);
+ const rows = await logRows(h, "alice");
+ expect(rows.map((row) => `${row.from}>${row.to}@${row.hop}`).sort()).toEqual(["helper-b>otto@1", "otto>helper-a@1"]);
+ const first = rows.find((row) => row.from === "otto")!;
+ expect(rows.find((row) => row.from === "helper-b")!.chain, "a fresh chain, not the filing's").not.toBe(first.chain);
+ } finally {
+ await h.dispose();
+ }
+ });
+
it("runs an ongoing-session task filed before rows recorded a count at its session's count, which counts on from its filer's", async () => {
const h = boot({ standard: teamWorkers(), agentAnswer: mockGenerator({ script: relayThroughTask({ session: "ongoing", held: true }) }) });
try {
diff --git a/specs/epics/FIX-2070/DECISIONS.md b/specs/epics/FIX-2070/DECISIONS.md
index e087b174f2..ed80dea6bc 100644
--- a/specs/epics/FIX-2070/DECISIONS.md
+++ b/specs/epics/FIX-2070/DECISIONS.md
@@ -99,7 +99,7 @@ A *uses* cell is a place a child must not re-decide.
| Seam | Owner, then who else touches it |
|---|---|
| The send path (`workforce/src/messages/send-message.ts`) | FIX-2238 rebuilds it for `sendMessage` and the landing rules. FIX-2160 adds target resolution before the limits; FIX-2239 adds the wait after the dispatch; FIX-2240 replaces the two tries with the wake. FIX-2238 moves the hop count onto the budget. Their specs run in parallel on FIX-2238's merge; their implementation PRs land in a fixed order, FIX-2238, then FIX-2160, then FIX-2240, then FIX-2239, then FIX-2241's Workforce send, each stacked on the one before (GitHub stacks), so no two rebase over each other |
-| The message row (`workforce/src/messages/log-row.ts`, pinned pattern `workforce/messages/*`) | FIX-2238 renames `replyTo` to `inReplyTo` on the row and drops `answerTo`. FIX-2160 adds the target kind as `addressedBy` (`task` or `session`; absent for a worker's name) and the task id `toTask`. Stores are reset between the refactor epics, so no old row is read (as FIX-2058's ER-5). FIX-2240 adds the delivery's take and resend record (`takenBy`, `deliveredAs`, `resent`, `toldAt`, `toState`; the owed ids live in the sending session's state and the next send in the pass's request state, [FIX-2240](../../issues/FIX-2240/DECISIONS.md#decided-not-asked)); FIX-2239 reads `deliveredAs` to find a late result |
+| The message row (`workforce/src/messages/log-row.ts`, pinned pattern `workforce/messages/*`) | FIX-2238 renames `replyTo` to `inReplyTo` on the row and drops `answerTo`. FIX-2160 adds the target kind as `addressedBy` (`task` or `session`; absent for a worker's name) and the task id `toTask`. Stores are reset between the refactor epics, so no old row is read (as FIX-2058's ER-5). FIX-2240 adds the delivery's take and resend record (`takenBy`, `deliveredAs`, `resent`, `toldAt`, `toState`; the owed ids live in the sending session's state and the next send in the pass's request state, [FIX-2240](../../issues/FIX-2240/DECISIONS.md#decided-not-asked)); FIX-2239 reads `deliveredAs` to find a late result, and adds `queuedBehind` (its spec's `heldBy`, renamed) for a message waiting behind a person |
| The session factory (`workforce/src/conversation-board/session-board.ts`) and the roles table (`workforce/src/worker-roles.ts`) | FIX-2238 spreads `onMessageReceived` into every worker flow and adds it to every worker's entries. No other child adds an entry |
| The question message (`orchestration`'s midway ask, FIX-2133's hold write) | FIX-2241 sends from the task's session after the hold is written, through `sendMessage`'s server path, never the model tool. The hold stays the record and the Inbox stays the answer's home (PR-3) |
| Shift Manager's conversation and Messages view (`shift-manager/src/`) | FIX-2238 draws a received message as its own item; FIX-2240 changes the Messages view's statuses (its fourth, `undeliverable`); FIX-2239 shows a call waiting; nothing else changes the view |
From 570849be4a7b2defd9897f19f6eaa0cf41faba84 Mon Sep 17 00:00:00 2001
From: Claude
Date: Wed, 28 Oct 2026 01:12:47 +0000
Subject: [PATCH 12/14] FIX-2238 follow-up: read a finished task session the
way the steer router does
markUserTurn now asks steer.ts whether the session's task chain has
finished (sessionTaskChainEnded, over sessionOpenTask), so a line counts
as a fresh budget exactly when it no longer steers: the same board
(boardAboveOf) and the same chain predicate. Still false with no board.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
.../workforce/src/conversation-board/steer.ts | 10 ++++++++++
.../workforce/src/standing-rules/user-turn.ts | 16 ++++------------
2 files changed, 14 insertions(+), 12 deletions(-)
diff --git a/packages/workforce/src/conversation-board/steer.ts b/packages/workforce/src/conversation-board/steer.ts
index bcd4537df1..3cdcd10ff7 100644
--- a/packages/workforce/src/conversation-board/steer.ts
+++ b/packages/workforce/src/conversation-board/steer.ts
@@ -57,6 +57,16 @@ async function sessionOpenTask(ctx: BlockContext): Promise<{ ledger: TaskCollect
return { ledger, row: latest(here.length > 0 ? here : open) };
}
+/**
+ * Whether every task in this task session's chain has finished (FIX-2238):
+ * a line here no longer steers. `false` outside a task session and with no
+ * board to read, where nothing says the task ended.
+ */
+export async function sessionTaskChainEnded(ctx: BlockContext): Promise {
+ if (sessionTaskOf(ctx) === undefined || (await sessionLedger(ctx)) === undefined) return false;
+ return (await sessionOpenTask(ctx)) === undefined;
+}
+
export { startOwedSteerTurn };
/** What a line steering the session's task answers: the task it steered. */
diff --git a/packages/workforce/src/standing-rules/user-turn.ts b/packages/workforce/src/standing-rules/user-turn.ts
index 3d2c34a473..4bd70999ea 100644
--- a/packages/workforce/src/standing-rules/user-turn.ts
+++ b/packages/workforce/src/standing-rules/user-turn.ts
@@ -13,7 +13,6 @@
*/
import { handler } from "@flow-state-dev/core";
import type { BlockContext } from "@flow-state-dev/core/types";
-import { isTerminalStatus } from "@flow-state-dev/orchestration/tasks";
import { z } from "zod";
import { messageTurnStateSchema, newChainId, sessionUserLinesOf, startTurnAtHop, USER_LINES_STATE } from "../messages/hop";
import { FILING_SESSION_STATE_KEY, TASK_ID_STATE_KEY } from "../workers/keys";
@@ -39,7 +38,10 @@ export async function markUserTurn(ctx: BlockContext): Promise {
const taskId = state[TASK_ID_STATE_KEY];
let mark: Record = { [USER_TURN_STATE]: true };
if (typeof taskId === "string") {
- if (!(await taskSessionEnded(ctx, taskId, state[FILING_SESSION_STATE_KEY]))) return;
+ // The same read that sends the line to the task as a steer while it is open.
+ // Loaded here, not at the top: its module graph reaches back to this one.
+ const { sessionTaskChainEnded } = await import("../conversation-board/steer");
+ if (!(await sessionTaskChainEnded(ctx))) return;
mark = {};
} else if (typeof state[FILING_SESSION_STATE_KEY] === "string") {
return;
@@ -49,16 +51,6 @@ export async function markUserTurn(ctx: BlockContext): Promise {
}));
}
-/** Whether a task session's task, and every follow-up run in its session, has ended, on the board that filed it. */
-async function taskSessionEnded(ctx: BlockContext, taskId: string, partition: unknown): Promise {
- if (typeof partition !== "string") return false;
- // Loaded here, not at the top: the ledger's module graph reaches back to this one.
- const { conversationLedgerAt } = await import("../conversation-board/ledger");
- const rows = (await conversationLedgerAt(ctx, partition))?.list() ?? [];
- const inSession = rows.filter((task) => task.id === taskId || task.followUpOf === taskId);
- return inSession.length > 0 && inSession.every((task) => isTerminalStatus(task.status));
-}
-
/** Whether this request is a turn a user's own message started. */
export function isUserTurn(ctx: BlockContext): boolean {
return (ctx.request.state as Record | undefined)?.[USER_TURN_STATE] === true;
From d9d39a532e6436cd735130686ae396fc36173639 Mon Sep 17 00:00:00 2001
From: Claude
Date: Wed, 28 Oct 2026 01:47:22 +0000
Subject: [PATCH 13/14] goal(FIX-2238): the goal's text for sendMessage, and
its verdict
Outcome, input, legs 1 to 4 and the controls now describe FIX-2238:
sendMessage and onMessageReceived, landing rules, the budget, the
coder's refusal, the round-robin coordinator and the hire check. The
verdict log records 3 passing runs of legs 1 to 5, the one ring run
that stopped short, and each control's FAIL.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
.../workers-message-each-other/goal.md | 39 +++++++++++--------
1 file changed, 23 insertions(+), 16 deletions(-)
diff --git a/goals/shift-manager/workers-message-each-other/goal.md b/goals/shift-manager/workers-message-each-other/goal.md
index 3cc24b856d..ad4f275dd5 100644
--- a/goals/shift-manager/workers-message-each-other/goal.md
+++ b/goals/shift-manager/workers-message-each-other/goal.md
@@ -1,25 +1,25 @@
# shift-manager › workers message each other
-**Issue:** FIX-1989; legs 6 to 8, FIX-2160 (`specs/issues/FIX-2160/SPEC.md`). Its spec's goal: `specs/issues/FIX-1989/SPEC.md` → "The goal, and how we'll know it's met".
+**Issue:** FIX-1989, amended by FIX-2238 (`specs/issues/FIX-2238/SPEC.md`); legs 6 to 8, FIX-2160 (`specs/issues/FIX-2160/SPEC.md`). Its spec's goal: `specs/issues/FIX-1989/SPEC.md` → "The goal, and how we'll know it's met".
-**Outcome:** any worker with a conversation can message any other worker on its user's roster. The message lands in the recipient's own conversation under the sender's name and wakes it; its answer comes back to the session that asked, or to the sender's own conversation when that session was a task's whose turn has ended, and wakes the sender. No task, delegation or person relays it. A chain of messages with no person between them stops at 6, one turn sends at most 3, a worker on another user's roster is refused as if it didn't exist, and the person sees every message, both sides, in Shift Manager's Messages view, across a restart.
+**Outcome:** any worker can message any other worker on its user's roster with `sendMessage`, and hears one on `onMessageReceived`. A message lands as its own item, under the sender's name, in the session it is about: an answer (`inReplyTo`) in the session its original was sent from, even a finished task's; a message to the filer of the sender's task in the filing conversation; anything else in the recipient's own conversation. It wakes the recipient, whose plain text reaches no one. One budget per message a person types: 6 messages in all, 3 per request, a refused send spending nothing, and a delegate's ongoing session counting on in its filer's budget. A worker on another user's roster is refused as if it didn't exist, the coder (which hears only in its tasks' sessions) is refused by name before anything is written, a round-robin coordinator is heard, and the person sees every message, both sides, in Shift Manager's Messages view, across a restart.
**Input:**
- Shift Manager's DevTeam install as the commit ships it, served by Shift Manager's own command over a fresh SQLite store (`DEVTEAM_STORE`). Alice is its owner and Bob its second member, each with their own verified bearer, each through the shipped clients (`createWorkforceClient`, the session client, an action client on the flow a session names), loaded from the commit under test.
-- The workers: the Shift Coordinator (`chief-of-staff`, the standard coordinator) and Researcher (`researcher`, a standard agent worker), and three Alice hires through the roster flow's `hire`: Helper A (`helper-a`, with Helper B as its delegate, and a favourite colour), Helper B (`helper-b`) and the herald (`herald`). Bob hires one worker of his own. Each person's line goes into the worker's own conversation, the session `ensureWorkerSession({ worker })` opens at its derived address.
-- The Shift Coordinator routes by best fit. Its conversation's default delegates are removed first, so every line the person sends it reaches its own turn; leg 2 adds Researcher for the task and removes it after. Routing is FIX-1791's and not what this goal grades.
+- The workers: the Shift Coordinator (`chief-of-staff`, the standard coordinator) and Researcher (`researcher`, a standard agent worker), and three Alice hires through the roster flow's `hire`: Helper A (`helper-a`, with Helper B as its delegate, and a favourite colour), Helper B (`helper-b`), the herald (`herald`) and a round-robin coordinator (`rr-lead`, delegate Helper A). Bob hires one worker of his own. Each person's line goes into the worker's own conversation, the session `ensureWorkerSession({ worker })` opens at its derived address.
+- The Shift Coordinator routes by best fit. Its conversation's default delegates are removed first, so every line the person sends it reaches its own turn; leg 2 adds Researcher for the task and removes it after. Leg 1b opens the coordinator's second conversation with Alice, and leg 2 files from it, so a message to the filer can be told from one to the default conversation. Routing is FIX-1791's and not what this goal grades.
- Held out, picked at run time: two codenames, Helper A's favourite colour, leg 3b's word, the ring's word and Bob's worker's id.
**Signal:** each failure is tagged `:`.
-- **1** (Alice tells Researcher *"Ask the Shift Coordinator what the codename is, and tell me"*, after telling the coordinator the codename): `1:sent` Researcher's turn messages the coordinator; `1:answer-holds-codename` a Researcher answer to the person, in a turn after the coordinator's answer landed, holds the codename; `1:coordinator-shows-message` the coordinator's conversation shows exactly one line *From researcher:* under Researcher's name; `1:coordinator-answered` it sent Researcher a message back.
-- **1b** (the other way): `1b:sent` the coordinator, told to tell Researcher a new codename, messages it; `1b:researcher-shows-message` Researcher's conversation shows it under the coordinator's name; `1b:next-answer-holds-it` Researcher's next answer to the person holds it.
-- **2** (from a task): the coordinator files Researcher a task to ask Helper A its favourite colour. `2:filed` the coordinator's board holds the task; `2:reached-helper` and `2:from-task` the message to Helper A was sent from the task's own session; `2:answered` Helper A answers it; `2:lands-in-own-conversation` the answer lands in Researcher's own conversation, not the task's ended session, under Helper A's name with the colour; `2:wakes` a Researcher turn writes after it; `2:no-row` Helper A's board holds no row.
-- **2b** (no waiting): Researcher told to wait for the answer: `2b:sent` its turn sends Helper A a message; `2b:turn-ends` its turn ends; `2b:no-wait` no call carrying `wait` was taken, and the answer never lands inside that turn.
-- **3b** (through a delegation): Researcher messages Helper A, Helper A files Helper B a task, Helper B's task messages Researcher. `3b:counts-on` that message is counted in the exchange Researcher's line started: the same chain in the log, at a later hop.
-- **3** (the limits): `3:per-turn` the herald, told to message everyone, sends 3 and the rest are refused for the per-turn limit; each of Researcher, Helper A and Helper B is told to pass every message on to the next, always, and the ring is started: `3:ring-stops-at-6` the ring's exchange (every message in the chain its first message started, whether or not it repeats the ring's word) holds exactly 6 messages (the limit is the whole exchange's: a worker that both passes a message on and answers it branches the ring, and every branch counts against the same 6; the run stops it at 20 messages); `3:seventh-refused` a conversation shows a send refused at the hop limit; `3:another-round` one more line from the person lets the ring pass at least one more, none past hop 6.
-- **4** (refusals, and no delegation): the herald, whose instructions have it call the tool with any id it is given (so the refusal is seen at the tool, not left to a model that skips an id missing from its list), is asked to message Bob's worker and then `eng.coder`. `4:bobs-worker-refused` the message to Bob's worker is refused `no_worker:` and writes no row; `4:create-check` Alice's create at Bob's derived conversation id is refused and Bob holds no session there; `4:coder-refused` a message to `eng.coder` is refused with *file a task*; `4:sender-not-settable` a call naming `from` is never taken, and no row sent from Researcher's conversation names another sender; `4:no-task-row` every row on every conversation's board is one leg 2 or 3b filed.
+- **1** (Alice tells Researcher *"Ask the Shift Coordinator what the codename is, and tell me"*, after telling the coordinator the codename): `1:sent` Researcher's turn messages the coordinator; `1:own-item` the coordinator's conversation holds exactly one received item from Researcher, with its id and no `inReplyTo`, and the coordinator's turn ran for it; `1:answer-holds-codename` a Researcher answer to the person, in a turn after the coordinator's answer landed, holds the codename; `1:coordinator-answered` the coordinator sent Researcher a message back; `1:no-relay` the herald, messaged by Researcher and answering in plain text, has nothing of its answer reach any session.
+- **1b** (the other way, and an answer to a second conversation): `1b:sent` the coordinator, told to tell Researcher a new codename, messages it; `1b:researcher-shows-message` Researcher's conversation shows it as a received item from the coordinator; `1b:next-answer-holds-it` Researcher's next answer to the person holds it; `1b:in-reply-to` the coordinator, asked in its second conversation to ask Helper A something, gets Helper A's answer in that second conversation, naming the question in `inReplyTo`.
+- **2** (from a task): the coordinator's second conversation files Researcher a task to ask Helper A its favourite colour, then message the coordinator that it asked. `2:filed` the coordinator's board holds the task; `2:reached-helper` and `2:from-task` the message to Helper A was sent from the task's own session; `2:to-filer` the task's message to the coordinator lands in the filing conversation, not the default one; `2:answered` Helper A answers it; `2:lands-in-task-session` the answer lands in the task's session it was sent from, even after the task ended, and not in Researcher's own conversation; `2:no-row` Helper A's board holds no row.
+- **2b** (no waiting): Researcher, told to message Helper A with `sendMessage` and wait for the answer: `2b:sent` its turn sends Helper A a message; `2b:turn-ends` its turn ends; `2b:no-wait` no call carrying `wait` was taken, and the answer never lands inside that turn.
+- **3b** (through a delegation): Researcher messages Helper A, Helper A files Helper B a task, Helper B's task messages Researcher. `3b:reached` that message arrives; `3b:counts-on` it is counted in the exchange Researcher's line started: the same chain in the log, at a later hop.
+- **3** (the budget): `3:per-request` the herald, told to message everyone, sends 3 and the rest are refused for the per-request limit; each of Researcher, Helper A and Helper B is told to pass every message on to the next, always, and the ring is started: `3:ring-stops-at-6` the ring's exchange (every message in the chain its first message started, whether or not it repeats the ring's word, including the ones Helper B sends from its ongoing session for Helper A's conversation) holds exactly 6 messages, and a session shows the seventh send refused `budget` (the run stops it at 20); `3:budget-left` each ring message's received item carries a budget that is a number, at least 0, at most 6 minus its hop, and never rising with the hop (a branched ring may leave less than 6 minus its hop); `3:refused-pays-nothing` the herald makes a refused send and then a sent one, and the sent one is the only row, at hop 1.
+- **4** (refusals, and who can be messaged): the herald, whose instructions have it call the tool with any id it is given (so the refusal is seen at the tool, not left to a model that skips an id missing from its list), is asked to message Bob's worker, `eng.coder` and `rr-lead`. `4:bobs-worker-refused` the message to Bob's worker is refused `no_worker:` and writes no row; `4:create-check` Alice's create at Bob's derived conversation id is refused and Bob holds no session there; `4:coder-refused` a message to `eng.coder` is refused `task_sessions_only` and writes no row; `4:round-robin-heard` `rr-lead`'s conversation shows its own turn for the herald's message; `4:sender-not-settable` a call naming `from`, `call` or `budget` is never taken, and no row sent from Researcher's conversation names another sender; `4:hire-refuses` `hireWorkforce` refuses a worker flow without `onMessageReceived` and takes one with it; `4:no-task-row` every row on every conversation's board is one leg 2, 3b or 3 filed (the ring's hand-offs from Helper A to Helper B).
- **5** (after a restart on the same store, in a browser as Alice): `5:lists-every-message` the Messages view lists every message the legs' tool calls say they sent; `5:both-sides` each with sender and recipient; `5:opens-side` the recipient's and the sender's links of Researcher's first message to the coordinator open those sessions, the recipient's showing the line from Researcher.
- **6** (to a task, FIX-2160; sent by the courier, a hire told to make exactly the call it is handed, so a refusal is seen at the tool): the coordinator's conversation files Researcher a task through the board's own action. `6:lands-in-task-session` a `{ task }` message lands in the session the task's run named, as a line from the courier, and the turn that hears it starts after the task's turn ended; `6:finished-keeps-history` once the task finished, a message asking for a word only the task's goal held is answered from that session; `6:task-unchanged` the row's status, attempts, output and session are the same before and after; `6:not-started` a held task's message is refused `no_task_session` and writes no row; `6:bobs-task` Bob's started task is refused with exactly the text an unknown id gets; `6:own-task` a follow-up running in the task's session, told to message its own task, is refused `not_yourself`.
- **7** (to a conversation by id): `7:second-conversation` Researcher, told to message its second conversation with Alice (opened as Shift Manager opens one), lands there; `7:project-conversation` the courier's message to Alice's Storefront project coordinator conversation lands there; `7:refusals` Bob's conversation (`no_session`), a fired worker's (`no_worker`), a moved worker's (`worker_unavailable`), the sending conversation (`not_yourself`), a task's session and a delegate's session (`not_a_conversation`) are each refused and gain no row.
@@ -33,11 +33,17 @@
**Controls:** each is one scratch patch to one Workforce module, applied as the process under test loads it (`goals/lib/module-patch.mjs` through `NODE_OPTIONS`; printed in full by the run, and refused when it never reached the code). A control runs the legs it needs.
-- `GOAL_CONTROL=no-wake`: a message is a line only, never a wake (`messages/worker-message-entry.ts`). Leg 1 must fail **`1:answer-holds-codename`**.
-- `GOAL_CONTROL=drop-ended`: an answer to a message from a task goes back to the task's ended session (`messages/send-message.ts`). Leg 2 must fail **`2:lands-in-own-conversation`**.
-- `GOAL_CONTROL=no-hop-cap`: no hop limit (`messages/send-message.ts`). Leg 3 must fail **`3:ring-stops-at-6`**.
+- `GOAL_CONTROL=relay-back`: the recipient sends every message straight back to its sender, as the relay did (`messages/message-received-entry.ts`). Leg 1 must fail **`1:no-relay`**.
+- `GOAL_CONTROL=no-wake`: a message is a line only, never a wake (`messages/message-received-entry.ts`). Leg 1 must fail **`1:answer-holds-codename`**.
+- `GOAL_CONTROL=answer-to-conversation`: an answer lands in the recipient's own conversation, not the session its original was sent from (`messages/send-message.ts`). Leg 2 must fail **`2:lands-in-task-session`**.
+- `GOAL_CONTROL=ongoing-at-0`: a delegate's ongoing session counts on its own, born at 0, and its task's turn starts there rather than at its filing's count (`conversation-board/board.ts`, `conversation-board/task-entry.ts`). Leg 3 must fail **`3:ring-stops-at-6`**.
+- `GOAL_CONTROL=no-hop-cap`: no budget (`messages/send-message.ts`). Leg 3 must fail **`3:ring-stops-at-6`**.
+- `GOAL_CONTROL=pay-first`: a send takes its place in the chain before the recipient is checked, so a refused send spends one (`messages/send-message.ts`). Leg 3 must fail **`3:refused-pays-nothing`**.
+- `GOAL_CONTROL=fresh-hop-on-task`: a task's session starts a fresh exchange at hop 0 (`conversation-board/task-entry.ts`). Leg 3b must fail **`3b:counts-on`**.
- `GOAL_CONTROL=no-roster-check`: a worker not on the sender's user's roster is taken as theirs (`messages/send-message.ts`). Leg 4 must fail **`4:bobs-worker-refused`**.
-- `GOAL_CONTROL=fresh-hop-on-task`: a task's session starts a fresh exchange at hop 0 (`conversation-board/board.ts`). Leg 3b must fail **`3b:counts-on`**.
+- `GOAL_CONTROL=refuse-at-receive`: the send no longer refuses a worker that hears only in its tasks' sessions, so the row is written and the refusal is left to its entry (`messages/send-message.ts`). Leg 4 must fail **`4:coder-refused`**.
+- `GOAL_CONTROL=no-turn-back`: a coordinator that hands every line on is refused `no_turn`, as before (`messages/send-message.ts`). Leg 4 must fail **`4:round-robin-heard`**.
+- `GOAL_CONTROL=no-hire-check`: `hireWorkforce` takes a worker flow with no `onMessageReceived` (`workers/register.ts`). Leg 4 must fail **`4:hire-refuses`**.
- `GOAL_CONTROL=memory-log`: the log is kept in the server's memory (`messages/message-log.ts`). Leg 5 must fail **`5:lists-every-message`** after the restart.
- `GOAL_CONTROL=task-to-conversation`: a `{ task }` message lands in the conversation that filed the task (`messages/message-target.ts`). Leg 6 must fail **`6:lands-in-task-session`**.
- `GOAL_CONTROL=no-kind-check`: a `{ session }` target isn't checked for a task's or a delegate's session (`messages/message-target.ts`). Leg 7 must fail **`7:refusals`**.
@@ -45,10 +51,11 @@
The spec's other-organization signals (`6:other-org`, and another org's session in `7:refusals`) and its `no-org-check` control are not run here: DevTeam verifies every bearer into its one organization, so no person here has a second one. The engine's `request-sessions.test.ts` covers that refusal.
-**Before-state:** `GOAL_COMMIT=e2ee2c18` is `main` with the spec merged and nothing built. Every leg must fail there: there is no message tool. For legs 6 to 8 (FIX-2160), `GOAL_COMMIT=` is the stack's base: `to` takes a worker's id only, so every leg fails.
+**Before-state:** `GOAL_COMMIT=e2ee2c18` is `main` with FIX-1989's spec merged and nothing built: every leg fails, there is no message tool. For FIX-2238, `main` before it (`e2c190e64`) has no `sendMessage`, so every leg fails, `1:own-item` first. For legs 6 to 8 (FIX-2160), `GOAL_COMMIT=` is the stack's base: `to` takes a worker's id only, so every leg fails.
## Verdict log
| Date | Commit | Model | Verdict | Notes |
|------|--------|-------|---------|-------|
| 2026-10-14 | `590b0c049` (stack head) | workers `openai/gpt-5.4-mini`, coordinator `anthropic/claude-haiku-5-5` | **PASS** | 3 of 3 runs passed every leg (1, 1b, 2, 2b, 3b, 3, 4, 5). Leg 3's exchange held exactly 6 messages each time, with the 7th send refused at the hop limit; in two runs some of the 6 were answers or forwards that didn't repeat the ring's word, which is why the leg counts the exchange by its chain. Every control failed on its assertion, and each patch was confirmed to reach its code: `no-wake` 1:answer-holds-codename (run on `5a9c69710`, whose Workforce code is the same), `drop-ended` 2:lands-in-own-conversation, `no-hop-cap` 3:ring-stops-at-6 (25 messages; the run stopped it at 20), `no-roster-check` 4:bobs-worker-refused, `fresh-hop-on-task` 3b:counts-on (the task's message started a new chain at hop 1), `memory-log` 5:lists-every-message (0 of 2 listed after the restart). Before-state `e2ee2c18`: every leg failed (1, 1b, 2b on their assertions with no tool to call; 2, 3b, 3, 4 threw; 5 found no Messages view). |
| 2026-10-14 | `fd8081663` (stack head) | workers `openai/gpt-5.4-mini`, coordinator `anthropic/claude-haiku-5-5` | **FAIL** | 1, 1b, 2b, 3b, 5 PASS. 2 FAIL `2:answered` (Helper A, woken, answered in plain text instead of calling `messageWorker`; leg 2 passed in 2 of 5 runs). 3 FAIL `3:ring-stops-at-6` (10 passed: woken workers both forwarded and answered, so the ring branched; each branch stopped at the hop limit). 4 FAIL `4:bobs-worker-refused`, `4:coder-refused` (the model declined to call the tool for an id not in its list, so no refusal was seen; leg 4 passed on an earlier run). Every control failed on its assertion: `no-wake` 1:answer-holds-codename, `drop-ended` 2:lands-in-own-conversation, `no-hop-cap` 3:ring-stops-at-6 (46 passed), `no-roster-check` 4:bobs-worker-refused, `fresh-hop-on-task` 3b:hop-2, `memory-log` 5:lists-every-message. Before-state `e2ee2c18`: every leg failed except 2b, which passed with no tool to call; `2b:sent` now requires a message to have gone out. |
+| 2026-10-28 | `570849be4` (#4021, FIX-2238 and its follow-up on `main` with FIX-2160) | workers `openai/gpt-5.4-mini`, coordinator `anthropic/claude-haiku-5-5` | **PASS** for FIX-2238's legs | Legs 1 to 5 passed in 3 runs: on `bfbae4c08` with the follow-up's changes uncommitted, and twice on `570849be4`. A fourth run on `570849be4` failed `3:ring-stops-at-6`: the ring stopped after 3 messages, with no budget refusal, which is a hand-off the model didn't make (the ring stopped at 6 in 5 of 6 full runs this session). Legs 6 to 8 (FIX-2160) ran alongside and failed `6:lands-in-task-session` in 1 of 3 runs on `570849be4`: the message's turn started before the task's turn ended. That was handed on as a FIX-2160 finding. Every FIX-2238 control failed on its assertion (run on `5d7ca952b` / `bfbae4c08`): `relay-back` 1:no-relay, `no-wake` 1:answer-holds-codename, `answer-to-conversation` 2:lands-in-task-session, `ongoing-at-0` and `no-hop-cap` 3:ring-stops-at-6, `pay-first` 3:refused-pays-nothing, `fresh-hop-on-task` 3b:counts-on, `no-roster-check` 4:bobs-worker-refused, `refuse-at-receive` 4:coder-refused, `no-turn-back` 4:round-robin-heard, `no-hire-check` 4:hire-refuses, `memory-log` 5:lists-every-message (0 of 3 listed after the restart). |
From 5bb75da4b235adced2601bebeca5a142012ba953 Mon Sep 17 00:00:00 2001
From: Claude
Date: Wed, 28 Oct 2026 01:56:17 +0000
Subject: [PATCH 14/14] goal(FIX-2238): leg 6's one failure was the goal's
timing, fixed in #4026
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01NczDiDWiB5JZRCvyAFUpe9
---
goals/shift-manager/workers-message-each-other/goal.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/goals/shift-manager/workers-message-each-other/goal.md b/goals/shift-manager/workers-message-each-other/goal.md
index 365f4b5a77..27df299fcf 100644
--- a/goals/shift-manager/workers-message-each-other/goal.md
+++ b/goals/shift-manager/workers-message-each-other/goal.md
@@ -59,4 +59,4 @@ The spec's other-organization signals (`6:other-org`, and another org's session
| 2026-10-14 | `590b0c049` (stack head) | workers `openai/gpt-5.4-mini`, coordinator `anthropic/claude-haiku-5-5` | **PASS** | 3 of 3 runs passed every leg (1, 1b, 2, 2b, 3b, 3, 4, 5). Leg 3's exchange held exactly 6 messages each time, with the 7th send refused at the hop limit; in two runs some of the 6 were answers or forwards that didn't repeat the ring's word, which is why the leg counts the exchange by its chain. Every control failed on its assertion, and each patch was confirmed to reach its code: `no-wake` 1:answer-holds-codename (run on `5a9c69710`, whose Workforce code is the same), `drop-ended` 2:lands-in-own-conversation, `no-hop-cap` 3:ring-stops-at-6 (25 messages; the run stopped it at 20), `no-roster-check` 4:bobs-worker-refused, `fresh-hop-on-task` 3b:counts-on (the task's message started a new chain at hop 1), `memory-log` 5:lists-every-message (0 of 2 listed after the restart). Before-state `e2ee2c18`: every leg failed (1, 1b, 2b on their assertions with no tool to call; 2, 3b, 3, 4 threw; 5 found no Messages view). |
| 2026-10-14 | `fd8081663` (stack head) | workers `openai/gpt-5.4-mini`, coordinator `anthropic/claude-haiku-5-5` | **FAIL** | 1, 1b, 2b, 3b, 5 PASS. 2 FAIL `2:answered` (Helper A, woken, answered in plain text instead of calling `messageWorker`; leg 2 passed in 2 of 5 runs). 3 FAIL `3:ring-stops-at-6` (10 passed: woken workers both forwarded and answered, so the ring branched; each branch stopped at the hop limit). 4 FAIL `4:bobs-worker-refused`, `4:coder-refused` (the model declined to call the tool for an id not in its list, so no refusal was seen; leg 4 passed on an earlier run). Every control failed on its assertion: `no-wake` 1:answer-holds-codename, `drop-ended` 2:lands-in-own-conversation, `no-hop-cap` 3:ring-stops-at-6 (46 passed), `no-roster-check` 4:bobs-worker-refused, `fresh-hop-on-task` 3b:hop-2, `memory-log` 5:lists-every-message. Before-state `e2ee2c18`: every leg failed except 2b, which passed with no tool to call; `2b:sent` now requires a message to have gone out. |
| 2026-10-28 | `3cbab3a64` (main, FIX-2160 merged) | workers `openai/gpt-5.4-mini`, coordinator `anthropic/claude-haiku-5-5` | **PASS** | Legs 6, 7, 8 (FIX-2160): 4 of 4 runs passed (three on the PR's heads `a0149c2d1` and `973404f23`, one on merged `main`). Every control failed on its assertion: `task-to-conversation` 6:lands-in-task-session, `no-kind-check` 7:refusals, `coder-resumes-open` 8:running-refused. The send's own controls were re-anchored to the by-name path and rerun on `main`: `pay-first` 3:refused-pays-nothing, `no-roster-check` 4:bobs-worker-refused, `no-turn-back` 4:round-robin-heard. Before-state `acdd3303c` (FIX-2238's head, `to` takes a worker's id only): 6, 7 and 8 all failed (6 on every signal it checks, 7 on second-conversation, project-conversation and refusals, 8 on finished-answered and running-refused). |
-| 2026-10-28 | `570849be4` (#4021, FIX-2238 and its follow-up on `main` with FIX-2160) | workers `openai/gpt-5.4-mini`, coordinator `anthropic/claude-haiku-5-5` | **PASS** for FIX-2238's legs | Legs 1 to 5 passed in 3 runs: on `bfbae4c08` with the follow-up's changes uncommitted, and twice on `570849be4`. A fourth run on `570849be4` failed `3:ring-stops-at-6`: the ring stopped after 3 messages, with no budget refusal, which is a hand-off the model didn't make (the ring stopped at 6 in 5 of 6 full runs this session). Legs 6 to 8 (FIX-2160) ran alongside and failed `6:lands-in-task-session` in 1 of 3 runs on `570849be4`: the message's turn started before the task's turn ended. That was handed on as a FIX-2160 finding. Every FIX-2238 control failed on its assertion (run on `5d7ca952b` / `bfbae4c08`): `relay-back` 1:no-relay, `no-wake` 1:answer-holds-codename, `answer-to-conversation` 2:lands-in-task-session, `ongoing-at-0` and `no-hop-cap` 3:ring-stops-at-6, `pay-first` 3:refused-pays-nothing, `fresh-hop-on-task` 3b:counts-on, `no-roster-check` 4:bobs-worker-refused, `refuse-at-receive` 4:coder-refused, `no-turn-back` 4:round-robin-heard, `no-hire-check` 4:hire-refuses, `memory-log` 5:lists-every-message (0 of 3 listed after the restart). |
+| 2026-10-28 | `570849be4` (#4021, FIX-2238 and its follow-up on `main` with FIX-2160) | workers `openai/gpt-5.4-mini`, coordinator `anthropic/claude-haiku-5-5` | **PASS** for FIX-2238's legs | Legs 1 to 5 passed in 3 runs: on `bfbae4c08` with the follow-up's changes uncommitted, and twice on `570849be4`. A fourth run on `570849be4` failed `3:ring-stops-at-6`: the ring stopped after 3 messages, with no budget refusal, which is a hand-off the model didn't make (the ring stopped at 6 in 5 of 6 full runs this session). Legs 6 to 8 (FIX-2160) ran alongside and failed `6:lands-in-task-session` in 1 of 3 runs on `570849be4`: by the turn's record, which the engine writes when a deferred request is queued; nothing of the message ran while the task's turn was open, and #4026 times the turn by its first item instead. Every FIX-2238 control failed on its assertion (run on `5d7ca952b` / `bfbae4c08`): `relay-back` 1:no-relay, `no-wake` 1:answer-holds-codename, `answer-to-conversation` 2:lands-in-task-session, `ongoing-at-0` and `no-hop-cap` 3:ring-stops-at-6, `pay-first` 3:refused-pays-nothing, `fresh-hop-on-task` 3b:counts-on, `no-roster-check` 4:bobs-worker-refused, `refuse-at-receive` 4:coder-refused, `no-turn-back` 4:round-robin-heard, `no-hire-check` 4:hire-refuses, `memory-log` 5:lists-every-message (0 of 3 listed after the restart). |