Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion FORK.md
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ migrations after upstream migrations.

47. Crew seats ask their Captain, not the person (#325, Jackson's 2026-09-26 decision). `packages/provider-core/src/server/ProviderAdapter.ts` (upstream moved the file into the package; case 60) appends an optional `crewSeat` to `ProviderAdapterV2RuntimePolicy` beside `agentPersonaInstructions`. J5-owned `makeAgentPersonaRuntimePolicyResolver` (`j5/agents/agentPersonaRuntime.ts`), the only resolver behind upstream `RuntimePolicy.ts`, asks J5-owned `makeCrewSeatLookup` (`j5/a2a/crewSeatRuntime.ts`) whether an `agent`/`mcp` thread holds a seat in a live Crew, through the Crew store built over the ambient SQL client. Without a SQL client nothing is a seat, and an unreadable store logs and answers no. `RuntimePolicy.ts` clamps the resolver's runtime mode with upstream's `providerRuntimeMode`, so a persona or seat never asks a provider for a mode it does not support. A seat's policy gets `crewSeat: true` and the ask-your-Captain rule appended to `agentPersonaInstructions`. On Claude that text follows the system prompt. On Codex it now travels as `j5_agent_persona` application context keys (Role library table), and whether Codex reads it after its Default-mode "ask the user directly" text was not verified at the 2026-10-08 advance. Two adapter appends consume the flag through J5-owned leaf `j5/a2a/crewSeatQuestions.ts`: `makeClaudeAdapterV2`'s `openQuery` spreads `j5ClaudeCrewSeatQueryOverrides(turnInput.runtimePolicy)` into `makeClaudeQueryOptions` (`disallowedTools: ["AskUserQuestion"]`, the SDK option that already existed but was never set), and `codexThreadRuntimeParams` spreads `j5CodexCrewSeatConfig(input.runtimePolicy)` into the thread `config` beside `mcp_servers` (dotted session overrides `features.default_mode_request_user_input = false` and `tools.experimental_request_user_input.enabled = false`, sent on thread start, resume, and fork only when the t3-code MCP session is attached). Cursor, Grok, OpenCode, Pi, ACP registry agents, Antigravity and Muse are not supported on seats: they get only the seat brief's instruction (`spawnFirstTurnText` in `j5/a2a/spawnIds.ts`). Captains and every other thread keep their native question tools. Tests: `j5/a2a/crewSeatRuntime.test.ts` (seat, Captain, person thread, persona seat, archived Crew, no SQL client), `j5/a2a/crewSeatQuestions.test.ts` (Codex config and developer-text order), and one `ClaudeAdapterV2.test.ts` case, "withholds AskUserQuestion only from a Crew seat", on the existing wake harness. On every rebase, verify both spreads survive and that upstream has not renamed the Codex switches or added another native question tool.

48. Cross-server peering's scope (Jackson's 2026-09-16 ruling: agents never address an environment; since 2026-10-02 agents see which server a participant lives on, by the server's own name, and still never manage one. Since the ledger re-keyed to projects, the wire names a project, not a Squadron). `packages/contracts/src/auth.ts` appends the `a2a:peer` literal as `AuthA2APeerScope` to `AuthEnvironmentScope`, outside `AuthStandardClientScopes` and `AuthGrantScope`, exactly as case 35 did for `a2a:send`: no pairing link, default session or grant carries it. Only J5-owned `PeerAdminService.issueCredential` mints it, bound by the session subject to one `peer:<environment id>`; a caller reaches it with `access:write`, the `j5` CLI through the credential route in `apps/server/src/j5/a2a/PeerHttp.ts` and a client through the RPC `j5.peers.issueCredential` (case 64). The peer routes authorize on that scope plus a registered peer. `packages/contracts/src/environment.ts` adds one optional capability key, `j5PeerPoll`, beside case 34's two, and `apps/server/src/environment/ServerEnvironment.ts` (with its test) reports it as true; it says a server has peering poll mode and the reachability checks, and the peering dialog offers a setup only when both servers publish it. Everything else is add-beside: migrations 23–27 (26 indexes the peer route probes; 27 indexes received sender labels by receipt time for the client identity read) 30 (poll mode: the peer table rebuilt with its link mode, the store grants, and the delivery rows' hand-out stamp) and 32 (a stored roster snapshot's fields renamed for peer protocol 2, where the wire names a project and no longer a Squadron), `PeerRegistryService.ts`, `PeerInboundService.ts`, `PeerDirectory.ts`, `PeerStoreService.ts` (the poll route's long poll), `PeerPoller.ts` (one loop per peer this server polls, started with the A2A runtime), `peerDeliveryBody.ts`, `peerRoster.ts`, `peerReachability.ts` (the origins the `j5.peers.addresses` RPC offers; it imports upstream's host helpers from `startupAccess.ts` without changing them), `peerProtocol.ts` (the one peer protocol version compare, used in both directions; the version is 2 since the wire fields were renamed, so two peered servers update together and an older one is named as the one to update), `PeerHttp.ts` entering through the case 9 aggregate (the J5 route files share `httpSupport.ts` for authentication and error shapes), the `peer` group in J5-owned `apps/server/src/j5/cli/a2a.ts`, and the wire contracts in `packages/contracts/src/j5.ts`. The peer layers are wired once in J5-owned `runtimeLayer.ts`, which gives them their own `FetchHttpClient` and takes `EnvironmentAuth` and `ServerEnvironment` from the server context, so the shared A2A runtime's requirements grow by those two upstream services; `ServerEnvironment`'s descriptor label is the name a server reports to its peers. One upstream-adjacent test moves with it: `apps/server/src/mcp/toolkits/worktree/registration.test.ts` (already J5-modified for `j5_list_participants`) provides the empty `PeerDirectory` and a ledger stub for project titles, and expects `unread_peer_count` and `project_title`. The web side is one mount: `apps/web/src/components/settings/ConnectionsSettings.tsx` renders the J5-owned `PeerServersSettings` (from `apps/web/src/j5/peering/`) after the remote-environments section, passing only the page's primary environment id, and imports nothing else from J5. The section gates itself: it reads the peers of every connected environment where this client holds `access:write`, lists each pairing among them once, and peers any of them, defaulting to the primary one, so the mount no longer reads `canWriteAccess` or the local-environment switch ([#611](https://github.com/Jacksondr5/j5code/issues/611)); the client's peer-list read lives in `packages/client-runtime/src/j5/http.ts`, its peering commands in `state.ts`, and the setup logic in the `peering.ts` subpath export, which adds one `./j5/peering` entry to that package's exports map beside the existing J5 subpaths. On every rebase, verify the literal is still outside the bundle, `AUTH_SCOPE_OPTIONS` is still typed `AuthGrantScope` (case 35), `runtimeLayer.ts` still provides the peer layers to the aggregate and the send service, and the single `PeerServersSettings` mount survives. `docs/README.md` links the peering guide, `docs/j5/user/j5-peering.md`, beside the other J5 user guides. Development databases that ran an earlier cut of this stack, where these migrations carried ids 14–16 and later 18–21, are disposable test state with no upgrade path: recreate them with `pr-env.sh --fresh`.
48. Cross-server peering's scope (Jackson's 2026-09-16 ruling: agents never address an environment; since 2026-10-02 agents see which server a participant lives on, by the server's own name, and still never manage one. Since the ledger re-keyed to projects, the wire names a project, not a Squadron). `packages/contracts/src/auth.ts` appends the `a2a:peer` literal as `AuthA2APeerScope` to `AuthEnvironmentScope`, outside `AuthStandardClientScopes` and `AuthGrantScope`, exactly as case 35 did for `a2a:send`: no pairing link, default session or grant carries it. Only J5-owned `PeerAdminService.issueCredential` mints it, bound by the session subject to one `peer:<environment id>`; a caller reaches it with `access:write`, the `j5` CLI through the credential route in `apps/server/src/j5/a2a/PeerHttp.ts` and a client through the RPC `j5.peers.issueCredential` (case 64). The peer routes authorize on that scope plus a registered peer. `packages/contracts/src/environment.ts` adds one optional capability key, `j5PeerPoll`, beside case 34's two, and `apps/server/src/environment/ServerEnvironment.ts` (with its test) reports it as true; it says a server has peering poll mode and the reachability checks, and the peering dialog offers a setup only when both servers publish it. Everything else is add-beside: migrations 23–27 (26 indexes the peer route probes; 27 indexes received sender labels by receipt time for the client identity read) 30 (poll mode: the peer table rebuilt with its link mode, the store grants, and the delivery rows' hand-out stamp) and 32 (a stored roster snapshot's fields renamed for peer protocol 2, where the wire names a project and no longer a Squadron), `PeerRegistryService.ts`, `PeerInboundService.ts`, `PeerDirectory.ts`, `PeerStoreService.ts` (the poll route's long poll), `PeerPoller.ts` (one loop per peer this server polls, started with the A2A runtime), `peerDeliveryBody.ts`, `peerRoster.ts`, `peerReachability.ts` (the origins the `j5.peers.addresses` RPC offers; it imports upstream's host helpers from `startupAccess.ts` without changing them), `peerProtocol.ts` (the one peer protocol version compare, used in both directions; the version is 2 since the wire fields were renamed, so two peered servers update together and an older one is named as the one to update), `PeerHttp.ts` entering through the case 9 aggregate (the J5 route files share `httpSupport.ts` for authentication and error shapes), the `peer` group in J5-owned `apps/server/src/j5/cli/a2a.ts`, and the wire contracts in `packages/contracts/src/j5.ts`. The peer layers are wired once in J5-owned `runtimeLayer.ts`, which gives them their own `FetchHttpClient` and takes `EnvironmentAuth` and `ServerEnvironment` from the server context, so the shared A2A runtime's requirements grow by those two upstream services; `ServerEnvironment`'s descriptor label is the name a server reports to its peers. One upstream-adjacent test moves with it: `apps/server/src/mcp/toolkits/worktree/registration.test.ts` (already J5-modified for `j5_list_participants`) provides the empty `PeerDirectory` and a ledger stub for project titles (and declares the `RequestReplayService` stub and stateless `SpawnAgentService` layer required by spawn replay checking), and expects `unread_peer_count` and `project_title`. The web side is one mount: `apps/web/src/components/settings/ConnectionsSettings.tsx` renders the J5-owned `PeerServersSettings` (from `apps/web/src/j5/peering/`) after the remote-environments section, passing only the page's primary environment id, and imports nothing else from J5. The section gates itself: it reads the peers of every connected environment where this client holds `access:write`, lists each pairing among them once, and peers any of them, defaulting to the primary one, so the mount no longer reads `canWriteAccess` or the local-environment switch ([#611](https://github.com/Jacksondr5/j5code/issues/611)); the client's peer-list read lives in `packages/client-runtime/src/j5/http.ts`, its peering commands in `state.ts`, and the setup logic in the `peering.ts` subpath export, which adds one `./j5/peering` entry to that package's exports map beside the existing J5 subpaths. On every rebase, verify the literal is still outside the bundle, `AUTH_SCOPE_OPTIONS` is still typed `AuthGrantScope` (case 35), `runtimeLayer.ts` still provides the peer layers to the aggregate and the send service, and the single `PeerServersSettings` mount survives. `docs/README.md` links the peering guide, `docs/j5/user/j5-peering.md`, beside the other J5 user guides. Development databases that ran an earlier cut of this stack, where these migrations carried ids 14–16 and later 18–21, are disposable test state with no upgrade path: recreate them with `pr-env.sh --fresh`.

49. Composer playbook picker (#314, #320). `/playbook ` (at message start) and `@playbook:` (anywhere) open one playbook picker fed by the J5 library route. These are client-side discovery and text-insertion seams; execution follows case 45's ordinary message expansion.
- Detection: shared `composerTrigger.ts` and web `composer-logic.ts` append the `"slash-playbook"` kind and delegate line-start `/playbook <name>` detection to J5-owned `packages/shared/src/j5/playbookTrigger.ts`, exported through `packages/shared/package.json`; it matches the kebab-case name at the start of the message and stops before following text (#314). Upstream detects `/` per token since the 2026-10-17 advance, so a slash command can start mid-message; `/playbook <name>` spans a space, so J5 keeps a line-start check for it alone, ahead of upstream's token detection. The J5 `detectAgentMention` hook, already called at token level from both, returns the same kind for `@playbook:` tokens with the raw token after the prefix as the query (`packages/shared/src/j5/playbookMention.ts`; no upstream line).
Expand Down
96 changes: 96 additions & 0 deletions apps/server/src/j5/a2a/AgentCaller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import * as ThreadRegistration from "./ThreadRegistration.ts";
import * as A2ALedger from "./LedgerService.ts";
import * as A2ASendService from "./SendService.ts";
import type { McpThreadInvocationScope } from "../../mcp/McpInvocationContext.ts";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";

import type { ParticipantDirectoryRow } from "./contracts.ts";
class J5AgentToolStateError extends Data.TaggedError("J5AgentToolStateError")<{
readonly state: string;
readonly nextCommand: string;
}> {
override get message(): string {
return `${this.state} ${this.nextCommand}`;
}
}

export const stateError = (state: string, nextCommand: string) =>
new J5AgentToolStateError({ state, nextCommand });

type AgentDirectoryRow = ParticipantDirectoryRow & {
readonly participant: Extract<ParticipantDirectoryRow["participant"], { readonly kind: "agent" }>;
};

export const resolveCallerMembership = Effect.fn("j5.a2a.mcp.resolveCallerMembership")(function* (
scope: McpThreadInvocationScope,
) {
const directory = yield* (yield* A2ASendService.A2ASendService)
.listParticipants(scope.thread.threadId)
.pipe(
Effect.mapError((error) =>
stateError(
`Caller thread ${scope.thread.threadId} has no usable membership in its project: ${error instanceof Error ? error.message : String(error)}.`,
"Call j5_list_participants to inspect current membership before retrying.",
),
),
);
const memberships = directory.filter(
(row): row is AgentDirectoryRow =>
row.participant.kind === "agent" && row.participant.threadId === scope.thread.threadId,
);
if (memberships.length === 0) {
return yield* stateError(
`Caller membership is missing for thread ${scope.thread.threadId}.`,
"Call j5_list_participants to inspect current membership before retrying.",
);
}
if (memberships.length !== 1) {
return yield* stateError(
`Caller membership for thread ${scope.thread.threadId} is ambiguous across projects ${memberships.map((row) => row.projectId).join(", ")}.`,
"Call j5_list_participants to inspect current membership before retrying.",
);
}
return memberships[0]!;
});

export const preflightSpawnCaller = Effect.fn("j5.a2a.mcp.preflightSpawnCaller")(function* (
scope: McpThreadInvocationScope,
) {
const ledger = yield* A2ALedger.A2ALedger;
// A thread from before every thread registered at creation registers here, on its first call.
const home = yield* (yield* ThreadRegistration.ThreadRegistration)
.ensureRegistered(scope.thread.threadId)
.pipe(
Effect.mapError((error) =>
stateError(
`Caller thread ${scope.thread.threadId} could not be registered in its project: ${error instanceof Error ? error.message : String(error)}.`,
"Retry j5_spawn_agent; if it keeps failing, tell the human.",
),
),
);
if (home === null) {
return yield* stateError(
`Caller thread ${scope.thread.threadId} is a Subagent and is not an agent-to-agent participant.`,
"Return your result to the agent that started you; it can spawn agents.",
);
}
const project = yield* ledger
.readProjectLedger(home.projectId)
.pipe(
Effect.mapError((error) =>
stateError(
`Caller thread ${scope.thread.threadId} is registered in project ${home.projectId}, but that project's ledger is unavailable: ${error instanceof Error ? error.message : String(error)}.`,
"Tell the human before retrying j5_spawn_agent.",
),
),
);
const membership = yield* resolveCallerMembership(scope);
if (membership.projectId !== home.projectId || membership.participantId !== home.participantId) {
return yield* stateError(
`Caller thread ${scope.thread.threadId} is registered as ${home.projectId}/${home.participantId}, but its current membership is ${membership.projectId}/${membership.participantId}.`,
"Call j5_list_participants to inspect current membership, then ask the human to repair the mismatch before retrying j5_spawn_agent.",
);
}
return { ...membership, project };
});
35 changes: 35 additions & 0 deletions apps/server/src/j5/a2a/AgentCrewProposalService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,3 +299,38 @@ it.effect(
),
),
);

it.effect("preserves library playbook paths in pre-upgrade and current proposals", () =>
Effect.gen(function* () {
yield* runJ5A2AMigrations({ toMigrationInclusive: 39 });
yield* (yield* A2ALedger).ensureProject({ projectId, createdAt });
const sql = yield* SqlClient.SqlClient;
yield* sql`INSERT INTO j5_agent_crew_proposal (
id, project_id, captain_participant_id, captain_thread_id, kind, status,
brief, display_name, requested_seats, created_at, playbook_name, playbook_definition_path
) VALUES (
'legacy', ${projectId}, ${captain}, ${captainThreadId}, 'roster', 'open',
'Original', 'Legacy', '[]', ${createdAt}, 'release', '/library/release.yaml'
)`;
yield* runJ5A2AMigrations();
const proposals = yield* AgentCrewProposalService;
const legacy = yield* proposals.read("legacy");
assert.deepStrictEqual(legacy?.playbook, {
name: "release",
definitionPath: "/library/release.yaml",
});
const current = yield* proposals.create({
...addition("current", "unused", []),
kind: "roster",
crewInstanceId: null,
playbook: {
name: "release",
definitionPath: "/library/release.yaml",
},
});
const reloaded = yield* proposals.read(current.id);
assert.deepStrictEqual(reloaded?.playbook, current.playbook);
yield* runJ5A2AMigrations();
assert.deepStrictEqual(yield* proposals.read("legacy"), legacy);
}).pipe(Effect.provide(testLayer)),
);
7 changes: 5 additions & 2 deletions apps/server/src/j5/a2a/AgentCrewProposalService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export const CrewProposalSeat = Schema.Struct({
});
export type CrewProposalSeat = typeof CrewProposalSeat.Type;

/** The playbook a Crew follows. The definition path is its identity; the name is for display. */
/** The resolved playbook a Crew follows. */
export interface CrewPlaybookRef {
readonly name: string;
readonly definitionPath: string;
Expand Down Expand Up @@ -200,7 +200,10 @@ const fromRow = (row: Row): CrewProposal => ({
playbook:
row.playbook_name === null || row.playbook_definition_path === null
? null
: { name: row.playbook_name, definitionPath: row.playbook_definition_path },
: {
name: row.playbook_name,
definitionPath: row.playbook_definition_path,
},
});

export const layer: Layer.Layer<AgentCrewProposalService, never, SqlClient.SqlClient> =
Expand Down
Loading
Loading