From 60bf7a0865550bc3192b926c9e72e110fed7625d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 00:09:04 +0000 Subject: [PATCH 1/7] feat(FIX-2161): a user's own conversation with a worker opens on a project Adds the server-owned session field workProjectId, written only by the setWorkProject action every worker flow declares (agent, coordinator, Error Reporter), and the client's setWorkProject(worker, project, { sessionId? }). The action admits the session's own user, on a project they are a member of (or own, if private), and refuses the project coordinator's, task, delegate and workstream-lead sessions. filingProjectOf reads workProjectId between projectId and filingProjectId. The board stamps the filer's project on each task row at filing (filedInProject; in a delegate's ongoing session, the held row's stamp); the hand-over copies filingProjectId from that stamp, and runProjectOf's held-row step reads it, so a filed task keeps its project after a change. Rows filed before the stamp existed fall back to the conversation's project (BP-030). Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Qsh48df8qzrorsfaCXn1X7 --- .changeset/conversation-work-project.md | 7 + apps/docs/docs/workforce/projects.md | 49 ++- packages/workforce/README.md | 51 ++- packages/workforce/src/agent-worker-flow.ts | 3 + packages/workforce/src/browser.ts | 12 +- .../src/conversation-board/board-entries.ts | 13 + .../workforce/src/conversation-board/board.ts | 30 +- .../src/conversation-board/filing-session.ts | 10 +- .../src/conversation-board/held-task.ts | 27 ++ .../src/conversation-board/ledger.ts | 7 +- .../src/conversation-board/session-board.ts | 7 +- .../src/coordinator/coordinator-flow.ts | 15 +- packages/workforce/src/error-reporter/flow.ts | 6 +- packages/workforce/src/projects/index.ts | 12 +- .../workforce/src/projects/run-project.ts | 30 +- .../workforce/src/projects/work-project.ts | 94 ++++++ packages/workforce/src/workers/client.ts | 24 +- packages/workforce/src/workers/index.ts | 4 +- .../workforce/src/workers/installation.ts | 14 +- packages/workforce/src/workers/keys.ts | 17 + .../test/agent-worker-memory.test.ts | 12 +- .../test/conversation-board-filing.test.ts | 18 +- packages/workforce/test/work-project.test.ts | 300 ++++++++++++++++++ 23 files changed, 709 insertions(+), 53 deletions(-) create mode 100644 .changeset/conversation-work-project.md create mode 100644 packages/workforce/src/projects/work-project.ts create mode 100644 packages/workforce/test/work-project.test.ts diff --git a/.changeset/conversation-work-project.md b/.changeset/conversation-work-project.md new file mode 100644 index 0000000000..5135fad697 --- /dev/null +++ b/.changeset/conversation-work-project.md @@ -0,0 +1,7 @@ +--- +"@flow-state-dev/workforce": minor +--- + +A user's own conversation with a worker can work in a project (FIX-2161). `createWorkforceClient(...).setWorkProject(worker, { visibility, id }, { sessionId? })` sets it on the user's default conversation with the worker, or on another session of theirs with it, such as a new session just created. The conversation's coding runs, and the tasks it files from then on, work in that project through `projectWorkspace()`. A later call replaces the project; tasks already filed keep the one they were filed in. + +The call is refused, storing nothing, for a project the user isn't a member of (a private one: isn't theirs), and on the project coordinator's, a task's, a delegate's or a workstream lead's session. It runs the `setWorkProject` action (`SET_WORK_PROJECT_ACTION`), which the agent, coordinator and Error Reporter flows declare; an app's own worker flow declares `setWorkProjectAction` under that name. The project is kept in the server-owned session field `workProjectId` (`WORK_PROJECT_STATE_KEY`), which a session create can't seed. diff --git a/apps/docs/docs/workforce/projects.md b/apps/docs/docs/workforce/projects.md index 84c5144c36..7d29cbf2d7 100644 --- a/apps/docs/docs/workforce/projects.md +++ b/apps/docs/docs/workforce/projects.md @@ -631,10 +631,10 @@ harnessManager({ `projectWorkspace` finds the project a run works in, in this order: 1. The workstream the task came from, when it was filed from one. -2. The project the task came from, when it was filed from a project's conversation. -3. The project the task names in `input.project`, by its visibility and id, when it came from a conversation that belongs to no project, such as the user's own coordinator. +2. The project the task came from, when it was filed from a project's conversation, or from a conversation [set to work in a project](#setting-the-project-a-conversation-works-in). +3. The project the task names in `input.project`, by its visibility and id, when it came from a conversation with no project, such as the user's own coordinator until it's set to one. -A task filed from a workstream or a project's conversation is stored naming that project, whatever the filer put in `input.project`. A worker filing from one is told which project it works in, so it doesn't have to name one. +A task filed from a workstream, a project's conversation or a conversation set to a project is stored naming that project, whatever the filer put in `input.project`. A worker filing from one is told which project it works in, so it doesn't have to name one. The run is refused, before any file is read, when: @@ -657,6 +657,49 @@ A coordinator filing for a coding worker from a conversation with no project nam Put `projectWorkspaceCapability` on the harness manager's `uses`, as in the example above. +### Setting the project a conversation works in + +A user's own conversation with a worker can be set to work in one of their projects. From then on, its coding runs and every task it files work in that project, so nobody has to name it in `input.project`. Set it from the app with the workforce client's `setWorkProject`: + +```ts +import { createSessionClient } from "@flow-state-dev/client"; +import { createWorkforceClient } from "@flow-state-dev/workforce/browser"; + +const workforce = createWorkforceClient({ userId, baseUrl, fetcher }); +const sessions = createSessionClient({ baseUrl, fetcher }); +// A worker's one conversation, at the first job that needs files +await workforce.setWorkProject("lead", { visibility: "shared", id: "apollo" }); +// A new session, after the user picks a project +const session = await sessions.createSession({ flowKind: "lab-main", userId, state: { workerId: "main" } }); +await workforce.setWorkProject("main", { visibility: "shared", id: "apollo" }, { sessionId: session.id }); +``` + +Without `sessionId`, it sets the user's default conversation with that worker, creating the conversation if there isn't one. With `sessionId`, it sets that session, which must be the user's own. It resolves to `{ project: { visibility, id } }`. A new session takes two calls, as above: create it, then set its project. A create that puts `workProjectId` in `state` is refused with a 400 naming the field. + +Calling it again with another project replaces the first. Tasks already filed keep the project they were filed in, including one still waiting on the board for a delegate and one handed to a delegate's ongoing session, along with whatever that delegate files while working it. A run that has already started stays where it is. There's no way to clear the project: once set, the conversation always has one. + +The worker flows the package ships take the call as they are: `agent`, `coordinator` and the [Error Reporter](./error-reporter.md)'s flow. A worker flow of your own declares the action under its name: + +```ts +import { SET_WORK_PROJECT_ACTION, setWorkProjectAction } from "@flow-state-dev/workforce"; + +defineFlow({ + // ... + actions: { respond, ...board.actions, [SET_WORK_PROJECT_ACTION]: setWorkProjectAction }, +}); +``` + +A refused call rejects with an `Error` whose message starts `Refused:`, and nothing is stored: + +| Refused when | The message says | +|---|---| +| The project is shared and the user isn't one of its members | `not-a-member` | +| The user has no private project with that id | `you have no private project ""` | +| The organization has no shared project with that id | `this organization has no project "" you can read` | +| The session is a project coordinator's, a task's, a delegate's or a workstream lead's | Which of those it is. Each of them works in the project it was created, filed or opened in. | + +Membership is checked again on every run, so a user removed from the project can't run work there through a conversation set to it earlier. A project coordinator's conversation gets its project from `ensureWorkerSession({ worker, projectId })`, as in [Talking to a project](#talking-to-a-project). + ### Tools a project's coding work gets A project can name MCP servers, and every coding run on the project can use their tools. MCP, the Model Context Protocol, is how an agent reaches a tool outside its checkout: an issue tracker, a docs search, a database. A run gets the project's servers however the work reached it: from a workstream, from the project's conversation, or from a task that names the project. diff --git a/packages/workforce/README.md b/packages/workforce/README.md index bf1971b11d..f5196ed2df 100644 --- a/packages/workforce/README.md +++ b/packages/workforce/README.md @@ -415,7 +415,10 @@ own worker when it is hired or edited. A worker flow declares the installation's session (`session: installation.session()`), so every session names its worker in a readonly `workerId`, checked when the session is created, and loads that worker on every turn with `installation.resolveWorker(ctx, flowKind)`. `hireWorkforce` refuses a -worker flow that doesn't declare it. +worker flow that doesn't declare it. The same session state (`installation.sessionStateShape`) +carries `workProjectId` (`WORK_PROJECT_STATE_KEY`), the project a user set their own conversation +to work in, as `/`. Only the `setWorkProject` action writes it, and a create that +seeds it is refused with a 400 naming the field (see [Projects](#projects)). A worker takes a user's message through its flow's **door**: the one public action the flow declares with `userMessage` and a `{ message }` input. `openInventory` writes it on the worker's @@ -1488,10 +1491,11 @@ defineFlow({ kind: "projects", actions: { ...projects.actions, ...workstreams.ac the repository of the project the run works for, with the project's files beside the checkout, or the project's files alone when it has no repository. A run in a workstream's session, or a task session filed from one, works for that workstream, and is refused `not-the-owner` when the run's - owner isn't the workstream's. A task session filed from a project's conversation works in that - project, and one filed from a conversation with no project works in the project its task names - as `input.project`, for that project's members only (`not-a-member`). A task filed from a - workstream or a project's conversation that names a project in `input.project` is filed naming + owner isn't the workstream's. A task session filed from a project's conversation, or from a + conversation set to a project with `setWorkProject`, works in that project, and one filed from a + conversation with no project works in the project its task names as `input.project`, for that + project's members only (`not-a-member`). A task filed from a workstream, a project's conversation + or a conversation set to a project that names a project in `input.project` is filed naming that conversation's project instead, and a worker filing there is told that project in its task tools' context, so it has no project to name. `no-project` when none applies. The block that asks it must hold `projectWorkspaceCapability`; with harness-manager, pass it on `uses`: @@ -1504,6 +1508,35 @@ defineFlow({ kind: "projects", actions: { ...projects.actions, ...workstreams.ac }); ``` +- **`setWorkProject`**, on the workforce client, sets the project one of the user's own + conversations with a worker works in. From then on its coding runs, and every task it files, work + in that project, as for a project's conversation above: + + ```ts + const workforce = createWorkforceClient({ userId, baseUrl, fetcher }); + const sessions = createSessionClient({ baseUrl, fetcher }); // from @flow-state-dev/client + // A worker's one conversation, at the first job that needs files + await workforce.setWorkProject("lead", { visibility: "shared", id: "apollo" }); + // A new session, after the user picks a project + const session = await sessions.createSession({ flowKind: "lab-main", userId, state: { workerId: "main" } }); + await workforce.setWorkProject("main", { visibility: "shared", id: "apollo" }, { sessionId: session.id }); + ``` + + Without `sessionId` it sets the user's default conversation with the worker, creating it if + there is none. With one, it sets that session, which must be the user's. It resolves to + `{ project }`. Calling it again replaces the project. Tasks already filed keep the project they + were filed in, including one still waiting on the board and one handed to a delegate's ongoing + session, with what that delegate files while working it. A run already started stays where it + is. Nothing clears it. A + refusal rejects with an `Error` whose message starts `Refused:`, and nothing is stored: a shared + project the user isn't a member of (`not-a-member`), a private project that isn't theirs or a + project that doesn't exist, and a project coordinator's, a task's, a delegate's or a workstream + lead's session, each named. Membership is checked again on every run. The action is + `setWorkProject` (`SET_WORK_PROJECT_ACTION`, input `{ project: { visibility, id } }`): the + `agent`, `coordinator` and Error Reporter flows declare it, and a worker flow of your own adds + `[SET_WORK_PROJECT_ACTION]: setWorkProjectAction` to its `actions`. A project coordinator's + conversation takes its project from `ensureWorkerSession({ worker, projectId })` instead. + - **`projectMcpTools(servers, { operator })`** is a resolver for a coding harness's per-run tools, in `claudeCodeAgent`'s `mcpTools` shape. It finds the run's project and owner the way `projectWorkspace()` does, connects to each server the project names in `servers` @@ -2122,7 +2155,8 @@ It exports `createWorkforceClient`, `deriveWorkerSessionId`, `isDerivedWorkerSes `ROSTER_FLOW`, `WORKER_ID_STATE_KEY`, `COORDINATOR_FLOW`, `COORDINATOR_ROUTE`, `COORDINATOR_JUDGMENT` (the 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`, `MESSAGE_WORKER_TOOL` (the +`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`, `WORKER_MESSAGES_RESOURCE` and `workerMessageRowSchema`, the same values the root exports, and reaches no Node built-in. @@ -2148,8 +2182,9 @@ tool a sent message is a call to), `WORKER_MESSAGE_ENTRY`, `WORKER_MESSAGES_PATT | `workerConfigOf(ctx)` | The configuration of the worker the turn loaded, synchronously, for a prompt, a tool list or a step condition. Throws when the turn loaded no worker: call `installation.resolveWorker` in the flow's `request.onStarted`. | | `createWorkerHireBlocks(installation)` | `{ hire, fork, edit, fire }`: writes to the caller's own roster, each checked as a turn would check it before anything is written, each refusing a standard worker's id. | | `defineWorkerRosterFlow(installation, actions?)` | The roster flow (`workforce-roster`), which declares the two worker collections so a client reads a user's roster through one session of it. Mount the hire blocks on it as actions. | -| `createWorkforceClient({ userId, baseUrl?, apiPath?, fetcher? })` | `roster()`, `findWorkerSession(criteria)`, `ensureWorkerSession(criteria)` and `standingRules(worker, input)` (see [Standing rules](#standing-rules)), over the session and resource clients. `criteria` is a `WorkerSessionCriteria`: `worker`, and optional keys such as `projectId`, which finds or starts the user's project coordinator for that project. From `./browser` only. | +| `createWorkforceClient({ userId, baseUrl?, apiPath?, fetcher? })` | `roster()`, `findWorkerSession(criteria)`, `ensureWorkerSession(criteria)`, `standingRules(worker, input)` (see [Standing rules](#standing-rules)) and `setWorkProject(worker, { visibility, id }, { sessionId? })` (see [Projects](#projects)), over the session and resource clients. `criteria` is a `WorkerSessionCriteria`: `worker`, and optional keys such as `projectId`, which finds or starts the user's project coordinator for that project. From `./browser` only. | | `RULE_TOOLS`, `MAX_RULES`, `MAX_RULE_CHARS`, `STANDING_RULES_ACTION`, `STANDING_RULES_LINE`, `STANDING_RULES_RESOURCE` | The four rule tools' names, the list's limits (20 and 300), the flow action `standingRules` calls, the `agentName` a rule write's line carries, and the resource the list is kept under. All but `STANDING_RULES_RESOURCE` are also exported from `./browser`. | +| `SET_WORK_PROJECT_ACTION` / `setWorkProjectAction` / `WORK_PROJECT_STATE_KEY` | The action `setWorkProject` calls (`"setWorkProject"`), the action itself for a worker flow of your own to declare under that name, and the server-owned session-state field it writes (`"workProjectId"`, `/`). The two constants are also exported from `./browser`. | | `deriveWorkerSessionId({ userId, orgId, flow, criteria })` / `isDerivedWorkerSessionId(id)` | The id `ensureWorkerSession` creates a session at, and the shape a worker flow's create check reserves for the user it derives to. | | `WorkerTurnRefusedError` | What `resolveWorker` throws when a turn can't run as the session's worker; nothing is written. | | `defineWorkerCollection()` / `workerRowSchema` / `parseWorkerRow(value)` | The user's worker collection at `workforce/workers/*`, user scope, and its row. | @@ -2201,7 +2236,7 @@ tool a sent message is a call to), `WORKER_MESSAGE_ENTRY`, `WORKER_MESSAGES_PATT | `parseWorkstreamEntry(path, state)` | One entry read off its storage key and checked against `workstreamEntrySchema`, with its `project`, `owner` and `id`; `undefined` for a key that isn't an entry. Also from `./browser`, for a browser reading entries through the resource routes. | | `projectCoordinatorTools` | `{ readProject }`, the project coordinator's tool, which marks each workstream `yours` when the user it talks to owns it: put it in `defineCoordinatorFlow({ agent: { catalog } })` and name it in the coordinator's `tools:`. Add `setBrief` and `setRepository` from `defineProjectBlocks()` for it to manage its own project. | | `linkedProjectOf(state)` | The `{ visibility, id }` a session's state links it to by its `projectId`, or `undefined`. | -| `projectWorkspace({ checkouts? })` / `projectWorkspaceCapability` / `ProjectCheckout` | A run source for a coding run on a project: from the workstream its session leads or was filed from, the project its conversation belongs to, or the project its task names. `checkouts` (`ProjectCheckout[]`: `{ remote, checkout, projects, baseRef? }`) sends the listed shared projects' runs, in their own organization, to a checkout on this machine. The capability holds the collections it reads. See [Projects](#projects). | +| `projectWorkspace({ checkouts? })` / `projectWorkspaceCapability` / `ProjectCheckout` | A run source for a coding run on a project: from the workstream its session leads or was filed from, the project its conversation belongs to or was set to, or the project its task names. `checkouts` (`ProjectCheckout[]`: `{ remote, checkout, projects, baseRef? }`) sends the listed shared projects' runs, in their own organization, to a checkout on this machine. The capability holds the collections it reads. See [Projects](#projects). | | `createWorkerLookup({ installation })` | Which standard worker a task's name means. Returns `{ find, flowKind, state, filingCheck }`. `find(name)` answers `{ found: true, flowId }`, or `{ found: false, reason, message }` with `reason` `not-found` or `takes-no-tasks` (a worker whose flow declares no `work` task entry). `flowKind` and `state` are a `per-task` dispatcher's targets: the flow of the worker the task's `assignee` names, and a starting state naming that worker. | | `WORKER_TASK_ENTRY` | `"work"`, the task entry a worker flow takes tasks through. | | `workerTaskEntry({ name, turn \| block })` / `WorkerTaskEntryOptions` / `WorkerTaskBlockInput` / `conversationLedgers` / `filingConversationBoard` | The `work` task entry for a worker flow of your own: `task: { actions: { work: workerTaskEntry({ name, turn }) } }`. Each task a coordinator files for one of its workers runs as one `turn` (`{ message }` in, the answer out), or, with `block` instead (one or the other, refused at build otherwise), as a block handed the task itself plus `claim` (`{ collectionId, partition, incarnationId }`, the board the task was claimed from, never read from the task), in a task session of its own, and the conversation that filed it is told when it ends. A flow whose `work` entry is built any other way takes no conversation task: `listDelegates` reports it as taking `nothing`, and a filing for it is refused. `conversationLedgers(ledgerId, ctx, partition)` finds the board of the conversation a task came from; pass it to a harness manager that takes tasks from conversations. `filingConversationBoard(ctx)` answers, in a task session, that conversation's board with the entry and flow that run it there (`{ tasks, runEntry, filingFlow, filingSession }`), for a door over the session's run (`harnessSessionDoor`'s `board`). A coding run's `projectWorkspace()` finds its project from the filing workstream, then the project of the conversation that filed it, then the task's `input.project` (`{ visibility, id }`, checked against the run's own user), then the `board` claim. | diff --git a/packages/workforce/src/agent-worker-flow.ts b/packages/workforce/src/agent-worker-flow.ts index 05c7c9f453..9c02b1763d 100644 --- a/packages/workforce/src/agent-worker-flow.ts +++ b/packages/workforce/src/agent-worker-flow.ts @@ -104,6 +104,8 @@ import { turnConfigOf, verifiedWorkerOf } from "./workers/verified-worker"; import { markUserTurnStep } from "./standing-rules/user-turn"; import { standingRulesCapability } from "./standing-rules/rules-capability"; import { STANDING_RULES_ACTION, standingRulesAction } from "./standing-rules/rules-action"; +import { setWorkProjectAction } from "./projects/work-project"; +import { SET_WORK_PROJECT_ACTION } from "./workers/keys"; import type { WorkerInstallation } from "./workers/installation"; import { steerOrTalk } from "./conversation-board/steer"; import { worksConversationResultTask } from "./conversation-board/task-admission"; @@ -1354,6 +1356,7 @@ function defineAgentFlowAround( concurrency: REPLY_CONCURRENCY }, [STANDING_RULES_ACTION]: standingRulesAction, + [SET_WORK_PROJECT_ACTION]: setWorkProjectAction, // On an installation: the task actions (`updateTask_tasks` and the // rest) over this session's board, and the four delegate actions. A // session whose delegates take no task answers `no_delegation_board`. diff --git a/packages/workforce/src/browser.ts b/packages/workforce/src/browser.ts index 43e983b3fa..17e8d72198 100644 --- a/packages/workforce/src/browser.ts +++ b/packages/workforce/src/browser.ts @@ -29,7 +29,17 @@ export { isDerivedWorkerSessionId, type WorkerSessionCriteria } from "./workers/derive-session-id"; -export { FILING_SESSION_STATE_KEY, PROJECT_STATE_KEY, ROSTER_FLOW, TASK_ID_STATE_KEY, WORKER_ID_STATE_KEY, WORKSTREAM_STATE_KEY } from "./workers/keys"; +export { + FILING_SESSION_STATE_KEY, + PROJECT_STATE_KEY, + ROSTER_FLOW, + SET_WORK_PROJECT_ACTION, + TASK_ID_STATE_KEY, + WORK_PROJECT_STATE_KEY, + WORKER_ID_STATE_KEY, + WORKSTREAM_STATE_KEY +} from "./workers/keys"; +export type { SetWorkProjectOutput } from "./projects/work-project"; export { sessionIdOfFiling } from "./conversation-board/filing-session"; export { parseProjectRef, diff --git a/packages/workforce/src/conversation-board/board-entries.ts b/packages/workforce/src/conversation-board/board-entries.ts index b2e92926c6..9b6a71bb00 100644 --- a/packages/workforce/src/conversation-board/board-entries.ts +++ b/packages/workforce/src/conversation-board/board-entries.ts @@ -76,3 +76,16 @@ export const FILED_MARKER = "filedFrom"; * reads its session's count, as before (BP-030). */ export const FILED_HOP = "filedAtHop"; + +/** + * The metadata key on a task's row naming the project it was filed in + * (FIX-2161), in `projectRef` form: the filing session's project + * (`filingProjectOf`), or, in a delegate's ongoing session, the stamp on the + * task that session holds. The hand-over copies it onto the task session as + * `filingProjectId`, and a held row's run reads it, so a task keeps its + * project when its conversation's project changes. Server-written by the + * filing; a caller's filing or patch never reaches it. `null` on a row filed + * with no project. **Absent** on a row filed before rows carried it, whose + * hand-over reads its conversation's project, as before (BP-030). + */ +export const FILED_PROJECT = "filedInProject"; diff --git a/packages/workforce/src/conversation-board/board.ts b/packages/workforce/src/conversation-board/board.ts index fc884e52a9..5e8d2181bb 100644 --- a/packages/workforce/src/conversation-board/board.ts +++ b/packages/workforce/src/conversation-board/board.ts @@ -133,7 +133,7 @@ import { TASK_ID_STATE_KEY, WORKER_ID_STATE_KEY } from "../workers/keys"; -import { FILED_HOP, PIECE_OF, DISPATCH_ENTRY } from "./board-entries"; +import { FILED_HOP, FILED_PROJECT, PIECE_OF, DISPATCH_ENTRY } from "./board-entries"; import { DEFAULT_TASK_CHAIN_LIMIT, MAX_TASK_DEPTH, @@ -159,7 +159,7 @@ import { startOwedSteerTurn } from "./steer-turn-start"; import { holdRoutedSession, routedSessionResources, sessionsHeldElsewhere } from "./routed-session"; import { conversationDelivery } from "./delivery"; import { owedReports, sendLegacyReports } from "./report-owed"; -import { pieceOwnerOf } from "./held-task"; +import { filedProjectOf, filingProjectStampOf, isStamped, pieceOwnerOf } from "./held-task"; import { PLAN_LEDGER_ID, STEP_ATTEMPTS, definePlanning, isAnsweringTurn, isSteppingTurn, planLedgerAt, planLedgerResources } from "./plan"; import { verifiedWorkerOf } from "../workers/verified-worker"; @@ -372,6 +372,19 @@ async function sessionSettingOf(ctx: BlockContext, taskId: string): Promise { + const ref = await conversationLedgerAt(ctx, await filingSessionIdOf(ctx.session)); + const row = ref?.get(taskId); + return isStamped(row) ? filedProjectOf(row) : filingProjectOf(ctx.session.state); +} + /** * The claim the board's dispatch holds while it addresses a task: on its * worker body's state, or in the claimed worker's async scope. Server-derived: @@ -893,7 +906,7 @@ export function defineConversationBoard(options: ConversationBoardOptions) { // hand-over has already opened it, so this is only ever the root. const taskId = claimOf(ctx)?.followUpOf ?? task.taskId; const workstream = filingWorkstreamOf(ctx.session.state); - const project = filingProjectOf(ctx.session.state); + const project = await handedProjectOf(ctx, taskId); return { [WORKER_ID_STATE_KEY]: task.assignee, [FILING_SESSION_STATE_KEY]: partition, @@ -1066,7 +1079,13 @@ export function defineConversationBoard(options: ConversationBoardOptions) { const owner = await pieceOwnerOf(ctx); const given = callerMetadata(init.metadata); // The filing turn's hop count, which the task's turn starts at (FIX-2106). - const metadata = { ...(given ?? {}), ...(owner === undefined ? {} : { [PIECE_OF]: owner }), [FILED_HOP]: turnHopMark(ctx) }; + // And the project it is filed in, which it keeps if the conversation's changes (FIX-2161). + const metadata = { + ...(given ?? {}), + ...(owner === undefined ? {} : { [PIECE_OF]: owner }), + [FILED_HOP]: turnHopMark(ctx), + [FILED_PROJECT]: await filingProjectStampOf(ctx) + }; const input = ownProjectIn(init.input, filingProjectAddressOf(ctx.session.state)); // The task this piece is for learns where its session is first, so its // ending's cascade can reach the piece (FIX-2080 D2). @@ -1658,7 +1677,8 @@ export function defineConversationBoard(options: ConversationBoardOptions) { // What a model asked beside the message is a caller's, as on any filing: // 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 metadata = { ...callerMetadata(filing.metadata), [FILED_HOP]: turnHopMark(ctx) }; + // And the project it is filed in, which it keeps if the conversation's changes (FIX-2161). + const metadata = { ...callerMetadata(filing.metadata), [FILED_HOP]: turnHopMark(ctx), [FILED_PROJECT]: await filingProjectStampOf(ctx) }; const input = ownProjectIn(filing.input, filingProjectAddressOf(ctx.session.state)); const { metadata: _metadata, input: _input, ...rest } = filing; const init: TaskInit & { id: string } = { diff --git a/packages/workforce/src/conversation-board/filing-session.ts b/packages/workforce/src/conversation-board/filing-session.ts index 33945f69ea..0343923904 100644 --- a/packages/workforce/src/conversation-board/filing-session.ts +++ b/packages/workforce/src/conversation-board/filing-session.ts @@ -13,6 +13,7 @@ import { FILING_PROJECT_STATE_KEY, FILING_WORKSTREAM_STATE_KEY, PROJECT_STATE_KEY, + WORK_PROJECT_STATE_KEY, WORKSTREAM_STATE_KEY } from "../workers/keys"; import { parseProjectRef, parseWorkstreamRef, type ProjectAddressRef } from "../projects/workstream-ref"; @@ -32,13 +33,18 @@ export function filingWorkstreamOf(state: unknown): string | undefined { /** * The project a session works in, from its server-written fields: the one it - * is the conversation of (`projectId`), else the one it was filed from - * (`filingProjectId`), in `projectRef` form. `undefined` for neither. + * is the coordinator conversation of (`projectId`), else the one its user + * set it to work in (`workProjectId`, FIX-2161), else the one it was filed + * from (`filingProjectId`), in `projectRef` form. `undefined` for none. The + * work-project action refuses a session carrying either of the others, so no + * two meet on one session. */ export function filingProjectOf(state: unknown): string | undefined { const fields = state as Record | undefined; const own = fields?.[PROJECT_STATE_KEY]; if (typeof own === "string") return own; + const set = fields?.[WORK_PROJECT_STATE_KEY]; + if (typeof set === "string") return set; const filed = fields?.[FILING_PROJECT_STATE_KEY]; return typeof filed === "string" ? filed : undefined; } diff --git a/packages/workforce/src/conversation-board/held-task.ts b/packages/workforce/src/conversation-board/held-task.ts index 8f2b3d7738..d9e834d6c0 100644 --- a/packages/workforce/src/conversation-board/held-task.ts +++ b/packages/workforce/src/conversation-board/held-task.ts @@ -7,6 +7,8 @@ import type { BlockContext } from "@flow-state-dev/core/types"; import type { Task, TaskCollectionRef } from "@flow-state-dev/orchestration/tasks"; import { TASK_ID_STATE_KEY } from "../workers/keys"; import { boardAboveOf } from "./board-above"; +import { FILED_PROJECT } from "./board-entries"; +import { filingProjectOf } from "./filing-session"; import { conversationLedgerAt } from "./ledger"; import { currentWorkerClaim } from "@flow-state-dev/orchestration/task-board"; @@ -47,3 +49,28 @@ export async function heldTask(ctx: BlockContext): Promise<{ ref: TaskCollection export async function pieceOwnerOf(ctx: BlockContext): Promise { return (await heldTask(ctx))?.row.id ?? stringAt(ctx, TASK_ID_STATE_KEY); } + +/** + * The project a task's row was stamped with when it was filed (FIX-2161), in + * `projectRef` form: `undefined` for a row filed with no project, and for a + * row filed before rows carried the stamp (see {@link isStamped}). + */ +export function filedProjectOf(row: Pick | undefined): string | undefined { + const stamp = row?.metadata?.[FILED_PROJECT]; + return typeof stamp === "string" ? stamp : undefined; +} + +/** Whether a task's row carries the project stamp, even an empty one: one filed before rows carried it doesn't (BP-030). */ +export function isStamped(row: Pick | undefined): boolean { + return row?.metadata != null && Object.hasOwn(row.metadata, FILED_PROJECT); +} + +/** + * The project a task filed now in the running session is stamped with: the + * session's own (`filingProjectOf`), else, in a delegate's ongoing session, + * which has none of its own, the stamp on the task this request holds, so a + * piece filed there carries its project on. `null` for none. + */ +export async function filingProjectStampOf(ctx: BlockContext): Promise { + return filingProjectOf(ctx.session.state) ?? filedProjectOf((await heldTask(ctx))?.row) ?? null; +} diff --git a/packages/workforce/src/conversation-board/ledger.ts b/packages/workforce/src/conversation-board/ledger.ts index 0f72c42aa4..384c6ce56f 100644 --- a/packages/workforce/src/conversation-board/ledger.ts +++ b/packages/workforce/src/conversation-board/ledger.ts @@ -42,7 +42,7 @@ import { type TaskSettingsSupport, withoutNoticeMarkers } from "@flow-state-dev/orchestration/tasks"; -import { FILED_HOP, FILED_MARKER, PIECE_OF, RETRY_OF, SPLIT_MARKER } from "./board-entries"; +import { FILED_HOP, FILED_MARKER, FILED_PROJECT, PIECE_OF, RETRY_OF, SPLIT_MARKER } from "./board-entries"; import { filedCascadeOver } from "./cascade"; import { filingSessionIdOf } from "./filing-session"; import { withoutReportMarkers } from "./report-owed"; @@ -162,7 +162,8 @@ export async function ownConversationLedger(ctx: BlockContext): Promise> | undefined @@ -170,6 +171,6 @@ export function callerMetadata( const unmarked = withoutNoticeMarkers(metadata); if (unmarked === undefined) return unmarked; const kept = withoutReportMarkers(unmarked); - const { [SPLIT_MARKER]: _split, [PIECE_OF]: _piece, [RETRY_OF]: _retry, [FILED_MARKER]: _filed, [FILED_HOP]: _hop, ...rest } = kept; + const { [SPLIT_MARKER]: _split, [PIECE_OF]: _piece, [RETRY_OF]: _retry, [FILED_MARKER]: _filed, [FILED_HOP]: _hop, [FILED_PROJECT]: _project, ...rest } = kept; return rest; } diff --git a/packages/workforce/src/conversation-board/session-board.ts b/packages/workforce/src/conversation-board/session-board.ts index b31f5d9f40..6e5132ffa1 100644 --- a/packages/workforce/src/conversation-board/session-board.ts +++ b/packages/workforce/src/conversation-board/session-board.ts @@ -53,7 +53,7 @@ import { WORKER_MESSAGE_ENTRY } from "../messages/keys"; import { workerMessageEntry, workerMessageSeenStateShape } from "../messages/worker-message-entry"; import { fileScheduledTaskEntry } from "../schedules/file-scheduled-task"; import { FILE_SCHEDULED_TASK_ENTRY } from "../schedules/keys"; -import { ROUTED_FROM_STATE_KEY } from "../workers/keys"; +import { ROUTED_FROM_STATE_KEY, WORK_PROJECT_STATE_KEY } from "../workers/keys"; import { taskChainLimitOf } from "../workers/chain-limit"; import { markRolePiece, takesTasks } from "../worker-roles"; import type { WorkerInstallation } from "../workers/installation"; @@ -101,7 +101,10 @@ export const SESSION_BOARD_SERVER_OWNED: readonly string[] = [ ROUTED_FROM_STATE_KEY, // A plan writes it while it waits on a step in a session of its own (FIX-2113). A seeded key // naming a request that never ends here would hold the session's notices with no live wait. - PLAN_WAITING_STATE + PLAN_WAITING_STATE, + // Not the board's: the work-project action writes it after a membership check (FIX-2161). Here so + // every flow declaring this list, with a board or without, refuses it on a caller's create. + WORK_PROJECT_STATE_KEY ]; /** What a session board is built from. */ diff --git a/packages/workforce/src/coordinator/coordinator-flow.ts b/packages/workforce/src/coordinator/coordinator-flow.ts index e035b08daf..17e49c17f6 100644 --- a/packages/workforce/src/coordinator/coordinator-flow.ts +++ b/packages/workforce/src/coordinator/coordinator-flow.ts @@ -128,7 +128,8 @@ import { RESPOND_ACTION } from "../worker-door"; import { declareBuiltInRoles, markRolePiece } from "../worker-roles"; import { reportRescuedFailure } from "../error-reporter/rescued"; import { verifiedWorkerOf, workerConfigOf } from "../workers/verified-worker"; -import { ROUTED_FROM_STATE_KEY, WORKER_ID_STATE_KEY } from "../workers/keys"; +import { ROUTED_FROM_STATE_KEY, SET_WORK_PROJECT_ACTION, WORK_PROJECT_STATE_KEY, WORKER_ID_STATE_KEY } from "../workers/keys"; +import { setWorkProjectAction } from "../projects/work-project"; import type { RosterWorker, WorkerInstallation } from "../workers/installation"; import { coordinatorConfigProblems, @@ -1708,7 +1709,14 @@ export function defineCoordinatorFlow(options: CoordinatorFlowOptions) { session: { ...installation.session({ ...coordinatorStateShape, ...conversationBoardStateShape, ...workerMessageStateShape }), // The board's `routedFrom` too: no caller names the conversation a routed task came from (BP-031). - serverOwned: [...COORDINATOR_SERVER_OWNED, ...CONVERSATION_BOARD_SERVER_OWNED, ...WORKER_MESSAGE_SERVER_OWNED, ROUTED_FROM_STATE_KEY], + // And `workProjectId`: only the work-project action sets the project a conversation works in (FIX-2161). + serverOwned: [ + ...COORDINATOR_SERVER_OWNED, + ...CONVERSATION_BOARD_SERVER_OWNED, + ...WORKER_MESSAGE_SERVER_OWNED, + ROUTED_FROM_STATE_KEY, + WORK_PROJECT_STATE_KEY + ], // Every answer, routing and pass-on writes this one record at once; a pass-on that // runs out of retries fails after its round has closed, and its answers are lost. cas: { maxRetries: 8 } @@ -1727,7 +1735,8 @@ export function defineCoordinatorFlow(options: CoordinatorFlowOptions) { userMessage: (input: DoorInput) => input.message, concurrency: REPLY_CONCURRENCY }, - [STANDING_RULES_ACTION]: standingRulesAction + [STANDING_RULES_ACTION]: standingRulesAction, + [SET_WORK_PROJECT_ACTION]: setWorkProjectAction }, internal: { actions: { diff --git a/packages/workforce/src/error-reporter/flow.ts b/packages/workforce/src/error-reporter/flow.ts index 4463a7a409..21f6400c35 100644 --- a/packages/workforce/src/error-reporter/flow.ts +++ b/packages/workforce/src/error-reporter/flow.ts @@ -12,10 +12,11 @@ import { MCP_CREDENTIALS_RESOURCE } from "../projects/mcp-credentials"; import { readStandingRules } from "../standing-rules/rules-record"; import { renderRules } from "../standing-rules/rules-list"; import { STANDING_RULES_ACTION, standingRulesAction } from "../standing-rules/rules-action"; +import { setWorkProjectAction } from "../projects/work-project"; import { markUserTurnStep } from "../standing-rules/user-turn"; import { turnConfigOf } from "../workers/verified-worker"; import type { WorkerInstallation } from "../workers/installation"; -import { PROJECT_STATE_KEY } from "../workers/keys"; +import { PROJECT_STATE_KEY, SET_WORK_PROJECT_ACTION } from "../workers/keys"; import { defineMcpCredentialsCollection } from "../projects/mcp-credentials"; import { conversationLedgerAt, conversationLedgerResources } from "../conversation-board/ledger"; import { reportOwedKey } from "../conversation-board/report-owed"; @@ -718,7 +719,8 @@ export function defineErrorReporterFlow(options: ErrorReporterFlowOptions) { // Public so its preview is answerable from Inbox (a dispatched run is never reopened from outside). // It takes no input, runs only in a report's own session, and only for the operator. [REPORT_ENTRY]: { inputSchema: reportInputSchema, block: report, onErrored: releaseClaim }, - [STANDING_RULES_ACTION]: standingRulesAction + [STANDING_RULES_ACTION]: standingRulesAction, + [SET_WORK_PROJECT_ACTION]: setWorkProjectAction }, internal: { actions: { diff --git a/packages/workforce/src/projects/index.ts b/packages/workforce/src/projects/index.ts index 3fc133858e..26371e4c46 100644 --- a/packages/workforce/src/projects/index.ts +++ b/packages/workforce/src/projects/index.ts @@ -11,7 +11,8 @@ * of a project's files; `run-project.ts` for the one read of a coding run's * project and owner; `project-workspace.ts` for the run source a coding run * gets its files from; `project-mcp-tools.ts` and `mcp-credentials.ts` for the - * MCP servers a run gets and each user's keys for them. + * MCP servers a run gets and each user's keys for them; `work-project.ts` for + * the action that sets the project a user's conversation works in. */ export { @@ -172,3 +173,12 @@ export { type ProjectWorkspaceOptions, type ProjectWorkspaceRefusalReason } from "./project-workspace"; + +export { + setWorkProjectAction, + setWorkProjectBlock, + setWorkProjectInputSchema, + setWorkProjectOutputSchema, + type SetWorkProjectInput, + type SetWorkProjectOutput +} from "./work-project"; diff --git a/packages/workforce/src/projects/run-project.ts b/packages/workforce/src/projects/run-project.ts index 0455b5daa5..8a584c2a01 100644 --- a/packages/workforce/src/projects/run-project.ts +++ b/packages/workforce/src/projects/run-project.ts @@ -8,11 +8,15 @@ * * 1. the workstream the run's session leads, or the one its task was filed * from (`workstreamId` / `filingWorkstreamId`); - * 2. the project the task was filed from (`filingProjectId`); - * 3. the project the held task names in `input.project`, by visibility and id. + * 2. the session's own project: the project coordinator's (`projectId`), the + * one its user set (`workProjectId`), or the one its task was filed from + * (`filingProjectId`); + * 3. the held task's: the project its row was stamped with when it was filed + * (a delegate's ongoing session has none of its own), else the one it + * names in `input.project`, by visibility and id. * * Every step reads stored, server-written data (BP-031): the session's - * readonly fields, the workstream entry, the project row and the row the + * server-written fields, the held row's filing stamp, the workstream entry, the project row and the row the * claim gate verified for this run. The owner is the request's resolved user, * checked against the workstream's owner or the project's members, never a * field of the task or a hand-over's payload. @@ -22,12 +26,13 @@ import type { LooseBlockContext } from "@flow-state-dev/core"; import type { BlockContext } from "@flow-state-dev/core/types"; import type { RunSourceRefusal } from "@flow-state-dev/workspace"; import { filingProjectAddressOf, filingProjectOf, filingWorkstreamOf } from "../conversation-board/filing-session"; -import { heldTask } from "../conversation-board/held-task"; +import { filedProjectOf, heldTask } from "../conversation-board/held-task"; +import type { Task } from "@flow-state-dev/orchestration/tasks"; import { projectAddressSchema, projectRowSchema, type ProjectAddress, type ProjectRow, type ProjectVisibility } from "./collections"; import { isMember } from "./membership-gate"; import { projectRowsAt, workstreamsAt, type MissingCollection } from "./project-address"; import { workstreamEntryKey } from "./workstream-collections"; -import { parseWorkstreamRef, type WorkstreamAddress } from "./workstream-ref"; +import { parseProjectRef, parseWorkstreamRef, type WorkstreamAddress } from "./workstream-ref"; /** * Why a run's project lookup refused. The refusal's `message` names the @@ -58,7 +63,8 @@ export interface RunProject { * @returns The project, its visibility and the run's owner, or a refusal. */ export async function runProjectOf(ctx: LooseBlockContext): Promise { - const named = await namedProjectOf(ctx); + const held = (await heldTask(ctx as unknown as BlockContext))?.row; + const named = namedProjectOf(held); if (named.kind === "malformed") return named.refusal; // The session's project address is the one the board writes on a task it // files (`filingProjectAddressOf`), so the two can't disagree. @@ -71,6 +77,13 @@ export async function runProjectOf(ctx: LooseBlockContext): Promise { - const held = await heldTask(ctx as unknown as BlockContext); - const input = held?.row.input as { project?: unknown } | null | undefined; +function namedProjectOf(held: Task | undefined): NamedProject { + const input = held?.input as { project?: unknown } | null | undefined; if (input == null || typeof input !== "object" || input.project == null) return { kind: "none" }; const parsed = projectAddressSchema.safeParse(input.project); if (parsed.success) return { kind: "named", address: parsed.data }; diff --git a/packages/workforce/src/projects/work-project.ts b/packages/workforce/src/projects/work-project.ts new file mode 100644 index 0000000000..17b859ea5f --- /dev/null +++ b/packages/workforce/src/projects/work-project.ts @@ -0,0 +1,94 @@ +/** + * The work-project action (FIX-2161): how a user sets the project one of + * their own conversations with a worker works in, a new session of the worker + * or the worker's one default conversation, from the screen. + * + * Declared on every worker flow, beside the standing-rules action, and run in + * the conversation it sets. It writes the session's server-owned + * `workProjectId`, which `filingProjectOf` reads, so the conversation's runs + * and the tasks it files work in that project. It admits only: + * + * - the session's own user, on a project they may work in: a member of a + * shared one, the owner of a private one, the rule `runProjectOf` checks + * at every run; + * - a user's own conversation: never the project coordinator's, a task's, + * a delegate's or a workstream lead's session, which take their project + * from where they were created, filed or opened. + * + * The input names the project and nothing else (BP-031). A refusal fails the + * request with its reason and stores nothing. Setting another project later + * replaces it; the tasks already filed keep the one stamped on their rows. + */ +import { handler } from "@flow-state-dev/core"; +import { z } from "zod"; +import { + FILING_PROJECT_STATE_KEY, + FILING_SESSION_STATE_KEY, + FILING_WORKSTREAM_STATE_KEY, + PROJECT_STATE_KEY, + TASK_ID_STATE_KEY, + WORK_PROJECT_STATE_KEY, + WORKER_ID_STATE_KEY, + WORKSTREAM_STATE_KEY +} from "../workers/keys"; +import { projectAddressSchema, projectRowSchema } from "./collections"; +import { isMember } from "./membership-gate"; +import { PROJECT_ROW_RESOURCES, projectRowsAt } from "./project-address"; +import { projectRef } from "./workstream-ref"; + +/** What the action takes: the project, by visibility and id. */ +export const setWorkProjectInputSchema = z.object({ project: projectAddressSchema }).strict(); + +export type SetWorkProjectInput = z.infer; + +/** What the action answers: the project the conversation now works in. */ +export const setWorkProjectOutputSchema = z.object({ project: projectAddressSchema }); + +export type SetWorkProjectOutput = z.infer; + +/** The session fields that make a session someone else's than the user's own conversation, and what each one is. */ +const LINKED: ReadonlyArray = [ + [PROJECT_STATE_KEY, "a project coordinator's session, which is linked to its project when it is created"], + [TASK_ID_STATE_KEY, "a task's session, which works in the project its task was filed in"], + [FILING_PROJECT_STATE_KEY, "a task's session, which works in the project its task was filed in"], + [FILING_WORKSTREAM_STATE_KEY, "a task's session, which works in its workstream's project"], + [FILING_SESSION_STATE_KEY, "a delegate's session, which works in the project of the task it holds"], + [WORKSTREAM_STATE_KEY, "a workstream lead's session, which works in its workstream's project"] +]; + +const refuse = (message: string): never => { + throw new Error(`Refused: ${message}`); +}; + +/** The action's block. */ +export const setWorkProjectBlock = handler({ + name: "set-work-project", + inputSchema: setWorkProjectInputSchema, + outputSchema: setWorkProjectOutputSchema, + resources: { ...PROJECT_ROW_RESOURCES }, + execute: async (input, ctx) => { + const state = (ctx.session.state ?? {}) as Record; + if (typeof state[WORKER_ID_STATE_KEY] !== "string") refuse("this session runs no worker, so it has no project to set."); + for (const [key, what] of LINKED) { + if (state[key] !== undefined) refuse(`this is ${what}. Its project can't be set.`); + } + const user = ctx.user?.identity?.userId; + const owner = ctx.session.identity.userId; + if (user === undefined || user !== owner) refuse("only the session's own user sets the project it works in."); + const { visibility, id } = input.project; + const stored = await projectRowsAt(ctx, visibility).getOptional(id); + if (stored === undefined) { + refuse( + visibility === "private" ? `you have no private project "${id}".` : `this organization has no project "${id}" you can read.` + ); + } + const row = projectRowSchema.parse(stored!.state); + const allowed = visibility === "private" ? row.ownerUserId === user : isMember(row, user); + if (!allowed) refuse(`not-a-member: "${user}" is not a member of project "${id}", so this conversation can't work in it.`); + await ctx.session.patchState({ [WORK_PROJECT_STATE_KEY]: projectRef(input.project) }); + return { project: input.project }; + } +}); + +/** The action, as a worker flow declares it under `SET_WORK_PROJECT_ACTION`. */ +export const setWorkProjectAction = { inputSchema: setWorkProjectInputSchema, block: setWorkProjectBlock }; diff --git a/packages/workforce/src/workers/client.ts b/packages/workforce/src/workers/client.ts index 0d068f9f92..8e3bcb7aef 100644 --- a/packages/workforce/src/workers/client.ts +++ b/packages/workforce/src/workers/client.ts @@ -26,9 +26,10 @@ import { } from "./derive-session-id"; import { ownerSegment } from "@flow-state-dev/core/types"; import { workstreamsAccessor, workstreamStorageKey, type WorkstreamAddress } from "../projects/workstream-ref"; -import { FILING_SESSION_STATE_KEY, ROSTER_FLOW, STANDARD_WORKERS_RESOURCE, WORKERS_RESOURCE } from "./keys"; +import { FILING_SESSION_STATE_KEY, ROSTER_FLOW, SET_WORK_PROJECT_ACTION, STANDARD_WORKERS_RESOURCE, WORKERS_RESOURCE } from "./keys"; import { STANDING_RULES_ACTION } from "../standing-rules/keys"; import type { StandingRulesActionInput, StandingRulesActionOutput } from "../standing-rules/rules-action"; +import type { SetWorkProjectOutput } from "../projects/work-project"; /** The transport options `createSessionClient` takes, plus the user the client acts for. */ export type WorkforceClientOptions = { @@ -98,6 +99,22 @@ export interface WorkforceClient { * reason and stores nothing. */ standingRules(worker: string, input: StandingRulesActionInput): Promise; + /** + * Set the project one of the user's own conversations with `worker` works + * in: its runs, and the tasks it files from now on. With no `sessionId`, + * the user's default conversation with the worker (created when there is + * none); with one, that session of the user's, such as a new session just + * created. A later call replaces the project; tasks already filed keep the + * one they were filed in. Rejects, storing nothing, for a project the user + * isn't a member of (a private one: isn't theirs), and for a session that + * isn't the user's own conversation: the project coordinator's, a task's, + * a delegate's or a workstream lead's. + */ + setWorkProject( + worker: string, + project: { visibility: "shared" | "private"; id: string }, + options?: { sessionId?: string } + ): Promise; } function stateOf(session: SessionSummary): Record { @@ -332,6 +349,11 @@ export function createWorkforceClient(options: WorkforceClientOptions): Workforc const session = await client.ensureWorkerSession({ worker }); const flow = flowOf(await readRoster((await roster()).id), worker); return (await runIn(flow, session.id, STANDING_RULES_ACTION, input)) as StandingRulesActionOutput; + }, + setWorkProject: async (worker, project, setOptions) => { + const sessionId = setOptions?.sessionId ?? (await client.ensureWorkerSession({ worker })).id; + const flow = flowOf(await readRoster((await roster()).id), worker); + return (await runIn(flow, sessionId, SET_WORK_PROJECT_ACTION, { project })) as SetWorkProjectOutput; } }; return client; diff --git a/packages/workforce/src/workers/index.ts b/packages/workforce/src/workers/index.ts index 465c0093cf..aff94c13a2 100644 --- a/packages/workforce/src/workers/index.ts +++ b/packages/workforce/src/workers/index.ts @@ -25,12 +25,14 @@ export { FILING_WORKSTREAM_STATE_KEY, PROJECT_STATE_KEY, ROSTER_FLOW, + SET_WORK_PROJECT_ACTION, STANDARD_WORKERS_PATTERN, STANDARD_WORKERS_RESOURCE, TASK_ID_STATE_KEY, WORKERS_PATTERN, WORKERS_RESOURCE, - WORKER_ID_STATE_KEY + WORKER_ID_STATE_KEY, + WORK_PROJECT_STATE_KEY } from "./keys"; export { deriveWorkerSessionId, diff --git a/packages/workforce/src/workers/installation.ts b/packages/workforce/src/workers/installation.ts index dc6eec7e43..2ec6d3c034 100644 --- a/packages/workforce/src/workers/installation.ts +++ b/packages/workforce/src/workers/installation.ts @@ -57,7 +57,8 @@ import { TASK_ID_STATE_KEY, WORKERS_RESOURCE, WORKER_ID_STATE_KEY, - WORKSTREAM_STATE_KEY + WORKSTREAM_STATE_KEY, + WORK_PROJECT_STATE_KEY } from "./keys"; import { COORDINATOR_FLOW } from "../coordinator/coordinator-keys"; import { PRIVATE_PROJECTS_RESOURCE, PROJECTS_RESOURCE } from "../projects/collections"; @@ -225,6 +226,7 @@ export type WorkerSessionStateShape = { readonly [FILING_WORKSTREAM_STATE_KEY]: z.ZodOptional>; readonly [FILING_PROJECT_STATE_KEY]: z.ZodOptional>; readonly [PROJECT_STATE_KEY]: z.ZodOptional>; + readonly [WORK_PROJECT_STATE_KEY]: z.ZodOptional; }; /** The installation's worker model. Build it once, at boot. */ @@ -251,7 +253,9 @@ export interface WorkerInstallation extends WorkerGrants { * session leads; `taskId`, when a conversation's board handed a task over, * names the task the session works, `filingWorkstreamId` the workstream * it was filed from, and `filingProjectId` the project; `projectId`, on a - * project coordinator's session, names its project. + * project coordinator's session, names its project; `workProjectId`, on a + * user's own conversation, names the project they set it to work in + * (not readonly: the work-project action writes and replaces it). */ readonly sessionStateShape: WorkerSessionStateShape; /** The create check a worker flow declares as `session.createCheck`. */ @@ -260,7 +264,7 @@ export interface WorkerInstallation extends WorkerGrants { * A worker flow's `session` declaration: {@link sessionStateShape} plus * `extraShape` as its `stateSchema`, {@link createCheck}, and as * `serverOwned` the delegate and board fields only the server writes - * ({@link SESSION_BOARD_SERVER_OWNED}). A flow without those fields still refuses a + * ({@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. */ session>( @@ -459,7 +463,9 @@ export function createWorkerInstallation(options: WorkerInstallationOptions = {} [TASK_FLOW_STATE_KEY]: z.string().min(1).readonly().optional(), [FILING_WORKSTREAM_STATE_KEY]: z.string().min(1).readonly().optional(), [FILING_PROJECT_STATE_KEY]: z.string().min(1).readonly().optional(), - [PROJECT_STATE_KEY]: z.string().min(1).readonly().optional() + [PROJECT_STATE_KEY]: z.string().min(1).readonly().optional(), + // Written only by the work-project action (FIX-2161): server-owned, and changeable. + [WORK_PROJECT_STATE_KEY]: z.string().min(1).optional() } as const; /** Every resource a worker may be granted: the documents and the references. */ diff --git a/packages/workforce/src/workers/keys.ts b/packages/workforce/src/workers/keys.ts index 164fd29b5b..6629483412 100644 --- a/packages/workforce/src/workers/keys.ts +++ b/packages/workforce/src/workers/keys.ts @@ -79,6 +79,23 @@ export const ROUTED_FROM_STATE_KEY = "routedFrom"; */ export const PROJECT_STATE_KEY = "projectId"; +/** + * The session-state field that names the project a user's own conversation + * with a worker works in (FIX-2161): a new session of the worker, or the + * worker's one default conversation. `projectRef` form, + * `/`. Written only by the {@link SET_WORK_PROJECT_ACTION} + * action, which checks the user is a member of the project, and declared + * server-owned, so no create can seed it. Not readonly: the user can set + * another project later, and the tasks already filed keep the one they were + * filed in. Never on a project coordinator's, a task's, a delegate's or a + * workstream lead's session, which take their project from where they were + * created, filed or opened. + */ +export const WORK_PROJECT_STATE_KEY = "workProjectId"; + +/** The action that sets {@link WORK_PROJECT_STATE_KEY} on the session it runs in. Every worker flow declares it. */ +export const SET_WORK_PROJECT_ACTION = "setWorkProject"; + /** * The session-state field that names the workstream a task session works * for: the one its filer leads, or its filer's own, carried down at each diff --git a/packages/workforce/test/agent-worker-memory.test.ts b/packages/workforce/test/agent-worker-memory.test.ts index a21ae4f3ed..1a5755462b 100644 --- a/packages/workforce/test/agent-worker-memory.test.ts +++ b/packages/workforce/test/agent-worker-memory.test.ts @@ -234,8 +234,16 @@ describe("memory attaches to the built-in agent worker flow by composition", () // tasks off are the whole resource surface — no memory store is declared // anywhere in the default worker flow. // The standing-rules record is the worker's notes for each user, not memory (FIX-1945), and the - // routed-session record is which routed task a workstream's session works (FIX-2083). - expect(Object.keys(plain!.resources ?? {}).sort()).toEqual(["skills", "standing-rules", "tasks", "workforceRoutedSessions"]); + // routed-session record is which routed task a workstream's session works (FIX-2083). The + // project rows are what the work-project action checks a user's membership against (FIX-2161). + expect(Object.keys(plain!.resources ?? {}).sort()).toEqual([ + "privateProjects", + "projects", + "skills", + "standing-rules", + "tasks", + "workforceRoutedSessions" + ]); // Nothing runs after the answer — the sequence is what it was. const children = stepNames(plain!.actions.respond!.block); expect(children.some((name) => name.startsWith("memory/"))).toBe(false); diff --git a/packages/workforce/test/conversation-board-filing.test.ts b/packages/workforce/test/conversation-board-filing.test.ts index 2b7e2cf6aa..79d8aab4cd 100644 --- a/packages/workforce/test/conversation-board-filing.test.ts +++ b/packages/workforce/test/conversation-board-filing.test.ts @@ -12,7 +12,7 @@ import { describe, expect, it } from "vitest"; import { encodeUserSegment } from "@flow-state-dev/core/types"; import { mockGenerator } from "@flow-state-dev/testing"; import { bootBoardHost, messageOf, type BoardHost } from "./conversation-board-harness"; -import { FILED_HOP } from "../src/conversation-board/board-entries"; +import { FILED_HOP, FILED_PROJECT } from "../src/conversation-board/board-entries"; const file = async (host: BoardHost, userId: string, conv: string, input: Record) => { const result = await host.act(userId, conv, "createTask_tasks", input); @@ -259,24 +259,30 @@ describe("what a filing can't name (BR-8)", () => { board: "elsewhere", partition: "someone-else", owner: "bob", - metadata: { "noticeOwed:1:completed": { attempt: 1, ending: "completed" }, note: "kept" } + metadata: { "noticeOwed:1:completed": { attempt: 1, ending: "completed" }, note: "kept", [FILED_PROJECT]: "shared/elsewhere" } }); expect(filed.ok).toBe(true); const rows = await host.rows("alice"); expect(rows).toHaveLength(1); const filing = await host.filingOf("alice", conv); const row = await host.row("alice", filing, filed.taskId!); - // The one marker on it is the board's own: the filing turn's hop count (FIX-2106). - expect(row?.metadata).toEqual({ note: "kept", [FILED_HOP]: { hop: 0, chain: null, lines: 0 } }); + // 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 }); // No start was owed, so nothing ran: the row has no assignee. await host.settled(); expect(host.runs).toEqual([]); // An update can't reach a marker either. await host.act("alice", conv, "updateTask_tasks", { id: filed.taskId, - metadata: { "noticeOwed:1:errored": { attempt: 1, ending: "errored" }, extra: 1 } + metadata: { "noticeOwed:1:errored": { attempt: 1, ending: "errored" }, extra: 1, [FILED_PROJECT]: "shared/elsewhere" } + }); + expect((await host.row("alice", filing, filed.taskId!))?.metadata).toEqual({ + note: "kept", + extra: 1, + [FILED_HOP]: { hop: 0, chain: null, lines: 0 }, + [FILED_PROJECT]: null }); - expect((await host.row("alice", filing, filed.taskId!))?.metadata).toEqual({ note: "kept", extra: 1, [FILED_HOP]: { hop: 0, chain: null, lines: 0 } }); } finally { await host.dispose(); } diff --git a/packages/workforce/test/work-project.test.ts b/packages/workforce/test/work-project.test.ts new file mode 100644 index 0000000000..447a37e68d --- /dev/null +++ b/packages/workforce/test/work-project.test.ts @@ -0,0 +1,300 @@ +/** + * A user's own conversation with a worker opens on a project (FIX-2161), + * on the real engine and HTTP router, through the workforce client: + * `setWorkProject` stores the project on the conversation, checked against + * the user's membership, and the tasks the conversation files run there. + * + * Each delegate's turn asks `runProjectOf` the way a coding run's would, and + * keeps what it answered; every assertion reads that answer or the client's, + * never a stored key. + */ +import { describe, expect, it } from "vitest"; +import { defineFlow, handler } from "@flow-state-dev/core"; +import type { BlockContext } from "@flow-state-dev/core/types"; +import { mockGenerator } from "@flow-state-dev/testing"; +import { z } from "zod"; +import { createWorkforceClient } from "../src/browser"; +import { + COORDINATOR_FLOW, + defineCoordinatorFlow, + defineProjectBlocks, + defineSessionBoard, + defineWorkstreamBlocks, + projectWorkspaceCapability, + SET_WORK_PROJECT_ACTION, + setWorkProjectAction, + WORKER_TASK_ENTRY, + workerConfigSchema, + WORKSTREAM_OPENED_ENTRY, + workstreamOpenedEntry +} from "../src/index"; +import { heldTask } from "../src/conversation-board/held-task"; +import { workerTaskEntry } from "../src/conversation-board/task-entry"; +import type { WorkerManifest } from "../src/manifest"; +import { PROJECT_ROW_RESOURCES } from "../src/projects/project-address"; +import { runProjectOf } from "../src/projects/run-project"; +import type { WorkerInstallation } from "../src/workers/installation"; +import { bootProjectsHost, ORG } from "./projects-harness"; + +const doorInput = z.object({ message: z.string() }); +type Address = { visibility: "shared" | "private"; id: string }; + +/** One run of a delegate: where it ran, the task it held, and what `runProjectOf` answered. */ +type Run = { worker: string; sessionId: string; state: Record; goal: string | undefined; answer: unknown }; + +/** A plain view of `runProjectOf`'s answer. */ +function view(found: Awaited>) { + if (found.kind === "refused") return { kind: "refused", reason: found.reason }; + return { kind: "found", project: `${found.visibility}/${found.project.id}`, owner: found.owner }; +} + +/** A workstream lead's flow: an app's own worker flow, declaring the action as every worker flow does. */ +function filerFlow(installation: WorkerInstallation) { + const board = defineSessionBoard({ installation, flowKind: "filer" }); + const door = handler({ + name: "filer-run", + inputSchema: doorInput, + resources: { ...installation.resources }, + execute: async (_input, ctx) => (await installation.resolveWorker(ctx, "filer")).id + }); + return defineFlow({ + kind: "filer", + configSchema: workerConfigSchema(), + session: { ...installation.session(board.sessionStateShape), serverOwned: [...board.serverOwned] }, + resources: { ...installation.resources, ...board.resources, ...PROJECT_ROW_RESOURCES }, + actions: { + respond: { inputSchema: doorInput, block: door, userMessage: (i: { message: string }) => i.message }, + ...board.actions, + [SET_WORK_PROJECT_ACTION]: setWorkProjectAction + }, + internal: { actions: { ...board.entries(door), [WORKSTREAM_OPENED_ENTRY]: workstreamOpenedEntry() } } + } as never); +} + +/** + * The delegates' flow. A turn asks `runProjectOf` and keeps its answer; a + * turn holding a task whose goal starts "split" files one piece for + * `eng.coder` through its own board first, once. + */ +function takerFlow(installation: WorkerInstallation, runs: Run[]) { + const board = defineSessionBoard({ installation, flowKind: "taker" }); + const split = new Set(); + const turn = handler({ + name: "taker-turn", + inputSchema: doorInput, + uses: [projectWorkspaceCapability], + resources: { ...installation.resources, ...board.resources }, + execute: async (_input, rawCtx) => { + const ctx = rawCtx as unknown as BlockContext; + const worker = (await installation.resolveWorker(rawCtx, "taker")).id; + const held = (await heldTask(ctx))?.row; + runs.push({ + worker, + sessionId: ctx.session.identity.id, + state: { ...(ctx.session.state as object) }, + goal: held?.goal, + answer: view(await runProjectOf(ctx as never)) + }); + if (held !== undefined && held.goal.startsWith("split") && !split.has(held.id)) { + split.add(held.id); + const ref = await board.board.resolver(ctx as never); + await ref!.addTask({ goal: `piece of ${held.goal}`, assignee: "eng.coder" }); + } + return "asked"; + } + }); + return defineFlow({ + kind: "taker", + configSchema: workerConfigSchema(), + session: { ...installation.session(board.sessionStateShape), serverOwned: [...board.serverOwned] }, + resources: { ...installation.resources, ...board.resources }, + actions: { + respond: { inputSchema: doorInput, block: turn, userMessage: (i: { message: string }) => i.message }, + ...board.actions, + [SET_WORK_PROJECT_ACTION]: setWorkProjectAction + }, + internal: { actions: board.entries(turn) }, + task: { actions: { [WORKER_TASK_ENTRY]: workerTaskEntry({ name: "taker-task", turn }) } } + } as never); +} + +const PROJECT_COORDINATOR = "pc"; +const worker = (id: string, declared: Record): WorkerManifest => ({ id, declared, body: "", skills: [] }); +const standardWorkers: WorkerManifest[] = [ + worker(PROJECT_COORDINATOR, { flow: COORDINATOR_FLOW, delegates: ["eng.taker"] }), + // Two task-taking delegates, so a task filed with no assignee waits on the board. + worker("lead", { flow: COORDINATOR_FLOW, delegates: ["eng.taker", "eng.coder"] }), + worker("main", { flow: COORDINATOR_FLOW, delegates: ["eng.taker"] }), + worker("eng.taker", { flow: "taker", description: "Takes tasks.", delegates: ["eng.coder"] }), + worker("eng.coder", { flow: "taker", description: "Codes." }) +]; + +async function boot() { + const runs: Run[] = []; + const projects = defineProjectBlocks(); + const judgment = mockGenerator({ script: [{ when: () => true, then: { text: "Noted." } }] }); + const filerRef = { kind: "filer", internal: { actions: { [WORKSTREAM_OPENED_ENTRY]: {} } } }; + const h = await bootProjectsHost({ + standardWorkers, + projectCoordinator: PROJECT_COORDINATOR, + lab: (installation) => ({ ...projects.actions, ...defineWorkstreamBlocks({ installation, leadFlows: [filerRef] }).actions }), + flows: (installation) => ({ + filer: { flow: filerFlow(installation), roles: ["manager"] }, + taker: { flow: takerFlow(installation, runs), roles: ["contributor", "manager"] }, + [COORDINATOR_FLOW]: defineCoordinatorFlow({ installation, routeModel: "typesafe-ai/jev" }) + }), + models: { generators: { "coordinator-judgment": judgment } } + }); + const settled = async () => { + const deadline = Date.now() + 10_000; + for (;;) { + const all = await h.runtime.stores.request.list({}); + if (!all.some((request: { status: string }) => request.status === "in_progress")) return; + if (Date.now() > deadline) throw new Error("a request never finished"); + await new Promise((resolve) => setTimeout(resolve, 10)); + } + }; + const client = (user: string) => createWorkforceClient({ userId: user, fetcher: h.fetcherFor(user, ORG) }); + const createProject = async (user: string, input: Record) => + h.ok(user, "lab", await h.openSession(user, "lab"), "createProject", input); + /** File `goal` from `session` (on the coordinator flow) and wait for every run it starts. */ + const file = async (user: string, session: string, goal: string, settings: Record = { assignee: "eng.taker" }) => { + const filed = (await h.ok(user, COORDINATOR_FLOW, session, "createTask_tasks", { goal, ...settings })) as { ok: boolean; taskId: string }; + expect(filed).toMatchObject({ ok: true }); + await settled(); + return filed.taskId; + }; + /** What the run of the task whose goal is `goal` answered. */ + const answerOf = (goal: string) => { + const found = runs.filter((run) => run.goal === goal); + expect(found, `runs of "${goal}"`).toHaveLength(1); + return found[0]!.answer; + }; + return { ...h, runs, client, createProject, file, settled, answerOf }; +} + +const apollo: Address = { visibility: "shared", id: "apollo" }; +const beta: Address = { visibility: "shared", id: "beta" }; +const inApollo = { kind: "found", project: "shared/apollo", owner: "alice" }; +const inBeta = { kind: "found", project: "shared/beta", owner: "alice" }; + +async function withProjects() { + const h = await boot(); + await h.createProject("alice", { id: "apollo", title: "Apollo" }); + await h.createProject("alice", { id: "beta", title: "Beta" }); + await h.createProject("bob", { id: "bobs", title: "Bob's", visibility: "private" }); + return h; +} + +describe("a user's conversation with a worker, set to a project", () => { + it("default: the worker's one conversation, set after it has talked, files a task that runs in the project", async () => { + const h = await withProjects(); + const alice = h.client("alice"); + const lead = await alice.ensureWorkerSession({ worker: "lead" }); + await h.ok("alice", COORDINATOR_FLOW, lead.id, "respond", { message: "hi" }); + + expect(await alice.setWorkProject("lead", apollo)).toEqual({ project: apollo }); + await h.file("alice", lead.id, "look at the repo"); + expect(h.answerOf("look at the repo")).toEqual(inApollo); + // The task's session was handed the project, readonly. + expect(h.runs[0]!.state).toMatchObject({ filingProjectId: "shared/apollo" }); + }); + + it("new-session: a session of the worker created at its own id, then set, runs its tasks in the project", async () => { + const h = await withProjects(); + const session = await h.openSession("alice", COORDINATOR_FLOW, { workerId: "main" }); + await h.client("alice").setWorkProject("main", apollo, { sessionId: session }); + await h.file("alice", session, "look at the repo"); + expect(h.answerOf("look at the repo")).toEqual(inApollo); + }); + + it("change: a task filed before the change keeps its project, and one filed after takes the new one", async () => { + const h = await withProjects(); + const alice = h.client("alice"); + const lead = (await alice.ensureWorkerSession({ worker: "lead" })).id; + await alice.setWorkProject("lead", apollo); + await h.file("alice", lead, "first"); + expect(await alice.setWorkProject("lead", beta)).toEqual({ project: beta }); + await h.file("alice", lead, "second"); + expect(h.answerOf("first")).toEqual(inApollo); + expect(h.answerOf("second")).toEqual(inBeta); + }); + + it("waiting: a task filed under one project and assigned after the change still runs in the first", async () => { + const h = await withProjects(); + const alice = h.client("alice"); + const lead = (await alice.ensureWorkerSession({ worker: "lead" })).id; + await alice.setWorkProject("lead", apollo); + // Two delegates take tasks, so a task with no assignee waits on the board. + const waiting = await h.file("alice", lead, "waiting", {}); + expect(h.runs).toHaveLength(0); + await alice.setWorkProject("lead", beta); + await h.ok("alice", COORDINATOR_FLOW, lead, "updateTask_tasks", { id: waiting, assignee: "eng.taker" }); + await h.settled(); + expect(h.answerOf("waiting")).toEqual(inApollo); + }); + + it("ongoing: a task routed to a delegate's ongoing session runs in the project, and so does a piece it files", async () => { + const h = await withProjects(); + const alice = h.client("alice"); + const lead = (await alice.ensureWorkerSession({ worker: "lead" })).id; + await alice.setWorkProject("lead", apollo); + await h.file("alice", lead, "split the work", { assignee: "eng.taker", session: "ongoing", resultTo: "conversation" }); + const ongoing = h.runs.find((run) => run.goal === "split the work")!; + // The delegate's ongoing session works no one task: it carries no project of its own. + expect(ongoing.state).not.toHaveProperty("taskId"); + expect(ongoing.state).not.toHaveProperty("filingProjectId"); + expect(ongoing.answer).toEqual(inApollo); + // One hop further down: the piece it filed while holding the task. + expect(h.answerOf("piece of split the work")).toEqual(inApollo); + }); + + it("not-a-member: a reader who isn't a member is refused, another user's private project isn't found, and nothing is stored", async () => { + const h = await withProjects(); + const carol = h.client("carol"); + const lead = (await carol.ensureWorkerSession({ worker: "lead" })).id; + await expect(carol.setWorkProject("lead", apollo)).rejects.toThrow(/not-a-member/); + await expect(h.client("alice").setWorkProject("lead", { visibility: "private", id: "bobs" })).rejects.toThrow( + /no private project "bobs"/ + ); + await h.file("carol", lead, "look at the repo"); + expect(h.answerOf("look at the repo")).toEqual({ kind: "refused", reason: "no-project" }); + }); + + it("not-seeded: a create that seeds the field is refused", async () => { + const h = await withProjects(); + const forged = await h.tryOpenSession("alice", COORDINATOR_FLOW, { workerId: "main", workProjectId: "shared/apollo" }); + expect(forged.status).toBe(400); + expect(JSON.stringify(forged.json)).toContain("workProjectId"); + }); + + it("not-these: the project coordinator's, a task's and a workstream lead's sessions are refused", async () => { + const h = await withProjects(); + const alice = h.client("alice"); + const pc = await alice.ensureWorkerSession({ worker: PROJECT_COORDINATOR, projectId: apollo }); + await expect(alice.setWorkProject(PROJECT_COORDINATOR, beta, { sessionId: pc.id })).rejects.toThrow(/a project coordinator's session/); + + const lead = (await alice.ensureWorkerSession({ worker: "lead" })).id; + await h.file("alice", lead, "look at the repo"); + const task = h.runs[0]!.sessionId; + await expect(alice.setWorkProject("eng.taker", beta, { sessionId: task })).rejects.toThrow(/a task's session/); + + const roster = await h.openSession("alice", "workforce-roster"); + await h.ok("alice", "workforce-roster", roster, "hire", { id: "alice-filer", flow: "filer", settings: { delegates: ["eng.taker"] } }); + const opened = (await h.ok("alice", "lab", await h.openSession("alice", "lab"), "openWorkstream", { + project: apollo, + id: "ws", + title: "ws", + lead: "alice-filer" + })) as { workstream: { sessionId: string } }; + await expect(alice.setWorkProject("alice-filer", beta, { sessionId: opened.workstream.sessionId })).rejects.toThrow(/a workstream lead's session/); + }); + + it("messages: setting the project leaves the conversation where messages land", async () => { + const h = await withProjects(); + const alice = h.client("alice"); + const before = await alice.ensureWorkerSession({ worker: "lead" }); + await alice.setWorkProject("lead", apollo); + expect((await alice.findWorkerSession({ worker: "lead" }))?.id).toBe(before.id); + }); +}); From fc0c10a1b32e9bcaecb1caaa34e204bd508e2ef0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 00:13:38 +0000 Subject: [PATCH 2/7] test(FIX-2161): name the not-a-member leg without the retired word Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Qsh48df8qzrorsfaCXn1X7 --- packages/workforce/test/work-project.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/workforce/test/work-project.test.ts b/packages/workforce/test/work-project.test.ts index 447a37e68d..03490b49cf 100644 --- a/packages/workforce/test/work-project.test.ts +++ b/packages/workforce/test/work-project.test.ts @@ -249,7 +249,7 @@ describe("a user's conversation with a worker, set to a project", () => { expect(h.answerOf("piece of split the work")).toEqual(inApollo); }); - it("not-a-member: a reader who isn't a member is refused, another user's private project isn't found, and nothing is stored", async () => { + it("not-a-member: a reader of the project who may not work in it is refused, another user's private project isn't found, and nothing is stored", async () => { const h = await withProjects(); const carol = h.client("carol"); const lead = (await carol.ensureWorkerSession({ worker: "lead" })).id; From a3d82e2a97aa483c65b2ef2942a3b25e9b9cae9f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 00:14:18 +0000 Subject: [PATCH 3/7] refactor(FIX-2161): narrow the stored row without a non-null assertion Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Qsh48df8qzrorsfaCXn1X7 --- packages/workforce/src/projects/work-project.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/workforce/src/projects/work-project.ts b/packages/workforce/src/projects/work-project.ts index 17b859ea5f..05dae03898 100644 --- a/packages/workforce/src/projects/work-project.ts +++ b/packages/workforce/src/projects/work-project.ts @@ -46,7 +46,11 @@ export const setWorkProjectOutputSchema = z.object({ project: projectAddressSche export type SetWorkProjectOutput = z.infer; -/** The session fields that make a session someone else's than the user's own conversation, and what each one is. */ +/** + * The session fields that make a session someone else's than the user's own conversation, and what + * each one is. A task session carries `taskId` and `filingProjectId` both, and a step's session + * `taskId` alone; each is listed, so either one refuses. + */ const LINKED: ReadonlyArray = [ [PROJECT_STATE_KEY, "a project coordinator's session, which is linked to its project when it is created"], [TASK_ID_STATE_KEY, "a task's session, which works in the project its task was filed in"], @@ -56,9 +60,9 @@ const LINKED: ReadonlyArray = [ [WORKSTREAM_STATE_KEY, "a workstream lead's session, which works in its workstream's project"] ]; -const refuse = (message: string): never => { +function refuse(message: string): never { throw new Error(`Refused: ${message}`); -}; +} /** The action's block. */ export const setWorkProjectBlock = handler({ @@ -82,7 +86,7 @@ export const setWorkProjectBlock = handler({ visibility === "private" ? `you have no private project "${id}".` : `this organization has no project "${id}" you can read.` ); } - const row = projectRowSchema.parse(stored!.state); + const row = projectRowSchema.parse(stored.state); const allowed = visibility === "private" ? row.ownerUserId === user : isMember(row, user); if (!allowed) refuse(`not-a-member: "${user}" is not a member of project "${id}", so this conversation can't work in it.`); await ctx.session.patchState({ [WORK_PROJECT_STATE_KEY]: projectRef(input.project) }); From 830e10f6d5d18c46195af8c82fb09eb6138268fa Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 00:18:43 +0000 Subject: [PATCH 4/7] fix(FIX-2161): carry the held project into a new-session step, refuse report sessions A step a delegate files for itself in a session of its own, from an ongoing session, now takes the held task's stamped project instead of none. The Error Reporter flow refuses setWorkProject on its report sessions. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Qsh48df8qzrorsfaCXn1X7 --- .../workforce/src/conversation-board/board.ts | 3 +- packages/workforce/src/error-reporter/flow.ts | 10 ++- packages/workforce/src/projects/index.ts | 1 + .../workforce/src/projects/work-project.ts | 70 +++++++++++-------- .../workforce/test/error-reporter.test.ts | 17 +++++ packages/workforce/test/projects-harness.ts | 3 + packages/workforce/test/work-project.test.ts | 36 ++++++++-- 7 files changed, 102 insertions(+), 38 deletions(-) diff --git a/packages/workforce/src/conversation-board/board.ts b/packages/workforce/src/conversation-board/board.ts index 5e8d2181bb..972edbb1cd 100644 --- a/packages/workforce/src/conversation-board/board.ts +++ b/packages/workforce/src/conversation-board/board.ts @@ -765,7 +765,8 @@ export function defineConversationBoard(options: ConversationBoardOptions) { state: async (task, ctx) => { const partition = await filingSessionIdOf(ctx.session); const workstream = filingWorkstreamOf(ctx.session.state); - const project = filingProjectOf(ctx.session.state); + // The session's project, or, in a delegate's ongoing session, the held task's (FIX-2161). + const project = (await filingProjectStampOf(ctx)) ?? undefined; return { [WORKER_ID_STATE_KEY]: task.assignee, [FILING_SESSION_STATE_KEY]: partition, diff --git a/packages/workforce/src/error-reporter/flow.ts b/packages/workforce/src/error-reporter/flow.ts index 21f6400c35..7f59e931df 100644 --- a/packages/workforce/src/error-reporter/flow.ts +++ b/packages/workforce/src/error-reporter/flow.ts @@ -12,7 +12,7 @@ import { MCP_CREDENTIALS_RESOURCE } from "../projects/mcp-credentials"; import { readStandingRules } from "../standing-rules/rules-record"; import { renderRules } from "../standing-rules/rules-list"; import { STANDING_RULES_ACTION, standingRulesAction } from "../standing-rules/rules-action"; -import { setWorkProjectAction } from "../projects/work-project"; +import { defineSetWorkProjectBlock, setWorkProjectInputSchema } from "../projects/work-project"; import { markUserTurnStep } from "../standing-rules/user-turn"; import { turnConfigOf } from "../workers/verified-worker"; import type { WorkerInstallation } from "../workers/installation"; @@ -720,7 +720,13 @@ export function defineErrorReporterFlow(options: ErrorReporterFlowOptions) { // It takes no input, runs only in a report's own session, and only for the operator. [REPORT_ENTRY]: { inputSchema: reportInputSchema, block: report, onErrored: releaseClaim }, [STANDING_RULES_ACTION]: standingRulesAction, - [SET_WORK_PROJECT_ACTION]: setWorkProjectAction + // Never on a report's session, which the reporter opens for its own work (FIX-2161). + [SET_WORK_PROJECT_ACTION]: { + inputSchema: setWorkProjectInputSchema, + block: defineSetWorkProjectBlock((id) => + reportIdOfSession(id) === undefined ? undefined : "an error report's session, which the Error Reporter opens for its own work" + ) + } }, internal: { actions: { diff --git a/packages/workforce/src/projects/index.ts b/packages/workforce/src/projects/index.ts index 26371e4c46..f47fa8ba12 100644 --- a/packages/workforce/src/projects/index.ts +++ b/packages/workforce/src/projects/index.ts @@ -175,6 +175,7 @@ export { } from "./project-workspace"; export { + defineSetWorkProjectBlock, setWorkProjectAction, setWorkProjectBlock, setWorkProjectInputSchema, diff --git a/packages/workforce/src/projects/work-project.ts b/packages/workforce/src/projects/work-project.ts index 05dae03898..ad0745ba42 100644 --- a/packages/workforce/src/projects/work-project.ts +++ b/packages/workforce/src/projects/work-project.ts @@ -64,35 +64,49 @@ function refuse(message: string): never { throw new Error(`Refused: ${message}`); } -/** The action's block. */ -export const setWorkProjectBlock = handler({ - name: "set-work-project", - inputSchema: setWorkProjectInputSchema, - outputSchema: setWorkProjectOutputSchema, - resources: { ...PROJECT_ROW_RESOURCES }, - execute: async (input, ctx) => { - const state = (ctx.session.state ?? {}) as Record; - if (typeof state[WORKER_ID_STATE_KEY] !== "string") refuse("this session runs no worker, so it has no project to set."); - for (const [key, what] of LINKED) { - if (state[key] !== undefined) refuse(`this is ${what}. Its project can't be set.`); - } - const user = ctx.user?.identity?.userId; - const owner = ctx.session.identity.userId; - if (user === undefined || user !== owner) refuse("only the session's own user sets the project it works in."); - const { visibility, id } = input.project; - const stored = await projectRowsAt(ctx, visibility).getOptional(id); - if (stored === undefined) { - refuse( - visibility === "private" ? `you have no private project "${id}".` : `this organization has no project "${id}" you can read.` - ); +/** + * The action's block, refusing too each session `otherSession` names as not + * the user's own conversation: sessions a flow's own code opens, which carry + * none of the fields above (the Error Reporter's report sessions). + * + * @param otherSession What a session that isn't the user's own conversation + * is, by its id, for the refusal; `undefined` admits it. + */ +export function defineSetWorkProjectBlock(otherSession: (sessionId: string) => string | undefined = () => undefined) { + return handler({ + name: "set-work-project", + inputSchema: setWorkProjectInputSchema, + outputSchema: setWorkProjectOutputSchema, + resources: { ...PROJECT_ROW_RESOURCES }, + execute: async (input, ctx) => { + const state = (ctx.session.state ?? {}) as Record; + if (typeof state[WORKER_ID_STATE_KEY] !== "string") refuse("this session runs no worker, so it has no project to set."); + for (const [key, what] of LINKED) { + if (state[key] !== undefined) refuse(`this is ${what}. Its project can't be set.`); + } + const other = otherSession(ctx.session.identity.id); + if (other !== undefined) refuse(`this is ${other}. Its project can't be set.`); + const user = ctx.user?.identity?.userId; + const owner = ctx.session.identity.userId; + if (user === undefined || user !== owner) refuse("only the session's own user sets the project it works in."); + const { visibility, id } = input.project; + const stored = await projectRowsAt(ctx, visibility).getOptional(id); + if (stored === undefined) { + refuse( + visibility === "private" ? `you have no private project "${id}".` : `this organization has no project "${id}" you can read.` + ); + } + const row = projectRowSchema.parse(stored.state); + const allowed = visibility === "private" ? row.ownerUserId === user : isMember(row, user); + if (!allowed) refuse(`not-a-member: "${user}" is not a member of project "${id}", so this conversation can't work in it.`); + await ctx.session.patchState({ [WORK_PROJECT_STATE_KEY]: projectRef(input.project) }); + return { project: input.project }; } - const row = projectRowSchema.parse(stored.state); - const allowed = visibility === "private" ? row.ownerUserId === user : isMember(row, user); - if (!allowed) refuse(`not-a-member: "${user}" is not a member of project "${id}", so this conversation can't work in it.`); - await ctx.session.patchState({ [WORK_PROJECT_STATE_KEY]: projectRef(input.project) }); - return { project: input.project }; - } -}); + }); +} + +/** The action's block, for a flow whose every session runs a worker for its user. */ +export const setWorkProjectBlock = defineSetWorkProjectBlock(); /** The action, as a worker flow declares it under `SET_WORK_PROJECT_ACTION`. */ export const setWorkProjectAction = { inputSchema: setWorkProjectInputSchema, block: setWorkProjectBlock }; diff --git a/packages/workforce/test/error-reporter.test.ts b/packages/workforce/test/error-reporter.test.ts index b8f2913db6..023f4990d2 100644 --- a/packages/workforce/test/error-reporter.test.ts +++ b/packages/workforce/test/error-reporter.test.ts @@ -597,6 +597,23 @@ describe("the reporter itself", () => { }); }); +describe("a report's session", () => { + // The Error Reporter flow declares the work-project action (FIX-2161), and a report's + // session carries only its worker, so only its id marks it as the reporter's own. + it("can't be set to work in a project, while the operator's own conversation with the reporter gets to the project check", async () => { + const lab = await openLab(); + const project = { project: { visibility: "shared", id: "storefront" } }; + const report = `${REPORT_SESSION_PREFIX}fp-a-report`; + await lab.open(ERROR_REPORTER_FLOW, report, OPERATOR, { workerId: "error-reporter" }); + const refused = await lab.host.act(OPERATOR, report, "setWorkProject", project, ERROR_REPORTER_FLOW); + expect(messageOf(refused.error)).toContain("an error report's session"); + const own = "operator-talks-to-the-reporter"; + await lab.open(ERROR_REPORTER_FLOW, own, OPERATOR, { workerId: "error-reporter" }); + const checked = await lab.host.act(OPERATOR, own, "setWorkProject", project, ERROR_REPORTER_FLOW); + expect(messageOf(checked.error)).toContain('no project "storefront"'); + }); +}); + describe("a user reporting a problem", () => { it("takes the same intake, preview and filing: one report in Inbox, nothing filed before the answer", async () => { const agentAnswer = mockGenerator({ diff --git a/packages/workforce/test/projects-harness.ts b/packages/workforce/test/projects-harness.ts index 82e7a9371d..6e0a75184a 100644 --- a/packages/workforce/test/projects-harness.ts +++ b/packages/workforce/test/projects-harness.ts @@ -63,6 +63,8 @@ export type HostExtras = { flows?: (installation: WorkerInstallation) => Record; /** The scripted models, as `createMockModelResolver` takes them. */ models?: Parameters[0]; + /** Durable execution, for a flow whose request parks on a wait (a worker's step in a session of its own). */ + durable?: boolean; }; const doorInput = z.object({ message: z.string() }); @@ -143,6 +145,7 @@ export async function bootProjectsHost(extras: HostExtras, options: { stores?: S flows: instances, stores: { default: { primary: stores } }, modelResolver: createMockModelResolver(extras.models ?? {}), + ...(extras.durable === true ? { durable: true } : {}), resolvePrincipal: (context: any) => { const user = context.request?.headers.get("x-user"); const org = context.request?.headers.get("x-org") ?? ORG; diff --git a/packages/workforce/test/work-project.test.ts b/packages/workforce/test/work-project.test.ts index 03490b49cf..3ea1742f0c 100644 --- a/packages/workforce/test/work-project.test.ts +++ b/packages/workforce/test/work-project.test.ts @@ -74,7 +74,8 @@ function filerFlow(installation: WorkerInstallation) { /** * The delegates' flow. A turn asks `runProjectOf` and keeps its answer; a * turn holding a task whose goal starts "split" files one piece for - * `eng.coder` through its own board first, once. + * `eng.coder` through its own board first, once, and one whose goal starts + * "plan" files a step for itself in a session of its own, once. */ function takerFlow(installation: WorkerInstallation, runs: Run[]) { const board = defineSessionBoard({ installation, flowKind: "taker" }); @@ -84,15 +85,18 @@ function takerFlow(installation: WorkerInstallation, runs: Run[]) { inputSchema: doorInput, uses: [projectWorkspaceCapability], resources: { ...installation.resources, ...board.resources }, - execute: async (_input, rawCtx) => { + execute: async (input, rawCtx) => { const ctx = rawCtx as unknown as BlockContext; const worker = (await installation.resolveWorker(rawCtx, "taker")).id; const held = (await heldTask(ctx))?.row; + // The answer turn after a step runs holding the same task: record only the first. + if (input.message.startsWith("The steps you filed for yourself have ended")) return "answered"; runs.push({ worker, sessionId: ctx.session.identity.id, state: { ...(ctx.session.state as object) }, - goal: held?.goal, + // A step in a session of its own arrives as its goal, holding no conversation task. + goal: held?.goal ?? input.message.trim(), answer: view(await runProjectOf(ctx as never)) }); if (held !== undefined && held.goal.startsWith("split") && !split.has(held.id)) { @@ -100,21 +104,27 @@ function takerFlow(installation: WorkerInstallation, runs: Run[]) { const ref = await board.board.resolver(ctx as never); await ref!.addTask({ goal: `piece of ${held.goal}`, assignee: "eng.coder" }); } + if (held !== undefined && held.goal.startsWith("plan") && !split.has(held.id)) { + split.add(held.id); + const ref = await board.board.turnResolver(ctx as never); + await ref!.addTask({ id: "s-own", goal: `step of ${held.goal}`, assignee: worker, session: "new" }); + } return "asked"; } }); + const planned = board.planned(turn); return defineFlow({ kind: "taker", configSchema: workerConfigSchema(), session: { ...installation.session(board.sessionStateShape), serverOwned: [...board.serverOwned] }, resources: { ...installation.resources, ...board.resources }, actions: { - respond: { inputSchema: doorInput, block: turn, userMessage: (i: { message: string }) => i.message }, + respond: { inputSchema: doorInput, block: planned, userMessage: (i: { message: string }) => i.message }, ...board.actions, [SET_WORK_PROJECT_ACTION]: setWorkProjectAction }, - internal: { actions: board.entries(turn) }, - task: { actions: { [WORKER_TASK_ENTRY]: workerTaskEntry({ name: "taker-task", turn }) } } + internal: { actions: board.entries(planned) }, + task: { actions: { [WORKER_TASK_ENTRY]: workerTaskEntry({ name: "taker-task", turn: planned }) } } } as never); } @@ -143,7 +153,9 @@ async function boot() { taker: { flow: takerFlow(installation, runs), roles: ["contributor", "manager"] }, [COORDINATOR_FLOW]: defineCoordinatorFlow({ installation, routeModel: "typesafe-ai/jev" }) }), - models: { generators: { "coordinator-judgment": judgment } } + models: { generators: { "coordinator-judgment": judgment } }, + // A step in a session of its own parks its request until the step ends. + durable: true }); const settled = async () => { const deadline = Date.now() + 10_000; @@ -249,6 +261,16 @@ describe("a user's conversation with a worker, set to a project", () => { expect(h.answerOf("piece of split the work")).toEqual(inApollo); }); + it("ongoing step: a step that delegate files for itself in a session of its own runs in the project too", async () => { + const h = await withProjects(); + const alice = h.client("alice"); + const lead = (await alice.ensureWorkerSession({ worker: "lead" })).id; + await alice.setWorkProject("lead", apollo); + await h.file("alice", lead, "plan the work", { assignee: "eng.taker", session: "ongoing", resultTo: "conversation" }); + expect(h.answerOf("plan the work")).toEqual(inApollo); + expect(h.answerOf("step of plan the work")).toEqual(inApollo); + }); + it("not-a-member: a reader of the project who may not work in it is refused, another user's private project isn't found, and nothing is stored", async () => { const h = await withProjects(); const carol = h.client("carol"); From 87d0d4e097ad4a8a94a01db8fa445956cf53409d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 00:22:07 +0000 Subject: [PATCH 5/7] fix(FIX-2161): a follow-up keeps its root task's project A follow-up runs in its root task's session, whose project was handed at the root's filing. Filed after the conversation's project changed, it now takes the root row's stamp, and a project named in its input is written over with the root's, so its run is not refused other-project. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Qsh48df8qzrorsfaCXn1X7 --- .../workforce/src/conversation-board/board.ts | 13 ++++++++++--- packages/workforce/test/work-project.test.ts | 15 +++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/packages/workforce/src/conversation-board/board.ts b/packages/workforce/src/conversation-board/board.ts index 972edbb1cd..5a817a051c 100644 --- a/packages/workforce/src/conversation-board/board.ts +++ b/packages/workforce/src/conversation-board/board.ts @@ -145,7 +145,7 @@ import { taskChainOf, taskChainResources } from "./chain"; -import type { ProjectAddressRef } from "../projects/workstream-ref"; +import { parseProjectRef, type ProjectAddressRef } from "../projects/workstream-ref"; import { filingProjectAddressOf, filingProjectOf, filingSessionIdOf, filingWorkstreamOf } from "./filing-session"; import { CONVERSATION_LEDGER_ID, @@ -1079,15 +1079,22 @@ export function defineConversationBoard(options: ConversationBoardOptions) { // server-written, so the task's cascade reaches only its own pieces. const owner = await pieceOwnerOf(ctx); const given = callerMetadata(init.metadata); + // A follow-up runs in its root's session, so it keeps the root's + // project even after the conversation's changes (FIX-2161). + const root = init.followUpOf === undefined ? undefined : ref.get(init.followUpOf); + const project = isStamped(root) ? (filedProjectOf(root) ?? null) : await filingProjectStampOf(ctx); // The filing turn's hop count, which the task's turn starts at (FIX-2106). // And the project it is filed in, which it keeps if the conversation's changes (FIX-2161). const metadata = { ...(given ?? {}), ...(owner === undefined ? {} : { [PIECE_OF]: owner }), [FILED_HOP]: turnHopMark(ctx), - [FILED_PROJECT]: await filingProjectStampOf(ctx) + [FILED_PROJECT]: project }; - const input = ownProjectIn(init.input, filingProjectAddressOf(ctx.session.state)); + const input = ownProjectIn( + init.input, + isStamped(root) ? (project === null ? undefined : parseProjectRef(project)) : filingProjectAddressOf(ctx.session.state) + ); // The task this piece is for learns where its session is first, so its // ending's cascade can reach the piece (FIX-2080 D2). if (owner !== undefined) await stampFiledMarker(ctx, owner, conversationLedgerAt); diff --git a/packages/workforce/test/work-project.test.ts b/packages/workforce/test/work-project.test.ts index 3ea1742f0c..ab61b06029 100644 --- a/packages/workforce/test/work-project.test.ts +++ b/packages/workforce/test/work-project.test.ts @@ -232,6 +232,21 @@ describe("a user's conversation with a worker, set to a project", () => { expect(h.answerOf("second")).toEqual(inBeta); }); + it("follow-up: a follow-up filed after the change runs in its root's session, in the root's project", async () => { + const h = await withProjects(); + const alice = h.client("alice"); + const lead = (await alice.ensureWorkerSession({ worker: "lead" })).id; + await alice.setWorkProject("lead", apollo); + const first = await h.file("alice", lead, "first"); + await alice.setWorkProject("lead", beta); + // Named either way, the follow-up works where its root's session works. + await h.file("alice", lead, "follow up in apollo", { followUpOf: first, input: { project: apollo } }); + await h.file("alice", lead, "follow up in beta", { followUpOf: first, input: { project: beta } }); + expect(h.answerOf("follow up in apollo")).toEqual(inApollo); + expect(h.answerOf("follow up in beta")).toEqual(inApollo); + expect(new Set(h.runs.map((run) => run.sessionId)).size).toBe(1); + }); + it("waiting: a task filed under one project and assigned after the change still runs in the first", async () => { const h = await withProjects(); const alice = h.client("alice"); From d3395f7c682031e942dc4555beadbc4a8f929886 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 00:27:06 +0000 Subject: [PATCH 6/7] fix(FIX-2161): write the inherited project over a filing's named project A row's stamp and the project its input names now come from one helper, so a piece filed in a delegate's ongoing session, or a follow-up, no longer keeps a project the session it runs in doesn't have, which runProjectOf refused as other-project. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Qsh48df8qzrorsfaCXn1X7 --- .../workforce/src/conversation-board/board.ts | 30 ++++++++++++++----- packages/workforce/test/work-project.test.ts | 11 +++++-- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/packages/workforce/src/conversation-board/board.ts b/packages/workforce/src/conversation-board/board.ts index 5a817a051c..903a25724e 100644 --- a/packages/workforce/src/conversation-board/board.ts +++ b/packages/workforce/src/conversation-board/board.ts @@ -372,6 +372,20 @@ async function sessionSettingOf(ctx: BlockContext, taskId: string): Promise { + const stamp = isStamped(root) ? (filedProjectOf(root) ?? null) : await filingProjectStampOf(ctx); + const inherited = stamp === null ? undefined : parseProjectRef(stamp); + const own = isStamped(root) ? inherited : (filingProjectAddressOf(ctx.session.state) ?? inherited); + return { stamp, own }; +} + /** * The project a task's session is handed (FIX-2161): the one its row was * stamped with when it was filed, so a task waiting on the board keeps it @@ -1082,7 +1096,7 @@ export function defineConversationBoard(options: ConversationBoardOptions) { // A follow-up runs in its root's session, so it keeps the root's // project even after the conversation's changes (FIX-2161). const root = init.followUpOf === undefined ? undefined : ref.get(init.followUpOf); - const project = isStamped(root) ? (filedProjectOf(root) ?? null) : await filingProjectStampOf(ctx); + const { stamp: project, own } = await filedProjectFor(ctx, root); // The filing turn's hop count, which the task's turn starts at (FIX-2106). // And the project it is filed in, which it keeps if the conversation's changes (FIX-2161). const metadata = { @@ -1091,10 +1105,7 @@ export function defineConversationBoard(options: ConversationBoardOptions) { [FILED_HOP]: turnHopMark(ctx), [FILED_PROJECT]: project }; - const input = ownProjectIn( - init.input, - isStamped(root) ? (project === null ? undefined : parseProjectRef(project)) : filingProjectAddressOf(ctx.session.state) - ); + const input = ownProjectIn(init.input, own); // The task this piece is for learns where its session is first, so its // ending's cascade can reach the piece (FIX-2080 D2). if (owner !== undefined) await stampFiledMarker(ctx, owner, conversationLedgerAt); @@ -1314,7 +1325,9 @@ export function defineConversationBoard(options: ConversationBoardOptions) { const fileReservedStep = async (init: TaskInit, reserved: { id: string; markAdded: () => Promise }): Promise => { const { id, markAdded } = reserved; const metadata = callerMetadata(init.metadata); - const input = ownProjectIn(init.input, filingProjectAddressOf(ctx.session.state)); + // The project the step's own session is handed, so a guess in its input + // matches it (FIX-2161). + const input = ownProjectIn(init.input, (await filedProjectFor(ctx)).own); // A step a task session plans is that task's, server-written (FIX-2081). const owner = await pieceOwnerOf(ctx); const added = await plan.addTask({ @@ -1686,8 +1699,9 @@ 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). // And the project it is filed in, which it keeps if the conversation's changes (FIX-2161). - const metadata = { ...callerMetadata(filing.metadata), [FILED_HOP]: turnHopMark(ctx), [FILED_PROJECT]: await filingProjectStampOf(ctx) }; - const input = ownProjectIn(filing.input, filingProjectAddressOf(ctx.session.state)); + const { stamp, own } = await filedProjectFor(ctx); + const metadata = { ...callerMetadata(filing.metadata), [FILED_HOP]: turnHopMark(ctx), [FILED_PROJECT]: stamp }; + const input = ownProjectIn(filing.input, own); const { metadata: _metadata, input: _input, ...rest } = filing; const init: TaskInit & { id: string } = { ...rest, diff --git a/packages/workforce/test/work-project.test.ts b/packages/workforce/test/work-project.test.ts index ab61b06029..e428f11bdc 100644 --- a/packages/workforce/test/work-project.test.ts +++ b/packages/workforce/test/work-project.test.ts @@ -102,7 +102,13 @@ function takerFlow(installation: WorkerInstallation, runs: Run[]) { if (held !== undefined && held.goal.startsWith("split") && !split.has(held.id)) { split.add(held.id); const ref = await board.board.resolver(ctx as never); - await ref!.addTask({ goal: `piece of ${held.goal}`, assignee: "eng.coder" }); + // The delegate names a project of its own: the board writes the one it + // works in over the guess, so the piece isn't refused other-project. + await ref!.addTask({ + goal: `piece of ${held.goal}`, + assignee: "eng.coder", + input: { message: "piece", project: { visibility: "shared", id: "beta" } } + }); } if (held !== undefined && held.goal.startsWith("plan") && !split.has(held.id)) { split.add(held.id); @@ -272,7 +278,8 @@ describe("a user's conversation with a worker, set to a project", () => { expect(ongoing.state).not.toHaveProperty("taskId"); expect(ongoing.state).not.toHaveProperty("filingProjectId"); expect(ongoing.answer).toEqual(inApollo); - // One hop further down: the piece it filed while holding the task. + // One hop further down: the piece it filed while holding the task, naming + // another project, which the board wrote over. expect(h.answerOf("piece of split the work")).toEqual(inApollo); }); From 94a291d6d2a235f974f8fa5a9d5c699f2fea7336 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 00:28:49 +0000 Subject: [PATCH 7/7] refactor(FIX-2161): use the harness lead flow as the goal test's workstream lead Drops the test's own 24-line lead flow for the projects harness's `lead` fixture flow with the action declared on it, the unused `setWorkProjectBlock` export, and two comments restating the stamp write. From the restraint review's POC (#3824). Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Qsh48df8qzrorsfaCXn1X7 --- .../workforce/src/conversation-board/board.ts | 2 -- packages/workforce/src/projects/index.ts | 1 - .../workforce/src/projects/work-project.ts | 2 +- packages/workforce/test/work-project.test.ts | 36 ++++--------------- 4 files changed, 8 insertions(+), 33 deletions(-) diff --git a/packages/workforce/src/conversation-board/board.ts b/packages/workforce/src/conversation-board/board.ts index 903a25724e..6a173f7461 100644 --- a/packages/workforce/src/conversation-board/board.ts +++ b/packages/workforce/src/conversation-board/board.ts @@ -1098,7 +1098,6 @@ export function defineConversationBoard(options: ConversationBoardOptions) { 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). - // And the project it is filed in, which it keeps if the conversation's changes (FIX-2161). const metadata = { ...(given ?? {}), ...(owner === undefined ? {} : { [PIECE_OF]: owner }), @@ -1698,7 +1697,6 @@ export function defineConversationBoard(options: ConversationBoardOptions) { // What a model asked beside the message is a caller's, as on any filing: // 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). - // And the project it is filed in, which it keeps if the conversation's changes (FIX-2161). const { stamp, own } = await filedProjectFor(ctx); const metadata = { ...callerMetadata(filing.metadata), [FILED_HOP]: turnHopMark(ctx), [FILED_PROJECT]: stamp }; const input = ownProjectIn(filing.input, own); diff --git a/packages/workforce/src/projects/index.ts b/packages/workforce/src/projects/index.ts index f47fa8ba12..04c52e8810 100644 --- a/packages/workforce/src/projects/index.ts +++ b/packages/workforce/src/projects/index.ts @@ -177,7 +177,6 @@ export { export { defineSetWorkProjectBlock, setWorkProjectAction, - setWorkProjectBlock, setWorkProjectInputSchema, setWorkProjectOutputSchema, type SetWorkProjectInput, diff --git a/packages/workforce/src/projects/work-project.ts b/packages/workforce/src/projects/work-project.ts index ad0745ba42..0956eedf47 100644 --- a/packages/workforce/src/projects/work-project.ts +++ b/packages/workforce/src/projects/work-project.ts @@ -106,7 +106,7 @@ export function defineSetWorkProjectBlock(otherSession: (sessionId: string) => s } /** The action's block, for a flow whose every session runs a worker for its user. */ -export const setWorkProjectBlock = defineSetWorkProjectBlock(); +const setWorkProjectBlock = defineSetWorkProjectBlock(); /** The action, as a worker flow declares it under `SET_WORK_PROJECT_ACTION`. */ export const setWorkProjectAction = { inputSchema: setWorkProjectInputSchema, block: setWorkProjectBlock }; diff --git a/packages/workforce/test/work-project.test.ts b/packages/workforce/test/work-project.test.ts index e428f11bdc..2df60183ae 100644 --- a/packages/workforce/test/work-project.test.ts +++ b/packages/workforce/test/work-project.test.ts @@ -31,7 +31,6 @@ import { import { heldTask } from "../src/conversation-board/held-task"; import { workerTaskEntry } from "../src/conversation-board/task-entry"; import type { WorkerManifest } from "../src/manifest"; -import { PROJECT_ROW_RESOURCES } from "../src/projects/project-address"; import { runProjectOf } from "../src/projects/run-project"; import type { WorkerInstallation } from "../src/workers/installation"; import { bootProjectsHost, ORG } from "./projects-harness"; @@ -48,29 +47,6 @@ function view(found: Awaited>) { return { kind: "found", project: `${found.visibility}/${found.project.id}`, owner: found.owner }; } -/** A workstream lead's flow: an app's own worker flow, declaring the action as every worker flow does. */ -function filerFlow(installation: WorkerInstallation) { - const board = defineSessionBoard({ installation, flowKind: "filer" }); - const door = handler({ - name: "filer-run", - inputSchema: doorInput, - resources: { ...installation.resources }, - execute: async (_input, ctx) => (await installation.resolveWorker(ctx, "filer")).id - }); - return defineFlow({ - kind: "filer", - configSchema: workerConfigSchema(), - session: { ...installation.session(board.sessionStateShape), serverOwned: [...board.serverOwned] }, - resources: { ...installation.resources, ...board.resources, ...PROJECT_ROW_RESOURCES }, - actions: { - respond: { inputSchema: doorInput, block: door, userMessage: (i: { message: string }) => i.message }, - ...board.actions, - [SET_WORK_PROJECT_ACTION]: setWorkProjectAction - }, - internal: { actions: { ...board.entries(door), [WORKSTREAM_OPENED_ENTRY]: workstreamOpenedEntry() } } - } as never); -} - /** * The delegates' flow. A turn asks `runProjectOf` and keeps its answer; a * turn holding a task whose goal starts "split" files one piece for @@ -149,13 +125,16 @@ async function boot() { const runs: Run[] = []; const projects = defineProjectBlocks(); const judgment = mockGenerator({ script: [{ when: () => true, then: { text: "Noted." } }] }); - const filerRef = { kind: "filer", internal: { actions: { [WORKSTREAM_OPENED_ENTRY]: {} } } }; + const leadRef = { kind: "lead", internal: { actions: { [WORKSTREAM_OPENED_ENTRY]: {} } } }; const h = await bootProjectsHost({ standardWorkers, projectCoordinator: PROJECT_COORDINATOR, - lab: (installation) => ({ ...projects.actions, ...defineWorkstreamBlocks({ installation, leadFlows: [filerRef] }).actions }), + lab: (installation) => ({ ...projects.actions, ...defineWorkstreamBlocks({ installation, leadFlows: [leadRef] }).actions }), + // The harness's own `lead` flow is the workstream lead: an app's own worker + // flow, declaring the action as every worker flow does. + lead: () => ({ [SET_WORK_PROJECT_ACTION]: setWorkProjectAction }), + leadInternal: () => ({ [WORKSTREAM_OPENED_ENTRY]: workstreamOpenedEntry() }), flows: (installation) => ({ - filer: { flow: filerFlow(installation), roles: ["manager"] }, taker: { flow: takerFlow(installation, runs), roles: ["contributor", "manager"] }, [COORDINATOR_FLOW]: defineCoordinatorFlow({ installation, routeModel: "typesafe-ai/jev" }) }), @@ -323,8 +302,7 @@ describe("a user's conversation with a worker, set to a project", () => { const task = h.runs[0]!.sessionId; await expect(alice.setWorkProject("eng.taker", beta, { sessionId: task })).rejects.toThrow(/a task's session/); - const roster = await h.openSession("alice", "workforce-roster"); - await h.ok("alice", "workforce-roster", roster, "hire", { id: "alice-filer", flow: "filer", settings: { delegates: ["eng.taker"] } }); + await h.hire("alice", "alice-filer", "lead", ORG, { delegates: ["eng.taker"] }); const opened = (await h.ok("alice", "lab", await h.openSession("alice", "lab"), "openWorkstream", { project: apollo, id: "ws",