diff --git a/FORK.md b/FORK.md index bb5006a3a31dd..61c532b627f3a 100644 --- a/FORK.md +++ b/FORK.md @@ -76,7 +76,7 @@ These files exist upstream, but J5 owns its copy outright and they are not integ ### Sanctioned appended integration cases -Against upstream pin `d2c440312e5f39d59827ed466838a623516454d6`, the inventory has 105 entries: 1–104 plus 15b. Seventeen are retired and keep their numbers (10–14, 15b, 16–18, 20, 27–29, 54, 55, 61, 66), and 19 and 39 are retired except for a remainder. Existing numbers never change; a new case takes the next number. Line coordinates and landing SHAs below describe historical integrations; use named symbols and tests after upstream movement. Branding has its own inventory in `BRANDING.md`; temporary defect patches are listed separately below. +Against upstream pin `d2c440312e5f39d59827ed466838a623516454d6`, the inventory has 106 entries: 1–105 plus 15b. Seventeen are retired and keep their numbers (10–14, 15b, 16–18, 20, 27–29, 54, 55, 61, 66), and 19 and 39 are retired except for a remainder. Existing numbers never change; a new case takes the next number. Line coordinates and landing SHAs below describe historical integrations; use named symbols and tests after upstream movement. Branding has its own inventory in `BRANDING.md`; temporary defect patches are listed separately below. 1. A1's independent communication-ledger migration lane: in `apps/server/src/persistence/Sqlite.ts`, `layerSetup` runs `runJ5CompatibleUpstreamMigrations` and then `runJ5A2AMigrations` where upstream calls `runMigrations()`. Upstream's `layerConfig` has already run `initializeV2Database`, which copies `state.sqlite` to `statev2.sqlite`, so both run only against `statev2.sqlite`. J5 adopts that copy-on-first-start unchanged (Jackson's 2026-09-24 decision #2): an existing `statev2.sqlite` wins and `state.sqlite` is never recopied or written again, so the cutover is one-way: writes after the first V2 boot are invisible to an older binary. Snapshot before the upgrade, and roll back across it by stopping writers and moving `statev2.sqlite` aside (`docs/j5/runbooks/dogfood-runtime.md`); never run old and new binaries against the two files. `layerFromPath` calls one J5 step, `snapshotBeforeMigrations` (`apps/server/src/j5/persistence/MigrationSnapshot.ts`), before it builds the SQL layer, so every file-backed open is covered. When the database has migration history and either lane has a migration pending (upstream's `effect_sql_migrations` against upstream's manifest, or `j5_a2a_migrations` against J5's ledger list), it is first copied with `VACUUM INTO`, through a read-only connection, to `statev2.pre-migration-u-j.sqlite` beside it, named for the newest migration each lane had recorded. The copy is synchronous and does not use `node:sqlite`'s `backup()`: on the Node 26 that release executables embed, `backup()` rejects the one-step rate Node 24 accepts and its promise settles only when another event wakes the loop, which stopped the first nightly from starting. The snapshot is a compacted copy in rollback-journal mode; the server sets WAL again when it opens a restored one. A database with no history, or with nothing pending, is not copied. The newest three snapshots are kept (`MIGRATION_SNAPSHOTS_KEPT`) and older ones deleted. This is the roll-forward policy's emergency exit (issue #507): J5 adds no refusal to start on a database newer than the build, as upstream adds none for that case. Upstream refuses only a history that would skip one of V2's own migrations (`assertV2MigrationsCanRun` in `Migrations.ts`), and a second server on the same home (`apps/server/src/serverOwnership.ts`, exit 78), whose lock `layerMakeServer` takes before anything opens the database, so before the snapshot. A failed copy dies there, so the server does not start and nothing migrates. It dies rather than fails so the layer's error type, which upstream's tests name, stays upstream's. `MigrationSnapshot.test.ts` covers it. The `j5_run_observability_migrations` lane (one index) is not consulted. J5 tooling (`fleet-load.ts`, `devDeliverySeed.ts`, `dogfood-snapshot.sh`, `dogfood-local.sh`) targets `statev2.sqlite`; `apps/server/src/j5/persistence/StateV2Cutover.test.ts` covers the copy, no-recopy and failed-first-boot retry. Case 31 defines the compatibility wrapper; J5's own migration IDs remain in separate tracking tables and run after upstream migration completion. 2. The authenticated J5 MCP registration seam: the `layer` of `apps/server/src/mcp/McpHttpServer.ts` calls `layerJ5Toolkits(toolkitRegistration)` (`apps/server/src/j5/a2a/mcp/registration.ts`) in place of upstream's orchestrator, thread, attachment, project and environment registrations. Upstream's preview, preview-controls, worktree, pull-request, device and html toolkits are registered whole, as upstream registers them. Upstream's lint rule `no-raw-mcp-registration` allows MCP registration only in `McpHttpServer.ts`, so J5 registers through the `toolkitRegistration` function that file passes in. `layerJ5Toolkits` registers J5's own tools and the admitted part of those five upstream toolkits. `upstreamCatalog.ts` selects the admitted tools one by one and runs them on upstream's own handlers through `handlersFor`, which is one documented cast. Upstream's `McpServer.toolkit` asks for every tool's declared dependencies at registration, so J5's environment toolkit registration (`registration.ts`) provides `ThreadCommandExecutor.layer`, as upstream's own does. `apps/server/src/mcp/McpInvocationContext.ts` adds the `artifacts` capability that case 33's tools check. @@ -251,7 +251,7 @@ Upstream settings sections no longer accept a `description` prop; J5 library pan `apps/server/src/orchestration-v2/ThreadMessageIntake.ts` treats the J5 `resolve-agent-persona` launch refusal as pre-dispatch failure and releases claimed uploads; the pending upload remains available for retry. -Bryant requested a shared agent picker for Codex and Claude, invoking a saved agent as a subagent within the current conversation. This is a narrow exception to the earlier native-only Subagent steering: the child uses the existing delegated-child engine with `lineage.relationshipToParent = subagent`. Its child thread is backing storage, not a top-level Peer Agent. Ordinary native subagent requests and `j5_spawn_agent` retain their existing meanings; `j5_spawn_agent`'s optional `agent` input (2026-09-09) resolves a saved agent into a Peer Agent's immutable assignment entirely inside `apps/server/src/j5/agents/agentPersonaSpawn.ts` and the J5 toolkit handlers, with no further upstream hook. Proposal-driven Crews use ordinary conversation. The former `/crew` send-path wrapper in `ChatView.tsx` and slash-menu spread in `ChatComposer.tsx` are removed; case 8's standing instructions guide the agent to propose a roster, including custom members, and wait for the person's decision before launching. The platform's `` decisions render as notices through case 7's `renderThreadA2ADelivery` call: J5-owned `apps/web/src/j5/crew/CrewNoticeRenderer.tsx` draws them, the shared parser in `packages/client-runtime/src/j5/crewNotices.ts` recognizes the tagged blocks strictly (anything unparsed stays raw), and the call passes the thread and markdown folder from `TimelineRowCtx`, so a seat opens its thread and the brief renders as markdown (2026-09-16). Mobile has no delivery seam and shows these notices in upstream's rows, as it does A2A deliveries. `ChatView.tsx` passes J5-owned `CrewRosterGate` (`apps/web/src/j5/crew/CrewRosterGate.tsx`) through the existing `ChatComposer.threadProgressControl` slot alongside Playbooks. It uses upstream’s `ComposerBanner` attachment and expands from a compact strip above the Captain’s composer; Add/Edit member dialogs stay outside the composer’s focus flow. The slot is hidden while a blocking tool approval or question is open, so the proposal disappears meanwhile; the person's saved roster edits live in J5-owned `apps/web/src/j5/crew/crewProposalDraftStore.ts` (keyed by environment and proposal, cleared when the proposal is approved or declined) and are restored when the gate returns. Mid-run seat additions stay on the inbox bell (`crewProposals.logic.ts` decides which is which). The human gate (open proposals, approve with edited seats, decline) lives entirely in J5 files: `apps/web/src/j5/crew/`, the J5 inbox page and bell, and the list, preview and resolve RPCs (case 64). One adapter append makes the gate reachable from Claude: `claudeMcpQueryOverrides` in `apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts` spreads J5-owned `J5_CLAUDE_MCP_ALLOWED_TOOLS` (`apps/server/src/j5/a2a/mcp/claudeAllowedTools.ts`) into the read-only pre-approval list, because Claude runs read-only personas in `dontAsk` mode and would otherwise deny every J5 coordination tool; the upstream `CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS` constant and its toolkit cross-check stay untouched, and the two exact-allowlist assertions in `ClaudeAdapterV2.test.ts` include the J5 spread. The Codex counterpart is one spread in `codexThreadRuntimeParams` (`apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts`, private to that file since the 2026-10-24 advance): upstream's injected `"mcp_servers.t3-code"` entry gains J5-owned `J5_CODEX_T3_MCP_SERVER_CONFIG` (`apps/server/src/j5/a2a/mcp/codexToolApproval.ts`; since 2026-09-14 a per-tool `tools..approval_mode = "approve"` map naming the J5 verbs plus `j5_write_artifact` (a saved agent's declared handoff artifact lives in application storage, never the workspace) and, since 2026-09-15, the provider-native Subagent verbs `delegate_task`, `task_status`, and `task_cancel` (a Crew member refused `j5_spawn_agent` is sent there), never a server-wide default, so worktree handoff, browser preview, and scheduling keep Codex's own verdict for read-only personas), because Codex 0.153+ rejects every non-read-only MCP tool under approval policy `never` with "MCP tool call requires approval, but approval policy is never"; that policy is what full-access mode and every saved-agent runtime policy send, so without the spread `j5_send_message`, `j5_spawn_agent`, and `j5_propose_crew` all fail on Codex. The full spread applies when the thread's resolved approval policy is `never` (`j5ApprovalPolicyIsNever`). Since 2026-09-24 both appends draw their names from one J5 leaf module, `apps/server/src/j5/a2a/mcp/j5ToolPreapproval.ts` (`J5_PREAPPROVED_TOOLS`, the interactive-mode `J5_COORDINATION_TOOLS`, and `j5PreapprovedTools(runtimePolicy)`), so Codex and Claude, the two harnesses J5 pre-approves its tools on (Jackson's ruling on #233), pre-approve the same set. Interactive modes pre-approve only routine messaging and the crew proposal/request tools; membership still waits for the platform's human roster or Inbox decision. Other tools retain Codex's prompting. The ten upstream tools admitted on 2026-10-08 (case 4) are not in J5's pre-approval lists; they keep each harness's own verdict, and upstream's Claude read-only list already carries `html_preview` and `html_render`. The expected thread config in `CodexAdapterV2.test.ts` includes the spread. +Bryant requested a shared agent picker for Codex and Claude, invoking a saved agent as a subagent within the current conversation. This is a narrow exception to the earlier native-only Subagent steering: the child uses the existing delegated-child engine with `lineage.relationshipToParent = subagent`. Its child thread is backing storage, not a top-level Peer Agent. Ordinary native subagent requests and `j5_spawn_agent` retain their existing meanings; `j5_spawn_agent`'s optional `agent` input (2026-09-09) resolves a saved agent into a Peer Agent's immutable assignment entirely inside `apps/server/src/j5/agents/agentPersonaSpawn.ts` and the J5 toolkit handlers, with no further upstream hook. Proposal-driven Crews use ordinary conversation. The former `/crew` send-path wrapper in `ChatView.tsx` and slash-menu spread in `ChatComposer.tsx` are removed; case 8's standing instructions guide the agent to propose a roster, including custom members, and wait for the person's decision before launching. The platform's `` decisions render as notices through case 7's `renderThreadA2ADelivery` call: J5-owned `apps/web/src/j5/crew/CrewNoticeRenderer.tsx` draws them, the shared parser in `packages/client-runtime/src/j5/crewNotices.ts` recognizes the tagged blocks strictly (anything unparsed stays raw), and the call passes the thread and markdown folder from `TimelineRowCtx`, so a seat opens its thread and the brief renders as markdown (2026-09-16). Mobile has no delivery seam and shows these notices in upstream's rows, as it does A2A deliveries. `ChatView.tsx` passes J5-owned `CrewRosterGate` (`apps/web/src/j5/crew/CrewRosterGate.tsx`) through the existing `ChatComposer.threadProgressControl` slot alongside Playbooks. It uses upstream’s `ComposerBanner` attachment and expands from a compact strip above the Captain’s composer; Add/Edit member dialogs stay outside the composer’s focus flow. The slot is hidden while a blocking tool approval or question is open, so the proposal disappears meanwhile; the person's saved roster edits live in J5-owned `apps/web/src/j5/crew/crewProposalDraftStore.ts` (keyed by environment and proposal, cleared when the proposal is approved or declined) and are restored when the gate returns. Mid-run seat additions stay on the inbox bell (`crewProposals.logic.ts` decides which is which). The human gate (open proposals, approve with edited seats, decline) lives entirely in J5 files: `apps/web/src/j5/crew/`, the J5 inbox page and bell, and the list, preview and resolve RPCs (case 64). One adapter append makes the gate reachable from Claude: `claudeMcpQueryOverrides` in `apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts` spreads J5-owned `J5_CLAUDE_MCP_ALLOWED_TOOLS` (`apps/server/src/j5/a2a/mcp/claudeAllowedTools.ts`) into the read-only pre-approval list, because Claude runs read-only personas in `dontAsk` mode and would otherwise deny every J5 coordination tool; the upstream `CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS` constant and its toolkit cross-check stay untouched, and the two exact-allowlist assertions in `ClaudeAdapterV2.test.ts` include the J5 spread. The Codex counterpart is one spread in `codexThreadRuntimeParams` (`apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts`, private to that file since the 2026-10-24 advance): upstream's injected `"mcp_servers.t3-code"` entry gains J5-owned `J5_CODEX_T3_MCP_SERVER_CONFIG` (`apps/server/src/j5/a2a/mcp/codexToolApproval.ts`; since 2026-09-14 a per-tool `tools..approval_mode = "approve"` map naming the J5 verbs plus `j5_write_artifact` (a saved agent's declared handoff artifact lives in application storage, never the workspace) and, since 2026-09-15, the provider-native Subagent verbs `delegate_task`, `task_status`, and `task_cancel` (a Crew member refused `j5_spawn_agent` is sent there), never a server-wide default, so worktree handoff, browser preview, and scheduling keep Codex's own verdict for read-only personas), because Codex 0.153+ rejects every non-read-only MCP tool under approval policy `never` with "MCP tool call requires approval, but approval policy is never"; that policy is what full-access mode and every saved-agent runtime policy send, so without the spread `j5_send_message`, `j5_spawn_agent`, and `j5_propose_crew` all fail on Codex. The full spread applies when the thread's resolved approval policy is `never` (`j5ApprovalPolicyIsNever`). Since 2026-09-24 both appends draw their names from one J5 leaf module, `apps/server/src/j5/a2a/mcp/j5ToolPreapproval.ts` (`J5_PREAPPROVED_TOOLS`, the interactive-mode `J5_COORDINATION_TOOLS`, and `j5PreapprovedTools(runtimePolicy)`), so Codex and Claude, the two harnesses J5 pre-approves its tools on (Jackson's ruling on #233), pre-approve the same set. Interactive modes pre-approve only routine messaging and the crew proposal/request tools. Pre-approval is the Captain's own staffing decision: a roster waits for the person unless the project's Crew approval is automatic (#743), and a Captain's addition (`j5_request_crew_member`) is automatic. A member's access defaults to Full access unless the Captain sets one, so a Supervised Captain can start a Full-access custom member without review; Jackson accepted that (2026-10-31). The Agent Setup approval setting governs rosters only; additions are always automatic. Other tools retain Codex's prompting. The ten upstream tools admitted on 2026-10-08 (case 4) are not in J5's pre-approval lists; they keep each harness's own verdict, and upstream's Claude read-only list already carries `html_preview` and `html_render`. The expected thread config in `CodexAdapterV2.test.ts` includes the spread. `packages/client-runtime/src/state/models.ts` accepts a status-only runtime in `threadRuntimeIsActive`; J5 crew state reuses that exported predicate without importing the upstream-private status helper. Preserve this narrow input contract when carrying crew reads forward. @@ -292,7 +292,7 @@ Revision scope approved by Bryant on 2026-09-08 following Jacksondr5's PR #75 re | `packages/client-runtime/src/j5/agentPersonas.ts`, `j5/agentPersonaAtoms.ts`, their tests, `package.json` | Shared presentation/import helpers and the environment-scoped RPC atoms for the persona library; `package.json` appends the `./j5/agent-personas` and `./j5/agent-persona-atoms` export entries. Web and mobile each instantiate the atoms in `src/j5/agents/agentPersonaAtoms.ts`. | Web and mobile display the same full server response, including custom ids and display names; clients do not resolve routes or load server files. `state/orchestration.ts` carries no persona atoms. | | `packages/client-runtime/src/operations/commands.ts`, `.test.ts`, `state/models.ts`, `state/entities.test.ts` | Carry the optional persona launch request and the shell assignment through existing commands/state. | Preserve backward-compatible ordinary tasks and environment-qualified queries. | | `apps/web/src/routes/_chat.settings.personas.tsx` (was `settings.agents.tsx` until the 2026-09-17 persona rename and `settings.personas.tsx` until v0.1.3 moved Settings under the chat layout; the route is `/settings/personas`, in the Agents group of the Settings sidebar, and the search entry keeps "agents" as a term), `components/settings/AgentSettingsPanel.tsx`, `SettingsSidebarNav.tsx`, `settingsSearch.ts` | Settings navigation/search registrations and the added environment-aware library view. | Keep the panel a thin mount of J5-owned `j5/agents/AgentLibrarySettings.tsx`, which owns folder/file picking and library actions. No editor or composer activation is introduced. Catalog error, empty, blocked, and available states must remain visible. Desktop inherits this web surface. The search-entry test lives in `apps/web/src/j5/agents/settingsSearch.test.ts`. | -| `apps/mobile/src/Stack.tsx`, `features/settings/SettingsRouteScreen.tsx`, `SettingsAgentsRouteScreen.tsx`, `components/settings-page-targets.ts` | Mount J5-owned `j5/agents/AgentLibrarySettingsScreen.tsx` on iOS and Android at `/settings/personas`; `Stack.tsx` registers the `SettingsAgents` screen at `settings/personas`, `settings-page-targets.ts` (which replaced upstream's deleted `settings-sheet-targets.ts` at v0.1.3) lists it, and `SettingsRouteScreen.tsx` appends one Personas row to upstream's Agents group; `pickAgentDefinitions.ts` handles native folder/file access and foreground handoff. `SettingsSection.tsx` is unchanged; the library screen renders its own header row. | Preserve existing navigation and selected-environment routing; no separate persona catalog or policy logic. | +| `apps/mobile/src/Stack.tsx`, `features/settings/SettingsRouteScreen.tsx`, `SettingsAgentsRouteScreen.tsx`, `components/settings-page-targets.ts` | Mount J5-owned `j5/agents/AgentLibrarySettingsScreen.tsx` on iOS and Android at `/settings/personas`; `Stack.tsx` registers the `SettingsAgents` screen at `settings/personas`, `settings-page-targets.ts` (which replaced upstream's deleted `settings-sheet-targets.ts` at v0.1.3) lists it, and `SettingsRouteScreen.tsx` appends one Agent Setup row (titled Personas before #743) to upstream's Agents group; `pickAgentDefinitions.ts` handles native folder/file access and foreground handoff. `SettingsSection.tsx` is unchanged; the library screen renders its own header row. | Preserve existing navigation and selected-environment routing; no separate persona catalog or policy logic. | | `apps/web/src/components/ChatView.tsx`, `components/chat/ChatComposer.tsx`, `apps/mobile/src/features/threads/ThreadComposer.tsx` | Pass the durable assignment to the composers; each composer renders the J5-owned `AgentPersonaAssignmentControl(s)` from `src/j5/agents/` in place of its model controls when an assignment exists. The web composer's `selectedModelSelection` also passes through J5-owned `composerModelSelectionForThread` (`client-runtime/src/j5/agentPersonas.ts`, 2026-09-10) so a persona thread always sends its launch route: without it a remembered draft pick made every human message to a Captain fail with "has an immutable model route". | Ordinary tasks retain existing controls. Labels use the launch snapshot, never today's definition name; server enforcement remains authoritative. Keep the composer edit to the prop and the one conditional render. | | `components/chat/ThreadRelationshipsControl.tsx`, `components/chat/V2LifecycleRow.tsx` | Stack #84/#86 normalizes runtime-child labels separately from reusable Role definitions. Upstream deleted `AgentsPanel` (#12835); the concern now lives in lineage rows and subagent cards (`AgentRowIdentity`, mounted beside the row button). | Keep this concern separate from catalog loading. Preserve provider-native activity semantics, focused label/panel tests, and no continuous animation. | | `apps/web/src/routeTree.gen.ts`, `pnpm-lock.yaml` | Generated route registration and dependency resolution carried by the original stack. | Regenerate only with the normal tooling when inputs change. The library revision adds no dependency and does not hand-edit either file. | @@ -525,6 +525,8 @@ migrations after upstream migrations. 104. A Crew notice with nothing for the person takes no timeline row ([#741](https://github.com/Jacksondr5/j5code/issues/741), Bryant 2026-10-27). `apps/web/src/components/chat/MessagesTimeline.tsx` carries one J5 import and one changed line in `ConversationTimeline`: `const rows = useStableRows(withoutHiddenCrewNotices(rawRows), listIdentityKey)`, J5-owned in `apps/web/src/j5/crew/crewNotices.logic.ts`. It drops the message rows of platform Crew notices (`createdBy === "system"`) whose `crewNoticeLines` are empty, a clean launch report or a clean finish, after upstream has derived the rows, so each notice still bounds the Captain turn it started (`deriveActiveVisualResponseRunIds`, terminal assistant messages and rollback all read user messages as turn boundaries), and returns the same array when nothing is hidden, cached per input array, because `useStableRows` compares its source by identity. Upstream's minimap reads the filtered rows, so an ask's reply preview can run past a hidden notice; that is accepted. Proof: `apps/web/src/j5/crew/crewNotices.logic.test.ts`, "keeps the rows a hidden notice bounded". On a pin advance: if upstream stops deriving rows through `useStableRows`, apply the filter to whatever the list renders, after turn boundaries are computed, never to the entries before them. +105. Agent Setup and Crew approval settings ([#743](https://github.com/Jacksondr5/j5code/issues/743)): `packages/contracts/src/settings.ts` registers J5's `crewAutoApprove` boolean (default off) in server settings, patches, and project overrides. `apps/web/src/components/settings/settingsSearch.ts` renames the existing `/settings/personas` destination to Agent Setup and adds search terms and the scoped Crew setting target. `apps/mobile/src/features/settings/SettingsRouteScreen.tsx` and `apps/mobile/src/Stack.tsx` rename the existing Personas navigation entry and title to Agent Setup. Runtime behavior and the web sections stay in J5-owned files; mobile still exposes only the persona library. + ## Pin and upstream advance runbook Current pin: `d2c440312e5f39d59827ed466838a623516454d6`, upstream's stable release tag `v0.1.3` on `main` (frozen 2026-10-27). The previous pin was `70d60e03a7a35c6fa131825bbfa05ec893e69912`, upstream's nightly tag `v0.1.1-nightly.20261017.3238`. @@ -739,10 +741,10 @@ explicitly marked. | `apps/mobile/src/features/threads/NewTaskDraftScreen.tsx` | A | 45, 90, 100, Saved-agent mentions | | `apps/mobile/src/features/threads/ThreadDetailScreen.tsx` | A | 45, 49 | | `apps/mobile/src/features/threads/ThreadRouteScreen.tsx` | A | 69, 90, 99 | -| `apps/mobile/src/features/settings/SettingsRouteScreen.tsx` | A | 72, Role library | +| `apps/mobile/src/features/settings/SettingsRouteScreen.tsx` | A | 72, Role library, 105 | | `apps/mobile/src/features/settings/components/SettingsScreen.tsx` | N | 72 | | `apps/mobile/src/features/settings/settings-environment-filter.tsx` | N | 72 | -| `apps/mobile/src/Stack.tsx` | A | 72, 98, 101, 103, Role library | +| `apps/mobile/src/Stack.tsx` | A | 72, 98, 101, 103, Role library, 105 | | `apps/mobile/src/features/home/ThreadListToolbar.tsx` | N | 102 | | `apps/mobile/src/features/workspace/WorkspaceToolbar.ios.tsx` | N | 102 | | `apps/mobile/src/features/archive/ArchivedThreadsRouteScreen.tsx` | N | 72 | @@ -805,7 +807,7 @@ explicitly marked. | `apps/web/src/components/settings/settingsSearch.test.ts` | N | 43 | | `apps/web/src/threadNotifications.ts` | N | 87 | | `apps/web/src/components/settings/SettingsPanels.tsx` | N | 87 | -| `apps/web/src/components/settings/settingsSearch.ts` | N | 42–44, 72, 77, 87, 92 | +| `apps/web/src/components/settings/settingsSearch.ts` | N | 42–44, 72, 77, 87, 92, 105 | | `apps/web/src/components/settings/SettingsSidebarNav.tsx` | N | 42, 72, 73 | | `docs/README.md` | N | 42, 45, 48 | | `knip.jsonc` | N | 95 | @@ -922,7 +924,7 @@ explicitly marked. | `packages/contracts/src/server.test.ts` | N | 43 | | `packages/contracts/src/server.ts` | N | 42, 43 | | `packages/contracts/src/settings.test.ts` | N | 42 | -| `packages/contracts/src/settings.ts` | N | 42, B | +| `packages/contracts/src/settings.ts` | N | 42, B, 105 | | `packages/shared/package.json` | N | 43, 46, 49, 52 | | `packages/shared/src/devHome.test.ts` | R | H | | `packages/shared/src/paletteSearch.test.ts` | N | B | diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 449b89580a4f6..990e221a04a01 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -352,7 +352,7 @@ const SETTINGS_SCREENS = { linking: "settings/personas", options: { ...SETTINGS_PAGE_OPTIONS, - title: "Personas", + title: "Agent Setup", }, }), ...j5SettingsFormRoutes(SETTINGS_PAGE_OPTIONS), diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx index d0985db824b5b..447e3173cb327 100644 --- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx @@ -258,7 +258,7 @@ function useSettingsIndexSections(): SettingsListSection[] { serverPage("SettingsProviderAccounts", "person.crop.circle", "Providers"), serverPage("SettingsThreads", "text.bubble", "Threads"), page("SettingsScheduledTasks", "clock", "Scheduled tasks"), - page("SettingsAgents", "person.2", "Personas"), + page("SettingsAgents", "person.2", "Agent Setup"), ], }, { diff --git a/apps/mobile/src/j5/agents/AgentLibrarySettingsScreen.tsx b/apps/mobile/src/j5/agents/AgentLibrarySettingsScreen.tsx index 3c7aeabd6ff73..a7e941fd75263 100644 --- a/apps/mobile/src/j5/agents/AgentLibrarySettingsScreen.tsx +++ b/apps/mobile/src/j5/agents/AgentLibrarySettingsScreen.tsx @@ -48,7 +48,7 @@ import { PlaybookLibrarySettingsSection } from "../playbooks/PlaybookLibrarySett export function AgentLibrarySettingsScreen() { // Personas and Playbooks are managed by a server's Owners (People and access AC27). return useOwnerSomewhere() === false ? ( - + diff --git a/apps/mobile/src/j5/upstreamSeams.test.ts b/apps/mobile/src/j5/upstreamSeams.test.ts index 058aa4de24d4d..01dc13a055c30 100644 --- a/apps/mobile/src/j5/upstreamSeams.test.ts +++ b/apps/mobile/src/j5/upstreamSeams.test.ts @@ -183,7 +183,7 @@ const SEAMS: ReadonlyArray = [ file: "features/settings/SettingsRouteScreen.tsx", record: "PR #75–#86 role library: Personas settings", from: "", - reaches: ['page("SettingsAgents", "person.2", "Personas")'], + reaches: ['page("SettingsAgents", "person.2", "Agent Setup")'], }, { file: "features/home/useThreadListActions.ts", diff --git a/apps/server/src/j5/a2a/AgentCrewProposalService.ts b/apps/server/src/j5/a2a/AgentCrewProposalService.ts index af25c4de14406..de82931ed6973 100644 --- a/apps/server/src/j5/a2a/AgentCrewProposalService.ts +++ b/apps/server/src/j5/a2a/AgentCrewProposalService.ts @@ -84,6 +84,8 @@ export interface CrewProposal { readonly crewInstanceId: string | null; readonly kind: CrewProposalKind; readonly status: CrewProposalStatus; + readonly approvalMode?: "human" | "automatic"; + readonly refusalDetail?: string | null; readonly brief: string; readonly displayName: string; readonly requestedSeats: ReadonlyArray; @@ -99,6 +101,7 @@ export interface CrewProposal { } export interface CreateCrewProposalInput { + readonly approvalMode?: "human" | "automatic"; readonly id: string; readonly projectId: LedgerProjectId; readonly captainParticipantId: ParticipantId; @@ -148,6 +151,7 @@ export interface AgentCrewProposalServiceShape { readonly approvedSeats: ReadonlyArray | null; readonly resolvedAt: string; readonly decidedBy?: string | null | undefined; + readonly refusalDetail?: string; }) => Effect.Effect; /** Approved proposals whose launch report has not reached the Captain yet. */ readonly listUnreported: () => Effect.Effect, SqlError>; @@ -180,6 +184,8 @@ interface Row { readonly resolved_at: string | null; readonly reported_at: string | null; readonly decided_by: string | null; + readonly approval_mode: "human" | "automatic"; + readonly refusal_detail: string | null; readonly playbook_name: string | null; readonly playbook_definition_path: string | null; } @@ -200,6 +206,8 @@ const fromRow = (row: Row): CrewProposal => ({ resolvedAt: row.resolved_at, reportedAt: row.reported_at, decidedBy: row.decided_by, + approvalMode: row.approval_mode, + refusalDetail: row.refusal_detail, playbook: row.playbook_name === null || row.playbook_definition_path === null ? null @@ -229,13 +237,13 @@ export const layer: Layer.Layer | null; readonly resolvedAt: string; readonly decidedBy?: string | null | undefined; + readonly refusalDetail?: string; }) { const approvedSeats = input.decision === "approve" && input.approvedSeats !== null @@ -313,7 +322,8 @@ export const layer: Layer.Layer items.filter((proposal) => proposal.approvalMode !== "automatic")), Effect.flatMap((open) => Effect.forEach(open, projectProposal)), Effect.map((listed) => ({ proposals: listed })), ), diff --git a/apps/server/src/j5/a2a/CrewLaunchService.ts b/apps/server/src/j5/a2a/CrewLaunchService.ts index d1cea8264bd3b..f85c9fc9fcb09 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.ts @@ -469,9 +469,8 @@ export const layer = Layer.effect( }), ), ); - // Every seat reaching this point was approved by a human, and that approval is the - // authority: explicit runtime choices override the persona sandbox while its behavior - // instructions remain pinned to the original snapshot. + // Explicit runtime choices override the persona sandbox for both human-approved and + // automatic launches; behavior instructions stay pinned to the original snapshot. const policy = translateAgentPersonaProviderPolicy( assignment.authorityPolicy, assignment.resolvedDriver, diff --git a/apps/server/src/j5/a2a/CrewProposalService.test.ts b/apps/server/src/j5/a2a/CrewProposalService.test.ts index 95f9c366bab86..3cb54a0cd2a75 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.test.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.test.ts @@ -14,7 +14,6 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; -import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; @@ -76,7 +75,9 @@ import { CrewProposalService, layer as crewProposalLayer, type ResolveCrewProposalInput, + type RequestCrewMemberInput, } from "./CrewProposalService.ts"; +import * as ServerSettings from "../../serverSettings.ts"; import { A2ALedger, layer as ledgerLayer } from "./LedgerService.ts"; import { participantIdForThread } from "./HomeRegistrar.ts"; import { runMigrations } from "../../persistence/Migrations.ts"; @@ -275,6 +276,32 @@ const withPreview = (gate: CrewProposalService["Service"]): CrewProposalService[ }), }); +// Seed a pre-upgrade pending addition to exercise the legacy preview and human-resolution path. +const legacyAddition = (input: RequestCrewMemberInput) => + Effect.gen(function* () { + const crews = yield* AgentCrewInstanceService; + const instance = (yield* crews.read(input.crewInstanceId!))!; + const proposal = yield* (yield* AgentCrewProposalService).create({ + id: lifecycleId({ + kind: "crew", + operation: "proposal", + providerSessionId: "j5-crew-proposal", + requestKey: input.requestKey, + }), + projectId: input.captain.projectId, + captainParticipantId: input.captain.participantId, + captainThreadId: input.captain.thread.id, + crewInstanceId: instance.id, + kind: "addition", + brief: input.brief ?? instance.brief, + displayName: instance.displayName, + requestedSeats: [input.seat], + createdAt: DateTime.formatIso(createdAt), + playbook: instance.playbook, + }); + return { proposal, instance }; + }); + /** A live Crew of `size` scout seats, approved through the gate; the seat names are s0, s1, ... */ const seedCrew = (gate: CrewProposalService["Service"], requestKey: string, size: number) => Effect.gen(function* () { @@ -308,6 +335,7 @@ const fixtureWithDatabase = Effect.fn("test.crewProposal.fixture")(function* ( readonly beforeAdmit?: Effect.Effect; readonly afterCreate?: Effect.Effect; readonly afterAdmit?: Effect.Effect; + readonly settings?: Parameters[0]; } = {}, ) { const database = NodeSqliteClient.layer({ filename }); @@ -376,6 +404,7 @@ const fixtureWithDatabase = Effect.fn("test.crewProposal.fixture")(function* ( ), }); const layer = crewProposalLayer.pipe( + Layer.provideMerge(ServerSettings.layerTest(options.settings)), Layer.provideMerge(flakyStore), Layer.provideMerge(fakeLauncher(crews)), Layer.provideMerge( @@ -448,8 +477,10 @@ const fixtureWithDatabase = Effect.fn("test.crewProposal.fixture")(function* ( captainModel, }; }); +const fixtureWithSettings = (settings: Parameters[0] = {}) => + fixtureWithDatabase(":memory:", { settings }); -const fixture = fixtureWithDatabase(":memory:"); +const fixture = fixtureWithSettings(); it.effect( "counts the person's roster decision, telling an edited roster from an unchanged one", @@ -611,9 +642,9 @@ it.effect( }).pipe(Effect.scoped), ); -it.effect("gates every roster on the human and gates additions with the seat cap", () => +it.effect("gates new rosters on the human and adds members directly with the seat cap", () => Effect.gen(function* () { - const { layer, notices } = yield* fixture; + const { layer } = yield* fixture; yield* Effect.gen(function* () { const gate = withPreview(yield* CrewProposalService); const opened = yield* gate.propose({ @@ -651,7 +682,9 @@ it.effect("gates every roster on the human and gates additions with the seat cap }, brief: null, }); - assert.equal(request.proposal.status, "open"); + assert.equal(request.proposal.status, "approved"); + assert.equal(request.proposal.approvalMode, "automatic"); + assert.lengthOf(request.instance!.members, 2); assert.equal(request.proposal.kind, "addition"); assert.equal(request.proposal.crewInstanceId, instance.id); assert.equal(request.proposal.brief, "Follow the release runbook."); @@ -736,18 +769,19 @@ it.effect("gates every roster on the human and gates additions with the seat cap }, brief: null, }); - assert.equal(custom.proposal.status, "open"); + assert.equal(custom.proposal.status, "approved"); assert.isNull(custom.proposal.requestedSeats[0]?.agentId); - yield* gate.resolve({ proposalId: custom.proposal.id, decision: "decline" }); - - const declined = yield* gate.resolve({ - proposalId: request.proposal.id, - decision: "decline", + assert.lengthOf(custom.instance!.members, 3); + const replay = yield* gate.requestMember({ + requestKey: "add-1", + captain, + crewInstanceId: instance.id, + seat: request.proposal.requestedSeats[0]!, + brief: null, }); - assert.equal(declined.proposal.status, "declined"); - assert.isNull(declined.instance); - const last = (yield* Ref.get(notices)).at(-1); - if (last?.type === "message.dispatch") assert.include(last.text, "decision: declined"); + assert.equal(replay.proposal.id, request.proposal.id); + assert.lengthOf(replay.instance!.members, 3); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listOpen(), 0); const tooMany = yield* gate .propose({ @@ -842,7 +876,7 @@ it.effect( assert.equal(again._tag, "CrewProposalNotOpenError"); // The human edits an addition on the card into a seat name the crew already has. - const addition = yield* gate.requestMember({ + const addition = yield* legacyAddition({ requestKey: "claim-add-1", captain, crewInstanceId: approved.instance!.id, @@ -877,7 +911,7 @@ it.effect( // An addition whose approval cannot be recorded after its seat is reserved releases the // reservation and stays open, so approving it again is not refused as a name clash. - const flaky = yield* gate.requestMember({ + const flaky = yield* legacyAddition({ requestKey: "flaky-add-1", captain, crewInstanceId: approved.instance!.id, @@ -983,7 +1017,7 @@ it.effect("holds every door to the same seat shape and seats nobody into a retir assert.equal(tooLong._tag, "CrewProposalRequestError"); const approved = yield* gate.resolve({ proposalId: opened.proposal.id, decision: "approve" }); - const addition = yield* gate.requestMember({ + const addition = yield* legacyAddition({ requestKey: "shape-add-1", captain, crewInstanceId: approved.instance!.id, @@ -1230,7 +1264,7 @@ it.effect( approvalToken: refreshed.approvalToken, }); assert.equal(approved.proposal.status, "approved"); - const addition = yield* gate.requestMember({ + const addition = yield* legacyAddition({ requestKey: "preview-addition", captain, crewInstanceId: approved.instance!.id, @@ -1459,14 +1493,14 @@ it.effect( const refused = outcomes.filter(Result.isFailure).map((result) => result.failure); assert.lengthOf(admitted, 1); assert.lengthOf(refused, 1); - assert.equal(admitted[0]!.proposal.status, "open"); + assert.equal(admitted[0]!.proposal.status, "approved"); assertCrewFull(refused[0]!); assert.include(refused[0]!.message, `holds 12 of ${CREW_SEAT_CAP} seats`); const openAdditions = (yield* proposals.listForCaptain(captainId)).filter( (proposal) => proposal.crewInstanceId === instance.id && proposal.status === "open", ); - assert.lengthOf(openAdditions, 1); - assert.lengthOf((yield* crews.read(instance.id))!.members, 11); + assert.lengthOf(openAdditions, 0); + assert.lengthOf((yield* crews.read(instance.id))!.members, 12); // The request holding seat twelve is found by its key before anything is counted, so a // retry is the same request, not a thirteenth seat. @@ -1474,14 +1508,14 @@ it.effect( const winnerKey = winner.requestedSeats[0]!.seat === "left" ? "race-a" : "race-b"; const replay = yield* request(winnerKey, winner.requestedSeats[0]!.seat); assert.equal(replay.proposal.id, winner.id); - assert.equal(replay.proposal.status, "open"); + assert.equal(replay.proposal.status, "approved"); assert.lengthOf( (yield* proposals.listForCaptain(captainId)).filter( (proposal) => proposal.crewInstanceId === instance.id && proposal.status === "open", ), - 1, + 0, ); - const approved = yield* gate.resolve({ proposalId: winner.id, decision: "approve" }); + const approved = admitted[0]!; assert.equal(approved.proposal.status, "approved"); assert.lengthOf(approved.instance!.members, 12); // Replayed after its seat launched: the seat name is now a member, and the retry still @@ -1599,7 +1633,7 @@ it.effect( }, ], }); - const addition = yield* gate.requestMember({ + const addition = yield* legacyAddition({ requestKey: "deleted-captain-add", captain, crewInstanceId: instance.id, @@ -1701,95 +1735,101 @@ const playbookStartTool = playbookTools.find( )!; const decodePlaybookStart = Schema.decodeUnknownEffect(playbookStartTool.parametersSchema); -const playbookFixture = Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "j5-crew-playbook-" }); - yield* fs.makeDirectory(path.join(workspaceRoot, ".j5/playbooks"), { recursive: true }); - const writePlaybook = (name: string, text: string) => - fs.writeFileString(path.join(workspaceRoot, ".j5/playbooks", `${name}.yaml`), text); - yield* writePlaybook("release", stringify(release())); - const database = NodeSqliteClient.layer({ filename: ":memory:" }); - const storage = Layer.mergeAll(crewInstanceLayer, proposalStoreLayer, ledgerLayer).pipe( - Layer.provideMerge(database), - ); - const context = yield* Layer.build(storage); - yield* Effect.provide( - Effect.gen(function* () { - yield* runJ5A2AMigrations(); - yield* seedPlaybookOwners([captainThread]); - yield* (yield* A2ALedger).ensureProject({ - projectId: projectId, - createdAt: DateTime.formatIso(createdAt), - }); - }), - context, - ); - const commands = yield* Ref.make>([]); - // Armed, provider reads wait until two approvals have both passed validation, so they race - // for the member store rather than one refusing in the other's wake. - const barrier = yield* Ref.make | null>(null); - const arrivals = yield* Ref.make(0); - const layer = crewProposalLayer.pipe( - Layer.provideMerge(crewLaunchLayer), - Layer.provideMerge(Layer.mock(CrewLaunchReporter)({ watch: () => Effect.void })), - Layer.provideMerge(playbookStoreLayer), - Layer.provideMerge(fakeSpawnWorkspaceLayer({ checkout: noRepository })), - Layer.provideMerge( - Layer.mock(ThreadManagementService)({ - getThreadProjection: (threadId) => - Effect.succeed({ - thread: thread(threadId), - messages: [], - } as unknown as OrchestrationV2ThreadProjection), - getThreadRecords: (threadId) => Effect.succeed({ thread: thread(threadId) } as never), - dispatch: (command) => - Ref.update(commands, (items) => [...items, command]).pipe( - Effect.as({ events: [], effects: [] } as never), - ), +const playbookFixtureWithSettings = ( + overrides: Parameters[0] = {}, +) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "j5-crew-playbook-" }); + yield* fs.makeDirectory(path.join(workspaceRoot, ".j5/playbooks"), { recursive: true }); + const writePlaybook = (name: string, text: string) => + fs.writeFileString(path.join(workspaceRoot, ".j5/playbooks", `${name}.yaml`), text); + yield* writePlaybook("release", stringify(release())); + const database = NodeSqliteClient.layer({ filename: ":memory:" }); + const storage = Layer.mergeAll(crewInstanceLayer, proposalStoreLayer, ledgerLayer).pipe( + Layer.provideMerge(database), + ); + const context = yield* Layer.build(storage); + yield* Effect.provide( + Effect.gen(function* () { + yield* runJ5A2AMigrations(); + yield* seedPlaybookOwners([captainThread]); + yield* (yield* A2ALedger).ensureProject({ + projectId: projectId, + createdAt: DateTime.formatIso(createdAt), + }); }), - ), - Layer.provideMerge( - Layer.mock(SpawnCompositionService)({ - recordFacts: (input) => - Effect.succeed({ - home: { projectId, participantId: participantIdForThread(input.threadId) }, - placement: { - projectId, - participantId: participantIdForThread(input.threadId), - provenance: input.provenance, - placementParentId: captainId, - createdEventSeq: 1, - updatedEventSeq: 1, - }, + context, + ); + const commands = yield* Ref.make>([]); + // Armed, provider reads wait until two approvals have both passed validation, so they race + // for the member store rather than one refusing in the other's wake. + const barrier = yield* Ref.make | null>(null); + const arrivals = yield* Ref.make(0); + const providers = yield* Ref.make>([codex]); + const layer = crewProposalLayer.pipe( + Layer.provideMerge(ServerSettings.layerTest(overrides)), + Layer.provideMerge(crewLaunchLayer), + Layer.provideMerge(Layer.mock(CrewLaunchReporter)({ watch: () => Effect.void })), + Layer.provideMerge(playbookStoreLayer), + Layer.provideMerge(fakeSpawnWorkspaceLayer({ checkout: noRepository })), + Layer.provideMerge( + Layer.mock(ThreadManagementService)({ + getThreadProjection: (threadId) => + Effect.succeed({ + thread: thread(threadId), + messages: [], + } as unknown as OrchestrationV2ThreadProjection), + getThreadRecords: (threadId) => Effect.succeed({ thread: thread(threadId) } as never), + dispatch: (command) => + Ref.update(commands, (items) => [...items, command]).pipe( + Effect.as({ events: [], effects: [] } as never), + ), + }), + ), + Layer.provideMerge( + Layer.mock(SpawnCompositionService)({ + recordFacts: (input) => + Effect.succeed({ + home: { projectId, participantId: participantIdForThread(input.threadId) }, + placement: { + projectId, + participantId: participantIdForThread(input.threadId), + provenance: input.provenance, + placementParentId: captainId, + createdEventSeq: 1, + updatedEventSeq: 1, + }, + }), + }), + ), + Layer.provideMerge( + Layer.mock(ProviderRegistry)({ + getProviders: Effect.gen(function* () { + const gate = yield* Ref.get(barrier); + if (gate !== null) { + if ((yield* Ref.updateAndGet(arrivals, (count) => count + 1)) === 2) + yield* Deferred.succeed(gate, undefined); + yield* Deferred.await(gate); + } + return yield* Ref.get(providers); }), - }), - ), - Layer.provideMerge( - Layer.mock(ProviderRegistry)({ - getProviders: Effect.gen(function* () { - const gate = yield* Ref.get(barrier); - if (gate !== null) { - if ((yield* Ref.updateAndGet(arrivals, (count) => count + 1)) === 2) - yield* Deferred.succeed(gate, undefined); - yield* Deferred.await(gate); - } - return [codex]; }), - }), - ), - Layer.provideMerge(Layer.succeedContext(context)), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { prefix: "j5-crew-playbook-state-" }), - ), - Layer.provideMerge(NodeServices.layer), - ); - const armBarrier = Effect.gen(function* () { - yield* Ref.set(arrivals, 0); - yield* Ref.set(barrier, yield* Deferred.make()); - }); - return { layer, workspaceRoot, writePlaybook, commands, armBarrier }; -}).pipe(Effect.provide(NodeServices.layer)); + ), + Layer.provideMerge(Layer.succeedContext(context)), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { prefix: "j5-crew-playbook-state-" }), + ), + Layer.provideMerge(NodeServices.layer), + ); + const armBarrier = Effect.gen(function* () { + yield* Ref.set(arrivals, 0); + yield* Ref.set(barrier, yield* Deferred.make()); + }); + return { layer, workspaceRoot, writePlaybook, commands, armBarrier, providers }; + }).pipe(Effect.provide(NodeServices.layer)); +const playbookFixture = playbookFixtureWithSettings(); /** Proposes the release Crew: planner owns plan, builder owns build, review is left unowned. */ const proposeRelease = ( @@ -1940,7 +1980,7 @@ it.effect("refuses a playbook Crew it cannot follow, each with a next step", () ); it.effect( - "two additions racing for one step: the first approval wins, the second is refused and stays open", + "two legacy additions racing for one step: the first approval wins, the second is refused and stays open", () => Effect.gen(function* () { const { layer, workspaceRoot, armBarrier } = yield* playbookFixture; @@ -1955,7 +1995,7 @@ it.effect( decision: "approve", })).instance!.id; const request = (seat: string) => - raw.requestMember({ + legacyAddition({ requestKey: seat, captain, crewInstanceId: crewId, @@ -2174,7 +2214,7 @@ it.effect("a Crew whose playbook file is gone still takes a seat that claims no seat: custom("helper"), brief: null, }); - const approved = yield* gate.resolve({ proposalId: filed.proposal.id, decision: "approve" }); + const approved = filed; assert.equal(approved.proposal.status, "approved"); const members = (yield* crews.read(crewId))!.members; assert.deepStrictEqual( @@ -2536,7 +2576,7 @@ it.effect.each(["approve", "decline"] as const)( ); it.effect.each(["approve", "decline"] as const)( - "replays an addition after %s with the original crew and omitted brief", + "replays a pending addition after %s with the original crew and omitted brief", (decision) => Effect.gen(function* () { const { layer, notices } = yield* fixture; @@ -2551,7 +2591,7 @@ it.effect.each(["approve", "decline"] as const)( brief: null, seat: custom("writer"), }; - const original = yield* gate.requestMember(input); + const original = yield* legacyAddition(input); assert.equal(original.proposal.brief, firstCrew.brief); for (const change of [ { crewInstanceId: secondCrew.id }, @@ -2582,6 +2622,48 @@ it.effect.each(["approve", "decline"] as const)( }), ); +it.effect("replays an automatic addition with the original crew and omitted brief", () => + Effect.gen(function* () { + const { layer, notices } = yield* fixture; + yield* Effect.gen(function* () { + const gate = withPreview(yield* CrewProposalService); + const firstCrew = yield* seedCrew(gate, "first-crew", 1); + const secondCrew = yield* seedCrew(gate, "second-crew", 1); + const input = { + requestKey: "addition-replay", + captain, + crewInstanceId: firstCrew.id, + brief: null, + seat: custom("writer"), + }; + const original = yield* gate.requestMember(input); + assert.equal(original.proposal.status, "approved"); + assert.equal(original.proposal.brief, firstCrew.brief); + for (const change of [ + { crewInstanceId: secondCrew.id }, + { brief: "Changed" }, + { seat: { ...input.seat, reason: "Changed" } }, + { seat: { ...input.seat, instructions: "Changed" } }, + { seat: { ...input.seat, workspace: { type: "worktree" as const, baseRef: "main" } } }, + ]) { + const refused = yield* gate.requestMember({ ...input, ...change }).pipe(Effect.flip); + assert.equal(refused._tag, "CrewProposalRequestError"); + assert.include(refused.message, original.proposal.id); + assert.include(refused.message, firstCrew.id); + assert.include(refused.message, "fresh client_request_id"); + } + const noticesBefore = yield* Ref.get(notices); + const replay = yield* gate.requestMember(input); + assert.equal(replay.proposal.id, original.proposal.id); + assert.equal(replay.proposal.status, "approved"); + assert.equal(replay.instance?.id, firstCrew.id); + assert.lengthOf(replay.instance!.members, 2); + assert.deepStrictEqual(yield* Ref.get(notices), noticesBefore); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listForCaptain(captainId), 3); + }).pipe(Effect.provide(layer)); + }), +); + it.effect( "an identical roster retry survives a disabled persona, while a fresh request is still validated", () => @@ -2663,17 +2745,7 @@ it.effect.each([ "concurrent $kind requests (different=$different) retain one proposal and compare the winning row", ({ kind, different }) => Effect.gen(function* () { - const entered = yield* Ref.make(0); - const both = yield* Deferred.make(); - const release = yield* Deferred.make(); - const barrier = Ref.updateAndGet(entered, (count) => count + 1).pipe( - Effect.tap((count) => (count === 2 ? Deferred.succeed(both, undefined) : Effect.void)), - Effect.andThen(Deferred.await(release)), - ); - const { layer } = yield* fixtureWithDatabase( - ":memory:", - kind === "roster" ? { beforeCreate: barrier } : { beforeAdmit: barrier }, - ); + const { layer } = yield* fixtureWithDatabase(":memory:"); yield* Effect.gen(function* () { const gate = withPreview(yield* CrewProposalService); const crew = kind === "addition" ? yield* seedCrew(gate, "nearly-full", 11) : null; @@ -2693,23 +2765,14 @@ it.effect.each([ brief, seat: custom("writer"), }); - const calls = yield* Effect.all( + // The proposal's lock serializes same-key requests; the second reads the first's stored row. + const results = yield* Effect.all( [ call("Original").pipe(Effect.result), call(different ? "Changed" : "Original").pipe(Effect.result), ], { concurrency: "unbounded" }, - ).pipe(Effect.forkChild({ startImmediately: true })); - yield* Effect.raceFirst( - Deferred.await(both), - Fiber.join(calls).pipe( - Effect.flatMap(() => - Effect.die(new Error("Requests completed before reaching both writes")), - ), - ), ); - yield* Deferred.succeed(release, undefined); - const results = yield* Fiber.join(calls); const successes = results.filter(Result.isSuccess); const failures = results.filter(Result.isFailure); assert.lengthOf(successes, different ? 1 : 2); @@ -2745,7 +2808,7 @@ it.effect.each([ }); assert.equal(replay.proposal.id, original.id); if (crew !== null) - assert.lengthOf((yield* (yield* AgentCrewInstanceService).read(crew.id))!.members, 11); + assert.lengthOf((yield* (yield* AgentCrewInstanceService).read(crew.id))!.members, 12); }).pipe(Effect.provide(layer)); }), ); @@ -3168,6 +3231,251 @@ it.effect.each(["roster", "addition"] as const)( }), ); +it.effect("auto-approves a roster once and keeps each seat's requested access", () => + Effect.gen(function* () { + const { layer, watched } = yield* fixtureWithSettings({ crewAutoApprove: true }); + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const settings = yield* ServerSettings.ServerSettingsService; + const input = { + requestKey: "automatic-roster", + captain, + displayName: "Automatic", + brief: "Review", + seats: [ + { + workspace: { type: "shared" as const }, + seat: "reviewer", + agentId: null, + reason: "Review", + instructions: "Review the change", + runtimeMode: "approval-required" as const, + }, + ], + }; + const [first, duplicate] = yield* Effect.all([gate.propose(input), gate.propose(input)], { + concurrency: "unbounded", + }); + assert.equal(first.proposal.status, "approved"); + assert.equal(first.proposal.approvalMode, "automatic"); + assert.equal(first.proposal.approvedSeats![0]!.runtimeMode, "approval-required"); + assert.equal(first.instance!.id, duplicate.instance!.id); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listOpen(), 0); + yield* settings.updateSettings({ crewAutoApprove: false }); + const replay = yield* gate.propose(input); + assert.equal(replay.proposal.status, "approved"); + assert.equal(replay.instance!.id, first.instance!.id); + assert.deepStrictEqual(yield* Ref.get(watched), [first.proposal.id]); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("project approval overrides beat the environment setting in both directions", () => + Effect.gen(function* () { + for (const global of [false, true]) { + const { layer } = yield* fixtureWithSettings({ + crewAutoApprove: global, + projectSettingsOverrides: { [captain.thread.projectId]: { crewAutoApprove: !global } }, + }); + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const outcome = yield* gate.propose({ + requestKey: `override-${global}`, + captain, + displayName: "Override", + brief: "Review", + seats: [ + { + workspace: { type: "shared" as const }, + seat: "scout", + agentId: "scout", + reason: "Inspect", + }, + ], + }); + assert.equal(outcome.proposal.status, global ? "open" : "approved"); + }).pipe(Effect.provide(layer)); + } + }).pipe(Effect.scoped), +); + +it.effect("turning on auto-approval leaves an existing human proposal open on retry", () => + Effect.gen(function* () { + const { layer } = yield* fixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const input = { + requestKey: "existing-human", + captain, + displayName: "Human", + brief: "Inspect", + seats: [ + { + workspace: { type: "shared" as const }, + seat: "scout", + agentId: "scout", + reason: "Inspect", + }, + ], + }; + const first = yield* gate.propose(input); + yield* (yield* ServerSettings.ServerSettingsService).updateSettings({ + crewAutoApprove: true, + }); + const replay = yield* gate.propose(input); + assert.equal(replay.proposal.id, first.proposal.id); + assert.equal(replay.proposal.status, "open"); + assert.isNull(replay.instance); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("refuses a signed-out provider before recording an automatic launch or addition", () => + Effect.gen(function* () { + const { layer, providers, commands } = yield* playbookFixtureWithSettings({ + crewAutoApprove: true, + }); + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const store = yield* AgentCrewProposalService; + const input = { + requestKey: "sign-in-roster", + captain, + displayName: "Sign in", + brief: "Inspect", + seats: [custom("scout")], + }; + yield* Ref.set(providers, [{ ...codex, auth: { status: "unauthenticated" } }]); + const refused = yield* gate.propose(input).pipe(Effect.flip); + assert.equal(refused._tag, "CrewLaunchSeatUnavailableError"); + assert.include(refused.message, "scout"); + assert.include(refused.message, "signed out"); + assert.lengthOf(yield* store.listForCaptain(captainId), 0); + yield* Ref.set(providers, [codex]); + const launched = yield* gate.propose(input); + yield* (yield* ServerSettings.ServerSettingsService).updateSettings({ + crewAutoApprove: false, + }); + const commandsBefore = (yield* Ref.get(commands)).length; + yield* Ref.set(providers, [{ ...codex, auth: { status: "unauthenticated" } }]); + const addition = yield* gate + .requestMember({ + requestKey: "sign-in-addition", + captain, + crewInstanceId: launched.instance!.id, + seat: custom("reviewer"), + brief: null, + }) + .pipe(Effect.flip); + assert.include(addition.message, "reviewer"); + assert.include(addition.message, "signed out"); + assert.lengthOf(yield* store.listForCaptain(captainId), 1); + assert.lengthOf( + (yield* (yield* AgentCrewInstanceService).read(launched.instance!.id))!.members, + 1, + ); + assert.lengthOf(yield* Ref.get(commands), commandsBefore); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect( + "direct additions preserve supervised access and launch only once on concurrent retries", + () => + Effect.gen(function* () { + const { layer, commands } = yield* playbookFixture; + yield* Effect.gen(function* () { + const gate = withPreview(yield* CrewProposalService); + const opened = yield* gate.propose({ + requestKey: "supervised-crew", + captain, + displayName: "Supervised", + brief: "Inspect", + seats: [custom("builder")], + }); + const crew = (yield* gate.resolve({ proposalId: opened.proposal.id, decision: "approve" })) + .instance!; + const input = { + requestKey: "supervised-addition", + captain, + crewInstanceId: crew.id, + seat: { ...custom("reviewer"), runtimeMode: "approval-required" as const }, + brief: null, + }; + const outcomes = yield* Effect.all([gate.requestMember(input), gate.requestMember(input)], { + concurrency: "unbounded", + }); + assert.equal(outcomes[0]!.proposal.status, "approved"); + assert.equal(outcomes[0]!.proposal.id, outcomes[1]!.proposal.id); + assert.lengthOf(outcomes[1]!.instance!.members, 2); + const starts = (yield* Ref.get(commands)).filter( + (command) => command.type === "thread.create" && command.title === "reviewer", + ); + assert.lengthOf(starts, 1); + assert.equal( + starts[0]?.type === "thread.create" ? starts[0].runtimeMode : null, + "approval-required", + ); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("refused concurrent additions release capacity and replay their original refusal", () => + Effect.gen(function* () { + const { layer, workspaceRoot, armBarrier } = yield* playbookFixture; + yield* Effect.gen(function* () { + const gate = withPreview(yield* CrewProposalService); + const opened = yield* proposeRelease(gate, workspaceRoot); + const launched = yield* gate.resolve({ proposalId: opened.proposal.id, decision: "approve" }); + yield* armBarrier; + const outcomes = yield* Effect.forEach( + ["review-a", "review-b"], + (name) => + Effect.result( + gate.requestMember({ + requestKey: name, + captain, + crewInstanceId: launched.instance!.id, + seat: custom(name, ["review"]), + brief: null, + }), + ), + { concurrency: "unbounded" }, + ); + assert.lengthOf(outcomes.filter(Result.isSuccess), 1); + const refused = outcomes.filter(Result.isFailure); + assert.lengthOf(refused, 1); + assert.include(refused[0]!.failure.message, "already owned"); + assert.equal(refused[0]!.failure._tag, "CrewProposalRequestError"); + assert.include(refused[0]!.failure.message, "new client_request_id"); + assert.notInclude(refused[0]!.failure.message, "Ask the Captain"); + const store = yield* AgentCrewProposalService; + const declined = (yield* store.listForCaptain(captainId)).find( + (proposal) => proposal.status === "declined", + )!; + assert.include(declined.refusalDetail!, "already owned"); + const rejectedSeat = declined.requestedSeats[0]!.seat; + const replay = yield* gate + .requestMember({ + requestKey: rejectedSeat, + captain, + crewInstanceId: launched.instance!.id, + seat: custom(rejectedSeat, ["review"]), + brief: null, + }) + .pipe(Effect.flip); + assert.equal(replay.message, refused[0]!.failure.message); + assert.include(replay.message, rejectedSeat); + assert.lengthOf(yield* store.listForCaptain(captainId), 3); + assert.lengthOf(yield* (yield* AgentCrewProposalService).listOpen(), 0); + assert.lengthOf( + (yield* (yield* AgentCrewInstanceService).read(launched.instance!.id))!.members, + 3, + ); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + it.effect( "an approved edit replaces the persona's instructions and leaves what the agent filed alone", () => diff --git a/apps/server/src/j5/a2a/CrewProposalService.ts b/apps/server/src/j5/a2a/CrewProposalService.ts index 37d982360d272..ff6fe1c7ba4ca 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.ts @@ -7,6 +7,8 @@ import type { } from "@t3tools/contracts/j5"; import { crewApprovalToken, crewPlaybookPlanDigest } from "./crewRuntimePreview.ts"; import { MessageId } from "@t3tools/contracts"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import * as ServerSettings from "../../serverSettings.ts"; import * as Context from "effect/Context"; import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; @@ -298,18 +300,21 @@ export const layer = Layer.effect( CrewProposalService, Effect.gen(function* () { const proposals = yield* AgentCrewProposalService; + const settings = yield* ServerSettings.ServerSettingsService; const crews = yield* AgentCrewInstanceService; const launcher = yield* CrewLaunchService; const reporter = yield* CrewLaunchReporter; const recordAnalytics = yield* j5AnalyticsRecorder; /** * The person's decision, as `feature.used`. Recorded here, not from the RPC, because only - * the proposal tells an edited roster from the one the Captain asked for. + * the proposal tells an edited roster from the one the Captain asked for. An automatic + * approval is no person's action, so it records nothing. */ const recordResolved = Effect.fn("j5.a2a.crewProposal.recordResolved")(function* ( proposal: CrewProposal, approved: ReadonlyArray | null, ) { + if (proposal.approvalMode === "automatic") return; yield* recordAnalytics("feature.used", { feature: "crew.proposal.resolve", variant: @@ -523,7 +528,7 @@ export const layer = Layer.effect( threadManagement, proposal.captainThreadId, ).pipe(Effect.mapError(operationError("reading the Captain thread"))); - // Checked when the person approves, not held: a Captain archived or deleted while its gate + // Checked at launch, not held: a Captain archived or deleted while its gate // is open is refused here, since new seats would be briefed to report to a participant // delivery no longer reaches. A Captain archived after this read is not caught. if (projection === null || projection.thread.deletedAt != null) @@ -638,164 +643,168 @@ export const layer = Layer.effect( }); }); - const replayProposal = Effect.fn("j5.a2a.crewProposal.replay")(function* ( - original: CrewProposal, - request: ProposalRequest, - ) { - if (requestDigest(proposalRequest(original)) !== requestDigest(proposalRequest(request))) - return yield* new CrewProposalRequestError( - requestReplayConflict( - `proposal ${original.id}${original.crewInstanceId === null ? "" : ` and crew ${original.crewInstanceId}`}`, - ), - ); - const instance = - original.crewInstanceId === null - ? null - : yield* crews - .read(original.crewInstanceId) - .pipe(Effect.mapError(operationError("reading the crew"))); - return { proposal: original, instance }; - }); - - const propose: CrewProposalServiceShape["propose"] = Effect.fn("j5.a2a.crewProposal.propose")( - function* (input) { - const id = lifecycleId({ - kind: "crew", - operation: "proposal", - providerSessionId: PROPOSAL_SESSION, - requestKey: input.requestKey, - }); - const original = yield* proposals - .read(id) - .pipe(Effect.mapError(operationError("reading the proposal"))); - const request = { - id, - projectId: input.captain.projectId, - captainParticipantId: input.captain.participantId, - captainThreadId: input.captain.thread.id, - crewInstanceId: null, - kind: "roster", - brief: input.brief, - displayName: input.displayName, - requestedSeats: input.seats, - createdAt: DateTime.formatIso(yield* DateTime.now), - playbook: + const propose: CrewProposalServiceShape["propose"] = (input) => { + const proposalId = lifecycleId({ + kind: "crew", + operation: "proposal", + providerSessionId: PROPOSAL_SESSION, + requestKey: input.requestKey, + }); + return gates.withLock( + proposalId, + Effect.gen(function* () { + const request = { + id: proposalId, + projectId: input.captain.projectId, + captainParticipantId: input.captain.participantId, + captainThreadId: input.captain.thread.id, + crewInstanceId: null, + kind: "roster", + brief: input.brief, + displayName: input.displayName, + requestedSeats: input.seats, + createdAt: DateTime.formatIso(yield* DateTime.now), + playbook: + input.playbook === undefined + ? null + : { name: input.playbook.name.replace(/\.yaml$/, "") }, + } satisfies ProposalRequest; + const original = yield* proposals + .read(proposalId) + .pipe(Effect.mapError(operationError("reading the proposal"))); + // The optional playbook summary describes fresh validation; replay never reads a changed definition. + if (original !== null) return yield* replayProposal(original, request); + const serverSettings = yield* settings.getSettings.pipe( + Effect.mapError(operationError("reading Crew approval settings")), + ); + const automatic = resolveProjectSettings(serverSettings, input.captain.thread.projectId) + .settings.crewAutoApprove; + const playbookRef = input.playbook === undefined ? null - : { name: input.playbook.name.replace(/\.yaml$/, "") }, - } satisfies ProposalRequest; - // The optional playbook summary describes fresh validation; a replay never reads a - // changed definition. - if (original !== null) return yield* replayProposal(original, request); - const playbookRef = - input.playbook === undefined - ? null - : yield* playbooks - .definitionPathFor(input.playbook.workspaceRoot, input.playbook.name) - .pipe( - Effect.map(({ stem, definitionPath }) => ({ name: stem, definitionPath })), - Effect.mapError(playbookRefusal(input.playbook.name, "propose")), - ); - const definition = - playbookRef === null ? null : yield* readPlaybook(playbookRef, "propose"); - const plan = yield* validateSeats( - input.seats, - null, - false, - definition === null ? null : { definition, existingMembers: [] }, - ); - const proposal = yield* proposals - .create({ - ...request, - playbook: playbookRef, - requestedSeats: withPersonaSwaps(input.seats, plan.swapsBySeat), - }) - .pipe(Effect.mapError(operationError("recording the proposal"))); - // Concurrent first attempts can both miss the read; the stored row decides which won. - return { ...(yield* replayProposal(proposal, request)), playbook: playbookOutcome(plan) }; - }, - ); + : yield* playbooks + .definitionPathFor(input.playbook.workspaceRoot, input.playbook.name) + .pipe( + Effect.map(({ stem, definitionPath }) => ({ name: stem, definitionPath })), + Effect.mapError(playbookRefusal(input.playbook.name, "propose")), + ); + const definition = + playbookRef === null ? null : yield* readPlaybook(playbookRef, "propose"); + const plan = yield* validateSeats( + input.seats, + null, + false, + definition === null ? null : { definition, existingMembers: [] }, + ); + if (automatic) + yield* resolveRuntime(input.captain, withPersonaSwaps(input.seats, plan.swapsBySeat)); + const proposal = yield* proposals + .create({ + ...request, + approvalMode: automatic ? "automatic" : "human", + playbook: playbookRef, + requestedSeats: withPersonaSwaps(input.seats, plan.swapsBySeat), + }) + .pipe(Effect.mapError(operationError("recording the proposal"))); + // The stored row decides what happened: an open automatic proposal is approved here. + return { + ...(yield* replayProposal(proposal, request)), + playbook: playbookOutcome(plan), + }; + }), + ); + }; - const requestMember: CrewProposalServiceShape["requestMember"] = Effect.fn( - "j5.a2a.crewProposal.requestMember", - )(function* (input) { - const commanded = yield* crews - .listForCaptain({ - projectId: input.captain.projectId, - captainParticipantId: input.captain.participantId, - }) - .pipe( - Effect.map((instances) => instances.filter((instance) => instance.archivedAt === null)), - Effect.mapError(operationError("reading commanded crews")), - ); - const instance = - input.crewInstanceId === null - ? commanded.length === 1 - ? commanded[0]! - : null - : (commanded.find(({ id }) => id === input.crewInstanceId) ?? null); - if (instance === null) - return yield* new CrewProposalRequestError({ - detail: - commanded.length === 0 - ? "You command no live crew, so there is nothing to add a member to." - : input.crewInstanceId === null - ? `You command ${commanded.length} crews; say which one.` - : `You do not command crew ${input.crewInstanceId}.`, - nextStep: - commanded.length === 0 - ? "Propose a crew with j5_propose_crew first." - : `Retry with crew_instance_id set to one of: ${commanded.map(({ id }) => id).join(", ")}.`, - }); + const requestMember: CrewProposalServiceShape["requestMember"] = (input) => { const proposalId = lifecycleId({ kind: "crew", operation: "proposal", providerSessionId: PROPOSAL_SESSION, requestKey: input.requestKey, }); - const request = { - id: proposalId, - projectId: input.captain.projectId, - captainParticipantId: input.captain.participantId, - captainThreadId: input.captain.thread.id, - crewInstanceId: instance.id, - kind: "addition", - brief: input.brief ?? instance.brief, - displayName: instance.displayName, - requestedSeats: [input.seat], - createdAt: DateTime.formatIso(yield* DateTime.now), - playbook: instance.playbook ?? null, - } satisfies CreateCrewProposalInput; - // Replays precede mutable catalog, playbook, seat-name and capacity validation. - const replayed = yield* proposals - .read(proposalId) - .pipe(Effect.mapError(operationError("reading the proposal"))); - if (replayed !== null) return yield* replayProposal(replayed, request); - const definition = yield* readFollowed(instance.playbook, [input.seat], "crew"); - const plan = yield* validateSeats( - [input.seat], - instance.members.map(({ seatName }) => seatName), - false, - definition === null ? null : { definition, existingMembers: memberSteps(instance) }, + return gates.withLock( + proposalId, + Effect.gen(function* () { + const commanded = yield* crews + .listForCaptain({ + projectId: input.captain.projectId, + captainParticipantId: input.captain.participantId, + }) + .pipe( + Effect.map((instances) => + instances.filter((instance) => instance.archivedAt === null), + ), + Effect.mapError(operationError("reading commanded crews")), + ); + const instance = + input.crewInstanceId === null + ? commanded.length === 1 + ? commanded[0]! + : null + : (commanded.find(({ id }) => id === input.crewInstanceId) ?? null); + if (instance === null) + return yield* new CrewProposalRequestError({ + detail: + commanded.length === 0 + ? "You command no live crew, so there is nothing to add a member to." + : input.crewInstanceId === null + ? `You command ${commanded.length} crews; say which one.` + : `You do not command crew ${input.crewInstanceId}.`, + nextStep: + commanded.length === 0 + ? "Propose a crew with j5_propose_crew first." + : `Retry with crew_instance_id set to one of: ${commanded.map(({ id }) => id).join(", ")}.`, + }); + const request = { + id: proposalId, + projectId: input.captain.projectId, + captainParticipantId: input.captain.participantId, + captainThreadId: input.captain.thread.id, + crewInstanceId: instance.id, + kind: "addition", + brief: input.brief ?? instance.brief, + displayName: instance.displayName, + requestedSeats: [input.seat], + createdAt: DateTime.formatIso(yield* DateTime.now), + playbook: instance.playbook ?? null, + } satisfies CreateCrewProposalInput; + // Replays precede mutable catalog, playbook, seat-name and capacity validation. + const existing = yield* proposals + .read(proposalId) + .pipe(Effect.mapError(operationError("reading the proposal"))); + if (existing !== null) return yield* replayProposal(existing, request); + const definition = yield* readFollowed(instance.playbook, [input.seat], "crew"); + const plan = yield* validateSeats( + [input.seat], + instance.members.map(({ seatName }) => seatName), + false, + definition === null ? null : { definition, existingMembers: memberSteps(instance) }, + ); + yield* resolveRuntime(input.captain, withPersonaSwaps([input.seat], plan.swapsBySeat)); + const admitted = yield* proposals + .admit( + { + ...request, + approvalMode: "automatic", + requestedSeats: withPersonaSwaps([input.seat], plan.swapsBySeat), + }, + { maxSeats: CREW_SEAT_CAP }, + ) + .pipe(Effect.mapError(operationError("recording the proposal"))); + if (admitted.status === "cap-exceeded") + return yield* crewFullError( + instance.displayName, + admitted.held, + admitted.adding, + "request", + ); + return { + ...(yield* replayProposal(admitted.proposal, request)), + playbook: playbookOutcome(plan), + }; + }), ); - const admitted = yield* proposals - .admit( - { ...request, requestedSeats: withPersonaSwaps([input.seat], plan.swapsBySeat) }, - { maxSeats: CREW_SEAT_CAP }, - ) - .pipe(Effect.mapError(operationError("recording the proposal"))); - if (admitted.status === "cap-exceeded") - return yield* crewFullError( - instance.displayName, - admitted.held, - admitted.adding, - "request", - ); - return { - ...(yield* replayProposal(admitted.proposal, request)), - playbook: playbookOutcome(plan), - }; - }); + }; /** * A roster approval that recorded its Crew and then failed before it resolved (its link or @@ -898,92 +907,161 @@ export const layer = Layer.effect( }, ); - const resolve: CrewProposalServiceShape["resolve"] = (input) => - gates.withLock( - input.proposalId, - Effect.gen(function* () { - // Who is answering rides on the proposal from here: both notices and the record read it. - const proposal = yield* proposals.read(input.proposalId).pipe( - Effect.mapError(operationError("reading the proposal")), - Effect.map((read) => - read === null ? null : { ...read, decidedBy: input.decidedBy ?? null }, + const resolveProposal = Effect.fn("j5.a2a.crewProposal.resolveProposal")(function* ( + input: ResolveCrewProposalInput, + automatic = false, + ): Effect.fn.Return { + // Who is answering rides on the proposal from here: both notices and the record read it. + const proposal = yield* proposals.read(input.proposalId).pipe( + Effect.mapError(operationError("reading the proposal")), + Effect.map((read) => + read === null ? null : { ...read, decidedBy: input.decidedBy ?? null }, + ), + ); + if (proposal === null) + return yield* new CrewProposalNotFoundError({ proposalId: input.proposalId }); + if (proposal.status !== "open") + return yield* new CrewProposalNotOpenError({ + proposalId: proposal.id, + status: proposal.status, + }); + if (input.decision === "decline") { + // Told before it is recorded: a notice or cleanup the store refused leaves the + // proposal open for the person to decline again, and the notice id is deterministic. + yield* retireUnlaunchedCrew(proposal); + yield* notifyDeclined(proposal); + const declined = yield* proposals + .resolve({ + id: proposal.id, + decision: "decline", + approvedSeats: null, + resolvedAt: DateTime.formatIso(yield* DateTime.now), + decidedBy: proposal.decidedBy, + }) + .pipe(Effect.mapError(operationError("recording the decline"))); + if (declined === null) + return yield* new CrewProposalNotOpenError({ + proposalId: proposal.id, + status: "resolved", + }); + yield* recordResolved(proposal, null); + return { proposal: declined, instance: null } satisfies CrewProposalOutcome; + } + const seats = input.seats ?? proposal.requestedSeats; + const { plan, definition } = yield* validateProposalSeats(proposal, seats); + const captain = yield* captainFor(proposal); + const resolved = yield* resolveRuntime(captain, seats); + if ( + !automatic && + input.approvalToken !== + crewApprovalToken(proposal, captain, resolved, planDigest(proposal.playbook, plan)) + ) + return yield* new CrewProposalRequestError({ + detail: + "The crew runtime preview is missing or has changed since it was shown: the roster, a seat's runtime, the playbook plan, a seat's workspace, or the Captain's branch or worktree may have changed.", + nextStep: "Refresh the preview and review the current settings before approving.", + }); + const launched = yield* fulfil( + proposal, + captain, + withPersonaSwaps(seats, plan.swapsBySeat), + resolved, + launchPlaybook(proposal.playbook, definition), + ).pipe( + // The member store is authoritative when concurrent additions claim the same step. + Effect.catchTags({ + CrewStepAlreadyOwnedError: (error) => + Effect.fail( + new CrewProposalRequestError({ + detail: `Step ${error.stepId} is already owned by seat ${error.ownerSeat}.`, + nextStep: "Ask the Captain to request the seat again with only unowned steps.", + }), ), - ); - if (proposal === null) - return yield* new CrewProposalNotFoundError({ proposalId: input.proposalId }); - if (proposal.status !== "open") - return yield* new CrewProposalNotOpenError({ - proposalId: proposal.id, - status: proposal.status, - }); - if (input.decision === "decline") { - // Told before it is recorded: a notice or cleanup the store refused leaves the - // proposal open for the person to decline again, and the notice id is deterministic. - yield* retireUnlaunchedCrew(proposal); - yield* notifyDeclined(proposal); - const declined = yield* proposals - .resolve({ - id: proposal.id, - decision: "decline", - approvedSeats: null, - resolvedAt: DateTime.formatIso(yield* DateTime.now), - decidedBy: proposal.decidedBy, - }) - .pipe(Effect.mapError(operationError("recording the decline"))); - if (declined === null) - return yield* new CrewProposalNotOpenError({ - proposalId: proposal.id, - status: "resolved", - }); - yield* recordResolved(proposal, null); - return { proposal: declined, instance: null } satisfies CrewProposalOutcome; - } - const seats = input.seats ?? proposal.requestedSeats; - const { plan, definition } = yield* validateProposalSeats(proposal, seats); - const captain = yield* captainFor(proposal); - const resolved = yield* resolveRuntime(captain, seats); - if ( - input.approvalToken !== - crewApprovalToken(proposal, captain, resolved, planDigest(proposal.playbook, plan)) - ) - return yield* new CrewProposalRequestError({ - detail: - "The crew runtime preview is missing or has changed since it was shown: the roster, a seat's runtime, the playbook plan, a seat's workspace, or the Captain's branch or worktree may have changed.", - nextStep: "Refresh the preview and review the current settings before approving.", - }); - const launched = yield* fulfil( - proposal, - captain, - withPersonaSwaps(seats, plan.swapsBySeat), - resolved, - launchPlaybook(proposal.playbook, definition), - ).pipe( - // The member store is the last word on ownership: two additions that both passed - // preview race to it, and the second is refused with nothing written and left open. - Effect.catchTags({ - CrewStepAlreadyOwnedError: (error) => - Effect.fail( - new CrewProposalRequestError({ - detail: `Step ${error.stepId} is already owned by seat ${error.ownerSeat}.`, - nextStep: "Ask the Captain to request the seat again with only unowned steps.", - }), - ), - }), - ); - const final = yield* proposals - .read(proposal.id) - .pipe(Effect.mapError(operationError("reading the approved proposal"))); - // The Captain hears once the seats have started or failed to start, not now: a - // dispatched brief is intent, and the report says what became of it. - yield* reporter.watch(proposal.id, launched.seats); - yield* recordResolved(proposal, seats); - return { - proposal: final ?? proposal, - instance: launched.instance, - } satisfies CrewProposalOutcome; }), ); + const final = yield* proposals + .read(proposal.id) + .pipe(Effect.mapError(operationError("reading the approved proposal"))); + // The Captain hears once the seats have started or failed to start, not now: a + // dispatched brief is intent, and the report says what became of it. + yield* reporter.watch(proposal.id, launched.seats); + yield* recordResolved(proposal, seats); + return { + proposal: final ?? proposal, + instance: launched.instance, + } satisfies CrewProposalOutcome; + }); + + const refusedAutomaticRequest = (proposal: CrewProposal, detail: string) => + new CrewProposalRequestError({ + detail: `Automatic request for ${proposal.requestedSeats.map(({ seat }) => seat).join(", ")} was refused: ${detail}`, + nextStep: + "Fix the reported problem, then submit a revised request with a new client_request_id.", + }); + + const approveAutomatically = (proposalId: string) => { + const refused = Effect.fn("j5.a2a.crewProposal.refused")(function* ( + error: CrewProposalError, + ): Effect.fn.Return { + const proposal = yield* proposals + .read(proposalId) + .pipe(Effect.mapError(operationError("reading the refused request"))); + const detail = error._tag === "CrewProposalRequestError" ? error.detail : error.message; + if (proposal?.status === "open") { + yield* retireUnlaunchedCrew(proposal); + yield* proposals + .resolve({ + id: proposalId, + decision: "decline", + refusalDetail: detail, + approvedSeats: null, + resolvedAt: DateTime.formatIso(yield* DateTime.now), + }) + .pipe(Effect.mapError(operationError("recording the refusal"))); + yield* recordResolved(proposal, null); + } + if (proposal === null) return yield* error; + return yield* refusedAutomaticRequest(proposal, detail); + }); + return resolveProposal({ proposalId, decision: "approve" }, true).pipe( + Effect.catchTags({ + CrewProposalRequestError: refused, + CrewLaunchSeatUnavailableError: refused, + CrewLaunchCapError: refused, + CrewLaunchSeatConflictError: refused, + CrewStepAlreadyOwnedError: refused, + }), + ); + }; + const replayProposal = Effect.fn("j5.a2a.crewProposal.replay")(function* ( + original: CrewProposal, + request: ProposalRequest, + ) { + if (requestDigest(proposalRequest(original)) !== requestDigest(proposalRequest(request))) + return yield* new CrewProposalRequestError( + requestReplayConflict( + `proposal ${original.id}${original.crewInstanceId === null ? "" : ` and crew ${original.crewInstanceId}`}`, + ), + ); + if (original.status === "declined" && original.approvalMode === "automatic") + return yield* refusedAutomaticRequest( + original, + original.refusalDetail ?? "The original refusal detail is unavailable.", + ); + if (original.status === "open" && original.approvalMode === "automatic") + return yield* approveAutomatically(original.id); + const instance = + original.crewInstanceId === null + ? null + : yield* crews + .read(original.crewInstanceId) + .pipe(Effect.mapError(operationError("reading the crew"))); + return { proposal: original, instance }; + }); + + const resolve: CrewProposalServiceShape["resolve"] = (input) => + gates.withLock(input.proposalId, resolveProposal(input)); return CrewProposalService.of({ propose, requestMember, preview, resolve }); }), ); diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index b954efd8b8099..e157b67721afb 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -65,7 +65,7 @@ it.effect("upgrades the current main schema with replay storage", () => yield* runJ5A2AMigrations(); const applied = yield* sql<{ readonly migration_id: number; readonly name: string }>` SELECT migration_id, name FROM j5_a2a_migrations - WHERE migration_id >= 47 ORDER BY migration_id + WHERE migration_id = 47 ORDER BY migration_id `; assert.deepStrictEqual(applied, [{ migration_id: 47, name: "RequestReplay" }]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), @@ -139,6 +139,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () { migration_id: 45, name: "McpClientApprovers" }, { migration_id: 46, name: "LocalDeliveryOrder" }, { migration_id: 47, name: "RequestReplay" }, + { migration_id: 48, name: "CrewApprovalMode" }, ]); assert.deepStrictEqual( migrationEntries.map(([id, name]) => [id, name]), @@ -190,6 +191,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () [45, "McpClientApprovers"], [46, "LocalDeliveryOrder"], [47, "RequestReplay"], + [48, "CrewApprovalMode"], ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), @@ -1438,7 +1440,7 @@ it.effect("recreates earlier-shaped crews tables when 14 runs over them", () => applied.map((row) => row.migration_id), [ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, ], ); const memberColumns = yield* sql<{ readonly name: string }>` diff --git a/apps/server/src/j5/a2a/Migrations.ts b/apps/server/src/j5/a2a/Migrations.ts index f54cf6c49cca9..cad75964dbc95 100644 --- a/apps/server/src/j5/a2a/Migrations.ts +++ b/apps/server/src/j5/a2a/Migrations.ts @@ -48,6 +48,7 @@ import Migration0044 from "./migrations/044_QueuedMessageEdits.ts"; import Migration0045 from "./migrations/045_McpClientApprovers.ts"; import Migration0046 from "./migrations/046_LocalDeliveryOrder.ts"; import Migration0047 from "./migrations/047_RequestReplay.ts"; +import Migration0048 from "./migrations/048_CrewApprovalMode.ts"; export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations"; @@ -106,6 +107,7 @@ export const migrationEntries = [ [45, "McpClientApprovers", Migration0045], [46, "LocalDeliveryOrder", Migration0046], [47, "RequestReplay", Migration0047], + [48, "CrewApprovalMode", Migration0048], ] as const; const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/j5/a2a/SpawnAgentService.ts b/apps/server/src/j5/a2a/SpawnAgentService.ts index 27cb86b31b5f4..2fa5ec1d18057 100644 --- a/apps/server/src/j5/a2a/SpawnAgentService.ts +++ b/apps/server/src/j5/a2a/SpawnAgentService.ts @@ -189,7 +189,7 @@ const preflightThreadSpawner = Effect.fn("j5.a2a.mcp.preflightThreadSpawner")(fu scope: McpThreadInvocationScope, ) { const caller = yield* preflightSpawnCaller(scope); - // Only a Captain grows a Crew, and only through the human gate (Bryant, 2026-09-14): a seat + // Only a Captain grows a Crew: a seat // that wants more hands escalates to its Captain; its own helpers are subagents. const membership = yield* (yield* AgentCrewInstanceService.AgentCrewInstanceService) .findMembership(caller.participantId) diff --git a/apps/server/src/j5/a2a/crewGateNotice.test.ts b/apps/server/src/j5/a2a/crewGateNotice.test.ts index d6839dcdfe22e..2ab1020544d54 100644 --- a/apps/server/src/j5/a2a/crewGateNotice.test.ts +++ b/apps/server/src/j5/a2a/crewGateNotice.test.ts @@ -284,4 +284,15 @@ describe("crew launch report", () => { assert.include(text, "Your crew is running."); assert.notInclude(text, "seat_failed"); }); + it("identifies automatic approval without attributing it to a person", () => { + const text = crewLaunchReportText({ + proposal: { ...proposal, approvalMode: "automatic" }, + instance, + verdicts: new Map(), + windowMs: 60_000, + }); + assert.include(text, "approval_mode: automatic"); + assert.include(text, "decision: approved"); + assert.notInclude(text, "decided_by:"); + }); }); diff --git a/apps/server/src/j5/a2a/crewGateNotice.ts b/apps/server/src/j5/a2a/crewGateNotice.ts index 0cc5dde917b04..90ce0917e3e16 100644 --- a/apps/server/src/j5/a2a/crewGateNotice.ts +++ b/apps/server/src/j5/a2a/crewGateNotice.ts @@ -110,7 +110,7 @@ const changesLine = (changes: CrewRosterChanges) => { // `decided_by` is there only in a shared conversation, where more than one person could have // answered (Shared conversations AC10); every other Captain reads the notice as it always was. const head = (proposal: CrewProposal, decision: "approved" | "declined") => - `\nproposal_id: ${proposal.id}\nkind: ${proposal.kind}\ndecision: ${decision}${proposal.decidedBy == null ? "" : `\ndecided_by: ${reportField(proposal.decidedBy)}`}\ncrew_name: ${proposal.displayName}`; + `\nproposal_id: ${proposal.id}\nkind: ${proposal.kind}${proposal.approvalMode === "automatic" ? "\napproval_mode: automatic" : ""}\ndecision: ${decision}${proposal.decidedBy == null ? "" : `\ndecided_by: ${reportField(proposal.decidedBy)}`}\ncrew_name: ${proposal.displayName}`; /** The platform-composed notice a Captain receives when the person declines: measured facts only. */ export const crewDeclinedNoticeText = (proposal: CrewProposal) => diff --git a/apps/server/src/j5/a2a/mcp/handlers.test.ts b/apps/server/src/j5/a2a/mcp/handlers.test.ts index 2c3fbf13e5e06..2cf3984195fdd 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.test.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.test.ts @@ -2355,6 +2355,7 @@ it.effect("routes crew proposals through a captain that is not itself a crew mem assert.deepStrictEqual(proposed.result, { proposal_id: `proposal:${invocation.providerSessionId}:propose-1`, status: "open", + approval_mode: "human", crew_instance_id: null, members: [], }); diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index 3947bab6fbcba..9bf40ff23091f 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -238,6 +238,7 @@ const crewProposalNextStep = (error: CrewProposalError) => const projectCrewProposal = (outcome: CrewProposalOutcome) => ({ proposal_id: outcome.proposal.id, status: outcome.proposal.status, + approval_mode: outcome.proposal.approvalMode ?? "human", crew_instance_id: outcome.instance?.id ?? null, members: (outcome.instance?.members ?? []).map((member) => ({ seat: member.seatName, @@ -795,7 +796,7 @@ const handlers = { Effect.mapError((error) => stateError( `The persona library cannot be read: ${error.message}`, - "Ask the user to fix the persona library in Settings → Personas, then retry j5_list_personas.", + "Ask the user to fix the persona library in Settings → Agent Setup, then retry j5_list_personas.", ), ), ); diff --git a/apps/server/src/j5/a2a/mcp/j5ToolPreapproval.ts b/apps/server/src/j5/a2a/mcp/j5ToolPreapproval.ts index cfb4ddfcc1c9c..72f3520b31e46 100644 --- a/apps/server/src/j5/a2a/mcp/j5ToolPreapproval.ts +++ b/apps/server/src/j5/a2a/mcp/j5ToolPreapproval.ts @@ -45,9 +45,10 @@ export const J5_PREAPPROVED_TOOLS: ReadonlyArray = [ ]; /** - * Interactive modes pre-approve routine communication, owner-thread playbook progress, and filing - * roster requests; the latter still require human approval in the app before any member launches. - * Lifecycle and spawning tools keep the harness's prompting in those modes. + * Interactive modes pre-approve routine communication, owner-thread playbook progress, and Crew + * staffing. A roster waits for the person unless the project's Crew approval is automatic, and + * `j5_request_crew_member` adds a member directly, so a Supervised Captain can start a Full-access + * custom member without review (Jackson accepted that, 2026-10-31). */ export const J5_COORDINATION_TOOLS: ReadonlyArray = [ "j5_send_message", diff --git a/apps/server/src/j5/a2a/mcp/tools.test.ts b/apps/server/src/j5/a2a/mcp/tools.test.ts index 0a2d9c9b63abe..87bf64443cf15 100644 --- a/apps/server/src/j5/a2a/mcp/tools.test.ts +++ b/apps/server/src/j5/a2a/mcp/tools.test.ts @@ -128,10 +128,8 @@ it("publishes the ratified single-target lifecycle contracts fail-closed", () => assert.include(J5ArchiveCrewTool.description ?? "", "confirmation_token"); assert.include(J5ArchiveCrewTool.description ?? "", "check with the user"); assert.isTrue(Context.get(J5ArchiveCrewTool.annotations, Tool.Destructive)); - // Proposals only file a human-gated request, and must say so: read-only Captains run with - // approval policy never and have refused the brief when the gate looked like a shell approval. - assert.isFalse(Context.get(J5ProposeCrewTool.annotations, Tool.Destructive)); - assert.isFalse(Context.get(J5RequestCrewMemberTool.annotations, Tool.Destructive)); + assert.isTrue(Context.get(J5ProposeCrewTool.annotations, Tool.Destructive)); + assert.isTrue(Context.get(J5RequestCrewMemberTool.annotations, Tool.Destructive)); assert.include(J5ProposeCrewTool.description ?? "", "including approval policy never"); assert.include(J5RequestCrewMemberTool.description ?? "", "including approval policy never"); // Declared handoffs are written by the seat itself with the project j5_write_artifact tool diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index 30b2a39f21150..18ffcc58fc386 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -443,6 +443,7 @@ export type J5RequestCrewMemberInput = typeof J5RequestCrewMemberInput.Type; export const J5CrewProposalResult = Schema.Struct({ proposal_id: NonEmptyString, status: Schema.Literals(["open", "approved", "declined"]), + approval_mode: Schema.optional(Schema.Literals(["human", "automatic"])), crew_instance_id: Schema.NullOr(NonEmptyString), members: Schema.Array( Schema.Struct({ @@ -561,10 +562,10 @@ const J5_LIST_AGENTS_DESCRIPTION = "List the personas in this environment: id, purpose, runtime policy, whether each can start now, and the provider, model, and reasoning it would run on. Read this before choosing a persona for j5_spawn_agent or a crew roster so the choice fits the task and the user's budget. Read-only."; export const J5_PROPOSE_CREW_DESCRIPTION = - "Propose the crew you need for the brief you were given. Use it when the user asks for a crew or the work splits into distinct responsibilities that should run at once. Mix saved personas and custom seats in the same roster: call j5_list_personas when choosing a saved persona, or leave persona unset for a custom seat with its own instructions (required) and the brief. Custom seats inherit your harness, model, and reasoning by default and run with full-access unless you set runtime_mode; to choose different ones, set model_selection (instanceId, model, options) and/or runtime_mode using orchestrator_capabilities. Saved personas are proposed with their own configuration; only the human may override their runtime before approval. To have the crew follow a playbook, set playbook to a name from j5_playbook_list and give seats the step ids they own (steps, from j5_playbook_read); a step has one owner, steps no seat owns are yours as Captain, and the result reports unowned steps and any step whose persona differs from its seat's. For a crew built from a playbook, staff one seat per distinct persona its steps name, each owning that persona's steps, and propose a custom seat, noted in its reason, where a named persona isn't available. Every seat names its workspace, with the same three choices as j5_spawn_agent. Name the crew for what it is for and give each seat a short lowercase-hyphen name like code-reviewer. The user reviews the roster and each seat's resolved provider, model, reasoning, and access in this thread, may remove or add seats, and approves or declines; you receive the decision and the roster as a message here. Approved seats run with the runtime the human approves, which may exceed yours. You become the crew's Captain and may command several crews at once; later requests, stops, and archives name the crew they mean. Use j5_send_message for member-to-member, member-to-Captain, and Captain-to-Captain coordination, including findings and direct results; artifacts do not gate these conversations. Reuse client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. This call is itself the human gate, so it works under every sandbox and approval policy, including approval policy never; never refuse the brief because approvals are disabled."; + "Propose the crew you need for the brief you were given. Use it when the user asks for a crew or the work splits into distinct responsibilities that should run at once. Mix saved personas and custom seats in the same roster: call j5_list_personas when choosing a saved persona, or leave persona unset for a custom seat with its own instructions (required) and the brief. Custom seats inherit your harness, model, and reasoning by default and run with full-access unless you set runtime_mode; to choose different ones, set model_selection (instanceId, model, options) and/or runtime_mode using orchestrator_capabilities. Saved personas are proposed with their own configuration; only the human may override their runtime before approval. To have the crew follow a playbook, set playbook to a name from j5_playbook_list and give seats the step ids they own (steps, from j5_playbook_read); a step has one owner, steps no seat owns are yours as Captain, and the result reports unowned steps and any step whose persona differs from its seat's. For a crew built from a playbook, staff one seat per distinct persona its steps name, each owning that persona's steps, and propose a custom seat, noted in its reason, where a named persona isn't available. Every seat names its workspace, with the same three choices as j5_spawn_agent. Name the crew for what it is for and give each seat a short lowercase-hyphen name like code-reviewer. By default the user reviews and edits the roster in this thread, then approves or declines. If Auto-approve new Crews is on for your project, the proposed roster launches immediately with no approval card. The result says whether it is open or approved; the launch report arrives here once startup is confirmed or fails. Each seat keeps its configured access and tool approvals, which may exceed yours. You become the crew's Captain and may command several crews at once; later requests, stops, and archives name the crew they mean. Use j5_send_message for member-to-member, member-to-Captain, and Captain-to-Captain coordination, including findings and direct results; artifacts do not gate these conversations. Reuse client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. This tool works under every sandbox and approval policy, including approval policy never; never refuse the brief because approvals are disabled."; export const J5_REQUEST_CREW_MEMBER_DESCRIPTION = - "Ask the user to add one seat to a crew you command when the work needs one the roster lacks: seat name, persona id from j5_list_personas (or none for a custom seat with required instructions and optional model_selection/runtime_mode overrides; an omitted model_selection inherits yours and an omitted runtime_mode is full-access; saved-persona runtime changes are made only by the human before approval), a clear reason identifying the concern and missing expertise or responsibility, its workspace (the same three choices as j5_propose_crew), and optionally instructions and a brief for the new seat. On a crew that follows a playbook, steps may claim step ids from j5_playbook_read that no seat owns yet. The user decides from their inbox; you receive the decision and the updated roster as a message here. Continue the already-approved work and direct coordination while the addition is pending. Captain-only; a member sends the concern and needed expertise to its Captain with j5_send_message. Reuse client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. Filing the request is the human gate itself and works under every approval policy, including approval policy never."; + "Add one seat directly to a running crew you command when the work needs expertise the roster lacks. No human approval is needed, regardless of Auto-approve new Crews. Give a seat name, a persona id from j5_list_personas or required instructions for a custom seat, a reason identifying the missing expertise, and its workspace (the same choices as j5_propose_crew). Custom seats inherit your model selection and run with full-access unless you set model_selection or runtime_mode; saved personas use their own configuration. Optionally give a brief; otherwise the seat gets the Crew's brief. On a playbook Crew, steps may claim only unowned step ids from j5_playbook_read. The result returns the updated roster or refuses the seat with its name and reason; startup is reported separately here. Each member's configured access still controls tool approvals. Captain-only: a member sends the concern to its Captain with j5_send_message. Reuse client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. Works under every approval policy, including approval policy never."; export const J5_STOP_AGENT_DESCRIPTION = "Stop one Peer Agent the way a user Stop does: its running turn is interrupted now, turns already queued behind it, messages you sent it included, are held until a person resumes its queue or the next message reaches it (that message resumes the queue and runs after them, in order), its pull request watches end, and the tasks it delegated stop too. The agent remains, stays readable, and can be messaged again later: stopping halts work, it retires nothing. It reaches any agent on this server, in any project. Reuse client_request_id to retry safely."; @@ -726,8 +727,7 @@ export const J5ProposeCrewTool = Tool.make("j5_propose_crew", { }) .annotate(Tool.Title, "Propose a Crew") .annotate(Tool.Readonly, false) - // Files a human-gated request; nothing spawns until the user approves it in the app. - .annotate(Tool.Destructive, false) + .annotate(Tool.Destructive, true) .annotate(Tool.Idempotent, false) .annotate(Tool.OpenWorld, true); @@ -741,7 +741,7 @@ export const J5RequestCrewMemberTool = Tool.make("j5_request_crew_member", { }) .annotate(Tool.Title, "Request a crew member") .annotate(Tool.Readonly, false) - .annotate(Tool.Destructive, false) + .annotate(Tool.Destructive, true) .annotate(Tool.Idempotent, false) .annotate(Tool.OpenWorld, true); diff --git a/apps/server/src/j5/a2a/migrations/048_CrewApprovalMode.test.ts b/apps/server/src/j5/a2a/migrations/048_CrewApprovalMode.test.ts new file mode 100644 index 0000000000000..dc7a7dc74bf4d --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/048_CrewApprovalMode.test.ts @@ -0,0 +1,24 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; +import { runJ5A2AMigrations } from "../Migrations.ts"; + +it.effect("preserves pre-upgrade addition decisions as human gates", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runJ5A2AMigrations({ toMigrationInclusive: 47 }); + yield* sql`INSERT INTO j5_a2a_project_ledger (project_id, created_at) VALUES ('project:legacy', '2026-10-27T00:00:00Z')`; + yield* sql`INSERT INTO j5_agent_crew_proposal (id, project_id, captain_participant_id, captain_thread_id, crew_instance_id, kind, status, brief, display_name, requested_seats, created_at) VALUES ('legacy', 'project:legacy', 'captain', 'thread:captain', NULL, 'addition', 'open', 'Review', 'Legacy', '[]', '2026-10-27T00:00:00Z')`; + const before = yield* sql`SELECT status, requested_seats FROM j5_agent_crew_proposal`; + yield* runJ5A2AMigrations(); + assert.deepStrictEqual( + yield* sql`SELECT status, requested_seats FROM j5_agent_crew_proposal`, + before, + ); + assert.deepStrictEqual( + yield* sql`SELECT approval_mode, refusal_detail FROM j5_agent_crew_proposal`, + [{ approval_mode: "human", refusal_detail: null }], + ); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); diff --git a/apps/server/src/j5/a2a/migrations/048_CrewApprovalMode.ts b/apps/server/src/j5/a2a/migrations/048_CrewApprovalMode.ts new file mode 100644 index 0000000000000..a2ebe77fa8dcc --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/048_CrewApprovalMode.ts @@ -0,0 +1,8 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE j5_agent_crew_proposal ADD COLUMN approval_mode TEXT NOT NULL DEFAULT 'human' CHECK (approval_mode IN ('human', 'automatic'))`; + yield* sql`ALTER TABLE j5_agent_crew_proposal ADD COLUMN refusal_detail TEXT`; +}); diff --git a/apps/server/src/j5/a2a/runtimeLayer.test.ts b/apps/server/src/j5/a2a/runtimeLayer.test.ts index f6b6791b4995d..180ee4e47ddd5 100644 --- a/apps/server/src/j5/a2a/runtimeLayer.test.ts +++ b/apps/server/src/j5/a2a/runtimeLayer.test.ts @@ -116,6 +116,7 @@ const measureNestedRuntimeBuilds = (nested: "http" | "mcp") => nested === "mcp" ? mcpConsumer.pipe(Layer.provide(Layer.fresh(runtime))) : mcpConsumer, ).pipe( Layer.provide(runtime), + Layer.provide(ServerSettingsService.layerTest()), Layer.provide(quietAccessLayer), Layer.provide(threadManagement), Layer.provide(emptyEventStore), diff --git a/apps/server/src/j5/a2a/spawnIds.test.ts b/apps/server/src/j5/a2a/spawnIds.test.ts index d72b667286354..cfa12ed7ff3d7 100644 --- a/apps/server/src/j5/a2a/spawnIds.test.ts +++ b/apps/server/src/j5/a2a/spawnIds.test.ts @@ -54,8 +54,8 @@ it("gives custom seats direct result and concern reporting without a mandatory a "use j5_send_message to coordinate directly with your Captain and other members", ); assert.include(text, "final result, supporting evidence, and any remaining blockers"); - assert.include(text, "j5_request_crew_member through the user's inbox"); - assert.include(text, "Continue already-approved work and coordination"); + assert.include(text, "j5_request_crew_member to add the seat directly"); + assert.include(text, "Continue your work and coordination"); assert.include(text, "A direct result is sufficient"); assert.include(text, `\n${crew.seatInstructions}\n`); assert.notInclude(text, ""); diff --git a/apps/server/src/j5/a2a/spawnIds.ts b/apps/server/src/j5/a2a/spawnIds.ts index 63481dbd9c806..9f69e3a2f1872 100644 --- a/apps/server/src/j5/a2a/spawnIds.ts +++ b/apps/server/src/j5/a2a/spawnIds.ts @@ -126,7 +126,7 @@ export const spawnFirstTurnText = (input: { crew.seatInstructions === undefined ? [] : [`\n${crew.seatInstructions}\n`]; - const collaboration = `\nResolve current participants with j5_list_participants and use j5_send_message to coordinate directly with your Captain and other members. Share useful findings, evidence, questions, and blockers immediately; do not wait for an artifact or coordination approval. Send your Captain your final result, supporting evidence, and any remaining blockers before finishing. If the roster lacks expertise needed to address a concern, tell your Captain what is missing and why so they can j5_request_crew_member through the user's inbox. Continue already-approved work and coordination while an addition is pending. A direct result is sufficient unless the user or your persona explicitly requires an artifact.\n`; + const collaboration = `\nResolve current participants with j5_list_participants and use j5_send_message to coordinate directly with your Captain and other members. Share useful findings, evidence, questions, and blockers immediately; do not wait for an artifact or coordination approval. Send your Captain your final result, supporting evidence, and any remaining blockers before finishing. If the roster lacks expertise needed to address a concern, tell your Captain what is missing and why so they can j5_request_crew_member to add the seat directly. Continue your work and coordination while the Captain handles staffing. A direct result is sufficient unless the user or your persona explicitly requires an artifact.\n`; // A persona's declared deliverable supplements the conversation; it never gates coordination. const obligation = crew.obligation === undefined diff --git a/apps/server/src/j5/agents/agentDelegation.ts b/apps/server/src/j5/agents/agentDelegation.ts index 1fe76bacfa0e4..fa789acda6ad7 100644 --- a/apps/server/src/j5/agents/agentDelegation.ts +++ b/apps/server/src/j5/agents/agentDelegation.ts @@ -24,7 +24,7 @@ export const J5DelegateTaskInput = Schema.Struct({ persona: Schema.optional( AgentPersonaId.annotate({ description: - "Persona ID to run the child as, taken from an @persona:ID mention or the Settings → Personas library. The server applies its instructions, model route, reasoning, and runtime policy; omit target and runtimeMode when passing persona.", + "Persona ID to run the child as, taken from an @persona:ID mention or the Settings → Agent Setup library. The server applies its instructions, model route, reasoning, and runtime policy; omit target and runtimeMode when passing persona.", }), ), }); diff --git a/apps/server/src/j5/playbooks/PlaybookStore.ts b/apps/server/src/j5/playbooks/PlaybookStore.ts index 7ffd32faaa48a..23ed79b2a023d 100644 --- a/apps/server/src/j5/playbooks/PlaybookStore.ts +++ b/apps/server/src/j5/playbooks/PlaybookStore.ts @@ -83,7 +83,7 @@ const stepPersonaWarnings = ( stepId: step.id, persona: step.persona, message: unverified - ? `Step "${step.id}" names persona "${step.persona}", which could not be checked because some persona files are invalid. Check Settings → Personas.` + ? `Step "${step.id}" names persona "${step.persona}", which could not be checked because some persona files are invalid. Check Settings → Agent Setup.` : problem === "missing" ? `Step "${step.id}" names persona "${step.persona}", which is not in this environment's library.` : `Step "${step.id}" names persona "${step.persona}", which is turned off.`, diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 4cd371b7e2db4..44ba56e86c647 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -95,7 +95,7 @@ export const SETTINGS_SECTION_LABELS: Readonly> = { "/settings/diffs": "Diffs & pull requests", "/settings/keybindings": "Keybindings", "/settings/snap-shot": "SnapShots", - "/settings/personas": "Personas", + "/settings/personas": "Agent Setup", "/settings/skills": "Skills", "/settings/providers": "Providers", "/settings/threads": "Threads", @@ -771,10 +771,19 @@ export const SETTINGS_SEARCH_ITEMS = [ }, { id: "personas", - title: "Personas", + title: "Agent Setup", to: "/settings/personas", // "agents" stays a search hit: the library was called Agents until 2026-09-17. - searchTerms: ["agents saved agent library yaml definitions instructions runtime policy"], + searchTerms: [ + "personas crews playbooks agents saved agent library yaml definitions instructions runtime policy", + ], + }, + { + id: "crew-auto-approve", + title: "Auto-approve new Crews", + to: "/settings/personas", + targetId: "crew-auto-approve", + searchTerms: ["crew approval automatic roster captain"], }, { id: "skills", diff --git a/apps/web/src/j5/a2a/HumanInboxBell.tsx b/apps/web/src/j5/a2a/HumanInboxBell.tsx index c1404a5658b75..0e99b7bc1d341 100644 --- a/apps/web/src/j5/a2a/HumanInboxBell.tsx +++ b/apps/web/src/j5/a2a/HumanInboxBell.tsx @@ -5,12 +5,9 @@ import { inboxBellPresentation, mergeOpenInboxCounts } from "@t3tools/client-run import { useSidebar } from "../../components/ui/sidebar"; import { cn } from "../../lib/utils"; -import { inboxCrewRequests } from "../crew/crewProposals.logic"; -import { mergeCrewProposalSources, useCrewProposalsRefresh } from "../crew/crewProposalsClient"; import { inboxBadgeCount } from "../crew/crewRuntimeRequests.logic"; import { useCrewRuntimeRequests, useNativeQuestionInbox } from "../crew/crewRuntimeRequestsClient"; import { - crewProposalSourcesAtom, crewRuntimeRequestSourcesAtom, inboxCountQueryAtom, inboxCountSourcesAtom, @@ -25,14 +22,9 @@ const useCountRefresh = createVisibleRefreshHook(() => { export function HumanInboxBell({ onBackdrop }: { readonly onBackdrop: boolean }) { const { isMobile, setOpenMobile } = useSidebar(); const sources = useAtomValue(inboxCountSourcesAtom); - const crewSources = useAtomValue(crewProposalSourcesAtom); const merged = mergeOpenInboxCounts(sources); - // Mid-run seat requests and seats' provider approvals wait on the person too; the badge counts - // them beside open questions. The initial roster and the Captain's own requests are answered - // inline in the Captain's thread and stay off the inbox badge. - const crewRequests = inboxCrewRequests(mergeCrewProposalSources(crewSources)).length; const runtimeRequests = useCrewRuntimeRequests().length + useNativeQuestionInbox().length; - const count = inboxBadgeCount(merged.count, crewRequests, runtimeRequests); + const count = inboxBadgeCount(merged.count, runtimeRequests); const runtimeSources = useAtomValue(crewRuntimeRequestSourcesAtom); const incomplete = merged.incomplete || @@ -41,7 +33,6 @@ export function HumanInboxBell({ onBackdrop }: { readonly onBackdrop: boolean }) (source) => source.status !== "ready" && source.status !== "unsupported", ); useCountRefresh(); - useCrewProposalsRefresh(); const closeMobileSidebar = () => { if (isMobile) setOpenMobile(false); diff --git a/apps/web/src/j5/a2a/HumanInboxPage.tsx b/apps/web/src/j5/a2a/HumanInboxPage.tsx index 87d857d6b5e14..70facdb584db5 100644 --- a/apps/web/src/j5/a2a/HumanInboxPage.tsx +++ b/apps/web/src/j5/a2a/HumanInboxPage.tsx @@ -46,8 +46,6 @@ import { RelativeAge } from "../RelativeAge"; import { answerHumanExchange } from "./humanInboxClient"; import { useScopedParticipantLabels } from "./ParticipantIdentitiesClient"; import { presentParticipantIdentity } from "@t3tools/client-runtime/j5/participant-identity"; -import { CrewProposalCard } from "../crew/CrewProposalCard"; -import { clearCrewProposalDraft } from "../crew/crewProposalDraftStore"; import { CrewRuntimeRequestsSection } from "../crew/CrewRuntimeRequestsSection"; import type { ScopedCrewRuntimeRequest } from "../crew/crewRuntimeRequests.logic"; import { @@ -56,19 +54,9 @@ import { useNativeQuestionInbox, } from "../crew/crewRuntimeRequestsClient"; import { NativeQuestionInboxSection } from "./NativeQuestionInboxSection"; -import { inboxCrewRequests } from "../crew/crewProposals.logic"; -import { - mergeCrewProposalSources, - refreshCrewProposals, - resolveCrewProposal, - useCrewProposalsRefresh, - type CrewProposalSeat, - type ScopedCrewProposal, -} from "../crew/crewProposalsClient"; import { answeredInboxQueryAtom, answeredInboxSourcesAtom, - crewProposalSourcesAtom, crewRuntimeRequestSourcesAtom, j5Environment, openInboxQueryAtom, @@ -408,30 +396,6 @@ async function refreshHumanInboxes(environmentId?: EnvironmentId, force = false) if (failed?._tag === "Failure") throw Cause.squash(failed.cause); } -/** Resolves outside the component: the React Compiler cannot compile `throw` inside `try`. */ -async function resolveInboxProposal( - proposal: ScopedCrewProposal, - decision: "approve" | "decline", - seats: ReadonlyArray, - approvalToken: string | undefined, -): Promise { - try { - if (decision === "approve" && approvalToken === undefined) - throw new Error("Refresh the runtime preview before approving."); - await resolveCrewProposal( - proposal.environmentId, - decision === "approve" - ? { proposalId: proposal.id, decision, seats, approvalToken: approvalToken! } - : { proposalId: proposal.id, decision }, - ); - notifyHumanInboxChanged(proposal.environmentId); - await refreshCrewProposals(proposal.environmentId).catch(() => undefined); - return null; - } catch (cause) { - return cause instanceof Error ? cause.message : "Could not resolve the crew request."; - } -} - const useInboxRefresh = createVisibleRefreshHook(() => { void refreshJ5Sources(openInboxSourcesAtom, openInboxQueryAtom); }); @@ -510,10 +474,6 @@ export function HumanInboxPage() { const [error, setError] = useState(null); const answerAttempts = useRef(new Map()); useInboxRefresh(); - const crewSources = useAtomValue(crewProposalSourcesAtom); - const proposals = inboxCrewRequests(mergeCrewProposalSources(crewSources)); - const [resolvingProposalId, setResolvingProposalId] = useState(null); - useCrewProposalsRefresh(); const runtimeRequests = useCrewRuntimeRequests(); const runtimeSources = useAtomValue(crewRuntimeRequestSourcesAtom); const nativeQuestions = useNativeQuestionInbox(); @@ -601,28 +561,6 @@ export function HumanInboxPage() { }); }; - const resolveProposal = async ( - proposal: ScopedCrewProposal, - decision: "approve" | "decline", - seats: ReadonlyArray, - approvalToken?: string, - ) => { - setResolvingProposalId(proposal.id); - setError(null); - const failure = await resolveInboxProposal(proposal, decision, seats, approvalToken); - if (failure === null) clearCrewProposalDraft(proposal.environmentId, proposal.id); - else setError(failure); - setResolvingProposalId(null); - }; - const openCaptain = (proposal: ScopedCrewProposal) => { - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams( - scopeThreadRef(proposal.environmentId, ThreadId.make(proposal.captainThreadId)), - ), - }); - }; - const openCrewThread = ( request: Pick, ) => { @@ -659,10 +597,6 @@ export function HumanInboxPage() { {loading && items.length === 0 ? "Loading questions waiting on you…" : `${items.length} ${complete ? "open" : "loaded"} ${items.length === 1 ? "question" : "questions"}${ - proposals.length === 0 - ? "" - : ` · ${proposals.length} crew ${proposals.length === 1 ? "request" : "requests"}` - }${ runtimeRequests.length + nativeQuestions.length === 0 ? "" : ` · ${runtimeRequests.length + nativeQuestions.length} agent ${runtimeRequests.length + nativeQuestions.length === 1 ? "request" : "requests"}` @@ -707,28 +641,6 @@ export function HumanInboxPage() { ) : null} - {proposals.length > 0 ? ( -
-

