diff --git a/apps/server/src/j5/a2a/ArchiveCrewService.test.ts b/apps/server/src/j5/a2a/ArchiveCrewService.test.ts index a2713813c5b1d..684b2264dfe32 100644 --- a/apps/server/src/j5/a2a/ArchiveCrewService.test.ts +++ b/apps/server/src/j5/a2a/ArchiveCrewService.test.ts @@ -94,6 +94,7 @@ const fixture = Effect.gen(function* () { // What cleanup was asked about, and what it reports back. const cleanedSeats = yield* Ref.make>>([]); const cleanupResult = yield* Ref.make>([]); + const approvalStamps = 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. @@ -119,9 +120,10 @@ const fixture = Effect.gen(function* () { ), closeSessions: (sessions) => Effect.forEach(sessions, (session) => step(`close:${session.providerSessionId}`)), - cleanup: ({ seats }) => + cleanup: ({ seats, crew }) => Effect.all([ step("cleanup"), + Ref.update(approvalStamps, (items) => [...items, crew?.archivedAt]), 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))), @@ -217,6 +219,7 @@ const fixture = Effect.gen(function* () { crewArchivedAt, cleanedSeats, cleanupResult, + approvalStamps, lifecycleAtCleanup, sessionSteps, }; @@ -552,7 +555,7 @@ it.effect("closes each seat's session after its archive and before the worktree it.effect("a replay of an archived Crew checks its worktrees again", () => Effect.gen(function* () { - const { layer, input, cleanedSeats, cleanupResult } = yield* fixture; + const { layer, input, cleanedSeats, cleanupResult, approvalStamps } = yield* fixture; yield* Effect.gen(function* () { const service = yield* ArchiveCrewService; yield* service.archive(input({ callerParticipantId: null, confirmationSatisfied: true })); @@ -560,9 +563,18 @@ it.effect("a replay of an archived Crew checks its worktrees again", () => { path: "/wt/critic", branch: "j5/critic", outcome: "removed", reason: null }, ]); const replay = yield* service.archive( - input({ callerParticipantId: null, confirmationSatisfied: true }), + input({ + callerParticipantId: null, + confirmationSatisfied: true, + archivedAt: "2026-09-10T08:00:00.000Z", + }), ); assert.equal(replay.status, "already_archived"); + // The replay is the same archive, so an approval it would file carries the original stamp. + assert.deepStrictEqual(yield* Ref.get(approvalStamps), [ + "2026-09-09T17:00:00.000Z", + "2026-09-09T17:00:00.000Z", + ]); assert.deepStrictEqual( replay.worktrees.map((entry) => entry.outcome), ["removed"], diff --git a/apps/server/src/j5/a2a/ArchiveCrewService.ts b/apps/server/src/j5/a2a/ArchiveCrewService.ts index 27128b6799869..801d7ff111918 100644 --- a/apps/server/src/j5/a2a/ArchiveCrewService.ts +++ b/apps/server/src/j5/a2a/ArchiveCrewService.ts @@ -215,6 +215,15 @@ const createdSeats = (facts: ArchiveCrewConsequenceFacts) => .filter((member) => !member.neverCreated) .map((member) => ({ seatName: member.seatName, threadId: member.threadId })); +/** Who the worktree approval is filed for. */ +const approvalCrew = (instance: AgentCrewInstance, archivedAt: string) => ({ + crewInstanceId: instance.id, + archivedAt: instance.archivedAt ?? archivedAt, + crewName: instance.displayName, + projectId: instance.projectId, + captainThreadId: instance.captainThreadId, +}); + const hasConsequences = (facts: ArchiveCrewConsequenceFacts) => facts.members.some( (member) => member.facts.openExchanges.length > 0 || member.facts.runningTurn !== null, @@ -407,6 +416,7 @@ export const layer = Layer.effect( : ("already_archived" as const), })), seats: createdSeats(facts), + crew: approvalCrew(instance, input.archivedAt), sessions: [] as ReadonlyArray, }; } @@ -493,6 +503,7 @@ export const layer = Layer.effect( status: "archived" as const, members: results, seats: createdSeats(facts), + crew: approvalCrew(instance, input.archivedAt), sessions, }; }, @@ -504,10 +515,10 @@ export const layer = Layer.effect( // 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); + const { seats, sessions, crew, ...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 }); + const removed = yield* worktrees.cleanup({ seats, crew }); return { ...outcome, worktrees: removed }; }, ); diff --git a/apps/server/src/j5/a2a/ClientActionsService.test.ts b/apps/server/src/j5/a2a/ClientActionsService.test.ts index 206154c18f816..427e2b1af3fd4 100644 --- a/apps/server/src/j5/a2a/ClientActionsService.test.ts +++ b/apps/server/src/j5/a2a/ClientActionsService.test.ts @@ -20,6 +20,7 @@ import { type RespondToCrewRuntimeRequestInput, } from "./CrewRuntimeRequestService.ts"; import { CrewStopNotFoundError, CrewStopService, type StopCrewInput } from "./CrewStopService.ts"; +import { CrewWorktrees } from "./CrewWorktrees.ts"; import { A2ADeliveryWorker } from "./DeliveryWorker.ts"; import { A2AHumanInbox } from "./HumanInboxService.ts"; @@ -169,6 +170,7 @@ const serviceWith = (seen: ReturnType) => seen.notified += 1; }), }), + Layer.mock(CrewWorktrees)({}), ), ), Layer.provide(NodeServices.layer), diff --git a/apps/server/src/j5/a2a/ClientActionsService.ts b/apps/server/src/j5/a2a/ClientActionsService.ts index 6c85ec7304e6d..e8ac2a06e1b73 100644 --- a/apps/server/src/j5/a2a/ClientActionsService.ts +++ b/apps/server/src/j5/a2a/ClientActionsService.ts @@ -5,6 +5,8 @@ import type { AnswerHumanExchangeResponse, CrewArchiveRequest, CrewArchiveResponse, + CrewWorktreeCleanupAnswerRequest, + CrewWorktreeCleanupAnswerResponse, CrewProposalPreviewRequest, CrewProposalPreviewResponse, CrewProposalResolveRequest, @@ -27,6 +29,7 @@ import { projectCrewProposal } from "./crewProposalProjection.ts"; import { CrewProposalService } from "./CrewProposalService.ts"; import { CrewRuntimeRequestService } from "./CrewRuntimeRequestService.ts"; import { CrewStopService } from "./CrewStopService.ts"; +import { CrewWorktrees } from "./CrewWorktrees.ts"; import { A2ADeliveryWorker } from "./DeliveryWorker.ts"; import { A2AHumanInbox } from "./HumanInboxService.ts"; import { crewSeatRequestKey, lifecycleCommandId } from "./spawnIds.ts"; @@ -98,6 +101,13 @@ export class ClientActionsService extends Context.Service< typeof AnswerHumanExchangeResponse.Type, Failure >; + /** Decide the worktree cleanup an archive filed in the Inbox; refused once decided. */ + readonly answerCrewWorktreeCleanup: ( + input: CrewWorktreeCleanupAnswerRequest, + ) => Effect.Effect< + typeof CrewWorktreeCleanupAnswerResponse.Type, + Failure + >; } >()("t3/j5/a2a/ClientActionsService") {} @@ -122,6 +132,7 @@ const make = Effect.gen(function* () { const runtimeRequests = yield* CrewRuntimeRequestService; const inbox = yield* A2AHumanInbox; const worker = yield* A2ADeliveryWorker; + const worktrees = yield* CrewWorktrees; // A random source that fails is the host's fault, not a refusal a client can act on. const freshId = (yield* Crypto.Crypto).randomUUIDv4().pipe(Effect.orDie); const projectProposal = projectCrewProposal(yield* PlaybookStore); @@ -231,6 +242,11 @@ const make = Effect.gen(function* () { return { result }; }, ), + answerCrewWorktreeCleanup: Effect.fn("j5.a2a.clientActions.answerCrewWorktreeCleanup")( + function* ({ itemId, removePaths }) { + return { item: yield* worktrees.answerCleanup({ itemId, removePaths }) }; + }, + ), }); }); diff --git a/apps/server/src/j5/a2a/ClientReadsService.ts b/apps/server/src/j5/a2a/ClientReadsService.ts index 58b61556c6cf6..36464f82ecba6 100644 --- a/apps/server/src/j5/a2a/ClientReadsService.ts +++ b/apps/server/src/j5/a2a/ClientReadsService.ts @@ -272,6 +272,8 @@ export interface ClientReadsShape { ReadonlyArray, Read["error"] >; + /** The Inbox's worktree cleanup approvals, open or decided. */ + readonly crewWorktreeCleanups: CrewWorktrees["Service"]["listCleanups"]; } export class ClientReadsService extends Context.Service()( @@ -403,6 +405,7 @@ export const layer: Layer.Layer< fleet: yield* makeFleetRead, preArchiveFacts: yield* makePreArchiveFactsRead, crewArchiveWorktrees: yield* makeCrewArchiveWorktreesRead, + crewWorktreeCleanups: (yield* CrewWorktrees).listCleanups, }); }), ); diff --git a/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.test.ts b/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.test.ts index ad26205c88d35..08930f5c2e40a 100644 --- a/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.test.ts +++ b/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.test.ts @@ -15,6 +15,7 @@ import { OrchestratorProjectionError } from "../../orchestration-v2/Orchestrator import { ProjectionStoreThreadNotFoundError } from "../../orchestration-v2/ProjectionStore.ts"; import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; import { AgentCrewInstanceService, type AgentCrewInstance } from "./AgentCrewInstanceService.ts"; +import { CrewWorktrees } from "./CrewWorktrees.ts"; import { ArchiveCrewService, type ArchiveCrewInput } from "./ArchiveCrewService.ts"; import { CrewCaptainArchiveCascade, layer as cascadeLayer } from "./CrewCaptainArchiveCascade.ts"; import { participantIdForThread } from "./HomeRegistrar.ts"; @@ -59,6 +60,7 @@ const captainProjection = (archivedAt: string | null, deletedAt: string | null = }, }) as unknown as OrchestrationV2ThreadProjection; const noThreads = Layer.mock(ThreadManagementService)({}); +const noWorktrees = Layer.mock(CrewWorktrees)({ withdrawCleanup: () => Effect.void }); it.effect("retires the live Crews a Captain commanded when the person archives its thread", () => Effect.gen(function* () { @@ -66,6 +68,7 @@ it.effect("retires the live Crews a Captain commanded when the person archives i const layer = cascadeLayer.pipe( Layer.provide( Layer.mergeAll( + noWorktrees, Layer.mock(AgentCrewInstanceService)({ listInvolving: (input) => Effect.succeed( @@ -126,6 +129,7 @@ it.effect( const layer = cascadeLayer.pipe( Layer.provide( Layer.mergeAll( + noWorktrees, Layer.mock(AgentCrewInstanceService)({ listLive: () => Effect.succeed([ @@ -179,6 +183,7 @@ it.effect("a Crew whose retirement fails is tried once, and the next Crew still const testLayer = cascadeLayer.pipe( Layer.provide( Layer.mergeAll( + noWorktrees, Layer.mock(AgentCrewInstanceService)({ listInvolving: () => Effect.succeed([crew("crew:broken", null), crew("crew:ok", null)]), }), @@ -315,6 +320,7 @@ it.effect("settling a Captain settles its Crew's seats, and unsettling it unsett const layer = cascadeLayer.pipe( Layer.provide( Layer.mergeAll( + noWorktrees, Layer.mock(AgentCrewInstanceService)({ listInvolving: () => Effect.succeed([ @@ -381,9 +387,13 @@ it.effect("unarchiving a Captain brings back the Crews that retired with it", () Effect.gen(function* () { const dispatched = yield* Ref.make>([]); const restored = yield* Ref.make>([]); + const withdrawn = yield* Ref.make>([]); const layer = cascadeLayer.pipe( Layer.provide( Layer.mergeAll( + Layer.mock(CrewWorktrees)({ + withdrawCleanup: (id) => Ref.update(withdrawn, (items) => [...items, id]), + }), Layer.mock(AgentCrewInstanceService)({ // The store lists only Crews that retired with this Captain, never one retired alone. listRetiredWithCaptain: (threadId) => @@ -437,6 +447,8 @@ it.effect("unarchiving a Captain brings back the Crews that retired with it", () [["thread.unarchive", seatThread]], ); assert.deepStrictEqual(yield* Ref.get(restored), ["crew:with-captain"]); + // The Crew is live again, so an open worktree approval for its archive is withdrawn. + assert.deepStrictEqual(yield* Ref.get(withdrawn), ["crew:with-captain"]); }).pipe(Effect.provide(layer)); }), ); @@ -452,6 +464,7 @@ it.effect("a Captain archived again after an unarchive retires its Crew again", const layer = cascadeLayer.pipe( Layer.provide( Layer.mergeAll( + noWorktrees, Layer.mock(AgentCrewInstanceService)({ listInvolving: () => Effect.map(current, (instance) => [instance]), listRetiredWithCaptain: () => @@ -529,6 +542,7 @@ it.effect("settling a Captain leaves a seat that is waiting on the person or sti const layer = cascadeLayer.pipe( Layer.provide( Layer.mergeAll( + noWorktrees, Layer.mock(AgentCrewInstanceService)({ listInvolving: () => Effect.succeed([trio]) }), Layer.mock(ArchiveCrewService)({}), Layer.mock(ThreadManagementService)({ @@ -589,6 +603,7 @@ it.effect( const layer = cascadeLayer.pipe( Layer.provide( Layer.mergeAll( + noWorktrees, Layer.mock(AgentCrewInstanceService)({ listInvolving: () => Effect.succeed([instance]), }), diff --git a/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.ts b/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.ts index ad1fecbb8fa24..f3b232c43fc2f 100644 --- a/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.ts +++ b/apps/server/src/j5/a2a/CrewCaptainArchiveCascade.ts @@ -15,6 +15,7 @@ import { ThreadManagementService } from "../../orchestration-v2/ThreadManagement import { isAutoSettlementCandidate } from "../../orchestration-v2/ThreadSettlementService.ts"; import { AgentCrewInstanceService, type AgentCrewInstance } from "./AgentCrewInstanceService.ts"; import { ArchiveCrewService } from "./ArchiveCrewService.ts"; +import { CrewWorktrees } from "./CrewWorktrees.ts"; import { participantIdForThread } from "./HomeRegistrar.ts"; import { crewSeatRequestKey, lifecycleCommandId } from "./spawnIds.ts"; import { @@ -75,6 +76,7 @@ export const layer = Layer.effect( Effect.gen(function* () { const crews = yield* AgentCrewInstanceService; const archives = yield* ArchiveCrewService; + const worktrees = yield* CrewWorktrees; const threads = yield* ThreadManagementService; const retire = Effect.fn("j5.a2a.captainArchiveCascade.retire")(function* ( @@ -211,7 +213,9 @@ export const layer = Layer.effect( threadId: member.threadId, }); } - yield* crews.restoreWithCaptain(instance.id); + // Its worktrees are in use again: an open approval to remove them is moot. + if (yield* crews.restoreWithCaptain(instance.id)) + yield* worktrees.withdrawCleanup(instance.id); }), ); yield* Effect.logInfo("J5 Captain unarchived; its Crew came back with it", { diff --git a/apps/server/src/j5/a2a/CrewWorktrees.integration.test.ts b/apps/server/src/j5/a2a/CrewWorktrees.integration.test.ts index 16fc90a35a341..7100f07a4964f 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.integration.test.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.integration.test.ts @@ -18,6 +18,7 @@ import { CrewWorktrees, manualLayer } from "./CrewWorktrees.ts"; import { LedgerProjectId } from "./contracts.ts"; import { A2ALedger, layer as ledgerLayer } from "./LedgerService.ts"; import { participantIdForThread } from "./HomeRegistrar.ts"; +import { ReadChanges } from "./ReadChanges.ts"; it.effect( "records the worktree upstream's launch creates for a seat's first assignment, from the event it commits", @@ -51,6 +52,7 @@ it.effect( Layer.mock(ProviderSessionManagerV2)({}), Layer.mock(GitVcsDriver)({}), Layer.mock(GitManager)({}), + Layer.mock(ReadChanges)({}), NodeServices.layer, ), ), diff --git a/apps/server/src/j5/a2a/CrewWorktrees.test.ts b/apps/server/src/j5/a2a/CrewWorktrees.test.ts index ccd0842967abc..055acc6b4e630 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.test.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.test.ts @@ -49,6 +49,7 @@ 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"; +import { ReadChanges } from "./ReadChanges.ts"; const projectId = ProjectId.make("project:crew-worktrees"); @@ -60,6 +61,7 @@ const gitLayer = GitVcsDriver.layer.pipe( interface SeatThread { archivedAt: DateTime.Utc | null; branch: string | null; + title: string; } /** @@ -108,6 +110,7 @@ const fixture = Effect.gen(function* () { let pullRequestFails = false; const pullRequestLookups: Array = []; const invalidated: Array = []; + const notified: Array> = []; const layer = manualLayer.pipe( Layer.provide( @@ -163,6 +166,9 @@ const fixture = Effect.gen(function* () { // Only the daemon reads the event store, and this is the layer without it. Layer.mock(EventSinkV2)({}), Layer.succeed(GitVcsDriver.GitVcsDriver, git), + Layer.mock(ReadChanges)({ + notify: (...keys) => Effect.sync(() => void notified.push(keys)), + }), Layer.mock(GitManager)({ branchPullRequest: ({ branch }) => { pullRequestLookups.push(branch); @@ -220,6 +226,7 @@ const fixture = Effect.gen(function* () { archivedAt: options.archived === false ? null : DateTime.makeUnsafe("2026-10-27T13:00:00.000Z"), branch, + title: `Thread ${name}`, }); bound.set(threadId, worktree); yield* sql` @@ -275,6 +282,7 @@ const fixture = Effect.gen(function* () { threads, metadataUpdated, invalidated, + notified, pullRequestLookups, bound, setProjectRoots: (roots: typeof otherProjectRoots) => (otherProjectRoots = roots), @@ -766,7 +774,7 @@ it.effect("records only the first worktree path of a seat on a new worktree", () workspace: '{"type":"existing_worktree","worktreePath":"/somewhere"}', }); const unrelated = ThreadId.make("thread:crew-worktrees:not-a-seat"); - f.threads.set(unrelated, { archivedAt: null, branch: "main" }); + f.threads.set(unrelated, { archivedAt: null, branch: "main", title: "Not a seat" }); assert.isFalse( yield* f.service.handleStoredEvent(f.metadataUpdated(sharedSeat.threadId, "main", f.repo)), ); @@ -939,3 +947,441 @@ it.effect( }), ), ); + +const crew = { + crewInstanceId: "crew:one", + archivedAt: "2026-10-27T13:00:00.000Z", + crewName: "Crew One", + projectId: projectId, + captainThreadId: ThreadId.make("thread:crew-worktrees:captain"), +}; + +type Fixture = Effect.Success; + +/** An archive that keeps two worktrees for unfinished work: two uncommitted files, one commit. */ +const archiveKeepingTwo = Effect.fn("test.archiveKeepingTwo")(function* (f: Fixture) { + const edited = yield* f.seat("edited"); + const ahead = yield* f.seat("ahead"); + yield* f.fs.writeFileString(f.path.join(edited.worktree, "tracked.txt"), "edited\n"); + yield* f.fs.writeFileString(f.path.join(edited.worktree, "new.txt"), "new\n"); + yield* f.fs.writeFileString(f.path.join(ahead.worktree, "tracked.txt"), "committed\n"); + yield* f.run(ahead.worktree, ["commit", "-am", "work"]); + yield* f.service.cleanup({ seats: [edited, ahead], crew }); + const [item] = yield* f.service.listCleanups("open"); + return { edited, ahead, item: item! }; +}); + +it.effect("files one approval for every worktree kept for unfinished work, and no other", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const edited = yield* f.seat("edited"); + const ahead = yield* f.seat("ahead"); + const merged = yield* f.seat("merged"); + const shared = yield* f.seat("shared"); + yield* f.fs.writeFileString(f.path.join(edited.worktree, "tracked.txt"), "edited\n"); + yield* f.fs.writeFileString(f.path.join(edited.worktree, "new.txt"), "new\n"); + yield* f.fs.writeFileString(f.path.join(ahead.worktree, "tracked.txt"), "committed\n"); + yield* f.run(ahead.worktree, ["commit", "-am", "work"]); + f.setPullRequest({ + state: "open", + url: "https://example.test/pull/7", + headRef: ahead.branch, + baseRef: "main", + }); + f.setOtherBoundPaths([ + { threadId: ThreadId.make("thread:crew-worktrees:other"), worktreePath: shared.worktree }, + ]); + const seats = [edited, ahead, merged, shared]; + yield* f.service.cleanup({ seats, crew }); + + const open = yield* f.service.listCleanups("open"); + assert.lengthOf(open, 1); + assert.deepInclude(open[0]!, { + crewInstanceId: "crew:one", + crewName: "Crew One", + status: "open", + decidedAt: null, + }); + assert.deepStrictEqual( + open[0]!.entries.map((entry) => [ + entry.threadId, + entry.threadTitle, + entry.branch, + entry.uncommittedFiles, + entry.commitsAhead, + entry.pullRequestUrl, + entry.outcome, + ]), + [ + [ + edited.threadId, + "Thread edited", + edited.branch, + 2, + 0, + "https://example.test/pull/7", + null, + ], + [ahead.threadId, "Thread ahead", ahead.branch, 0, 1, "https://example.test/pull/7", null], + ], + ); + // What the recheck compares against stays on the server. + assert.notProperty(open[0]!.entries[0]!, "headSha"); + assert.deepStrictEqual(f.notified, [["inbox"]]); + + // The archive asked for again while the item is open files nothing more. + yield* f.service.cleanup({ seats, crew }); + assert.lengthOf(yield* f.service.listCleanups("open"), 1); + assert.deepStrictEqual(f.notified, [["inbox"]]); + }), + ), +); + +it.effect( + "removes every worktree of the item when asked to, keeps their branches, and records it", + () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const { edited, ahead, item } = yield* archiveKeepingTwo(f); + const decided = yield* f.service.answerCleanup({ + itemId: item.id, + removePaths: [edited.worktree, ahead.worktree], + }); + assert.strictEqual(decided.status, "decided"); + assert.deepStrictEqual( + decided.entries.map((entry) => [entry.outcome, entry.reason, entry.detail]), + [ + ["removed", null, null], + ["removed", null, null], + ], + ); + assert.isFalse(yield* f.fs.exists(edited.worktree)); + assert.isFalse(yield* f.fs.exists(ahead.worktree)); + // The commit survives on the branch; the uncommitted files are what removal discards. + yield* f.run(f.repo, ["rev-parse", "--verify", `refs/heads/${ahead.branch}`]); + assert.lengthOf(yield* f.service.listCleanups("open"), 0); + const [listed] = yield* f.service.listCleanups("decided"); + assert.deepStrictEqual(listed, decided); + assert.deepStrictEqual(f.notified, [["inbox"], ["inbox"]]); + }), + ), +); + +it.effect("removes only the worktrees picked and keeps the rest", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const { edited, ahead, item } = yield* archiveKeepingTwo(f); + const decided = yield* f.service.answerCleanup({ + itemId: item.id, + removePaths: [ahead.worktree], + }); + assert.deepStrictEqual( + decided.entries.map((entry) => [entry.path, entry.outcome]), + [ + [edited.worktree, "kept"], + [ahead.worktree, "removed"], + ], + ); + assert.isTrue(yield* f.fs.exists(edited.worktree)); + assert.isFalse(yield* f.fs.exists(ahead.worktree)); + }), + ), +); + +it.effect("keeping all clears the item and changes nothing", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const { edited, ahead, item } = yield* archiveKeepingTwo(f); + const decided = yield* f.service.answerCleanup({ itemId: item.id, removePaths: [] }); + assert.deepStrictEqual( + decided.entries.map((entry) => entry.outcome), + ["kept", "kept"], + ); + assert.isTrue(yield* f.fs.exists(edited.worktree)); + assert.isTrue(yield* f.fs.exists(ahead.worktree)); + assert.lengthOf(yield* f.service.listCleanups("open"), 0); + }), + ), +); + +it.effect("an archive that runs again after keeping all files nothing more", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const { edited, ahead, item } = yield* archiveKeepingTwo(f); + yield* f.service.answerCleanup({ itemId: item.id, removePaths: [] }); + + yield* f.service.cleanup({ seats: [edited, ahead], crew }); + assert.lengthOf(yield* f.service.listCleanups("open"), 0); + assert.lengthOf(yield* f.service.listCleanups("decided"), 1); + }), + ), +); + +it.effect("skips a worktree whose files were already changed when they change again", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const { edited, item } = yield* archiveKeepingTwo(f); + // Same files, same status codes: only what is in them differs from what was filed. + yield* f.fs.writeFileString(f.path.join(edited.worktree, "tracked.txt"), "edited again\n"); + yield* f.fs.writeFileString(f.path.join(edited.worktree, "new.txt"), "new again\n"); + + const decided = yield* f.service.answerCleanup({ + itemId: item.id, + removePaths: [edited.worktree], + }); + assert.deepStrictEqual( + decided.entries.map((entry) => [entry.outcome, entry.reason]), + [ + ["skipped", "changed"], + ["kept", null], + ], + ); + assert.strictEqual( + yield* f.fs.readFileString(f.path.join(edited.worktree, "tracked.txt")), + "edited again\n", + ); + }), + ), +); + +it.effect("skips a worktree whose staged content changed under identical working files", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const staged = yield* f.seat("staged"); + const file = f.path.join(staged.worktree, "tracked.txt"); + // The file reads MM both times, with the same working copy; only the staged blob differs. + const stage = Effect.fn("test.stage")(function* (content: string) { + yield* f.fs.writeFileString(file, content); + yield* f.run(staged.worktree, ["add", "tracked.txt"]); + yield* f.fs.writeFileString(file, "working\n"); + }); + yield* stage("staged first\n"); + yield* f.service.cleanup({ seats: [staged], crew }); + const [item] = yield* f.service.listCleanups("open"); + + yield* stage("staged NEW\n"); + const decided = yield* f.service.answerCleanup({ + itemId: item!.id, + removePaths: [staged.worktree], + }); + assert.deepStrictEqual( + decided.entries.map((entry) => [entry.outcome, entry.reason]), + [["skipped", "changed"]], + ); + assert.isTrue(yield* f.fs.exists(staged.worktree)); + }), + ), +); + +it.effect("files nothing for commits its branch does not hold, and never removes them", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const strayed = yield* f.seat("strayed"); + const tracked = f.path.join(strayed.worktree, "tracked.txt"); + yield* f.run(strayed.worktree, ["checkout", "--detach"]); + yield* f.fs.writeFileString(tracked, "detached work\n"); + yield* f.run(strayed.worktree, ["commit", "-am", "work"]); + const results = yield* f.service.cleanup({ seats: [strayed], crew }); + assert.deepStrictEqual( + results.map((result) => [result.outcome, result.reason]), + [["kept", "unverified"]], + ); + assert.lengthOf(yield* f.service.listCleanups("open"), 0); + assert.isTrue(yield* f.fs.exists(strayed.worktree)); + + // The same after an item was filed: the branch moved off the commit the item measured. + const moved = yield* f.seat("moved"); + yield* f.fs.writeFileString(f.path.join(moved.worktree, "tracked.txt"), "committed\n"); + yield* f.run(moved.worktree, ["commit", "-am", "work"]); + yield* f.service.cleanup({ seats: [moved], crew }); + const [item] = yield* f.service.listCleanups("open"); + yield* f.run(moved.worktree, ["checkout", "--detach"]); + yield* f.run(f.repo, ["update-ref", `refs/heads/${moved.branch}`, "main"]); + const decided = yield* f.service.answerCleanup({ + itemId: item!.id, + removePaths: [moved.worktree], + }); + assert.deepStrictEqual( + decided.entries.map((entry) => [entry.outcome, entry.reason]), + [["skipped", "unverified"]], + ); + assert.isTrue(yield* f.fs.exists(moved.worktree)); + }), + ), +); + +it.effect("a Crew archived again after it came back files its own approval", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const first = yield* f.seat("first"); + yield* f.fs.writeFileString(f.path.join(first.worktree, "new.txt"), "new\n"); + yield* f.service.cleanup({ seats: [first], crew }); + assert.lengthOf(yield* f.service.listCleanups("open"), 1); + + // The Captain came back: the open item has nothing left to decide, and shows nowhere. + f.notified.length = 0; + yield* f.service.withdrawCleanup(crew.crewInstanceId); + assert.lengthOf(yield* f.service.listCleanups("open"), 0); + assert.lengthOf(yield* f.service.listCleanups("decided"), 0); + assert.deepStrictEqual(f.notified, [["inbox"]]); + + const second = yield* f.seat("second"); + yield* f.fs.writeFileString(f.path.join(second.worktree, "new.txt"), "new\n"); + const again = { ...crew, archivedAt: "2026-10-28T13:00:00.000Z" }; + yield* f.service.cleanup({ seats: [first, second], crew: again }); + const [item] = yield* f.service.listCleanups("open"); + assert.deepStrictEqual( + item!.entries.map((entry) => entry.threadId), + [first.threadId, second.threadId], + ); + + // The same archive run again files nothing more, and withdrawing leaves an answered item. + yield* f.service.cleanup({ seats: [first, second], crew: again }); + assert.lengthOf(yield* f.service.listCleanups("open"), 1); + yield* f.service.answerCleanup({ itemId: item!.id, removePaths: [] }); + yield* f.service.withdrawCleanup(crew.crewInstanceId); + assert.lengthOf(yield* f.service.listCleanups("decided"), 1); + }), + ), +); + +it.effect("skips a worktree with a nested repository, which cannot be compared by content", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const nested = yield* f.seat("nested"); + const inner = f.path.join(nested.worktree, "inner"); + yield* f.fs.makeDirectory(inner); + yield* f.run(inner, ["init"]); + yield* f.fs.writeFileString(f.path.join(inner, "file.txt"), "x\n"); + yield* f.service.cleanup({ seats: [nested], crew }); + const [item] = yield* f.service.listCleanups("open"); + + const decided = yield* f.service.answerCleanup({ + itemId: item!.id, + removePaths: [nested.worktree], + }); + assert.deepStrictEqual( + decided.entries.map((entry) => [entry.outcome, entry.reason]), + [["skipped", "changed"]], + ); + assert.isTrue(yield* f.fs.exists(nested.worktree)); + }), + ), +); + +it.effect("skips and reports a worktree that changed, is shared, is in use or came back", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const edited = yield* f.seat("edited"); + const ahead = yield* f.seat("ahead"); + const busy = yield* f.seat("busy"); + const back = yield* f.seat("back"); + const plain = yield* f.seat("plain"); + for (const seat of [edited, busy, back, plain]) + yield* f.fs.writeFileString(f.path.join(seat.worktree, "new.txt"), "new\n"); + yield* f.fs.writeFileString(f.path.join(ahead.worktree, "tracked.txt"), "committed\n"); + yield* f.run(ahead.worktree, ["commit", "-am", "work"]); + yield* f.service.cleanup({ seats: [edited, ahead, busy, back, plain], crew }); + const [item] = yield* f.service.listCleanups("open"); + + // After the item was filed: more work, a new commit, an open session, an unarchived thread. + yield* f.fs.writeFileString(f.path.join(edited.worktree, "other.txt"), "more\n"); + yield* f.fs.writeFileString(f.path.join(ahead.worktree, "tracked.txt"), "again\n"); + yield* f.run(ahead.worktree, ["commit", "-am", "more work"]); + yield* f.setSession(busy.worktree); + f.threads.get(back.threadId)!.archivedAt = null; + + const decided = yield* f.service.answerCleanup({ + itemId: item!.id, + removePaths: item!.entries.map((entry) => entry.path), + }); + assert.deepStrictEqual( + decided.entries.map((entry) => [entry.outcome, entry.reason]), + [ + ["skipped", "changed"], + ["skipped", "changed"], + ["skipped", "in_use"], + ["skipped", "shared"], + ["removed", null], + ], + ); + for (const seat of [edited, ahead, busy, back]) + assert.isTrue(yield* f.fs.exists(seat.worktree)); + assert.isFalse(yield* f.fs.exists(plain.worktree)); + }), + ), +); + +it.effect("refuses a second answer, and a path the item does not list", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const { ahead, item } = yield* archiveKeepingTwo(f); + const stray = yield* f.service + .answerCleanup({ itemId: item.id, removePaths: ["/not/listed"] }) + .pipe(Effect.flip); + assert.strictEqual(stray._tag, "CrewWorktreeCleanupPathError"); + assert.lengthOf(yield* f.service.listCleanups("open"), 1); + + yield* f.service.answerCleanup({ itemId: item.id, removePaths: [] }); + const second = yield* f.service + .answerCleanup({ itemId: item.id, removePaths: [ahead.worktree] }) + .pipe(Effect.flip); + assert.strictEqual(second._tag, "CrewWorktreeCleanupAnsweredError"); + assert.strictEqual(second.message, "This worktree cleanup was already answered."); + assert.isTrue(yield* f.fs.exists(ahead.worktree)); + }), + ), +); + +it.effect("reports a removal git refuses and still removes the others", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const { edited, ahead, item } = yield* archiveKeepingTwo(f); + yield* f.run(f.repo, ["worktree", "lock", edited.worktree]); + const decided = yield* f.service.answerCleanup({ + itemId: item.id, + removePaths: [edited.worktree, ahead.worktree], + }); + const [first, second] = decided.entries; + assert.strictEqual(first!.outcome, "failed"); + assert.isString(first!.detail); + assert.isAbove(first!.detail!.length, 0); + assert.strictEqual(second!.outcome, "removed"); + assert.isTrue(yield* f.fs.exists(edited.worktree)); + }), + ), +); + +it.effect("skips a worktree that was removed some other way while the item was open", () => + run( + Effect.gen(function* () { + const f = yield* fixture; + const { edited, ahead, item } = yield* archiveKeepingTwo(f); + yield* f.run(f.repo, ["worktree", "remove", "--force", edited.worktree]); + const decided = yield* f.service.answerCleanup({ + itemId: item.id, + removePaths: [edited.worktree, ahead.worktree], + }); + assert.deepStrictEqual( + decided.entries.map((entry) => [entry.outcome, entry.reason]), + [ + ["skipped", "gone"], + ["removed", null], + ], + ); + }), + ), +); diff --git a/apps/server/src/j5/a2a/CrewWorktrees.ts b/apps/server/src/j5/a2a/CrewWorktrees.ts index a06f772184429..30f4101cec8a8 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.ts @@ -1,18 +1,25 @@ import { OrchestrationV2ProviderSessionJson, + ProjectId, ProviderSessionId, type OrchestrationV2StoredEvent, type TerminalSummary, - type ThreadId, + ThreadId, } from "@t3tools/contracts"; import { CrewSeatWorkspace, + CrewWorktreeCleanupEntry, type CrewArchiveWorktree, type CrewArchiveWorktreeEstimate, + type CrewWorktreeCleanupItem, type CrewWorktreeReason, } from "@t3tools/contracts/j5"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- a synchronous digest and id; no Crypto service is wired into this layer. +import * as NodeCrypto from "node:crypto"; +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as Data from "effect/Data"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -23,6 +30,7 @@ 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 type { SqlError } from "effect/sql/SqlError"; import * as GitManager from "../../git/GitManager.ts"; import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts"; @@ -35,8 +43,51 @@ import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts"; import { withWorkspaceLease } from "../../workspace/workspaceLease.ts"; import { isSeatWorktreeCreation } from "./CrewSeatPreparation.ts"; import { readEventStoreHighWater } from "./eventStoreHighWater.ts"; +import { ReadChanges } from "./ReadChanges.ts"; const decodeSeatWorkspace = Schema.decodeUnknownOption(Schema.fromJsonString(CrewSeatWorkspace)); + +/** What the recheck compares a worktree against: its commit and its uncommitted work when the archive kept it. */ +const StoredCleanupEntry = Schema.Struct({ + ...CrewWorktreeCleanupEntry.fields, + headSha: Schema.String, + statusDigest: Schema.String, +}); +type StoredCleanupEntry = typeof StoredCleanupEntry.Type; +const StoredCleanupEntries = Schema.fromJsonString(Schema.Array(StoredCleanupEntry)); +const decodeEntries = Schema.decodeUnknownEffect(StoredCleanupEntries); +const encodeEntries = Schema.encodeEffect(StoredCleanupEntries); + +const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error)); + +class CrewWorktreeCleanupNotFoundError extends Data.TaggedError( + "CrewWorktreeCleanupNotFoundError", +)<{ readonly itemId: string }> { + override get message(): string { + return `There is no worktree cleanup item ${this.itemId}.`; + } +} + +class CrewWorktreeCleanupAnsweredError extends Data.TaggedError( + "CrewWorktreeCleanupAnsweredError", +)<{ readonly itemId: string }> { + override get message(): string { + return "This worktree cleanup was already answered."; + } +} + +class CrewWorktreeCleanupPathError extends Data.TaggedError("CrewWorktreeCleanupPathError")<{ + readonly path: string; +}> { + override get message(): string { + return `${this.path} is not one of this cleanup's worktrees.`; + } +} + +export type CrewWorktreeCleanupError = + | CrewWorktreeCleanupNotFoundError + | CrewWorktreeCleanupAnsweredError + | CrewWorktreeCleanupPathError; const decodeSession = Schema.decodeUnknownEffect( Schema.fromJsonString(OrchestrationV2ProviderSessionJson), ); @@ -66,8 +117,13 @@ interface RecordedWorktree { type Verdict = | { readonly kind: "gone" } | { readonly kind: "keep"; readonly reason: KeepReason } + /** Only a recheck against a stored baseline says this. */ + | { readonly kind: "changed" } | { readonly kind: "remove"; readonly headSha: string }; +/** What a person's answer did with one worktree. */ +type CleanupResult = Pick; + export interface CrewWorktreesShape { /** * Records the worktree ThreadLaunch creates for a Crew seat, when the event is the metadata @@ -97,7 +153,37 @@ export interface CrewWorktreesShape { */ readonly cleanup: (input: { readonly seats: ReadonlyArray; + /** + * Given, the worktrees kept for unfinished work (uncommitted changes, unmerged commits) are + * also filed as one Inbox approval for this archive of the Crew, unless it already has one. + */ + readonly crew?: { + readonly crewInstanceId: string; + /** The Crew's archive stamp: the same archive run again files nothing, a later one files its own. */ + readonly archivedAt: string; + readonly crewName: string; + readonly projectId: string; + readonly captainThreadId: ThreadId; + }; }) => Effect.Effect>; + /** The cleanup approvals, open or decided, newest first. */ + readonly listCleanups: ( + status: "open" | "decided", + ) => Effect.Effect, SqlError>; + /** + * The Crew came back (its Captain was unarchived): an open approval for its earlier archive no + * longer has anything to decide, so it is dropped. An answered one stays as the record. + */ + readonly withdrawCleanup: (crewInstanceId: string) => Effect.Effect; + /** + * A person's answer: removes the listed worktrees of the item, keeps the rest, and records what + * happened to each. Each is checked again first, against what the archive measured, and one + * that changed is skipped. The first answer wins; the item keeps branches either way. + */ + readonly answerCleanup: (input: { + readonly itemId: string; + readonly removePaths: 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. @@ -119,6 +205,7 @@ const makeLayer = (daemon: boolean) => CrewWorktrees, Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; + const changes = yield* ReadChanges; const threads = yield* ThreadManagementService; const projects = yield* ProjectService; const projections = yield* ProjectionStore.ProjectionStoreV2; @@ -321,8 +408,8 @@ const makeLayer = (daemon: boolean) => }); /** 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({ + const localChanges = (worktreePath: string) => + git.execute({ operation: "CrewWorktrees.localChanges", cwd: worktreePath, args: [ @@ -334,9 +421,73 @@ const makeLayer = (daemon: boolean) => ], maxOutputBytes: 64 * 1024, }); + + const hasBlockingChanges = Effect.fnUntraced(function* (worktreePath: string) { + const status = yield* localChanges(worktreePath); return status.stdoutTruncated || status.stdout.split("\0").some((record) => record !== ""); }); + const digestOf = (text: string) => NodeCrypto.createHash("sha256").update(text).digest("hex"); + + /** + * What the worktree holds uncommitted, by content, since status lists only names and codes: + * the index tree is part of it so a changed staged blob shows. Cut-off status, a nested + * repository, or an index with no tree (unmerged) cannot be compared, so it never matches + * again and the worktree is kept. + */ + const snapshotOf = Effect.fnUntraced(function* (worktreePath: string) { + const status = yield* localChanges(worktreePath); + const unmatched = () => `unverifiable:${NodeCrypto.randomUUID()}`; + if (status.stdoutTruncated) return { status, digest: unmatched() }; + // A deleted file has no content to read; its status code already says so. + const paths = status.stdout + .split("\0") + .filter((record) => /^[ MTADRCU?!]{2} /.test(record) && !record.slice(0, 2).includes("D")) + .map((record) => record.slice(3)); + if (paths.some((changed) => changed.endsWith("/"))) return { status, digest: unmatched() }; + const [index, hashed] = yield* Effect.all([ + git.execute({ + operation: "CrewWorktrees.index", + cwd: worktreePath, + args: ["write-tree"], + allowNonZeroExit: true, + }), + paths.length === 0 + ? Effect.succeed({ exitCode: 0, stdout: "", stdoutTruncated: false }) + : git.execute({ + operation: "CrewWorktrees.contents", + cwd: worktreePath, + args: ["hash-object", "--", ...paths], + allowNonZeroExit: true, + }), + ]); + return { + status, + digest: + index.exitCode === 0 && hashed.exitCode === 0 && !hashed.stdoutTruncated + ? digestOf(`${status.stdout}\n${hashed.stdout}\n${index.stdout}`) + : unmatched(), + }; + }); + + /** + * HEAD is on the branch the approval says removal keeps. A seat that detached or switched + * branches and then committed has commits only the reflog would hold once the worktree goes. + */ + const branchHoldsHead = Effect.fnUntraced(function* ( + worktreePath: string, + branch: string | null, + ) { + if (branch === null) return false; + const held = yield* git.execute({ + operation: "CrewWorktrees.branchHoldsHead", + cwd: worktreePath, + args: ["merge-base", "--is-ancestor", "HEAD", `refs/heads/${branch}`], + allowNonZeroExit: true, + }); + return held.exitCode === 0; + }); + /** * 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. @@ -394,6 +545,8 @@ const makeLayer = (daemon: 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; + /** Given, the worktree is approved for removal as it was measured: it may only be unchanged since. */ + readonly baseline?: Pick; } const threadFacts = (threadId: ThreadId) => @@ -421,8 +574,26 @@ const makeLayer = (daemon: boolean) => return { kind: "keep", reason: "shared" } satisfies Verdict; if ((yield* sessionOpenIn(worktreePath)) || (yield* terminalOpenIn(worktreePath))) return { kind: "keep", reason: "in_use" } satisfies Verdict; + if (context.baseline !== undefined) { + if (!(yield* branchHoldsHead(worktreePath, branch))) + return { kind: "keep", reason: "unverified" } satisfies Verdict; + const [head, snapshot] = yield* Effect.all([ + git.resolveCommit({ cwd: worktreePath, revision: "HEAD" }), + snapshotOf(worktreePath), + ]); + return head.commitSha === context.baseline.headSha && + snapshot.digest === context.baseline.statusDigest + ? ({ kind: "remove", headSha: head.commitSha } satisfies Verdict) + : ({ kind: "changed" } satisfies Verdict); + } + // What is kept for unfinished work is offered for removal while its branch stays, so + // work the branch does not hold is never offered. + const unfinished = (reason: "uncommitted_changes" | "unmerged_commits") => + branchHoldsHead(worktreePath, branch).pipe( + Effect.map((held): Verdict => ({ kind: "keep", reason: held ? reason : "unverified" })), + ); if (yield* hasBlockingChanges(worktreePath)) - return { kind: "keep", reason: "uncommitted_changes" } satisfies Verdict; + return yield* unfinished("uncommitted_changes"); const unmerged = context.checkMerged ? yield* mergeKeepReason({ worktreePath, @@ -432,6 +603,7 @@ const makeLayer = (daemon: boolean) => fetched: context.fetched, }) : null; + if (unmerged === "unmerged_commits") return yield* unfinished(unmerged); 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; @@ -483,15 +655,114 @@ const makeLayer = (daemon: boolean) => return again.kind === "remove" ? ({ kind: "keep", reason: "unverified" } satisfies Verdict) : again; - yield* git.removeWorktree({ cwd: repositoryRoot, path: worktreePath }); + // An approved worktree has the uncommitted changes the person agreed to discard. + yield* git.removeWorktree({ + cwd: repositoryRoot, + path: worktreePath, + force: context.baseline !== undefined, + }); yield* gitManager.invalidateStatus(repositoryRoot); return first; }), ); }); + interface UnfinishedWorktree { + readonly threadId: ThreadId; + readonly threadTitle: string; + readonly path: string; + readonly branch: string | null; + readonly repositoryRoot: string; + } + + /** Measured once, as the archive keeps the worktree; the recheck compares against the commit and status taken here. */ + const measure = Effect.fnUntraced(function* (worktree: UnfinishedWorktree) { + const worktreePath = path.resolve(worktree.path); + const [{ status, digest }, head] = yield* Effect.all([ + snapshotOf(worktreePath), + git.resolveCommit({ cwd: worktreePath, revision: "HEAD" }), + ]); + const commitsAhead = yield* Effect.gen(function* () { + const remote = yield* git.resolvePrimaryRemoteName(worktree.repositoryRoot); + const defaultBranch = yield* git.resolveDefaultBranchName( + worktree.repositoryRoot, + remote, + ); + if (defaultBranch === null) return null; + const counted = yield* git.execute({ + operation: "CrewWorktrees.commitsAhead", + cwd: worktreePath, + args: ["rev-list", "--count", `refs/remotes/${remote}/${defaultBranch}..HEAD`], + }); + return Number.parseInt(counted.stdout.trim(), 10); + }).pipe(Effect.catchCause(() => Effect.succeed(null))); + const pullRequestUrl = + worktree.branch === null + ? null + : yield* gitManager + .branchPullRequest({ cwd: worktreePath, branch: worktree.branch }) + .pipe( + Effect.map((pullRequest) => pullRequest?.url ?? null), + Effect.catchCause(() => Effect.succeed(null)), + ); + return { + threadId: worktree.threadId, + threadTitle: worktree.threadTitle, + path: worktree.path, + branch: worktree.branch, + uncommittedFiles: status.stdout + .split("\0") + .filter((record) => /^[ MTADRCU?!]{2} /.test(record)).length, + commitsAhead: Number.isNaN(commitsAhead) ? null : commitsAhead, + pullRequestUrl, + outcome: null, + reason: null, + detail: null, + headSha: head.commitSha, + statusDigest: digest, + } satisfies StoredCleanupEntry; + }); + + /** One approval per archive of a Crew, answered or not, so the same archive run again files nothing. */ + const fileCleanup = Effect.fnUntraced(function* ( + crew: NonNullable[0]["crew"]>, + unfinished: ReadonlyArray, + ) { + const entries = yield* Effect.forEach(unfinished, measure); + const filed = yield* sql<{ readonly id: string }>` + INSERT INTO j5_crew_worktree_cleanup ( + id, crew_instance_id, crew_name, project_id, captain_thread_id, archived_at, filed_at, + entries_json + ) + VALUES ( + ${NodeCrypto.randomUUID()}, ${crew.crewInstanceId}, ${crew.crewName}, ${crew.projectId}, + ${crew.captainThreadId}, ${crew.archivedAt}, ${DateTime.formatIso(yield* DateTime.now)}, + ${yield* encodeEntries(entries)} + ) + ON CONFLICT DO NOTHING + RETURNING id + `; + if (filed.length > 0) yield* changes.notify("inbox"); + }); + + const withdrawCleanup: CrewWorktreesShape["withdrawCleanup"] = Effect.fn( + "j5.a2a.crewWorktrees.withdrawCleanup", + )( + function* (crewInstanceId) { + const withdrawn = yield* sql<{ readonly id: string }>` + DELETE FROM j5_crew_worktree_cleanup + WHERE crew_instance_id = ${crewInstanceId} AND decided_at IS NULL + RETURNING id + `; + if (withdrawn.length > 0) yield* changes.notify("inbox"); + }, + Effect.catchCause((cause) => + Effect.logWarning("J5 Crew worktree cleanup approval not withdrawn", { cause }), + ), + ); + const cleanup: CrewWorktreesShape["cleanup"] = Effect.fn("j5.a2a.crewWorktrees.cleanup")( - function* ({ seats }) { + function* ({ seats, crew }) { // 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 = { @@ -501,6 +772,7 @@ const makeLayer = (daemon: boolean) => checkMerged: true, }; const results: Array = []; + const unfinished: Array = []; for (const seat of seats) { const record = yield* readRecord(seat.threadId); if (record === null) continue; @@ -528,15 +800,30 @@ const makeLayer = (daemon: boolean) => ), ); if (done === "failed") results.push(outcome({ outcome: "failed", reason: "failed" })); - else if (done.kind === "keep") + else if (done.kind === "keep") { results.push(outcome({ outcome: "kept", reason: done.reason })); - else if (done.kind === "remove") { + // Shared, in use and unverified worktrees are not unfinished work: nothing to approve. + if (done.reason === "uncommitted_changes" || done.reason === "unmerged_commits") + unfinished.push({ + threadId: seat.threadId, + threadTitle: thread.success.title, + path: record.path, + branch, + repositoryRoot, + }); + } else if (done.kind === "remove") { yield* Effect.logInfo("J5 Crew worktree removed after archive", { threadId: seat.threadId, }); results.push(outcome({ outcome: "removed", reason: null })); } } + if (crew !== undefined && unfinished.length > 0) + yield* fileCleanup(crew, unfinished).pipe( + Effect.catchCause((cause) => + Effect.logWarning("J5 Crew worktree cleanup approval not filed", { cause }), + ), + ); return results; }, Effect.catchCause((cause) => @@ -589,6 +876,146 @@ const makeLayer = (daemon: boolean) => ), ); + interface CleanupRow { + readonly id: string; + readonly crew_instance_id: string; + readonly crew_name: string; + readonly project_id: string; + readonly captain_thread_id: string; + readonly filed_at: string; + readonly decided_at: string | null; + readonly entries_json: string; + } + + /** What a client sees: the entries without the baseline the recheck keeps to itself. */ + const projectCleanup = ( + row: CleanupRow, + entries: ReadonlyArray, + ): CrewWorktreeCleanupItem => ({ + id: row.id, + crewInstanceId: row.crew_instance_id, + crewName: row.crew_name, + projectId: row.project_id, + captainThreadId: ThreadId.make(row.captain_thread_id), + filedAt: row.filed_at, + status: row.decided_at === null ? "open" : "decided", + decidedAt: row.decided_at, + entries: entries.map( + ({ headSha: _headSha, statusDigest: _statusDigest, ...entry }) => entry, + ), + }); + + const listCleanups: CrewWorktreesShape["listCleanups"] = Effect.fn( + "j5.a2a.crewWorktrees.listCleanups", + )(function* (status) { + const rows = yield* sql` + SELECT * FROM j5_crew_worktree_cleanup + WHERE (decided_at IS NULL) = (${status} = 'open') + ORDER BY COALESCE(decided_at, filed_at) DESC + `; + return yield* Effect.forEach(rows, (row) => + decodeEntries(row.entries_json).pipe( + Effect.map((entries) => projectCleanup(row, entries)), + Effect.orDie, + ), + ); + }); + + const skippedFor = (reason: KeepReason): CleanupResult => ({ + outcome: "skipped", + reason: reason === "shared" || reason === "in_use" ? reason : "unverified", + detail: null, + }); + + /** Checked again and removed under the same lease and re-read as the archive's own removal. */ + const removeApproved = Effect.fnUntraced(function* ( + projectId: string, + entry: StoredCleanupEntry, + ) { + const repositoryRoot = yield* repositoryRootOf(ProjectId.make(projectId)).pipe( + Effect.orElseSucceed(() => null), + ); + if (repositoryRoot === null) return skippedFor("unverified"); + const done = yield* remove( + { threadId: entry.threadId, path: entry.path, createdBranch: entry.branch }, + entry.branch, + repositoryRoot, + { + own: new Set(), + refresh: false, + fetched: new Set(), + checkMerged: false, + baseline: entry, + }, + ).pipe( + Effect.catchCause((cause) => + Effect.logWarning("J5 Crew worktree removal failed", { + threadId: entry.threadId, + cause, + }).pipe( + Effect.as({ + kind: "failed" as const, + detail: errorText(Cause.squash(cause)), + }), + ), + ), + ); + switch (done.kind) { + case "failed": + return { + outcome: "failed", + reason: null, + detail: done.detail, + } satisfies CleanupResult; + case "remove": + return { outcome: "removed", reason: null, detail: null } satisfies CleanupResult; + case "gone": + return { outcome: "skipped", reason: "gone", detail: null } satisfies CleanupResult; + case "changed": + return { outcome: "skipped", reason: "changed", detail: null } satisfies CleanupResult; + case "keep": + return skippedFor(done.reason); + } + }); + + const answerCleanup: CrewWorktreesShape["answerCleanup"] = Effect.fn( + "j5.a2a.crewWorktrees.answerCleanup", + )(function* ({ itemId, removePaths }) { + const [row] = yield* sql` + SELECT * FROM j5_crew_worktree_cleanup WHERE id = ${itemId} + `; + if (row === undefined) return yield* new CrewWorktreeCleanupNotFoundError({ itemId }); + if (row.decided_at !== null) return yield* new CrewWorktreeCleanupAnsweredError({ itemId }); + const entries = yield* decodeEntries(row.entries_json).pipe(Effect.orDie); + for (const removePath of removePaths) + if (!entries.some((entry) => entry.path === removePath)) + return yield* new CrewWorktreeCleanupPathError({ path: removePath }); + // The claim comes before any removal, so a second answer meanwhile is refused. + const decidedAt = DateTime.formatIso(yield* DateTime.now); + const claimed = yield* sql<{ readonly id: string }>` + UPDATE j5_crew_worktree_cleanup SET decided_at = ${decidedAt} + WHERE id = ${itemId} AND decided_at IS NULL + RETURNING id + `; + if (claimed.length === 0) return yield* new CrewWorktreeCleanupAnsweredError({ itemId }); + const approved = new Set(removePaths); + const decided: Array = []; + for (const entry of entries) + decided.push({ + ...entry, + ...(approved.has(entry.path) + ? yield* removeApproved(row.project_id, entry) + : ({ outcome: "kept", reason: null, detail: null } satisfies CleanupResult)), + }); + yield* sql` + UPDATE j5_crew_worktree_cleanup + SET entries_json = ${yield* encodeEntries(decided).pipe(Effect.orDie)} + WHERE id = ${itemId} + `; + yield* changes.notify("inbox"); + return projectCleanup({ ...row, decided_at: decidedAt }, decided); + }); + 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. @@ -618,6 +1045,9 @@ const makeLayer = (daemon: boolean) => closeSessions, cleanup, estimate, + withdrawCleanup, + listCleanups, + answerCleanup, }); }), ); diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index 881c99d283f6c..6a9d999f9fbba 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -142,6 +142,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () { migration_id: 48, name: "CrewApprovalMode" }, { migration_id: 49, name: "CrewSeatActivation" }, { migration_id: 50, name: "CrewWorktrees" }, + { migration_id: 51, name: "CrewWorktreeCleanup" }, ]); assert.deepStrictEqual( migrationEntries.map(([id, name]) => [id, name]), @@ -196,6 +197,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () [48, "CrewApprovalMode"], [49, "CrewSeatActivation"], [50, "CrewWorktrees"], + [51, "CrewWorktreeCleanup"], ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), @@ -1444,7 +1446,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, 50, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, ], ); 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 47924a2438a0b..c545eda976d52 100644 --- a/apps/server/src/j5/a2a/Migrations.ts +++ b/apps/server/src/j5/a2a/Migrations.ts @@ -51,6 +51,7 @@ 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"; +import Migration0051 from "./migrations/051_CrewWorktreeCleanup.ts"; export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations"; @@ -112,6 +113,7 @@ export const migrationEntries = [ [48, "CrewApprovalMode", Migration0048], [49, "CrewSeatActivation", Migration0049], [50, "CrewWorktrees", Migration0050], + [51, "CrewWorktreeCleanup", Migration0051], ] as const; const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/j5/a2a/clientActionRpc.ts b/apps/server/src/j5/a2a/clientActionRpc.ts index 747301f292772..88d580342ef18 100644 --- a/apps/server/src/j5/a2a/clientActionRpc.ts +++ b/apps/server/src/j5/a2a/clientActionRpc.ts @@ -2,6 +2,7 @@ import { AuthAccessWriteScope, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, + AuthSettingsWriteScope, } from "@t3tools/contracts"; import { J5ActionError, @@ -14,6 +15,7 @@ import { type CrewProposalResolveRequest, type CrewRuntimeRequestRespondRequest, type CrewStopRequest, + type CrewWorktreeCleanupAnswerRequest, type IssuePeerCredentialRequest, type PeerProbeRequest, type RemovePeerRequest, @@ -45,6 +47,7 @@ export const CLIENT_ACTION_RPC_SCOPES = { [METHODS.archiveCrew]: AuthOrchestrationOperateScope, [METHODS.respondCrewRuntimeRequest]: AuthOrchestrationOperateScope, [METHODS.answerHumanExchange]: AuthOrchestrationOperateScope, + [METHODS.answerCrewWorktreeCleanup]: AuthSettingsWriteScope, [METHODS.issuePeerCredential]: AuthAccessWriteScope, [METHODS.addPeer]: AuthAccessWriteScope, [METHODS.removePeer]: AuthAccessWriteScope, @@ -175,6 +178,21 @@ export const makeClientActionRpcHandlers = Effect.fn("j5.makeClientActionRpcHand .pipe(Effect.catch(failAsJ5ActionError({ failed: "Human inbox operation failed." }))), ), ), + // Removing worktrees is the Owner's call, like archiving the Crew that left them. + [METHODS.answerCrewWorktreeCleanup]: (input: CrewWorktreeCleanupAnswerRequest) => + services(requireOwner(session)).pipe( + Effect.andThen(actions.answerCrewWorktreeCleanup(input)), + Effect.catch( + failAsJ5ActionError({ + refusals: [ + "CrewWorktreeCleanupNotFoundError", + "CrewWorktreeCleanupAnsweredError", + "CrewWorktreeCleanupPathError", + ], + failed: "Answering the worktree cleanup failed.", + }), + ), + ), [METHODS.issuePeerCredential]: (input: IssuePeerCredentialRequest) => peers.issueCredential(input).pipe(Effect.catch(peerFailure("credential issuance"))), [METHODS.addPeer]: (input: AddPeerRequest) => diff --git a/apps/server/src/j5/a2a/clientReadRpc.test.ts b/apps/server/src/j5/a2a/clientReadRpc.test.ts index 3de5c225d6599..0bafdbdf7275a 100644 --- a/apps/server/src/j5/a2a/clientReadRpc.test.ts +++ b/apps/server/src/j5/a2a/clientReadRpc.test.ts @@ -49,8 +49,8 @@ const SESSION = { subject: "one-time-token", }; -/** A connection that is the given person's device, or no one's. */ -const connectionOf = (personId: ParticipantId | null) => +/** A connection that is the given person's device at a level of the server, or no one's. */ +const connectionOf = (personId: ParticipantId | null, level: "owner" | "collaborator" = "owner") => Layer.mock(PersonAccess)({ sessionReach: () => Effect.succeed( @@ -60,8 +60,8 @@ const connectionOf = (personId: ParticipantId | null) => kind: "person" as const, person: { personId, displayName: null, firstOwner: true }, levels: [], - serverLevel: "owner" as const, - highest: "owner" as const, + serverLevel: level, + highest: level, ceiling: null, }, ), @@ -74,6 +74,7 @@ const writesEverywhere = Layer.mock(SharedThreads)({}); const handlersOver = ( reads: Layer.Layer, personId: ParticipantId | null = LOCAL_PERSON, + level: "owner" | "collaborator" = "owner", ) => makeClientReadRpcHandlers(SESSION).pipe( Effect.provide( @@ -81,7 +82,7 @@ const handlersOver = ( reads, Layer.mock(PeerAdminService)({}), readChangesLayer, - connectionOf(personId), + connectionOf(personId, level), writesEverywhere, ), ), @@ -205,6 +206,7 @@ it.effect("keeps identity requests exact, ordered, and total, and drops an id th return Effect.succeed({ entries }); }, openInboxCount: (personId) => Effect.succeed({ personId: personId ?? alpha, count: 3 }), + crewWorktreeCleanups: () => Effect.succeed([]), }), ); const identities = handlers[METHODS.readParticipantIdentities]; @@ -226,6 +228,43 @@ it.effect("keeps identity requests exact, ordered, and total, and drops an id th }), ); +const openCleanup = { + id: "cleanup:1", + crewInstanceId: "crew:1", + crewName: "Crew One", + projectId: "project:gate", + captainThreadId: ThreadId.make("thread:captain"), + filedAt: "2026-10-27T12:00:00.000Z", + status: "open" as const, + decidedAt: null, + entries: [], +}; +const cleanupReads = Layer.mock(ClientReadsService)({ + openInboxCount: (personId) => + Effect.succeed({ personId: personId ?? ParticipantId.make("agent:none"), count: 3 }), + crewWorktreeCleanups: () => Effect.succeed([openCleanup]), +}); + +it.effect("counts and lists an open worktree cleanup for an Owner, who answers it", () => + Effect.gen(function* () { + const handlers = yield* handlersOver(cleanupReads); + assert.strictEqual((yield* handlers[METHODS.readOpenInboxCount]({})).count, 4); + assert.deepStrictEqual(yield* handlers[METHODS.listCrewWorktreeCleanups]({ status: "open" }), { + items: [openCleanup], + }); + }), +); + +it.effect("neither counts nor lists a worktree cleanup for someone who cannot answer it", () => + Effect.gen(function* () { + const handlers = yield* handlersOver(cleanupReads, LOCAL_PERSON, "collaborator"); + assert.strictEqual((yield* handlers[METHODS.readOpenInboxCount]({})).count, 3); + assert.deepStrictEqual(yield* handlers[METHODS.listCrewWorktreeCleanups]({ status: "open" }), { + items: [], + }); + }), +); + const proposal: CrewProposal = { id: "crew:j5:a2a:mcp:j5-crew-proposal:proposal:req", projectId: LedgerProjectId.make("project:gate"), diff --git a/apps/server/src/j5/a2a/clientReadRpc.ts b/apps/server/src/j5/a2a/clientReadRpc.ts index 8f9d45b157d80..c743ac5f52653 100644 --- a/apps/server/src/j5/a2a/clientReadRpc.ts +++ b/apps/server/src/j5/a2a/clientReadRpc.ts @@ -2,6 +2,7 @@ import { AuthAccessReadScope, AuthOrchestrationReadScope, ThreadId } from "@t3to import { J5_CLIENT_READ_WS_METHODS, type CrewArchiveWorktreesRequest, + type CrewWorktreeCleanupListRequest, type FleetReadRequest, type HumanInboxListRequest, type OpenInboxCountRequest, @@ -14,7 +15,7 @@ import * as Schema from "effect/Schema"; import { failAsJ5ActionError } from "../rpcActionError.ts"; import { connectionPersonId } from "../sharing/connectionPerson.ts"; -import { connectionReads, connectionWrites } from "../sharing/connectionWriter.ts"; +import { connectionReads, connectionWrites, isOwner } from "../sharing/connectionWriter.ts"; import { PersonAccess, type SessionIdentity } from "../sharing/PersonAccess.ts"; import { SharedThreads } from "../sharing/SharedThreads.ts"; import { ClientReadsService } from "./ClientReadsService.ts"; @@ -38,6 +39,7 @@ export const CLIENT_READ_RPC_SCOPES = { [METHODS.listSpawnedChildren]: AuthOrchestrationReadScope, [METHODS.readPreArchiveFacts]: AuthOrchestrationReadScope, [METHODS.readCrewArchiveWorktrees]: AuthOrchestrationReadScope, + [METHODS.listCrewWorktreeCleanups]: AuthOrchestrationReadScope, [METHODS.readParticipantIdentities]: AuthOrchestrationReadScope, [METHODS.listPeers]: AuthAccessReadScope, [METHODS.subscribeReadChanges]: AuthOrchestrationReadScope, @@ -78,6 +80,16 @@ export const makeClientReadRpcHandlers = Effect.fn("j5.makeClientReadRpcHandlers Effect.provideService(PersonAccess, people), Effect.provideService(SharedThreads, shared), ); + // Listed to Owners only: removing worktrees is the Owner's call, so no one else has anything + // to answer, and the count is of what waits on the person. + const cleanupsReached = Effect.fn("j5.a2a.clientReadRpc.cleanupsReached")(function* ( + status: CrewWorktreeCleanupListRequest["status"], + ) { + if (!(yield* isOwner(session).pipe(Effect.provideService(PersonAccess, people)))) return []; + return yield* clientReads + .crewWorktreeCleanups(status) + .pipe(Effect.catch(failed("Reading worktree cleanups failed."))); + }); return { [METHODS.listHumanInbox]: (input: HumanInboxListRequest) => personOf.pipe( @@ -92,7 +104,18 @@ export const makeClientReadRpcHandlers = Effect.fn("j5.makeClientReadRpcHandlers Effect.flatMap((personId) => clientReads.openInboxCount(personId).pipe(Effect.catch(inboxFailure)), ), + // An open worktree cleanup waits on a person like an ask does. + Effect.flatMap((counted) => + cleanupsReached("open").pipe( + Effect.map((open) => ({ ...counted, count: counted.count + open.length })), + ), + ), ), + [METHODS.listCrewWorktreeCleanups]: Effect.fn("j5.a2a.clientReadRpc.listCrewWorktreeCleanups")( + function* (input: CrewWorktreeCleanupListRequest) { + return { items: yield* cleanupsReached(input.status) }; + }, + ), [METHODS.listCrewProposals]: Effect.fn("j5.a2a.clientReadRpc.listCrewProposals")(function* () { const listed = yield* clientReads.crewProposals.pipe( Effect.catch(failed("Reading crew proposals failed.")), diff --git a/apps/server/src/j5/a2a/mcp/tools.test.ts b/apps/server/src/j5/a2a/mcp/tools.test.ts index f57e7eb52d2e4..56543244506dc 100644 --- a/apps/server/src/j5/a2a/mcp/tools.test.ts +++ b/apps/server/src/j5/a2a/mcp/tools.test.ts @@ -103,6 +103,7 @@ it("publishes the ratified single-target lifecycle contracts fail-closed", () => assert.notProperty(spawnSchema.properties ?? {}, "agent"); assert.include(J5SpawnAgentTool.description ?? "", "one of that persona's declared routes"); assert.property(stopSchema.properties ?? {}, "client_request_id"); + // Exact on purpose: no tool answers the Inbox's worktree cleanup approval; only a person can. assert.sameMembers(Object.keys(J5Toolkit.tools), [ "j5_playbook_back", "j5_playbook_cancel", diff --git a/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.test.ts b/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.test.ts new file mode 100644 index 0000000000000..6a3651dc2d5bf --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.test.ts @@ -0,0 +1,36 @@ +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 cleanup table with one item per archive of a Crew, and is safe to run again", + () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runJ5A2AMigrations({ toMigrationInclusive: 50 }); + yield* runJ5A2AMigrations(); + yield* runJ5A2AMigrations(); + + assert.deepStrictEqual(yield* sql`SELECT * FROM j5_crew_worktree_cleanup`, []); + const file = (id: string, crew: string, archivedAt = "2026-10-26T00:00:00.000Z") => sql` + INSERT INTO j5_crew_worktree_cleanup ( + id, crew_instance_id, crew_name, project_id, captain_thread_id, archived_at, filed_at, + entries_json + ) + VALUES ( + ${id}, ${crew}, 'Crew', 'project:one', 'thread:captain', ${archivedAt}, + '2026-10-27T00:00:00.000Z', '[]' + ) + `; + yield* file("cleanup:1", "crew:one"); + yield* file("cleanup:2", "crew:two"); + yield* sql`UPDATE j5_crew_worktree_cleanup SET decided_at = '2026-10-27T01:00:00.000Z' WHERE id = 'cleanup:1'`; + const again = yield* Effect.exit(file("cleanup:3", "crew:one")); + assert.strictEqual(again._tag, "Failure"); + // The Crew archived a second time is a new archive. + yield* file("cleanup:4", "crew:one", "2026-10-28T00:00:00.000Z"); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), +); diff --git a/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.ts b/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.ts new file mode 100644 index 0000000000000..e10662684ae85 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.ts @@ -0,0 +1,28 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * The Inbox approval an archive files for the worktrees it kept: one row per item, open until + * `decided_at` is set. An archive (the Crew's `archived_at`) has at most one item, so running it + * again files nothing, while a Crew restored and archived again files its own. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql` + CREATE TABLE j5_crew_worktree_cleanup ( + id TEXT PRIMARY KEY, + crew_instance_id TEXT NOT NULL, + crew_name TEXT NOT NULL, + project_id TEXT NOT NULL, + captain_thread_id TEXT NOT NULL, + archived_at TEXT NOT NULL, + filed_at TEXT NOT NULL, + decided_at TEXT, + entries_json TEXT NOT NULL + ) + `; + yield* sql` + CREATE UNIQUE INDEX j5_crew_worktree_cleanup_crew + ON j5_crew_worktree_cleanup (crew_instance_id, archived_at) + `; +}); diff --git a/apps/server/src/j5/a2a/runtimeLayer.ts b/apps/server/src/j5/a2a/runtimeLayer.ts index 222505c1b9833..5223d408cfba3 100644 --- a/apps/server/src/j5/a2a/runtimeLayer.ts +++ b/apps/server/src/j5/a2a/runtimeLayer.ts @@ -149,7 +149,10 @@ const makeJ5A2AAuxiliaryLayer = ( 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)); + const crewWorktreesProvided = crewWorktreesLayer.pipe( + Layer.provide(projectionStoreLayer), + Layer.provide(readChangesLayer), + ); // 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( diff --git a/apps/server/src/j5/sharing/connectionWriter.ts b/apps/server/src/j5/sharing/connectionWriter.ts index a2eedf1a2de3b..bbf947cf09762 100644 --- a/apps/server/src/j5/sharing/connectionWriter.ts +++ b/apps/server/src/j5/sharing/connectionWriter.ts @@ -86,6 +86,19 @@ const requireAt = export const requireWrites = requireAt("write"); export const requireReaches = requireAt("read"); +/** Whether the connection is an Owner of the server, or a service session, which acts for one. */ +export const isOwner = Effect.fn("j5.sharing.connectionWriter.isOwner")(function* ( + session: SessionIdentity, +) { + const reach = yield* (yield* PersonAccess) + .sessionReach(session) + .pipe(Effect.mapError(unreadable)); + return ( + reach.kind === "service" || + (reach.kind === "person" && levelReaches(reach.serverLevel, "owner")) + ); +}); + /** * Refuses anyone who is not an Owner of the server, for now, as command admission refuses them * archiving or deleting a thread (People and access AC14). A service session passes. @@ -93,13 +106,7 @@ export const requireReaches = requireAt("read"); export const requireOwner = Effect.fn("j5.sharing.connectionWriter.requireOwner")(function* ( session: SessionIdentity, ) { - const reach = yield* (yield* PersonAccess) - .sessionReach(session) - .pipe(Effect.mapError(unreadable)); - const owner = - reach.kind === "service" || - (reach.kind === "person" && levelReaches(reach.serverLevel, "owner")); - if (!owner) { + if (!(yield* isOwner(session))) { return yield* new J5ActionError({ code: "OwnersOnly", message: "Only an Owner of this server archives a Crew, for now. Ask an Owner to do it.", diff --git a/apps/server/src/j5/wsRpc.test.ts b/apps/server/src/j5/wsRpc.test.ts index 49fdaebb1bb31..7a24e07ab1d9e 100644 --- a/apps/server/src/j5/wsRpc.test.ts +++ b/apps/server/src/j5/wsRpc.test.ts @@ -170,6 +170,20 @@ const clientFor = (scopes: ReadonlyArray) => }, }) : Effect.fail(new A2AExchangeNotOpenError({ exchangeId: input.exchangeId })), + answerCrewWorktreeCleanup: ({ itemId }) => + reached("cleanup", { + item: { + id: itemId, + crewInstanceId: "crew:1", + crewName: "Login Fix Crew", + projectId: "project:gate", + captainThreadId: ThreadId.make("thread:captain"), + filedAt: "2026-10-27T12:00:00.000Z", + status: "decided" as const, + decidedAt: "2026-10-27T12:05:00.000Z", + entries: [], + }, + }), }), Layer.mock(PeerAdminService)({ issueCredential: (input) => @@ -303,6 +317,9 @@ const callEach = (client: Effect.Success>["client"] exchangeId: "ask:1", }), ), + [ACTIONS.answerCrewWorktreeCleanup]: outcome( + client[ACTIONS.answerCrewWorktreeCleanup]({ itemId: "cleanup:1", removePaths: [] }), + ), [ACTIONS.issuePeerCredential]: outcome( client[ACTIONS.issuePeerCredential]({ environmentId: "environment-home", @@ -407,7 +424,8 @@ describe("J5 client action RPC scopes", () => { tag: "EnvironmentAuthorizationError", requiredPermission: method.startsWith("j5.peers.") ? AuthAccessWriteScope - : method.startsWith("j5.playbooks.") + : method.startsWith("j5.playbooks.") || + method === ACTIONS.answerCrewWorktreeCleanup ? AuthSettingsWriteScope : AuthOrchestrationOperateScope, }, @@ -461,6 +479,15 @@ describe("J5 client action RPC handlers", () => { (yield* client[ACTIONS.archiveCrew]({ crewInstanceId: "crew:1" })).status, "archived", ); + // Removing worktrees is an Owner's call, which the settings scope stands for. + const owner = yield* clientFor([...operator, AuthSettingsWriteScope]); + assert.equal( + (yield* owner.client[ACTIONS.answerCrewWorktreeCleanup]({ + itemId: "cleanup:1", + removePaths: [], + })).item.status, + "decided", + ); assert.deepStrictEqual( yield* client[ACTIONS.respondCrewRuntimeRequest]({ threadId, @@ -486,6 +513,7 @@ describe("J5 client action RPC handlers", () => { "answer", "delete artifact", ]); + assert.deepStrictEqual(owner.handled, ["cleanup"]); }).pipe(Effect.scoped), ); diff --git a/apps/web/src/j5/a2a/CrewWorktreeCleanupSection.tsx b/apps/web/src/j5/a2a/CrewWorktreeCleanupSection.tsx new file mode 100644 index 0000000000000..ac3044da65a56 --- /dev/null +++ b/apps/web/src/j5/a2a/CrewWorktreeCleanupSection.tsx @@ -0,0 +1,447 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + ArrowUpRightIcon, + ChevronRightIcon, + CircleCheckIcon, + CircleMinusIcon, + CircleXIcon, + TriangleAlertIcon, +} from "lucide-react"; +import { useState } from "react"; + +import { Badge } from "../../components/ui/badge"; +import { Button } from "../../components/ui/button"; +import { Checkbox } from "../../components/ui/checkbox"; +import { formatElapsedDurationLabel } from "../../timestampFormat"; +import { useLogicalProjects } from "../logicalProjects"; +import { + decidedWorktreeCleanupSourcesAtom, + j5Environment, + openWorktreeCleanupSourcesAtom, +} from "../state"; +import { notifyHumanInboxChanged } from "./humanInboxRefresh"; +import { answerCrewWorktreeCleanup, refreshWorktreeCleanups } from "./crewWorktreeCleanupClient"; +import { + answerFailure, + answeredAgeLabel, + cleanupButtons, + cleanupNeedsAttention, + cleanupTitle, + commitsAheadLabel, + groupCleanupOutcomes, + mergeWorktreeCleanupSources, + orderCleanupRows, + outcomeReason, + outcomeSummary, + pickedCleanupPaths, + pullRequestLabel, + sliceCleanupRows, + toggleCleanupPath, + uncommittedFilesLabel, + worktreeCleanupKey, + type ScopedWorktreeCleanup, +} from "./crewWorktreeCleanup.logic"; + +/** + * The cleanup approvals as the Inbox page shows them. An item answered on this device stays in + * place with its result, as does one whose second answer was refused, until the page is left; + * the others that are decided go to the Answered shelf. + */ +export function useWorktreeCleanupInbox() { + const openSources = useAtomValue(openWorktreeCleanupSourcesAtom); + const decidedSources = useAtomValue(decidedWorktreeCleanupSourcesAtom); + const open = mergeWorktreeCleanupSources(openSources); + const decided = mergeWorktreeCleanupSources(decidedSources); + // The answer's own item stands in until the decided read arrives; null is a refused answer. + const [pinned, setPinned] = useState>( + new Map(), + ); + const [pendingKey, setPendingKey] = useState(null); + const [errors, setErrors] = useState>>({}); + + const decidedByKey = new Map(decided.map((item) => [worktreeCleanupKey(item), item])); + const openKeys = open.map(worktreeCleanupKey); + const inPlace = [...new Set([...openKeys, ...pinned.keys()])].flatMap((key) => { + const item = pinned.has(key) + ? (decidedByKey.get(key) ?? pinned.get(key)) + : open[openKeys.indexOf(key)]; + return item === null || item === undefined ? [] : [item]; + }); + const shelf = decided.filter((item) => !pinned.has(worktreeCleanupKey(item))); + + const answer = async (item: ScopedWorktreeCleanup, removePaths: ReadonlyArray) => { + const key = worktreeCleanupKey(item); + setPendingKey(key); + setErrors((current) => + Object.fromEntries(Object.entries(current).filter(([errorKey]) => errorKey !== key)), + ); + try { + const decidedItem = await answerCrewWorktreeCleanup(item.environmentId, { + itemId: item.id, + removePaths, + }); + setPinned((current) => new Map(current).set(key, { ...item, ...decidedItem })); + notifyHumanInboxChanged(item.environmentId); + } catch (cause) { + const failure = answerFailure(cause); + setErrors((current) => ({ ...current, [key]: failure.message })); + if (failure.alreadyAnswered) setPinned((current) => new Map(current).set(key, null)); + } + try { + await refreshWorktreeCleanups(item.environmentId); + } catch { + setErrors((current) => ({ + ...current, + [key]: current[key] ?? "The inbox could not be refreshed. The list may be stale.", + })); + } + setPendingKey(null); + }; + + return { + inPlace, + shelf, + openCount: inPlace.filter((item) => item.status === "open").length, + pendingKey, + errors, + answer, + }; +} + +const unavailable = "This environment is unavailable, or only an Owner of this server can answer."; + +function ItemHeader({ + item, + showEnvironment, +}: { + readonly item: ScopedWorktreeCleanup; + readonly showEnvironment: boolean; +}) { + const projectOf = useLogicalProjects(); + const needsAttention = cleanupNeedsAttention(item.entries); + const since = item.status === "open" ? item.filedAt : item.decidedAt; + const age = since === null ? "" : formatElapsedDurationLabel(since); + return ( + + {item.status === "open" ? ( + + FYI + + ) : needsAttention ? ( + + ) : ( + + )} +
+
+ J5 + · + + {projectOf(item.environmentId, item.projectId)?.displayName ?? item.projectId} + + {showEnvironment || !item.connected ? ( + <> + · + + {showEnvironment ? item.environmentLabel : ""} + {item.connected ? "" : showEnvironment ? " (offline)" : "offline"} + + + ) : null} + {age ? ( + <> + · + + {item.status === "open" ? `open ${age}` : answeredAgeLabel(age)} + + + ) : null} +
+

+ {cleanupTitle(item)} +

+
+ +
+ ); +} + +function PendingRows({ + item, + disabled, + selected, + onToggle, +}: { + readonly item: ScopedWorktreeCleanup; + readonly disabled: boolean; + readonly selected: ReadonlySet; + readonly onToggle: (path: string) => void; +}) { + const [showAll, setShowAll] = useState(false); + const { shown, hidden } = sliceCleanupRows(orderCleanupRows(item.entries), showAll); + return ( + <> +
    + {shown.map((entry) => ( +
  • + +
  • + ))} +
+ {hidden > 0 ? ( + + ) : null} + + ); +} + +function OpenBody({ + item, + pending, + error, + onAnswer, +}: { + readonly item: ScopedWorktreeCleanup; + readonly pending: boolean; + readonly error: string | undefined; + readonly onAnswer: (item: ScopedWorktreeCleanup, removePaths: ReadonlyArray) => void; +}) { + const mayAnswer = useAtomValue( + j5Environment.answerCrewWorktreeCleanup.permissionAtom(item.environmentId), + ); + const canAnswer = item.sourceReady && mayAnswer; + const [selected, setSelected] = useState>(new Set()); + const buttons = cleanupButtons(selected, item.entries); + const hold = !canAnswer || pending; + return ( +
+

+ Removing a worktree keeps its branch and discards its uncommitted changes. +

+ setSelected((current) => toggleCleanupPath(current, path))} + selected={selected} + /> + {error === undefined ? null : ( +

+ {error} +

+ )} +
+ +
+ + +
+
+
+ ); +} + +const groupIcon = { + removed: , + kept: , + skipped: , + failed: , +}; + +function ResultBody({ + item, + error, +}: { + readonly item: ScopedWorktreeCleanup; + readonly error: string | undefined; +}) { + return ( +
+ {error === undefined ? null : ( +

+ {error} +

+ )} +

{outcomeSummary(item.entries)}

+ {groupCleanupOutcomes(item.entries).map((group) => ( +
+
+ {groupIcon[group.outcome]} + {group.label} +
+
    + {group.rows.map((entry) => { + const reason = outcomeReason(entry); + return ( +
  • + + {entry.threadTitle} + + {entry.branch ?? entry.path} + + + {reason === null ? null : ( + + {reason} + + )} +
  • + ); + })} +
+
+ ))} +
+ ); +} + +export function CrewWorktreeCleanupSection({ + items, + pendingKey, + errors, + onAnswer, + showEnvironment, +}: { + readonly items: ReadonlyArray; + readonly pendingKey: string | null; + readonly errors: Readonly>; + readonly onAnswer: (item: ScopedWorktreeCleanup, removePaths: ReadonlyArray) => void; + readonly showEnvironment: boolean; +}) { + if (items.length === 0) return null; + return ( +
    + {items.map((item) => { + const key = worktreeCleanupKey(item); + return ( +
  1. +
    + + {item.status === "open" ? ( + + ) : ( + + )} +
    +
  2. + ); + })} +
+ ); +} + +/** A decided item's row on the Answered shelf. */ +export function DecidedCleanupRow({ + item, + showEnvironment, +}: { + readonly item: ScopedWorktreeCleanup; + readonly showEnvironment: boolean; +}) { + const projectOf = useLogicalProjects(); + const age = item.decidedAt === null ? "" : formatElapsedDurationLabel(item.decidedAt); + return ( +
  • + {cleanupNeedsAttention(item.entries) ? ( + + ) : ( + + )} +
    +

    {cleanupTitle(item)}

    +

    + J5 · {projectOf(item.environmentId, item.projectId)?.displayName ?? item.projectId} + {showEnvironment ? ` · ${item.environmentLabel}` : ""} + {` · ${answeredAgeLabel(age)}`} +

    +

    {outcomeSummary(item.entries)}

    +
    +
  • + ); +} diff --git a/apps/web/src/j5/a2a/HumanInboxPage.tsx b/apps/web/src/j5/a2a/HumanInboxPage.tsx index 70facdb584db5..ed1e6ef515c22 100644 --- a/apps/web/src/j5/a2a/HumanInboxPage.tsx +++ b/apps/web/src/j5/a2a/HumanInboxPage.tsx @@ -54,6 +54,17 @@ import { useNativeQuestionInbox, } from "../crew/crewRuntimeRequestsClient"; import { NativeQuestionInboxSection } from "./NativeQuestionInboxSection"; +import { + CrewWorktreeCleanupSection, + DecidedCleanupRow, + useWorktreeCleanupInbox, +} from "./CrewWorktreeCleanupSection"; +import { refreshWorktreeCleanups } from "./crewWorktreeCleanupClient"; +import { + inboxSummary, + worktreeCleanupKey, + type ScopedWorktreeCleanup, +} from "./crewWorktreeCleanup.logic"; import { answeredInboxQueryAtom, answeredInboxSourcesAtom, @@ -323,18 +334,21 @@ function OpenInboxItem({ function AnsweredShelf({ items, + cleanups, onOpenThread, senderLabels, projectNameOf, showEnvironment, }: { readonly items: ReadonlyArray; + /** Worktree cleanups that are decided and not shown in place. */ + readonly cleanups: ReadonlyArray; readonly onOpenThread: (item: HumanInboxItem) => void; readonly senderLabels: SenderLabels; readonly projectNameOf: ProjectNameOf; readonly showEnvironment: boolean; }) { - if (items.length === 0) return null; + if (items.length === 0 && cleanups.length === 0) return null; return (
    @@ -343,7 +357,9 @@ function AnsweredShelf({ className="size-4 transition-transform duration-150 group-open/shelf:rotate-90" /> Answered - {items.length} + + {items.length + cleanups.length} +
      {items.map((item) => { @@ -374,6 +390,13 @@ function AnsweredShelf({ ); })} + {cleanups.map((item) => ( + + ))}
    ); @@ -391,6 +414,7 @@ async function refreshHumanInboxes(environmentId?: EnvironmentId, force = false) refreshJ5Sources(openInboxSourcesAtom, openInboxQueryAtom, options), refreshJ5Sources(answeredInboxSourcesAtom, answeredInboxQueryAtom, options), refreshCrewRuntimeRequests(environmentId), + refreshWorktreeCleanups(environmentId), ]); const failed = results.flat().find((result) => result._tag === "Failure"); if (failed?._tag === "Failure") throw Cause.squash(failed.cause); @@ -477,6 +501,7 @@ export function HumanInboxPage() { const runtimeRequests = useCrewRuntimeRequests(); const runtimeSources = useAtomValue(crewRuntimeRequestSourcesAtom); const nativeQuestions = useNativeQuestionInbox(); + const cleanups = useWorktreeCleanupInbox(); const previousOpenItems = useRef(new Map>()); // oxlint-disable-next-line t3code/react-effect-budget -- an answered item leaving the open list rereads the answered list; it reacts to data arriving, not to a handler here. useEffect(() => { @@ -596,11 +621,12 @@ export function HumanInboxPage() {

    {loading && items.length === 0 ? "Loading questions waiting on you…" - : `${items.length} ${complete ? "open" : "loaded"} ${items.length === 1 ? "question" : "questions"}${ - runtimeRequests.length + nativeQuestions.length === 0 - ? "" - : ` · ${runtimeRequests.length + nativeQuestions.length} agent ${runtimeRequests.length + nativeQuestions.length === 1 ? "request" : "requests"}` - }`} + : inboxSummary({ + questions: items.length, + complete, + agentRequests: runtimeRequests.length + nativeQuestions.length, + worktreeCleanups: cleanups.openCount, + })}