diff --git a/apps/mobile/src/j5/archive/ArchiveWarningSheet.tsx b/apps/mobile/src/j5/archive/ArchiveWarningSheet.tsx index 0e9f1d7ee56ad..8a843b29beb14 100644 --- a/apps/mobile/src/j5/archive/ArchiveWarningSheet.tsx +++ b/apps/mobile/src/j5/archive/ArchiveWarningSheet.tsx @@ -2,10 +2,14 @@ import { ARCHIVE_WARNING_WORKSPACE_NOTE, archiveWarningAskHeader, archiveWarningSeatConsequences, + groupWorktreeEstimates, sentenceEnd, + worktreeReasonLabel, + worktreeShortPath, type ArchiveWarning, type ArchiveWarningPayload, type ArchiveWarningRow, + type ArchiveWarningWorktrees, } from "@t3tools/client-runtime/j5/archive-flow"; import { useSyncExternalStore } from "react"; import { Modal, Platform, ScrollView, View } from "react-native"; @@ -84,6 +88,64 @@ function AskRow({ row }: { readonly row: ArchiveWarningRow }) { ); } +function WorktreeList({ + heading, + worktrees, +}: { + readonly heading: string; + readonly worktrees: NonNullable; +}) { + if (worktrees.length === 0) return null; + return ( + + + {heading} + + {worktrees.map((worktree) => ( + + + {worktree.seat} + + + {worktreeShortPath(worktree.path)} + + {worktree.reason === null ? null : ( + + {worktreeReasonLabel[worktree.reason]} + + )} + + ))} + + ); +} + +/** Which worktrees J5 made for the Crews' seats archiving would remove, and which stay. */ +function WorktreeSection({ worktrees }: { readonly worktrees: ArchiveWarningWorktrees }) { + if (worktrees === null) + return ( + + Worktrees: couldn't check. Branches and pull requests remain. + + ); + const { removed, kept } = groupWorktreeEstimates(worktrees); + return ( + + + + + {worktrees.length === 0 + ? "No worktrees were created for these seats. " + : "This is an estimate; each is checked again when you archive. "} + Branches and pull requests remain. + + + ); +} + function ArchiveWarningFacts({ payload }: { readonly payload: ArchiveWarningPayload }) { const crews = payload.crews?.state === "known" ? payload.crews.crews : []; const asks = asksByUrgency(payload.openAsks); @@ -160,9 +222,13 @@ function ArchiveWarningFacts({ payload }: { readonly payload: ArchiveWarningPayl ))} ) : null} - - {ARCHIVE_WARNING_WORKSPACE_NOTE} - + {payload.worktrees === undefined ? ( + + {ARCHIVE_WARNING_WORKSPACE_NOTE} + + ) : ( + + )} ); } diff --git a/apps/server/src/j5/a2a/ArchiveCrewService.test.ts b/apps/server/src/j5/a2a/ArchiveCrewService.test.ts index d0a332f698452..a2713813c5b1d 100644 --- a/apps/server/src/j5/a2a/ArchiveCrewService.test.ts +++ b/apps/server/src/j5/a2a/ArchiveCrewService.test.ts @@ -1,5 +1,5 @@ import { assert, it } from "@effect/vitest"; -import { CommandId, RunId, ThreadId } from "@t3tools/contracts"; +import { CommandId, ProviderSessionId, RunId, ThreadId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; @@ -23,6 +23,8 @@ import { } from "./ArchiveCrewService.ts"; import { PlaybookStore } from "../playbooks/PlaybookStore.ts"; import { ExchangeId, ParticipantId, LedgerProjectId } from "./contracts.ts"; +import { CrewWorktrees } from "./CrewWorktrees.ts"; +import type { CrewArchiveWorktree } from "@t3tools/contracts/j5"; const projectId = LedgerProjectId.make("project:j5:archive-crew"); const captain = ParticipantId.make("agent:j5:a2a:captain"); @@ -89,9 +91,41 @@ const fixture = Effect.gen(function* () { const crewArchivedAt = yield* Ref.make(null); // The order of cancels and retired stamps, so a test can see the run ends before the stamp. const lifecycle = yield* Ref.make>([]); + // What cleanup was asked about, and what it reports back. + const cleanedSeats = yield* Ref.make>>([]); + const cleanupResult = yield* Ref.make>([]); + // The retired stamps and playbook cancels that had already happened when cleanup was asked. + const lifecycleAtCleanup = yield* Ref.make>([]); + // The order of session reads, seat archives, session closes and cleanup passes. + const sessionSteps = yield* Ref.make>([]); + const openSessions = new Map([ + [ThreadId.make("t:b"), ProviderSessionId.make("session:b")], + ]); + const step = (name: string) => Ref.update(sessionSteps, (items) => [...items, name]); const layer = archiveCrewLayer.pipe( Layer.provide( Layer.mergeAll( + Layer.mock(CrewWorktrees)({ + liveSessions: (seats) => + Effect.forEach(seats, (seat) => step(`read:${seat.threadId}`)).pipe( + Effect.as( + seats.flatMap((seat) => { + const providerSessionId = openSessions.get(seat.threadId); + return providerSessionId === undefined + ? [] + : [{ threadId: seat.threadId, providerSessionId }]; + }), + ), + ), + closeSessions: (sessions) => + Effect.forEach(sessions, (session) => step(`close:${session.providerSessionId}`)), + cleanup: ({ seats }) => + Effect.all([ + step("cleanup"), + Ref.update(cleanedSeats, (items) => [...items, seats.map((seat) => seat.threadId)]), + Ref.get(lifecycle).pipe(Effect.flatMap((seen) => Ref.set(lifecycleAtCleanup, seen))), + ]).pipe(Effect.andThen(Ref.get(cleanupResult))), + }), Layer.mock(ArchiveAgentService)({ readFacts: (target) => Effect.gen(function* () { @@ -105,6 +139,7 @@ const fixture = Effect.gen(function* () { }), archive: (input) => Effect.gen(function* () { + yield* step(`archive:${input.target.threadId}`); // Mirrors the real service: a retired member replays as already archived. if ((yield* Ref.get(facts))[input.target.participantId]?.retired) return "already_archived" as const; @@ -180,6 +215,10 @@ const fixture = Effect.gen(function* () { facts, lifecycle, crewArchivedAt, + cleanedSeats, + cleanupResult, + lifecycleAtCleanup, + sessionSteps, }; }); @@ -225,6 +264,7 @@ it.effect("refuses until the captain confirms every member's facts, then retires { seatName: "builder", participantId: builder, result: "archived" }, { seatName: "critic", participantId: critic, result: "archived" }, ], + worktrees: [], }); const calls = yield* Ref.get(archived); assert.deepStrictEqual( @@ -422,6 +462,7 @@ it.effect("retires the unit past a seat whose thread was never created, and says { seatName: "builder", participantId: builder, result: "archived" }, { seatName: "critic", participantId: critic, result: "never_created" }, ], + worktrees: [], }); assert.deepStrictEqual( (yield* Ref.get(archived)).map((call) => call.target.participantId), @@ -463,3 +504,97 @@ it.effect( }).pipe(Effect.provide(layer)); }), ); + +it.effect( + "cleans up worktrees once every seat is archived and the Crew is stamped, and reports the result", + () => + Effect.gen(function* () { + const { layer, input, lifecycleAtCleanup, cleanedSeats, cleanupResult } = yield* fixture; + const reported: ReadonlyArray = [ + { path: "/wt/builder", branch: "j5/builder", outcome: "removed", reason: null }, + { path: "/wt/critic", branch: "j5/critic", outcome: "kept", reason: "unmerged_commits" }, + ]; + yield* Ref.set(cleanupResult, reported); + yield* Effect.gen(function* () { + const service = yield* ArchiveCrewService; + const outcome = yield* service.archive( + input({ callerParticipantId: null, confirmationSatisfied: true }), + ); + assert.deepStrictEqual(outcome.worktrees, reported); + assert.deepStrictEqual(yield* Ref.get(cleanedSeats), [ + [ThreadId.make("t:b"), ThreadId.make("t:c")], + ]); + // The archive is committed, and the Crew stamped, before anything is removed. + assert.include(yield* Ref.get(lifecycleAtCleanup), `marked:${instance.id}`); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("closes each seat's session after its archive and before the worktree cleanup", () => + Effect.gen(function* () { + const { layer, input, sessionSteps } = yield* fixture; + yield* Effect.gen(function* () { + const service = yield* ArchiveCrewService; + yield* service.archive(input({ callerParticipantId: null, confirmationSatisfied: true })); + // The session is read before the seat's archive removes its binding, closed once every + // seat is archived, and the cleanup comes last. + assert.deepStrictEqual(yield* Ref.get(sessionSteps), [ + "read:t:b", + "archive:t:b", + "read:t:c", + "archive:t:c", + "close:session:b", + "cleanup", + ]); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("a replay of an archived Crew checks its worktrees again", () => + Effect.gen(function* () { + const { layer, input, cleanedSeats, cleanupResult } = yield* fixture; + yield* Effect.gen(function* () { + const service = yield* ArchiveCrewService; + yield* service.archive(input({ callerParticipantId: null, confirmationSatisfied: true })); + yield* Ref.set(cleanupResult, [ + { path: "/wt/critic", branch: "j5/critic", outcome: "removed", reason: null }, + ]); + const replay = yield* service.archive( + input({ callerParticipantId: null, confirmationSatisfied: true }), + ); + assert.equal(replay.status, "already_archived"); + assert.deepStrictEqual( + replay.worktrees.map((entry) => entry.outcome), + ["removed"], + ); + assert.lengthOf(yield* Ref.get(cleanedSeats), 2); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("a seat that never came to exist is not looked at for a worktree", () => + Effect.gen(function* () { + const { layer, input, facts, cleanedSeats } = yield* fixture; + yield* Ref.update(facts, (current) => ({ ...current, [critic]: null })); + yield* Effect.gen(function* () { + const service = yield* ArchiveCrewService; + yield* service.archive(input({ callerParticipantId: null, confirmationSatisfied: true })); + assert.deepStrictEqual(yield* Ref.get(cleanedSeats), [[ThreadId.make("t:b")]]); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("a failed archive removes nothing", () => + Effect.gen(function* () { + const { layer, input, failSeat, cleanedSeats } = yield* fixture; + yield* Ref.set(failSeat, critic); + yield* Effect.gen(function* () { + const service = yield* ArchiveCrewService; + const failure = yield* service + .archive(input({ callerParticipantId: null, confirmationSatisfied: true })) + .pipe(Effect.flip); + assert.instanceOf(failure, ArchiveCrewPartialFailureError); + assert.lengthOf(yield* Ref.get(cleanedSeats), 0); + }).pipe(Effect.provide(layer)); + }), +); diff --git a/apps/server/src/j5/a2a/ArchiveCrewService.ts b/apps/server/src/j5/a2a/ArchiveCrewService.ts index 3752276415c60..27128b6799869 100644 --- a/apps/server/src/j5/a2a/ArchiveCrewService.ts +++ b/apps/server/src/j5/a2a/ArchiveCrewService.ts @@ -13,6 +13,7 @@ import { signPayload, timingSafeEqualBase64Url, } from "../../auth/utils.ts"; +import type { CrewArchiveWorktree } from "@t3tools/contracts/j5"; import { PlaybookStore } from "../playbooks/PlaybookStore.ts"; import { AgentCrewInstanceService, type AgentCrewInstance } from "./AgentCrewInstanceService.ts"; import { @@ -22,6 +23,7 @@ import { type ArchiveAgentResult, } from "./ArchiveAgentService.ts"; import { ParticipantId, LedgerProjectId } from "./contracts.ts"; +import { CrewWorktrees, type CrewSeatSession } from "./CrewWorktrees.ts"; const TOKEN_VERSION = "j5-crew-archive-confirmation/v1" as const; const TOKEN_SECRET_NAME = "j5-a2a-archive-confirmation-v1"; @@ -78,6 +80,12 @@ export interface ArchiveCrewMemberResult { export interface ArchiveCrewOutcome { readonly status: ArchiveAgentResult; readonly members: ReadonlyArray; + /** + * What the archive did with each worktree J5 created for the Crew's seats. Cleanup runs after + * the archive commits and never fails it, so this reports removals, worktrees kept with the + * reason, and removals that failed. + */ + readonly worktrees: ReadonlyArray; } export class ArchiveCrewNotFoundError extends Data.TaggedError("ArchiveCrewNotFoundError")<{ @@ -201,6 +209,12 @@ const payloadFor = (input: ArchiveCrewInput, facts: ArchiveCrewConsequenceFacts) })), }); +/** The seats whose threads exist; a seat that never came to exist has no worktree to look at. */ +const createdSeats = (facts: ArchiveCrewConsequenceFacts) => + facts.members + .filter((member) => !member.neverCreated) + .map((member) => ({ seatName: member.seatName, threadId: member.threadId })); + const hasConsequences = (facts: ArchiveCrewConsequenceFacts) => facts.members.some( (member) => member.facts.openExchanges.length > 0 || member.facts.runningTurn !== null, @@ -265,6 +279,7 @@ export const layer = Layer.effect( const archiveAgent = yield* ArchiveAgentService; const crews = yield* AgentCrewInstanceService; const playbooks = yield* PlaybookStore; + const worktrees = yield* CrewWorktrees; const secrets = yield* ServerSecretStore; const secret = secrets .getOrCreateRandom(TOKEN_SECRET_NAME, TOKEN_SECRET_BYTES) @@ -346,8 +361,8 @@ export const layer = Layer.effect( // The roster is read, confirmed, and retired as one unit step, so an approved launch or // addition either lands before the read and retires with the rest, or waits and meets the // retired stamp before it reserves a seat. - const archive: ArchiveCrewServiceShape["archive"] = Effect.fn("j5.a2a.archiveCrew.archive")( - function* (input) { + const archiveUnit = Effect.fn("j5.a2a.archiveCrew.archiveUnit")( + function* (input: ArchiveCrewInput) { const decodedToken = input.confirmationToken === undefined ? undefined @@ -391,6 +406,8 @@ export const layer = Layer.effect( ? ("never_created" as const) : ("already_archived" as const), })), + seats: createdSeats(facts), + sessions: [] as ReadonlyArray, }; } @@ -418,6 +435,7 @@ export const layer = Layer.effect( } const results: Array = []; + const sessions: Array = []; for (const member of facts.members) { if (member.neverCreated) { results.push({ @@ -428,6 +446,12 @@ export const layer = Layer.effect( continue; } const ids = input.commandIds(member.seatName); + // Before the archive: committing it removes the binding that names the session. + sessions.push( + ...(yield* worktrees.liveSessions([ + { seatName: member.seatName, threadId: member.threadId }, + ])), + ); const result = yield* archiveAgent .archive({ providerSessionId: input.providerSessionId, @@ -465,11 +489,29 @@ export const layer = Layer.effect( yield* crews .markArchived(instance.id, input.archivedAt, { withCaptain: input.withCaptain === true }) .pipe(Effect.orDie); - return { status: "archived" as const, members: results }; + return { + status: "archived" as const, + members: results, + seats: createdSeats(facts), + sessions, + }; }, (unit, input) => crews.serialize(input.crewInstanceId, unit), ); + // After the unit's step commits and its lock is released, so a slow check or removal holds + // nothing. Also on the already-archived replay: a worktree kept because a session was still + // open, or because a check failed, gets another look when the archive is asked for again. + const archive: ArchiveCrewServiceShape["archive"] = Effect.fn("j5.a2a.archiveCrew.archive")( + function* (input) { + const { seats, sessions, ...outcome } = yield* archiveUnit(input); + // Each seat's session is closed before the cleanup looks for one open in its worktree. + yield* worktrees.closeSessions(sessions); + const removed = yield* worktrees.cleanup({ seats }); + return { ...outcome, worktrees: removed }; + }, + ); + const readCaptainFacts: ArchiveCrewServiceShape["readCaptainFacts"] = Effect.fn( "j5.a2a.archiveCrew.readCaptainFacts", )(function* (input) { diff --git a/apps/server/src/j5/a2a/ClientActionsService.test.ts b/apps/server/src/j5/a2a/ClientActionsService.test.ts index 702e927077ad3..206154c18f816 100644 --- a/apps/server/src/j5/a2a/ClientActionsService.test.ts +++ b/apps/server/src/j5/a2a/ClientActionsService.test.ts @@ -102,6 +102,20 @@ const serviceWith = (seen: ReturnType) => result: "never_created" as const, }, ], + worktrees: [ + { + path: "/wt/builder", + branch: "j5/builder", + outcome: "removed" as const, + reason: null, + }, + { + path: "/wt/critic", + branch: null, + outcome: "kept" as const, + reason: "uncommitted_changes" as const, + }, + ], }) : Effect.fail(new ArchiveCrewNotFoundError({ crewInstanceId: input.crewInstanceId })); }, @@ -206,6 +220,13 @@ it.effect("archives a Crew as a person, with the dialog's confirmation already s ["critic", "already_archived"], ], ); + assert.deepStrictEqual( + archived.worktrees.map((entry) => [entry.path, entry.outcome, entry.reason]), + [ + ["/wt/builder", "removed", null], + ["/wt/critic", "kept", "uncommitted_changes"], + ], + ); // A person is not a participant and confirmed the dialog: no Captain check, no token dance. const [input] = seen.archives; assert.isNull(input?.callerParticipantId); diff --git a/apps/server/src/j5/a2a/ClientActionsService.ts b/apps/server/src/j5/a2a/ClientActionsService.ts index e17b2579333d8..6c85ec7304e6d 100644 --- a/apps/server/src/j5/a2a/ClientActionsService.ts +++ b/apps/server/src/j5/a2a/ClientActionsService.ts @@ -191,7 +191,12 @@ const make = Effect.gen(function* () { }), }), }); - return { crewInstanceId, status: result.status, members: createdSeats(result.members) }; + return { + crewInstanceId, + status: result.status, + members: createdSeats(result.members), + worktrees: result.worktrees, + }; }), respondCrewRuntimeRequest: Effect.fn("ClientActionsService.respondCrewRuntimeRequest")( function ({ threadId, requestId, decision }, claim) { diff --git a/apps/server/src/j5/a2a/ClientReadsService.test.ts b/apps/server/src/j5/a2a/ClientReadsService.test.ts index 9d86bd2eaee17..d873ccd14f754 100644 --- a/apps/server/src/j5/a2a/ClientReadsService.test.ts +++ b/apps/server/src/j5/a2a/ClientReadsService.test.ts @@ -11,6 +11,7 @@ import { PlaybookStore } from "../playbooks/PlaybookStore.ts"; import { AgentCrewInstanceService } from "./AgentCrewInstanceService.ts"; import { AgentCrewProposalService } from "./AgentCrewProposalService.ts"; import { ArchiveCrewService } from "./ArchiveCrewService.ts"; +import { CrewWorktrees } from "./CrewWorktrees.ts"; import { A2AArchiveFacts } from "./ArchiveFactsService.ts"; import { CrewRuntimeRequestService } from "./CrewRuntimeRequestService.ts"; import { ParticipantPlacementService } from "./PlacementService.ts"; @@ -49,6 +50,7 @@ const makeTestLayer = () => { Layer.mock(PlaybookStore)({}), Layer.mock(A2AArchiveFacts)({}), Layer.mock(ArchiveCrewService)({}), + Layer.mock(CrewWorktrees)({}), ); const clientReads = clientReadsLayer.pipe( Layer.provide(inbox), diff --git a/apps/server/src/j5/a2a/ClientReadsService.ts b/apps/server/src/j5/a2a/ClientReadsService.ts index 0603f06c81adc..58b61556c6cf6 100644 --- a/apps/server/src/j5/a2a/ClientReadsService.ts +++ b/apps/server/src/j5/a2a/ClientReadsService.ts @@ -21,10 +21,15 @@ import { AgentCrewInstanceService } from "./AgentCrewInstanceService.ts"; import { AgentCrewProposalService } from "./AgentCrewProposalService.ts"; import { ArchiveCrewService } from "./ArchiveCrewService.ts"; import { A2AArchiveFacts } from "./ArchiveFactsService.ts"; +import { + makeCrewArchiveWorktreesRead, + type CrewArchiveWorktreeRead, +} from "./crewArchiveWorktreesRead.ts"; import { makeCrewMembershipsRead } from "./crewMembershipsRead.ts"; import { projectCrewProposal } from "./crewProposalProjection.ts"; import { CrewRuntimeRequestService } from "./CrewRuntimeRequestService.ts"; import { clientReadBatches } from "./clientReadBatches.ts"; +import { CrewWorktrees } from "./CrewWorktrees.ts"; import { makeFleetRead } from "./fleetRead.ts"; import { type A2AHumanInboxError, A2AHumanInbox } from "./HumanInboxService.ts"; import { A2ALedger } from "./LedgerService.ts"; @@ -257,6 +262,16 @@ export interface ClientReadsShape { readonly preArchiveFacts: ( threadId: ThreadId, ) => Effect.Effect["error"]>; + /** + * What archiving these Crews would do with the worktrees J5 created for their seats; an + * estimate. Changes nothing. + */ + readonly crewArchiveWorktrees: ( + crewInstanceIds: ReadonlyArray, + ) => Effect.Effect< + ReadonlyArray, + Read["error"] + >; } export class ClientReadsService extends Context.Service()( @@ -277,6 +292,7 @@ export const layer: Layer.Layer< | PlaybookStore | A2AArchiveFacts | ArchiveCrewService + | CrewWorktrees > = Layer.effect( ClientReadsService, Effect.gen(function* () { @@ -386,6 +402,7 @@ export const layer: Layer.Layer< spawnedChildren: yield* makeSpawnedChildrenRead, fleet: yield* makeFleetRead, preArchiveFacts: yield* makePreArchiveFactsRead, + crewArchiveWorktrees: yield* makeCrewArchiveWorktreesRead, }); }), ); diff --git a/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.test.ts b/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.test.ts index b461fdad68392..ad26205c88d35 100644 --- a/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.test.ts +++ b/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.test.ts @@ -77,7 +77,7 @@ it.effect("retires the live Crews a Captain commanded when the person archives i Layer.mock(ArchiveCrewService)({ archive: (input) => Ref.update(calls, (items) => [...items, input]).pipe( - Effect.as({ status: "archived" as const, members: [] }), + Effect.as({ status: "archived" as const, members: [], worktrees: [] }), ), }), noThreads, @@ -142,7 +142,7 @@ it.effect( Effect.flatMap(() => input.crewInstanceId === "crew:archived-captain" ? Effect.die(new Error("a seat refused to archive")) - : Effect.succeed({ status: "archived" as const, members: [] }), + : Effect.succeed({ status: "archived" as const, members: [], worktrees: [] }), ), ), }), @@ -188,7 +188,7 @@ it.effect("a Crew whose retirement fails is tried once, and the next Crew still calls.push(input); return input.crewInstanceId === "crew:broken" ? Effect.die("archive failure") - : Effect.succeed({ status: "archived" as const, members: [] }); + : Effect.succeed({ status: "archived" as const, members: [], worktrees: [] }); }), }), noThreads, @@ -470,7 +470,7 @@ it.effect("a Captain archived again after an unarchive retires its Crew again", seen.add(commandId); yield* Ref.set(seatArchived, true); yield* Ref.set(retiredAt, input.archivedAt); - return { status: "archived" as const, members: [] }; + return { status: "archived" as const, members: [], worktrees: [] }; }), }), Layer.mock(ThreadManagementService)({ diff --git a/apps/server/src/j5/a2a/CrewLaunchService.test.ts b/apps/server/src/j5/a2a/CrewLaunchService.test.ts index 2aa6f5cebb55f..021896ba7d0a5 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.test.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.test.ts @@ -48,6 +48,7 @@ import { import { ArchiveAgentService } from "./ArchiveAgentService.ts"; import { playbookStoreLayer } from "../playbooks/PlaybookStore.ts"; import { ArchiveCrewService, layer as archiveCrewLayer } from "./ArchiveCrewService.ts"; +import { CrewWorktrees } from "./CrewWorktrees.ts"; import { crewApprovalToken, describeCrewSeatRuntime } from "./crewRuntimePreview.ts"; import { CrewLaunchOperationError, @@ -1412,6 +1413,13 @@ const unitFixture = Effect.gen(function* () { archiveCrewLayer.pipe( Layer.provide(archiveAgent), Layer.provide(playbookStoreLayer), + Layer.provide( + Layer.mock(CrewWorktrees)({ + cleanup: () => Effect.succeed([]), + liveSessions: () => Effect.succeed([]), + closeSessions: () => Effect.void, + }), + ), Layer.provide( Layer.mock(ServerSecretStore)({ getOrCreateRandom: () => Effect.succeed(new Uint8Array(32).fill(7)), diff --git a/apps/server/src/j5/a2a/CrewSeatPreparation.ts b/apps/server/src/j5/a2a/CrewSeatPreparation.ts index ff481cf75224a..3d604ab8c49ef 100644 --- a/apps/server/src/j5/a2a/CrewSeatPreparation.ts +++ b/apps/server/src/j5/a2a/CrewSeatPreparation.ts @@ -8,6 +8,20 @@ import { ThreadManagementService } from "../../orchestration-v2/ThreadManagement import { ThreadLaunchService } from "../../orchestration-v2/ThreadLaunchService.ts"; import { readEventStoreHighWater } from "./eventStoreHighWater.ts"; +const PREPARE_COMMAND_PREFIX = "command:j5:crew-seat-prepare:"; + +const prepareCommandId = (runId: RunId) => CommandId.make(`${PREPARE_COMMAND_PREFIX}${runId}`); + +/** + * Whether a stored event is the metadata update ThreadLaunch commits (as `:workspace`) + * when this module's preparation creates a seat's worktree. A worktree bound any other way, by a + * handoff or a metadata update, never carries this command. + */ +export const isSeatWorktreeCreation = (commandId: CommandId | null) => + commandId !== null && + commandId.startsWith(PREPARE_COMMAND_PREFIX) && + commandId.endsWith(":workspace"); + /** A waiting seat's first assignment uses upstream's durable worktree preparation path. */ export const layer = Layer.effectDiscard( Effect.gen(function* () { @@ -24,7 +38,7 @@ export const layer = Layer.effectDiscard( yield* launcher.prepareRun({ threadId: run.threadId, runId: run.id, - commandId: CommandId.make(`command:j5:crew-seat-prepare:${run.id}`), + commandId: prepareCommandId(run.id), }); }); const afterSequence = yield* readEventStoreHighWater("J5 crew seat preparation"); diff --git a/apps/server/src/j5/a2a/CrewWorktrees.integration.test.ts b/apps/server/src/j5/a2a/CrewWorktrees.integration.test.ts new file mode 100644 index 0000000000000..16fc90a35a341 --- /dev/null +++ b/apps/server/src/j5/a2a/CrewWorktrees.integration.test.ts @@ -0,0 +1,150 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { CommandId, MessageId, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { GitManager } from "../../git/GitManager.ts"; +import { layer as projectionStoreLayer } from "../../orchestration-v2/ProjectionStore.ts"; +import { ProviderSessionManagerV2 } from "../../orchestration-v2/ProviderSessionManager.ts"; +import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; +import { GitVcsDriver } from "../../vcs/GitVcsDriver.ts"; +import { makeHarness, modelSelection, projectId } from "../test-support/threadLaunchHarness.ts"; +import * as Crews from "./AgentCrewInstanceService.ts"; +import * as Preparation from "./CrewSeatPreparation.ts"; +import { CrewWorktrees, manualLayer } from "./CrewWorktrees.ts"; +import { LedgerProjectId } from "./contracts.ts"; +import { A2ALedger, layer as ledgerLayer } from "./LedgerService.ts"; +import { participantIdForThread } from "./HomeRegistrar.ts"; + +it.effect( + "records the worktree upstream's launch creates for a seat's first assignment, from the event it commits", + () => + Effect.gen(function* () { + const harness = makeHarness({ + crewDeliveryContext: true, + createWorktree: (input) => + Effect.succeed({ + worktree: { + path: "/repo-worktrees/crew-builder", + refName: input.newRefName, + headSha: "abc", + }, + } as never), + }); + const services = Layer.mergeAll( + harness.layer, + Crews.layer.pipe(Layer.provide(harness.layer)), + ledgerLayer.pipe(Layer.provide(harness.layer)), + ); + const base = Preparation.layer.pipe( + Layer.provideMerge(services), + Layer.provideMerge(harness.orchestrator), + ); + const layer = manualLayer.pipe( + Layer.provide( + Layer.mergeAll( + harness.services, + projectionStoreLayer.pipe(Layer.provide(harness.layer)), + Layer.mock(ProviderSessionManagerV2)({}), + Layer.mock(GitVcsDriver)({}), + Layer.mock(GitManager)({}), + NodeServices.layer, + ), + ), + Layer.provideMerge(base), + ); + yield* Effect.gen(function* () { + const threads = yield* ThreadManagementService; + const crews = yield* Crews.AgentCrewInstanceService; + const worktrees = yield* CrewWorktrees; + const sql = yield* SqlClient.SqlClient; + const threadId = ThreadId.make("thread:crew-builder"); + const captainThreadId = ThreadId.make("thread:captain"); + const ledgerProjectId = LedgerProjectId.make(projectId); + yield* (yield* A2ALedger).ensureProject({ + projectId: ledgerProjectId, + createdAt: "2026-10-27T12:00:00Z", + }); + yield* crews.record({ + id: "crew:worktrees", + projectId: ledgerProjectId, + captainThreadId, + captainParticipantId: participantIdForThread(captainThreadId), + displayName: "Build", + brief: "Shared goal", + createdAt: "2026-10-27T12:00:00Z", + members: [ + { + seatName: "builder", + agentId: null, + threadId, + participantId: participantIdForThread(threadId), + reason: "Build the fix", + }, + ], + }); + yield* sql`INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace) + VALUES (${threadId}, '', '{"type":"worktree","baseRef":"main"}')`; + yield* threads.dispatch({ + type: "thread.create", + commandId: CommandId.make("command:create-builder"), + threadId, + projectId, + title: "Builder", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "agent", + creationSource: "mcp", + branch: null, + worktreePath: null, + }); + // Created unbound: nothing is recorded until a worktree exists. + assert.lengthOf(yield* sql`SELECT * FROM j5_crew_worktree`, 0); + yield* threads.sendToThread({ + projectId, + threadId, + commandId: CommandId.make("command:first-assignment"), + messageId: MessageId.make("message:first-assignment"), + text: "Build it now.", + attachments: [], + mode: "auto", + createdBy: "user", + creationSource: "web", + }); + // The event upstream's launch commits when it binds the new worktree is the record's input. + const bound = yield* threads.streamStoredEventsFrom({ afterSequence: 0 }).pipe( + Stream.filter( + (stored) => + stored.event.type === "thread.metadata-updated" && + stored.event.threadId === threadId && + stored.event.payload.worktreePath !== null, + ), + Stream.take(1), + Stream.runCollect, + ); + assert.deepStrictEqual( + yield* Effect.forEach(bound, (stored) => worktrees.handleStoredEvent(stored)), + [true], + ); + const [row] = yield* sql<{ + readonly thread_id: string; + readonly project_id: string; + readonly path: string; + readonly branch: string | null; + }>`SELECT thread_id, project_id, path, branch FROM j5_crew_worktree`; + assert.equal(row?.thread_id, threadId); + assert.equal(row?.project_id, projectId); + assert.equal(row?.path, "/repo-worktrees/crew-builder"); + assert.isString(row?.branch); + // Later metadata updates for the same thread (the branch rename) leave the record alone. + const projection = yield* threads.getThreadProjection(threadId); + assert.equal(projection.thread.worktreePath, "/repo-worktrees/crew-builder"); + const [again] = bound; + assert.isFalse(yield* worktrees.handleStoredEvent(again!)); + }).pipe(Effect.provide(layer)); + }), +); diff --git a/apps/server/src/j5/a2a/CrewWorktrees.test.ts b/apps/server/src/j5/a2a/CrewWorktrees.test.ts new file mode 100644 index 0000000000000..ccd0842967abc --- /dev/null +++ b/apps/server/src/j5/a2a/CrewWorktrees.test.ts @@ -0,0 +1,941 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { + CheckpointScopeId, + CommandId, + EventId, + MessageId, + NodeId, + ProjectId, + ProviderSessionId, + ProviderThreadId, + RunAttemptId, + RunId, + ThreadId, + type OrchestrationV2StoredEvent, + type OrchestrationV2ThreadProjection, + type TerminalSummary, +} from "@t3tools/contracts"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as DateTime from "effect/DateTime"; +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 SqlClient from "effect/sql/SqlClient"; + +import * as ServerConfig from "../../config.ts"; +import { CodexProviderCapabilitiesV2 } from "../../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import { GitManager } from "../../git/GitManager.ts"; +import { GitWorkflowService } from "../../git/GitWorkflowService.ts"; +import { + ProjectionStoreReadError, + ProjectionStoreV2, +} from "../../orchestration-v2/ProjectionStore.ts"; +import * as ContextHandoffService from "../../orchestration-v2/ContextHandoffService.ts"; +import * as EventSink from "../../orchestration-v2/EventSink.ts"; +import { EventSinkV2 } from "../../orchestration-v2/EventSink.ts"; +import * as RunExecutionService from "../../orchestration-v2/RunExecutionService.ts"; +import * as RuntimePolicy from "../../orchestration-v2/RuntimePolicy.ts"; +import * as ProviderAuthService from "../../provider/ProviderAuthService.ts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as ProviderSessionManager from "../../orchestration-v2/ProviderSessionManager.ts"; +import * as ProviderTurnStart from "../../orchestration-v2/ProviderTurnStartService.ts"; +import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; +import { runMigrations } from "../../persistence/Migrations.ts"; +import * as ServerSettings from "../../serverSettings.ts"; +import { ProjectService } from "../../project/ProjectService.ts"; +import * as TerminalManager from "../../terminal/Manager.ts"; +import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts"; +import { CrewWorktrees, manualLayer } from "./CrewWorktrees.ts"; +import { runJ5A2AMigrations } from "./Migrations.ts"; + +const projectId = ProjectId.make("project:crew-worktrees"); + +const gitLayer = GitVcsDriver.layer.pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "crew-worktrees-" })), + Layer.provideMerge(NodeServices.layer), +); + +interface SeatThread { + archivedAt: DateTime.Utc | null; + branch: string | null; +} + +/** + * A real repository with a real default branch fetched from a real remote, real worktrees, and + * the real git driver. Only what J5 reads from elsewhere is given: the threads, the other threads + * bound to a path, the registered projects, the open terminals and provider sessions, and what + * the host says about pull requests. + */ +const fixture = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const git = yield* GitVcsDriver.GitVcsDriver; + const sql = yield* SqlClient.SqlClient; + yield* runMigrations(); + yield* runJ5A2AMigrations(); + + const root = yield* fs.makeTempDirectoryScoped({ prefix: "crew-worktrees-" }); + const repo = path.join(root, "repo"); + const origin = path.join(root, "origin.git"); + // Two folders below the worktrees directory, where upstream's repair treats a path as managed. + const worktreesDir = path.join(root, "worktrees"); + yield* fs.makeDirectory(path.join(worktreesDir, "repo"), { recursive: true }); + const run = (cwd: string, args: ReadonlyArray) => + git.execute({ operation: "crew-worktrees-test", cwd, args }); + yield* fs.makeDirectory(repo); + yield* run(repo, ["init", "-b", "main"]); + yield* run(repo, ["config", "user.email", "crew@example.test"]); + yield* run(repo, ["config", "user.name", "Crew test"]); + yield* fs.writeFileString(path.join(repo, "tracked.txt"), "original\n"); + yield* fs.writeFileString(path.join(repo, ".gitignore"), ".env\n"); + yield* run(repo, ["add", "."]); + yield* run(repo, ["commit", "-m", "initial"]); + yield* run(root, ["clone", "--bare", repo, origin]); + yield* run(repo, ["remote", "add", "origin", origin]); + yield* run(repo, ["fetch", "origin"]); + yield* run(repo, ["remote", "set-head", "origin", "main"]); + + const threads = new Map(); + let otherBoundPaths: Array<{ threadId: ThreadId; worktreePath: string }> = []; + let sessionLive = true; + let closeFails = false; + const sessionCalls: Array = []; + let otherProjectRoots: Array = []; + let openTerminals: Array> = []; + let pullRequest: unknown = null; + let pullRequestFails = false; + const pullRequestLookups: Array = []; + const invalidated: Array = []; + + const layer = manualLayer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(SqlClient.SqlClient, sql), + Layer.mock(ThreadManagementService)({ + getThreadRecords: ((threadId: ThreadId) => { + const seat = threads.get(threadId); + return seat === undefined + ? Effect.die(`unknown thread ${threadId}`) + : Effect.succeed({ thread: { id: threadId, projectId, ...seat } }); + }) as never, + }), + Layer.mock(ProjectService)({ + getById: () => Effect.succeedSome({ workspaceRoot: repo } as never), + listShells: () => + Effect.succeed( + [repo, ...otherProjectRoots].map((workspaceRoot) => ({ workspaceRoot }) as never), + ), + }), + Layer.mock(TerminalManager.TerminalManager)({ + subscribeMetadata: (listener) => + listener({ + type: "snapshot", + terminals: openTerminals.map((terminal) => ({ ...terminal }) as TerminalSummary), + }).pipe(Effect.as(() => {})), + }), + Layer.mock(ProjectionStoreV2)({ + getThreadWorktreePaths: () => + Effect.succeed([ + // Archived seats are not here: the store lists only unarchived threads. + ...[...threads].flatMap(([threadId, seat]) => + seat.archivedAt === null && bound.has(threadId) + ? [{ threadId, worktreePath: bound.get(threadId)! }] + : [], + ), + ...otherBoundPaths, + ]), + }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ + isLive: () => Effect.succeed(sessionLive), + // A detach alone leaves the session open, as it does for a session shared across threads. + detach: ({ providerSessionId, threadId }) => + Effect.sync(() => void sessionCalls.push(`detach:${providerSessionId}:${threadId}`)), + close: (providerSessionId) => + Effect.suspend(() => { + sessionCalls.push(`close:${providerSessionId}`); + if (closeFails) return Effect.die("the runtime would not stop"); + sessionLive = false; + return Effect.void; + }), + }), + // Only the daemon reads the event store, and this is the layer without it. + Layer.mock(EventSinkV2)({}), + Layer.succeed(GitVcsDriver.GitVcsDriver, git), + Layer.mock(GitManager)({ + branchPullRequest: ({ branch }) => { + pullRequestLookups.push(branch); + return pullRequestFails + ? Effect.die("the host is unreachable") + : Effect.succeed(pullRequest as never); + }, + invalidateStatus: (cwd) => Effect.sync(() => void invalidated.push(cwd)), + }), + ), + ), + ); + const bound = new Map(); + const service = yield* Effect.service(CrewWorktrees).pipe(Effect.provide(layer)); + + let eventSequence = 0; + // The command upstream's launch gives the update when the seat's own preparation creates the worktree. + const preparationCommand = CommandId.make("command:j5:crew-seat-prepare:run:one:workspace"); + const metadataUpdated = ( + threadId: ThreadId, + branch: string | null, + worktreePath: string, + commandId: CommandId | null = preparationCommand, + ) => + ({ + sequence: ++eventSequence, + commandId, + event: { + id: EventId.make(`event:crew-worktrees:${eventSequence}`), + threadId, + type: "thread.metadata-updated", + occurredAt: DateTime.makeUnsafe("2026-10-27T12:00:00.000Z"), + payload: { id: threadId, projectId, branch, worktreePath }, + }, + }) as unknown as OrchestrationV2StoredEvent; + + /** + * A seat on a new worktree as ThreadLaunch leaves it: the worktree on a branch, the thread + * bound to it, and the record the metadata update writes. `record: false` is a worktree from + * before the record existed. + */ + const seat = Effect.fn("test.seat")(function* ( + name: string, + options: { + readonly record?: boolean; + readonly workspace?: string; + readonly archived?: boolean; + } = {}, + ) { + const threadId = ThreadId.make(`thread:crew-worktrees:${name}`); + const worktree = path.join(worktreesDir, "repo", name); + const branch = `j5/${name}`; + yield* run(repo, ["worktree", "add", "-b", branch, worktree]); + threads.set(threadId, { + archivedAt: + options.archived === false ? null : DateTime.makeUnsafe("2026-10-27T13:00:00.000Z"), + branch, + }); + bound.set(threadId, worktree); + yield* sql` + INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace) + VALUES (${threadId}, '', ${options.workspace ?? '{"type":"worktree","baseRef":"main"}'}) + `; + if (options.record !== false) + yield* service.handleStoredEvent(metadataUpdated(threadId, branch, worktree)); + return { name, threadId, worktree, branch, seatName: name }; + }); + + const setSession = (cwd: string | null, live = true) => { + sessionLive = live; + return sql`DELETE FROM orchestration_v2_projection_provider_sessions`.pipe( + Effect.andThen( + cwd === null + ? Effect.void + : sql` + INSERT INTO orchestration_v2_projection_provider_sessions + (provider_session_id, thread_id, provider, status, updated_at, payload_json) + VALUES ('session:one', NULL, 'codex', 'ready', '2026-10-27T12:00:00.000Z', ${JSON.stringify( + { + id: "session:one", + driver: "codex", + providerInstanceId: "codex", + status: "ready", + cwd, + model: null, + capabilities: CodexProviderCapabilitiesV2, + createdAt: "2026-10-27T12:00:00.000Z", + updatedAt: "2026-10-27T12:00:00.000Z", + lastError: null, + }, + )}) + `, + ), + ); + }; + + return { + fs, + path, + git, + sql, + repo, + origin, + root, + worktreesDir, + layer, + service, + run, + seat, + threads, + metadataUpdated, + invalidated, + pullRequestLookups, + bound, + setProjectRoots: (roots: typeof otherProjectRoots) => (otherProjectRoots = roots), + setTerminals: (terminals: typeof openTerminals) => (openTerminals = terminals), + setOtherBoundPaths: (paths: typeof otherBoundPaths) => (otherBoundPaths = paths), + sessionCalls, + failClose: () => { + closeFails = true; + }, + /** A live session open in `cwd`, attached to each of these threads. */ + attachSession: Effect.fn("test.attachSession")(function* ( + cwd: string, + threadIds: ReadonlyArray, + ) { + yield* setSession(cwd); + yield* sql`DELETE FROM orchestration_v2_projection_provider_session_bindings`; + for (const threadId of threadIds) + yield* sql` + INSERT INTO orchestration_v2_projection_provider_session_bindings + (provider_session_id, thread_id) + VALUES ('session:one', ${threadId}) + `; + }), + /** What committing a thread's archive does to its binding. */ + detachBinding: (threadId: ThreadId) => + sql` + DELETE FROM orchestration_v2_projection_provider_session_bindings + WHERE thread_id = ${threadId} + `, + setSession, + setPullRequest: (next: unknown) => { + pullRequest = next; + }, + failPullRequest: () => { + pullRequestFails = true; + }, + }; +}); + +const run = ( + effect: Effect.Effect< + A, + E, + | FileSystem.FileSystem + | Path.Path + | GitVcsDriver.GitVcsDriver + | SqlClient.SqlClient + | import("effect/Scope").Scope + >, +) => + effect.pipe( + Effect.provide(Layer.mergeAll(gitLayer, NodeSqliteClient.layer({ filename: ":memory:" }))), + Effect.scoped, + ); + +const cleanup = ( + f: Effect.Success, + seats: ReadonlyArray<{ readonly seatName: string; readonly threadId: ThreadId }>, +) => f.service.cleanup({ seats }); + +it.effect( + "removes a clean worktree whose work reached the default branch and keeps its branch", + () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const merged = yield* f.seat("merged"); + const result = yield* cleanup(f, [merged]); + assert.deepStrictEqual(result, [ + { path: merged.worktree, branch: merged.branch, outcome: "removed", reason: null }, + ]); + assert.isFalse(yield* f.fs.exists(merged.worktree)); + // The branch stays, and so does the row, so the seat can come back and be archived again. + yield* f.run(f.repo, ["rev-parse", "--verify", `refs/heads/${merged.branch}`]); + assert.lengthOf(yield* f.sql`SELECT * FROM j5_crew_worktree`, 1); + assert.deepStrictEqual(f.invalidated, [f.repo]); + }), + ), +); + +it.effect( + "keeps a worktree with uncommitted changes, tracked or untracked, but not ignored ones", + () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const edited = yield* f.seat("edited"); + const untracked = yield* f.seat("untracked"); + const ignored = yield* f.seat("ignored"); + yield* f.fs.writeFileString(f.path.join(edited.worktree, "tracked.txt"), "edited\n"); + yield* f.fs.writeFileString(f.path.join(untracked.worktree, "new.txt"), "new\n"); + yield* f.fs.writeFileString(f.path.join(ignored.worktree, ".env"), "SECRET=1\n"); + const result = yield* cleanup(f, [edited, untracked, ignored]); + assert.deepStrictEqual( + result.map((entry) => [entry.outcome, entry.reason]), + [ + ["kept", "uncommitted_changes"], + ["kept", "uncommitted_changes"], + ["removed", null], + ], + ); + assert.isTrue(yield* f.fs.exists(edited.worktree)); + assert.isTrue(yield* f.fs.exists(untracked.worktree)); + assert.isFalse(yield* f.fs.exists(ignored.worktree)); + }), + ), +); + +it.effect("keeps a worktree with committed work the default branch does not have", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const ahead = yield* f.seat("ahead"); + yield* f.fs.writeFileString(f.path.join(ahead.worktree, "tracked.txt"), "committed\n"); + yield* f.run(ahead.worktree, ["commit", "-am", "work"]); + const result = yield* cleanup(f, [ahead]); + assert.deepStrictEqual( + result.map((entry) => [entry.outcome, entry.reason]), + [["kept", "unmerged_commits"]], + ); + assert.isTrue(yield* f.fs.exists(ahead.worktree)); + }), + ), +); + +it.effect( + "removes a squash-merged worktree when a merged pull request names its exact commit", + () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const squashed = yield* f.seat("squashed"); + yield* f.fs.writeFileString(f.path.join(squashed.worktree, "tracked.txt"), "squashed\n"); + yield* f.run(squashed.worktree, ["commit", "-am", "work"]); + // The seat renamed its branch after the worktree was created; the pull request is under + // the name the thread has now. + yield* f.run(squashed.worktree, ["branch", "-m", "j5/squashed", "feature/squashed"]); + f.threads.get(squashed.threadId)!.branch = "feature/squashed"; + const head = (yield* f.run(squashed.worktree, ["rev-parse", "HEAD"])).stdout.trim(); + f.setPullRequest({ + state: "merged", + headRef: "feature/squashed", + baseRef: "main", + headSha: head, + }); + const result = yield* cleanup(f, [squashed]); + assert.deepStrictEqual(result, [ + { path: squashed.worktree, branch: "feature/squashed", outcome: "removed", reason: null }, + ]); + assert.deepStrictEqual(f.pullRequestLookups, ["feature/squashed"]); + assert.isFalse(yield* f.fs.exists(squashed.worktree)); + }), + ), +); + +it.effect("keeps a worktree whose pull request merged a different commit", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const later = yield* f.seat("later"); + yield* f.fs.writeFileString(f.path.join(later.worktree, "tracked.txt"), "one\n"); + yield* f.run(later.worktree, ["commit", "-am", "merged part"]); + const merged = (yield* f.run(later.worktree, ["rev-parse", "HEAD"])).stdout.trim(); + yield* f.fs.writeFileString(f.path.join(later.worktree, "tracked.txt"), "two\n"); + yield* f.run(later.worktree, ["commit", "-am", "after the merge"]); + f.setPullRequest({ + state: "merged", + headRef: later.branch, + baseRef: "main", + headSha: merged, + }); + const result = yield* cleanup(f, [later]); + assert.deepStrictEqual( + result.map((entry) => [entry.outcome, entry.reason]), + [["kept", "unmerged_commits"]], + ); + }), + ), +); + +it.effect("keeps a worktree another unarchived thread is bound to", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const shared = yield* f.seat("shared"); + const alone = yield* f.seat("alone"); + f.setOtherBoundPaths([ + { threadId: ThreadId.make("thread:crew-worktrees:other"), worktreePath: shared.worktree }, + ]); + const result = yield* cleanup(f, [shared, alone]); + assert.deepStrictEqual( + result.map((entry) => [entry.outcome, entry.reason]), + [ + ["kept", "shared"], + ["removed", null], + ], + ); + assert.isTrue(yield* f.fs.exists(shared.worktree)); + }), + ), +); + +it.effect("keeps a worktree a seat was unarchived into after the archive committed", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const archived = yield* f.seat("archived"); + const returned = yield* f.seat("returned", { archived: false }); + f.bound.set(returned.threadId, archived.worktree); + const result = yield* cleanup(f, [archived, returned]); + assert.deepStrictEqual( + result.map((entry) => [entry.outcome, entry.reason]), + [["kept", "shared"]], + ); + assert.isTrue(yield* f.fs.exists(archived.worktree)); + }), + ), +); + +it.effect("keeps a worktree that is a project's root, or holds one", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const opened = yield* f.seat("opened"); + const holder = yield* f.seat("holder"); + const free = yield* f.seat("free"); + f.setProjectRoots([opened.worktree, f.path.join(holder.worktree, "packages", "app")]); + const result = yield* cleanup(f, [opened, holder, free]); + assert.deepStrictEqual( + result.map((entry) => [entry.outcome, entry.reason]), + [ + ["kept", "shared"], + ["kept", "shared"], + ["removed", null], + ], + ); + assert.isTrue(yield* f.fs.exists(opened.worktree)); + assert.isTrue(yield* f.fs.exists(holder.worktree)); + assert.isFalse(yield* f.fs.exists(free.worktree)); + }), + ), +); + +it.effect("keeps a worktree a terminal is open in, but not one that has exited", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const bound = yield* f.seat("bound-terminal"); + const nested = yield* f.seat("nested-terminal"); + const exited = yield* f.seat("exited-terminal"); + const elsewhere = yield* f.seat("elsewhere-terminal"); + f.setTerminals([ + { cwd: f.root, worktreePath: bound.worktree, status: "running" }, + { cwd: f.path.join(nested.worktree, "packages"), worktreePath: null, status: "starting" }, + { cwd: exited.worktree, worktreePath: exited.worktree, status: "exited" }, + { cwd: f.root, worktreePath: null, status: "running" }, + ]); + const result = yield* cleanup(f, [bound, nested, exited, elsewhere]); + assert.deepStrictEqual( + result.map((entry) => [entry.outcome, entry.reason]), + [ + ["kept", "in_use"], + ["kept", "in_use"], + ["removed", null], + ["removed", null], + ], + ); + }), + ), +); + +it.effect( + "closes a seat's session when the Crew archives, so its clean, merged worktree goes", + () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const working = yield* f.seat("working"); + const idle = yield* f.seat("idle-seat"); + yield* f.attachSession(working.worktree, [working.threadId]); + // Read before the archive commits, which is what removes the binding naming it. + assert.deepStrictEqual(yield* f.service.liveSessions([working, idle]), [ + { threadId: working.threadId, providerSessionId: ProviderSessionId.make("session:one") }, + ]); + const sessions = yield* f.service.liveSessions([working, idle]); + yield* f.detachBinding(working.threadId); + yield* f.service.closeSessions(sessions); + assert.deepStrictEqual(f.sessionCalls, [ + `detach:session:one:${working.threadId}`, + "close:session:one", + ]); + assert.deepStrictEqual( + (yield* cleanup(f, [working])).map((entry) => [entry.outcome, entry.reason]), + [["removed", null]], + ); + assert.isFalse(yield* f.fs.exists(working.worktree)); + }), + ), +); + +it.effect("lets a seat's session go but leaves one another thread is attached to open", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const archived = yield* f.seat("archived-seat"); + const other = ThreadId.make("thread:crew-worktrees:other-thread"); + yield* f.attachSession(archived.worktree, [archived.threadId, other]); + const sessions = yield* f.service.liveSessions([archived]); + yield* f.detachBinding(archived.threadId); + yield* f.service.closeSessions(sessions); + assert.deepStrictEqual(f.sessionCalls, [`detach:session:one:${archived.threadId}`]); + assert.deepStrictEqual( + (yield* cleanup(f, [archived])).map((entry) => [entry.outcome, entry.reason]), + [["kept", "in_use"]], + ); + }), + ), +); + +it.effect("a session that will not close keeps the worktree as in use and fails nothing", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const stuck = yield* f.seat("stuck"); + yield* f.attachSession(stuck.worktree, [stuck.threadId]); + f.failClose(); + const sessions = yield* f.service.liveSessions([stuck]); + yield* f.detachBinding(stuck.threadId); + yield* f.service.closeSessions(sessions); + assert.include(f.sessionCalls, "close:session:one"); + assert.deepStrictEqual( + (yield* cleanup(f, [stuck])).map((entry) => [entry.outcome, entry.reason]), + [["kept", "in_use"]], + ); + assert.isTrue(yield* f.fs.exists(stuck.worktree)); + }), + ), +); + +it.effect("keeps a worktree a live provider session is open in, or in a folder of it", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const busy = yield* f.seat("busy"); + const nested = yield* f.seat("nested"); + const idle = yield* f.seat("idle"); + yield* f.setSession(busy.worktree); + assert.deepStrictEqual( + (yield* cleanup(f, [busy])).map((entry) => [entry.outcome, entry.reason]), + [["kept", "in_use"]], + ); + yield* f.fs.makeDirectory(f.path.join(nested.worktree, "packages")); + yield* f.setSession(f.path.join(nested.worktree, "packages")); + assert.deepStrictEqual( + (yield* cleanup(f, [nested])).map((entry) => [entry.outcome, entry.reason]), + [["kept", "in_use"]], + ); + // A stored session whose runtime was released holds nothing. + yield* f.setSession(idle.worktree, false); + assert.deepStrictEqual( + (yield* cleanup(f, [idle])).map((entry) => [entry.outcome, entry.reason]), + [["removed", null]], + ); + assert.isTrue(yield* f.fs.exists(busy.worktree)); + }), + ), +); + +it.effect("never removes a worktree from before the record existed", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const old = yield* f.seat("old", { record: false }); + assert.deepStrictEqual(yield* cleanup(f, [old]), []); + assert.isTrue(yield* f.fs.exists(old.worktree)); + }), + ), +); + +it.effect("reports a removal git refuses, and leaves the worktree as it was", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const locked = yield* f.seat("locked"); + yield* f.run(f.repo, ["worktree", "lock", locked.worktree]); + const result = yield* cleanup(f, [locked]); + assert.deepStrictEqual(result, [ + { path: locked.worktree, branch: locked.branch, outcome: "failed", reason: "failed" }, + ]); + assert.isTrue(yield* f.fs.exists(locked.worktree)); + }), + ), +); + +it.effect("keeps a worktree it could not check as unverified", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const unreachable = yield* f.seat("unreachable"); + const ahead = yield* f.seat("ahead"); + yield* f.fs.writeFileString(f.path.join(ahead.worktree, "tracked.txt"), "committed\n"); + yield* f.run(ahead.worktree, ["commit", "-am", "work"]); + // The default branch cannot be fetched. + yield* f.run(f.repo, ["remote", "set-url", "origin", f.path.join(f.root, "gone.git")]); + assert.deepStrictEqual( + (yield* cleanup(f, [unreachable])).map((entry) => [entry.outcome, entry.reason]), + [["kept", "unverified"]], + ); + // The host cannot say whether the pull request merged. + yield* f.run(f.repo, ["remote", "set-url", "origin", f.origin]); + f.failPullRequest(); + assert.deepStrictEqual( + (yield* cleanup(f, [ahead])).map((entry) => [entry.outcome, entry.reason]), + [["kept", "unverified"]], + ); + assert.isTrue(yield* f.fs.exists(unreachable.worktree)); + }), + ), +); + +it.effect("leaves a seat whose thread is not archived alone", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const live = yield* f.seat("live", { archived: false }); + assert.deepStrictEqual(yield* cleanup(f, [live]), []); + assert.isTrue(yield* f.fs.exists(live.worktree)); + }), + ), +); + +it.effect("estimates what the archive would do without changing anything", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const clean = yield* f.seat("clean", { archived: false }); + const dirty = yield* f.seat("dirty", { archived: false }); + yield* f.fs.writeFileString(f.path.join(dirty.worktree, "tracked.txt"), "edited\n"); + // Both seats are bound to their own worktree and are the Crew's own, so neither is shared. + const estimate = yield* f.service.estimate({ + crews: [{ crewInstanceId: "crew:one", seats: [clean, dirty] }], + }); + assert.deepStrictEqual( + estimate.map((entry) => [entry.seat, entry.verdict, entry.reason, entry.crewInstanceId]), + [ + ["clean", "remove", null, "crew:one"], + ["dirty", "keep", "uncommitted_changes", "crew:one"], + ], + ); + assert.isTrue(yield* f.fs.exists(clean.worktree)); + assert.deepStrictEqual(f.invalidated, []); + }), + ), +); + +it.effect("estimates the same keeps the removal would make for a project root or a terminal", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const opened = yield* f.seat("opened", { archived: false }); + const typing = yield* f.seat("typing", { archived: false }); + f.setProjectRoots([opened.worktree]); + f.setTerminals([{ cwd: typing.worktree, worktreePath: null, status: "running" }]); + const estimate = yield* f.service.estimate({ + crews: [{ crewInstanceId: "crew:one", seats: [opened, typing] }], + }); + assert.deepStrictEqual( + estimate.map((entry) => [entry.seat, entry.verdict, entry.reason]), + [ + ["opened", "keep", "shared"], + ["typing", "keep", "in_use"], + ], + ); + }), + ), +); + +it.effect("records only the first worktree path of a seat on a new worktree", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const first = yield* f.seat("first"); + const sharedSeat = yield* f.seat("shared-seat", { + record: false, + workspace: '{"type":"shared"}', + }); + const existingSeat = yield* f.seat("existing-seat", { + record: false, + workspace: '{"type":"existing_worktree","worktreePath":"/somewhere"}', + }); + const unrelated = ThreadId.make("thread:crew-worktrees:not-a-seat"); + f.threads.set(unrelated, { archivedAt: null, branch: "main" }); + assert.isFalse( + yield* f.service.handleStoredEvent(f.metadataUpdated(sharedSeat.threadId, "main", f.repo)), + ); + assert.isFalse( + yield* f.service.handleStoredEvent( + f.metadataUpdated(existingSeat.threadId, "x", "/somewhere"), + ), + ); + assert.isFalse( + yield* f.service.handleStoredEvent(f.metadataUpdated(unrelated, "main", f.repo)), + ); + // A rename or a re-pointing later does not move the record off the checkout J5 created. + assert.isFalse( + yield* f.service.handleStoredEvent( + f.metadataUpdated(first.threadId, "renamed", "/elsewhere"), + ), + ); + assert.deepStrictEqual( + (yield* f.sql<{ readonly thread_id: string; readonly path: string }>` + SELECT thread_id, path FROM j5_crew_worktree + `).map((row) => [row.thread_id, row.path]), + [[first.threadId, first.worktree]], + ); + }), + ), +); + +it.effect("does not record a worktree a handoff or a metadata update bound to a waiting seat", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const waiting = yield* f.seat("waiting", { record: false }); + const existing = f.path.join(f.worktreesDir, "repo", "someone-elses"); + // Before its first assignment the seat is pointed at a worktree that already existed. + assert.isFalse( + yield* f.service.handleStoredEvent( + f.metadataUpdated( + waiting.threadId, + "someone-elses", + existing, + CommandId.make("command:handoff:waiting"), + ), + ), + ); + assert.isFalse( + yield* f.service.handleStoredEvent( + f.metadataUpdated(waiting.threadId, null, existing, null), + ), + ); + assert.lengthOf(yield* f.sql`SELECT * FROM j5_crew_worktree`, 0); + // The preparation's own update, arriving afterwards, is still recorded. + assert.isTrue( + yield* f.service.handleStoredEvent( + f.metadataUpdated(waiting.threadId, waiting.branch, waiting.worktree), + ), + ); + assert.deepStrictEqual( + (yield* f.sql<{ readonly path: string }>`SELECT path FROM j5_crew_worktree`).map( + (row) => row.path, + ), + [waiting.worktree], + ); + }), + ), +); + +it.effect( + "lets the thread's next turn recreate a worktree archiving removed, from its kept branch", + () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const returning = yield* f.seat("returning"); + const [removed] = yield* cleanup(f, [returning]); + assert.equal(removed?.outcome, "removed"); + assert.isFalse(yield* f.fs.exists(returning.worktree)); + + // Unarchived or forked, the thread still names the same branch and path; its next turn + // starts through upstream's own repair, which J5 does not touch. The turn stops right + // after the repair, as upstream's own test for it does. + const runId = RunId.make("run:crew-worktrees:returning"); + const rootNodeId = NodeId.make("node:crew-worktrees:returning"); + const attemptId = RunAttemptId.make("attempt:crew-worktrees:returning"); + const providerThreadId = ProviderThreadId.make("provider-thread:crew-worktrees:returning"); + const messageId = MessageId.make("message:crew-worktrees:returning"); + const scopeId = CheckpointScopeId.make("scope:crew-worktrees:returning"); + const projection = { + thread: { + id: returning.threadId, + projectId, + branch: returning.branch, + worktreePath: returning.worktree, + }, + runs: [ + { + id: runId, + status: "starting", + rootNodeId, + activeAttemptId: attemptId, + providerThreadId, + userMessageId: messageId, + ordinal: 2, + }, + ], + nodes: [{ id: rootNodeId, checkpointScopeId: scopeId }], + attempts: [{ id: attemptId }], + providerThreads: [ + { + id: providerThreadId, + providerSessionId: ProviderSessionId.make("session:crew-worktrees:returning"), + }, + ], + messages: [{ id: messageId, text: "Continue", attachments: [], role: "user" }], + checkpointScopes: [{ id: scopeId }], + contextHandoffs: [], + contextTransfers: [], + turnItems: [], + } as unknown as OrchestrationV2ThreadProjection; + const startLayer = ProviderTurnStart.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}), + Layer.mock(EventSink.EventSinkV2)({}), + IdAllocator.layer, + Layer.succeed(Path.Path, f.path), + Layer.succeed(FileSystem.FileSystem, f.fs), + Layer.mock(GitWorkflowService)({ + pruneWorktrees: (input) => f.git.pruneWorktrees(input), + listLocalBranchNames: (cwd) => f.git.listLocalBranchNames(cwd), + createWorktree: (input) => f.git.createWorktree(input), + }), + Layer.mock(ProjectService)({ + getById: () => Effect.succeedSome({ workspaceRoot: f.repo } as never), + }), + Layer.mock(ProjectionStoreV2)({ + getThreadRecords: () => Effect.succeed(projection), + getTurnStartContext: () => + Effect.succeed({ ...projection, hasConversation: true } as never), + getRuntimeRecoveryProjection: () => + Effect.fail( + new ProjectionStoreReadError({ + threadId: returning.threadId, + cause: "stop after the repair", + }), + ), + }), + Layer.mock(ServerConfig.ServerConfig)({ + worktreesDir: f.worktreesDir, + } as ServerConfig.ServerConfig["Service"]), + ServerSettings.layerTest(), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}), + Layer.mock(ProviderAuthService.ProviderAuthService)({ + tryHandlePromptCommand: () => Effect.succeed(false), + }), + Layer.mock(RunExecutionService.RunExecutionServiceV2)({}), + Layer.mock(RuntimePolicy.RuntimePolicyV2)({}), + ), + ), + ); + const stopped = yield* Effect.gen(function* () { + const starter = yield* ProviderTurnStart.ProviderTurnStartServiceV2; + return yield* starter.start({ threadId: returning.threadId, runId }).pipe(Effect.flip); + }).pipe(Effect.provide(startLayer)); + assert.equal(stopped._tag, "ProviderTurnStartError"); + assert.isTrue(yield* f.fs.exists(returning.worktree)); + assert.equal( + (yield* f.run(returning.worktree, ["rev-parse", "--abbrev-ref", "HEAD"])).stdout.trim(), + returning.branch, + ); + }), + ), +); diff --git a/apps/server/src/j5/a2a/CrewWorktrees.ts b/apps/server/src/j5/a2a/CrewWorktrees.ts new file mode 100644 index 0000000000000..a06f772184429 --- /dev/null +++ b/apps/server/src/j5/a2a/CrewWorktrees.ts @@ -0,0 +1,626 @@ +import { + OrchestrationV2ProviderSessionJson, + ProviderSessionId, + type OrchestrationV2StoredEvent, + type TerminalSummary, + type ThreadId, +} from "@t3tools/contracts"; +import { + CrewSeatWorkspace, + type CrewArchiveWorktree, + type CrewArchiveWorktreeEstimate, + type CrewWorktreeReason, +} from "@t3tools/contracts/j5"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as GitManager from "../../git/GitManager.ts"; +import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; +import * as ProviderSessionManager from "../../orchestration-v2/ProviderSessionManager.ts"; +import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; +import { ProjectService } from "../../project/ProjectService.ts"; +import { storageCleanupPullRequestMerged } from "../../storageCleanup.ts"; +import * as TerminalManager from "../../terminal/Manager.ts"; +import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts"; +import { withWorkspaceLease } from "../../workspace/workspaceLease.ts"; +import { isSeatWorktreeCreation } from "./CrewSeatPreparation.ts"; +import { readEventStoreHighWater } from "./eventStoreHighWater.ts"; + +const decodeSeatWorkspace = Schema.decodeUnknownOption(Schema.fromJsonString(CrewSeatWorkspace)); +const decodeSession = Schema.decodeUnknownEffect( + Schema.fromJsonString(OrchestrationV2ProviderSessionJson), +); + +/** A seat of a Crew being archived, with the thread whose worktree it may own. */ +export interface CrewWorktreeSeat { + readonly seatName: string; + readonly threadId: ThreadId; +} + +/** A provider session a seat's thread had attached, read before its archive removes the binding. */ +export interface CrewSeatSession { + readonly threadId: ThreadId; + readonly providerSessionId: ProviderSessionId; +} + +type KeepReason = Exclude; + +interface RecordedWorktree { + readonly threadId: ThreadId; + readonly path: string; + /** The branch as the worktree was created; the thread's current branch is read when it counts. */ + readonly createdBranch: string | null; +} + +/** What a check found at one worktree: gone, or a reason to keep it, or free to remove. */ +type Verdict = + | { readonly kind: "gone" } + | { readonly kind: "keep"; readonly reason: KeepReason } + | { readonly kind: "remove"; readonly headSha: string }; + +export interface CrewWorktreesShape { + /** + * Records the worktree ThreadLaunch creates for a Crew seat, when the event is the metadata + * update its first-assignment preparation commits. Worktrees bound any other way, a retried + * preparation's included, have no row and are never removed. Returns whether a row was written. + */ + readonly handleStoredEvent: (event: OrchestrationV2StoredEvent) => Effect.Effect; + /** + * The live provider sessions these seats' threads are attached to, read before the archive + * commits because it removes the binding that names them. Never fails: unreadable sessions are + * kept, and the cleanup reports the worktree as in use. + */ + readonly liveSessions: ( + seats: ReadonlyArray, + ) => Effect.Effect>; + /** + * Closes the sessions `liveSessions` found, after the archive commits and before the cleanup + * looks for sessions, so the cleanup need not race the archive's own detach. A session another + * thread still uses (Codex shares one) stays open. Never fails: a session that does not close + * keeps its worktree as in use. + */ + readonly closeSessions: (sessions: ReadonlyArray) => Effect.Effect; + /** + * The cleanup after a Crew's archive commits: each recorded worktree of an archived seat is + * removed when clean, merged, unshared and unused, and kept with its reason otherwise. Never + * fails: one worktree's problem is its outcome, and unreadable records leave the pass empty. + */ + readonly cleanup: (input: { + readonly seats: ReadonlyArray; + }) => Effect.Effect>; + /** + * What cleanup would do to these Crews' worktrees if it ran now, for the pre-archive warning. + * Changes nothing and fetches nothing, so it is only an estimate. Never fails. + */ + readonly estimate: (input: { + readonly crews: ReadonlyArray<{ + readonly crewInstanceId: string; + readonly seats: ReadonlyArray; + }>; + }) => Effect.Effect>; +} + +export class CrewWorktrees extends Context.Service()( + "t3/j5/a2a/CrewWorktrees", +) {} + +const makeLayer = (daemon: boolean) => + Layer.effect( + CrewWorktrees, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const threads = yield* ThreadManagementService; + const projects = yield* ProjectService; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + const git = yield* GitVcsDriver.GitVcsDriver; + const gitManager = yield* GitManager.GitManager; + const terminals = yield* TerminalManager.TerminalManager; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const isWindows = yield* HostProcess.isWindows; + + const handleStoredEvent: CrewWorktreesShape["handleStoredEvent"] = Effect.fn( + "j5.a2a.crewWorktrees.handleStoredEvent", + )( + function* (stored) { + const event = stored.event; + if (event.type !== "thread.metadata-updated" || event.payload.worktreePath === null) + return false; + // Only the worktree the seat's own first-assignment preparation creates. A seat can be + // pointed at an existing worktree before then (a handoff, a metadata update), and that + // one was never J5's to remove. + if (!isSeatWorktreeCreation(stored.commandId)) return false; + const [context] = yield* sql<{ readonly workspace: string }>` + SELECT workspace FROM j5_crew_seat_context WHERE thread_id = ${event.threadId} + `; + if (context === undefined) return false; + const workspace = decodeSeatWorkspace(context.workspace); + if (Option.isNone(workspace) || workspace.value.type !== "worktree") return false; + // The first path wins: a later update (a branch rename, a person re-pointing the + // thread) must not move the record off the checkout J5 created. + const inserted = yield* sql<{ readonly thread_id: string }>` + INSERT INTO j5_crew_worktree (thread_id, project_id, path, branch, created_at) + VALUES ( + ${event.threadId}, ${event.payload.projectId}, ${event.payload.worktreePath}, + ${event.payload.branch}, ${DateTime.formatIso(event.occurredAt)} + ) + ON CONFLICT (thread_id) DO NOTHING + RETURNING thread_id + `; + return inserted.length > 0; + }, + Effect.catchCause((cause) => + Effect.logWarning("J5 Crew worktree record skipped", { cause }).pipe(Effect.as(false)), + ), + ); + + const liveSessions: CrewWorktreesShape["liveSessions"] = Effect.fn( + "j5.a2a.crewWorktrees.liveSessions", + )( + function* (seats) { + const found: Array = []; + for (const seat of seats) { + const rows = yield* sql<{ readonly provider_session_id: string }>` + SELECT session.provider_session_id + FROM orchestration_v2_projection_provider_session_bindings AS binding + INNER JOIN orchestration_v2_projection_provider_sessions AS session + ON session.provider_session_id = binding.provider_session_id + WHERE binding.thread_id = ${seat.threadId} + AND session.status NOT IN ('stopped', 'error') + `; + for (const row of rows) + found.push({ + threadId: seat.threadId, + providerSessionId: ProviderSessionId.make(row.provider_session_id), + }); + } + return found; + }, + Effect.catchCause((cause) => + Effect.logWarning("J5 Crew seat sessions could not be read", { cause }).pipe( + Effect.as([] as ReadonlyArray), + ), + ), + ); + + const closeSessions: CrewWorktreesShape["closeSessions"] = Effect.fn( + "j5.a2a.crewWorktrees.closeSessions", + )(function* (sessions) { + for (const { threadId, providerSessionId } of sessions) { + yield* Effect.gen(function* () { + // Revokes the thread's MCP credential, which the archive's own detach does too and, + // finding the thread already detached, would then not. + yield* providerSessions.detach({ + providerSessionId, + threadId, + detail: "Thread archived.", + revokeMcpCredential: true, + }); + const [others] = yield* sql<{ readonly count: number }>` + SELECT COUNT(*) AS count FROM orchestration_v2_projection_provider_session_bindings + WHERE provider_session_id = ${providerSessionId} + `; + if (others !== undefined && others.count > 0) return; + yield* providerSessions.close(providerSessionId); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("J5 Crew seat session did not close", { + threadId, + providerSessionId, + cause, + }), + ), + ); + } + }); + + const readRecord = (threadId: ThreadId) => + sql<{ + readonly path: string; + readonly branch: string | null; + }>`SELECT path, branch FROM j5_crew_worktree WHERE thread_id = ${threadId}`.pipe( + Effect.map((rows): RecordedWorktree | null => + rows[0] === undefined + ? null + : { threadId, path: rows[0].path, createdBranch: rows[0].branch }, + ), + ); + + /** Another unarchived thread bound to this path; `own` are seats about to be archived, which only the estimate has. */ + const sharedWithOthers = (worktreePath: string, own: ReadonlySet) => + projections + .getThreadWorktreePaths() + .pipe( + Effect.map((bound) => + bound.some( + (entry) => + path.resolve(entry.worktreePath) === worktreePath && !own.has(entry.threadId), + ), + ), + ); + + const pathKey = (target: string) => { + const resolved = path.resolve(target); + return isWindows ? resolved.toLowerCase() : resolved; + }; + + /** + * Some project's root is this worktree or a folder of it. A project opened at a seat's + * worktree has threads with no worktree path, so the thread bindings cannot see it. This is + * storage cleanup's own guard, which keeps its helper private. + */ + const containsProjectRoot = Effect.fnUntraced(function* (worktreePath: string) { + const key = pathKey(worktreePath); + const within = (target: string) => { + const relative = path.relative(key, pathKey(target)); + return ( + relative === "" || + (relative !== ".." && + !relative.startsWith(`..${path.sep}`) && + !path.isAbsolute(relative)) + ); + }; + for (const project of yield* projects.listShells()) { + const root = path.resolve(project.workspaceRoot); + if (within(root)) return true; + const real = yield* fs.realPath(root).pipe(Effect.orElseSucceed(() => root)); + if (within(real)) return true; + } + return false; + }); + + /** + * A terminal still starting or running in the worktree or a folder of it. The terminal + * manager has no list call, so this takes the snapshot a subscription opens with and lets go. + */ + const terminalOpenIn = Effect.fnUntraced(function* (worktreePath: string) { + let open: ReadonlyArray = []; + const unsubscribe = yield* terminals.subscribeMetadata((event) => + Effect.sync(() => { + if (event.type === "snapshot") open = event.terminals; + }), + ); + unsubscribe(); + return open.some((terminal) => { + if (terminal.status !== "starting" && terminal.status !== "running") return false; + const cwd = path.resolve(terminal.cwd); + return ( + (terminal.worktreePath !== null && + path.resolve(terminal.worktreePath) === worktreePath) || + cwd === worktreePath || + cwd.startsWith(`${worktreePath}${path.sep}`) + ); + }); + }); + + /** A provider session still open in the worktree or a folder of it. */ + const sessionOpenIn = Effect.fnUntraced(function* (worktreePath: string) { + const rows = yield* sql<{ readonly payload_json: string }>` + SELECT payload_json FROM orchestration_v2_projection_provider_sessions + WHERE status != 'stopped' + `; + for (const row of rows) { + const session = yield* decodeSession(row.payload_json); + const cwd = path.resolve(session.cwd); + const inside = cwd === worktreePath || cwd.startsWith(`${worktreePath}${path.sep}`); + // A stored session can stay ready after its runtime was released; only a live one holds it. + if (inside && (yield* providerSessions.isLive(session.id))) return true; + } + return false; + }); + + /** Tracked changes, and untracked files git does not ignore. Ignored files never block. */ + const hasBlockingChanges = Effect.fnUntraced(function* (worktreePath: string) { + const status = yield* git.execute({ + operation: "CrewWorktrees.localChanges", + cwd: worktreePath, + args: [ + "status", + "--porcelain=v1", + "-z", + "--ignore-submodules=none", + "--untracked-files=all", + ], + maxOutputBytes: 64 * 1024, + }); + return status.stdoutTruncated || status.stdout.split("\0").some((record) => record !== ""); + }); + + /** + * Merged into the project's default branch as last fetched, or named by a merged pull + * request as exactly this commit, which is how a squash or rebase merge shows. + */ + const mergeKeepReason = Effect.fnUntraced(function* (input: { + readonly worktreePath: string; + readonly repositoryRoot: string; + readonly branch: string | null; + readonly refresh: boolean; + readonly fetched: Set; + }) { + const remote = yield* git.resolvePrimaryRemoteName(input.repositoryRoot); + const defaultBranch = yield* git.resolveDefaultBranchName(input.repositoryRoot, remote); + if (defaultBranch === null) return "unverified" as const; + const fetchKey = `${input.repositoryRoot}\0${remote}\0${defaultBranch}`; + if (input.refresh && !input.fetched.has(fetchKey)) { + yield* git.fetchRemoteTrackingBranch({ + cwd: input.repositoryRoot, + remoteName: remote, + remoteBranch: defaultBranch, + }); + input.fetched.add(fetchKey); + } + const head = yield* git.resolveCommit({ cwd: input.worktreePath, revision: "HEAD" }); + const base = yield* git.resolveCommit({ + cwd: input.worktreePath, + revision: `refs/remotes/${remote}/${defaultBranch}`, + }); + const ancestor = yield* git.execute({ + operation: "CrewWorktrees.integrated", + cwd: input.worktreePath, + args: ["merge-base", "--is-ancestor", head.commitSha, base.commitSha], + allowNonZeroExit: true, + }); + if (ancestor.exitCode === 0) return null; + if (ancestor.exitCode !== 1) return "unverified" as const; + if (input.branch === null) return "unmerged_commits" as const; + const pullRequest = yield* gitManager.branchPullRequest( + { cwd: input.worktreePath, branch: input.branch }, + { refresh: input.refresh }, + ); + return storageCleanupPullRequestMerged(pullRequest, { + branch: input.branch, + defaultBranch, + headSha: head.commitSha, + integrated: false, + }) + ? null + : ("unmerged_commits" as const); + }); + + interface CheckContext { + readonly own: ReadonlySet; + readonly refresh: boolean; + readonly fetched: Set; + /** False for the look right before a removal: the first look already decided it, and the commit is compared instead. */ + readonly checkMerged: boolean; + } + + const threadFacts = (threadId: ThreadId) => + threads.getThreadRecords(threadId, []).pipe( + Effect.map(({ thread }) => thread), + Effect.result, + ); + + /** Everything that can keep a worktree, cheapest first. Throws nothing: a failed check keeps it. */ + const check = Effect.fnUntraced(function* ( + record: RecordedWorktree, + branch: string | null, + repositoryRoot: string, + context: CheckContext, + ) { + const worktreePath = path.resolve(record.path); + if (!(yield* fs.exists(worktreePath))) return { kind: "gone" } satisfies Verdict; + // A linked worktree's `.git` is a file; a directory is a whole checkout, never ours to remove. + if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File") + return { kind: "keep", reason: "unverified" } satisfies Verdict; + if ( + (yield* sharedWithOthers(worktreePath, context.own)) || + (yield* containsProjectRoot(worktreePath)) + ) + return { kind: "keep", reason: "shared" } satisfies Verdict; + if ((yield* sessionOpenIn(worktreePath)) || (yield* terminalOpenIn(worktreePath))) + return { kind: "keep", reason: "in_use" } satisfies Verdict; + if (yield* hasBlockingChanges(worktreePath)) + return { kind: "keep", reason: "uncommitted_changes" } satisfies Verdict; + const unmerged = context.checkMerged + ? yield* mergeKeepReason({ + worktreePath, + repositoryRoot, + branch, + refresh: context.refresh, + fetched: context.fetched, + }) + : null; + if (unmerged !== null) return { kind: "keep", reason: unmerged } satisfies Verdict; + const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" }); + return { kind: "remove", headSha: head.commitSha } satisfies Verdict; + }); + + const verdictOf = ( + record: RecordedWorktree, + branch: string | null, + repositoryRoot: string, + context: CheckContext, + ) => + check(record, branch, repositoryRoot, context).pipe( + Effect.catchCause((cause) => + Effect.logWarning("J5 Crew worktree check could not finish", { + threadId: record.threadId, + cause, + }).pipe(Effect.as({ kind: "keep", reason: "unverified" } satisfies Verdict)), + ), + ); + + const repositoryRootOf = (projectId: Parameters[0]) => + projects + .getById(projectId) + .pipe( + Effect.map((project) => Option.getOrNull(Option.map(project, (p) => p.workspaceRoot))), + ); + + const remove = Effect.fnUntraced(function* ( + record: RecordedWorktree, + branch: string | null, + repositoryRoot: string, + context: CheckContext, + ) { + const worktreePath = path.resolve(record.path); + // Under the workspace lease storage cleanup and a thread's own repair use, and read + // again right before the removal: a session, a second thread, an edit or a commit that + // arrived since the first look cancels it. + return yield* withWorkspaceLease( + worktreePath, + Effect.gen(function* () { + const first = yield* verdictOf(record, branch, repositoryRoot, context); + if (first.kind !== "remove") return first; + const again = yield* verdictOf(record, branch, repositoryRoot, { + ...context, + refresh: false, + checkMerged: false, + }); + if (again.kind !== "remove" || again.headSha !== first.headSha) + return again.kind === "remove" + ? ({ kind: "keep", reason: "unverified" } satisfies Verdict) + : again; + yield* git.removeWorktree({ cwd: repositoryRoot, path: worktreePath }); + yield* gitManager.invalidateStatus(repositoryRoot); + return first; + }), + ); + }); + + const cleanup: CrewWorktreesShape["cleanup"] = Effect.fn("j5.a2a.crewWorktrees.cleanup")( + function* ({ seats }) { + // No seat is exempt: a seat that was unarchived since the archive committed is bound to + // its worktree again, and that is what must keep the worktree. + const context: CheckContext = { + own: new Set(), + refresh: true, + fetched: new Set(), + checkMerged: true, + }; + const results: Array = []; + for (const seat of seats) { + const record = yield* readRecord(seat.threadId); + if (record === null) continue; + const thread = yield* threadFacts(seat.threadId); + // Only a thread that is archived has let go of its worktree. + if (thread._tag === "Failure" || thread.success.archivedAt === null) continue; + // The branch is read now: the seat may have renamed it since the worktree was created. + const branch = thread.success.branch ?? record.createdBranch; + const outcome = ( + result: Pick, + ): CrewArchiveWorktree => ({ path: record.path, branch, ...result }); + const repositoryRoot = yield* repositoryRootOf(thread.success.projectId).pipe( + Effect.orElseSucceed(() => null), + ); + if (repositoryRoot === null) { + results.push(outcome({ outcome: "kept", reason: "unverified" })); + continue; + } + const done = yield* remove(record, branch, repositoryRoot, context).pipe( + Effect.catchCause((cause) => + Effect.logWarning("J5 Crew worktree removal failed", { + threadId: seat.threadId, + cause, + }).pipe(Effect.as("failed" as const)), + ), + ); + if (done === "failed") results.push(outcome({ outcome: "failed", reason: "failed" })); + else if (done.kind === "keep") + results.push(outcome({ outcome: "kept", reason: done.reason })); + else if (done.kind === "remove") { + yield* Effect.logInfo("J5 Crew worktree removed after archive", { + threadId: seat.threadId, + }); + results.push(outcome({ outcome: "removed", reason: null })); + } + } + return results; + }, + Effect.catchCause((cause) => + Effect.logWarning("J5 Crew worktree cleanup skipped", { cause }).pipe( + Effect.as([] as ReadonlyArray), + ), + ), + ); + + const estimate: CrewWorktreesShape["estimate"] = Effect.fn("j5.a2a.crewWorktrees.estimate")( + function* ({ crews }) { + const results: Array = []; + for (const crew of crews) { + const context: CheckContext = { + own: new Set(crew.seats.map((seat) => seat.threadId)), + refresh: false, + fetched: new Set(), + checkMerged: true, + }; + for (const seat of crew.seats) { + const record = yield* readRecord(seat.threadId); + if (record === null) continue; + const thread = yield* threadFacts(seat.threadId); + if (thread._tag === "Failure") continue; + const branch = thread.success.branch ?? record.createdBranch; + const repositoryRoot = yield* repositoryRootOf(thread.success.projectId).pipe( + Effect.orElseSucceed(() => null), + ); + const verdict: Verdict = + repositoryRoot === null + ? { kind: "keep", reason: "unverified" } + : yield* verdictOf(record, branch, repositoryRoot, context); + if (verdict.kind === "gone") continue; + results.push({ + crewInstanceId: crew.crewInstanceId, + seat: seat.seatName, + path: record.path, + branch, + verdict: verdict.kind === "remove" ? "remove" : "keep", + reason: verdict.kind === "keep" ? verdict.reason : null, + }); + } + } + return results; + }, + Effect.catchCause((cause) => + Effect.logWarning("J5 Crew worktree estimate skipped", { cause }).pipe( + Effect.as([] as ReadonlyArray), + ), + ), + ); + + if (daemon) { + // From the event store's current high-water mark: a launch that finished while the server + // was down is simply not recorded, and a worktree with no row is never removed. + const runDaemon = Effect.gen(function* () { + let afterSequence = yield* readEventStoreHighWater("J5 Crew worktree recorder"); + return yield* Effect.forever( + Stream.suspend(() => threads.streamStoredEventsFrom({ afterSequence })).pipe( + Stream.runForEach((event) => + handleStoredEvent(event).pipe( + Effect.tap(() => Effect.sync(() => (afterSequence = event.sequence))), + ), + ), + Effect.catchCause((cause) => + Effect.logWarning("J5 Crew worktree recorder stream failed; resuming", { + cause, + }).pipe(Effect.andThen(Effect.sleep(Duration.seconds(1)))), + ), + ), + ); + }); + yield* Effect.forkScoped(runDaemon); + } + + return CrewWorktrees.of({ + handleStoredEvent, + liveSessions, + closeSessions, + cleanup, + estimate, + }); + }), + ); + +export const manualLayer = makeLayer(false); +export const layer = makeLayer(true); diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index 64bd7ef76f419..881c99d283f6c 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -141,6 +141,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () { migration_id: 47, name: "RequestReplay" }, { migration_id: 48, name: "CrewApprovalMode" }, { migration_id: 49, name: "CrewSeatActivation" }, + { migration_id: 50, name: "CrewWorktrees" }, ]); assert.deepStrictEqual( migrationEntries.map(([id, name]) => [id, name]), @@ -194,6 +195,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () [47, "RequestReplay"], [48, "CrewApprovalMode"], [49, "CrewSeatActivation"], + [50, "CrewWorktrees"], ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), @@ -1442,7 +1444,7 @@ it.effect("recreates earlier-shaped crews tables when 14 runs over them", () => applied.map((row) => row.migration_id), [ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, ], ); const memberColumns = yield* sql<{ readonly name: string }>` diff --git a/apps/server/src/j5/a2a/Migrations.ts b/apps/server/src/j5/a2a/Migrations.ts index aa49915559adf..47924a2438a0b 100644 --- a/apps/server/src/j5/a2a/Migrations.ts +++ b/apps/server/src/j5/a2a/Migrations.ts @@ -50,6 +50,7 @@ import Migration0046 from "./migrations/046_LocalDeliveryOrder.ts"; import Migration0047 from "./migrations/047_RequestReplay.ts"; import Migration0048 from "./migrations/048_CrewApprovalMode.ts"; import Migration0049 from "./migrations/049_CrewSeatActivation.ts"; +import Migration0050 from "./migrations/050_CrewWorktrees.ts"; export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations"; @@ -110,6 +111,7 @@ export const migrationEntries = [ [47, "RequestReplay", Migration0047], [48, "CrewApprovalMode", Migration0048], [49, "CrewSeatActivation", Migration0049], + [50, "CrewWorktrees", Migration0050], ] as const; const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/j5/a2a/clientReadRpc.test.ts b/apps/server/src/j5/a2a/clientReadRpc.test.ts index df09fa600a233..3de5c225d6599 100644 --- a/apps/server/src/j5/a2a/clientReadRpc.test.ts +++ b/apps/server/src/j5/a2a/clientReadRpc.test.ts @@ -25,6 +25,7 @@ import { PlaybookStore, playbookStoreLayer } from "../playbooks/PlaybookStore.ts import { AgentCrewInstanceService } from "./AgentCrewInstanceService.ts"; import { AgentCrewProposalService, type CrewProposal } from "./AgentCrewProposalService.ts"; import { ArchiveCrewService } from "./ArchiveCrewService.ts"; +import { CrewWorktrees } from "./CrewWorktrees.ts"; import { A2AArchiveFacts, A2AArchiveFactsError } from "./ArchiveFactsService.ts"; import { makeClientReadRpcHandlers } from "./clientReadRpc.ts"; import { ClientReadsService, layer as clientReadsLayer } from "./ClientReadsService.ts"; @@ -112,6 +113,7 @@ const handlersWith = (given: { Layer.mock(AgentCrewInstanceService)({}), Layer.mock(PlaybookCrewRelay)({}), Layer.mock(ArchiveCrewService)({}), + Layer.mock(CrewWorktrees)({}), database, ), ), diff --git a/apps/server/src/j5/a2a/clientReadRpc.ts b/apps/server/src/j5/a2a/clientReadRpc.ts index fa9d4b0417080..8f9d45b157d80 100644 --- a/apps/server/src/j5/a2a/clientReadRpc.ts +++ b/apps/server/src/j5/a2a/clientReadRpc.ts @@ -1,6 +1,7 @@ import { AuthAccessReadScope, AuthOrchestrationReadScope, ThreadId } from "@t3tools/contracts"; import { J5_CLIENT_READ_WS_METHODS, + type CrewArchiveWorktreesRequest, type FleetReadRequest, type HumanInboxListRequest, type OpenInboxCountRequest, @@ -36,6 +37,7 @@ export const CLIENT_READ_RPC_SCOPES = { [METHODS.readFleet]: AuthOrchestrationReadScope, [METHODS.listSpawnedChildren]: AuthOrchestrationReadScope, [METHODS.readPreArchiveFacts]: AuthOrchestrationReadScope, + [METHODS.readCrewArchiveWorktrees]: AuthOrchestrationReadScope, [METHODS.readParticipantIdentities]: AuthOrchestrationReadScope, [METHODS.listPeers]: AuthAccessReadScope, [METHODS.subscribeReadChanges]: AuthOrchestrationReadScope, @@ -146,6 +148,23 @@ export const makeClientReadRpcHandlers = Effect.fn("j5.makeClientReadRpcHandlers clientReads .preArchiveFacts(input.threadId) .pipe(Effect.catch(failed("Pre-archive fact lookup failed."))), + [METHODS.readCrewArchiveWorktrees]: Effect.fn("j5.a2a.clientReadRpc.readCrewArchiveWorktrees")( + function* (input: CrewArchiveWorktreesRequest) { + const listed = yield* clientReads + .crewArchiveWorktrees(input.crewInstanceIds) + .pipe(Effect.catch(failed("Crew worktree lookup failed."))); + // A worktree's path is shown to whoever reaches its Crew's Captain. + const reachesCaptain = yield* reaches; + const worktrees = yield* Effect.filter(listed, (entry) => + reachesCaptain(Effect.succeed(entry.captainThreadId)), + ); + return { + worktrees: worktrees.map( + ({ captainThreadId: _captainThreadId, ...estimate }) => estimate, + ), + }; + }, + ), [METHODS.readParticipantIdentities]: (input: ParticipantIdentitiesRequest) => clientReads .participantIdentities({ participantIds: input.participantIds.filter(isParticipantId) }) diff --git a/apps/server/src/j5/a2a/crewAccessRpc.test.ts b/apps/server/src/j5/a2a/crewAccessRpc.test.ts index 32df8d2a78eda..82e1aba81849b 100644 --- a/apps/server/src/j5/a2a/crewAccessRpc.test.ts +++ b/apps/server/src/j5/a2a/crewAccessRpc.test.ts @@ -33,13 +33,30 @@ const crewServices = Layer.mergeAll( crewRuntimeRequests: Effect.succeed({ requests: [{ threadId: SEAT, requestId: "request:seat", crewInstanceId: "crew:1" } as never], }), + crewArchiveWorktrees: (crewInstanceIds) => + Effect.succeed( + crewInstanceIds.map((crewInstanceId) => ({ + crewInstanceId, + captainThreadId: CAPTAIN, + seat: "builder", + path: "/wt/builder", + branch: "j5/builder", + verdict: "remove" as const, + reason: null, + })), + ), }), Layer.mock(ClientActionsService)({ resolveCrewProposal: () => Effect.succeed({ proposal: {} as never, crewInstanceId: null }), respondCrewRuntimeRequest: (input) => Effect.succeed({ threadId: input.threadId, requestId: input.requestId }), archiveCrew: (input) => - Effect.succeed({ crewInstanceId: input.crewInstanceId, status: "archived", members: [] }), + Effect.succeed({ + crewInstanceId: input.crewInstanceId, + status: "archived", + members: [], + worktrees: [], + }), }), Layer.mock(PeerAdminService)({}), readChangesLayer, @@ -157,3 +174,33 @@ it.effect("only an Owner archives a Crew, for now", () => assert.strictEqual(yield* archive(owner), "allowed"); }).pipe(Effect.provide(conversationLayer)), ); + +it.effect("shows a Crew's worktree paths to whoever reaches its Captain, and to no one else", () => + Effect.gen(function* () { + yield* seed; + const onCaptain = yield* connection("Cara", [ + { scope: { kind: "thread", threadId: CAPTAIN }, level: "viewer" }, + ]); + const elsewhere = yield* connection("Eli", [ + { scope: { kind: "thread", threadId: "thread:unrelated" as ThreadId }, level: "viewer" }, + ]); + const read = (session: typeof onCaptain) => + handlersFor(session).pipe( + Effect.flatMap(({ reads }) => + reads["j5.archive.readCrewWorktrees"]({ crewInstanceIds: ["crew:1"] }), + ), + ); + // The captain id the service reports is for filtering only; the client never sees it. + assert.deepStrictEqual((yield* read(onCaptain)).worktrees, [ + { + crewInstanceId: "crew:1", + seat: "builder", + path: "/wt/builder", + branch: "j5/builder", + verdict: "remove", + reason: null, + }, + ]); + assert.deepStrictEqual((yield* read(elsewhere)).worktrees, []); + }).pipe(Effect.provide(conversationLayer)), +); diff --git a/apps/server/src/j5/a2a/crewArchiveWorktreesRead.ts b/apps/server/src/j5/a2a/crewArchiveWorktreesRead.ts new file mode 100644 index 0000000000000..0139a23893608 --- /dev/null +++ b/apps/server/src/j5/a2a/crewArchiveWorktreesRead.ts @@ -0,0 +1,46 @@ +import type { CrewArchiveWorktreeEstimate } from "@t3tools/contracts/j5"; +import type { ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; + +import { AgentCrewInstanceService } from "./AgentCrewInstanceService.ts"; +import { CrewWorktrees } from "./CrewWorktrees.ts"; + +/** An estimate with the Captain's thread it belongs to, so a narrowed reader sees only their own. */ +export type CrewArchiveWorktreeRead = CrewArchiveWorktreeEstimate & { + readonly captainThreadId: ThreadId; +}; + +/** + * What archiving these live Crews would do with the worktrees J5 created for their seats, read + * for the dialog that confirms the archive: the sidebar's, when a Captain with Crews is archived, + * and Fleet's Archive crew. A Crew that is unknown or already retired has nothing to say. + * Changes nothing, and is an estimate: the archive checks again when it runs. + */ +export const makeCrewArchiveWorktreesRead = Effect.gen(function* () { + const crews = yield* AgentCrewInstanceService; + const worktrees = yield* CrewWorktrees; + return Effect.fn("j5.a2a.crewArchiveWorktrees.read")(function* ( + crewInstanceIds: ReadonlyArray, + ) { + const instances = yield* Effect.forEach([...new Set(crewInstanceIds)], (id) => crews.read(id), { + concurrency: 1, + }); + const live = instances.flatMap((instance) => + instance === null || instance.archivedAt !== null ? [] : [instance], + ); + const estimates = yield* worktrees.estimate({ + crews: live.map((instance) => ({ + crewInstanceId: instance.id, + seats: instance.members.map((member) => ({ + seatName: member.seatName, + threadId: member.threadId, + })), + })), + }); + const captainOf = new Map(live.map((instance) => [instance.id, instance.captainThreadId])); + return estimates.flatMap((estimate): Array => { + const captainThreadId = captainOf.get(estimate.crewInstanceId); + return captainThreadId === undefined ? [] : [{ ...estimate, captainThreadId }]; + }); + }); +}); diff --git a/apps/server/src/j5/a2a/mcp/handlers.test.ts b/apps/server/src/j5/a2a/mcp/handlers.test.ts index 2cf3984195fdd..25d2f28b4323c 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.test.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.test.ts @@ -2007,6 +2007,14 @@ it.effect("archives a crew only as a unit through its captain with one confirmat result: "archived" as const, }, ], + worktrees: [ + { + path: "/wt/builder", + branch: "j5/builder", + outcome: "kept" as const, + reason: "unmerged_commits" as const, + }, + ], }), ), ), @@ -2073,6 +2081,14 @@ it.effect("archives a crew only as a unit through its captain with one confirmat status: "archived", crew_instance_id: "crew:j5:test", members: [{ seat: "builder", participant_id: memberParticipantId, result: "archived" }], + worktrees: [ + { + path: "/wt/builder", + branch: "j5/builder", + outcome: "kept", + reason: "unmerged_commits", + }, + ], }); const calls = yield* Ref.get(archiveCalls); assert.lengthOf(calls, 2); diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index 9bf40ff23091f..8eec8eb7e7dc2 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -1012,6 +1012,7 @@ const handlers = { participant_id: member.participantId, result: member.result, })), + worktrees: outcome.worktrees, }; }).pipe(Effect.mapError(archiveCrewFailure)), ), diff --git a/apps/server/src/j5/a2a/mcp/orchestratorVerbs.live.test.ts b/apps/server/src/j5/a2a/mcp/orchestratorVerbs.live.test.ts index 2770ed32556f7..72e191c95214f 100644 --- a/apps/server/src/j5/a2a/mcp/orchestratorVerbs.live.test.ts +++ b/apps/server/src/j5/a2a/mcp/orchestratorVerbs.live.test.ts @@ -1,5 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { GitVcsDriver } from "../../../vcs/GitVcsDriver.ts"; +import { GitManager } from "../../../git/GitManager.ts"; +import { TerminalManager } from "../../../terminal/Manager.ts"; import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { assert, it } from "@effect/vitest"; @@ -254,6 +256,7 @@ const liveLayer = Layer.mergeAll( ), Layer.provide(mcpSessionRegistryTestLayer), Layer.provide(Layer.mock(GitVcsDriver)({})), + Layer.provide(Layer.mergeAll(Layer.mock(GitManager)({}), Layer.mock(TerminalManager)({}))), Layer.provide(SqlitePersistence.layerMemory), Layer.provide(checkpointStoreLayer), Layer.provide(serverConfigLayer), diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index 20e23b878255e..68909c9aed710 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -535,6 +535,25 @@ export const J5ArchiveCrewResult = Schema.Struct({ result: Schema.Literals(["archived", "already_archived", "never_created"]), }), ), + // The worktrees J5 created for the Crew's seats on a new worktree, and what the archive did + // with each: removed (clean and merged), kept with a reason, or a removal that failed. + worktrees: Schema.Array( + Schema.Struct({ + path: Schema.String, + branch: Schema.NullOr(Schema.String), + outcome: Schema.Literals(["removed", "kept", "failed"]), + reason: Schema.NullOr( + Schema.Literals([ + "uncommitted_changes", + "unmerged_commits", + "shared", + "in_use", + "unverified", + "failed", + ]), + ), + }), + ), }); export const J5ArchiveCrewMemberFacts = Schema.Struct({ @@ -571,7 +590,7 @@ export const J5_STOP_AGENT_DESCRIPTION = "Stop one Peer Agent the way a user Stop does: its running turn is interrupted now, turns already queued behind it, messages you sent it included, are held until a person resumes its queue or the next message reaches it (that message resumes the queue and runs after them, in order), its pull request watches end, and the tasks it delegated stop too. The agent remains, stays readable, and can be messaged again later: stopping halts work, it retires nothing. It reaches any agent on this server, in any project. Reuse client_request_id to retry safely."; const J5_ARCHIVE_CREW_DESCRIPTION = - "Retire a whole Crew you command. Crews archive only as a unit; members are never retired one by one. A clean archive completes immediately; otherwise the call refuses with the facts and a confirmation_token. Before retrying with that token, check with the user. Nothing is destroyed: worktrees, branches, and ledgers stay readable. Reuse client_request_id to retry safely."; + "Retire a whole Crew you command. Crews archive only as a unit; members are never retired one by one. A clean archive completes immediately; otherwise the call refuses with the facts and a confirmation_token. Before retrying with that token, check with the user. Archiving removes the worktrees J5 created for the Crew's seats when they are clean, committed, merged, used by no other thread or project, and have no open session or terminal, and keeps every branch and pull request. Anything else stays and is listed in the result's worktrees with its reason: uncommitted_changes, unmerged_commits, shared, in_use, unverified (a check could not run), or failed (the removal itself failed). Worktrees from before this existed, the Captain's checkout, and existing worktrees a seat was pointed at are never removed. Ledgers stay readable. Reuse client_request_id to retry safely."; // McpToolAccess reads the calling thread before any tool that needs one, so each of those // tools depends on ThreadManagementService whether or not its handler does. diff --git a/apps/server/src/j5/a2a/migrations/050_CrewWorktrees.test.ts b/apps/server/src/j5/a2a/migrations/050_CrewWorktrees.test.ts new file mode 100644 index 0000000000000..6a39a896aa594 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/050_CrewWorktrees.test.ts @@ -0,0 +1,33 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runJ5A2AMigrations } from "../Migrations.ts"; + +it.effect("adds the worktree record without touching the seat context it follows", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runJ5A2AMigrations({ toMigrationInclusive: 49 }); + yield* sql` + INSERT INTO j5_crew_seat_context (thread_id, first_turn_text, workspace) + VALUES ('thread:seat', '', '{"type":"worktree","baseRef":"main"}') + `; + const before = yield* sql`SELECT * FROM j5_crew_seat_context`; + + yield* runJ5A2AMigrations(); + yield* runJ5A2AMigrations(); + + assert.deepStrictEqual(yield* sql`SELECT * FROM j5_crew_seat_context`, before); + assert.deepStrictEqual(yield* sql`SELECT * FROM j5_crew_worktree`, []); + yield* sql` + INSERT INTO j5_crew_worktree (thread_id, project_id, path, branch, created_at) + VALUES ('thread:seat', 'project:one', '/wt/seat', 'j5/seat', '2026-10-27T00:00:00.000Z') + `; + const duplicate = yield* Effect.exit(sql` + INSERT INTO j5_crew_worktree (thread_id, project_id, path, branch, created_at) + VALUES ('thread:seat', 'project:one', '/wt/other', NULL, '2026-10-27T00:00:01.000Z') + `); + assert.strictEqual(duplicate._tag, "Failure"); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); diff --git a/apps/server/src/j5/a2a/migrations/050_CrewWorktrees.ts b/apps/server/src/j5/a2a/migrations/050_CrewWorktrees.ts new file mode 100644 index 0000000000000..ddf38877e1087 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/050_CrewWorktrees.ts @@ -0,0 +1,20 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * The worktrees J5 itself created for Crew seats, one row per seat thread. The row outlives the + * checkout: a seat that is unarchived, repaired and archived again is looked at again, and a + * worktree with no row (every worktree from before this table) is never removed by J5. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql` + CREATE TABLE j5_crew_worktree ( + thread_id TEXT PRIMARY KEY, + project_id TEXT NOT NULL, + path TEXT NOT NULL, + branch TEXT, + created_at TEXT NOT NULL + ) + `; +}); diff --git a/apps/server/src/j5/a2a/runtimeLayer.test.ts b/apps/server/src/j5/a2a/runtimeLayer.test.ts index 180ee4e47ddd5..a3a641757d27d 100644 --- a/apps/server/src/j5/a2a/runtimeLayer.test.ts +++ b/apps/server/src/j5/a2a/runtimeLayer.test.ts @@ -21,6 +21,9 @@ import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts"; import * as PreviewAutomationBroker from "../../mcp/PreviewAutomationBroker.ts"; import * as PreviewBrowser from "../../preview/PreviewBrowser.ts"; import { GitVcsDriver } from "../../vcs/GitVcsDriver.ts"; +import { GitManager } from "../../git/GitManager.ts"; +import { ProviderSessionManagerV2 } from "../../orchestration-v2/ProviderSessionManager.ts"; +import { TerminalManager } from "../../terminal/Manager.ts"; import { ManagedProjectFolders } from "../../project/ManagedProjectFolders.ts"; import { PreviewManager } from "../../preview/Manager.ts"; import { PullRequestReviewGuideService } from "../../pullRequest/PullRequestReviewGuideService.ts"; @@ -127,6 +130,14 @@ const measureNestedRuntimeBuilds = (nested: "http" | "mcp") => Layer.provide(AnalyticsService.layerTest), Layer.provide(Layer.mock(ProjectService)({})), Layer.provide(Layer.mock(GitWorkflowService)({})), + Layer.provide(Layer.mock(GitVcsDriver)({})), + Layer.provide(Layer.mock(GitManager)({})), + Layer.provide( + Layer.mergeAll( + Layer.mock(ProviderSessionManagerV2)({}), + Layer.mock(TerminalManager)({}), + ), + ), Layer.provide(Layer.mock(EnvironmentAuth)({})), Layer.provide( Layer.mock(ServerEnvironment)({ @@ -271,6 +282,9 @@ it.effect("shares one runtime and outbox across the production HTTP and MCP regi Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(PreviewBrowser.PreviewBrowser)({}), Layer.mock(GitVcsDriver)({}), + Layer.mock(GitManager)({}), + Layer.mock(ProviderSessionManagerV2)({}), + Layer.mock(TerminalManager)({}), Layer.mock(ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), Layer.mock(PreviewManager)({}), Layer.mock(PullRequestReviewGuideService)({}), diff --git a/apps/server/src/j5/a2a/runtimeLayer.ts b/apps/server/src/j5/a2a/runtimeLayer.ts index f2eada4bc4b2c..a47be9b054e02 100644 --- a/apps/server/src/j5/a2a/runtimeLayer.ts +++ b/apps/server/src/j5/a2a/runtimeLayer.ts @@ -21,6 +21,8 @@ import { layer as crewSeatFinishNotifierLayer } from "./CrewSeatFinishNotifier.t import * as NativeQuestionNotifier from "./NativeQuestionNotifier.ts"; import { layer as captainArchiveCascadeLayer } from "./CrewCaptainArchiveCascade.ts"; import { layer as crewStopLayer } from "./CrewStopService.ts"; +import { layer as crewWorktreesLayer } from "./CrewWorktrees.ts"; +import { layer as projectionStoreLayer } from "../../orchestration-v2/ProjectionStore.ts"; import { layer as crewRuntimeRequestLayer } from "./CrewRuntimeRequestService.ts"; import { layer as deliveryWorkerLayer } from "./DeliveryWorker.ts"; import { live as deliveryTransportLayer } from "./DeliveryTransport.ts"; @@ -144,6 +146,9 @@ const makeJ5A2AAuxiliaryLayer = ( Layer.provide(peerHttpClient), ); const archiveFactsProvided = archiveFactsLayer.pipe(Layer.provide(placementFactsLayer)); + // One instance: its recorder daemon tails the event stream, and the archive and the dialog's + // read use the same service. The stateless projection reader is built from the shared database. + const crewWorktreesProvided = crewWorktreesLayer.pipe(Layer.provide(projectionStoreLayer)); // The saved-agent handoff worker drains the queue the run-finalization observer fills; the // queue layer is the same instance server.ts provides to that observer. const agentHandoffNudgeWorkerProvided = agentHandoffNudgeWorkerLayer.pipe( @@ -159,6 +164,7 @@ const makeJ5A2AAuxiliaryLayer = ( Layer.provideMerge(archiveAgentProvided), Layer.provideMerge(agentCrewInstanceLayer), Layer.provideMerge(playbookStoreLayer), + Layer.provideMerge(crewWorktreesProvided), ); // Hands each landing of a Crew-linked run to the seat that owns it, inside the Captain's step // calls; a pending hand-off is finished by the Captain's next or retried call. diff --git a/apps/server/src/j5/wsRpc.test.ts b/apps/server/src/j5/wsRpc.test.ts index 9bc1a701b44b5..49fdaebb1bb31 100644 --- a/apps/server/src/j5/wsRpc.test.ts +++ b/apps/server/src/j5/wsRpc.test.ts @@ -140,7 +140,12 @@ const clientFor = (scopes: ReadonlyArray) => : Effect.fail(new CrewStopNotFoundError({ crewInstanceId })), archiveCrew: ({ crewInstanceId }) => crewInstanceId === "crew:1" - ? reached("archive", { crewInstanceId, status: "archived" as const, members: [] }) + ? reached("archive", { + crewInstanceId, + status: "archived" as const, + members: [], + worktrees: [], + }) : Effect.fail( new ArchiveCrewPartialFailureError({ crewInstanceId, diff --git a/apps/web/src/j5/a2a/ArchiveWarningContent.tsx b/apps/web/src/j5/a2a/ArchiveWarningContent.tsx index a142ed73fd399..7081d296015fa 100644 --- a/apps/web/src/j5/a2a/ArchiveWarningContent.tsx +++ b/apps/web/src/j5/a2a/ArchiveWarningContent.tsx @@ -3,17 +3,91 @@ import { InboxIcon, SendIcon } from "lucide-react"; import { RelativeAge } from "../RelativeAge"; import { Badge } from "../../components/ui/badge"; +import type { CrewArchiveWorktreeEstimate } from "@t3tools/contracts/j5"; import { ARCHIVE_WARNING_WORKSPACE_NOTE, archiveWarningAskHeader, archiveWarningSeatConsequences, + groupWorktreeEstimates, sentenceEnd, + worktreeReasonLabel, + worktreeShortPath, type ArchiveWarningCrew, type ArchiveWarningParticipant, type ArchiveWarningPayload, type ArchiveWarningRow, + type ArchiveWarningWorktrees, } from "@t3tools/client-runtime/j5/archive-flow"; +function ArchiveWarningWorktreeList({ + worktrees, + heading, +}: { + readonly worktrees: ReadonlyArray; + readonly heading: string; +}) { + if (worktrees.length === 0) return null; + return ( +
+

{heading}

+
    + {worktrees.map((worktree) => ( +
  • + + {worktree.seat} + + + }> + {worktreeShortPath(worktree.path)} + + {worktree.path} + + {worktree.reason === null ? null : ( + + {worktreeReasonLabel[worktree.reason]} + + )} +
  • + ))} +
+
+ ); +} + +/** + * Which worktrees J5 created for the Crews' seats archiving would remove, and which stay. It is + * an estimate: the archive checks each one again, and a worktree that is still clean and merged + * then is the only kind it removes. Shared by the Captain's dialog and the Fleet page's. + */ +export function ArchiveWarningWorktreeSection({ + worktrees, +}: { + readonly worktrees: ArchiveWarningWorktrees; +}) { + if (worktrees === null) + return ( +

+ Worktrees: couldn't check. Branches and pull requests remain. +

+ ); + const { removed, kept } = groupWorktreeEstimates(worktrees); + return ( +
+ + +

+ {worktrees.length === 0 + ? "No worktrees were created for these seats. " + : "This is an estimate; each is checked again when you archive. "} + Branches and pull requests remain. +

+
+ ); +} + /** The seats of one Crew with what ends for each; shared by the Captain's dialog and the Fleet page. */ export function ArchiveWarningCrewSeats({ crew }: { readonly crew: ArchiveWarningCrew }) { return ( @@ -157,9 +231,13 @@ export function ArchiveWarningContent({ payload }: { readonly payload: ArchiveWa ) : null} -

- {ARCHIVE_WARNING_WORKSPACE_NOTE} -

+ {payload.worktrees === undefined ? ( +

+ {ARCHIVE_WARNING_WORKSPACE_NOTE} +

+ ) : ( + + )} ); } diff --git a/apps/web/src/j5/a2a/archiveFlowClient.ts b/apps/web/src/j5/a2a/archiveFlowClient.ts index a0d7f602e6f5f..6dad07e9a6aee 100644 --- a/apps/web/src/j5/a2a/archiveFlowClient.ts +++ b/apps/web/src/j5/a2a/archiveFlowClient.ts @@ -25,3 +25,9 @@ export async function readParticipantLabels( export const readArchivePreflight = (threadRef: ScopedThreadRef) => Shared.readArchivePreflight(j5Environment, appAtomRegistry, threadRef); + +export const readCrewArchiveWorktrees = ( + environmentId: EnvironmentId, + crewInstanceIds: ReadonlyArray, +) => + Shared.readCrewArchiveWorktrees(j5Environment, appAtomRegistry, environmentId, crewInstanceIds); diff --git a/apps/web/src/j5/fleet/FleetPage.tsx b/apps/web/src/j5/fleet/FleetPage.tsx index 8bc3ffae375d1..3a81af73c3ab2 100644 --- a/apps/web/src/j5/fleet/FleetPage.tsx +++ b/apps/web/src/j5/fleet/FleetPage.tsx @@ -32,7 +32,11 @@ import { fleetDetailSourcesAtom, j5Environment } from "../state"; import { useLogicalProjects } from "../logicalProjects"; import { requestConfirmDialog } from "../../confirmDialog"; import type { ArchiveWarningCrew } from "@t3tools/client-runtime/j5/archive-flow"; -import { ArchiveWarningCrewSeats } from "../a2a/ArchiveWarningContent"; +import { + ArchiveWarningCrewSeats, + ArchiveWarningWorktreeSection, +} from "../a2a/ArchiveWarningContent"; +import { readCrewArchiveWorktrees } from "../a2a/archiveFlowClient"; import { archiveCrew } from "../crew/crewArchiveClient"; import { classifyCrewSeat, @@ -384,6 +388,11 @@ function FleetNodeRows( }), }; const consequential = warning.seats.some((seat) => seat.runningTurn || seat.openAsks > 0); + // Read before the dialog opens, so it can say what happens to each seat's worktree. A read + // that fails says so rather than promising nothing is removed. + const worktrees = await readCrewArchiveWorktrees(environmentId, [crew.crewInstanceId]).catch( + () => null, + ); const confirmed = await (requestConfirmDialog( `Archive crew ${crew.crewName}?`, { variant: "destructive" }, @@ -392,10 +401,8 @@ function FleetNodeRows(

