diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts index b38868f792eec..4868077f880d9 100644 --- a/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.test.ts @@ -261,6 +261,32 @@ it.effect( }).pipe(Effect.provide(base)), ); +it.effect("a pinned worktree is prepared from its saved commit, never fetched forward", () => + Effect.gen(function* () { + const f = yield* fixture; + const baseCommit = "4".repeat(40); + yield* f.sql`UPDATE j5_crew_seat_context SET workspace = ${JSON.stringify({ + type: "worktree", + baseRef: "renamed-away", + baseCommit, + branch: "fix/pin", + startFromOrigin: true, + })}`; + yield* f.send(assignment("playbook", "system")).pipe(Effect.provide(f.layer)); + const [delivered] = yield* Ref.get(f.commands); + if (delivered?.type !== "message.dispatch") return assert.fail("missing assignment"); + assert.deepStrictEqual(delivered.dispatchMode, { + type: "defer_start", + workspaceStrategy: { + type: "worktree", + baseRef: baseCommit, + branch: "fix/pin", + startFromOrigin: false, + }, + }); + }).pipe(Effect.provide(base)), +); + it.effect("provider refusal keeps the introduction and roster changes owed", () => Effect.gen(function* () { const f = yield* fixture; diff --git a/apps/server/src/j5/a2a/CrewDeliveryContext.ts b/apps/server/src/j5/a2a/CrewDeliveryContext.ts index c8364aa8dc07a..851c80eee1965 100644 --- a/apps/server/src/j5/a2a/CrewDeliveryContext.ts +++ b/apps/server/src/j5/a2a/CrewDeliveryContext.ts @@ -88,7 +88,20 @@ export const layer = Layer.effect( } return yield* inner.dispatch({ ...command, - dispatchMode: { type: "defer_start", workspaceStrategy: workspace }, + dispatchMode: { + type: "defer_start", + // The saved commit is the base, and it is never fetched forward: a seat saved + // before commits were pinned still starts from its ref. + workspaceStrategy: + workspace.baseCommit === undefined + ? workspace + : { + type: "worktree", + baseRef: workspace.baseCommit, + ...(workspace.branch === undefined ? {} : { branch: workspace.branch }), + startFromOrigin: false, + }, + }, }); }).pipe( Effect.mapError((cause) => diff --git a/apps/server/src/j5/a2a/CrewLaunchService.test.ts b/apps/server/src/j5/a2a/CrewLaunchService.test.ts index b30fcbeac8b33..aeb1c33150dee 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.test.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.test.ts @@ -65,9 +65,13 @@ import { crewSeatRequestKey, spawnThreadId } from "./spawnIds.ts"; import { A2ALedger, layer as ledgerLayer } from "./LedgerService.ts"; import { runJ5A2AMigrations } from "./Migrations.ts"; import { SpawnCompositionService } from "./SpawnCompositionService.ts"; -import { type FakeCheckout, fakeSpawnWorkspaceLayer } from "./test-support/spawnWorkspaceFakes.ts"; +import { + type FakeCheckout, + fakeSha, + fakeSpawnWorkspaceLayer, +} from "./test-support/spawnWorkspaceFakes.ts"; import type { ThreadLaunchInput } from "../../orchestration-v2/ThreadLaunchService.ts"; -import type { SpawnWorkspaceChoice } from "./spawnWorkspace.ts"; +import type { ResolvedSpawnWorkspace, SpawnWorkspaceChoice } from "./spawnWorkspace.ts"; import { ParticipantId, LedgerProjectId } from "./contracts.ts"; const savedBriefs = Effect.gen(function* () { @@ -2080,7 +2084,12 @@ it.effect("launches each seat in the workspace it names, and refuses one git can assert.deepStrictEqual( resolved.map((entry) => entry.runtime.workspace), [ - { type: "worktree", baseRef: "j5/main", startFromOrigin: false }, + { + type: "worktree", + baseRef: "j5/main", + baseCommit: fakeSha(repo, "j5/main"), + startFromOrigin: false, + }, { type: "existing_worktree", worktreePath: "/repo-worktrees/feature", @@ -2132,6 +2141,7 @@ it.effect("launches each seat in the workspace it names, and refuses one git can SELECT workspace FROM j5_crew_seat_context WHERE thread_id = ${threadOf("builder")} `; assert.include(contexts[0]!.workspace, '"baseRef":"j5/main"'); + assert.include(contexts[0]!.workspace, `"baseCommit":"${fakeSha(repo, "j5/main")}"`); }).pipe(Effect.provide(layerFor(repo))); }), ); @@ -2224,6 +2234,223 @@ it.effect("binds an existing worktree's live branch, so a stale preview can't ap }), ); +it.effect("pins a new worktree's base commit, and a moved or renamed branch can't change it", () => + Effect.gen(function* () { + const { context, commands, captain } = yield* fixture; + const codex = provider("codex", "codex", [{ slug: "gpt-5.6-sol", options: ["high"] }]); + const release = "1".repeat(40); + const live = yield* Ref.make({ + isRepo: true, + refName: "j5/main", + commits: { release }, + }); + const layer = crewLaunchLayer.pipe( + Layer.provideMerge( + dependencies( + commands, + [codex], + new Set(), + new Set(), + new Set(), + false, + new Set(), + () => Effect.void, + { checkout: { isRepo: false, refName: null }, liveCheckout: live }, + ), + ), + Layer.provideMerge(Layer.succeedContext(context)), + Layer.provideMerge( + personaLibraryLayer("j5-crew-launch-", Object.values(BUILT_IN_AGENT_PERSONAS)), + ), + Layer.provideMerge(NodeServices.layer), + ); + const builder = (workspace: SpawnWorkspaceChoice) => ({ + name: "builder", + agentId: null, + reason: "Builds", + instructions: "Build it", + workspace, + }); + const baseOf = (seats: ReadonlyArray<{ readonly workspace: ResolvedSpawnWorkspace }>) => + seats[0]?.workspace.type === "worktree" ? seats[0].workspace.baseCommit : undefined; + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + const [pinned] = yield* launcher.pinWorkspaces(captain, [ + builder({ type: "worktree", baseRef: "release" }), + ]); + assert.deepStrictEqual(pinned, { type: "worktree", baseRef: "release", baseCommit: release }); + + // The branch moves, then is renamed away: the saved commit still resolves and is what shows. + yield* Ref.set(live, { + isRepo: true, + refName: "j5/main", + commits: { release: "2".repeat(40) }, + }); + assert.equal(baseOf(yield* launcher.resolveSeats(captain, [builder(pinned!)])), release); + yield* Ref.set(live, { isRepo: true, refName: "j5/main", missingRefs: ["release"] }); + assert.equal(baseOf(yield* launcher.resolveSeats(captain, [builder(pinned!)])), release); + + // A seat saved before pins existed has none, so the ref is read now and shown for approval. + const legacy = yield* launcher + .resolveSeats(captain, [builder({ type: "worktree", baseRef: "release" })]) + .pipe(Effect.flip); + assert.include(legacy.message, "Base ref 'release' doesn't resolve to a commit"); + assert.include(legacy.message, "builder"); + yield* Ref.set(live, { + isRepo: true, + refName: "j5/main", + commits: { release: "3".repeat(40) }, + }); + assert.equal( + baseOf( + yield* launcher.resolveSeats(captain, [ + builder({ type: "worktree", baseRef: "release" }), + ]), + ), + "3".repeat(40), + ); + + // A submitted ref that resolves to nothing is refused naming the seat, so nothing is stored. + yield* Ref.set(live, { isRepo: true, refName: "j5/main", missingRefs: ["j5/2969a292"] }); + const stale = yield* launcher + .pinWorkspaces(captain, [builder({ type: "worktree", baseRef: "j5/2969a292" })]) + .pipe(Effect.flip); + assert.equal( + stale.detail, + `Seat "builder": Base ref 'j5/2969a292' doesn't resolve to a commit in this repository.`, + ); + + // A saved commit that is truly gone fails naming the revision, with no fallback to the ref. + yield* Ref.set(live, { isRepo: true, refName: "j5/main", missingRefs: [release] }); + const gone = yield* launcher.resolveSeats(captain, [builder(pinned!)]).pipe(Effect.flip); + assert.include( + gone.message, + `Base commit ${release.slice(0, 8)} (from 'release') is no longer in this repository.`, + ); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect( + "start_from_origin pins origin's tip when the base is chosen, and never advances it", + () => + Effect.gen(function* () { + const { context, commands, captain } = yield* fixture; + const codex = provider("codex", "codex", [{ slug: "gpt-5.6-sol", options: ["high"] }]); + const fetches = yield* Ref.make>([]); + const live = yield* Ref.make({ + isRepo: true, + refName: "j5/main", + commits: { main: "a".repeat(40) }, + origin: { main: "b".repeat(40) }, + }); + const layer = crewLaunchLayer.pipe( + Layer.provideMerge( + dependencies( + commands, + [codex], + new Set(), + new Set(), + new Set(), + false, + new Set(), + () => Effect.void, + { checkout: { isRepo: false, refName: null }, liveCheckout: live, fetches }, + ), + ), + Layer.provideMerge(Layer.succeedContext(context)), + Layer.provideMerge( + personaLibraryLayer("j5-crew-launch-", Object.values(BUILT_IN_AGENT_PERSONAS)), + ), + Layer.provideMerge(NodeServices.layer), + ); + const seat = (startFromOrigin: boolean) => ({ + name: "builder", + agentId: null, + reason: "Builds", + instructions: "Build it", + workspace: { type: "worktree" as const, baseRef: "main", startFromOrigin }, + }); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + // Locally the branch is a, origin's is b; from origin the pin is b, fetched first. + const [local] = yield* launcher.pinWorkspaces(captain, [seat(false)]); + assert.equal(local?.type === "worktree" && local.baseCommit, "a".repeat(40)); + assert.deepStrictEqual(yield* Ref.get(fetches), []); + const [fromOrigin] = yield* launcher.pinWorkspaces(captain, [seat(true)]); + assert.equal(fromOrigin?.type === "worktree" && fromOrigin.baseCommit, "b".repeat(40)); + assert.deepStrictEqual(yield* Ref.get(fetches), ["main"]); + // Origin moves on; the saved commit is used without another fetch. + yield* Ref.update(live, (checkout) => ({ ...checkout, origin: { main: "c".repeat(40) } })); + const resolved = yield* launcher.resolveSeats(captain, [ + { ...seat(true), workspace: fromOrigin as never }, + ]); + assert.equal( + resolved[0]?.workspace.type === "worktree" && resolved[0].workspace.baseCommit, + "b".repeat(40), + ); + assert.deepStrictEqual(yield* Ref.get(fetches), ["main"]); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect( + "an unreachable origin refuses only the seat that started from it, naming that seat", + () => + Effect.gen(function* () { + const { context, commands, captain } = yield* fixture; + const codex = provider("codex", "codex", [{ slug: "gpt-5.6-sol", options: ["high"] }]); + const layer = crewLaunchLayer.pipe( + Layer.provideMerge( + dependencies( + commands, + [codex], + new Set(), + new Set(), + new Set(), + false, + new Set(), + () => Effect.void, + { + checkout: { + isRepo: true, + refName: "j5/main", + commits: { main: "a".repeat(40) }, + origin: { main: "b".repeat(40) }, + unreachableOriginBranches: ["main"], + }, + }, + ), + ), + Layer.provideMerge(Layer.succeedContext(context)), + Layer.provideMerge( + personaLibraryLayer("j5-crew-launch-", Object.values(BUILT_IN_AGENT_PERSONAS)), + ), + Layer.provideMerge(NodeServices.layer), + ); + const seat = (name: string, startFromOrigin: boolean) => ({ + name, + agentId: null, + reason: "Builds", + instructions: "Build it", + workspace: { type: "worktree" as const, baseRef: "main", startFromOrigin }, + }); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + // The other seats of the roster resolve; the seat from origin is refused by name. + const pinned = yield* launcher + .pinWorkspaces(captain, [seat("local", false), seat("fresh", true)]) + .pipe(Effect.flip); + assert.include(pinned.detail, 'Seat "fresh":'); + assert.include(pinned.detail, "could not be fetched"); + assert.notInclude(pinned.detail, "can't be read"); + assert.include(pinned.nextStep, "local branch"); + const [local] = yield* launcher.pinWorkspaces(captain, [seat("local", false)]); + assert.equal(local?.type === "worktree" && local.baseCommit, "a".repeat(40)); + }).pipe(Effect.provide(layer)); + }), +); + const captainProjectId = () => ProjectId.make("project:crew-launch"); const eligibilityFixture = (input: { diff --git a/apps/server/src/j5/a2a/CrewLaunchService.ts b/apps/server/src/j5/a2a/CrewLaunchService.ts index cccca393fcb3e..1a37cae976261 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.ts @@ -49,6 +49,7 @@ import { namedBaseRefs, namedWorktreePaths, resolveSpawnWorkspace, + SpawnWorkspaceError, spawnCreateCommandId, spawnThreadCheckout, } from "./spawnWorkspace.ts"; @@ -177,7 +178,9 @@ export interface CrewLaunchResult { readonly seats: ReadonlyArray; } -class CrewLaunchSeatUnavailableError extends Data.TaggedError("CrewLaunchSeatUnavailableError")<{ +export class CrewLaunchSeatUnavailableError extends Data.TaggedError( + "CrewLaunchSeatUnavailableError", +)<{ readonly seatName: string; readonly agentId: string; readonly detail: string; @@ -252,6 +255,15 @@ export interface CrewLaunchServiceShape { captain: CrewCaptain, seats: ReadonlyArray, ) => Effect.Effect, CrewLaunchError>; + /** + * Each seat's workspace choice as it should be stored: a new worktree's base resolved to a + * commit and saved on the choice, anything else as given. Refuses a base that resolves to + * nothing, naming the seat. Only worktree seats are read from the repository. + */ + readonly pinWorkspaces: ( + captain: CrewCaptain, + seats: ReadonlyArray, + ) => Effect.Effect, SpawnWorkspaceError>; /** * Launch an approved roster once: seats resolve, the instance is recorded with every planned * seat, `onRecorded` runs, then every seat is attempted and briefed. A seat that fails does not @@ -284,25 +296,62 @@ export const layer = Layer.effect( const spawnWorkspace = yield* SpawnWorkspaceService; const memberModels = yield* CrewMemberModels; - // Resolve every seat before creating anything: a Crew launches whole or not at all. - const resolveSeats = Effect.fn("j5.a2a.crewLaunch.resolveSeats")(function* ( - captain: CrewCaptain, - seats: ReadonlyArray, - ) { - const providers = yield* registry.getProviders; - // Every seat's workspace resolves against one read of the Captain's repository, here at - // preview, so the approval token binds what each seat will get. Shared seats need none. - const checkout = seats.every((seat) => seat.workspace.type === "shared") - ? null - : yield* spawnWorkspace.inspect({ + /** One read of the Captain's repository for what these seats name; null when all are shared. */ + const inspectWorkspaces = (captain: CrewCaptain, seats: ReadonlyArray) => + seats.every((seat) => seat.workspace.type === "shared") + ? Effect.succeed(null) + : spawnWorkspace.inspect({ projectId: captain.thread.projectId, worktreePath: captain.thread.worktreePath, checkBranches: seats.some( (seat) => seat.workspace.type === "worktree" && seat.workspace.branch !== undefined, ), baseRefs: namedBaseRefs(seats.map((seat) => seat.workspace)), + pinBases: true, existingWorktreePaths: namedWorktreePaths(seats.map((seat) => seat.workspace)), }); + + const pinWorkspaces = Effect.fn("j5.a2a.crewLaunch.pinWorkspaces")(function* ( + captain: CrewCaptain, + seats: ReadonlyArray, + ) { + const checkout = yield* inspectWorkspaces( + captain, + seats.filter((seat) => seat.workspace.type === "worktree"), + ); + if (checkout === null) return seats.map((seat) => seat.workspace); + return yield* Effect.forEach( + seats, + (seat): Effect.Effect => { + const { workspace } = seat; + if (workspace.type !== "worktree") return Effect.succeed(workspace); + return Effect.fromResult(resolveSpawnWorkspace(checkout, workspace)).pipe( + Effect.map((resolved) => + resolved.type === "worktree" && resolved.baseCommit !== undefined + ? { ...workspace, baseCommit: resolved.baseCommit } + : workspace, + ), + Effect.mapError( + (error) => + new SpawnWorkspaceError({ + detail: `Seat "${seat.name}": ${error.detail}`, + nextStep: error.nextStep, + }), + ), + ); + }, + ); + }); + + // Resolve every seat before creating anything: a Crew launches whole or not at all. + const resolveSeats = Effect.fn("j5.a2a.crewLaunch.resolveSeats")(function* ( + captain: CrewCaptain, + seats: ReadonlyArray, + ) { + const providers = yield* registry.getProviders; + // Every seat's workspace resolves against one read of the Captain's repository, here at + // preview, so the approval token binds what each seat will get. Shared seats need none. + const checkout = yield* inspectWorkspaces(captain, seats); const resolveWorkspace = (seat: CrewLaunchSeat) => Effect.fromResult( checkout === null @@ -996,6 +1045,12 @@ export const layer = Layer.effect( worktreePath: captain.thread.worktreePath, }); - return CrewLaunchService.of({ launch, addSeats, resolveSeats, workspaceOptions }); + return CrewLaunchService.of({ + launch, + addSeats, + resolveSeats, + pinWorkspaces, + workspaceOptions, + }); }), ); diff --git a/apps/server/src/j5/a2a/CrewProposalService.test.ts b/apps/server/src/j5/a2a/CrewProposalService.test.ts index 9cd8dbbdff66f..e3d5c4f407f12 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.test.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.test.ts @@ -61,10 +61,12 @@ import { import { AgentCrewProposalService, layer as proposalStoreLayer, + type CrewProposalSeat, } from "./AgentCrewProposalService.ts"; import { CrewLaunchReporter } from "./CrewLaunchReporter.ts"; import { CrewLaunchOperationError, + CrewLaunchSeatUnavailableError, CrewLaunchService, layer as crewLaunchLayer, type CrewCaptain, @@ -84,8 +86,12 @@ import { participantIdForThread } from "./HomeRegistrar.ts"; import { runMigrations } from "../../persistence/Migrations.ts"; import { runJ5A2AMigrations } from "./Migrations.ts"; import { SpawnCompositionService } from "./SpawnCompositionService.ts"; -import type { ResolvedSpawnWorkspace } from "./spawnWorkspace.ts"; -import { fakeSpawnWorkspaceLayer, noRepository } from "./test-support/spawnWorkspaceFakes.ts"; +import { + SpawnWorkspaceError, + type ResolvedSpawnWorkspace, + type SpawnWorkspaceChoice, +} from "./spawnWorkspace.ts"; +import { fakeSpawnWorkspaceLayer } from "./test-support/spawnWorkspaceFakes.ts"; import { crewSeatRequestKey, lifecycleId, spawnThreadId } from "./spawnIds.ts"; import { CREW_PROPOSAL_SESSION } from "./crewSeatIds.ts"; import { ParticipantId, LedgerProjectId } from "./contracts.ts"; @@ -120,10 +126,34 @@ const launchFailure = (cause: unknown) => const decodeProposeCrewInput = Schema.decodeUnknownEffect(J5ProposeCrewInput); +/** + * The fake repository's bases. A ref resolves to `fakeCommit(ref)` unless a test moved it or took + * it away; a saved commit exists unless a test removed it. Tests use their own ref names. + */ +const repo = { moved: new Map(), gone: new Set() }; +const fakeCommit = (ref: string) => Buffer.from(ref).toString("hex").padEnd(40, "0").slice(0, 40); + +/** A base as the launcher resolves it: its saved commit while it exists, else the ref now. */ +const fakeBaseCommit = (workspace: { baseRef: string; baseCommit?: string | undefined }) => + workspace.baseCommit === undefined + ? repo.gone.has(workspace.baseRef) + ? null + : (repo.moved.get(workspace.baseRef) ?? fakeCommit(workspace.baseRef)) + : repo.gone.has(workspace.baseCommit) + ? null + : workspace.baseCommit; + /** The launcher's resolution is tested on its own; here a seat's choice passes through as given. */ const fakeWorkspace = (seat: CrewLaunchSeat): ResolvedSpawnWorkspace => seat.workspace.type === "worktree" - ? { type: "worktree", baseRef: seat.workspace.baseRef, startFromOrigin: false } + ? { + type: "worktree", + baseRef: seat.workspace.baseRef, + ...(fakeBaseCommit(seat.workspace) === null + ? {} + : { baseCommit: fakeBaseCommit(seat.workspace)! }), + startFromOrigin: false, + } : seat.workspace.type === "existing_worktree" ? { type: "existing_worktree", @@ -147,8 +177,33 @@ const fakeWorkspaceOptions = { const fakeLauncher = (crews: AgentCrewInstanceService["Service"]) => Layer.mock(CrewLaunchService)({ workspaceOptions: () => Effect.succeed(fakeWorkspaceOptions), - resolveSeats: (captain, seats) => - Effect.succeed( + pinWorkspaces: (_captain, seats) => + Effect.forEach(seats, (seat): Effect.Effect => { + const { workspace } = seat; + if (workspace.type !== "worktree") return Effect.succeed(workspace); + const baseCommit = fakeBaseCommit(workspace); + return baseCommit === null + ? Effect.fail( + new SpawnWorkspaceError({ + detail: `Seat "${seat.name}": Base ref '${workspace.baseRef}' doesn't resolve to a commit in this repository.`, + nextStep: "Name an existing branch, tag, or commit for workspace.base_ref.", + }), + ) + : Effect.succeed({ ...workspace, baseCommit }); + }), + resolveSeats: (captain, seats) => { + const unresolved = seats.find( + (seat) => seat.workspace.type === "worktree" && fakeBaseCommit(seat.workspace) === null, + ); + if (unresolved !== undefined) + return Effect.fail( + new CrewLaunchSeatUnavailableError({ + seatName: unresolved.name, + agentId: unresolved.agentId ?? "custom seat", + detail: "Its base doesn't resolve to a commit.", + }), + ); + return Effect.succeed( seats.map( (seat) => ({ @@ -172,7 +227,8 @@ const fakeLauncher = (crews: AgentCrewInstanceService["Service"]) => }, }) satisfies ResolvedCrewLaunchSeat, ), - ), + ); + }, launch: (input) => input.displayName === "Boom" ? Effect.fail(launchFailure(new Error("provider unavailable"))) @@ -1327,13 +1383,20 @@ it.effect( brief: input.brief, seats: proposed, }); - assert.deepStrictEqual((yield* store.read(open.proposal.id))?.requestedSeats, proposed); + const baseCommit = fakeCommit("release"); + assert.deepStrictEqual((yield* store.read(open.proposal.id))?.requestedSeats, [ + { + ...proposed[0]!, + workspace: { type: "worktree", baseRef: "release", branch: "fix/login", baseCommit }, + }, + ]); const first = yield* gate.preview({ proposalId: open.proposal.id }); // Every preview carries what the card offers: the Captain's branch, where it works, worktrees. assert.deepStrictEqual(first.workspaceOptions, fakeWorkspaceOptions); assert.deepStrictEqual(first.seats[0]?.workspace, { type: "worktree", baseRef: "release", + baseCommit, startFromOrigin: false, }); const shared = [{ ...proposed[0]!, workspace: { type: "shared" as const } }]; @@ -1783,7 +1846,7 @@ const playbookFixtureWithSettings = ( ), Layer.provideMerge(Layer.mock(CrewLaunchReporter)({ watch: () => Effect.void })), Layer.provideMerge(playbookStoreLayer), - Layer.provideMerge(fakeSpawnWorkspaceLayer({ checkout: noRepository })), + Layer.provideMerge(fakeSpawnWorkspaceLayer({ checkout: { isRepo: true, refName: "main" } })), Layer.provideMerge( Layer.mock(ThreadManagementService)({ getThreadProjection: (threadId) => @@ -3693,3 +3756,244 @@ it.effect( }).pipe(Effect.provide(layer)); }).pipe(Effect.scoped), ); + +const builderOn = (baseRef: string, seat = "builder") => ({ + ...custom(seat), + workspace: { type: "worktree" as const, baseRef }, +}); + +const baseCommitOf = (seat: CrewProposalSeat | undefined) => + seat?.workspace?.type === "worktree" ? seat.workspace.baseCommit : undefined; + +it.effect("a base is pinned to its commit when proposed, and a renamed branch can't unpin it", () => + Effect.gen(function* () { + const { layer } = yield* fixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const store = yield* AgentCrewProposalService; + const open = yield* gate.propose({ + requestKey: "pin-rename", + captain, + displayName: "Pinned", + brief: "Build", + seats: [builderOn("pin-rename-branch")], + }); + const pin = fakeCommit("pin-rename-branch"); + assert.equal(baseCommitOf(open.proposal.requestedSeats[0]), pin); + + // The branch is renamed after the proposal was accepted and before it is previewed. + repo.gone.add("pin-rename-branch"); + const shown = yield* gate.preview({ proposalId: open.proposal.id }); + const workspace = shown.seats[0]?.workspace; + assert.equal(workspace?.type === "worktree" && workspace.baseCommit, pin); + + // It stays renamed through approval, so the commit saved on the proposal is what launches. + const approved = yield* gate.resolve({ + proposalId: open.proposal.id, + decision: "approve", + approvalToken: shown.approvalToken, + }); + assert.equal(approved.proposal.status, "approved"); + assert.equal(baseCommitOf((yield* store.read(open.proposal.id))?.approvedSeats?.[0]), pin); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a ref that resolves to nothing is refused when proposed, and stores nothing", () => + Effect.gen(function* () { + const { layer } = yield* fixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + repo.gone.add("pin-stale-branch"); + const roster = yield* gate + .propose({ + requestKey: "pin-stale", + captain, + displayName: "Stale", + brief: "Build", + seats: [builderOn("pin-stale-branch")], + }) + .pipe(Effect.flip); + assert.equal(roster._tag, "CrewProposalRequestError"); + assert.include(roster.message, 'Seat "builder"'); + assert.include(roster.message, "'pin-stale-branch'"); + assert.include(roster.message, "Name an existing branch, tag, or commit"); + const launched = yield* gate.propose({ + requestKey: "pin-stale-crew", + captain, + displayName: "Crew", + brief: "Build", + seats: [custom("lead")], + }); + const addition = yield* gate + .requestMember({ + requestKey: "pin-stale-addition", + captain, + crewInstanceId: launched.instance?.id ?? null, + seat: builderOn("pin-stale-branch"), + brief: null, + }) + .pipe(Effect.flip); + assert.equal(addition._tag, "CrewProposalRequestError"); + const proposals = yield* (yield* AgentCrewProposalService).listForCaptain(captainId); + assert.deepStrictEqual( + proposals.map(({ requestedSeats }) => requestedSeats[0]?.seat), + ["lead"], + ); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("editing a base resolves and previews a new commit that needs its own approval", () => + Effect.gen(function* () { + const { layer } = yield* fixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const store = yield* AgentCrewProposalService; + const open = yield* gate.propose({ + requestKey: "pin-edit", + captain, + displayName: "Edit", + brief: "Build", + seats: [builderOn("pin-edit-old")], + }); + const original = yield* gate.preview({ proposalId: open.proposal.id }); + // The card drops the saved commit when the base is edited. + const edited = [builderOn("pin-edit-new")]; + const next = yield* gate.preview({ proposalId: open.proposal.id, seats: edited }); + const workspace = next.seats[0]?.workspace; + assert.equal( + workspace?.type === "worktree" && workspace.baseCommit, + fakeCommit("pin-edit-new"), + ); + assert.notEqual(next.approvalToken, original.approvalToken); + const stale = yield* gate + .resolve({ + proposalId: open.proposal.id, + decision: "approve", + seats: edited, + approvalToken: original.approvalToken, + }) + .pipe(Effect.flip); + assert.equal(stale._tag, "CrewProposalRequestError"); + yield* gate.resolve({ + proposalId: open.proposal.id, + decision: "approve", + seats: edited, + approvalToken: next.approvalToken, + }); + assert.equal( + baseCommitOf((yield* store.read(open.proposal.id))?.approvedSeats?.[0]), + fakeCommit("pin-edit-new"), + ); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a retry keeps the original pin, and changed arguments are still a conflict", () => + Effect.gen(function* () { + const { layer } = yield* fixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const input = { + requestKey: "pin-retry", + captain, + displayName: "Retry", + brief: "Build", + seats: [builderOn("pin-retry-branch")], + }; + const first = yield* gate.propose(input); + // The branch moves on; an identical retry finds the stored proposal and its pin. + repo.moved.set("pin-retry-branch", "9".repeat(40)); + const retry = yield* gate.propose(input); + assert.deepStrictEqual(retry.proposal, first.proposal); + assert.equal(baseCommitOf(retry.proposal.requestedSeats[0]), fakeCommit("pin-retry-branch")); + const changed = yield* gate + .propose({ ...input, seats: [builderOn("pin-retry-other")] }) + .pipe(Effect.flip); + assert.include(changed.message, "different request"); + assert.deepStrictEqual( + (yield* (yield* AgentCrewProposalService).read(first.proposal.id))?.requestedSeats, + first.proposal.requestedSeats, + ); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("automatic approval and direct additions launch from the pinned commit", () => + Effect.gen(function* () { + const { layer } = yield* fixtureWithSettings({ crewAutoApprove: true }); + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const roster = yield* gate.propose({ + requestKey: "pin-auto", + captain, + displayName: "Auto", + brief: "Build", + seats: [builderOn("pin-auto-branch")], + }); + assert.equal(roster.proposal.status, "approved"); + assert.equal(baseCommitOf(roster.proposal.approvedSeats?.[0]), fakeCommit("pin-auto-branch")); + const addition = yield* gate.requestMember({ + requestKey: "pin-auto-addition", + captain, + crewInstanceId: roster.instance!.id, + seat: builderOn("pin-auto-addition-branch", "second"), + brief: null, + }); + assert.equal(addition.proposal.status, "approved"); + assert.equal( + baseCommitOf(addition.proposal.approvedSeats?.[0]), + fakeCommit("pin-auto-addition-branch"), + ); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("an open proposal from before pins is pinned by its first preview, never guessed", () => + Effect.gen(function* () { + const { layer } = yield* fixture; + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const store = yield* AgentCrewProposalService; + const legacy = (id: string, baseRef: string) => + store.create({ + id: `legacy-${id}`, + projectId: captain.projectId, + captainParticipantId: captain.participantId, + captainThreadId: captain.thread.id, + crewInstanceId: null, + kind: "roster", + brief: "Build", + displayName: "Legacy", + requestedSeats: [builderOn(baseRef)], + createdAt: DateTime.formatIso(createdAt), + }); + const open = yield* legacy("live", "pin-legacy-branch"); + const shown = yield* gate.preview({ proposalId: open.id }); + const workspace = shown.seats[0]?.workspace; + assert.equal( + workspace?.type === "worktree" && workspace.baseCommit, + fakeCommit("pin-legacy-branch"), + ); + // Nothing is written to the open row; approval binds what the preview showed. + assert.isUndefined(baseCommitOf((yield* store.read(open.id))?.requestedSeats[0])); + yield* gate.resolve({ + proposalId: open.id, + decision: "approve", + approvalToken: shown.approvalToken, + }); + assert.equal( + baseCommitOf((yield* store.read(open.id))?.approvedSeats?.[0]), + fakeCommit("pin-legacy-branch"), + ); + + // Its ref already gone: the preview says so and the proposal needs an edit or a decline. + repo.gone.add("pin-legacy-gone"); + const stale = yield* legacy("gone", "pin-legacy-gone"); + const refused = yield* gate.preview({ proposalId: stale.id }).pipe(Effect.flip); + assert.equal(refused._tag, "CrewLaunchSeatUnavailableError"); + assert.include(refused.message, "builder"); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/j5/a2a/CrewProposalService.ts b/apps/server/src/j5/a2a/CrewProposalService.ts index 16906fe9b1426..50b6dcc32ce54 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.ts @@ -45,6 +45,7 @@ import { crewSeatShapeProblem } from "./crewLimits.ts"; import { CREW_PROPOSAL_SESSION } from "./crewSeatIds.ts"; import { A2ALedger } from "./LedgerService.ts"; import { lifecycleCommandId, lifecycleId } from "./spawnIds.ts"; +import type { ResolvedSpawnWorkspace, SpawnWorkspaceChoice } from "./spawnWorkspace.ts"; import { requestDigest, requestReplayConflict } from "./RequestReplayService.ts"; import { worktreePathKey } from "./spawnWorkspace.ts"; import { getThreadProjectionIfPresent } from "./threadProjectionReads.ts"; @@ -239,6 +240,25 @@ const memberSteps = (instance: AgentCrewInstance | null) => playbookStepIds: member.playbookStepIds ?? [], })); +const omitBaseCommit = ({ + baseCommit: _pin, + ...workspace +}: Extract) => workspace; + +/** The seats with each new worktree's commit saved in its choice, from the workspaces resolved for them. */ +const withBaseCommits = ( + seats: ReadonlyArray, + workspaces: ReadonlyArray, +): ReadonlyArray => + seats.map((seat, index) => { + const resolved = workspaces[index]; + return seat.workspace?.type === "worktree" && + resolved?.type === "worktree" && + resolved.baseCommit !== undefined + ? { ...seat, workspace: { ...seat.workspace, baseCommit: resolved.baseCommit } } + : seat; + }); + /** Whether the person changed a seat's workspace; `crewRosterChanges` leaves workspaces out. */ const sameWorkspace = (a: CrewProposalSeat["workspace"], b: CrewProposalSeat["workspace"]) => { if (a === undefined || b === undefined) return a === b; @@ -287,9 +307,13 @@ const proposalRequest = (proposal: ProposalRequest) => ({ seats: proposal.requestedSeats.map(({ personaSwaps: _swaps, workspace, ...seat }) => ({ ...seat, steps: seat.steps ?? [], + // The server saves the pin after the request; a retry never carries it. workspace: workspace?.type === "worktree" - ? { ...workspace, startFromOrigin: workspace.startFromOrigin ?? false } + ? { + ...omitBaseCommit(workspace), + startFromOrigin: workspace.startFromOrigin ?? false, + } : workspace?.type === "existing_worktree" ? { ...workspace, worktreePath: worktreePathKey(workspace.worktreePath) } : workspace, @@ -696,14 +720,17 @@ export const layer = Layer.effect( false, definition === null ? null : { definition, existingMembers: [] }, ); - if (automatic) - yield* resolveRuntime(input.captain, withPersonaSwaps(input.seats, plan.swapsBySeat)); + const seats = withPersonaSwaps( + yield* pinSeats(input.captain, input.seats), + plan.swapsBySeat, + ); + if (automatic) yield* resolveRuntime(input.captain, seats); const proposal = yield* proposals .create({ ...request, approvalMode: automatic ? "automatic" : "human", playbook: playbookRef, - requestedSeats: withPersonaSwaps(input.seats, plan.swapsBySeat), + requestedSeats: seats, }) .pipe(Effect.mapError(operationError("recording the proposal"))); // The stored row decides what happened: an open automatic proposal is approved here. @@ -780,13 +807,17 @@ export const layer = Layer.effect( false, definition === null ? null : { definition, existingMembers: memberSteps(instance) }, ); - yield* resolveRuntime(input.captain, withPersonaSwaps([input.seat], plan.swapsBySeat)); + const seats = withPersonaSwaps( + yield* pinSeats(input.captain, [input.seat]), + plan.swapsBySeat, + ); + yield* resolveRuntime(input.captain, seats); const admitted = yield* proposals .admit( { ...request, approvalMode: "automatic", - requestedSeats: withPersonaSwaps([input.seat], plan.swapsBySeat), + requestedSeats: seats, }, { maxSeats: CREW_SEAT_CAP }, ) @@ -827,6 +858,15 @@ export const layer = Layer.effect( const resolveRuntime = (captain: CrewCaptain, seats: ReadonlyArray) => launcher.resolveSeats(captain, seats.map(launchSeatOf)); + /** Saves each new worktree's commit on its seat before a proposal is stored; refuses a base that has none. */ + const pinSeats = (captain: CrewCaptain, seats: ReadonlyArray) => + launcher.pinWorkspaces(captain, seats.map(launchSeatOf)).pipe( + Effect.map((workspaces) => withBaseCommits(seats, workspaces)), + Effect.mapError( + ({ detail, nextStep }) => new CrewProposalRequestError({ detail, nextStep }), + ), + ); + /** Preview and approval consult the same live roster and the same live playbook. */ const validateProposalSeats = Effect.fn("j5.a2a.crewProposal.validateProposalSeats")(function* ( proposal: CrewProposal, @@ -964,7 +1004,13 @@ export const layer = Layer.effect( const launched = yield* fulfil( proposal, captain, - withPersonaSwaps(seats, plan.swapsBySeat), + withPersonaSwaps( + withBaseCommits( + seats, + resolved.map(({ workspace }) => workspace), + ), + plan.swapsBySeat, + ), resolved, launchPlaybook(proposal.playbook, definition), ).pipe( diff --git a/apps/server/src/j5/a2a/SpawnAgentService.ts b/apps/server/src/j5/a2a/SpawnAgentService.ts index 36a14f2597f8c..20a5cfab52478 100644 --- a/apps/server/src/j5/a2a/SpawnAgentService.ts +++ b/apps/server/src/j5/a2a/SpawnAgentService.ts @@ -527,6 +527,7 @@ const spawn = Effect.fn("j5.a2a.spawnAgent")(function* ( worktreePath: own?.thread.worktreePath ?? null, checkBranches, baseRefs: SpawnWorkspace.namedBaseRefs([choice]), + pinBases: false, existingWorktreePaths: SpawnWorkspace.namedWorktreePaths([choice]), }); const workspace = yield* Effect.fromResult( diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index f73b4c0d625e5..429bbfb6a8597 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -396,7 +396,7 @@ const CrewPlaybookName = NonEmptyString.annotate({ }); const CrewSeatWorkspace = J5SpawnWorkspace.annotate({ description: - 'Where the seat works, chosen for every seat, with the same three choices as j5_spawn_agent: {"type":"shared"} (your checkout), {"type":"worktree","base_ref":...}, or {"type":"existing_worktree","worktree_path":...}.', + 'Where the seat works, chosen for every seat, with the same three choices as j5_spawn_agent: {"type":"shared"} (your checkout), {"type":"worktree","base_ref":...}, or {"type":"existing_worktree","worktree_path":...}. A new worktree\'s base_ref is resolved to a commit when the proposal is accepted and the worktree starts from that commit, so renaming or moving the branch later changes nothing; a base_ref that does not resolve is refused. Name your own branch to start from your checkout\'s current commit; uncommitted changes are not included.', }); const CrewSeatRuntimeMode = RuntimeMode.annotate({ description: diff --git a/apps/server/src/j5/a2a/spawnWorkspace.test.ts b/apps/server/src/j5/a2a/spawnWorkspace.test.ts index 72dd3e5f094b7..6acc8e78ecf30 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.test.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.test.ts @@ -78,9 +78,38 @@ const checkout = ( worktrees: [{ path: "/repo-worktrees/feature", branch: "fix/login" }], localBranchNames: ["j5/main", "taken"], missingBaseRefs: [], + baseCommits: [], + unreachableBaseRefs: [], ...overrides, }); +it("refuses only the seats whose base could not be fetched from origin", () => { + const unreachable = { ref: "main", startFromOrigin: true, commit: undefined }; + const state = checkout({ + baseCommits: [ + { ref: "release", startFromOrigin: false, commit: undefined, sha: "a".repeat(40) }, + ], + unreachableBaseRefs: [{ ...unreachable, problem: "could not read from remote repository" }], + }); + const refused = resolveSpawnWorkspace(state, { + type: "worktree", + baseRef: "main", + startFromOrigin: true, + }); + assert.isTrue(Result.isFailure(refused)); + const failure = Result.isFailure(refused) ? refused.failure : undefined; + assert.include(failure?.detail, "Base 'main' was chosen from origin"); + assert.include(failure?.detail, "could not read from remote repository"); + assert.include(failure?.nextStep, "local branch"); + // The same ref locally, and another base, resolve against the same checkout. + assert.isTrue( + Result.isSuccess(resolveSpawnWorkspace(state, { type: "worktree", baseRef: "main" })), + ); + assert.isTrue( + Result.isSuccess(resolveSpawnWorkspace(state, { type: "worktree", baseRef: "release" })), + ); +}); + it("resolves each explicit choice; only shared asks nothing of git", () => { const resolve = (...args: Parameters) => Result.getOrThrow(resolveSpawnWorkspace(...args)); @@ -196,6 +225,8 @@ const spawnHarness = (input: { readonly scope?: McpInvocationScope; /** The check on a plain agent's model; every model is eligible unless a test saves a list. */ readonly memberModels?: Layer.Layer; + /** Records the ref of each fetch from origin. */ + readonly fetches?: Ref.Ref>; }) => Effect.gen(function* () { const log = yield* Ref.make>([]); @@ -436,6 +467,7 @@ const spawnHarness = (input: { Layer.provideMerge( fakeSpawnWorkspaceLayer({ checkout: input.checkout, + ...(input.fetches === undefined ? {} : { fetches: input.fetches }), ...(input.replay === undefined ? {} : { replay: input.replay }), ...(input.liveCheckout === undefined ? {} : { liveCheckout: input.liveCheckout }), launches, @@ -1619,6 +1651,7 @@ it.effect("refuses a base ref git can't resolve before anything is created", () isRepo: true, refName: "j5/main", missingRefs: ["no-such-ref", "only-on-origin"], + origin: { "only-on-origin": "0".repeat(40) }, }, }); yield* Effect.gen(function* () { @@ -1651,6 +1684,33 @@ it.effect("refuses a base ref git can't resolve before anything is created", () }), ); +it.effect( + "a direct spawn from origin never fetches, so an unreachable origin doesn't refuse it", + () => + Effect.gen(function* () { + const fetches = yield* Ref.make>([]); + const { layer, call, launches } = yield* spawnHarness({ + checkout: { + isRepo: true, + refName: "j5/main", + origin: { "j5/main": "0".repeat(40) }, + unreachableOriginBranches: ["j5/main"], + }, + fetches, + }); + yield* Effect.gen(function* () { + const spawned = yield* call({ + ...spawnArgs, + workspace: { type: "worktree", base_ref: "j5/main", start_from_origin: true }, + client_request_id: "direct-from-origin", + }); + assert.isFalse(spawned.isFailure); + assert.lengthOf(yield* Ref.get(launches), 1); + assert.deepStrictEqual(yield* Ref.get(fetches), []); + }).pipe(Effect.provide(layer)); + }), +); + const decodeSpawnInput = Schema.decodeUnknownExit(J5SpawnAgentInput); it("requires a workspace on every spawn", () => { diff --git a/apps/server/src/j5/a2a/spawnWorkspace.ts b/apps/server/src/j5/a2a/spawnWorkspace.ts index 1b38f4133475b..7c6bb9541a3cc 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.ts @@ -2,6 +2,7 @@ import type { J5SpawnWorkspace } from "./mcp/tools.ts"; import { type ChatAttachment, CommandId, + type GitCommandError, type MessageId, type ModelSelection, type ProjectId, @@ -19,6 +20,7 @@ import * as Schema from "effect/Schema"; import type { CrewWorkspaceOptions } from "@t3tools/contracts/j5"; import { GitWorkflowService } from "../../git/GitWorkflowService.ts"; +import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts"; import { CommandReceiptStoreV2, type CommandReceiptStoreV2Error, @@ -50,6 +52,9 @@ export const GitRefName = Schema.String.check( Schema.isPattern(GIT_REF_PATTERN, { message: GIT_REF_MESSAGE }), ); +/** A full commit id as it is printed. */ +const COMMIT_SHA_PATTERN = /^[0-9a-f]{40,64}$/; + /** A worktree path with its trailing separators dropped, so `/repo/wt/` matches git's `/repo/wt`. */ export const worktreePathKey = (path: string) => path.replace(/[\\/]+$/, ""); @@ -67,6 +72,7 @@ export const SpawnWorkspaceChoice = Schema.Union([ Schema.Struct({ type: Schema.Literal("worktree"), baseRef: GitRefName, + baseCommit: Schema.optionalKey(Schema.String.check(Schema.isPattern(COMMIT_SHA_PATTERN))), branch: Schema.optionalKey(GitRefName), startFromOrigin: Schema.optionalKey(Schema.Boolean), }), @@ -79,15 +85,21 @@ export type ResolvedSpawnWorkspace = | { readonly type: "worktree"; readonly baseRef: string; + /** The commit the worktree starts from; always set when a Crew seat resolves. */ + readonly baseCommit?: string; readonly branch?: string; readonly startFromOrigin: boolean; } | { readonly type: "existing_worktree"; readonly worktreePath: string; readonly branch: string }; -/** A base ref as a caller named it; from origin, its fetched remote-tracking copy also counts. */ +/** + * A base ref as a caller named it; from origin, its fetched remote-tracking copy also counts. + * `commit` is the pin an earlier acceptance saved, which is checked instead of the ref. + */ export interface SpawnBaseRef { readonly ref: string; readonly startFromOrigin: boolean; + readonly commit?: string | undefined; } /** The existing worktrees a set of choices name, for `inspect` to read live. */ @@ -102,7 +114,13 @@ export const namedBaseRefs = ( ): ReadonlyArray => choices.flatMap((choice) => choice.type === "worktree" - ? [{ ref: choice.baseRef, startFromOrigin: choice.startFromOrigin ?? false }] + ? [ + { + ref: choice.baseRef, + startFromOrigin: choice.startFromOrigin ?? false, + commit: choice.baseCommit, + }, + ] : [], ); @@ -127,6 +145,10 @@ export type SpawnCheckout = readonly localBranchNames: ReadonlyArray; /** Base refs a caller named that git can't resolve to a commit, as they were asked for. */ readonly missingBaseRefs: ReadonlyArray; + /** The commit each base ref that resolved means now, or the saved pin that still exists. */ + readonly baseCommits: ReadonlyArray; + /** Base refs chosen from origin whose fetch failed, with why; only their seats are refused. */ + readonly unreachableBaseRefs: ReadonlyArray; } | { readonly readable: false; readonly problem: string }; @@ -160,6 +182,17 @@ export const resolveSpawnWorkspace = ( (ref) => ref !== undefined && (ref.length > 255 || !GIT_REF_PATTERN.test(ref)), ) : undefined; + if ( + choice.type === "worktree" && + choice.baseCommit !== undefined && + !COMMIT_SHA_PATTERN.test(choice.baseCommit) + ) + return Result.fail( + new SpawnWorkspaceError({ + detail: `The saved base commit ${JSON.stringify(choice.baseCommit)} is not a full commit id.`, + nextStep: "Edit the member's base to a branch, tag, or commit that exists.", + }), + ); if (badRef !== undefined) return Result.fail( new SpawnWorkspaceError({ @@ -199,19 +232,32 @@ export const resolveSpawnWorkspace = ( branch: found.branch, }); } - if ( - checkout.missingBaseRefs.some( - (missing) => - missing.ref === choice.baseRef && - missing.startFromOrigin === (choice.startFromOrigin ?? false), - ) - ) + const startFromOrigin = choice.startFromOrigin ?? false; + const sameBase = (base: SpawnBaseRef) => + base.ref === choice.baseRef && + base.startFromOrigin === startFromOrigin && + base.commit === choice.baseCommit; + const unreachable = checkout.unreachableBaseRefs.find(sameBase); + if (unreachable !== undefined) return Result.fail( new SpawnWorkspaceError({ - detail: `Base ref '${choice.baseRef}' doesn't resolve to a commit in this repository${choice.startFromOrigin === true ? ", locally or as a fetched origin branch" : ""}.`, - nextStep: "Name an existing branch, tag, or commit for workspace.base_ref.", + detail: `Base '${choice.baseRef}' was chosen from origin, but origin could not be fetched (${unreachable.problem}).`, + nextStep: + "Check the connection to origin, or start the member from the local branch instead.", }), ); + if (checkout.missingBaseRefs.some(sameBase)) + return Result.fail( + choice.baseCommit === undefined + ? new SpawnWorkspaceError({ + detail: `Base ref '${choice.baseRef}' doesn't resolve to a commit in this repository${startFromOrigin ? ", locally or as a fetched origin branch" : ""}.`, + nextStep: "Name an existing branch, tag, or commit for workspace.base_ref.", + }) + : new SpawnWorkspaceError({ + detail: `Base commit ${choice.baseCommit.slice(0, 8)} (from '${choice.baseRef}') is no longer in this repository.`, + nextStep: "Edit the member's base to a commit that exists, or decline.", + }), + ); if (choice.branch !== undefined && checkout.localBranchNames.includes(choice.branch)) return Result.fail( new SpawnWorkspaceError({ @@ -220,11 +266,13 @@ export const resolveSpawnWorkspace = ( "Choose a different workspace.branch, or omit it and let the server name the branch.", }), ); + const baseCommit = checkout.baseCommits.find(sameBase)?.sha; return Result.succeed({ type: "worktree", baseRef: choice.baseRef, + ...(baseCommit === undefined ? {} : { baseCommit }), ...(choice.branch === undefined ? {} : { branch: choice.branch }), - startFromOrigin: choice.startFromOrigin ?? false, + startFromOrigin, }); }; @@ -300,6 +348,11 @@ export interface SpawnWorkspaceServiceShape { readonly checkBranches: boolean; /** Base refs to check before anything is created (see `namedBaseRefs`). */ readonly baseRefs: ReadonlyArray; + /** + * Pin each base to a commit, fetching origin for one chosen from there. Off for a direct + * spawn, which doesn't use a pin: it only checks the ref exists, with no fetch. + */ + readonly pinBases: boolean; }) => Effect.Effect; /** * What the roster card offers: the caller's branch, the directory its branch picker searches, @@ -363,6 +416,7 @@ const BRANCH_PAGE = 100; const make = Effect.gen(function* () { const projects = yield* ProjectService; const git = yield* GitWorkflowService; + const driver = yield* GitVcsDriver.GitVcsDriver; const receipts = yield* CommandReceiptStoreV2; const launcher = yield* ThreadLaunchService; const threads = yield* ThreadManagementService; @@ -414,6 +468,58 @@ const make = Effect.gen(function* () { }; }); + type BaseResolution = + | { readonly kind: "commit"; readonly sha: string } + | { readonly kind: "found" } + | { readonly kind: "missing" } + | { readonly kind: "unreachable"; readonly problem: string }; + + /** + * The commit a base means, from where the caller works: its saved pin while that commit exists, + * else the ref now (from origin, origin's, fetched now). Missing when nothing resolves, and + * unreachable when the fetch fails, rather than pinning a stale ref the person didn't choose. + */ + const resolveBase = Effect.fn("j5.spawnWorkspace.resolveBase")(function* ( + cwd: string, + base: SpawnBaseRef, + ): Effect.fn.Return { + if (base.commit !== undefined) + return (yield* git.hasCommit({ cwd, refName: base.commit })) + ? { kind: "commit", sha: base.commit } + : { kind: "missing" }; + if (base.startFromOrigin && (yield* git.remoteExists({ cwd, remoteName: "origin" }))) { + const fetched = yield* git + .fetchRemote({ cwd, remoteName: "origin", refName: base.ref }) + .pipe(Effect.result); + if (Result.isFailure(fetched)) + return { kind: "unreachable", problem: detailOf(fetched.failure) }; + if (yield* git.remoteBranchExists({ cwd, remoteName: "origin", refName: base.ref })) + return { + kind: "commit", + sha: (yield* git.resolveRemoteTrackingCommit({ + cwd, + refName: base.ref, + fallbackRemoteName: "origin", + })).commitSha, + }; + } + return yield* driver.resolveCommit({ cwd, revision: base.ref }).pipe( + Effect.map(({ commitSha }): BaseResolution => ({ kind: "commit", sha: commitSha })), + Effect.orElseSucceed((): BaseResolution => ({ kind: "missing" })), + ); + }); + + /** Whether a base exists as asked, with no fetch; a base from origin may be its fetched copy. */ + const baseExists = Effect.fn("j5.spawnWorkspace.baseExists")(function* ( + cwd: string, + base: SpawnBaseRef, + ) { + const found = yield* git.hasCommit({ cwd, refName: base.ref }); + return found || !base.startFromOrigin + ? found + : yield* git.hasCommit({ cwd, refName: `refs/remotes/origin/${base.ref}` }); + }); + const inspect: SpawnWorkspaceServiceShape["inspect"] = Effect.fn("j5.spawnWorkspace.inspect")( function* (caller) { const workspaceRoot = yield* projectRoot(caller.projectId); @@ -435,20 +541,30 @@ const make = Effect.gen(function* () { ) : Effect.succeed(worktree), ); - const missingBaseRefs = yield* Effect.filter(caller.baseRefs, (base) => - git.hasCommit({ cwd, refName: base.ref }).pipe( - Effect.filterOrElse( - (found) => found || !base.startFromOrigin, - () => git.hasCommit({ cwd, refName: `refs/remotes/origin/${base.ref}` }), - ), - Effect.map((found) => !found), - ), + const bases = yield* Effect.forEach(caller.baseRefs, (base) => + (caller.pinBases + ? resolveBase(cwd, base) + : baseExists(cwd, base).pipe( + Effect.map((found): BaseResolution => ({ kind: found ? "found" : "missing" })), + ) + ).pipe(Effect.map((resolution) => ({ base, resolution }))), + ); + const missingBaseRefs = bases.flatMap(({ base, resolution }) => + resolution.kind === "missing" ? [base] : [], + ); + const baseCommits = bases.flatMap(({ base, resolution }) => + resolution.kind === "commit" ? [{ ...base, sha: resolution.sha }] : [], + ); + const unreachableBaseRefs = bases.flatMap(({ base, resolution }) => + resolution.kind === "unreachable" ? [{ ...base, problem: resolution.problem }] : [], ); return { readable: true, worktrees, localBranchNames: caller.checkBranches ? yield* git.listLocalBranchNames(cwd) : [], missingBaseRefs, + baseCommits, + unreachableBaseRefs, } satisfies SpawnCheckout; }, Effect.catch((cause) => diff --git a/apps/server/src/j5/a2a/spawnWorkspacePin.test.ts b/apps/server/src/j5/a2a/spawnWorkspacePin.test.ts new file mode 100644 index 0000000000000..8216dacfa0255 --- /dev/null +++ b/apps/server/src/j5/a2a/spawnWorkspacePin.test.ts @@ -0,0 +1,254 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { ProjectId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Result from "effect/Result"; +import type * as Scope from "effect/Scope"; + +import * as ServerConfig from "../../config.ts"; +import { GitWorkflowService } from "../../git/GitWorkflowService.ts"; +import { CommandReceiptStoreV2 } from "../../orchestration-v2/CommandReceiptStore.ts"; +import { ThreadLaunchService } from "../../orchestration-v2/ThreadLaunchService.ts"; +import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; +import { ProjectService } from "../../project/ProjectService.ts"; +import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts"; +import { + SpawnWorkspaceService, + layerFromReceiptStore, + namedBaseRefs, + resolveSpawnWorkspace, + type SpawnWorkspaceChoice, +} from "./spawnWorkspace.ts"; + +const projectId = ProjectId.make("project:spawn-pin"); + +const driverLayer = GitVcsDriver.layer.pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "spawn-pin-" })), + Layer.provideMerge(NodeServices.layer), +); + +/** Upstream's workflow service reads through the driver, so the real driver stands in for it. */ +const workflowOverDriver = Layer.effect( + GitWorkflowService, + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + return GitWorkflowService.of({ + listRefs: driver.listRefs, + listLocalBranchNames: driver.listLocalBranchNames, + fetchRemote: driver.fetchRemote, + remoteExists: driver.remoteExists, + remoteBranchExists: driver.remoteBranchExists, + resolveRemoteTrackingCommit: driver.resolveRemoteTrackingCommit, + hasCommit: ({ cwd, refName }: { readonly cwd: string; readonly refName: string }) => + driver.resolveCommit({ cwd, revision: refName }).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ), + invalidateLocalStatus: () => Effect.void, + } as unknown as GitWorkflowService["Service"]); + }), +); + +const inScratch = ( + effect: Effect.Effect< + A, + E, + FileSystem.FileSystem | Path.Path | Scope.Scope | GitVcsDriver.GitVcsDriver + >, +) => Effect.scoped(effect).pipe(Effect.provide(driverLayer)); + +/** Runs one command in a repository and returns its trimmed output. */ +const sh = (cwd: string, ...args: ReadonlyArray) => + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const result = yield* driver.execute({ + operation: "spawnWorkspacePin.test", + cwd, + args, + env: { + ...process.env, + GIT_AUTHOR_NAME: "t", + GIT_AUTHOR_EMAIL: "t@example.com", + GIT_COMMITTER_NAME: "t", + GIT_COMMITTER_EMAIL: "t@example.com", + }, + }); + return result.stdout.trim(); + }); + +const scenario = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "spawn-pin-repo-" }); + const origin = path.join(root, "origin.git"); + const work = path.join(root, "work"); + const other = path.join(root, "other"); + yield* sh(root, "init", "--bare", "--initial-branch=main", origin); + yield* sh(root, "clone", origin, work); + yield* sh(work, "checkout", "-b", "main"); + yield* sh(work, "commit", "--allow-empty", "-m", "first"); + yield* sh(work, "push", "origin", "main"); + yield* sh(work, "branch", "release"); + const layer = layerFromReceiptStore.pipe( + Layer.provide( + Layer.mergeAll( + workflowOverDriver, + Layer.mock(ProjectService)({ + getById: (id) => Effect.succeedSome({ id, workspaceRoot: work } as never), + }), + Layer.mock(CommandReceiptStoreV2)({}), + Layer.mock(ThreadLaunchService)({}), + Layer.mock(ThreadManagementService)({}), + ), + ), + Layer.provideMerge(driverLayer), + ); + return { work, other, origin, root, layer }; +}); + +/** What a Crew seat's base resolves to in the repository as it is now. */ +const resolveBase = (choice: Extract) => + Effect.gen(function* () { + const workspace = yield* SpawnWorkspaceService; + const checkout = yield* workspace.inspect({ + projectId, + worktreePath: null, + existingWorktreePaths: [], + checkBranches: false, + baseRefs: namedBaseRefs([choice]), + pinBases: true, + }); + return resolveSpawnWorkspace(checkout, choice); + }); + +it.effect("a pin survives its branch being renamed, moved or deleted while the commit exists", () => + inScratch( + Effect.gen(function* () { + const { work, layer } = yield* scenario; + const releaseCommit = yield* sh(work, "rev-parse", "release"); + yield* Effect.gen(function* () { + const pinned = Result.getOrThrow( + yield* resolveBase({ type: "worktree", baseRef: "release" }), + ); + assert.equal(pinned.type === "worktree" && pinned.baseCommit, releaseCommit); + const choice = { type: "worktree" as const, baseRef: "release", baseCommit: releaseCommit }; + + // Moved: the branch name now means another commit, and the pin does not follow it. + yield* sh(work, "commit", "--allow-empty", "-m", "second"); + yield* sh(work, "branch", "-f", "release", "HEAD"); + const moved = Result.getOrThrow(yield* resolveBase(choice)); + assert.equal(moved.type === "worktree" && moved.baseCommit, releaseCommit); + + // Renamed, then deleted: the name is gone but the commit is still in the repository. + yield* sh(work, "branch", "-m", "release", "renamed"); + yield* sh(work, "branch", "-D", "renamed"); + const renamed = Result.getOrThrow(yield* resolveBase(choice)); + assert.equal(renamed.type === "worktree" && renamed.baseCommit, releaseCommit); + + // A base with no pin, such as one submitted by name, is refused rather than guessed. + const stale = yield* resolveBase({ type: "worktree", baseRef: "release" }); + assert.isTrue(Result.isFailure(stale)); + assert.include( + Result.isFailure(stale) ? stale.failure.detail : "", + "'release' doesn't resolve", + ); + + // A commit that is truly gone fails naming the revision. + const missing = yield* resolveBase({ ...choice, baseCommit: "0".repeat(40) }); + assert.isTrue(Result.isFailure(missing)); + assert.include( + Result.isFailure(missing) ? missing.failure.detail : "", + "Base commit 00000000 (from 'release') is no longer in this repository.", + ); + }).pipe(Effect.provide(layer)); + }), + ), +); + +it.effect( + "from origin, the pin is origin's fetched tip, and only a fresh choice reads it again", + () => + inScratch( + Effect.gen(function* () { + const { work, other, origin, root, layer } = yield* scenario; + const localTip = yield* sh(work, "rev-parse", "main"); + yield* sh(root, "clone", origin, other); + yield* sh(other, "checkout", "main"); + yield* sh(other, "commit", "--allow-empty", "-m", "ahead on origin"); + yield* sh(other, "push", "origin", "main"); + const originTip = yield* sh(other, "rev-parse", "HEAD"); + yield* Effect.gen(function* () { + const local = Result.getOrThrow( + yield* resolveBase({ type: "worktree", baseRef: "main" }), + ); + assert.equal(local.type === "worktree" && local.baseCommit, localTip); + const choice = { type: "worktree" as const, baseRef: "main", startFromOrigin: true }; + const fromOrigin = Result.getOrThrow(yield* resolveBase(choice)); + assert.equal(fromOrigin.type === "worktree" && fromOrigin.baseCommit, originTip); + + // Origin moves again; the saved commit is used as it is, with no fetch to advance it. + yield* sh(other, "commit", "--allow-empty", "-m", "further"); + yield* sh(other, "push", "origin", "main"); + const kept = Result.getOrThrow(yield* resolveBase({ ...choice, baseCommit: originTip })); + assert.equal(kept.type === "worktree" && kept.baseCommit, originTip); + assert.equal(yield* sh(work, "rev-parse", "refs/remotes/origin/main"), originTip); + }).pipe(Effect.provide(layer)); + }), + ), +); + +it.effect("a local-only branch with origin present falls back to the local ref", () => + inScratch( + Effect.gen(function* () { + const { work, layer } = yield* scenario; + yield* sh(work, "commit", "--allow-empty", "-m", "local only"); + yield* sh(work, "branch", "local-only", "HEAD"); + const localTip = yield* sh(work, "rev-parse", "local-only"); + yield* Effect.gen(function* () { + const resolved = Result.getOrThrow( + yield* resolveBase({ type: "worktree", baseRef: "local-only", startFromOrigin: true }), + ); + assert.equal(resolved.type === "worktree" && resolved.baseCommit, localTip); + }).pipe(Effect.provide(layer)); + }), + ), +); + +it.effect("an unreachable origin refuses only the seat that started from it", () => + inScratch( + Effect.gen(function* () { + const { work, origin, layer } = yield* scenario; + const fs = yield* FileSystem.FileSystem; + yield* fs.remove(origin, { recursive: true }); + const releaseCommit = yield* sh(work, "rev-parse", "release"); + yield* Effect.gen(function* () { + const workspace = yield* SpawnWorkspaceService; + const choices: ReadonlyArray = [ + { type: "worktree", baseRef: "release" }, + { type: "worktree", baseRef: "main", startFromOrigin: true }, + ]; + const checkout = yield* workspace.inspect({ + projectId, + worktreePath: null, + existingWorktreePaths: [], + checkBranches: false, + baseRefs: namedBaseRefs(choices), + pinBases: true, + }); + assert.isTrue(checkout.readable); + const [local, fromOrigin] = choices.map((choice) => + resolveSpawnWorkspace(checkout, choice), + ); + const pinned = Result.getOrThrow(local!); + assert.equal(pinned.type === "worktree" && pinned.baseCommit, releaseCommit); + assert.isTrue(Result.isFailure(fromOrigin!)); + const failure = Result.isFailure(fromOrigin!) ? fromOrigin.failure : undefined; + assert.include(failure?.detail, "Base 'main' was chosen from origin"); + assert.include(failure?.nextStep, "local branch"); + }).pipe(Effect.provide(layer)); + }), + ), +); diff --git a/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts b/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts index e0b545cb31ec5..2b4e1232b8dde 100644 --- a/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts +++ b/apps/server/src/j5/a2a/test-support/spawnWorkspaceFakes.ts @@ -6,6 +6,7 @@ import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import { GitWorkflowService } from "../../../git/GitWorkflowService.ts"; +import { GitVcsDriver } from "../../../vcs/GitVcsDriver.ts"; import { CommandReceiptStoreV2 } from "../../../orchestration-v2/CommandReceiptStore.ts"; import { ThreadLaunchService, @@ -26,8 +27,18 @@ export interface FakeCheckout { readonly worktrees?: ReadonlyArray<{ readonly path: string; readonly branch: string }>; /** Refs git can't resolve; every other ref exists. */ readonly missingRefs?: ReadonlyArray; + /** The commit a ref resolves to; `fakeSha` derives one for any other. */ + readonly commits?: Readonly>; + /** Branches on the `origin` remote and their tips; the remote exists only when this is given. */ + readonly origin?: Readonly>; + /** Branches whose fetch from `origin` fails, as a dead network or bad credentials would. */ + readonly unreachableOriginBranches?: ReadonlyArray; } +/** A full-length id for a ref the checkout doesn't pin to a particular commit. */ +export const fakeSha = (checkout: FakeCheckout, ref: string) => + checkout.commits?.[ref] ?? Buffer.from(ref).toString("hex").padEnd(40, "0").slice(0, 40); + /** A project that is not a git repository; only a shared choice can resolve there. */ export const noRepository: FakeCheckout = { isRepo: false, refName: null }; @@ -65,6 +76,8 @@ export const fakeSpawnWorkspaceLayer = (options: { */ readonly liveCheckout?: Ref.Ref; readonly workspaceRoot?: string; + /** Records the ref of each fetch from `origin`. */ + readonly fetches?: Ref.Ref>; readonly launches?: Ref.Ref>; readonly launch?: (input: ThreadLaunchInput) => Effect.Effect; readonly accepted?: Effect.Effect>; @@ -100,6 +113,28 @@ export const fakeSpawnWorkspaceLayer = (options: { }), hasCommit: ({ refName }) => current.pipe(Effect.map((checkout) => !(checkout.missingRefs ?? []).includes(refName))), + remoteExists: () => current.pipe(Effect.map((checkout) => checkout.origin !== undefined)), + fetchRemote: ({ refName }) => + (options.fetches === undefined + ? Effect.void + : Ref.update(options.fetches, (all) => [...all, refName ?? ""]) + ).pipe( + Effect.andThen(current), + Effect.flatMap((checkout) => + (checkout.unreachableOriginBranches ?? []).includes(refName ?? "") + ? Effect.fail(new Error("could not read from remote repository") as never) + : Effect.void, + ), + ), + remoteBranchExists: ({ refName }) => + current.pipe(Effect.map((checkout) => checkout.origin?.[refName] !== undefined)), + resolveRemoteTrackingCommit: ({ refName }) => + current.pipe( + Effect.map((checkout) => ({ + commitSha: checkout.origin![refName]!, + remoteRefName: `origin/${refName}`, + })), + ), // A checkout's status is cached per path until invalidated, as upstream's is, so only a // read that invalidates first sees a branch switched since the last one. invalidateLocalStatus: (cwd) => Effect.sync(() => void cachedStatus.delete(cwd)), @@ -118,6 +153,16 @@ export const fakeSpawnWorkspaceLayer = (options: { listLocalBranchNames: () => current.pipe(Effect.map((checkout) => fakeRefs(checkout, root).map((ref) => ref.name))), }), + Layer.mock(GitVcsDriver)({ + resolveCommit: ({ revision }) => + current.pipe( + Effect.flatMap((checkout) => + (checkout.missingRefs ?? []).includes(revision) + ? Effect.fail(new Error(`no commit for ${revision}`) as never) + : Effect.succeed({ commitSha: fakeSha(checkout, revision) }), + ), + ), + }), Layer.mock(ThreadLaunchService)({ launch: Effect.fn("j5.a2a.spawnWorkspaceFakes.launch")(function* (input) { if (options.launches) yield* Ref.update(options.launches, (all) => [...all, input]); diff --git a/apps/server/src/j5/test-support/threadLaunchHarness.ts b/apps/server/src/j5/test-support/threadLaunchHarness.ts index 248ed37a06b2d..3ae1a3f0bc56a 100644 --- a/apps/server/src/j5/test-support/threadLaunchHarness.ts +++ b/apps/server/src/j5/test-support/threadLaunchHarness.ts @@ -14,6 +14,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as GitWorkflow from "../../git/GitWorkflowService.ts"; +import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts"; import { CodexProviderCapabilitiesV2 } from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; import * as CommandReceiptStore from "../../orchestration-v2/CommandReceiptStore.ts"; import * as EffectOutbox from "../../orchestration-v2/EffectOutbox.ts"; @@ -163,6 +164,7 @@ export function makeHarness(options: HarnessOptions = {}) { resolveRemoteTrackingCommit: () => Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" }), }), + Layer.mock(GitVcsDriver.GitVcsDriver)({}), Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, { runForThread: runSetup, }), diff --git a/apps/web/src/j5/crew/CrewProposalMemberRow.tsx b/apps/web/src/j5/crew/CrewProposalMemberRow.tsx index 6f09b933e1e92..ab6f8a9d13307 100644 --- a/apps/web/src/j5/crew/CrewProposalMemberRow.tsx +++ b/apps/web/src/j5/crew/CrewProposalMemberRow.tsx @@ -1,6 +1,6 @@ import { useAtomValue } from "@effect/atom-react"; import type { EnvironmentId } from "@t3tools/contracts"; -import type { CrewProposalSeatRuntime } from "@t3tools/contracts/j5"; +import type { CrewProposalSeatRuntime, CrewSeatWorkspace } from "@t3tools/contracts/j5"; import { PencilIcon, Trash2Icon } from "lucide-react"; import { type ReactNode } from "react"; @@ -12,6 +12,21 @@ import { deriveProviderInstanceEntries } from "../../providerInstances"; import { CUSTOM_AGENT, crewProposalRowChange, type CrewProposalRow } from "./crewProposalDraft"; import { crewSeatStopsForApprovals, describeCrewSeatWorkspace } from "./crewSeatRuntime"; +/** Where the member works; a new worktree's line carries the commit it starts from, in full on hover. */ +function MemberWorkspace(props: { workspace: CrewSeatWorkspace }) { + const { workspace } = props; + const line = describeCrewSeatWorkspace(workspace); + const className = "mt-1 break-words text-xs text-muted-foreground"; + if (workspace.type !== "worktree" || workspace.baseCommit === undefined) + return

{line}

; + return ( + + }>{line} + {workspace.baseCommit} + + ); +} + function MemberProvider(props: { environmentId: EnvironmentId; runtime?: CrewProposalSeatRuntime | undefined; @@ -94,9 +109,7 @@ export function CrewProposalMemberRow(props: { {row.original?.reason ?? "Added by the user"}

{runtime?.workspace && runtime.workspace.type !== "shared" ? ( -

- {describeCrewSeatWorkspace(runtime.workspace)} -

+ ) : null} {crewSeatStopsForApprovals(seat, runtime) ? (

Asks for approvals

diff --git a/apps/web/src/j5/crew/crewProposalDraft.ts b/apps/web/src/j5/crew/crewProposalDraft.ts index 0ad838521e7b0..722357a516f4e 100644 --- a/apps/web/src/j5/crew/crewProposalDraft.ts +++ b/apps/web/src/j5/crew/crewProposalDraft.ts @@ -153,7 +153,12 @@ const comparableDraft = (draft: CrewSeatDraft) => : draft.workspace.type === "shared" ? ["shared"] : draft.workspace.type === "worktree" - ? ["worktree", draft.workspace.baseRef, draft.workspace.startFromOrigin ?? false] + ? [ + "worktree", + draft.workspace.baseRef, + draft.workspace.baseCommit ?? null, + draft.workspace.startFromOrigin ?? false, + ] : ["existing_worktree", draft.workspace.worktreePath], ]); diff --git a/apps/web/src/j5/crew/crewSeatRuntime.test.ts b/apps/web/src/j5/crew/crewSeatRuntime.test.ts index e2fb22b5e8423..040104dc191f5 100644 --- a/apps/web/src/j5/crew/crewSeatRuntime.test.ts +++ b/apps/web/src/j5/crew/crewSeatRuntime.test.ts @@ -281,7 +281,33 @@ describe("crew seat workspace", () => { expect(added.seats[0]?.workspace).toEqual({ type: "shared" }); }); + it("drops a saved commit when the base or its origin choice is edited", () => { + const baseCommit = "3f9c2ab1".repeat(5); + const pinned = { + seat: "builder", + agentId: CUSTOM_AGENT, + instructions: "Build", + workspace: { type: "worktree" as const, baseRef: "main", baseCommit }, + }; + expect(setCrewSeatBaseRef(pinned, "release").workspace).toEqual({ + type: "worktree", + baseRef: "release", + }); + expect(setCrewSeatStartFromOrigin(pinned, true).workspace).toEqual({ + type: "worktree", + baseRef: "main", + startFromOrigin: true, + }); + }); + it("describes each choice on the seat row", () => { + expect( + describeCrewSeatWorkspace({ + type: "worktree", + baseRef: "main", + baseCommit: "3f9c2ab1".repeat(5), + }), + ).toBe("New worktree from main @ 3f9c2ab1"); expect(describeCrewSeatWorkspace({ type: "shared" })).toBe("Captain's checkout"); expect(describeCrewSeatWorkspace({ type: "worktree", baseRef: "release" })).toBe( "New worktree from release", diff --git a/apps/web/src/j5/crew/crewSeatRuntime.ts b/apps/web/src/j5/crew/crewSeatRuntime.ts index 4595bea1c0210..fd2680f607ba4 100644 --- a/apps/web/src/j5/crew/crewSeatRuntime.ts +++ b/apps/web/src/j5/crew/crewSeatRuntime.ts @@ -125,20 +125,24 @@ export const chooseCrewSeatWorkspace = ( : { type, worktreePath: options?.worktrees[0]?.path ?? "" }, }); -/** A new worktree's base branch; other fields of the choice stay as they were. */ -export const setCrewSeatBaseRef = (draft: CrewSeatDraft, baseRef: string): CrewSeatDraft => - draft.workspace?.type === "worktree" - ? { ...draft, workspace: { ...draft.workspace, baseRef } } - : { ...draft, workspace: { type: "worktree", baseRef } }; +/** + * A new worktree's base branch; other fields of the choice stay as they were. The saved commit is + * dropped: an edited base is resolved again, and the new commit shown, before it can be approved. + */ +export const setCrewSeatBaseRef = (draft: CrewSeatDraft, baseRef: string): CrewSeatDraft => { + const { baseCommit: _pin, ...kept } = draft.workspace?.type === "worktree" ? draft.workspace : {}; + return { ...draft, workspace: { ...kept, type: "worktree", baseRef } }; +}; /** Whether a new worktree starts from the fetched origin copy of its base branch. */ export const setCrewSeatStartFromOrigin = ( draft: CrewSeatDraft, startFromOrigin: boolean, -): CrewSeatDraft => - draft.workspace?.type === "worktree" - ? { ...draft, workspace: { ...draft.workspace, startFromOrigin } } - : draft; +): CrewSeatDraft => { + if (draft.workspace?.type !== "worktree") return draft; + const { baseCommit: _pin, ...kept } = draft.workspace; + return { ...draft, workspace: { ...kept, startFromOrigin } }; +}; export const setCrewSeatWorktree = (draft: CrewSeatDraft, worktreePath: string): CrewSeatDraft => ({ ...draft, @@ -149,7 +153,7 @@ export const describeCrewSeatWorkspace = (workspace: CrewSeatWorkspace): string workspace.type === "shared" ? "Captain's checkout" : workspace.type === "worktree" - ? `New worktree from ${workspace.baseRef}` + ? `New worktree from ${workspace.baseRef}${workspace.baseCommit === undefined ? "" : ` @ ${workspace.baseCommit.slice(0, 8)}`}` : `Existing worktree on ${workspace.branch ?? workspace.worktreePath}`; /** A different model starts with its own advertised defaults, never options from another model. */ diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index f5f434fc92494..6006847d295fe 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -123,7 +123,7 @@ safely; reusing it with any change to the request is refused, so use a fresh one **Rules.** The new agent is an ordinary root-lineage thread created through upstream's creation seam, never through delegation. It is created in the caller's project unless the caller names another with `project_id` or sets `scratch`, and it joins that project's ledger. An [outside agent](index.md#participants) has no project, so it passes one of the two on every spawn. These are what upstream's own launch tool offers and J5's lacked (Jackson, 2026-10-11). In another project the caller is still recorded as the spawner, but the placement tree is one project's, so the agent is a root there and stays at the top level of the sidebar. An outside agent is in no project's tree, so every agent it starts is a root, with the outside agent's `outside:` id recorded as its spawner. Without a persona the agent runs in the caller's permission and interaction modes, or in ones the caller chose, which may be no broader than the caller's own. Without a persona its model must also be one the project's [Models for custom members](../features/crews.md) list allows, the project being the one the agent joins. The check runs before anything is created and only on a first attempt, so a retry that finds its agent already created is not held to a list saved since; a refusal names the model, the project and the setting and lists the eligible models. A persona's own model is never checked. For an outside agent the caller's modes are the level its sign-in was approved at, and a read-only sign-in spawns nothing. A persona's policy sets its permissions. For a thread caller it has no ceiling (2026-09-16). For an outside agent it must be within the approved level, because that level is a promise the approval page makes about an agent the person does not watch. Either caller may still choose a narrower interaction mode for a persona. A retry finishes the agent its first attempt created, in the modes it was created with, so it is refused when those are now broader than the caller's own; a caller's modes can be narrowed between the two. An outside agent's retry keys belong to its sign-in, whose level never changes. `attachments` are pending uploads, claimed into the new thread once it exists and carried by the brief. Placement and provenance are recorded atomically with creation; then the brief starts as the first turn. The new agent's first turn also states its own participant id and project as platform-provided facts, beside the brief and never inside it. When an outside agent started it, those facts name the outside agent by its label and say that `j5_send_message` cannot reply to it. Provider, model and reasoning are required and explicit even when a Role is given: a Role's allowlist constrains the choice and an out-of-list pick is an error naming the Role, never a silent default. The brief carries the task and the reply expectation; the spawner does not follow a spawn with a reply-expected `j5_send_message` — that form is for later work owed by an existing participant. Selection guidance and brief-writing conventions live in the [Spawning Guide](../features/spawning-guide.md). -**Workspace.** The spawner chooses where a Peer Agent works every time; there is no default, because the spawner knows whether it is starting a reviewer that must see uncommitted work, a builder that must not collide, or a scout that can't collide at all (Jackson, 2026-10-03). `{type: "shared"}` is the caller's own checkout and branch, and asks nothing of git; it is refused for an agent that joins another project, and for an outside agent, which has no checkout. `{type: "root"}` is the project's main checkout, upstream's name for it, and the only choice with `scratch`. As upstream's launch does, a main-checkout thread in the "No project" project gets a fresh folder of its own, whether the caller set `scratch` or named that project by its id. `{type: "worktree"}` is a new worktree from `base_ref`, which is required and must resolve to a commit (with `start_from_origin`, its fetched origin copy counts); a `branch` that already exists is refused. `{type: "existing_worktree"}` is one of the project's git worktrees other than its main checkout, named by path; the agent works on the branch git has checked out there, and any other path is refused with the valid ones listed. A choice that needs git is refused when the repository can't be read, before anything is created. A new worktree's thread is created unbound, with its registration and placement committed, so `j5_spawn_agent` returns as soon as the agent is registered and its brief accepted, not once the worktree is ready. Upstream's ThreadLaunch then creates the worktree, names a temporary `j5code/` branch and renames it from the brief in the background, and holds the brief as a preparing run until the worktree is bound and the project's setup script has started. The setup script is awaited first only when it is set to finish before the agent starts (`async: false`); otherwise the agent may begin while it is still running. If preparation fails, the agent's thread shows the failed preparation, as any upstream launch does; it is not retried or retired, and the spawner is not told. The agent is then unbound, which upstream reads as the project's checkout, so a later message to it runs there, where every Peer Agent worked before workspaces existed. J5 doesn't guard this upstream behaviour: in Jackson's install, 3 of 61 preparations failed, all on the first day, and none was messaged again (Jackson, 2026-10-06). A shared checkout or an existing worktree binds at creation, so its brief starts at once. A `client_request_id` is bound to the whole request it was first accepted with, before anything is created, and the binding survives a restart. A retry with any change, including another workspace, `base_ref` or `worktree_path`, is refused, naming the agent the first attempt created; new work needs a fresh `client_request_id`. A request refused before it is accepted, such as one with duplicate attachment ids or an unusable workspace, binds nothing, so it can be corrected under the same key. A retry of a spawn from before request binding binds its first retry when the workspace type matches its accepted create receipt, and is refused otherwise; later request changes under that key are refused. A second start for the same thread while one is in flight is refused with a retry instruction, so two concurrent retries cannot both create it. An existing worktree is looked up in upstream's ref listing, which refreshes every few seconds, so one created moments ago may be refused once; retry in a moment. Closing or archiving a Peer Agent never removes its worktree. +**Workspace.** The spawner chooses where a Peer Agent works every time; there is no default, because the spawner knows whether it is starting a reviewer that must see uncommitted work, a builder that must not collide, or a scout that can't collide at all (Jackson, 2026-10-03). `{type: "shared"}` is the caller's own checkout and branch, and asks nothing of git; it is refused for an agent that joins another project, and for an outside agent, which has no checkout. `{type: "root"}` is the project's main checkout, upstream's name for it, and the only choice with `scratch`. As upstream's launch does, a main-checkout thread in the "No project" project gets a fresh folder of its own, whether the caller set `scratch` or named that project by its id. `{type: "worktree"}` is a new worktree from `base_ref`, which is required and must resolve to a commit (with `start_from_origin`, an already fetched origin copy counts; the spawn checks this without fetching, and preparation does the fetch); a `branch` that already exists is refused. `{type: "existing_worktree"}` is one of the project's git worktrees other than its main checkout, named by path; the agent works on the branch git has checked out there, and any other path is refused with the valid ones listed. A choice that needs git is refused when the repository can't be read, before anything is created. A new worktree's thread is created unbound, with its registration and placement committed, so `j5_spawn_agent` returns as soon as the agent is registered and its brief accepted, not once the worktree is ready. Upstream's ThreadLaunch then creates the worktree, names a temporary `j5code/` branch and renames it from the brief in the background, and holds the brief as a preparing run until the worktree is bound and the project's setup script has started. The setup script is awaited first only when it is set to finish before the agent starts (`async: false`); otherwise the agent may begin while it is still running. If preparation fails, the agent's thread shows the failed preparation, as any upstream launch does; it is not retried or retired, and the spawner is not told. The agent is then unbound, which upstream reads as the project's checkout, so a later message to it runs there, where every Peer Agent worked before workspaces existed. J5 doesn't guard this upstream behaviour: in Jackson's install, 3 of 61 preparations failed, all on the first day, and none was messaged again (Jackson, 2026-10-06). A shared checkout or an existing worktree binds at creation, so its brief starts at once. A `client_request_id` is bound to the whole request it was first accepted with, before anything is created, and the binding survives a restart. A retry with any change, including another workspace, `base_ref` or `worktree_path`, is refused, naming the agent the first attempt created; new work needs a fresh `client_request_id`. A request refused before it is accepted, such as one with duplicate attachment ids or an unusable workspace, binds nothing, so it can be corrected under the same key. A retry of a spawn from before request binding binds its first retry when the workspace type matches its accepted create receipt, and is refused otherwise; later request changes under that key are refused. A second start for the same thread while one is in flight is refused with a retry instruction, so two concurrent retries cannot both create it. An existing worktree is looked up in upstream's ref listing, which refreshes every few seconds, so one created moments ago may be refused once; retry in a moment. Closing or archiving a Peer Agent never removes its worktree. **Result:** the new agent's `participant_id` and `thread_id`, its `project_id` and `project_title`, and its placement with the caller recorded as spawner: under the caller in the caller's own project, and with no parent in another or when the caller is an outside agent. @@ -267,7 +267,7 @@ gate inline above the Captain's composer unless Auto-approve new Crews is enable caller, persona-backed where a seat names one, records the Crew snapshot with each member's reason (with human or automatic approval recorded), and posts a `` launch report into the caller's thread immediately after creation: the roster, what the user changed against the proposal, and per seat `start=waiting|started|failed|pending`, with a `seat_failed` line carrying the run's error (`not_started` when the seat's thread exists but registration failed) 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. New and added seats wait for their first assignment. A direct chat message, participant message, or playbook handoff activates the seat with its approved instructions and shared brief, the current roster with responsibilities and participant ids, and the assignment with its envelope and reply obligation intact. A new-worktree seat prepares its workspace before running that assignment; failed preparation is reported as a seat failure. +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). A new worktree's base is resolved to a full commit before the proposal is stored, and the proposal keeps that commit with the requested ref as its label; a ref that doesn't resolve is refused at once, naming the seat, and renaming, moving or deleting the branch afterwards changes nothing while the commit exists. With `start_from_origin` the commit is origin's tip, fetched when the base is chosen, and preparation starts from it without fetching again; a base with no branch on origin falls back to the local ref, and when origin can't be fetched the preview refuses that seat alone, naming it, rather than pinning a stale commit, with a next step to check the connection to origin or start from the local branch. To start from the Captain's current checkout, name the branch it is on; uncommitted changes are not included. Preparation names the commit as the worktree's base, so such a worktree has no `gh-merge-base` and the setup tracker shows the commit; `gh pr create` there needs an explicit base. Each seat's workspace resolves again at preview against the Captain's repository, and the approval token binds it, as it binds the Captain's branch and worktree. A proposal stored before commits were pinned has its ref resolved at its first preview, which approval then binds; if the ref is gone the preview refuses, naming the seat and ref, and the base must be edited. 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. New and added seats wait for their first assignment. A direct chat message, participant message, or playbook handoff activates the seat with its approved instructions and shared brief, the current roster with responsibilities and participant ids, and the assignment with its envelope and reply obligation intact. A new-worktree seat prepares its workspace before running that assignment; failed preparation is reported as a seat failure. 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. **Models for custom members** is a pair of project settings holding the checked provider models and the checked reasoning levels; until a list is saved everything it covers is eligible. A custom seat, including one that inherits the Captain's selection, must run on an eligible model at an eligible level (its explicit one, or the model's default), checked at preview, at approval, and for an automatic launch, so a roster naming another is refused whole before anything spawns, with an error naming the seat, the model or level, the project and the setting and listing the eligible ones. A model with no reasoning option has no level to check. A saved persona seat that keeps the persona's model and level skips the check; one where the person changed either on the card is checked like a custom seat. An accepted proposal is not checked again. diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index ff720334c752d..1371bf4b2d748 100644 --- a/docs/j5/product/features/crews.md +++ b/docs/j5/product/features/crews.md @@ -67,7 +67,7 @@ A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26). 1. An explicit request for a Crew, a Peer Agent or a subagent gets that mechanism (Jackson, 2026-10-31); a word mentioned in passing, or in quoted text, is not a request. When the person asked for none, an agent chooses between working directly, subagents for independent assignments, and a Crew for work whose workers must respond to each other, from the work. It may reassess mid-work and carry finished findings forward without restarting completed work. Once it chooses a Crew it proposes 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. 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. +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. A new worktree’s line shows the commit it starts from (the base branch is its label), and renaming or moving that branch does not change it. Editing a base resolves and shows a new commit that the person approves. A base started from origin shows origin's tip, or the local branch when origin has no such branch; if origin can't be reached, only that member is refused until the connection is back or its base is edited. 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. @@ -175,7 +175,11 @@ A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26). - 2026-10-27 — when the person asked for none, an agent chooses between working directly, subagents, and a Crew from the work; an explicit request for a Crew, a Peer Agent or a subagent still gets that mechanism; members run their own review loops and reach the Captain only for a review pass, a blocker, or a disagreement, or their final result (AC1, AC9; Bryant and Jackson; [#746](https://github.com/Jacksondr5/j5code/issues/746)). <<<<<<< HEAD - 2026-10-27 — a Captain asks the person for a decision with `j5_send_message`: one request, listed in the Inbox and pinned above the Captain's composer, answered in either place (Bryant; [#747](https://github.com/Jacksondr5/j5code/issues/747)). This replaces the 2026-09-26 line that had the Captain ask inline with its own question tool. + <<<<<<< HEAD +- 2026-10-27 — a new worktree seat's base is resolved to a commit when the proposal is accepted and launches from it, so branch renames cannot break a launch; a worktree prepared from that commit has no `gh-merge-base` (AC3; Bryant; [#752](https://github.com/Jacksondr5/j5code/issues/752)). + \======= \======= - 2026-10-31 — a member's introduction and roster changes are visible in its own thread, as a collapsed card that opens to what the model read, where they had been sent to the model only (Jackson, 2026-10-31; register D43). > > > > > > > s/746 +> > > > > > > s/747 diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index 425c9a31e7c6f..39e6265452c93 100644 --- a/packages/contracts/src/j5.ts +++ b/packages/contracts/src/j5.ts @@ -107,7 +107,14 @@ export const CrewSeatWorkspace = Schema.Union([ Schema.Struct({ type: Schema.Literal("shared") }), Schema.Struct({ type: Schema.Literal("worktree"), + /** The label for the base; what the worktree starts from is `baseCommit`. */ baseRef: Schema.String, + /** + * The full commit `baseRef` meant when the choice was accepted. Absent only on a choice stored + * before commits were pinned, or edited on the card since; preview then resolves it and the + * approval binds what it showed. + */ + baseCommit: Schema.optionalKey(Schema.String), branch: Schema.optionalKey(Schema.String), startFromOrigin: Schema.optionalKey(Schema.Boolean), }), diff --git a/packages/contracts/src/j5/crewProposal.test.ts b/packages/contracts/src/j5/crewProposal.test.ts index 19ee349e73c3e..e2db6b2bb9c4a 100644 --- a/packages/contracts/src/j5/crewProposal.test.ts +++ b/packages/contracts/src/j5/crewProposal.test.ts @@ -105,3 +105,27 @@ it("carries the person's replacement persona text through a preview and an appro }), ).toMatchObject({ seats: [{ personaInstructions: "Only read the README." }] }); }); + +it("carries a new worktree's saved commit through a preview request and a preview's runtime", () => { + const baseCommit = "3f9c2ab1".repeat(5); + const workspace = { type: "worktree", baseRef: "main", baseCommit } as const; + const seat = { seat: "builder", agentId: null, reason: "Build", workspace }; + expect( + decodePreviewRequest({ proposalId: "proposal", seats: [seat] }).seats?.[0]?.workspace, + ).toEqual(workspace); + const runtime = { + seat: "builder", + provider: "Codex", + harness: "Codex", + model: "gpt", + reasoning: "High", + access: "Full access", + modelSelection: { instanceId: "codex", model: "gpt" }, + runtimeMode: "full-access", + workspace, + }; + expect( + decodePreviewResponse({ proposalId: "proposal", approvalToken: "token", seats: [runtime] }) + .seats[0]?.workspace, + ).toEqual(workspace); +});