- Crew requests -

-
    - {proposals.map((proposal) => ( - - void resolveProposal(proposal, decision, seats, approvalToken) - } - onOpenCaptain={() => openCaptain(proposal)} - /> - ))} -
-
- ) : null} - @@ -736,7 +648,6 @@ export function HumanInboxPage() { !loading && error === null && shownItems.length === 0 && - proposals.length === 0 && runtimeRequests.length === 0 && nativeQuestions.length === 0 ? (
diff --git a/apps/web/src/j5/agents/AgentLibrarySettings.tsx b/apps/web/src/j5/agents/AgentLibrarySettings.tsx index 23bebc5de9a52..c0e19c3335cd6 100644 --- a/apps/web/src/j5/agents/AgentLibrarySettings.tsx +++ b/apps/web/src/j5/agents/AgentLibrarySettings.tsx @@ -43,6 +43,9 @@ import { useSettingsScopeEnvironments } from "../settingsScopeEnvironment"; import { LIBRARY_FOR_OWNERS } from "@t3tools/client-runtime/j5/sharing"; import { useIsOwnerSomewhere, useOwnedEnvironmentIds } from "../sharing/access"; import { agentPersonaEnvironment } from "./agentPersonaAtoms"; +import { SettingsScopeNotice } from "../../components/settings/SettingsScopeNotice"; +import { AgentSetupLinks } from "./AgentSetupLinks"; +import { CrewApprovalSettings } from "../crew/CrewApprovalSettings"; import { PlaybookLibrarySettings } from "../playbooks/PlaybookLibrarySettings"; import { useEnvironmentQuery } from "../../state/query"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; @@ -61,13 +64,6 @@ import { Button } from "../../components/ui/button"; import { Switch } from "../../components/ui/switch"; import { Badge } from "../../components/ui/badge"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../../components/ui/tooltip"; -import { - Select, - SelectItem, - SelectPopup, - SelectTrigger, - SelectValue, -} from "../../components/ui/select"; import { SettingsPageContainer, SettingsRow, @@ -113,19 +109,16 @@ function MemberAgentLibrarySettings() { const rightPrimary = right.environmentId === primaryEnvironmentId; return Number(rightPrimary) - Number(leftPrimary) || left.label.localeCompare(right.label); }); - const { - candidates: pickerEnvironments, - pinnedEnvironmentId, - initialEnvironmentId, - } = useSettingsScopeEnvironments(orderedEnvironments, primaryEnvironmentId); - const [selectedEnvironmentId, setSelectedEnvironmentId] = useState( - initialEnvironmentId, + const { candidates: libraryEnvironments, initialEnvironmentId } = useSettingsScopeEnvironments( + orderedEnvironments, + primaryEnvironmentId, ); const effectiveEnvironmentId = - pinnedEnvironmentId ?? - (pickerEnvironments.some((environment) => environment.environmentId === selectedEnvironmentId) - ? selectedEnvironmentId - : (pickerEnvironments[0]?.environmentId ?? null)); + libraryEnvironments.length > 1 + ? null + : orderedEnvironments.some((entry) => entry.environmentId === initialEnvironmentId) + ? initialEnvironmentId + : null; const selectedEnvironment = orderedEnvironments.find( (environment) => environment.environmentId === effectiveEnvironmentId, ); @@ -372,45 +365,37 @@ function MemberAgentLibrarySettings() { ? [] : presentAgentPersonaCatalog(catalog.data); + if (libraryEnvironments.length > 1) + return ( + + +
+ + + + entry.environmentId)} + > + Choose an environment to manage its Personas and Playbooks. + +
+ + + + +
+ ); + return ( - {pinnedEnvironmentId === null && pickerEnvironments.length > 1 ? ( - - { - const environment = pickerEnvironments.find( - (candidate) => candidate.environmentId === value, - ); - if (environment) setSelectedEnvironmentId(environment.environmentId); - }} - > - - {selectedEnvironment?.label} - - - {pickerEnvironments.map((environment) => ( - - {environment.label} - - ))} - - - } - /> - - ) : null} + @@ -798,6 +783,7 @@ function MemberAgentLibrarySettings() { }} /> ) : null} + ); diff --git a/apps/web/src/j5/agents/AgentSetupLinks.browser.test.tsx b/apps/web/src/j5/agents/AgentSetupLinks.browser.test.tsx new file mode 100644 index 0000000000000..245c1756fcf47 --- /dev/null +++ b/apps/web/src/j5/agents/AgentSetupLinks.browser.test.tsx @@ -0,0 +1,94 @@ +import { + createHashHistory, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + RouterProvider, +} from "@tanstack/react-router"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { render } from "../../../test/render"; +import { AgentSetupLinks } from "./AgentSetupLinks"; + +const scope = { project: "repo:review", machine: "remote-server", checkout: "/repo/worktree" }; +const initialEntry = `/settings/personas?${new URLSearchParams(scope)}`; + +function desktopHistory(href = `file:///app/index.html#${initialEntry}`) { + const location = new URL(href); + const history = { + state: undefined as unknown, + length: 1, + pushState(state: unknown, _title: string, href?: string) { + this.state = state; + if (href) location.href = new URL(href, location).href; + this.length++; + }, + replaceState(state: unknown, _title: string, href?: string) { + this.state = state; + if (href) location.href = new URL(href, location).href; + }, + }; + return { + location, + history: createHashHistory({ + window: { location, history, addEventListener: vi.fn(), removeEventListener: vi.fn() }, + }), + }; +} + +function settingsRouter(history: ReturnType) { + const root = createRootRoute(); + const settings = createRoute({ + getParentRoute: () => root, + path: "/settings/personas", + validateSearch: (search) => search, + component: AgentSetupLinks, + }); + return createRouter({ routeTree: root.addChildren([settings]), history }); +} + +describe("Agent Setup section navigation", () => { + it.each([ + { desktop: false, label: "web" }, + { desktop: true, label: "desktop" }, + ])( + "preserves the settings route and scope when following section links on $label", + async ({ desktop }) => { + const shell = desktop ? desktopHistory() : null; + const history = shell?.history ?? createMemoryHistory({ initialEntries: [initialEntry] }); + const router = settingsRouter(history); + try { + await router.load(); + await using screen = await render(, { router: false }); + for (const section of ["crews", "playbooks", "personas"]) { + const label = + section === "crews" ? "Crews" : section === "playbooks" ? "Playbooks" : "Personas"; + const link = [...screen.container.querySelectorAll("a")].find( + (entry) => entry.textContent === label, + )!; + const destination = new URL( + link.getAttribute("href")!, + shell?.location ?? "http://localhost", + ); + const followed = desktop + ? desktopHistory(destination.href).history + : createMemoryHistory({ + initialEntries: [destination.pathname + destination.search + destination.hash], + }); + try { + const reloaded = settingsRouter(followed); + await reloaded.load(); + expect(reloaded.state.location.pathname).toBe("/settings/personas"); + expect(reloaded.state.location.search).toEqual(scope); + expect(reloaded.state.location.hash).toBe(section); + } finally { + followed.destroy(); + } + } + } finally { + history.destroy(); + } + }, + ); +}); diff --git a/apps/web/src/j5/agents/AgentSetupLinks.tsx b/apps/web/src/j5/agents/AgentSetupLinks.tsx new file mode 100644 index 0000000000000..6d65f34b9abd4 --- /dev/null +++ b/apps/web/src/j5/agents/AgentSetupLinks.tsx @@ -0,0 +1,32 @@ +import { Link } from "@tanstack/react-router"; + +export function AgentSetupLinks() { + return ( + + ); +} diff --git a/apps/web/src/j5/agents/settingsSearch.test.ts b/apps/web/src/j5/agents/settingsSearch.test.ts index 1c02abc45ddba..ab4303fe880c4 100644 --- a/apps/web/src/j5/agents/settingsSearch.test.ts +++ b/apps/web/src/j5/agents/settingsSearch.test.ts @@ -3,11 +3,13 @@ import { describe, expect, it } from "vite-plus/test"; import { searchSettings } from "../../components/settings/settingsSearch"; describe("persona library settings search", () => { - it("exposes the Personas destination, under its old name too", () => { + it("finds Agent Setup by its sections and old name", () => { expect(searchSettings("personas")[0]).toMatchObject({ id: "personas", to: "/settings/personas", }); - expect(searchSettings("agents").some((entry) => entry.id === "personas")).toBe(true); + for (const query of ["Agent Setup", "personas", "crews", "playbooks", "agents"]) { + expect(searchSettings(query).some((entry) => entry.id === "personas")).toBe(true); + } }); }); diff --git a/apps/web/src/j5/crew/CrewApprovalSettings.tsx b/apps/web/src/j5/crew/CrewApprovalSettings.tsx new file mode 100644 index 0000000000000..a2bfd635a0fee --- /dev/null +++ b/apps/web/src/j5/crew/CrewApprovalSettings.tsx @@ -0,0 +1,46 @@ +import { + SettingsRow, + SettingsSection, + SettingResetButton, +} from "../../components/settings/settingsLayout"; +import { + useScopedSettings, + useScopedSettingsMixed, + useUpdateScopedSettings, +} from "../../components/settings/useScopedSettings"; +import { Switch } from "../../components/ui/switch"; + +export function CrewApprovalSettings() { + const settings = useScopedSettings(); + const mixed = useScopedSettingsMixed(["crewAutoApprove"]); + const updateSettings = useUpdateScopedSettings(); + return ( + + updateSettings({ crewAutoApprove: false })} + /> + ) : null + } + control={ + updateSettings({ crewAutoApprove: enabled })} + /> + } + /> + + ); +} diff --git a/apps/web/src/j5/crew/crewProposals.logic.test.ts b/apps/web/src/j5/crew/crewProposals.logic.test.ts index 2adbdb8a29ad8..3693d3c6f910a 100644 --- a/apps/web/src/j5/crew/crewProposals.logic.test.ts +++ b/apps/web/src/j5/crew/crewProposals.logic.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { inboxCrewRequests, rosterGatesForThread } from "./crewProposals.logic"; +import { rosterGatesForThread } from "./crewProposals.logic"; import type { CrewProposal } from "./crewProposalsClient"; const proposal = (overrides: Partial): CrewProposal => ({ @@ -28,15 +28,18 @@ describe("crew gate routing", () => { proposal({ id: "resolved", status: "approved", resolvedAt: "2026-09-10T00:01:00.000Z" }), ]; - it("shows only this thread's open roster gate inline", () => { + it("shows this thread's open roster and legacy addition gates inline", () => { expect(rosterGatesForThread(proposals, "thread:captain").map((p) => p.id)).toEqual([ "roster-here", + "addition", ]); expect(rosterGatesForThread(proposals, null)).toEqual([]); expect(rosterGatesForThread(proposals, "thread:none")).toEqual([]); }); - it("sends only open additions to the inbox bell", () => { - expect(inboxCrewRequests(proposals).map((p) => p.id)).toEqual(["addition"]); + it("does not show automatic approvals as human gates", () => { + expect( + rosterGatesForThread([proposal({ approvalMode: "automatic" })], "thread:captain"), + ).toEqual([]); }); }); diff --git a/apps/web/src/j5/crew/crewProposals.logic.ts b/apps/web/src/j5/crew/crewProposals.logic.ts index d12e15221c2e5..f57db5a52b0e9 100644 --- a/apps/web/src/j5/crew/crewProposals.logic.ts +++ b/apps/web/src/j5/crew/crewProposals.logic.ts @@ -2,13 +2,10 @@ interface GateLike { readonly status: "open" | "approved" | "declined"; readonly kind: "roster" | "addition"; readonly captainThreadId: string; + readonly approvalMode?: "human" | "automatic"; } -/** - * Where each crew gate is answered. The initial roster is a planning question for the thread - * that asked it, so it renders inline above the Captain's composer; a mid-run addition arrives - * while the user may be anywhere, so it goes to the inbox bell like other questions. - */ +/** Initial rosters and legacy addition requests are answered in their Captain's thread. */ export const rosterGatesForThread = ( proposals: ReadonlyArray, threadId: string | null | undefined, @@ -18,11 +15,6 @@ export const rosterGatesForThread = ( : proposals.filter( (proposal) => proposal.status === "open" && - proposal.kind === "roster" && + proposal.approvalMode !== "automatic" && proposal.captainThreadId === threadId, ); - -export const inboxCrewRequests = ( - proposals: ReadonlyArray, -): ReadonlyArray => - proposals.filter((proposal) => proposal.status === "open" && proposal.kind === "addition"); diff --git a/apps/web/src/j5/crew/crewProposalsClient.ts b/apps/web/src/j5/crew/crewProposalsClient.ts index 14e570624f636..074a9b57cb1f7 100644 --- a/apps/web/src/j5/crew/crewProposalsClient.ts +++ b/apps/web/src/j5/crew/crewProposalsClient.ts @@ -60,7 +60,7 @@ export const refreshCrewProposals = (environmentId?: EnvironmentId) => ...(environmentId === undefined ? {} : { environmentId }), }); -/** The bell, the inbox page, and every composer's inline gate share this one refresh on focus. */ +/** Every composer's inline gate shares this refresh on focus. */ export const useCrewProposalsRefresh = createVisibleRefreshHook(() => { void refreshJ5Sources(crewProposalSourcesAtom, crewProposalsQueryAtom); }); diff --git a/apps/web/src/j5/crew/crewRuntimeRequests.logic.test.ts b/apps/web/src/j5/crew/crewRuntimeRequests.logic.test.ts index e70352af904ff..b20256b51425c 100644 --- a/apps/web/src/j5/crew/crewRuntimeRequests.logic.test.ts +++ b/apps/web/src/j5/crew/crewRuntimeRequests.logic.test.ts @@ -116,12 +116,12 @@ describe("Crew seat approvals in the Inbox", () => { }); it("counts seat approvals on the bell, up while waiting and back down once answered", () => { - expect(inboxBadgeCount(2, 0, 0)).toBe(2); - expect(inboxBadgeCount(2, 1, 3)).toBe(6); - expect(inboxBadgeCount(2, 1, 1)).toBe(4); + expect(inboxBadgeCount(2, 0)).toBe(2); + expect(inboxBadgeCount(2, 3)).toBe(5); + expect(inboxBadgeCount(2, 1)).toBe(3); // Asks unread, Crew items read: still counted; nothing at all reads as no badge. - expect(inboxBadgeCount(null, 0, 1)).toBe(1); - expect(inboxBadgeCount(null, 0, 0)).toBeNull(); + expect(inboxBadgeCount(null, 1)).toBe(1); + expect(inboxBadgeCount(null, 0)).toBeNull(); }); }); @@ -166,7 +166,7 @@ it("keeps native question links scoped to the owning environment without adding ]); expect(mergeCrewRuntimeRequestSources(input)).toEqual([]); expect(mergeNativeQuestionInboxSources(sources([[envA, []]]))).toEqual([]); - expect(inboxBadgeCount(0, 0, mergeNativeQuestionInboxSources(input).length)).toBe(2); + expect(inboxBadgeCount(0, mergeNativeQuestionInboxSources(input).length)).toBe(2); }); it("reads an async question summary even when presentation keeps the thread working", () => { diff --git a/apps/web/src/j5/crew/crewRuntimeRequests.logic.ts b/apps/web/src/j5/crew/crewRuntimeRequests.logic.ts index f599f9fadb0c6..0356d8825e1c9 100644 --- a/apps/web/src/j5/crew/crewRuntimeRequests.logic.ts +++ b/apps/web/src/j5/crew/crewRuntimeRequests.logic.ts @@ -100,9 +100,8 @@ export const crewApprovalReadPlan = ( */ export const inboxBadgeCount = ( openAsks: number | null, - crewSeatRequests: number, crewRuntimeRequests: number, ): number | null => { - const crew = crewSeatRequests + crewRuntimeRequests; + const crew = crewRuntimeRequests; return openAsks === null ? (crew > 0 ? crew : null) : openAsks + crew; }; diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index d16e612c15aa0..ff7c55216e5d4 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -189,7 +189,7 @@ user's budget. Read-only." Named `list_agents` until 2026-09-17. No inputs. Result: `personas[]` with `id`, `display_name`, `description`, `runtime_policy`, `availability` (`available`, `blocked`, `disabled`) and `route` (driver · model · reasoning, or -null when blocked). The same catalog Settings → Personas shows; disabled imports read as disabled, +null when blocked). The same catalog Settings → Agent Setup shows; disabled imports read as disabled, unroutable or unenforceable personas as blocked. This is the P-B(a) spawn listing the spawning guide asked for. @@ -204,24 +204,25 @@ unless you set runtime_mode; to choose different ones, set model_selection (inst options) and/or runtime_mode using orchestrator_capabilities. Saved personas are proposed with their own configuration; only the human may override their runtime before approval. To have the crew follow a playbook, set playbook to a name from j5_playbook_list and give seats the step ids they own -(steps, from j5_playbook_read); a step has one owner, steps no seat owns are yours as Captain, and the -result reports unowned steps and any step whose persona differs from its seat's. For a crew built -from a playbook, staff one seat per distinct persona its steps name, each owning that persona's -steps, and propose a custom seat, noted in its reason, where a named persona isn't available. Every -seat names its workspace, with the same three choices as j5_spawn_agent. Name the crew for what it is -for and give each seat a short lowercase-hyphen name like code-reviewer. The user reviews the roster -and each seat's resolved provider, model, reasoning, and access in this thread, may remove or add -seats, and approves or declines; you receive the decision and the roster as a message here. Approved -seats run with the runtime the human approves, which may exceed yours. You become the crew's Captain -and may command several crews at once; later requests, stops, and archives name the crew they mean. -Use j5_send_message for member-to-member, member-to-Captain, and Captain-to-Captain coordination, -including findings and direct results; artifacts do not gate these conversations. Reuse -client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. This call is itself the human gate, so it works under every -sandbox and approval policy, including approval policy never; never refuse the brief because -approvals are disabled." - -Published as non-destructive (`destructiveHint: false`): the call records a pending request and -nothing spawns until a human approves it. +(steps, from j5_playbook_read); a step has one owner, steps no seat owns are yours as Captain, and +the result reports unowned steps and any step whose persona differs from its seat's. For a crew +built from a playbook, staff one seat per distinct persona its steps name, each owning that +persona's steps, and propose a custom seat, noted in its reason, where a named persona isn't +available. Every seat names its workspace, with the same three choices as j5_spawn_agent. Name the +crew for what it is for and give each seat a short lowercase-hyphen name like code-reviewer. By +default the user reviews and edits the roster in this thread, then approves or declines. If +Auto-approve new Crews is on for your project, the proposed roster launches immediately with no +approval card. The result says whether it is open or approved; the launch report arrives here once +startup is confirmed or fails. Each seat keeps its configured access and tool approvals, which may +exceed yours. You become the crew's Captain and may command several crews at once; later requests, +stops, and archives name the crew they mean. Use j5_send_message for member-to-member, +member-to-Captain, and Captain-to-Captain coordination, including findings and direct results; +artifacts do not gate these conversations. Reuse client_request_id to retry safely; a changed +request is refused, so use a fresh one for new work. This tool works under every sandbox and +approval policy, including approval policy never; never refuse the brief because approvals are +disabled." + +Published with `destructiveHint: true`: depending on the project setting, this call can launch agents immediately. | Input | Type | Required | Meaning | | ------------------- | ----------------------------------------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -248,53 +249,41 @@ steps needs no readable definition, so a Crew whose playbook file is gone can st proposal records the playbook's definition path, and the Crew keeps it from approval on; each member records the step ids it owns, and each seat's first turn lists its steps by live title in a `` block. An open roster proposal waits for the human -gate inline above the Captain's composer (additions wait in the Inbox); approval spawns the approved roster (the human may have edited it) as Peer Agents under the +gate inline above the Captain's composer unless Auto-approve new Crews is enabled for the Captain's project; approval spawns the approved roster (the human may have edited it) as Peer Agents under the caller, persona-backed where a seat names one, records the Crew snapshot with each member's reason -(the person approves every seat), and posts +(with human or automatic approval recorded), and posts a `` launch report into the caller's thread once every seat has started or failed to start (or a minute has passed): the roster, what the user changed against the proposal, and per seat `start=started|failed|pending`, with a `seat_failed` line carrying the run's error (`not_started` when the seat's thread exists but its brief never went out) and a `seat_not_created` line for an approved seat whose thread was never created, which is left off the roster. A proposal resolves once: a seat that fails does not stop the others or reopen the gate. Declines post the decline at once. Every seat names its workspace, with the same three choices as `j5_spawn_agent`, so there is no Captain-aware default (Jackson, 2026-10-03). Each seat's workspace resolves at preview against the Captain's repository, and the approval token binds it, as it binds the Captain's branch and worktree. Every preview also carries the Captain's current branch, the directory its branch picker searches, and its worktrees, for the roster card's editor; the branches themselves are searched live, so no list is capped. A seat the person adds starts in the Captain's checkout. A seat recorded before workspaces were required stays readable but is refused at preview and approval until one is chosen. A new-worktree seat's brief starts once ThreadLaunch has prepared it, as for `j5_spawn_agent`, so the launch report may read `pending` for a seat whose setup outlasts the report's minute, and a failed preparation arrives as that seat's failure. -Human approval is the authority (Bryant, 2026-09-10): seats run with the runtime the person -approved, their persona's policy when no override was chosen, so a read-only Captain may command -writing seats once a person approved them; a seat's permissions never come from its Captain's. -There is no auto-approval: the earlier `runbook_declared` column and `auto_approved` status were -cut before shipping, since nothing wrote them and runbooks do not exist yet. +New Crews require human approval by default. **Settings → Agent Setup → Crews → Auto-approve new Crews** skips that gate, off by default and overridable per project. The server reads the Captain's project setting only for a new request; changing it leaves existing Crews and open proposals alone. Automatic approval launches the proposed configuration through the same provider, workspace, capacity, and persona checks. Tool approvals still follow each seat's access. The persisted proposal and launch report distinguish automatic approval from a human decision. ### `j5_request_crew_member` -**Description (contract):** "Ask the user to add one seat to a crew you command when the work needs -one the roster lacks: seat name, persona id from j5_list_personas (or none for a custom seat with -required instructions and optional model_selection/runtime_mode overrides; an omitted -model_selection inherits yours and an omitted runtime_mode is full-access; saved-persona runtime -changes are made only by the human before approval), a clear reason identifying the concern and -missing expertise or responsibility, its workspace (the same three choices as j5_propose_crew), and -optionally instructions and a brief for the new seat. On a crew that follows a playbook, steps may -claim step ids from j5_playbook_read that no seat owns yet. The user decides from their inbox; you -receive the decision and the updated roster as a message here. Continue the already-approved work -and direct coordination while the addition is pending. Captain-only; a member sends the concern and -needed expertise to its Captain with j5_send_message. Reuse client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. Filing -the request is the human gate itself and works under every approval policy, including approval -policy never." +**Description (contract):** "Add one seat directly to a running crew you command when the work needs +expertise the roster lacks. No human approval is needed, regardless of Auto-approve new Crews. Give +a seat name, a persona id from j5_list_personas or required instructions for a custom seat, a reason +identifying the missing expertise, and its workspace (the same choices as j5_propose_crew). Custom +seats inherit your model selection and run with full-access unless you set model_selection or +runtime_mode; saved personas use their own configuration. Optionally give a brief; otherwise the +seat gets the Crew's brief. On a playbook Crew, steps may claim only unowned step ids from +j5_playbook_read. The result returns the updated roster or refuses the seat with its name and +reason; startup is reported separately here. Each member's configured access still controls tool +approvals. Captain-only: a member sends the concern to its Captain with j5_send_message. Reuse +client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. +Works under every approval policy, including approval policy never." | Input | Type | Required | Meaning | | --------------------------------- | -------------- | -------- | --------------------------------------------------------------------------- | | `crew_instance_id` | string | no | Required only when the caller commands more than one live Crew | | `seat`, `persona` | string | yes | New seat name and persona id (none for a custom seat) | | `model_selection`, `runtime_mode` | object, string | no | Custom seats only; omitted, the Captain's model selection and `full-access` | -| `reason` | string | yes | One line the human reads before approving | +| `reason` | string | yes | The expertise the Crew needs | | `brief` | string | no | The new seat's brief; the Crew's brief when omitted | | `instructions` | string | no | Seat wiring text, verbatim | | `steps` | string[] | no | Playbook step ids no seat owns yet; only on a Crew that follows a playbook | | `workspace` | object | yes | Where the seat works; the same three choices as `j5_propose_crew` | | `client_request_id` | string | no | Supply and reuse to make retries safe | -Result: as `j5_propose_crew`. Semantics: the caller must command the Crew; the seat name must be new; -the cap counts current members plus seats in other open requests for the same Crew. Approval -reserves the seat inside one store transaction (count, cap, step ownership, version bump, and -ordinal decided together under an optimistic version check, so two approvals landing at once cannot -both pass; the second one claiming a taken step is refused and stays open), -then spawns the seat under the Captain and posts the updated roster to the Captain. If the approval -cannot be recorded, the reservation is released and the request stays open; once the seat starts -spawning the request is approved, and a seat that was never created is reported, not retried. +Result: as `j5_propose_crew`. Only the Captain can add a seat. The member is added directly regardless of the auto-approval setting, with the same validation and capacity checks as a launch. The result returns the updated roster or a refusal naming the seat and reason; the launch report later records its startup outcome. Retries reuse the original request and cannot add a second copy. A refused automatic request repeats its original reason on retry; a revised request needs a new `client_request_id`. Existing pending addition requests remain human decisions above their Captain's composer, where they can still be approved or declined; additions never appear in the Inbox or its bell count. Member tool approvals remain in the Inbox. ### Handoff artifacts in Crews @@ -392,7 +381,7 @@ run; `j5_stop_crew` doesn't, and unarchiving doesn't restart it. ### Kept upstream tools - `orchestrator_capabilities` — providers and models (ids, labels, option descriptors) for spawn targeting, plus runtime and interaction-mode facts. It deliberately stays silent about delegation even though `delegate_task` is back on the surface: that tool's own description carries its persona use, and J5 verbs are advertised by their own descriptions. -- `delegate_task`, `task_status`, `task_cancel` — upstream's provider-owned child delegation. J5 re-declares `delegate_task` with its own description, which leads with the optional `persona` (a persona id from an `@persona:ID` mention or the Settings → Personas library) and presents the plain child as the fallback for cross-provider or T3-tracked work rather than the default for any subagent request. With `persona`, the server pins that persona's instructions, model route, reasoning, and runtime policy and refuses `target` and `runtimeMode`; without it, the child is upstream's plain subagent. Upstream's `isolation: "worktree"` gives a child a checkout of its own, started from the parent's local commit, and the description says so in upstream's words. The child is backing storage under the calling thread, not a Peer Agent; use `j5_spawn_agent` for a participant. Its wait mode is safe where `t3_thread_wait` was not: a child that messages its parent ends its own turn, so the wait returns and the parent reads the message on its next turn (latency, never starvation). +- `delegate_task`, `task_status`, `task_cancel` — upstream's provider-owned child delegation. J5 re-declares `delegate_task` with its own description, which leads with the optional `persona` (a persona id from an `@persona:ID` mention or the Settings → Agent Setup library) and presents the plain child as the fallback for cross-provider or T3-tracked work rather than the default for any subagent request. With `persona`, the server pins that persona's instructions, model route, reasoning, and runtime policy and refuses `target` and `runtimeMode`; without it, the child is upstream's plain subagent. Upstream's `isolation: "worktree"` gives a child a checkout of its own, started from the parent's local commit, and the description says so in upstream's words. The child is backing storage under the calling thread, not a Peer Agent; use `j5_spawn_agent` for a participant. Its wait mode is safe where `t3_thread_wait` was not: a child that messages its parent ends its own turn, so the wait returns and the parent reads the message on its next turn (latency, never starvation). - `schedule_task` (which also updates a task since upstream folded `update_scheduled_task` into it at v0.1.3), `list_scheduled_tasks`, `delete_scheduled_task`, `run_scheduled_task_now` — consumed as-is. - `t3_thread_list`, `t3_thread_read` — consumed as-is; if an upstream description mentions delegation, J5 re-declares that tool with corrected prose. - `html_preview`, `html_render`, `request_secret`, `preview_dialog`, `preview_act`, `watch_pull_request`, `unwatch_pull_request` — consumed as-is. `preview_act` is upstream's one browser-control tool since v0.1.3, in place of `preview_click`, `preview_drag`, `preview_hover`, `preview_press`, `preview_scroll`, `preview_select`, `preview_type` and `preview_upload`. @@ -422,7 +411,7 @@ run; `j5_stop_crew` doesn't, and unarchiving doesn't restart it. 14. Unarchiving an archived agent restores the same participant id, placement and provenance and makes it addressable again; the Exchanges archiving closed stay closed and no cancelled delivery is replayed. 15. Retired (see History). 16. Retired (see History). -17. `j5_list_personas` returns every persona with its availability and route; `j5_propose_crew` and `j5_request_crew_member` file a human gate and refuse unknown, disabled, duplicate, or over-cap seats before anything is recorded; both succeed under every sandbox and approval policy, including Codex approval policy `never`. +17. `j5_list_personas` returns every persona with its availability and route. `j5_propose_crew` waits for human approval by default or launches directly when the Captain's project enables auto-approval. `j5_request_crew_member` adds directly in every case. Both validate seats and use the existing spawn checks, work under every sandbox and approval policy including `never`, and preserve each seat's tool approval policy. 18. Approving a proposal spawns exactly once; a second approval finds it resolved; a seat that fails to spawn is reported by name in the launch report and the other seats still start. 19. `j5_archive_crew` is Captain-only, refuses with per-seat facts and a token when any seat has an open Exchange or a running turn, and finishes a partial archive on retry; `t3_thread_organize` refuses an active Crew member, while Captain archive retains the unit cascade. 20. `j5_stop_crew` is Captain-only, stops every seat as a user Stop does and reports each seat as interrupted, already idle, or archived; it settles, retires, and closes nothing, and a non-Captain or an archived Crew is refused naming the next step. The person's Stop crew control does the same through the operate scope. diff --git a/docs/j5/product/agent-personas/index.md b/docs/j5/product/agent-personas/index.md index 5722d39f8b821..f593993d96082 100644 --- a/docs/j5/product/agent-personas/index.md +++ b/docs/j5/product/agent-personas/index.md @@ -18,17 +18,17 @@ Crew composition, Playbook steps, workflow gates, and lifecycle automation remai ## User-authored library -- Settings → Personas offers **Create persona**, which authors a personal persona (name, stable ID, description, markdown instructions, runtime policy, primary and fallback models) and stores it as an imported definition of the selected environment; the server supplies the remaining contract fields. It also offers one **Import** menu with **Persona file** (one YAML definition) and **Folder** (all YAML definitions, including subfolders). The selected files are copied into the selected environment, so the same flow works remotely. Up to 50 files of 64 KiB each are validated as one atomic batch. +- Settings → Agent Setup offers **Create persona**, which authors a personal persona (name, stable ID, description, markdown instructions, runtime policy, primary and fallback models) and stores it as an imported definition of the selected environment; the server supplies the remaining contract fields. It also offers one **Import** menu with **Persona file** (one YAML definition) and **Folder** (all YAML definitions, including subfolders). The selected files are copied into the selected environment, so the same flow works remotely. Up to 50 files of 64 KiB each are validated as one atomic batch. - Imported agents can be edited in Settings: name, description, instructions, runtime policy, and primary/fallback models with reasoning settings. Any listed agent, including removed folder sources, can be duplicated into a personal agent or exported as YAML. Changes apply only to the imported copy and future launches, preserve enabled state, and reject stale concurrent edits. - Every listed agent has an environment-local **On/Off** setting, including folder definitions. New imports start enabled; disabling prevents new launches and keeps the entry visible. Replacement imports preserve the setting; removing an import clears it. Source ids are disabled through a separate state file that never touches their files. Running tasks retain their snapshots. - UI imports show a confirmation for existing IDs: each conflicting agent has a replacement toggle. Cancel imports nothing; Import selected imports new agents and overwrites only the selected existing definitions, including local edits, while preserving enabled state and saved tasks. Toggled-off agents are skipped throughout the import. New or changed conflicts require fresh confirmation. Duplicate IDs within a selection fail the batch. The trash action removes the imported copy and excludes any underlying source definition, without altering running tasks. Removed source definitions stay listed as **Removed** with a **Restore** action, so removal from Settings is reversible without any file. Source edits require reimporting unless the server reads that folder directly through configuration. - A library combines imported copies with optional source folders on the selected environment's filesystem. Definitions are plain YAML files with markdown instruction content, editable and shareable through ordinary editors and git. Git is optional. Loading never clones, pulls, pushes, or executes a file. - For directly configured source folders, each `.yaml` or `.yml` file in the folder tree holds one definition; subfolders are walked recursively in sorted order (dot-directories such as `.git` are skipped), matching the import picker. JSON and other file types are ignored there and JSON is rejected on import. Configuration selects folders explicitly; order is preserved and filenames are sorted. Duplicate ids fail the library read rather than silently choosing a winner. - The default library folder is `personas` below the environment's state directory. An absent default folder, an existing empty folder, or an explicit empty folder list yields no source definitions; imports remain available. No bundled personas are added, and former example IDs are available for user-authored definitions. -- `/agent-personas.json` accepts `{ "folders": ["personas", "/absolute/team-library"] }`. Relative paths resolve from that environment's state directory. Configuration and source files are re-read at catalog requests and new activations; no restart or continuous watcher is required. Reopening Settings reads the library again. Settings → Personas → **Library sources** lists and edits this file through J5 RPCs, shows each folder's existence and definition count, and, for folders inside a git checkout, the two permitted nudges (uncommitted changes, remote ahead) plus an open-in-editor action on web/desktop. The server only reads `git status`; it never fetches, pulls, or commits. +- `/agent-personas.json` accepts `{ "folders": ["personas", "/absolute/team-library"] }`. Relative paths resolve from that environment's state directory. Configuration and source files are re-read at catalog requests and new activations; no restart or continuous watcher is required. Reopening Settings reads the library again. Settings → Agent Setup → **Library sources** lists and edits this file through J5 RPCs, shows each folder's existence and definition count, and, for folders inside a git checkout, the two permitted nudges (uncommitted changes, remote ahead) plus an open-in-editor action on web/desktop. The server only reads `git status`; it never fetches, pulls, or commits. - Every new catalog entry carries an `origin` (`imported` or `folder` with the source file path), shown as a badge. Clients retain the legacy `bundled` origin for compatibility with older environments. A per-agent usage line (tasks, runs, completed/failed, mean completed-run duration, provider-reported tokens, last launch, resolved routes) is aggregated from existing thread, run, and provider-turn projections on request through `getAgentPersonaUsage`; nothing new is persisted. - **Copy to environment** in a row's more menu reads the agent's YAML from the selected environment and imports it into another connected environment with the ordinary conflict confirmation; personal agents therefore stay environment-local by default and travel only on request. -- Invalid source files are excluded individually; Settings → Personas and `j5_list_personas` report their paths and validation reasons while valid personas remain available. Missing configured folders, malformed configuration, and duplicate ids produce a library error. A launch of an unavailable persona fails before thread creation. No missing or invalid source silently adds example personas. +- Invalid source files are excluded individually; Settings → Agent Setup and `j5_list_personas` report their paths and validation reasons while valid personas remain available. Missing configured folders, malformed configuration, and duplicate ids produce a library error. A launch of an unavailable persona fails before thread creation. No missing or invalid source silently adds example personas. - Source and imported definitions use the same validation. Historical definitions remain available only for resolving legacy assignments without snapshots; they do not populate the library or reserve IDs. ## Definition format @@ -201,7 +201,7 @@ Backups and environment migration must preserve snapshots together with the even ## Clients and activation -Settings → Personas displays the selected environment's persona library, including empty, error, available, and blocked states. Web and mobile use shared presentation logic; desktop inherits web. Clients neither load server-local files nor resolve models. Local, remote, relay, and tunnel clients use the same authenticated catalog RPC. +Settings → Agent Setup displays the selected environment's persona library, including empty, error, available, and blocked states. Web and mobile use shared presentation logic; desktop inherits web. Clients neither load server-local files nor resolve models. Local, remote, relay, and tunnel clients use the same authenticated catalog RPC. Activation continues through the existing orchestrator launch contract. No direct persona picker or editor is added in this slice. A launched task shows its snapshotted display name and fixed route. Runtime activity for launched provider children stays in upstream's Lineage section and subagent cards, separate from the persona library. diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index 686e059fdee33..b69939f8d6b3b 100644 --- a/docs/j5/product/features/crews.md +++ b/docs/j5/product/features/crews.md @@ -11,13 +11,13 @@ Complex work needs a group of agents with defined jobs working together with a h ## Definition -A **Crew** is a group of agents launched as a unit from a **roster its Captain proposes and the person approves**, composed for the brief in front of it. Nobody writes a Crew file in advance. The person asks the agent in an ordinary conversation to compose a Crew (web and desktop). The agent uses the conversation as context, keeps its current persona, model, and policy, and proposes the team before starting its work. There is no Crew slash command. No dedicated Captain agent exists; the agent that proposes becomes the Captain. It proposes a roster — a name, the brief every seat will start on, and a responsibility with a reason and instructions for each member. Saved personas are optional templates; a roster can mix them with custom members. A seat may name no persona at all: a **custom seat**, named and briefed by the Captain or the person, defaults to the Captain's provider, model, and reasoning but to Full access, with harness, model, reasoning, and access editable before approval, so a Crew need not fit a mold anyone saved before (Jackson and Bryant, 2026-09-17). The Captain's access is never carried: a seat nobody configured would otherwise stop for approvals in a thread the person is not watching (Jackson, 2026-09-26). Its instructions are required at every door, since nothing else defines it. The proposal is a **human gate** answered where it was asked: inline above the Captain's composer, like a planning question, and never on the inbox bell (reaffirmed by Bryant, 2026-09-14). The Captain is the thread the person watches, so its own tool approvals and questions are answered inline there too. A seat runs out of view, so its provider tool approvals are answered from the Inbox (Jackson, 2026-09-26). A seat has no native question tool: when it needs a decision it asks its Captain with `j5_send_message`, and the Captain answers, or asks the person with its own question tool, inline in the Captain thread (Jackson, 2026-09-26). Claude seats run without `AskUserQuestion` and Codex seats without `request_user_input`; Cursor exposes no structured native question tool. Other harnesses keep their native tools and the standing rule to ask the Captain. If a seat still raises a native question, its Captain receives a queued notice naming the question and its thread. The person also sees a link in the Inbox to answer in the seat's original question form (Bryant, 2026-10-19). The person may drop seats, select personas from the library, or create custom seats with names, instructions, and runtime settings. Every proposed or manually added member uses the same editor before approval. Saved personas supply defaults; the person may override harness, model, reasoning, and access for this member without changing the saved definition. Approval spawns every seat as a Peer Agent placed under the Captain, with a persona assignment only when the seat names a saved definition, records the roster snapshot (the _Manifest_ in implementation vocabulary: name, brief, members with each one's reason, version; the person approves every seat), and tells the Captain how the launch went once every seat has opened its first turn or failed to: one **launch report** naming what the person changed against the proposal and, per seat, started, failed with the run's error, or startup still unconfirmed after a minute. Dispatching a brief commits intent, not a running seat, so nothing is said before that (Jackson's dogfood, 2026-09-17). A decline is told at once. Each seat's first turn carries the platform's identity facts, the crew context and roster, any seat instructions, a handoff artifact obligation when its definition declares one, and the brief. +A **Crew** is a group of agents launched as a unit from a **roster its Captain proposes, approved by the person by default**, composed for the brief in front of it. Nobody writes a Crew file in advance. The person asks the agent in an ordinary conversation to compose a Crew (web and desktop). The agent uses the conversation as context, keeps its current persona, model, and policy, and proposes the team before starting its work. There is no Crew slash command. No dedicated Captain agent exists; the agent that proposes becomes the Captain. It proposes a roster — a name, the brief every seat will start on, and a responsibility with a reason and instructions for each member. Saved personas are optional templates; a roster can mix them with custom members. A seat may name no persona at all: a **custom seat**, named and briefed by the Captain or the person, defaults to the Captain's provider, model, and reasoning but to Full access, with harness, model, reasoning, and access editable before approval, so a Crew need not fit a mold anyone saved before (Jackson and Bryant, 2026-09-17). The Captain's access is never carried: a seat nobody configured would otherwise stop for approvals in a thread the person is not watching (Jackson, 2026-09-26). Its instructions are required at every door, since nothing else defines it. By default the proposal is a **human gate**, answered inline above the Captain's composer and never on the Inbox bell. **Settings → Agent Setup → Crews → Auto-approve new Crews** skips that gate when enabled for the Captain's project; it is off by default with project overrides. The setting is read for each new request, and changes leave existing Crews and open proposals alone. The Captain is the thread the person watches, so its own tool approvals and questions are answered inline there too. A seat runs out of view, so its provider tool approvals are answered from the Inbox (Jackson, 2026-09-26). A seat has no native question tool: when it needs a decision it asks its Captain with `j5_send_message`, and the Captain answers, or asks the person with its own question tool, inline in the Captain thread (Jackson, 2026-09-26). Claude seats run without `AskUserQuestion` and Codex seats without `request_user_input`; Cursor exposes no structured native question tool. Other harnesses keep their native tools and the standing rule to ask the Captain. If a seat still raises a native question, its Captain receives a queued notice naming the question and its thread. The person also sees a link in the Inbox to answer in the seat's original question form (Bryant, 2026-10-19). The person may drop seats, select personas from the library, or create custom seats with names, instructions, and runtime settings. Every proposed or manually added member uses the same editor before approval. Saved personas supply defaults; the person may override harness, model, reasoning, and access for this member without changing the saved definition. Approval spawns every seat as a Peer Agent placed under the Captain, with a persona assignment only when the seat names a saved definition, records the roster snapshot (the _Manifest_ in implementation vocabulary: name, brief, members with each one's reason and version), and tells the Captain how the launch went once every seat has opened its first turn or failed to: one **launch report** naming what the person changed against the proposal and, per seat, started, failed with the run's error, or startup still unconfirmed after a minute. Dispatching a brief commits intent, not a running seat, so nothing is said before that (Jackson's dogfood, 2026-09-17). A decline is told at once. Each seat's first turn carries the platform's identity facts, the crew context and roster, any seat instructions, a handoff artifact obligation when its definition declares one, and the brief. -**Membership changes only through the gate.** When the work needs a seat the roster lacks, the Captain asks for one agent with a reason and an optional brief for that seat. The request lands in the person's Inbox and counts on the bell, because the person may be anywhere mid-run; approval appends the seat to the snapshot and bumps its version, and either decision is posted to the Captain, who keeps working meanwhile. A Crew holds at most **twelve seats**, initial roster and additions together, counting requests still open. Crew members cannot propose or grow Crews — wanting more hands is an escalation to the Captain. +**Captains add members directly.** When the work needs expertise the roster lacks, the Captain adds one seat with a reason and optional brief. No human approval is needed, regardless of the auto-approval setting. The same launch checks apply; the tool returns the updated roster or a refusal naming the member and reason, and the launch report follows. A Crew holds at most **twelve seats**, counting open legacy requests. Members escalate staffing needs to their Captain. Pending addition requests from before this change remain approvable or declinable above their Captain's composer and stay off the Inbox and its bell. -**Human approval is the authority.** The person who approves a seat decides what access it runs with, so approved seats run with the person's chosen runtime settings, using their persona's policy when no access override is selected, even when the Captain is read-only; the gate shows each seat's persona or custom-seat choice, instructions, and resolved harness, model, reasoning level, and access before approval, and the Captain's reason for a seat stays readable in its row. Initial rosters and Inbox additions use the same preview. Approval binds the displayed roster and configuration; changed configuration requires a fresh review, and a launch uses the validated resolution rather than choosing a different route afterward. Seats are checked where they are structured: a persona missing from the library or turned off, a duplicate seat name, or a roster past the cap is refused to the Captain with the next step, before anyone spawns. Prose in a brief is never parsed or validated. +**Configured access controls tool approvals.** A seat runs with its proposed configuration, or the person's final configuration when a human approves it, using its persona's policy when no override is selected; the Captain may be read-only. The gate shows each seat's persona or custom-seat choice, instructions, and resolved harness, model, reasoning level, and access before approval, and the Captain's reason for a seat stays readable in its row. Human-approved rosters and legacy additions use the same preview. Automatically approved rosters and direct additions use the proposed configuration through the same runtime validation; their history records automatic approval. Automatic approval never changes a seat's tool approval policy. A custom member started automatically, by an auto-approved roster or a Captain's addition, defaults to Full access like any custom seat, so a Supervised Captain can start a Full-access member without review; that is accepted (Jackson, 2026-10-31), and the Agent Setup setting governs rosters only. Approval binds the displayed roster and configuration; changed configuration requires a fresh review, and a launch uses the validated resolution rather than choosing a different route afterward. Seats are checked where they are structured: a persona missing from the library or turned off, a duplicate seat name, or a roster past the cap is refused to the Captain with the next step, before anyone spawns. Prose in a brief is never parsed or validated. -**Several people.** Where more than one person can write to a Captain's thread, "the person" in this definition is any of them. The roster, a seat's approvals and a request for a further seat go to everyone who can write to that thread, and the first answer settles each; anyone who can write to the Captain's thread can write to its seats too ([shared conversations](shared-conversations.md), [people and access](people-and-access.md)). +**Several people.** Where more than one person can write to a Captain's thread, "the person" in this definition is any of them. The roster and a seat's tool approvals go to everyone who can write to that thread, and the first answer settles each; anyone who can write to the Captain's thread can write to its seats too ([shared conversations](shared-conversations.md), [people and access](people-and-access.md)). **Communication is direct; handoff artifacts record durable outputs.** Members exchange findings, questions, blockers, and results directly with one another and their Captain; Captains can coordinate with other Captains. Neither an artifact nor a human approval is required for these messages. Members send their final result with evidence and unresolved issues to the Captain. Active Codex GPT 6 and Claude runs accept peer steering, Claude once its running tool calls finish; other models and providers queue messages until the next safe turn boundary. A seat whose persona declares an output artifact (a Critic's ReviewHandoff, a Scout's ContextBrief) owes it as the same shared handoff artifact every persona writes — `handoffs//-.md` in the project's artifacts (see the [persona contract](../agent-personas/index.md)) — and its first turn names that exact path. The handoff gate checks for the file when a run ends and reminds the seat once. File existence is evidence of delivery, not validation or acceptance of the result; the Captain reviews the handoff artifact against the task. **Every seat tells its Captain when it finishes**, as measured facts: how the run ended first, the run's error when it failed, and whether its handoff artifact was written, missing, unavailable (with why), or never declared, with the artifact inline when short. A first turn that fails is a launch outcome, told once by the launch report and not again as a finish; and a seat's failure that its Captain hears this way is not repeated by the silence detector as an unanswered ask. The notice is posted the first time a seat finishes and again only when those facts change; a finish that would repeat the last notice word for word is silent, because the seat's own reply already reached the Captain. Notices that arrive while the Captain's turn is running fold into the one seat notice already queued behind that turn, so the Captain absorbs its Crew's news in one turn rather than one per seat. Notice delivery retries on a later finish or the next server startup if dispatch fails; it is not guaranteed promptly while the seat stays idle. Sign-in and permission failures also raise a platform notice in the person’s Inbox, with replies routed to the Captain; other failures remain for the Captain to assess. A Captain normally does not have to interview its Crew to learn a seat is done, and it never waits for one inside a turn: `t3_thread_wait` is not on its surface, because a turn that blocks cannot receive the notice it is waiting for. The person opens every handoff on the Artifacts page. A direct result message does not replace a handoff artifact explicitly required by a saved persona. @@ -50,21 +50,21 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif ### Launch and the gate 1. Asking for a Crew in ordinary chat causes the current agent to propose a roster before doing the delegated work. The thread retains its persona, model, and policy; saved personas are optional and there is no Crew slash command. -2. Initial roster proposals start collapsed in a compact strip above the Captain’s composer, alongside Tasks and Playbooks. Expanding or collapsing the strip is remembered for that thread and environment; the roster draft survives collapsing and the strip leaving while the composer shows an approval or a question, until the person decides. The person reviews the outcome and members, adds or removes members, edits a member in a modal, and approves or declines the final roster. Add and Edit share the same modal: Cancel discards that modal’s changes, while Save validates the member and returns to the roster. Invalid or duplicate names and missing custom-member instructions prevent saving. The last member cannot be removed. Approval is unavailable while a modal is open or a matching full-roster preview is missing. +2. Initial roster proposals start collapsed in a compact strip above the Captain’s composer, alongside Tasks and Playbooks. Expanding or collapsing the strip is remembered for that thread and environment; the roster draft survives collapsing and the strip leaving while the composer shows an approval or a question, until the person decides. The person reviews the outcome and members, adds or removes members, edits a member in a modal, and approves or declines the final roster. Add and Edit share the same modal: Cancel discards that modal’s changes, while Save validates the member and returns to the roster. Invalid or duplicate names and missing custom-member instructions prevent saving. The last member cannot be removed. Approval is unavailable while a modal is open or a matching full-roster preview is missing. With Auto-approve new Crews enabled for the Captain’s project, it launches as proposed with no card. 3. Each proposal member shows its provider, name, model, reasoning, access, and the Captain’s reason. Non-shared workspaces and access that stops for approvals remain visible. The Persona picker offers Custom member and the available saved personas. Selecting a saved persona populates its name and instructions and resolves its runtime defaults; the saved definition is unchanged. The instructions box holds the persona’s whole text, and an edit replaces the persona’s instructions for this member only; the original is not also sent, and Reset to persona text returns the box to the saved text. The instructions an agent attaches to a persona seat stay additional, and an unedited box keeps them. Runtime and workspace choices remain editable. A new custom member starts in the Captain’s checkout. Existing and new worktrees use the Captain’s repository options. Editing the roster refreshes the server preview, which binds the exact runtime settings, Captain’s project and checkout, each seat’s workspace, and the current playbook plan. Missing, unavailable, incomplete, or stale previews cannot approve a launch. Playbook proposals retain each member’s steps, persona-swap explanations, and unowned steps for the Captain. The card cannot reassign steps; removing a member leaves its steps unowned. -4. A seat naming an agent missing from or disabled in the library, a duplicate seat name, or a roster past twelve seats is refused to the Captain with the next step, before anything spawns; prose is never parsed. So are an unknown or invalid playbook, a step the playbook lacks, a step claimed by two seats (or already owned by a live member), and steps on a Crew without a playbook. A seat that claims no steps needs no readable playbook, so a Crew whose playbook file is gone can still grow. Each step has one owner, enforced again where member rows are written, so of two additions racing for one step the first approval wins and the second is refused and stays open. -5. Filing a proposal or a seat request is itself the human gate. On Codex and Claude, under every sandbox, approval policy, and runtime mode, including Codex approval policy `never`, `j5_propose_crew`, `j5_request_crew_member`, `j5_send_message`, and `j5_clear_own_ask` reach the gate or their recipient with no other human step and are never refused. On every other shipped harness they may first raise that harness's own MCP prompt once, and a read-only persona there cannot propose. Where the thread never asks for approval (full access, or a saved persona whose policy resolves to never), spawning, stopping, and archiving, `j5_write_artifact`, and the delegated-task verbs also run without a prompt; in interactive modes the harness's own approval may apply to them. +4. A seat naming an agent missing from or disabled in the library, a duplicate seat name, or a roster past twelve seats is refused to the Captain with the next step, before anything spawns; prose is never parsed. So are an unknown or invalid playbook, a step the playbook lacks, a step claimed by two seats (or already owned by a live member), and steps on a Crew without a playbook. A seat that claims no steps needs no readable playbook, so a Crew whose playbook file is gone can still grow. Each step has one owner, enforced again where member rows are written, so of two additions racing for one step the first reservation wins and the second is refused. +5. New Crew proposals require human approval unless the Captain's project enables auto-approval. Additions run directly without approval. On Codex and Claude, under every sandbox, approval policy, and runtime mode, including Codex approval policy `never`, `j5_propose_crew`, `j5_request_crew_member`, `j5_send_message`, and `j5_clear_own_ask` reach the service or their recipient with no other human step and are never refused. On every other shipped harness they may first raise that harness's own MCP prompt once, and a read-only persona there cannot propose. Where the thread never asks for approval (full access, or a saved persona whose policy resolves to never), spawning, stopping, and archiving, `j5_write_artifact`, and the delegated-task verbs also run without a prompt; in interactive modes the harness's own approval may apply to them. ### The unit -6. Approval spawns every seat as a Peer Agent placed under the Captain and records the roster snapshot with each member's reason (the person approves every seat); a proposal resolves once, so a second approval spawns nothing and a decision that races another device's on the same gate is refused rather than undoing it. The Captain is told by one launch report, posted once every seat has produced provider activity, completed, or failed (or a minute has passed without confirmation), naming what the person changed against the proposal and each seat's outcome with the run's error; a seat whose provider is signed out is refused at spawn with that reason, before anything is created. +6. Approval spawns every seat as a Peer Agent placed under the Captain and records the roster snapshot with each member's reason (human or automatic approval is recorded); a proposal resolves once, so a second approval spawns nothing and a decision that races another device's on the same gate is refused rather than undoing it. The Captain is told by one launch report, posted once every seat has produced provider activity, completed, or failed (or a minute has passed without confirmation), naming what the person changed against the proposal and each seat's outcome with the run's error; a seat whose provider is signed out is refused at spawn with that reason, before anything is created. 7. An approval launches once. A failure before any seat spawns (the Crew or the approval could not be recorded) leaves the gate open to approve again; once seats start spawning, a seat that fails does not stop the others, and the launch report names every approved seat, including one whose thread was never created. A seat that was never created is not on the roster; the Captain asks for it again with `j5_request_crew_member`. 8. A Crew lives in exactly one project and renders as one node under its Captain with its members beneath it. 9. Every member can message any participant; the Crew's contact with the person goes through the inbox or its Captain rather than chat — a plain send to the person is refused by the [human-ask rule](../a2a/agent-tools.md), so a seat reaches the person only with an ask that lands in the Inbox or a reply on an open Exchange. A live Crew seat's pending provider approvals that the provider can still take are listed in the Inbox with their Crew and seat, counted on the bell, and answerable there; the seat's own thread still shows them too, so either place may answer. The Captain's approvals and questions, and approvals a seat can no longer take, are not listed. A live seat's pending native question that can still take an answer is listed as an Inbox link and counted on the bell; it is answered in the original thread, and the link disappears when resolved. A seat asks its Captain rather than the person: Claude and Codex seats have no native question tool, and every seat is told to ask its Captain with `j5_send_message`; a harness that still lets a seat ask natively shows the question in the seat's thread and notifies its Captain. The Captain may answer through upstream's pending-request tools when its modes allow and the answer follows the brief or the person's instructions; otherwise it asks the person to answer in the seat's thread. Native questions are not Inbox Exchanges. An answer to a request already resolved elsewhere is refused and changes nothing. ### Growing -10. When a member raises a concern or needs help, the Captain can request another seat with a reason describing the gap and its assignment. The person answers the request in the Inbox, where it also counts on the bell; approval appends the seat and bumps the snapshot version; either decision is posted to the Captain. +10. Only the Captain adds members, directly with a reason and assignment, regardless of the auto-approval setting. The same launch checks apply; successful additions append the seat and bump the snapshot version. The tool returns the updated roster or a refusal naming the seat and reason. No new addition request waits for a human; open legacy requests remain resolvable above their Captain's composer. 11. A Crew holds at most twelve seats, counting open requests; a member's request is refused naming escalation to its Captain. ### Handoff artifacts @@ -92,13 +92,13 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif ### Several people -23. Where more than one person can write to a Captain's thread, a seat's approvals and a request for a further seat are listed in the inbox of each of them, the first answer settles each, and each of them can message, stop and answer the prompts of the Crew's seats. +23. Where more than one person can write to a Captain's thread, a seat's approvals are listed in the inbox of each of them, the first answer settles each, and each of them can message, stop and answer the prompts of the Crew's seats. ## Scenarios - **A pull-request Crew.** In Billing Migration the user sends "Put together a crew to land the invoice-export PR: build, review, sit on CI." The Captain proposes Builder, Critic, and Sitter with a reason each; the user drops the Sitter, approves, and the two seats appear under the Captain with the brief and the roster. The Critic finishes and writes its ReviewHandoff into the project's artifacts; the Captain's thread receives the notice with the findings inline. (AC1, AC2, AC6, AC8, AC12, AC13) - **Two Crews at once.** In Website Redesign the user, mid-conversation with the agent that has been planning the launch, sends "Create a crew to migrate the blog to the new CMS" and then "Create another crew to rewrite the pricing page copy". The same thread proposes two rosters, each answered above its composer; both appear under the Captain's row as named groups, Blog Migration and Pricing Copy, each with its own toggle, state, and Stop. (AC1, AC2, AC15) -- **More hands.** The Captain judges the CI failures need a Sitter and requests one; the request appears in the Inbox and on the bell, the user approves, and the seat joins the roster at version 2. The Builder tries to request a helper itself and is refused, naming escalation to the Captain. (AC10, AC11) +- **More hands.** The Captain adds a Sitter for the CI failures directly; the seat joins at version 2. A signed-out provider instead refuses the named seat without adding it. A Builder trying to add a helper is refused and told to escalate to its Captain. (AC10, AC11) - **A flaky launch.** One of three approved seats cannot be created when the user approves the roster. The other two start; the launch report says the third was never created and why, and the Captain asks for it again with `j5_request_crew_member`. (AC7) - **Stop everything.** The Builder is heading down a path the person recognizes as wrong while the Critic is mid-review. The person clicks Stop crew on the Crew's Fleet header; both running turns end, the seats stay on the roster, and the Captain briefs them again. (AC21) - **A playbook-shaped Crew.** After talking through a change with the agent, the user sends "ok, lets create a crew to implement what we have discussed. Please use @playbook:release for this work." The agent reads the playbook and proposes a roster above its composer: "Follows playbook: Release", a planner seat and a builder seat each owning the steps that name them, the step that names no persona placed with the builder, and a stand-in custom seat for the turned-off reviewer persona, flagged as a swap. The user approves; the launch report names the playbook, the Captain starts it, and the first step reaches the planner seat. Asking for "the release playbook" by name does the same; a message that only mentions the playbook in passing gets an ordinary roster. (AC1, AC2, AC3, AC6) @@ -118,7 +118,7 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif - 2026-09-15 — the person's side of AC17 and AC20 built: a Captain's archive or deletion from any surface retires its live Crews as units through the lifecycle cascade (the web dialog lists seats, running turns, and open asks first), a seat is refused archive on its own from the app, the Fleet header gains Archive crew, and retired Crews stay readable on the Fleet page with brief and roster snapshot. AC9 noted as enforced by the human-ask rule rather than by guidance ([record](../../worklog/2026-09-14-crews-consolidation.md)). - 2026-09-16 — `/crew` decoupled from the `crew-captain` saved agent: the command sends the brief with the platform's crew-composition guidance to whatever agent the thread runs as, from a fresh draft or an existing thread, and the bundled example is retired; a Captain may command several Crews at once, each a named, collapsible group with its own Stop on the sidebar expander (Bryant; [record](../../worklog/2026-09-16-crew-command-decoupling.md)). - 2026-09-17 — after Jackson's review of the stack: the lone-seat rule of AC19 is enforced on the server's one command handler for every client door, delete included; a roster launch records its Crew before any seat spawns, so a failed launch is retired by a decline rather than abandoned; the Captain cascade and seat settlement gain a boot sweep for what the event stream missed; Crew and seat names are one line each; seat notices are keyed by participant and carry a handoff digest (Bryant; [record](../../worklog/2026-09-16-crew-command-decoupling.md)). -- 2026-09-17 — vocabulary: library definitions are **personas** everywhere a person or a model reads the word (Settings → Personas at `/settings/personas`, `list_personas`, a `persona` parameter, `@persona:` mentions); "agent" is a running participant, and a seat with no persona is a custom seat (Bryant; [record](../../worklog/2026-09-16-crew-command-decoupling.md)). +- 2026-09-17 — vocabulary: library definitions are **personas** everywhere a person or a model reads the word (Settings → Agent Setup at `/settings/personas`, `list_personas`, a `persona` parameter, `@persona:` mentions); "agent" is a running participant, and a seat with no persona is a custom seat (Bryant; [record](../../worklog/2026-09-16-crew-command-decoupling.md)). - 2026-09-17 — custom seats: a seat may name no persona and runs on the Captain's provider, model, and effective access mode, with instructions required; Custom seat is the first choice on the card and takes a name and instructions (Jackson and Bryant; [record](../../worklog/2026-09-16-crew-command-decoupling.md)). - 2026-09-17 — the second round of Jackson's review: the standing orchestration instructions name Crews beside Subagents and Peer Agents; the platform settles no seat (the settler is the seat finish notifier); the Captain badge is an anchor mark; seat threads are titled by seat; tool descriptions are shorter and say "user"; seats without a persona are taken up in a PR on top of the stack (Bryant; [record](../../worklog/2026-09-16-crew-command-decoupling.md)). - 2026-09-18 — the recovery path after Jackson's third and fourth rounds: a decline cleans up before it is recorded and releases every row its proposal minted; a retry retires seats the person dropped or renamed; every resolution claims the gate first (`approving`, `declining`) so two devices cannot undo each other, with a boot sweep settling a claim the server lost; only a genuine not-found reads as a missing seat thread; the sidebar poll re-reads every row still showing a chip so a retired Crew's Captain clears (Bryant; [record](../../worklog/2026-09-16-crew-command-decoupling.md)). diff --git a/docs/j5/product/features/inbox.md b/docs/j5/product/features/inbox.md index fb412f0fcad0f..b0c13a8ddacb7 100644 --- a/docs/j5/product/features/inbox.md +++ b/docs/j5/product/features/inbox.md @@ -15,7 +15,7 @@ The inbox is the one place a person looks to find everything that is waiting on The **inbox** is a person's queue of open asks, live Crew-seat provider approvals, and placed agents' pending native questions. It is **person-scoped, not project-scoped**: a person has one inbox across every environment the client connects to, every item wears the project it came from and, when more than one environment is connected, its environment, and no project selection elsewhere in the app hides an item. -The Inbox holds requests the person can act on: agent-addressed Exchanges, live Crew-seat provider approvals, pending Crew-member requests, and native questions on J5-spawned Peer Agents and live Crew seats. Native questions are links to the agent's original question form, not Exchanges or another answering form. A pending question counts whether it blocks the agent or the provider lets it continue working. Resolved, expired or cancelled questions leave the list as the server reports the change. Captains' own requests stay inline in the thread the person watches, and native or delegated Subagents use upstream's parent routing. +The Inbox holds requests the person can act on: agent-addressed Exchanges, live Crew-seat provider approvals, and native questions on J5-spawned Peer Agents and live Crew seats. Native questions are links to the agent's original question form, not Exchanges or another answering form. A pending question counts whether it blocks the agent or the provider lets it continue working. Resolved, expired or cancelled questions leave the list as the server reports the change. Captains' own requests and Crew roster approvals stay inline in the thread the person watches, and native or delegated Subagents use upstream's parent routing. A plain message to a person is refused; agents send an ask when a reply is owed. The person never opens an ask through the platform: their channel to an agent is its thread, and their only act on the ledger is the answer that closes an Exchange. @@ -31,7 +31,7 @@ A server puts asks only in the inboxes of people who can write to the asking age **Several people.** Where more than one person can write to an agent's thread, the agent can ask one of them, or **everyone here**: everyone who can write to its thread when the ask is read. An ask to everyone appears in each of their inboxes, marked as for everyone, and is counted on each of their bells. The first reply closes it for all of them, as any reply closes an ask, and for the others it moves to the Replied shelf showing who answered. A reply that arrives after that is refused and changes nothing. A person who had started typing an answer keeps the item in place, with their words, and sees who answered. In a thread only one person can write to, there is no "everyone here": the agent asks that person ([shared conversations](shared-conversations.md)). -The Inbox is reached from a bell in the rail that counts open asks, Crew requests, seat approvals and native-question links, and opens a full page. It is available on web, desktop and the mobile app, over local, remote and tunnel connections. On the mobile app the bell sits in the thread list's header and opens a full screen where asks are read and answered in place; for now it counts and shows open asks only, and Crew requests, seat approvals and native-question links are answered on web and desktop. +The Inbox is reached from a bell in the rail that counts open asks, seat approvals and native-question links, and opens a full page. It is available on web, desktop and the mobile app, over local, remote and tunnel connections. On the mobile app the bell sits in the thread list's header and opens a full screen where asks are read and answered in place; for now it counts and shows open asks only, and seat approvals and native-question links are answered on web and desktop. The inbox is **not** a backlog (a non-blocking note an agent wants to keep is a Memo), **not** an alerts feed (an agent that fell over is a measured fact for the Fleet page, not an obligation), and **not** project-scoped. @@ -39,7 +39,7 @@ The inbox is **not** a backlog (a non-blocking note an agent wants to keep is a ### Contents -1. The Inbox lists open asks addressed to the person, live Crew-seat provider approvals, pending Crew-member requests, and actionable pending native questions from J5-spawned Peer Agents and live Crew seats across connected environments. Native questions open the original thread form and disappear when resolved; they are not answered as Exchanges. No plain messages or inferred stalls are added. +1. The Inbox lists open asks addressed to the person, live Crew-seat provider approvals, and actionable pending native questions from J5-spawned Peer Agents and live Crew seats across connected environments. Native questions open the original thread form and disappear when resolved; they are not answered as Exchanges. No plain messages or inferred stalls are added. 2. A plain message from an agent to a person is refused at the tool; the person's row in the address book says it cannot receive one. 3. Several open asks from the same agent to the same person appear as separate items; a follow-up that references an open ask by its Exchange id appears beneath that ask's original text in the same item. 4. The bell's count equals the number of open items. diff --git a/docs/j5/product/features/shared-conversations.md b/docs/j5/product/features/shared-conversations.md index 0d1b17ece7265..360fbcb8ee12e 100644 --- a/docs/j5/product/features/shared-conversations.md +++ b/docs/j5/product/features/shared-conversations.md @@ -63,7 +63,7 @@ Set aside on purpose, each tracked where it is linked. An item leaves this list 10. The first answer settles a prompt for everyone, and the settled prompt shows who answered. An answer to a question carries its author's name and level to the agent. A Crew roster's Captain is told who approved or declined it. For a command's approval, the people on the thread see who answered and the agent is not told. 11. A Viewer sees each prompt and its outcome, with its controls shown disabled. -12. A Crew seat's request for approval, and a Captain's request for a further seat, reach the inbox of everyone who can write to that thread, and the first answer settles each. +12. A Crew seat's request for approval reaches the inbox of everyone who can write to that thread, and the first answer settles each. 13. In a shared conversation, an agent can ask one person who can write to its thread, or everyone here while more than one person can write to it; an ask and its reply show in the thread to everyone on it. diff --git a/docs/j5/product/glossary.md b/docs/j5/product/glossary.md index 2d826e10d1800..71538a1c4c6cd 100644 --- a/docs/j5/product/glossary.md +++ b/docs/j5/product/glossary.md @@ -39,7 +39,7 @@ These entries are the distinctions the whole team must share; the glossary owns | Term | Definition | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | agent | An LLM-driven participant running in a provider session. The ordinary word, lowercase. Never the library entry: that is a persona (2026-09-17). | -| **persona** | A saved definition in the library (Settings → Personas): instructions, model routes, runtime policy, declared handoff artifact. An agent may run as a persona; a persona is not itself running. "Saved agent" is retired vocabulary. | +| **persona** | A saved definition in the library (Settings → Agent Setup): instructions, model routes, runtime policy, declared handoff artifact. An agent may run as a persona; a persona is not itself running. "Saved agent" is retired vocabulary. | | **handoff artifact** | The versioned document one agent writes for another: a persona's declared `outputArtifact`, stored under `handoffs/` in the project's artifacts and read by the next agent. Never a context handoff. Owner: [agent-personas/index.md](agent-personas/index.md#artifact-contracts). | | context handoff | Upstream's mechanism, not a J5 concept: the automatic transfer of a budgeted slice of a thread's history into a new provider conversation of the same thread when it changes provider or model, forks, or restarts. Never a handoff artifact. Owner: upstream's [portable handoffs](../../user/portable-handoffs.md). | | participant | Anything that takes part over the communication ledger: agents (every thread that is not a provider-native Subagent), people, machine participants, and outside agents. Provider-native Subagents are not participants. | diff --git a/docs/j5/product/overview.md b/docs/j5/product/overview.md index ab2380b7823d1..8b62517db4bf4 100644 --- a/docs/j5/product/overview.md +++ b/docs/j5/product/overview.md @@ -13,21 +13,21 @@ This page is the map. Read it before changing anything, to know whether you're i These areas are J5's. Their definitions are the source of truth; build within them under the [principles](principles.md). -| Area | What it is | Definition | -| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Agent-to-agent communication | Agents message each other directly. An ask opens an Exchange that the receiver owes a reply to; silence is noticed and surfaced. | [A2A](a2a/index.md), [agent tools](a2a/agent-tools.md), [upstream substrate](a2a/substrate.md) | -| Inbox | The person's one queue of open asks addressed to them, across every connected environment. | [Inbox](features/inbox.md) | -| Agent-to-agent messages in the thread | How A2A traffic renders in a thread: as cards, leaving upstream's conversation rendering untouched. | [Thread A2A rendering](features/thread-a2a-rendering.md) | -| Crews and Captains | A group of agents launched as a unit from a roster its Captain proposes and the person approves. The Captain is the thread the person watches. | [Crews](features/crews.md) | -| Personas | Reusable, user-authored definitions of a kind of agent: instructions, model routes, runtime policy, declared handoff artifact. | [Roles](features/roles.md), [persona contract](agent-personas/index.md) | -| Spawning Guide | The user's own guidance, consulted when spawning, on which provider, model, and brief fit which work. | [Spawning Guide](features/spawning-guide.md) | -| Playbooks | User-authored, step-by-step prompts that a persona or a Crew follows, with progress declared by its agents. | [Playbooks](features/playbooks.md) | -| Memos | Small self-addressed notes an agent keeps through the platform, visible to the person. | [Memos](features/memos.md) | -| Artifacts and handoffs | Server-owned documents agents write for each other and the person, including a persona's versioned handoff. | [glossary](glossary.md), user guide `docs/j5/user/artifacts.md` | -| Fleet page and sidebar roster | Measured status for every agent and Crew: the Fleet page and the sidebar's spawned-children expander. | [Fleet page](features/fleet-page.md) | -| Shared server and cross-device | Several people on one server, each at a level on the server, a project or a thread, and messages crossing between servers. Authority never replicates. | [Shared server](features/shared-server.md), [people and access](features/people-and-access.md), [shared conversations](features/shared-conversations.md), [cross-device](cross-device.md) | -| Skills | A skill catalog and links that make one skill available across providers. | user guide `docs/j5/user/skills.md` | -| Highlights | A short "What's new" a client shows once after it updates to a build with a substantial new feature. | [Highlights](features/highlights.md) | +| Area | What it is | Definition | +| ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Agent-to-agent communication | Agents message each other directly. An ask opens an Exchange that the receiver owes a reply to; silence is noticed and surfaced. | [A2A](a2a/index.md), [agent tools](a2a/agent-tools.md), [upstream substrate](a2a/substrate.md) | +| Inbox | The person's one queue of open asks addressed to them, across every connected environment. | [Inbox](features/inbox.md) | +| Agent-to-agent messages in the thread | How A2A traffic renders in a thread: as cards, leaving upstream's conversation rendering untouched. | [Thread A2A rendering](features/thread-a2a-rendering.md) | +| Crews and Captains | A group of agents launched as a unit from a roster its Captain proposes, with human approval on by default. The Captain is the thread the person watches. | [Crews](features/crews.md) | +| Personas | Reusable, user-authored definitions of a kind of agent: instructions, model routes, runtime policy, declared handoff artifact. | [Roles](features/roles.md), [persona contract](agent-personas/index.md) | +| Spawning Guide | The user's own guidance, consulted when spawning, on which provider, model, and brief fit which work. | [Spawning Guide](features/spawning-guide.md) | +| Playbooks | User-authored, step-by-step prompts that a persona or a Crew follows, with progress declared by its agents. | [Playbooks](features/playbooks.md) | +| Memos | Small self-addressed notes an agent keeps through the platform, visible to the person. | [Memos](features/memos.md) | +| Artifacts and handoffs | Server-owned documents agents write for each other and the person, including a persona's versioned handoff. | [glossary](glossary.md), user guide `docs/j5/user/artifacts.md` | +| Fleet page and sidebar roster | Measured status for every agent and Crew: the Fleet page and the sidebar's spawned-children expander. | [Fleet page](features/fleet-page.md) | +| Shared server and cross-device | Several people on one server, each at a level on the server, a project or a thread, and messages crossing between servers. Authority never replicates. | [Shared server](features/shared-server.md), [people and access](features/people-and-access.md), [shared conversations](features/shared-conversations.md), [cross-device](cross-device.md) | +| Skills | A skill catalog and links that make one skill available across providers. | user guide `docs/j5/user/skills.md` | +| Highlights | A short "What's new" a client shows once after it updates to a build with a substantial new feature. | [Highlights](features/highlights.md) | ## Everything else is upstream's diff --git a/docs/j5/runbooks/persona-library.md b/docs/j5/runbooks/persona-library.md index c2ee8bddcd86a..8f24e1b7718ca 100644 --- a/docs/j5/runbooks/persona-library.md +++ b/docs/j5/runbooks/persona-library.md @@ -9,7 +9,7 @@ Persona files live on the server environment, including when clients connect rem ## Import from a client -Settings → Personas provides one **Import** menu with **Persona file** and **Folder** options on web, desktop, iOS, and Android. Folder selection includes `.yaml` and `.yml` files recursively; a single-file selection imports only that definition. The client uploads selected definition contents to the chosen environment using authenticated orchestration-operate RPCs. Paths are diagnostic labels, never server write destinations. +Settings → Agent Setup provides one **Import** menu with **Persona file** and **Folder** options on web, desktop, iOS, and Android. Folder selection includes `.yaml` and `.yml` files recursively; a single-file selection imports only that definition. The client uploads selected definition contents to the chosen environment using authenticated orchestration-operate RPCs. Paths are diagnostic labels, never server write destinations. Imports are copies, stored as one atomically replaced `/imported-agent-personas.json` collection. Imported IDs take precedence over the source library below. The UI first imports with `replaceExisting: false`. Existing IDs produce a typed `AgentPersonaImportConflictError` before any writes, carrying names, IDs, and definition digests. Cancel rejects the entire selection. Each conflict has a replacement toggle. Import selected retries the same files with `replaceExisting: true`, the approved `confirmedConflicts`, and `skippedPersonaIds` for toggled-off agents; the server checks those digests under the mutation permit and requests fresh confirmation for new or changed conflicts. Skipped IDs are excluded before conflict checks and writes, even if their definitions were removed while the dialog was open. They stay skipped across retries. New agents are imported alongside approved replacements; an entirely skipped selection succeeds without writing. Acceptance overwrites local edits only for approved replacements while preserving enabled state and saved task snapshots. The RPC retains explicit replacement without `confirmedConflicts` for existing clients; duplicate IDs within a batch are always rejected. All files are validated before writing. Batches are limited to 50 files and 64 KiB of UTF-8 per file. Other file extensions are ignored; unrelated or malformed JSON/YAML fails the entire selection. @@ -33,7 +33,7 @@ To select other folders, create `/agent-personas.json`: Relative paths resolve from the state directory. Explicit configuration replaces the default/example catalog. An empty `folders` list disables source definitions; client imports remain available. The server never clones, fetches, pulls, or commits; maintain the folders using an editor and git as desired. -Settings → Personas → **Library sources** edits the same file through `getAgentPersonaLibrarySources` (orchestration-read) and `setAgentPersonaLibraryFolders` (orchestration-operate). The read RPC reports each configured entry with its resolved path, whether it exists, and a count of YAML files in its tree, plus a read-only git summary when `git` is on the server's PATH and the folder is inside a repository: the repository root, whether `git status -- .` shows uncommitted changes under that folder, and how many commits the tracked upstream is ahead (from the last fetch; the server does not fetch). The write RPC deduplicates entries, creates missing folders that resolve inside the state directory, rejects missing folders elsewhere and any non-directory before writing, and replaces the file atomically under the shared mutation permit. The catalog marks every entry's origin as `bundled`, `imported`, or `folder` with its source file path. +Settings → Agent Setup → **Library sources** edits the same file through `getAgentPersonaLibrarySources` (orchestration-read) and `setAgentPersonaLibraryFolders` (orchestration-operate). The read RPC reports each configured entry with its resolved path, whether it exists, and a count of YAML files in its tree, plus a read-only git summary when `git` is on the server's PATH and the folder is inside a repository: the repository root, whether `git status -- .` shows uncommitted changes under that folder, and how many commits the tracked upstream is ahead (from the last fetch; the server does not fetch). The write RPC deduplicates entries, creates missing folders that resolve inside the state directory, rejects missing folders elsewhere and any non-directory before writing, and replaces the file atomically under the shared mutation permit. The catalog marks every entry's origin as `bundled`, `imported`, or `folder` with its source file path. Declared handoffs bind to the shared artifacts system (`/artifacts//`). When a snapshot declares `outputArtifact`, the persona instructions gain a section naming `handoffs//-.md` and the artifact's checklist; declared `inputArtifacts` point the agent at `j5_list_artifacts` and `j5_read_artifact`. A J5 run-finalization observer (`agentHandoffObserver.ts`, wrapped around the plan-export observer in `server.ts`) checks the project's artifact list after each completed run of a persona thread and writes one row per thread to `j5_agent_handoffs` (J5 migration 12): `written` when the file exists; otherwise `nudged` the first time, with one system message queued into the agent's thread through `ThreadManagementService.sendToThread` (the worker drains the queue inside the J5 auxiliary layer, ids derived from the run so redelivery cannot start a second turn), and `missing` if a later run still ends without the file. `getAgentHandoffs` (orchestration-read) returns rows for the requested thread ids, or the 500 most recent. Read-only personas can make that call because J5 pre-approves `j5_write_artifact` in both adapters, and the pre-approval is not persona-aware: `J5_CLAUDE_MCP_ALLOWED_TOOLS` joins Claude's read-only allowlist under `dontAsk` for every read-only Claude thread, and `j5CodexT3McpServerConfig` sets `mcp_servers.t3-code.tools.j5_write_artifact.approval_mode = approve` for every Codex thread running with approval policy `never`; artifacts live in application storage, so neither widens the workspace sandbox. Platform-spawned threads with deterministic ids hash to an eight-hex task segment instead of the first eight characters. The check does not gate the parent: `RunFinalizationService.finalize` commits the run's completion, and the delegated completion that wakes the parent, before it calls the observer, so a `mode: "wait"` parent has already returned and an async parent's continuation is already queued when the reminder is sent. The reminder starts one follow-up run in the child's own thread; a later run that still ends without the file marks the row `missing`, and no further reminder is ever sent for that task. Clients hold one environment-wide `getAgentHandoffs` query and refetch it when `subscribeHandoffRefreshes` emits after a row write. @@ -73,7 +73,7 @@ Choose exact models and reasoning values advertised by the environment. A route Copy and customize the starter files in `apps/server/src/j5/agents/examples/` when working from the repository. Source folders may be shared through git. The source format is identical for starter and custom personas. The file limit is 64 KiB, with 32,768 characters available for instructions. Declare custom handoff names in an optional `artifacts` array before referencing them in `inputArtifacts` or `outputArtifact`. -Reopen Settings → Personas to read the updated catalog, or launch a new persona through the existing orchestrator contract. The server reads files on each catalog request and new activation; a restart is unnecessary. Empty libraries display an empty state. Missing configured folders, malformed files, undefined artifact references, or duplicate ids fail the library read and prevent new persona launches. Fix the indicated source and retry. +Reopen Settings → Agent Setup to read the updated catalog, or launch a new persona through the existing orchestrator contract. The server reads files on each catalog request and new activation; a restart is unnecessary. Empty libraries display an empty state. Missing configured folders, malformed files, undefined artifact references, or duplicate ids fail the library read and prevent new persona launches. Fix the indicated source and retry. Changing the configuration or a source file does not modify running tasks. Every new assignment records a content digest and has an immutable definition snapshot under `/agent-persona-snapshots`. Back up and restore that directory alongside the event database. A missing or corrupt snapshot blocks reuse rather than silently substituting current instructions. Do not prune snapshots while tasks or their forks may reference them. Ordinary non-persona tasks are unaffected by library errors. diff --git a/docs/j5/user/personas.md b/docs/j5/user/personas.md index 6b7610d7fa53c..610ebdb9627a4 100644 --- a/docs/j5/user/personas.md +++ b/docs/j5/user/personas.md @@ -14,13 +14,13 @@ Threads launched as a persona show the persona beside their home in the thread l To run a persona inside a conversation, type `@persona:` followed by its ID, or type `@` and the start of the persona's ID or name; matching personas appear above the file results. Choosing one inserts the mention, and the next message runs that persona as a subagent of the conversation. -Open **Settings → Personas** on web, desktop, or mobile to see the reusable personas in a connected environment. Select an environment to inspect its library and available model routes. Personas can be authored in folders and shared through git. J5 Code adds no bundled personas; the library is empty until you create or import personas or add a source folder. A personal persona is already available across all projects on its environment. To share a persona created in Settings through a git-backed library, export its YAML into that repository and configure each environment to read its local clone. Provider credentials, available models, and on/off settings stay local to each environment. +Open **Settings → Agent Setup** on web, desktop, or mobile to see the reusable personas in a connected environment. Select an environment to inspect its library and available model routes. Personas can be authored in folders and shared through git. J5 Code adds no bundled personas; the library is empty until you create or import personas or add a source folder. A personal persona is already available across all projects on its environment. To share a persona created in Settings through a git-backed library, export its YAML into that repository and configure each environment to read its local clone. Provider credentials, available models, and on/off settings stay local to each environment. To create a personal persona without writing a file, use **Create persona** beside **Personas**. Give it a name, a stable ID for `@persona:` mentions, a one-line description, markdown instructions, a runtime policy, and primary and fallback models. The persona is stored in the selected environment as an imported definition, so it can be edited, switched off, or removed like any import. Instructions describe behavior; only the runtime policy is enforced. **Full access (unsandboxed)** removes the sandbox: the persona runs with full access on every supported provider, so it can use the network and run any command, and nothing but its instructions limits what it does. To import definitions written as files: -1. Open **Settings → Personas** and select the destination environment. +1. Open **Settings → Agent Setup** and select the destination environment. 2. Use **Import** beside **Personas** (on mobile, the **Import persona file** and **Import a folder of personas** rows under the list). Choose **Folder** to include all YAML definitions (`.yaml` or `.yml`) in that folder and its subfolders (hidden folders and `node_modules` are skipped), or **Import → Persona file** to select one YAML file. On web and desktop the picker browses the selected environment's filesystem, the same picker **Add folder** uses; on mobile it opens your device's file picker. Other files are ignored. Each file must contain one persona definition with its own unique ID. 3. The library refreshes after a successful import. Import and removal results appear as temporary toast notifications. A selection can contain up to 50 definitions, each at most 64 KiB. If any definition is invalid, none of the selection is imported; the error identifies the file. @@ -48,16 +48,18 @@ A crew is a group of agents that one agent, the Captain, runs as a unit for one The agent uses the conversation to propose a roster above the composer. Each member has a responsibility, a reason for joining, and instructions. Members may use saved personas or be custom agents created for this task. You can remove members, add a saved persona, or add a custom seat with a name and instructions, then approve or decline. Custom members start with the Captain's harness, model, and reasoning level, and with Full access. Before approval, you can change their harness, model, reasoning level, and access, whether the agent proposed the member or you added it manually. Selecting a saved persona uses that persona's configured runtime policy. No special Captain persona is needed, and one Captain can coordinate several crews in the same conversation. Before you approve, each member shows its resolved harness, model, reasoning level, and access. Members whose access asks before acting are marked **Stops for approvals**: they pause in their own threads until you answer, so give them Full access if you will not be watching. Changing the roster refreshes these details. If the configuration changes before launch, review the refreshed settings and approve again. The preview also covers the Captain's branch and worktree, so switching the Captain's branch before you approve means reviewing a fresh preview. Each member also shows where it works, chosen by the Captain for every member it proposes: **Captain's checkout**, a **New worktree** from a base branch, or an **Existing worktree** of the project. You can change any member's choice before approving. A new worktree offers a searchable branch list, starting at the Captain's current one, with an option to start from the branch's copy on origin; an existing worktree offers the project's worktrees. A member you add yourself starts in the Captain's checkout. A new worktree's setup script starts with it, and unless the script is set to finish first, the member may begin before it does. If preparing a member's worktree fails, the Captain is told why in the launch report. A member on an ACP registry harness offers only **Supervised** and **Full access**, because those harnesses can't enforce **Auto-accept edits** or **Auto**. +To let Captains launch new Crews without reviewing the initial roster, open **Settings → Agent Setup → Crews** and enable **Auto-approve new Crews**. It starts off. Use the settings scope to set an environment default or a project override. Changing it leaves existing Crews and open proposals alone. + A crew can follow a playbook: ask for one by name, and the Captain assigns each member the steps it owns. The roster card then shows the playbook, which member owns which step, the steps no member owns (the Captain does those), and any step whose persona differs from the member's, including when the wanted persona is missing or turned off. You can't move steps between members; removing a member leaves its steps unowned, and the card tells you. If the playbook or a persona it names changes after you open the card, approval asks you to review again. -A conversation on any harness can propose a crew. On **Codex** and **Claude**, approving the roster is the only confirmation you give. Other harnesses may show their own approval prompt once before the roster, and a conversation running as a saved persona with read-only access can't propose a crew on them. Two cases differ: +A conversation on any harness can propose a crew. On **Codex** and **Claude**, the roster is the only Crew approval when auto-approval is off. With auto-approval on, it launches directly. Other harnesses may show their own approval prompt once before the roster, and a conversation running as a saved persona with read-only access can't propose a crew on them. Two cases differ: - **Cursor** proposes a crew only when the conversation runs in **Full access**. In other modes, a Cursor team admin can add the t3-code tools to the team's MCP tool allowlist. - An OpenCode conversation on an external server cannot propose a crew. Members can talk directly to each other and their Captain, and Captains can coordinate with other Captains. They share findings, questions, blockers, and results as messages while work continues; creating a report is not a prerequisite for communication. Active Codex GPT 6 runs can receive peer messages during work; other models and providers receive queued messages at the next safe turn boundary. -When a member needs help, it tells the Captain. The Captain can request another member, explaining the gap and the proposed assignment. The request appears under **Crew requests** in the Inbox and counts on the Inbox badge. Review why the member is needed, its instructions, and its harness, model, reasoning level, and access, then approve or decline it there; independent work can continue while the request awaits your decision. A crew holds at most twelve seats, and only its Captain can request additions. +When a member needs help, it tells the Captain. The Captain can add another member directly, explaining the gap and assignment. No approval is needed for additions. Provider sign-in, capacity, and member configuration checks still apply; each member's access still controls its tool approvals in the Inbox. Existing addition requests from an older version can be approved or declined above their Captain's composer. When a crew member needs your approval to use a tool, the request appears under **Crew agent requests** in the Inbox and counts on the Inbox badge, so you can approve or decline it without opening the member's conversation; it also stays in that conversation. The Captain's own approvals and questions appear in the Captain's conversation, where you are working with it. Crew members take their questions to the Captain rather than to you: a member that needs a decision asks its Captain, which answers or asks you in the Captain's conversation. Members running on Claude or Codex have native questions suppressed; on other harnesses they are instructed not to ask natively. If a native question still arrives from a live member or a solo Peer Agent started by J5, it appears under **Agent questions** in the Inbox. Open it to answer in the agent's original conversation. Its Captain or parent agent is notified when available. Native-question answers do not record who answered. If you need a record of who answered, ask the agent to send its question to your Inbox instead, and reply there. The mobile app has no Inbox yet, so approvals and questions remain in the agent's conversation. @@ -83,7 +85,7 @@ A persona whose definition declares an output artifact (for example `ReviewHando The task's persona control (web, desktop, and mobile) and, on web and desktop, the persona chip beside a delegated child's Lineage row and subagent card show the handoff artifact's status: the artifact name when written, **pending** after the reminder, or **missing**. On web and desktop the chip opens the file in the Artifacts page. Declared input artifacts are read the same way, so a Builder started after a Navigator finds the `PlanHandoff` under `handoffs/`. -If a source file is invalid, the remaining personas stay available. Settings → Personas reports the file path and reason so you can fix it in your editor. The next catalog read picks up the correction. +If a source file is invalid, the remaining personas stay available. Settings → Agent Setup reports the file path and reason so you can fix it in your editor. The next catalog read picks up the correction. The persona library is separate from the Lineage section and subagent cards, which show runtime activity. diff --git a/docs/j5/user/playbooks.md b/docs/j5/user/playbooks.md index 3f66905a8b79f..7b9a5f4617e5b 100644 --- a/docs/j5/user/playbooks.md +++ b/docs/j5/user/playbooks.md @@ -6,7 +6,7 @@ chat box shows the current stage and whether the run is active, completed, or cancelled. A checked stage means the agent moved past it, not that its work was verified. -Open **Settings → Personas** to manage playbooks. Playbooks in the environment +Open **Settings → Agent Setup** to manage playbooks. Playbooks in the environment library are available across all projects and worktrees on its environment. Choose **Create playbook** to work with Playbook Author, or **Import YAML** to add a finished definition without a project. A project chosen for an authoring or playbook @@ -71,10 +71,10 @@ steps: ``` A step can name the persona that should do it with `persona:`, using a persona id -from Settings → Personas. A step without one is done by whoever runs the playbook. +from Settings → Agent Setup. A step without one is done by whoever runs the playbook. Missing, turned-off, or unverified personas show as warnings in Settings and do not stop the playbook from starting. Invalid persona files leave absent personas unverified; -fix the files reported in Settings → Personas before treating them as missing. +fix the files reported in Settings → Agent Setup before treating them as missing. Type `/playbook ` to choose a registered playbook, then send the command to start it. Send `/playbook review` to start directly, or `/playbook` to ask what is available. diff --git a/packages/client-runtime/src/j5/playbookAuthorLegacy.ts b/packages/client-runtime/src/j5/playbookAuthorLegacy.ts index 078e90c4d2e32..1aab2d579cc2b 100644 --- a/packages/client-runtime/src/j5/playbookAuthorLegacy.ts +++ b/packages/client-runtime/src/j5/playbookAuthorLegacy.ts @@ -18,6 +18,6 @@ steps: Each prompt tells the same agent what work to do, what evidence to retain, and when to advance. 4. Call j5_playbook_list in this thread after writing. Fix reported issues and repeat until the named definition is listed without an issue. Tell the user about any warnings, such as a persona that is missing or turned off. If the tool is unavailable, state that runtime validation is still unverified. -5. Report the file path, purpose, and steps. Explain that the user can inspect it in Settings → Personas and send /playbook when ready to run it. +5. Report the file path, purpose, and steps. Explain that the user can inspect it in Settings → Agent Setup and send /playbook when ready to run it. Stay within authoring and validation. Start a run only when the user explicitly asks. Make changes needed for the playbook; leave unrelated workspace files alone.`; diff --git a/packages/client-runtime/src/j5/playbooks.test.ts b/packages/client-runtime/src/j5/playbooks.test.ts index 4f65d0b9b57a5..35a018bc64f3d 100644 --- a/packages/client-runtime/src/j5/playbooks.test.ts +++ b/packages/client-runtime/src/j5/playbooks.test.ts @@ -247,7 +247,7 @@ describe("Playbook Author installation", () => { throw new Error("must not replace"); }, }), - ).rejects.toThrow("Settings → Personas"); + ).rejects.toThrow("Settings → Agent Setup"); }, ); diff --git a/packages/client-runtime/src/j5/playbooks.ts b/packages/client-runtime/src/j5/playbooks.ts index 083238903eecc..1a32b290e9d2a 100644 --- a/packages/client-runtime/src/j5/playbooks.ts +++ b/packages/client-runtime/src/j5/playbooks.ts @@ -44,7 +44,7 @@ steps: Each prompt tells the same agent what work to do, what evidence to retain, and when to advance. 4. Call j5_playbook_list in this thread after writing. Fix issues in the definition you are authoring and repeat until it is listed without an issue. If a same-named workspace playbook is listed instead, explain that it overrides the library copy here; do not modify an unrelated local file. A successful environment save receipt confirms publication. Tell the user about any warnings, such as a persona that is missing or turned off. If the tool is unavailable, state that runtime validation is still unverified. -5. Report the playbook name, saved destination, purpose, and steps. Say Environment library or the workspace file path; do not invent an absolute server path. Explain that the user can inspect it in Settings → Personas and send /playbook when ready to run it. +5. Report the playbook name, saved destination, purpose, and steps. Say Environment library or the workspace file path; do not invent an absolute server path. Explain that the user can inspect it in Settings → Agent Setup and send /playbook when ready to run it. Stay within authoring and validation. Start a run only when the user explicitly asks. Make changes needed for the playbook; leave unrelated workspace files alone.`; @@ -86,11 +86,11 @@ export async function ensurePlaybookAuthor(input: { } if (!persona || persona.availability.status !== "available") throw new Error( - "Playbook Author is unavailable. Enable or restore it and check its model route in Settings → Personas for this environment.", + "Playbook Author is unavailable. Enable or restore it and check its model route in Settings → Agent Setup for this environment.", ); if (persona.defaultAuthorityPolicy !== "workspace-write") throw new Error( - "Playbook Author needs Workspace write authority to save YAML. Update it in Settings → Personas for this environment.", + "Playbook Author needs Workspace write authority to save YAML. Update it in Settings → Agent Setup for this environment.", ); // Saved authors predate environment libraries. Update only the exact stock instructions, // using the existing digest guard so a concurrent human edit is never overwritten. diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index 9a9a6ac48af23..9ff70fcbf67e3 100644 --- a/packages/contracts/src/j5.ts +++ b/packages/contracts/src/j5.ts @@ -200,6 +200,7 @@ export const CrewProposal = Schema.Struct({ captainThreadId: Schema.String, crewInstanceId: Schema.NullOr(Schema.String), kind: Schema.Literals(["roster", "addition"]), + approvalMode: Schema.optionalKey(Schema.Literals(["human", "automatic"])), status: Schema.Literals(["open", "approved", "declined"]), displayName: Schema.String, brief: Schema.String, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 58ee9d7f58a5e..095bfcddf2655 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -969,6 +969,7 @@ export const PROJECT_SCOPED_SERVER_SETTING_KEYS = [ "defaultThreadEnvMode", "newWorktreesStartFromOrigin", "worktreeSubmodules", + "crewAutoApprove", "defaultAutoPull", "defaultProjectScripts", "enableAgentBrowserAccess", @@ -1006,6 +1007,7 @@ export const ProjectSettingsOverrides = Schema.Struct({ defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode), newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean), worktreeSubmodules: ForwardCompatibleOptional(WorktreeSubmodules), + crewAutoApprove: Schema.optionalKey(Schema.Boolean), defaultAutoPull: Schema.optionalKey(Schema.Boolean), defaultProjectScripts: Schema.optionalKey(Schema.Array(ProjectScript)), enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean), @@ -1138,6 +1140,7 @@ export const ServerSettings = Schema.Struct({ projectAgentBrowserAccessOverrides: Schema.Record(ProjectId, Schema.Boolean).pipe( Schema.withDecodingDefault(Effect.succeed({})), ), + crewAutoApprove: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), defaultAutoPull: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), defaultProjectScripts: Schema.Array(ProjectScript).pipe( Schema.withDecodingDefault(Effect.succeed([])), @@ -1497,6 +1500,7 @@ export const ServerSettingsPatch = Schema.Struct({ projectAgentBrowserAccessOverrides: Schema.optionalKey( Schema.Record(ProjectId, Schema.NullOr(Schema.Boolean)), ), + crewAutoApprove: Schema.optionalKey(Schema.Boolean), defaultAutoPull: Schema.optionalKey(Schema.Boolean), defaultProjectScripts: Schema.optionalKey(Schema.Array(ProjectScript)), projectScriptOverrides: Schema.optionalKey(