Its {warning.seats.length === 1 ? "seat retires" : "seats retire"} together:

-

- Worktrees, branches, and pull requests remain. The roster stays readable under Retired - crews. -

+ +

The roster stays readable under Retired crews.

), confirmLabel: consequential ? "Archive anyway" : "Archive", diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index 35ee5ff0b50fc..337f98248e80d 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -331,11 +331,13 @@ participant, so no Captain check applies to it (Bryant, 2026-09-14). ### `j5_archive_crew` -**Description (contract):** "Retire a whole Crew you command. Crews archive only as a unit — +**Description (contract):** "Retire a whole Crew you command. Crews archive only as a unit; members are never retired one by one. A clean archive completes immediately; otherwise the call refuses with the facts and a confirmation_token. Before retrying with that token, check with the -user. Nothing is destroyed: worktrees, branches, and ledgers stay readable. Reuse -client_request_id to retry safely." +user. Archiving removes the worktrees J5 created for the Crew's seats when they are clean, merged, +unshared (no other thread or project uses it) and unused (no session or terminal is open in it), +keeps every branch and pull request, and lists the rest with their reasons. +Reuse client_request_id to retry safely." | Input | Type | Required | Meaning | | -------------------- | ----------------- | -------- | ---------------------------------------------------- | @@ -343,8 +345,13 @@ client_request_id to retry safely." | `confirmation_token` | string | no | Token from the refusal; confirms exactly those facts | | `client_request_id` | string, non-empty | no | Supply and reuse to make retries safe | -Result: `status` (`archived` or `already_archived`), `crew_instance_id`, and `members` (seat, -participant_id, per-member result). Semantics: only the Captain — the participant that launched the +Result: `status` (`archived` or `already_archived`), `crew_instance_id`, `members` (seat, +participant_id, per-member result), and `worktrees`: one entry for each worktree J5 created for a +seat on a new worktree, with its `path`, `branch`, an `outcome` of `removed`, `kept` or `failed`, and +a `reason` (`uncommitted_changes`, `unmerged_commits`, `shared`, `in_use`, `unverified`, or +`failed`) unless removed. The removal runs after every seat is archived and the Crew is marked +archived, never fails the archive, and runs again when an archived Crew is archived again, so a +worktree kept because a session or terminal was still open can be retried once it closes. Semantics: only the Captain — the participant that launched the Crew — may archive it (R19); anyone else is refused and pointed at asking the Captain. Facts are read for every member before anything happens. If any member has an open Exchange or a running turn, the call refuses with a per-seat list (`members[].open_exchanges`, `members[].running_turn`, diff --git a/docs/j5/product/features/archive-flow.md b/docs/j5/product/features/archive-flow.md index d545054e6f151..4c4ecc4362d9b 100644 --- a/docs/j5/product/features/archive-flow.md +++ b/docs/j5/product/features/archive-flow.md @@ -11,15 +11,15 @@ Archiving an agent is where obligations get stranded: the agent that was owed a ## Definition -Archiving sets an agent aside, and a person can bring it back. It **never destroys work**: worktrees, branches and pull requests survive, and cleaning them up is a separate act. It is **loud**: every open Exchange the agent holds ends with a notice to the waiter, and every fact that archiving will change is shown before it happens. +Archiving sets an agent aside, and a person can bring it back. It **never destroys work**: branches and pull requests survive, and so does every worktree that holds unfinished work. Archiving one agent removes nothing; archiving a Crew removes only the clean, merged worktrees J5 created for its seats ([Crews](crews.md) AC19), and cleaning up any other is a separate act. It is **loud**: every open Exchange the agent holds ends with a notice to the waiter, and every fact that archiving will change is shown before it happens. Before the dialog appears, the platform reads the facts: the agent's open asks in both directions, and the agents placed beneath it. A fact it could not read is shown as "couldn't check" — never as an empty, reassuring list. -**The dialog appears only when the facts warrant it.** An agent with nothing open and nothing beneath it archives without ceremony. Otherwise the dialog is titled "Archive ⟨agent name⟩?" and shows: the agents beneath it, which keep running; each open ask that will be terminated, as a two-line row mirroring an inbox item — urgency badge first, then "To" or "From" and the counterpart's name, then the time open, then the intent verbatim; the section's count and consequence ("N open asks will be terminated (counterparties are notified)"); a quiet reassurance that the workspace survives; and one destructive-styled confirm. One confirm, no type-to-confirm. Every line is a measured fact; the dialog offers no opinion on whether to proceed. +**The dialog appears only when the facts warrant it.** An agent with nothing open and nothing beneath it archives without ceremony. Otherwise the dialog is titled "Archive ⟨agent name⟩?" and shows: the agents beneath it, which keep running; each open ask that will be terminated, as a two-line row mirroring an inbox item — urgency badge first, then "To" or "From" and the counterpart's name, then the time open, then the intent verbatim; the section's count and consequence ("N open asks will be terminated (counterparties are notified)"); a quiet reassurance that the workspace survives, or, for a Captain's live Crews, which seat worktrees would be removed and which kept, as an estimate; and one destructive-styled confirm. One confirm, no type-to-confirm. Every line is a measured fact; the dialog offers no opinion on whether to proceed. Afterwards, waiters receive a platform notice that the Exchange ended, the person's inbox items from this agent leave immediately (the dialog was the loud moment), the agent leaves the active sidebar, the Fleet page and the agents' address book, it can no longer be messaged, and its ledger and conversation stay readable forever. -**Unarchiving** is the way back. It restores the same agent — the same participant id, placement and provenance — and makes it addressable again. It does not undo what archiving ended: the Exchanges that closed stay closed, and deliveries that were cancelled are not replayed. An agent may be archived and unarchived any number of times. +**Unarchiving** is the way back. It restores the same agent — the same participant id, placement and provenance — and makes it addressable again. It does not undo what archiving ended: the Exchanges that closed stay closed, and deliveries that were cancelled are not replayed. A worktree that archiving removed keeps its recorded branch and path, and the agent's next turn recreates it from that branch. An agent may be archived and unarchived any number of times. **Deleting** is a different act, permanent, and only a person performs it. It removes the agent's membership and placement, offers to clean up the worktree, and leaves the agents beneath it, the historical provenance, and the ledger intact. When Memos exist, the agent's open Memos appear as a third section of the dialog. @@ -45,7 +45,7 @@ Archiving is **not** deleting, **not** a way to archive a single Crew member, an 6. Every waiter on an ended Exchange receives a platform notice rendered as a muted notice line in its thread. 7. The person's inbox items from the archived agent leave immediately, with no terminal row. 8. The archived agent leaves the active sidebar and the Fleet page, is hidden from the agents' address book unless archived agents are asked for, and cannot receive a message or an ask; its ledger and conversation remain readable. -9. No worktree, branch, or pull request is deleted by archiving. +9. Archiving an agent deletes no worktree, branch, or pull request. Archiving a Crew, including through its Captain, deletes no branch or pull request, and closes the seats' provider sessions and removes a worktree only as [Crews](crews.md) AC19 allows, after the Captain's own archive, which upstream's sidebar performs, has committed; that archive itself removes nothing. Before a Captain's archive or Archive crew, the dialog lists the seat worktrees it would remove and those it would keep with the reason, labeled as an estimate, or says it couldn't check. ### Boundaries @@ -54,8 +54,8 @@ Archiving is **not** deleting, **not** a way to archive a single Crew member, an ### Unarchiving and deleting -12. Unarchiving restores the same participant id, placement and provenance and makes the agent addressable again; the Exchanges that archiving closed stay closed and no cancelled delivery is replayed. -13. Deleting is permanent, is performed only by a person, removes the agent's membership and placement, and leaves the agents beneath it, historical provenance and the ledger intact; it is the only flow that offers worktree cleanup. +12. Unarchiving restores the same participant id, placement and provenance and makes the agent addressable again; the Exchanges that archiving closed stay closed and no cancelled delivery is replayed; a worktree archiving removed is recreated from its kept branch on the agent's next turn, and forking the agent does the same. +13. Deleting is permanent, is performed only by a person, removes the agent's membership and placement, and leaves the agents beneath it, historical provenance and the ledger intact; it is the only flow that offers to clean up an agent's own worktree. ## Scenarios @@ -73,3 +73,5 @@ Archiving is **not** deleting, **not** a way to archive a single Crew member, an - 2026-09-08 — rewritten into the definition shape. Former identifiers: AR1 → AC11; AR2 → AC1; AR3 → AC2–AC5; AR4 → AC6–AC9; AR5 → AC3–AC4; J1–J3 → AC3, AC5. Build sequencing that lived here (the dialog shipping ahead of waiter notices) is history. - 2026-09-22 — an archive touches one agent: the dialog names the agents beneath it as ones that keep running, not as ones it archives (#254, option A; Bryant). - 2026-10-07 — Squadrons retired: an agent's project is upstream's and never changes, so unarchiving has no home to restore, and there is no Squadron to archive (Jackson, 2026-10-05; [#412](https://github.com/Jacksondr5/j5code/issues/412)). +- 2026-10-27 — archiving a Crew removes the clean, merged worktrees J5 created for its seats; the dialog lists what would go and what would stay; AC9 and the definition rewritten ([#748](https://github.com/Jacksondr5/j5code/issues/748); Crews proposal v2). +- 2026-10-31 — archiving a Crew also closes its seats' provider sessions before the worktree cleanup, so an open session no longer keeps a clean, merged worktree (Jackson, 2026-10-31; [#748](https://github.com/Jacksondr5/j5code/issues/748)). diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index 2e70672572565..37f562cbe52ad 100644 --- a/docs/j5/product/features/crews.md +++ b/docs/j5/product/features/crews.md @@ -39,7 +39,7 @@ Any agent with Crews placed under it is a **Captain** — a derived, measured st ### Lifecycle -Crews are deliberately disposable. They **archive only as a unit** — members are never individually archived or replaced — because an agent's death is usually recoverable by messaging it again, and an irrecoverably poisoned member has likely contaminated its crewmates. Recovery is **propose again**, which is cheap because a Background Crew's value lives in its brief, its approved roster, and its durable artifacts — worktree, branch, pull request, handoff artifacts — which survive the agents. Two platform rules make this safe: archive never destroys work, and archive is loud, with every open Exchange ending in a notice to its waiter. A former seat unarchived on its own through the ordinary unarchive is a solo agent, not a member of any Crew; a Crew comes back only with its Captain. +Crews are deliberately disposable. They **archive only as a unit** — members are never individually archived or replaced — because an agent's death is usually recoverable by messaging it again, and an irrecoverably poisoned member has likely contaminated its crewmates. Recovery is **propose again**, which is cheap because a Background Crew's value lives in its brief, its approved roster, and its durable artifacts — branch, pull request, handoff artifacts, and any worktree with unfinished work — which survive the agents. Two platform rules make this safe: archive keeps every branch and pull request, and removes only the worktrees J5 created for seats when they hold nothing unfinished (clean, merged, used by no one else), reporting every one it keeps and why; and archive is loud, with every open Exchange ending in a notice to its waiter. A former seat unarchived on its own through the ordinary unarchive is a solo agent, not a member of any Crew; a Crew comes back only with its Captain. **Archive and respawn are judgment moments, and the platform never makes that decision itself.** Archiving a Crew with open Exchanges or running turns refuses with the list, seat by seat, and requires a confirmation token; the expectation, carried in guidance rather than enforced, is that a Captain checks with the person and they plan together. The successor Crew starts from a fresh proposal and a fresh brief written by whoever respawns it — where things stand, the state of the durable artifacts, what to do next. There is no auto-forwarded original brief, no generated summary, no transferred conversation, no inherited obligations, no auto-reopened asks; the archived Crew's brief, roster, ledger, and handoff artifacts stay readable for the respawner to consult. @@ -82,7 +82,7 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif ### Lifecycle 18. J5 never settles a seat because its run finished; settling the Captain settles its seats; upstream's settle rules apply to every thread. -19. A Crew archives only as a unit; archiving never deletes a worktree, branch, or checkpoint; archiving with open Exchanges or running turns lists them seat by seat and requires a confirmation token. +19. A Crew archives only as a unit; archiving never deletes a branch, pull request, or checkpoint, and removes a worktree only when J5 created it for a seat on a new worktree, at that seat's first assignment (a worktree a seat was pointed at any other way, and one created by a retried preparation, is never recorded and stays), and, when the archive runs, it has no uncommitted or untracked changes, its commit is merged into the project's fetched default branch or named by a merged pull request, no other unarchived thread uses it, no project is rooted in it, and no provider session or terminal is open in it (the archive first closes each seat's provider session, so a session left open by the seat itself does not keep its worktree; a session another thread still uses stays open and keeps it, as does one that fails to close); every other worktree is left as it was and listed in the archive's result with its reason, and a removal that fails is reported without failing the archive; a Captain's archive from any door, upstream's sidebar included, retires its Crews through this same flow once the Captain's own archive has committed, so the same worktrees go; archiving with open Exchanges or running turns lists them seat by seat and requires a confirmation token. 20. A successor Crew starts from a new proposal and a fresh brief; nothing from the archived Crew's conversation, obligations, or asks is carried over automatically, and its brief, roster, ledger, and handoff artifacts stay readable: the Fleet page's Retired section lists retired Crews across projects, each naming its project, with a link to the Captain's thread while it is active (the ledger's home), the brief, the roster snapshot (seat, agent, why it joined, version), the version, and when it retired, and offers no action on them; a retired Crew comes back only with its Captain, when it retired because the Captain was archived (AC17); handoff artifacts stay on the Artifacts page. 21. A Crew stops as a unit: its Captain over `j5_stop_crew`, or the person from the Crew's Fleet header or the Captain's expander, interrupts every seat with a running turn; idle and not-started seats are untouched, nothing settles or is retired, and the result names each seat as interrupted, already idle, or archived. @@ -138,6 +138,8 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif - 2026-10-06 — a seat whose new worktree fails to prepare is left as upstream leaves any failed launch: its thread shows the failure, and it is not retried, retired, or guarded. Upstream reads an unbound thread as the project's checkout, but this has not happened in practice, so J5 doesn't build for it. The launch report counts a seat still preparing as pending (Jackson; [#274](https://github.com/Jacksondr5/j5code/issues/274)). - 2026-10-07 — Squadrons retired: a Crew lives in its Captain's project, and the Fleet page names that project (Jackson, 2026-10-05; [#412](https://github.com/Jacksondr5/j5code/issues/412)). - 2026-10-12 — active peer steering covers every Codex GPT 6 model, not Astra alone (Jackson, [#569](https://github.com/Jacksondr5/j5code/pull/569)). +- 2026-10-27 — AC19: archiving a Crew removes the clean, merged worktrees J5 created for its seats, instead of leaving every one behind; anything unfinished stays and is reported ([#748](https://github.com/Jacksondr5/j5code/issues/748); Crews proposal v2). +- 2026-10-31 — AC19: archiving a Crew closes its seats' provider sessions before the worktree cleanup, so a clean, merged worktree is not kept as in use by a session the archive itself left open; only worktrees recorded at a seat's first assignment are removed (Jackson, 2026-10-31; [#748](https://github.com/Jacksondr5/j5code/issues/748)). - 2026-10-22 — active peer steering covers Claude (Bryant). - 2026-10-17 — several people (Jackson; [record](../../worklog/2026-10-16-people-and-access-session.md)): "the person" is anyone who can write to the Captain's thread, and a Crew's later requests reach all of them, which ends the stall where a guest who asked for a Crew never saw its seats' approvals (AC23; [#534](https://github.com/Jacksondr5/j5code/issues/534)). - 2026-10-27 — the Captain's timeline shows the person only what they would act on: launch and finish notices become one line per seat that needs them, and each seat's row says how its last run ended (Bryant; [#741](https://github.com/Jacksondr5/j5code/issues/741)). diff --git a/docs/j5/product/problems.md b/docs/j5/product/problems.md index 0bd8a799f2a27..8ff1a12fa7c0c 100644 --- a/docs/j5/product/problems.md +++ b/docs/j5/product/problems.md @@ -94,7 +94,7 @@ Complex work needs groups of agents with defined Roles — a Builder, a Reviewer Crews are meant to work the task they're assigned with a high degree of independence from the user, working until they hit a defined stopping point or they complete their task. They can always reach out to other agents for help. But, their communication to the user is rarely through direct chat — they reach the human through the inbox and their Captain (`../worklog/2026-08-14-communication-graph-draft.md`, the human-contact spectrum lens's far-end norms) and record deferred items as Memos (`features/memos.md`). -Crews are deliberately disposable: when their task is done, the user or spawner archives them. They archive only as a unit, members are never individually replaced, and recovery from a poisoned Crew is respawning a fresh one from its definition — cheap because the real work lives in durable artifacts (worktree, branch, PR) that survive the agents. Agents can spawn Crews themselves (Captains running Crews without the human in the loop is the point), Captains can archive the Crews they command, and Crew members can't spawn Crews of their own — wanting more hands is an escalation. +Crews are deliberately disposable: when their task is done, the user or spawner archives them. They archive only as a unit, members are never individually replaced, and recovery from a poisoned Crew is respawning a fresh one from its definition — cheap because the real work lives in durable artifacts (branch, PR, and any worktree with unfinished work) that survive the agents. Agents can spawn Crews themselves (Captains running Crews without the human in the loop is the point), Captains can archive the Crews they command, and Crew members can't spawn Crews of their own — wanting more hands is an escalation. The platform ships the machinery — define, spawn, render, archive; the Playbook a Crew executes and the Roles it contains are always the user's content. The PR Group is one Crew definition someone wrote, never the product's opinion. (The definition of record is [Crews](features/crews.md).) diff --git a/docs/j5/user/personas.md b/docs/j5/user/personas.md index 610ebdb9627a4..71fdddcbb49ae 100644 --- a/docs/j5/user/personas.md +++ b/docs/j5/user/personas.md @@ -69,7 +69,7 @@ Crews are a web and desktop feature; the mobile app shows crew members as ordina To stop a crew that is heading the wrong way, use **Stop crew** on the crew's row in Fleet or the small **Stop** beside that crew's toggle under the Captain in the thread list; both appear only while a member is running. Stopping interrupts every running member's turn and nothing else: members stay on the roster and can be messaged again. The Captain can do the same from its own tools. -A crew is retired as a unit, by the Captain or by you. The Captain is shown exactly what will end, seat by seat, and asked to confirm; the guidance is to check with you first. You can retire a crew yourself with **Archive crew** on its row in Fleet. A crew always follows its Captain: archiving a Captain's thread retires its crews with it (from the thread list, a dialog first lists every member with any running turn or open ask), and unarchiving the Captain (or **Undo** on its archive) brings those crews back, though not the turns the archive interrupted. If some members come back and the crew still shows as retired, archive the Captain again and unarchive it. Settling or unsettling a Captain does the same to its members. A crew you retired with **Archive crew** stays retired. Individual crew members cannot be archived or deleted on their own, from any device. Archiving never deletes worktrees, branches, or conversation history, and a retired crew's brief and roster stay readable in the **Retired crews** section of Fleet, which lists retired crews from every project. +A crew is retired as a unit, by the Captain or by you. The Captain is shown exactly what will end, seat by seat, and asked to confirm; the guidance is to check with you first. You can retire a crew yourself with **Archive crew** on its row in Fleet. A crew always follows its Captain: archiving a Captain's thread retires its crews with it (from the thread list, a dialog first lists every member with any running turn or open ask), and unarchiving the Captain (or **Undo** on its archive) brings those crews back, though not the turns the archive interrupted. If some members come back and the crew still shows as retired, archive the Captain again and unarchive it. Settling or unsettling a Captain does the same to its members. A crew you retired with **Archive crew** stays retired. Individual crew members cannot be archived or deleted on their own, from any device. Archiving a crew removes the worktrees it created for its members when they are clean and their work is merged, and keeps any with unfinished work; a member whose worktree was removed gets it back, from its branch, on its next turn after you unarchive it; the dialog lists which it expects to remove and which to keep, and the archive result lists what it did. Archiving never deletes branches, pull requests, or conversation history, and a retired crew's brief and roster stay readable in the **Retired crews** section of Fleet, which lists retired crews from every project. Persona instructions describe intended behavior. They do not grant permissions or guarantee that an agent obeys them. The displayed runtime policy reflects supported provider controls; unsupported modes appear as **Blocked**. A persona whose runtime policy your app doesn't recognize, because the environment runs a newer J5 Code, appears as **Unsupported** with the policy's name and can't be launched, edited, or duplicated from that app until you update it. diff --git a/packages/client-runtime/src/j5/archiveFlow.test.ts b/packages/client-runtime/src/j5/archiveFlow.test.ts index f65df88616dbf..b71e8e026930d 100644 --- a/packages/client-runtime/src/j5/archiveFlow.test.ts +++ b/packages/client-runtime/src/j5/archiveFlow.test.ts @@ -1,6 +1,12 @@ +import type { CrewArchiveWorktreeEstimate } from "@t3tools/contracts/j5"; import { describe, expect, it } from "vite-plus/test"; -import { sentenceEnd } from "./archiveFlow.ts"; +import { + groupWorktreeEstimates, + sentenceEnd, + worktreeReasonLabel, + worktreeShortPath, +} from "./archiveFlow.ts"; describe("sentenceEnd", () => { it("closes a sentence after a plain name", () => { @@ -20,3 +26,40 @@ describe("sentenceEnd", () => { } }); }); + +const estimate = ( + overrides: Partial & Pick, +): CrewArchiveWorktreeEstimate => ({ + crewInstanceId: "crew:one", + path: `/wt/${overrides.seat}`, + branch: `j5/${overrides.seat}`, + verdict: "remove", + reason: null, + ...overrides, +}); + +describe("archive worktree estimate", () => { + it("lists what would be removed apart from what stays, with the reason for each keeper", () => { + const grouped = groupWorktreeEstimates([ + estimate({ seat: "builder" }), + estimate({ seat: "critic", verdict: "keep", reason: "unmerged_commits" }), + estimate({ seat: "tester", verdict: "keep", reason: "in_use" }), + ]); + expect(grouped.removed.map((worktree) => worktree.seat)).toEqual(["builder"]); + expect( + grouped.kept.map((worktree) => [ + worktree.seat, + worktree.reason === null ? null : worktreeReasonLabel[worktree.reason], + ]), + ).toEqual([ + ["critic", "has commits that aren't merged"], + ["tester", "a session or terminal is open in it"], + ]); + }); + + it("names a worktree by its last two folders", () => { + expect(worktreeShortPath("/Users/me/.j5code/worktrees/repo/seat-a/")).toBe("repo/seat-a"); + expect(worktreeShortPath("C:\\work\\wt\\seat-b")).toBe("wt/seat-b"); + expect(worktreeShortPath("/seat")).toBe("seat"); + }); +}); diff --git a/packages/client-runtime/src/j5/archiveFlow.ts b/packages/client-runtime/src/j5/archiveFlow.ts index 2b730956421a8..dd1f2adaf0192 100644 --- a/packages/client-runtime/src/j5/archiveFlow.ts +++ b/packages/client-runtime/src/j5/archiveFlow.ts @@ -1,5 +1,10 @@ import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; -import type { PreArchiveCrewSeat, PreArchiveFacts } from "@t3tools/contracts/j5"; +import type { + CrewArchiveWorktreeEstimate, + CrewWorktreeReason, + PreArchiveCrewSeat, + PreArchiveFacts, +} from "@t3tools/contracts/j5"; import * as Cause from "effect/Cause"; import type { AtomRegistry } from "effect/reactivity"; @@ -14,7 +19,7 @@ export type { PreArchiveFacts, PreArchiveLiveCrew as LiveCrew } from "@t3tools/c type J5Reads = Pick< ReturnType>, - "readPreArchiveFacts" | "readParticipantIdentities" + "readPreArchiveFacts" | "readParticipantIdentities" | "readCrewArchiveWorktrees" >; /** Unknown participants stay absent, and so does every one when the read fails. */ @@ -37,6 +42,25 @@ export async function readParticipantIdentities( export interface ArchivePreflight { readonly facts: PreArchiveFacts | null; readonly participantLabels: ReadonlyMap; + /** + * What archiving the Crews the thread commands would do with their seats' worktrees; null when + * that couldn't be read. Absent when the thread commands no Crew. + */ + readonly worktrees?: ArchiveWarningWorktrees; +} + +/** The worktree estimate for these Crews, or null when the read failed: "couldn't check". */ +export async function readCrewArchiveWorktrees( + j5: Pick, + registry: AtomRegistry.AtomRegistry, + environmentId: EnvironmentId, + crewInstanceIds: ReadonlyArray, +): Promise { + const result = await j5.readCrewArchiveWorktrees.run(registry, { + environmentId, + input: { crewInstanceIds }, + }); + return result._tag === "Failure" ? null : result.value.worktrees; } /** Facts remain useful without identity labels; literal participant ids are the honest fallback. */ @@ -59,8 +83,18 @@ export async function readArchivePreflight( ...(facts.liveCrews ?? []).flatMap((crew) => crew.seats.map((seat) => seat.participantId)), ]), ); - const identities = await readParticipantIdentities(j5, registry, threadRef.environmentId, ids); - return { facts, participantLabels: identities.labels }; + const crewIds = (facts.liveCrews ?? []).map((crew) => crew.crewInstanceId); + const [identities, worktrees] = await Promise.all([ + readParticipantIdentities(j5, registry, threadRef.environmentId, ids), + crewIds.length === 0 + ? undefined + : readCrewArchiveWorktrees(j5, registry, threadRef.environmentId, crewIds), + ]); + return { + facts, + participantLabels: identities.labels, + ...(worktrees === undefined ? {} : { worktrees }), + }; } export type ArchiveWarningUrgency = "blocking" | "soon" | "fyi" | null; @@ -102,6 +136,8 @@ export type ArchiveWarningCrews = | { readonly state: "unknown" } | { readonly state: "known"; readonly crews: ReadonlyArray }; +export type ArchiveWarningWorktrees = ReadonlyArray | null; + export interface ArchiveWarningPayload { readonly threadTitle: string; readonly factsUnavailable: boolean; @@ -109,6 +145,11 @@ export interface ArchiveWarningPayload { readonly openAsks: ReadonlyArray; /** Live Crews the agent commands; absent when the caller has no Crew facts to show. */ readonly crews?: ArchiveWarningCrews; + /** + * What archiving the Crews would do with their seats' worktrees: null when it couldn't be + * read, absent when there are no Crews to read it for. + */ + readonly worktrees?: ArchiveWarningWorktrees; } export interface ArchiveWarning { @@ -134,6 +175,30 @@ export const archiveWarningAskHeader = (askCount: number) => export const ARCHIVE_WARNING_WORKSPACE_NOTE = "Worktrees, branches, and pull requests remain. Cleanup is a separate action."; +/** Why a worktree stays, in the words the archive warning uses. */ +export const worktreeReasonLabel: Record = { + uncommitted_changes: "has uncommitted changes", + unmerged_commits: "has commits that aren't merged", + shared: "another thread or project uses it", + in_use: "a session or terminal is open in it", + unverified: "couldn't be checked", + failed: "couldn't be removed", +}; + +/** The estimate split the way the warning lists it: what goes, and what stays and why. */ +export function groupWorktreeEstimates(worktrees: ReadonlyArray) { + return { + removed: worktrees.filter((worktree) => worktree.verdict === "remove"), + kept: worktrees.filter((worktree) => worktree.verdict === "keep"), + }; +} + +/** The last folders of a path, which tell worktrees of one project apart. */ +export function worktreeShortPath(path: string): string { + const parts = path.split(/[\\/]+/).filter((part) => part !== ""); + return parts.slice(-2).join("/"); +} + /** Agent names can be a whole brief, so one may already end its own sentence. */ export const sentenceEnd = (lastWords: string) => (/[.!?…]$/.test(lastWords.trimEnd()) ? "" : "."); @@ -183,6 +248,8 @@ export function buildArchiveWarning(input: { placement: { state: "unknown" }, openAsks: [], crews: { state: "unknown" }, + // Unknown Crews may hold worktrees the archive would remove. + worktrees: null, }, }; } @@ -243,7 +310,20 @@ export function buildArchiveWarning(input: { })); return { title, - payload: { threadTitle, factsUnavailable: false, placement, openAsks, crews }, + payload: { + threadTitle, + factsUnavailable: false, + placement, + openAsks, + crews, + // Only a Captain with live Crews has seats whose worktrees archiving removes; Crews that + // couldn't be read may have some. + ...(crews.state === "unknown" + ? { worktrees: null } + : preflight.worktrees === undefined + ? {} + : { worktrees: preflight.worktrees }), + }, confirmLabel: openAsks.length > 0 || crewsHaveConsequences ? "Archive anyway" : "Archive", }; } diff --git a/packages/client-runtime/src/j5/state.ts b/packages/client-runtime/src/j5/state.ts index 5d3cb88af8eb7..e628f87fea870 100644 --- a/packages/client-runtime/src/j5/state.ts +++ b/packages/client-runtime/src/j5/state.ts @@ -249,6 +249,12 @@ export function createJ5EnvironmentAtoms( tag: J5_CLIENT_READ_WS_METHODS.readPreArchiveFacts, execute: (input) => j5Read(J5_CLIENT_READ_WS_METHODS.readPreArchiveFacts, input), }), + // What archiving a Crew would do with its seats' worktrees; shown beside the facts above. + readCrewArchiveWorktrees: createEnvironmentRpcCommand(runtime, { + label: "j5:crew-archive-worktrees", + tag: J5_CLIENT_READ_WS_METHODS.readCrewArchiveWorktrees, + execute: (input) => j5Read(J5_CLIENT_READ_WS_METHODS.readCrewArchiveWorktrees, input), + }), readParticipantIdentities: createEnvironmentRpcCommand(runtime, { label: "j5:participant-identities", tag: J5_CLIENT_READ_WS_METHODS.readParticipantIdentities, diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index f24359c97be75..79a04b5fd1be2 100644 --- a/packages/contracts/src/j5.ts +++ b/packages/contracts/src/j5.ts @@ -478,6 +478,33 @@ export type PreArchiveCrewSeat = typeof PreArchiveCrewSeat.Type; */ export const CrewArchiveRequest = Schema.Struct({ crewInstanceId: Schema.String }); export type CrewArchiveRequest = typeof CrewArchiveRequest.Type; + +/** + * Why a Crew seat's worktree stays after the Crew is archived: it has uncommitted or untracked + * changes, commits the default branch does not have (and no merged pull request for that exact + * commit), another unarchived thread works in it, a provider session is still open in it, J5 + * could not check one of those, or `git worktree remove` failed. + */ +export const CrewWorktreeReason = Schema.Literals([ + "uncommitted_changes", + "unmerged_commits", + "shared", + "in_use", + "unverified", + "failed", +]); +export type CrewWorktreeReason = typeof CrewWorktreeReason.Type; + +/** One worktree J5 created for a Crew seat, and what archiving the Crew did with it. */ +export const CrewArchiveWorktree = Schema.Struct({ + path: Schema.String, + branch: Schema.NullOr(Schema.String), + outcome: Schema.Literals(["removed", "kept", "failed"]), + /** Null when removed. */ + reason: Schema.NullOr(CrewWorktreeReason), +}); +export type CrewArchiveWorktree = typeof CrewArchiveWorktree.Type; + export const CrewArchiveResponse = Schema.Struct({ crewInstanceId: Schema.String, status: Schema.Literals(["archived", "already_archived"]), @@ -488,9 +515,33 @@ export const CrewArchiveResponse = Schema.Struct({ result: Schema.Literals(["archived", "already_archived"]), }), ), + /** Absent from a server that predates worktree cleanup, which removed none. */ + worktrees: Schema.Array(CrewArchiveWorktree).pipe(Schema.withDecodingDefault(Effect.succeed([]))), }); export type CrewArchiveResponse = typeof CrewArchiveResponse.Type; +/** + * What archiving these Crews would do with the worktrees J5 created for their seats, read before + * the person confirms. An estimate: each is checked again when the archive runs. + */ +export const CrewArchiveWorktreesRequest = Schema.Struct({ + crewInstanceIds: Schema.Array(Schema.String), +}); +export type CrewArchiveWorktreesRequest = typeof CrewArchiveWorktreesRequest.Type; +export const CrewArchiveWorktreeEstimate = Schema.Struct({ + crewInstanceId: Schema.String, + seat: Schema.String, + path: Schema.String, + branch: Schema.NullOr(Schema.String), + verdict: Schema.Literals(["remove", "keep"]), + /** Null when it would be removed. */ + reason: Schema.NullOr(CrewWorktreeReason), +}); +export type CrewArchiveWorktreeEstimate = typeof CrewArchiveWorktreeEstimate.Type; +const CrewArchiveWorktreesResponse = Schema.Struct({ + worktrees: Schema.Array(CrewArchiveWorktreeEstimate), +}); + /** * What a J5 server reports about its ledger. Every J5 read is gated on `j5ProjectLedger`. The two * older keys are reported `false`, not left out: a client from before the ledger was re-keyed @@ -1194,6 +1245,7 @@ export const J5_CLIENT_READ_WS_METHODS = { readFleet: "j5.fleet.read", listSpawnedChildren: "j5.fleet.listSpawnedChildren", readPreArchiveFacts: "j5.archive.readFacts", + readCrewArchiveWorktrees: "j5.archive.readCrewWorktrees", readParticipantIdentities: "j5.participants.readIdentities", listPeers: "j5.peers.list", subscribeReadChanges: "j5.reads.subscribeChanges", @@ -1263,6 +1315,11 @@ export const J5ClientReadRpcGroup = RpcGroup.make( PreArchiveFactsRequest, PreArchiveFacts, ), + clientRead( + J5_CLIENT_READ_WS_METHODS.readCrewArchiveWorktrees, + CrewArchiveWorktreesRequest, + CrewArchiveWorktreesResponse, + ), clientRead( J5_CLIENT_READ_WS_METHODS.readParticipantIdentities, ParticipantIdentitiesRequest,