From d587056eb9bf66008f93ea15546f4d3d4917c56a Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 20:59:05 -0400 Subject: [PATCH 01/14] feat(j5): one Inbox approval for the worktrees a Crew archive keeps with unfinished work An archive that keeps J5-created worktrees for uncommitted changes or unmerged commits files one approval for the Crew, measured when the archive kept them. A person removes all, the ones they pick, or none; each approved worktree is checked again against what was measured and skipped if it changed. Answering is an Owner-only RPC with no agent tool, and the open item counts on the Inbox bell. Co-Authored-By: Claude Sonnet 5.5 --- apps/server/src/j5/a2a/ArchiveCrewService.ts | 20 +- .../src/j5/a2a/ClientActionsService.test.ts | 2 + .../server/src/j5/a2a/ClientActionsService.ts | 13 + apps/server/src/j5/a2a/ClientReadsService.ts | 3 + .../j5/a2a/CrewWorktrees.integration.test.ts | 2 + apps/server/src/j5/a2a/CrewWorktrees.test.ts | 276 +++++++++++++- apps/server/src/j5/a2a/CrewWorktrees.ts | 356 +++++++++++++++++- apps/server/src/j5/a2a/Migrations.test.ts | 4 +- apps/server/src/j5/a2a/Migrations.ts | 2 + apps/server/src/j5/a2a/clientActionRpc.ts | 18 + apps/server/src/j5/a2a/clientReadRpc.test.ts | 27 ++ apps/server/src/j5/a2a/clientReadRpc.ts | 21 ++ apps/server/src/j5/a2a/mcp/tools.test.ts | 1 + .../a2a/migrations/051_CrewWorktreeCleanup.ts | 27 ++ apps/server/src/j5/a2a/runtimeLayer.ts | 5 +- apps/server/src/j5/wsRpc.test.ts | 23 ++ packages/contracts/src/j5.ts | 69 ++++ .../contracts/src/j5/clientRpcPermissions.ts | 1 + 18 files changed, 856 insertions(+), 14 deletions(-) create mode 100644 apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.ts diff --git a/apps/server/src/j5/a2a/ArchiveCrewService.ts b/apps/server/src/j5/a2a/ArchiveCrewService.ts index bbd04f09b4836..8bd95ebebcc9e 100644 --- a/apps/server/src/j5/a2a/ArchiveCrewService.ts +++ b/apps/server/src/j5/a2a/ArchiveCrewService.ts @@ -217,6 +217,14 @@ 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) => ({ + crewInstanceId: instance.id, + 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, @@ -409,6 +417,7 @@ export const layer = Layer.effect( : ("already_archived" as const), })), seats: createdSeats(facts), + crew: approvalCrew(instance), }; } @@ -483,7 +492,12 @@ 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, seats: createdSeats(facts) }; + return { + status: "archived" as const, + members: results, + seats: createdSeats(facts), + crew: approvalCrew(instance), + }; }).pipe((unit) => crews.serialize(input.crewInstanceId, unit)); // After the unit's step commits and its lock is released, so a slow check or removal holds @@ -491,9 +505,9 @@ 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"] = (input) => archiveUnit(input).pipe( - Effect.flatMap(({ seats, ...outcome }) => + Effect.flatMap(({ seats, crew, ...outcome }) => worktrees - .cleanup({ seats }) + .cleanup({ seats, crew }) .pipe(Effect.map((removed) => ({ ...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 4a5e73e49cc13..606077ff942bf 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); @@ -223,6 +234,8 @@ const make = Effect.gen(function* () { yield* worker.notify; return { result }; }), + answerCrewWorktreeCleanup: ({ itemId, removePaths }) => + worktrees.answerCleanup({ itemId, removePaths }).pipe(Effect.map((item) => ({ item }))), }); }); diff --git a/apps/server/src/j5/a2a/ClientReadsService.ts b/apps/server/src/j5/a2a/ClientReadsService.ts index 3410b41e1233b..f488b728a5098 100644 --- a/apps/server/src/j5/a2a/ClientReadsService.ts +++ b/apps/server/src/j5/a2a/ClientReadsService.ts @@ -279,6 +279,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()( @@ -409,6 +411,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/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 e5a6b8480a19d..81b84c633a84d 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.test.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.test.ts @@ -48,6 +48,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"); @@ -59,6 +60,7 @@ const gitLayer = GitVcsDriver.layer.pipe( interface SeatThread { archivedAt: DateTime.Utc | null; branch: string | null; + title: string; } /** @@ -102,6 +104,7 @@ const fixture = Effect.gen(function* () { let pullRequestFails = false; const pullRequestLookups: Array = []; const invalidated: Array = []; + const notified: Array> = []; const layer = manualLayer.pipe( Layer.provide( @@ -147,6 +150,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); @@ -197,6 +203,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` @@ -223,6 +230,7 @@ const fixture = Effect.gen(function* () { threads, metadataUpdated, invalidated, + notified, pullRequestLookups, bound, setProjectRoots: (roots: typeof otherProjectRoots) => (otherProjectRoots = roots), @@ -648,7 +656,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)), ); @@ -777,3 +785,269 @@ it.effect( }), ), ); + +const crew = { + crewInstanceId: "crew:one", + 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("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 29400391c973c..026285e3f8ea7 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.ts @@ -1,17 +1,24 @@ import { OrchestrationV2ProviderSessionJson, + ProjectId, 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"; @@ -22,6 +29,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"; @@ -33,8 +41,51 @@ import * as TerminalManager from "../../terminal/Manager.ts"; import * as GitVcsDriver from "../../vcs/GitVcsDriver.ts"; import { withWorkspaceLease } from "../../workspace/workspaceLease.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)); + +export class CrewWorktreeCleanupNotFoundError extends Data.TaggedError( + "CrewWorktreeCleanupNotFoundError", +)<{ readonly itemId: string }> { + override get message(): string { + return `There is no worktree cleanup item ${this.itemId}.`; + } +} + +export class CrewWorktreeCleanupAnsweredError extends Data.TaggedError( + "CrewWorktreeCleanupAnsweredError", +)<{ readonly itemId: string }> { + override get message(): string { + return "This worktree cleanup was already answered."; + } +} + +export 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), ); @@ -58,8 +109,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 upstream's ThreadLaunch creates for a Crew seat on a new worktree, when @@ -77,7 +133,30 @@ 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 Crew, unless it already has an open one. + */ + readonly crew?: { + readonly crewInstanceId: 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>; + /** + * 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. @@ -99,6 +178,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; @@ -235,8 +315,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: [ @@ -248,9 +328,14 @@ 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"); + /** * 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. @@ -308,6 +393,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) => @@ -335,6 +422,16 @@ 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) { + const [head, status] = yield* Effect.all([ + git.resolveCommit({ cwd: worktreePath, revision: "HEAD" }), + localChanges(worktreePath), + ]); + return head.commitSha === context.baseline.headSha && + digestOf(status.stdout) === context.baseline.statusDigest + ? ({ kind: "remove", headSha: head.commitSha } satisfies Verdict) + : ({ kind: "changed" } satisfies Verdict); + } if (yield* hasBlockingChanges(worktreePath)) return { kind: "keep", reason: "uncommitted_changes" } satisfies Verdict; const unmerged = context.checkMerged @@ -397,14 +494,96 @@ 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; }), ); }); - const cleanup: CrewWorktreesShape["cleanup"] = ({ seats }) => + 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, head] = yield* Effect.all([ + localChanges(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: digestOf(status.stdout), + } satisfies StoredCleanupEntry; + }); + + /** One approval per archive: a Crew with an open one keeps it, so an archive that runs 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, filed_at, entries_json + ) + VALUES ( + ${NodeCrypto.randomUUID()}, ${crew.crewInstanceId}, ${crew.crewName}, ${crew.projectId}, + ${crew.captainThreadId}, ${DateTime.formatIso(yield* DateTime.now)}, + ${yield* encodeEntries(entries)} + ) + ON CONFLICT DO NOTHING + RETURNING id + `; + if (filed.length > 0) yield* changes.notify("inbox"); + }); + + const cleanup: CrewWorktreesShape["cleanup"] = ({ seats, crew }) => Effect.gen(function* () { // 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. @@ -415,6 +594,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; @@ -442,15 +622,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; }).pipe( Effect.catchCause((cause) => @@ -503,6 +698,145 @@ 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"] = (status) => + Effect.gen(function* () { + 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"] = ({ itemId, removePaths }) => + Effect.gen(function* () { + 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. @@ -526,7 +860,13 @@ const makeLayer = (daemon: boolean) => yield* Effect.forkScoped(runDaemon); } - return CrewWorktrees.of({ handleStoredEvent, cleanup, estimate }); + return CrewWorktrees.of({ + handleStoredEvent, + cleanup, + estimate, + 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 6db431a25ebec..6234c2814b670 100644 --- a/apps/server/src/j5/a2a/clientActionRpc.ts +++ b/apps/server/src/j5/a2a/clientActionRpc.ts @@ -14,6 +14,7 @@ import { type CrewProposalResolveRequest, type CrewRuntimeRequestRespondRequest, type CrewStopRequest, + type CrewWorktreeCleanupAnswerRequest, type IssuePeerCredentialRequest, type PeerProbeRequest, type RemovePeerRequest, @@ -45,6 +46,7 @@ export const CLIENT_ACTION_RPC_SCOPES = { [METHODS.archiveCrew]: AuthOrchestrationOperateScope, [METHODS.respondCrewRuntimeRequest]: AuthOrchestrationOperateScope, [METHODS.answerHumanExchange]: AuthOrchestrationOperateScope, + [METHODS.answerCrewWorktreeCleanup]: AuthOrchestrationOperateScope, [METHODS.issuePeerCredential]: AuthAccessWriteScope, [METHODS.addPeer]: AuthAccessWriteScope, [METHODS.removePeer]: AuthAccessWriteScope, @@ -182,6 +184,22 @@ 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))) + .pipe( + 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..e9007effa5047 100644 --- a/apps/server/src/j5/a2a/clientReadRpc.test.ts +++ b/apps/server/src/j5/a2a/clientReadRpc.test.ts @@ -205,6 +205,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 +227,32 @@ it.effect("keeps identity requests exact, ordered, and total, and drops an id th }), ); +it.effect("counts an open worktree cleanup the person reaches in the open Inbox count", () => + Effect.gen(function* () { + const handlers = yield* handlersOver( + Layer.mock(ClientReadsService)({ + openInboxCount: (personId) => + Effect.succeed({ personId: personId ?? ParticipantId.make("agent:none"), count: 3 }), + crewWorktreeCleanups: () => + Effect.succeed([ + { + 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: [], + }, + ]), + }), + ); + assert.strictEqual((yield* handlers[METHODS.readOpenInboxCount]({})).count, 4); + }), +); + 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 12a2390ecf475..3fc1c0319670f 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, @@ -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,17 @@ export const makeClientReadRpcHandlers = Effect.fn("j5.makeClientReadRpcHandlers Effect.provideService(PersonAccess, people), Effect.provideService(SharedThreads, shared), ); + // Listed to whoever reaches the Crew's Captain, like its archive's worktrees. + const cleanupsReached = (status: CrewWorktreeCleanupListRequest["status"]) => + Effect.gen(function* () { + const listed = yield* clientReads + .crewWorktreeCleanups(status) + .pipe(Effect.catch(failed("Reading worktree cleanups failed."))); + const reachesCaptain = yield* reaches; + return yield* Effect.filter(listed, (item) => + reachesCaptain(Effect.succeed(item.captainThreadId)), + ); + }); return { [METHODS.listHumanInbox]: (input: HumanInboxListRequest) => personOf.pipe( @@ -92,7 +105,15 @@ 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]: (input: CrewWorktreeCleanupListRequest) => + cleanupsReached(input.status).pipe(Effect.map((items) => ({ items }))), [METHODS.listCrewProposals]: () => Effect.gen(function* () { const listed = yield* clientReads.crewProposals.pipe( diff --git a/apps/server/src/j5/a2a/mcp/tools.test.ts b/apps/server/src/j5/a2a/mcp/tools.test.ts index d499e29a6f335..4fea380b6c7e8 100644 --- a/apps/server/src/j5/a2a/mcp/tools.test.ts +++ b/apps/server/src/j5/a2a/mcp/tools.test.ts @@ -94,6 +94,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.ts b/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.ts new file mode 100644 index 0000000000000..caafde50b8a48 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.ts @@ -0,0 +1,27 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * The Inbox approval an archive files for the worktrees it kept with unfinished work: one row per + * item, its worktrees (as measured, then as decided) in `entries_json`. An item is open until + * `decided_at` is set, and a Crew has at most one open item. + */ +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, + filed_at TEXT NOT NULL, + decided_at TEXT, + entries_json TEXT NOT NULL + ) + `; + yield* sql` + CREATE UNIQUE INDEX j5_crew_worktree_cleanup_open_crew + ON j5_crew_worktree_cleanup (crew_instance_id) WHERE decided_at IS NULL + `; +}); diff --git a/apps/server/src/j5/a2a/runtimeLayer.ts b/apps/server/src/j5/a2a/runtimeLayer.ts index f2f3e3ea0fcdf..d47f6dbba4d46 100644 --- a/apps/server/src/j5/a2a/runtimeLayer.ts +++ b/apps/server/src/j5/a2a/runtimeLayer.ts @@ -155,7 +155,10 @@ export 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/wsRpc.test.ts b/apps/server/src/j5/wsRpc.test.ts index 49fdaebb1bb31..2c483c408a289 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", @@ -461,6 +478,11 @@ describe("J5 client action RPC handlers", () => { (yield* client[ACTIONS.archiveCrew]({ crewInstanceId: "crew:1" })).status, "archived", ); + assert.equal( + (yield* client[ACTIONS.answerCrewWorktreeCleanup]({ itemId: "cleanup:1", removePaths: [] })) + .item.status, + "decided", + ); assert.deepStrictEqual( yield* client[ACTIONS.respondCrewRuntimeRequest]({ threadId, @@ -482,6 +504,7 @@ describe("J5 client action RPC handlers", () => { "resolve", "stop", "archive", + "cleanup", "respond", "answer", "delete artifact", diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index 1aa63623aa6e1..94e5ce15604d1 100644 --- a/packages/contracts/src/j5.ts +++ b/packages/contracts/src/j5.ts @@ -551,6 +551,63 @@ const CrewArchiveWorktreesResponse = Schema.Struct({ worktrees: Schema.Array(CrewArchiveWorktreeEstimate), }); +/** + * One worktree an archive kept with unfinished work, as measured when the archive kept it. + * Removing it discards the uncommitted files; the branch, and so every commit, stays. + */ +export const CrewWorktreeCleanupEntry = Schema.Struct({ + threadId: ThreadId, + threadTitle: Schema.String, + path: Schema.String, + branch: Schema.NullOr(Schema.String), + uncommittedFiles: Schema.Int, + /** Null when the default branch could not be compared. */ + commitsAhead: Schema.NullOr(Schema.Int), + pullRequestUrl: Schema.NullOr(Schema.String), + /** Null until the item is decided. `kept` is the person's choice; `skipped` is J5's. */ + outcome: Schema.NullOr(Schema.Literals(["removed", "kept", "skipped", "failed"])), + /** + * Why it was skipped: its work changed after the item was filed, another unarchived thread or + * an open session now uses it, it was already gone, or J5 could not check it. + */ + reason: Schema.NullOr(Schema.Literals(["changed", "shared", "in_use", "gone", "unverified"])), + /** The git error text of a failed removal. */ + detail: Schema.NullOr(Schema.String), +}); +export type CrewWorktreeCleanupEntry = typeof CrewWorktreeCleanupEntry.Type; + +/** The one Inbox approval an archive files for every J5-created worktree it kept unfinished. */ +export const CrewWorktreeCleanupItem = Schema.Struct({ + id: Schema.String, + crewInstanceId: Schema.String, + crewName: Schema.String, + projectId: Schema.String, + captainThreadId: ThreadId, + filedAt: Schema.String, + status: Schema.Literals(["open", "decided"]), + decidedAt: Schema.NullOr(Schema.String), + entries: Schema.Array(CrewWorktreeCleanupEntry), +}); +export type CrewWorktreeCleanupItem = typeof CrewWorktreeCleanupItem.Type; + +export const CrewWorktreeCleanupListRequest = Schema.Struct({ + status: Schema.Literals(["open", "decided"]), +}); +export type CrewWorktreeCleanupListRequest = typeof CrewWorktreeCleanupListRequest.Type; +export const CrewWorktreeCleanupListResponse = Schema.Struct({ + items: Schema.Array(CrewWorktreeCleanupItem), +}); + +/** The paths to remove; an empty list keeps every worktree and clears the item. */ +export const CrewWorktreeCleanupAnswerRequest = Schema.Struct({ + itemId: Schema.String.check(Schema.isNonEmpty()), + removePaths: Schema.Array(Schema.String), +}); +export type CrewWorktreeCleanupAnswerRequest = typeof CrewWorktreeCleanupAnswerRequest.Type; +export const CrewWorktreeCleanupAnswerResponse = Schema.Struct({ + item: CrewWorktreeCleanupItem, +}); + /** * 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 @@ -1083,6 +1140,7 @@ export const J5_CLIENT_ACTION_WS_METHODS = { archiveCrew: "j5.crews.archive", respondCrewRuntimeRequest: "j5.crews.respondRuntimeRequest", answerHumanExchange: "j5.inbox.answer", + answerCrewWorktreeCleanup: "j5.crews.answerWorktreeCleanup", issuePeerCredential: "j5.peers.issueCredential", addPeer: "j5.peers.add", removePeer: "j5.peers.remove", @@ -1124,6 +1182,11 @@ export const J5ClientActionRpcGroup = RpcGroup.make( success: AnswerHumanExchangeResponse, error: clientActionError, }), + Rpc.make(J5_CLIENT_ACTION_WS_METHODS.answerCrewWorktreeCleanup, { + payload: CrewWorktreeCleanupAnswerRequest, + success: CrewWorktreeCleanupAnswerResponse, + error: clientActionError, + }), Rpc.make(J5_CLIENT_ACTION_WS_METHODS.issuePeerCredential, { payload: IssuePeerCredentialRequest, success: IssuePeerCredentialResponse, @@ -1257,6 +1320,7 @@ export const J5_CLIENT_READ_WS_METHODS = { listSpawnedChildren: "j5.fleet.listSpawnedChildren", readPreArchiveFacts: "j5.archive.readFacts", readCrewArchiveWorktrees: "j5.archive.readCrewWorktrees", + listCrewWorktreeCleanups: "j5.crews.listWorktreeCleanups", readParticipantIdentities: "j5.participants.readIdentities", listPeers: "j5.peers.list", subscribeReadChanges: "j5.reads.subscribeChanges", @@ -1331,6 +1395,11 @@ export const J5ClientReadRpcGroup = RpcGroup.make( CrewArchiveWorktreesRequest, CrewArchiveWorktreesResponse, ), + clientRead( + J5_CLIENT_READ_WS_METHODS.listCrewWorktreeCleanups, + CrewWorktreeCleanupListRequest, + CrewWorktreeCleanupListResponse, + ), clientRead( J5_CLIENT_READ_WS_METHODS.readParticipantIdentities, ParticipantIdentitiesRequest, diff --git a/packages/contracts/src/j5/clientRpcPermissions.ts b/packages/contracts/src/j5/clientRpcPermissions.ts index 2f7dd9415bec1..57a908cf39b80 100644 --- a/packages/contracts/src/j5/clientRpcPermissions.ts +++ b/packages/contracts/src/j5/clientRpcPermissions.ts @@ -53,6 +53,7 @@ export const J5_CLIENT_GUARDED_RPC_SCOPES = { [J5_CLIENT_ACTION_WS_METHODS.archiveCrew]: AuthOrchestrationOperateScope, [J5_CLIENT_ACTION_WS_METHODS.respondCrewRuntimeRequest]: AuthOrchestrationOperateScope, [J5_CLIENT_ACTION_WS_METHODS.answerHumanExchange]: AuthOrchestrationOperateScope, + [J5_CLIENT_ACTION_WS_METHODS.answerCrewWorktreeCleanup]: AuthOrchestrationOperateScope, [J5_CLIENT_ACTION_WS_METHODS.issuePeerCredential]: AuthAccessWriteScope, [J5_CLIENT_ACTION_WS_METHODS.addPeer]: AuthAccessWriteScope, From 9eb1404797f3b22c9fa85e3801ca3c597e9d31f6 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 20:59:07 -0400 Subject: [PATCH 02/14] feat(client-runtime): read and answer the worktree cleanup approval Co-Authored-By: Claude Sonnet 5.5 --- packages/client-runtime/src/j5/actions.test.ts | 1 + packages/client-runtime/src/j5/state.ts | 13 +++++++++++++ 2 files changed, 14 insertions(+) diff --git a/packages/client-runtime/src/j5/actions.test.ts b/packages/client-runtime/src/j5/actions.test.ts index a17baa377c29e..4f2fc073f1527 100644 --- a/packages/client-runtime/src/j5/actions.test.ts +++ b/packages/client-runtime/src/j5/actions.test.ts @@ -187,6 +187,7 @@ describe("J5 action commands", () => { atoms.archiveCrew, atoms.respondCrewRuntimeRequest, atoms.answerHumanExchange, + atoms.answerCrewWorktreeCleanup, atoms.deleteArtifact, atoms.deleteAllArtifacts, ]) { diff --git a/packages/client-runtime/src/j5/state.ts b/packages/client-runtime/src/j5/state.ts index 975059806325b..a71aa160754d2 100644 --- a/packages/client-runtime/src/j5/state.ts +++ b/packages/client-runtime/src/j5/state.ts @@ -296,6 +296,19 @@ export function createJ5EnvironmentAtoms( execute: (_input: Record) => j5Read(J5_CLIENT_READ_WS_METHODS.listCrewRuntimeRequests, {}), }), + // The Inbox's worktree cleanup approval: one per Crew archive that kept unfinished worktrees. + crewWorktreeCleanups: createEnvironmentQueryAtomFamily(runtime, { + label: "j5:crew-worktree-cleanups", + staleTimeMs: 7_500, + refreshTrigger: rereadOn("inbox"), + execute: (input: { readonly status: "open" | "decided" }) => + j5Read(J5_CLIENT_READ_WS_METHODS.listCrewWorktreeCleanups, input), + }), + answerCrewWorktreeCleanup: createJ5ActionCommand( + runtime, + "j5:answer-crew-worktree-cleanup", + J5_CLIENT_ACTION_WS_METHODS.answerCrewWorktreeCleanup, + ), respondCrewRuntimeRequest: createJ5ActionCommand( runtime, "j5:respond-crew-runtime-request", From 295d76e6a6c15606f5889b356d113c78cf51b567 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 20:59:08 -0400 Subject: [PATCH 03/14] docs(j5): the worktree cleanup approval in the Inbox, archive flow and Crews Co-Authored-By: Claude Sonnet 5.5 --- docs/j5/product/features/archive-flow.md | 5 +++-- docs/j5/product/features/crews.md | 5 +++-- docs/j5/product/features/inbox.md | 13 ++++++++++++- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/docs/j5/product/features/archive-flow.md b/docs/j5/product/features/archive-flow.md index b68ff87710a41..61b2d3586973e 100644 --- a/docs/j5/product/features/archive-flow.md +++ b/docs/j5/product/features/archive-flow.md @@ -11,7 +11,7 @@ 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**: 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. +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 until a person approves its removal. Archiving one agent removes nothing; archiving a Crew removes only the clean, merged worktrees J5 created for its seats ([Crews](crews.md) AC19), and files one Inbox item for the ones it kept with uncommitted or unmerged work, which the person answers ([Inbox](inbox.md) AC18–AC22). 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. @@ -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. Archiving an agent deletes no worktree, branch, or pull request. Archiving a Crew, including through its Captain, deletes no branch or pull request, 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. +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 removes a worktree only as [Crews](crews.md) AC19 allows, or after the person approves it in the Inbox item the archive files for worktrees kept with unfinished work ([Inbox](inbox.md) AC18–AC22), 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 @@ -74,3 +74,4 @@ Archiving is **not** deleting, **not** a way to archive a single Crew member, an - 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-27 — the worktrees a Crew archive keeps with unfinished work are filed as one Inbox approval; AC9 and the definition rewritten ([#749](https://github.com/Jacksondr5/j5code/issues/749)). diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index 3c2517ba935d5..9f8065180de58 100644 --- a/docs/j5/product/features/crews.md +++ b/docs/j5/product/features/crews.md @@ -41,7 +41,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 — 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. +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 filing one Inbox approval for the ones kept with uncommitted or unmerged 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. **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. @@ -98,7 +98,7 @@ A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26). ### 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 branch, pull request, or checkpoint, and removes a worktree only when J5 created it for a seat on a new worktree 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; 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. +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 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; 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; the ones kept for uncommitted changes or unmerged commits are also filed as one Inbox approval the person answers ([Inbox](inbox.md) AC18–AC22); 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. @@ -178,3 +178,4 @@ A steer that races a Stop is a known case ([FORK.md](../../../FORK.md) case 26). - 2026-10-27 — an agent chooses between working directly, subagents, and a Crew from the work, not from the word "crew"; members run their own review loops and reach the Captain only for a review pass, a blocker, or a disagreement; `j5_send_message` reports a delivery outcome (AC1, AC9, AC31; Bryant; [#746](https://github.com/Jacksondr5/j5code/issues/746)). - 2026-10-27 — a Captain asks the person for a decision with `j5_send_message`: one request, listed in the Inbox and pinned above the Captain's composer, answered in either place (Bryant; [#747](https://github.com/Jacksondr5/j5code/issues/747)). This replaces the 2026-09-26 line that had the Captain ask inline with its own question tool. - 2026-10-27 — a new worktree seat's base is resolved to a commit when the proposal is accepted and launches from it, so branch renames cannot break a launch; a worktree prepared from that commit has no `gh-merge-base` (AC3; Bryant; [#752](https://github.com/Jacksondr5/j5code/issues/752)). +- 2026-10-27 — AC19: the worktrees an archive keeps for uncommitted or unmerged work are filed as one Inbox approval, and removed only when the person approves ([#749](https://github.com/Jacksondr5/j5code/issues/749); Crews proposal v2). diff --git a/docs/j5/product/features/inbox.md b/docs/j5/product/features/inbox.md index 90204525b0ab6..89dbd427ef1a6 100644 --- a/docs/j5/product/features/inbox.md +++ b/docs/j5/product/features/inbox.md @@ -31,7 +31,9 @@ A server puts asks only in the inboxes of people who can write to the asking age **Several people.** Where more than one person can write to an agent's thread, the agent can ask one of them, or **everyone here**: everyone who can write to its thread when the ask is read. An ask to everyone appears in each of their inboxes, marked as for everyone, and is counted on each of their bells. The first reply closes it for all of them, as any reply closes an ask, and for the others it moves to the Replied shelf showing who answered. A reply that arrives after that is refused and changes nothing. A person who had started typing an answer keeps the item in place, with their words, and sees who answered. In a thread only one person can write to, there is no "everyone here": the agent asks that person ([shared conversations](shared-conversations.md)). -The Inbox is reached from a bell in the rail that counts open asks, seat approvals and native-question links, and opens a full page. It is available on web and desktop, over local, remote and tunnel connections; mobile has no J5 Inbox surface. +**Worktree cleanup.** When archiving a Crew keeps worktrees J5 created for its seats because they hold uncommitted changes or commits that never merged, the archive files one item for all of them, however many seats and worktrees it covered. No agent sent it, it is not an Exchange, and no agent can answer it. Each worktree shows its thread, its branch, its uncommitted files, its commits not on the default branch, and its pull request when it has one, and the item says that removing discards the uncommitted changes and keeps the branch. The person removes all, removes the ones they pick, or keeps all, which clears the item and changes nothing. Each worktree they approve is checked again first; one that changed, is now used by an unarchived thread or an open session, or is already gone is skipped and reported, and a removal that fails is reported with its reason. The item resolves once, and afterwards shows what was removed, kept, skipped or failed. + +The Inbox is reached from a bell in the rail that counts open asks, seat approvals, native-question links and worktree cleanups, and opens a full page. It is available on web and desktop, over local, remote and tunnel connections; mobile has no J5 Inbox surface. The inbox is **not** a backlog (a non-blocking note an agent wants to keep is a Memo), **not** an alerts feed (an agent that fell over is a measured fact for the Fleet page, not an obligation), and **not** project-scoped. @@ -69,6 +71,14 @@ The inbox is **not** a backlog (a non-blocking note an agent wants to keep is a 16. The first reply to an ask to everyone closes it for all of them, and for the others it moves to the Replied shelf naming who answered; a later reply is refused and changes nothing. 17. An open item a person has typed an answer into stays in place when it closes, with their text and a line saying who answered or that the agent withdrew it, until they clear the text or leave the page. +### Worktree cleanup + +18. An archive of a Crew that keeps J5-created worktrees for uncommitted changes or unmerged commits files exactly one item for that Crew, however many seats and worktrees; archiving again while it is open files nothing more. The item has no sender, is not an Exchange, and counts on the bell. +19. Each worktree in the item shows its thread and branch, the number of its uncommitted files, the number of its commits not on the default branch, and its pull request link when it has one; the item says that removing discards uncommitted changes and keeps the branch. +20. The person can remove every worktree, remove the ones they pick, or keep all; keeping all clears the item and changes nothing. Only an Owner answers it, from the app; no agent tool does. +21. Before removing an approved worktree, J5 checks it again and skips and reports it when its commit or its list of changed files differs from when the archive kept it, another unarchived thread now uses it, its thread was unarchived, or a provider session is open in it. A worktree already removed some other way is skipped without error, and a removal that fails is reported with its reason without stopping the others. +22. The item resolves once: a second answer is refused with a message, and the item clears on the person's other devices. Afterwards it shows each worktree as removed, kept, skipped or failed, with the reason. + ## Scenarios - **Two questions, one agent.** An agent in Billing Migration asks the user "merge now or after the audit?" (urgency _soon_) and, separately, "may I delete the old branch?" Two items appear, the _soon_ one first. The agent later follows up on the first by name; the follow-up text appears beneath it. The user answers each in place; each agent-side Exchange closes with the exact text; both items move to the Replied shelf. (AC3, AC5, AC6, AC8, AC10) @@ -90,3 +100,4 @@ The inbox is **not** a backlog (a non-blocking note an agent wants to keep is a - 2026-10-17 — several people (Jackson; [record](../../worklog/2026-10-16-people-and-access-session.md)): asks go to the people who can write to the asking agent's thread, and Viewers have none (AC14 rewritten from the guest rule); an agent can ask everyone here, the first reply closing it for all (AC15, AC16); an item being answered stays in place when it closes (AC17). - 2026-10-18 — "everyone here" is offered, and taken, only while more than one person can write to the asking agent's thread; from a thread only one person can write to, the agent asks that person (AC15; Jackson, in the review of [#638](https://github.com/Jacksondr5/j5code/pull/638)). - 2026-10-27 — a Captain asks the person for a decision with `j5_send_message`: one request, listed in the Inbox and pinned above the Captain's composer, answered in either place (Bryant; [#747](https://github.com/Jacksondr5/j5code/issues/747)). This replaces the 2026-09-26 line that had the Captain ask inline with its own question tool. +- 2026-10-27 — archiving a Crew files one worktree cleanup item for the J5-created worktrees it keeps with unfinished work (AC18–AC22; [#749](https://github.com/Jacksondr5/j5code/issues/749); Crews proposal v2). From 70a09b82f812d2658f19d4843b884fa81b32f284 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 21:19:29 -0400 Subject: [PATCH 04/14] feat(web): answer the worktree cleanup approval from the Inbox The item reads "J5", is marked FYI and sits after the asks. Nothing is picked at first; Keep all, Select all and Remove selected (n) answer it. It stays in place with what was removed, kept, skipped or failed, then moves to the Answered shelf. Anyone who cannot answer sees it read-only. Co-Authored-By: Claude Sonnet 5.5 --- .../src/j5/a2a/CrewWorktreeCleanupSection.tsx | 446 ++++++++++++++++++ apps/web/src/j5/a2a/HumanInboxPage.tsx | 37 +- .../j5/a2a/crewWorktreeCleanup.logic.test.ts | 162 +++++++ .../src/j5/a2a/crewWorktreeCleanup.logic.ts | 171 +++++++ .../src/j5/a2a/crewWorktreeCleanupClient.ts | 38 ++ apps/web/src/j5/state.ts | 17 + 6 files changed, 868 insertions(+), 3 deletions(-) create mode 100644 apps/web/src/j5/a2a/CrewWorktreeCleanupSection.tsx create mode 100644 apps/web/src/j5/a2a/crewWorktreeCleanup.logic.test.ts create mode 100644 apps/web/src/j5/a2a/crewWorktreeCleanup.logic.ts create mode 100644 apps/web/src/j5/a2a/crewWorktreeCleanupClient.ts diff --git a/apps/web/src/j5/a2a/CrewWorktreeCleanupSection.tsx b/apps/web/src/j5/a2a/CrewWorktreeCleanupSection.tsx new file mode 100644 index 0000000000000..47abea2f14281 --- /dev/null +++ b/apps/web/src/j5/a2a/CrewWorktreeCleanupSection.tsx @@ -0,0 +1,446 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + ArrowUpRightIcon, + ChevronRightIcon, + CircleCheckIcon, + CircleMinusIcon, + CircleXIcon, + TriangleAlertIcon, +} from "lucide-react"; +import { useMemo, 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 = useMemo(() => mergeWorktreeCleanupSources(openSources), [openSources]); + const decided = useMemo(() => mergeWorktreeCleanupSources(decidedSources), [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(({ [key]: _cleared, ...rest }) => rest); + 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.", + })); + } finally { + setPendingKey(null); + } + }; + + return { + inPlace, + shelf, + openCount: inPlace.filter((item) => item.status === "open").length, + pendingKey, + errors, + answer, + }; +} + +const unavailable = "This environment is unavailable or this connection is read-only."; + +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 db7fe4a9dd3d5..6d11479a0329a 100644 --- a/apps/web/src/j5/a2a/HumanInboxPage.tsx +++ b/apps/web/src/j5/a2a/HumanInboxPage.tsx @@ -47,6 +47,13 @@ import { useNativeQuestionInbox, } from "../crew/crewRuntimeRequestsClient"; import { NativeQuestionInboxSection } from "./NativeQuestionInboxSection"; +import { + CrewWorktreeCleanupSection, + DecidedCleanupRow, + useWorktreeCleanupInbox, +} from "./CrewWorktreeCleanupSection"; +import { refreshWorktreeCleanups } from "./crewWorktreeCleanupClient"; +import { worktreeCleanupKey, type ScopedWorktreeCleanup } from "./crewWorktreeCleanup.logic"; import { answeredInboxQueryAtom, answeredInboxSourcesAtom, @@ -381,18 +388,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 (
    @@ -401,7 +411,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) => { @@ -429,6 +441,13 @@ function AnsweredShelf({ ); })} + {cleanups.map((item) => ( + + ))}
    ); @@ -446,6 +465,7 @@ export async function refreshHumanInboxes(environmentId?: EnvironmentId, force = 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); @@ -523,6 +543,7 @@ export function HumanInboxPage() { const runtimeRequests = useCrewRuntimeRequests(); const runtimeSources = useAtomValue(crewRuntimeRequestSourcesAtom); const nativeQuestions = useNativeQuestionInbox(); + const cleanups = useWorktreeCleanupInbox(); const previousOpenItems = useRef(new Map>()); useEffect(() => { const next = new Map>(); @@ -659,7 +680,7 @@ export function HumanInboxPage() {

    {loading && items.length === 0 ? "Loading questions waiting on you…" - : `${items.length} ${complete ? "open" : "loaded"} ${items.length === 1 ? "question" : "questions"}${ + : `${items.length + cleanups.openCount} ${complete ? "open" : "loaded"} ${items.length + cleanups.openCount === 1 ? "question" : "questions"}${ runtimeRequests.length + nativeQuestions.length === 0 ? "" : ` · ${runtimeRequests.length + nativeQuestions.length} agent ${runtimeRequests.length + nativeQuestions.length === 1 ? "request" : "requests"}` @@ -711,6 +732,7 @@ export function HumanInboxPage() { !loading && error === null && shownItems.length === 0 && + cleanups.inPlace.length === 0 && runtimeRequests.length === 0 && nativeQuestions.length === 0 ? (

    @@ -742,7 +764,16 @@ export function HumanInboxPage() { )} + + = {}, +): CrewWorktreeCleanupEntry => ({ + threadId: ThreadId.make(`thread:${name}`), + threadTitle: name, + path: `/wt/${name}`, + branch: `j5/${name}`, + uncommittedFiles: 0, + commitsAhead: 0, + pullRequestUrl: null, + outcome: null, + reason: null, + detail: null, + ...overrides, +}); + +describe("the worktree cleanup item's list", () => { + it("puts uncommitted work first, then commits only, and keeps five rows before Show more", () => { + const rows = orderCleanupRows([ + entry("review", { commitsAhead: 1 }), + entry("tests", { uncommittedFiles: 7 }), + entry("replay", { uncommittedFiles: 12, commitsAhead: 5 }), + entry("docs", { commitsAhead: 3 }), + entry("adapter", { uncommittedFiles: 4, commitsAhead: 2 }), + entry("spike", { uncommittedFiles: 3, commitsAhead: 8 }), + entry("proto", { uncommittedFiles: 2 }), + entry("flaky", { commitsAhead: 1 }), + ]); + expect(rows.map((row) => row.threadTitle)).toEqual([ + "replay", + "tests", + "adapter", + "spike", + "proto", + "docs", + "review", + "flaky", + ]); + const collapsed = sliceCleanupRows(rows, false); + expect(collapsed.shown).toHaveLength(5); + expect(collapsed.hidden).toBe(3); + expect(sliceCleanupRows(rows, true)).toEqual({ shown: rows, hidden: 0 }); + expect(sliceCleanupRows(rows.slice(0, 5), false).hidden).toBe(0); + }); +}); + +describe("picking worktrees to remove", () => { + const entries = [entry("a"), entry("b"), entry("c")]; + + it("starts with nothing picked: Remove is disabled at 0 and Select all is not", () => { + expect(cleanupButtons(new Set(), entries)).toEqual({ + removeLabel: "Remove selected (0)", + removeDisabled: true, + selectAllDisabled: false, + }); + }); + + it("counts the picks, and disables Select all once every row is picked", () => { + const picked = toggleCleanupPath(toggleCleanupPath(new Set(), "/wt/a"), "/wt/c"); + expect(cleanupButtons(picked, entries)).toMatchObject({ + removeLabel: "Remove selected (2)", + removeDisabled: false, + selectAllDisabled: false, + }); + const all = new Set(entries.map((row) => row.path)); + expect(cleanupButtons(all, entries)).toMatchObject({ + removeLabel: "Remove selected (3)", + selectAllDisabled: true, + }); + expect(toggleCleanupPath(picked, "/wt/a").has("/wt/a")).toBe(false); + }); + + it("sends only picks the item still lists, in its order", () => { + const picked = new Set(["/wt/c", "/wt/gone", "/wt/a"]); + expect(pickedCleanupPaths(picked, entries)).toEqual(["/wt/a", "/wt/c"]); + expect(cleanupButtons(picked, entries).removeLabel).toBe("Remove selected (2)"); + }); +}); + +describe("the decided item", () => { + const decided = [ + entry("done", { outcome: "removed" }), + entry("later", { outcome: "kept" }), + entry("busy", { outcome: "skipped", reason: "in_use" }), + entry("changed", { outcome: "skipped", reason: "changed" }), + entry("locked", { outcome: "failed", detail: "git worktree remove failed" }), + ]; + + it("groups by outcome in the order removed, kept, skipped, failed", () => { + expect( + groupCleanupOutcomes(decided).map((group) => [ + group.label, + group.rows.map((row) => row.threadTitle), + ]), + ).toEqual([ + ["Removed", ["done"]], + ["Kept", ["later"]], + ["Skipped", ["busy", "changed"]], + ["Failed", ["locked"]], + ]); + expect(groupCleanupOutcomes(decided.slice(0, 1)).map((group) => group.label)).toEqual([ + "Removed", + ]); + expect(outcomeSummary(decided)).toBe("1 removed · 1 kept · 2 skipped · 1 failed"); + }); + + it("gives each row its reason: not picked, why it was skipped, git's own text", () => { + expect(decided.map(outcomeReason)).toEqual([ + null, + "Not picked", + "A session is open in it", + "Changed since this was filed", + "git worktree remove failed", + ]); + }); +}); + +describe("a refused answer", () => { + it("says it was already answered in the server's words, and shows the decided item", () => { + const refusal = Object.assign(new Error("This worktree cleanup was already answered."), { + code: "CrewWorktreeCleanupAnsweredError", + }); + expect(answerFailure(refusal)).toEqual({ message: ANSWERED_ALREADY, alreadyAnswered: true }); + expect(ANSWERED_ALREADY).toBe("This worktree cleanup was already answered."); + }); + + it("keeps any other failure open with its own message", () => { + expect( + answerFailure( + Object.assign(new Error("Owners only."), { code: "EnvironmentAuthorizationError" }), + ), + ).toEqual({ message: "Owners only.", alreadyAnswered: false }); + expect(answerFailure("boom")).toEqual({ + message: "Could not answer the worktree cleanup.", + alreadyAnswered: false, + }); + }); +}); + +it("names a pull request by its number when the link has one", () => { + expect(pullRequestLabel("https://github.com/Jacksondr5/j5code/pull/815")).toBe("PR #815"); + expect(pullRequestLabel("https://example.test/mr/7")).toBe("Pull request"); +}); diff --git a/apps/web/src/j5/a2a/crewWorktreeCleanup.logic.ts b/apps/web/src/j5/a2a/crewWorktreeCleanup.logic.ts new file mode 100644 index 0000000000000..7126cf7f52e97 --- /dev/null +++ b/apps/web/src/j5/a2a/crewWorktreeCleanup.logic.ts @@ -0,0 +1,171 @@ +import type { J5ReadSources } from "@t3tools/client-runtime/j5/readSources"; +import type { EnvironmentId } from "@t3tools/contracts"; +import type { + CrewWorktreeCleanupEntry, + CrewWorktreeCleanupItem, + CrewWorktreeCleanupListResponse, +} from "@t3tools/contracts/j5"; + +export type ScopedWorktreeCleanup = CrewWorktreeCleanupItem & { + readonly environmentId: EnvironmentId; + readonly environmentLabel: string; + readonly connected: boolean; + readonly sourceReady: boolean; +}; + +export const worktreeCleanupKey = (item: Pick) => + JSON.stringify([item.environmentId, item.id]); + +/** Open ones oldest first, like asks of one urgency; decided ones newest first. */ +export function mergeWorktreeCleanupSources( + sources: J5ReadSources, +): ReadonlyArray { + return sources.sources + .flatMap((source) => + (source.data?.items ?? []).map((item) => ({ + ...item, + environmentId: source.environmentId, + environmentLabel: source.environmentLabel, + connected: source.connected, + sourceReady: source.status === "ready", + })), + ) + .toSorted((left, right) => + left.status === "open" + ? left.filedAt.localeCompare(right.filedAt) + : (right.decidedAt ?? "").localeCompare(left.decidedAt ?? ""), + ); +} + +/** Five rows show before "Show N more". */ +export const WORKTREE_CLEANUP_VISIBLE_ROWS = 5; + +/** Uncommitted work first, then commits only; the more of each, the nearer the top. */ +export const orderCleanupRows = (entries: ReadonlyArray) => + entries.toSorted( + (left, right) => + right.uncommittedFiles - left.uncommittedFiles || + (right.commitsAhead ?? 0) - (left.commitsAhead ?? 0), + ); + +export const sliceCleanupRows = (rows: ReadonlyArray, showAll: boolean) => ({ + shown: showAll ? rows : rows.slice(0, WORKTREE_CLEANUP_VISIBLE_ROWS), + hidden: showAll ? 0 : Math.max(0, rows.length - WORKTREE_CLEANUP_VISIBLE_ROWS), +}); + +export const toggleCleanupPath = (selected: ReadonlySet, path: string) => { + const next = new Set(selected); + if (!next.delete(path)) next.add(path); + return next; +}; + +/** What the person picked that the item still lists, in the item's order. */ +export const pickedCleanupPaths = ( + selected: ReadonlySet, + entries: ReadonlyArray, +) => entries.map((entry) => entry.path).filter((path) => selected.has(path)); + +export const cleanupButtons = ( + selected: ReadonlySet, + entries: ReadonlyArray, +) => { + const picked = pickedCleanupPaths(selected, entries).length; + return { + removeLabel: `Remove selected (${picked})`, + removeDisabled: picked === 0, + selectAllDisabled: picked === entries.length, + }; +}; + +const plural = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`; + +export const uncommittedFilesLabel = (count: number) => + plural(count, "uncommitted file", "uncommitted files"); + +/** Null commits means the default branch could not be compared. */ +export const commitsAheadLabel = (count: number | null) => + count === null + ? "commits not compared" + : `${count} ${count === 1 ? "commit" : "commits"} not on the default branch`; + +export const cleanupTitle = (item: Pick) => + `${plural(item.entries.length, "worktree", "worktrees")} from "${item.crewName}" still ${item.entries.length === 1 ? "holds" : "hold"} unfinished work`; + +type SkipReason = NonNullable; + +const skipReasonText: Record = { + changed: "Changed since this was filed", + shared: "Another thread uses it", + in_use: "A session is open in it", + gone: "Already gone", + unverified: "Couldn't be checked", +}; + +export const OUTCOME_GROUPS = [ + { outcome: "removed", label: "Removed" }, + { outcome: "kept", label: "Kept" }, + { outcome: "skipped", label: "Skipped" }, + { outcome: "failed", label: "Failed" }, +] as const; + +/** Why a decided worktree is where it is: nothing for removed, the git error for a failure. */ +export const outcomeReason = (entry: CrewWorktreeCleanupEntry): string | null => { + switch (entry.outcome) { + case "kept": + return "Not picked"; + case "skipped": + return entry.reason === null ? null : skipReasonText[entry.reason]; + case "failed": + return entry.detail; + default: + return null; + } +}; + +/** The decided item's worktrees by outcome, in the mockup's order, leaving out empty groups. */ +export const groupCleanupOutcomes = (entries: ReadonlyArray) => + OUTCOME_GROUPS.flatMap((group) => { + const rows = entries.filter((entry) => entry.outcome === group.outcome); + return rows.length === 0 ? [] : [{ ...group, rows }]; + }); + +export const outcomeCounts = (entries: ReadonlyArray) => + groupCleanupOutcomes(entries).map((group) => ({ + label: group.outcome, + count: group.rows.length, + })); + +/** The shelf's one line: "1 removed · 3 kept · 3 skipped · 1 failed". */ +export const outcomeSummary = (entries: ReadonlyArray) => + outcomeCounts(entries) + .map(({ label, count }) => `${count} ${label}`) + .join(" · "); + +/** Whether every worktree went as asked: a skip or a failure is what to look at. */ +export const cleanupNeedsAttention = (entries: ReadonlyArray) => + entries.some((entry) => entry.outcome === "skipped" || entry.outcome === "failed"); + +/** "PR #815" for a pull request link that names its number, else a plain "Pull request". */ +export const pullRequestLabel = (url: string) => { + const number = /\/pull\/(\d+)/.exec(url)?.[1]; + return number === undefined ? "Pull request" : `PR #${number}`; +}; + +export const answeredAgeLabel = (elapsed: string) => + elapsed === "just now" ? "answered just now" : elapsed ? `answered ${elapsed} ago` : "answered"; + +export const ANSWERED_ALREADY = "This worktree cleanup was already answered."; + +/** + * What a failed answer means for the item. A refused second answer says so in the server's own + * words and shows the decided item; anything else is the message to show, and the item stays open. + */ +export const answerFailure = (cause: unknown) => { + const message = cause instanceof Error ? cause.message : "Could not answer the worktree cleanup."; + const alreadyAnswered = + typeof cause === "object" && + cause !== null && + "code" in cause && + cause.code === "CrewWorktreeCleanupAnsweredError"; + return { message: alreadyAnswered ? ANSWERED_ALREADY : message, alreadyAnswered }; +}; diff --git a/apps/web/src/j5/a2a/crewWorktreeCleanupClient.ts b/apps/web/src/j5/a2a/crewWorktreeCleanupClient.ts new file mode 100644 index 0000000000000..c02e284d94a3a --- /dev/null +++ b/apps/web/src/j5/a2a/crewWorktreeCleanupClient.ts @@ -0,0 +1,38 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import type { CrewWorktreeCleanupAnswerRequest } from "@t3tools/contracts/j5"; +import * as Cause from "effect/Cause"; + +import { appAtomRegistry } from "../../rpc/atomRegistry"; +import { + decidedWorktreeCleanupSourcesAtom, + j5Environment, + openWorktreeCleanupSourcesAtom, + refreshJ5Sources, + worktreeCleanupQueryAtom, +} from "../state"; + +/** Answer on the environment that holds the item; the refusal's message says why it failed. */ +export async function answerCrewWorktreeCleanup( + environmentId: EnvironmentId, + input: CrewWorktreeCleanupAnswerRequest, +) { + const result = await j5Environment.answerCrewWorktreeCleanup.run(appAtomRegistry, { + environmentId, + input, + }); + if (result._tag === "Failure") throw Cause.squash(result.cause); + return result.value.item; +} + +/** Forced re-read after an answer or a refusal, so the item is as the server has it. */ +export const refreshWorktreeCleanups = (environmentId?: EnvironmentId) => { + const options = { force: true, ...(environmentId === undefined ? {} : { environmentId }) }; + return Promise.all([ + refreshJ5Sources(openWorktreeCleanupSourcesAtom, worktreeCleanupQueryAtom("open"), options), + refreshJ5Sources( + decidedWorktreeCleanupSourcesAtom, + worktreeCleanupQueryAtom("decided"), + options, + ), + ]).then((results) => results.flat()); +}; diff --git a/apps/web/src/j5/state.ts b/apps/web/src/j5/state.ts index 046017313d186..ca38af3b688c7 100644 --- a/apps/web/src/j5/state.ts +++ b/apps/web/src/j5/state.ts @@ -73,6 +73,23 @@ export const answeredInboxSourcesAtom = createJ5ReadSourcesAtom({ capability: "j5ProjectLedger", queryAtom: answeredInboxQueryAtom, }); +// The worktree cleanup approvals an archive files; shown in the Inbox beside the asks. A server +// without the read fails its source alone. +export const worktreeCleanupQueryAtom = + (status: "open" | "decided") => (environmentId: EnvironmentId) => + j5Environment.crewWorktreeCleanups({ environmentId, input: { status } }); +export const openWorktreeCleanupSourcesAtom = createJ5ReadSourcesAtom({ + ...inboxSourcesInput, + label: "web-j5:worktree-cleanup-sources", + capability: "j5ProjectLedger", + queryAtom: worktreeCleanupQueryAtom("open"), +}); +export const decidedWorktreeCleanupSourcesAtom = createJ5ReadSourcesAtom({ + ...inboxSourcesInput, + label: "web-j5:decided-worktree-cleanup-sources", + capability: "j5ProjectLedger", + queryAtom: worktreeCleanupQueryAtom("decided"), +}); export const crewProposalSourcesAtom = createJ5ReadSourcesAtom({ ...inboxSourcesInput, label: "web-j5:crew-proposal-sources", From 79ec5a5b3146989a295c9f397a2e8b00976a5687 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 21:19:31 -0400 Subject: [PATCH 05/14] docs(j5): the worktree cleanup item as the Inbox shows it Co-Authored-By: Claude Sonnet 5.5 --- docs/j5/product/features/archive-flow.md | 2 +- docs/j5/product/features/inbox.md | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/j5/product/features/archive-flow.md b/docs/j5/product/features/archive-flow.md index 61b2d3586973e..f4034562be4b2 100644 --- a/docs/j5/product/features/archive-flow.md +++ b/docs/j5/product/features/archive-flow.md @@ -11,7 +11,7 @@ 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**: branches and pull requests survive, and so does every worktree that holds unfinished work until a person approves its removal. Archiving one agent removes nothing; archiving a Crew removes only the clean, merged worktrees J5 created for its seats ([Crews](crews.md) AC19), and files one Inbox item for the ones it kept with uncommitted or unmerged work, which the person answers ([Inbox](inbox.md) AC18–AC22). 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 until a person approves its removal. Archiving one agent removes nothing; archiving a Crew removes only the clean, merged worktrees J5 created for its seats ([Crews](crews.md) AC19), and files one Inbox item for the ones it kept with uncommitted or unmerged work, where the person removes all, the ones they pick, or none ([Inbox](inbox.md) AC18–AC22). 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. diff --git a/docs/j5/product/features/inbox.md b/docs/j5/product/features/inbox.md index 89dbd427ef1a6..a1fb00e81483b 100644 --- a/docs/j5/product/features/inbox.md +++ b/docs/j5/product/features/inbox.md @@ -31,7 +31,7 @@ A server puts asks only in the inboxes of people who can write to the asking age **Several people.** Where more than one person can write to an agent's thread, the agent can ask one of them, or **everyone here**: everyone who can write to its thread when the ask is read. An ask to everyone appears in each of their inboxes, marked as for everyone, and is counted on each of their bells. The first reply closes it for all of them, as any reply closes an ask, and for the others it moves to the Replied shelf showing who answered. A reply that arrives after that is refused and changes nothing. A person who had started typing an answer keeps the item in place, with their words, and sees who answered. In a thread only one person can write to, there is no "everyone here": the agent asks that person ([shared conversations](shared-conversations.md)). -**Worktree cleanup.** When archiving a Crew keeps worktrees J5 created for its seats because they hold uncommitted changes or commits that never merged, the archive files one item for all of them, however many seats and worktrees it covered. No agent sent it, it is not an Exchange, and no agent can answer it. Each worktree shows its thread, its branch, its uncommitted files, its commits not on the default branch, and its pull request when it has one, and the item says that removing discards the uncommitted changes and keeps the branch. The person removes all, removes the ones they pick, or keeps all, which clears the item and changes nothing. Each worktree they approve is checked again first; one that changed, is now used by an unarchived thread or an open session, or is already gone is skipped and reported, and a removal that fails is reported with its reason. The item resolves once, and afterwards shows what was removed, kept, skipped or failed. +**Worktree cleanup.** When archiving a Crew keeps worktrees J5 created for its seats because they hold uncommitted changes or commits that never merged, the archive files one item for all of them, however many seats and worktrees it covered. No agent sent it, it is not an Exchange, and no agent can answer it; it reads "J5" as its sender, is marked FYI, and sits after the asks. Each worktree shows its thread, its branch, its uncommitted files, its commits not on the default branch, and its pull request when it has one, and the item says that removing discards the uncommitted changes and keeps the branch. Nothing is picked at first: the person keeps all, which clears the item and changes nothing, selects the worktrees to remove, or selects all. Each worktree they approve is checked again first; one that changed, is now used by an unarchived thread or an open session, or is already gone is skipped and reported, and a removal that fails is reported with its reason. The item resolves once, stays in place afterwards showing what was removed, kept, skipped or failed, and then lives on the Answered shelf. The Inbox is reached from a bell in the rail that counts open asks, seat approvals, native-question links and worktree cleanups, and opens a full page. It is available on web and desktop, over local, remote and tunnel connections; mobile has no J5 Inbox surface. @@ -73,11 +73,11 @@ The inbox is **not** a backlog (a non-blocking note an agent wants to keep is a ### Worktree cleanup -18. An archive of a Crew that keeps J5-created worktrees for uncommitted changes or unmerged commits files exactly one item for that Crew, however many seats and worktrees; archiving again while it is open files nothing more. The item has no sender, is not an Exchange, and counts on the bell. -19. Each worktree in the item shows its thread and branch, the number of its uncommitted files, the number of its commits not on the default branch, and its pull request link when it has one; the item says that removing discards uncommitted changes and keeps the branch. -20. The person can remove every worktree, remove the ones they pick, or keep all; keeping all clears the item and changes nothing. Only an Owner answers it, from the app; no agent tool does. +18. An archive of a Crew that keeps J5-created worktrees for uncommitted changes or unmerged commits files exactly one item for that Crew, however many seats and worktrees; archiving again while it is open files nothing more. The item has no sender, is not an Exchange, reads "J5" with urgency FYI, and counts on the bell. +19. Each worktree in the item shows its thread and branch, the number of its uncommitted files, the number of its commits not on the default branch, and its pull request link when it has one; the item says that removing discards uncommitted changes and keeps the branch. Worktrees with uncommitted work come first, and a list longer than five shows five rows and "Show N more". +20. No worktree is picked at first. The person can keep all, which clears the item and changes nothing, pick worktrees and remove them (Remove selected is disabled while none is picked), or select all (disabled once every worktree is picked). Only an Owner answers it, from the app, and anyone else sees it read-only; no agent tool answers it. 21. Before removing an approved worktree, J5 checks it again and skips and reports it when its commit or its list of changed files differs from when the archive kept it, another unarchived thread now uses it, its thread was unarchived, or a provider session is open in it. A worktree already removed some other way is skipped without error, and a removal that fails is reported with its reason without stopping the others. -22. The item resolves once: a second answer is refused with a message, and the item clears on the person's other devices. Afterwards it shows each worktree as removed, kept, skipped or failed, with the reason. +22. The item resolves once: a second answer is refused with "This worktree cleanup was already answered." and the item shows its decided state, and it clears on the person's other devices. Afterwards it stays in place showing each worktree as removed, kept ("Not picked"), skipped (changed since it was filed, another thread uses it, a session is open in it, already gone, or couldn't be checked) or failed (git's own error text), and then moves to the Answered shelf as a one-line count of each. Nothing is offered to retry a skipped or failed worktree. ## Scenarios From 16cb7824a1aefba0d5e6356cd0721def3d135553 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Wed, 28 Oct 2026 12:53:38 -0400 Subject: [PATCH 06/14] fix(j5): the removal recheck compares file contents, and a Crew files one cleanup item The recheck before a forced removal compared git status, which lists names and codes, so an edit to a file that was already changed went unseen and was deleted. It now compares what is in those files, and keeps a worktree it can't compare (a nested repository, or a status git cut off). An archive that runs again after "Keep all" no longer files a second item for the same Crew. Co-Authored-By: Claude Sonnet 5.5 --- apps/server/src/j5/a2a/CrewWorktrees.test.ts | 67 +++++++++++++++++++ apps/server/src/j5/a2a/CrewWorktrees.ts | 48 ++++++++++--- .../051_CrewWorktreeCleanup.test.ts | 28 ++++++++ .../a2a/migrations/051_CrewWorktreeCleanup.ts | 7 +- docs/j5/product/features/archive-flow.md | 2 +- docs/j5/product/features/inbox.md | 6 +- docs/j5/product/overview.md | 2 +- 7 files changed, 144 insertions(+), 16 deletions(-) create mode 100644 apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.test.ts diff --git a/apps/server/src/j5/a2a/CrewWorktrees.test.ts b/apps/server/src/j5/a2a/CrewWorktrees.test.ts index 81b84c633a84d..521c2308bbcc9 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.test.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.test.ts @@ -945,6 +945,73 @@ it.effect("keeping all clears the item and changes nothing", () => ), ); +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 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* () { diff --git a/apps/server/src/j5/a2a/CrewWorktrees.ts b/apps/server/src/j5/a2a/CrewWorktrees.ts index 026285e3f8ea7..74ddc4d923d47 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.ts @@ -135,7 +135,7 @@ export interface CrewWorktreesShape { readonly seats: ReadonlyArray; /** * Given, the worktrees kept for unfinished work (uncommitted changes, unmerged commits) are - * also filed as one Inbox approval for this Crew, unless it already has an open one. + * also filed as one Inbox approval for this Crew, unless it already has one. */ readonly crew?: { readonly crewInstanceId: string; @@ -336,6 +336,38 @@ const makeLayer = (daemon: boolean) => const digestOf = (text: string) => NodeCrypto.createHash("sha256").update(text).digest("hex"); + /** + * What the worktree holds uncommitted, by content: the status lists names and codes, so an + * edit to a file that was already dirty would not show. Status git cut off, or a folder it + * lists whole (a nested repository), 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() }; + if (paths.length === 0) return { status, digest: digestOf(status.stdout) }; + const hashed = yield* git.execute({ + operation: "CrewWorktrees.contents", + cwd: worktreePath, + args: ["hash-object", "--", ...paths], + allowNonZeroExit: true, + }); + return { + status, + digest: + hashed.exitCode === 0 && !hashed.stdoutTruncated + ? digestOf(`${status.stdout}\n${hashed.stdout}`) + : unmatched(), + }; + }); + /** * 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. @@ -423,12 +455,12 @@ const makeLayer = (daemon: boolean) => if ((yield* sessionOpenIn(worktreePath)) || (yield* terminalOpenIn(worktreePath))) return { kind: "keep", reason: "in_use" } satisfies Verdict; if (context.baseline !== undefined) { - const [head, status] = yield* Effect.all([ + const [head, snapshot] = yield* Effect.all([ git.resolveCommit({ cwd: worktreePath, revision: "HEAD" }), - localChanges(worktreePath), + snapshotOf(worktreePath), ]); return head.commitSha === context.baseline.headSha && - digestOf(status.stdout) === context.baseline.statusDigest + snapshot.digest === context.baseline.statusDigest ? ({ kind: "remove", headSha: head.commitSha } satisfies Verdict) : ({ kind: "changed" } satisfies Verdict); } @@ -517,8 +549,8 @@ const makeLayer = (daemon: boolean) => /** 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, head] = yield* Effect.all([ - localChanges(worktreePath), + const [{ status, digest }, head] = yield* Effect.all([ + snapshotOf(worktreePath), git.resolveCommit({ cwd: worktreePath, revision: "HEAD" }), ]); const commitsAhead = yield* Effect.gen(function* () { @@ -558,11 +590,11 @@ const makeLayer = (daemon: boolean) => reason: null, detail: null, headSha: head.commitSha, - statusDigest: digestOf(status.stdout), + statusDigest: digest, } satisfies StoredCleanupEntry; }); - /** One approval per archive: a Crew with an open one keeps it, so an archive that runs again files nothing. */ + /** One approval per Crew, answered or not, so an archive that runs again files nothing. */ const fileCleanup = Effect.fnUntraced(function* ( crew: NonNullable[0]["crew"]>, unfinished: ReadonlyArray, 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..67463b937493f --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.test.ts @@ -0,0 +1,28 @@ +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 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) => sql` + INSERT INTO j5_crew_worktree_cleanup ( + id, crew_instance_id, crew_name, project_id, captain_thread_id, filed_at, entries_json + ) + VALUES (${id}, ${crew}, 'Crew', 'project:one', 'thread:captain', '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"); + }).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 index caafde50b8a48..1a9b9b5c6b424 100644 --- a/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.ts +++ b/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.ts @@ -4,7 +4,8 @@ import * as SqlClient from "effect/sql/SqlClient"; /** * The Inbox approval an archive files for the worktrees it kept with unfinished work: one row per * item, its worktrees (as measured, then as decided) in `entries_json`. An item is open until - * `decided_at` is set, and a Crew has at most one open item. + * `decided_at` is set, and a Crew has at most one item, open or decided, so an archive that runs + * again after "Keep all" files nothing. */ export default Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; @@ -21,7 +22,7 @@ export default Effect.gen(function* () { ) `; yield* sql` - CREATE UNIQUE INDEX j5_crew_worktree_cleanup_open_crew - ON j5_crew_worktree_cleanup (crew_instance_id) WHERE decided_at IS NULL + CREATE UNIQUE INDEX j5_crew_worktree_cleanup_crew + ON j5_crew_worktree_cleanup (crew_instance_id) `; }); diff --git a/docs/j5/product/features/archive-flow.md b/docs/j5/product/features/archive-flow.md index f4034562be4b2..72e10ee2b49ea 100644 --- a/docs/j5/product/features/archive-flow.md +++ b/docs/j5/product/features/archive-flow.md @@ -36,7 +36,7 @@ Archiving is **not** deleting, **not** a way to archive a single Crew member, an ### The dialog 2. An agent with no open Exchanges and no agents beneath it archives immediately, with no dialog. -3. Otherwise the dialog names the agent in its title, lists the agents beneath it, lists every live Crew the agent commands with each seat's running turn and open asks, lists every open ask with its urgency, direction, counterpart, time open, and verbatim intent, states the count of asks that will be terminated, and reassures that the workspace survives. +3. Otherwise the dialog names the agent in its title, lists the agents beneath it, lists every live Crew the agent commands with each seat's running turn and open asks, lists every open ask with its urgency, direction, counterpart, time open, and verbatim intent, states the count of asks that will be terminated, and reassures that the workspace survives (archiving a Crew removes only the clean, merged worktrees J5 created for its seats). 4. An ask row names its counterpart by display name — an agent's thread title, a person's name with "(inbox)" — and never shows a raw id; an unnamed counterpart reads "Unnamed participant". 5. The dialog has one confirm and no type-to-confirm. diff --git a/docs/j5/product/features/inbox.md b/docs/j5/product/features/inbox.md index a1fb00e81483b..608ebbc862830 100644 --- a/docs/j5/product/features/inbox.md +++ b/docs/j5/product/features/inbox.md @@ -41,7 +41,7 @@ The inbox is **not** a backlog (a non-blocking note an agent wants to keep is a ### Contents -1. The Inbox lists open asks addressed to the person, live Crew-seat provider approvals, and actionable pending native questions from J5-spawned Peer Agents and live Crew seats across connected environments. Native questions open the original thread form and disappear when resolved; they are not answered as Exchanges. No plain messages or inferred stalls are added. +1. The Inbox lists open asks addressed to the person, live Crew-seat provider approvals, worktree cleanup items, and actionable pending native questions from J5-spawned Peer Agents and live Crew seats across connected environments. Native questions open the original thread form and disappear when resolved; they are not answered as Exchanges. No plain messages or inferred stalls are added. 2. A plain message from an agent to a person is refused at the tool; the person's row in the address book says it cannot receive one. 3. Several open asks from the same agent to the same person appear as separate items; a follow-up that references an open ask by its Exchange id appears beneath that ask's original text in the same item. 4. The bell's count equals the number of open items. @@ -73,10 +73,10 @@ The inbox is **not** a backlog (a non-blocking note an agent wants to keep is a ### Worktree cleanup -18. An archive of a Crew that keeps J5-created worktrees for uncommitted changes or unmerged commits files exactly one item for that Crew, however many seats and worktrees; archiving again while it is open files nothing more. The item has no sender, is not an Exchange, reads "J5" with urgency FYI, and counts on the bell. +18. An archive of a Crew that keeps J5-created worktrees for uncommitted changes or unmerged commits files exactly one item for that Crew, however many seats and worktrees; archiving again files nothing more, whether the item is open or answered. The item has no sender, is not an Exchange, reads "J5" with urgency FYI, and counts on the bell. 19. Each worktree in the item shows its thread and branch, the number of its uncommitted files, the number of its commits not on the default branch, and its pull request link when it has one; the item says that removing discards uncommitted changes and keeps the branch. Worktrees with uncommitted work come first, and a list longer than five shows five rows and "Show N more". 20. No worktree is picked at first. The person can keep all, which clears the item and changes nothing, pick worktrees and remove them (Remove selected is disabled while none is picked), or select all (disabled once every worktree is picked). Only an Owner answers it, from the app, and anyone else sees it read-only; no agent tool answers it. -21. Before removing an approved worktree, J5 checks it again and skips and reports it when its commit or its list of changed files differs from when the archive kept it, another unarchived thread now uses it, its thread was unarchived, or a provider session is open in it. A worktree already removed some other way is skipped without error, and a removal that fails is reported with its reason without stopping the others. +21. Before removing an approved worktree, J5 checks it again and skips and reports it when its commit, its list of changed files or what is in those files differs from when the archive kept it (a nested repository or a very long list of changes can't be compared, so it is skipped), another unarchived thread now uses it, its thread was unarchived, or a provider session is open in it. A worktree already removed some other way is skipped without error, and a removal that fails is reported with its reason without stopping the others. 22. The item resolves once: a second answer is refused with "This worktree cleanup was already answered." and the item shows its decided state, and it clears on the person's other devices. Afterwards it stays in place showing each worktree as removed, kept ("Not picked"), skipped (changed since it was filed, another thread uses it, a session is open in it, already gone, or couldn't be checked) or failed (git's own error text), and then moves to the Answered shelf as a one-line count of each. Nothing is offered to retry a skipped or failed worktree. ## Scenarios diff --git a/docs/j5/product/overview.md b/docs/j5/product/overview.md index 8b62517db4bf4..11a803c542f78 100644 --- a/docs/j5/product/overview.md +++ b/docs/j5/product/overview.md @@ -16,7 +16,7 @@ These areas are J5's. Their definitions are the source of truth; build within th | Area | What it is | Definition | | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Agent-to-agent communication | Agents message each other directly. An ask opens an Exchange that the receiver owes a reply to; silence is noticed and surfaced. | [A2A](a2a/index.md), [agent tools](a2a/agent-tools.md), [upstream substrate](a2a/substrate.md) | -| Inbox | The person's one queue of open asks addressed to them, across every connected environment. | [Inbox](features/inbox.md) | +| Inbox | The person's one queue of open asks, approvals and worktree cleanups addressed to them, across every connected environment. | [Inbox](features/inbox.md) | | Agent-to-agent messages in the thread | How A2A traffic renders in a thread: as cards, leaving upstream's conversation rendering untouched. | [Thread A2A rendering](features/thread-a2a-rendering.md) | | Crews and Captains | A group of agents launched as a unit from a roster its Captain proposes, with human approval on by default. The Captain is the thread the person watches. | [Crews](features/crews.md) | | Personas | Reusable, user-authored definitions of a kind of agent: instructions, model routes, runtime policy, declared handoff artifact. | [Roles](features/roles.md), [persona contract](agent-personas/index.md) | From 2a7be7490c9635e127b04932408921f6208c9ca0 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Mon, 2 Nov 2026 09:43:14 -0500 Subject: [PATCH 07/14] fix(j5): a Crew archived again after it came back files its own cleanup item The cleanup item is now keyed on the archive (the Crew and its archived stamp), so the same archive run again still files nothing, while a Crew restored with its Captain and archived a second time files a new one. Bringing the Crew back withdraws an item still open for the earlier archive. An answered item stays as the record. Migration 051 is edited in place: it is only in this unmerged stack. Co-Authored-By: Claude Sonnet 5.5 --- .../src/j5/a2a/ArchiveCrewService.test.ts | 18 +++++++-- apps/server/src/j5/a2a/ArchiveCrewService.ts | 7 ++-- .../j5/a2a/CrewCaptainArchiveCascade.test.ts | 15 +++++++ .../src/j5/a2a/CrewCaptainArchiveCascade.ts | 6 ++- apps/server/src/j5/a2a/CrewWorktrees.test.ts | 37 +++++++++++++++++ apps/server/src/j5/a2a/CrewWorktrees.ts | 33 +++++++++++++-- .../051_CrewWorktreeCleanup.test.ts | 40 +++++++++++-------- .../a2a/migrations/051_CrewWorktreeCleanup.ts | 8 ++-- 8 files changed, 134 insertions(+), 30 deletions(-) diff --git a/apps/server/src/j5/a2a/ArchiveCrewService.test.ts b/apps/server/src/j5/a2a/ArchiveCrewService.test.ts index 2801bb739b24f..a9ccf9d757cfc 100644 --- a/apps/server/src/j5/a2a/ArchiveCrewService.test.ts +++ b/apps/server/src/j5/a2a/ArchiveCrewService.test.ts @@ -94,14 +94,16 @@ 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>([]); const layer = archiveCrewLayer.pipe( Layer.provide( Layer.mergeAll( Layer.mock(CrewWorktrees)({ - cleanup: ({ seats }) => + cleanup: ({ seats, crew }) => Effect.all([ + 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))), @@ -196,6 +198,7 @@ const fixture = Effect.gen(function* () { crewArchivedAt, cleanedSeats, cleanupResult, + approvalStamps, lifecycleAtCleanup, }; }); @@ -510,7 +513,7 @@ it.effect( 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 })); @@ -518,9 +521,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 1d9bdeac27fa7..d15801ff3fbbc 100644 --- a/apps/server/src/j5/a2a/ArchiveCrewService.ts +++ b/apps/server/src/j5/a2a/ArchiveCrewService.ts @@ -216,8 +216,9 @@ const createdSeats = (facts: ArchiveCrewConsequenceFacts) => .map((member) => ({ seatName: member.seatName, threadId: member.threadId })); /** Who the worktree approval is filed for. */ -const approvalCrew = (instance: AgentCrewInstance) => ({ +const approvalCrew = (instance: AgentCrewInstance, archivedAt: string) => ({ crewInstanceId: instance.id, + archivedAt: instance.archivedAt ?? archivedAt, crewName: instance.displayName, projectId: instance.projectId, captainThreadId: instance.captainThreadId, @@ -415,7 +416,7 @@ export const layer = Layer.effect( : ("already_archived" as const), })), seats: createdSeats(facts), - crew: approvalCrew(instance), + crew: approvalCrew(instance, input.archivedAt), }; } @@ -494,7 +495,7 @@ export const layer = Layer.effect( status: "archived" as const, members: results, seats: createdSeats(facts), - crew: approvalCrew(instance), + crew: approvalCrew(instance, input.archivedAt), }; }, (unit, input) => crews.serialize(input.crewInstanceId, unit), 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.test.ts b/apps/server/src/j5/a2a/CrewWorktrees.test.ts index d4f421cdcf86e..545ac0200faaa 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.test.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.test.ts @@ -798,6 +798,7 @@ 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"), @@ -997,6 +998,42 @@ it.effect("skips a worktree whose files were already changed when they change ag ), ); +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* () { diff --git a/apps/server/src/j5/a2a/CrewWorktrees.ts b/apps/server/src/j5/a2a/CrewWorktrees.ts index 255eb5324a7ca..7b085df115d02 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.ts @@ -135,10 +135,12 @@ export interface CrewWorktreesShape { readonly seats: ReadonlyArray; /** * Given, the worktrees kept for unfinished work (uncommitted changes, unmerged commits) are - * also filed as one Inbox approval for this Crew, unless it already has one. + * 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; @@ -148,6 +150,11 @@ export interface CrewWorktreesShape { 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 @@ -596,7 +603,7 @@ const makeLayer = (daemon: boolean) => } satisfies StoredCleanupEntry; }); - /** One approval per Crew, answered or not, so an archive that runs again files nothing. */ + /** 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, @@ -604,11 +611,12 @@ const makeLayer = (daemon: boolean) => 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, filed_at, entries_json + 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}, ${DateTime.formatIso(yield* DateTime.now)}, + ${crew.captainThreadId}, ${crew.archivedAt}, ${DateTime.formatIso(yield* DateTime.now)}, ${yield* encodeEntries(entries)} ) ON CONFLICT DO NOTHING @@ -617,6 +625,22 @@ const makeLayer = (daemon: boolean) => 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, crew }) { // No seat is exempt: a seat that was unarchived since the archive committed is bound to @@ -899,6 +923,7 @@ const makeLayer = (daemon: boolean) => handleStoredEvent, cleanup, estimate, + withdrawCleanup, listCleanups, answerCleanup, }); diff --git a/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.test.ts b/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.test.ts index 67463b937493f..6a3651dc2d5bf 100644 --- a/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.test.ts +++ b/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.test.ts @@ -5,24 +5,32 @@ import * as SqlClient from "effect/sql/SqlClient"; import { runJ5A2AMigrations } from "../Migrations.ts"; -it.effect("adds the cleanup table with one item per Crew, and is safe to run again", () => - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - yield* runJ5A2AMigrations({ toMigrationInclusive: 50 }); - yield* runJ5A2AMigrations(); - yield* runJ5A2AMigrations(); +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) => sql` + 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, filed_at, entries_json + 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', '[]' ) - VALUES (${id}, ${crew}, 'Crew', 'project:one', 'thread:captain', '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"); - }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), + 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 index 1a9b9b5c6b424..73d509cec9b6a 100644 --- a/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.ts +++ b/apps/server/src/j5/a2a/migrations/051_CrewWorktreeCleanup.ts @@ -4,8 +4,9 @@ import * as SqlClient from "effect/sql/SqlClient"; /** * The Inbox approval an archive files for the worktrees it kept with unfinished work: one row per * item, its worktrees (as measured, then as decided) in `entries_json`. An item is open until - * `decided_at` is set, and a Crew has at most one item, open or decided, so an archive that runs - * again after "Keep all" files nothing. + * `decided_at` is set, and an archive of a Crew (named by the Crew's `archived_at`) has at most one + * item, open or decided, so the same archive run again after "Keep all" files nothing, while a + * Crew restored with its Captain and archived again files its own. */ export default Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; @@ -16,6 +17,7 @@ export default Effect.gen(function* () { 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 @@ -23,6 +25,6 @@ export default Effect.gen(function* () { `; yield* sql` CREATE UNIQUE INDEX j5_crew_worktree_cleanup_crew - ON j5_crew_worktree_cleanup (crew_instance_id) + ON j5_crew_worktree_cleanup (crew_instance_id, archived_at) `; }); From cabe7159bf7b64c044b83d5712eca945a578cec1 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Mon, 2 Nov 2026 09:43:59 -0500 Subject: [PATCH 08/14] fix(j5): a worktree whose commits its branch does not hold is never offered for removal An approved removal keeps the branch, so work only counts as kept when HEAD is reachable from that branch. A seat that detached or switched branches and then committed is kept as unverified, and the recheck refuses it too. Co-Authored-By: Claude Sonnet 5.5 --- apps/server/src/j5/a2a/CrewWorktrees.test.ts | 38 ++++++++++++++++++++ apps/server/src/j5/a2a/CrewWorktrees.ts | 29 ++++++++++++++- 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/apps/server/src/j5/a2a/CrewWorktrees.test.ts b/apps/server/src/j5/a2a/CrewWorktrees.test.ts index 545ac0200faaa..8645eeabb349a 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.test.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.test.ts @@ -998,6 +998,44 @@ it.effect("skips a worktree whose files were already changed when they change ag ), ); +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* () { diff --git a/apps/server/src/j5/a2a/CrewWorktrees.ts b/apps/server/src/j5/a2a/CrewWorktrees.ts index 7b085df115d02..60432480108ce 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.ts @@ -377,6 +377,24 @@ const makeLayer = (daemon: boolean) => }; }); + /** + * 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. @@ -464,6 +482,8 @@ const makeLayer = (daemon: boolean) => 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), @@ -473,8 +493,14 @@ const makeLayer = (daemon: boolean) => ? ({ 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, @@ -484,6 +510,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; From d700a5cdd4733699b950f783538e9be2999f68cc Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Mon, 2 Nov 2026 09:44:45 -0500 Subject: [PATCH 09/14] fix(j5): the removal recheck notices newly staged content under unchanged files The baseline now includes the index tree, so a file that stays modified in the same way with the same working copy, while its staged content changes, no longer matches and the removal is skipped. An index git cannot write a tree for (unmerged entries) never matches, so the worktree is kept. Co-Authored-By: Claude Sonnet 5.5 --- apps/server/src/j5/a2a/CrewWorktrees.test.ts | 30 ++++++++++++++++++ apps/server/src/j5/a2a/CrewWorktrees.ts | 33 +++++++++++++------- 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/apps/server/src/j5/a2a/CrewWorktrees.test.ts b/apps/server/src/j5/a2a/CrewWorktrees.test.ts index 8645eeabb349a..ff91c63e6fe05 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.test.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.test.ts @@ -998,6 +998,36 @@ it.effect("skips a worktree whose files were already changed when they change ag ), ); +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* () { diff --git a/apps/server/src/j5/a2a/CrewWorktrees.ts b/apps/server/src/j5/a2a/CrewWorktrees.ts index 60432480108ce..703936c631f4c 100644 --- a/apps/server/src/j5/a2a/CrewWorktrees.ts +++ b/apps/server/src/j5/a2a/CrewWorktrees.ts @@ -347,8 +347,10 @@ const makeLayer = (daemon: boolean) => /** * What the worktree holds uncommitted, by content: the status lists names and codes, so an - * edit to a file that was already dirty would not show. Status git cut off, or a folder it - * lists whole (a nested repository), cannot be compared, so it never matches again and the + * edit to a file that was already dirty would not show, and neither would a changed staged + * blob under a file whose working copy stayed the same, so the index tree is part of it. + * Status git cut off, a folder it lists whole (a nested repository), or an index git cannot + * write a tree for (unmerged entries) cannot be compared, so it never matches again and the * worktree is kept. */ const snapshotOf = Effect.fnUntraced(function* (worktreePath: string) { @@ -361,18 +363,27 @@ const makeLayer = (daemon: boolean) => .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() }; - if (paths.length === 0) return { status, digest: digestOf(status.stdout) }; - const hashed = yield* git.execute({ - operation: "CrewWorktrees.contents", - cwd: worktreePath, - args: ["hash-object", "--", ...paths], - allowNonZeroExit: true, - }); + 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: - hashed.exitCode === 0 && !hashed.stdoutTruncated - ? digestOf(`${status.stdout}\n${hashed.stdout}`) + index.exitCode === 0 && hashed.exitCode === 0 && !hashed.stdoutTruncated + ? digestOf(`${status.stdout}\n${hashed.stdout}\n${index.stdout}`) : unmatched(), }; }); From a2c758518c922bfcf725685d534ea9321dd312e0 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Mon, 2 Nov 2026 09:48:17 -0500 Subject: [PATCH 10/14] fix(j5): only an Owner is offered, counted and listed a worktree cleanup Answering a cleanup is the Owner's call, but the buttons were gated on operate scope, so a Collaborator saw them enabled and was refused on press, and the Inbox counted items they could not answer. The answer now needs the settings scope an Owner's device holds, on the client and the server, the cleanup list and the open count are an Owner's alone, and the Inbox header counts cleanups as their own clause instead of as questions. Co-Authored-By: Claude Sonnet 5.5 --- apps/server/src/j5/a2a/clientActionRpc.ts | 3 +- apps/server/src/j5/a2a/clientReadRpc.test.ts | 64 +++++++++++-------- apps/server/src/j5/a2a/clientReadRpc.ts | 12 ++-- .../server/src/j5/sharing/connectionWriter.ts | 21 ++++-- apps/server/src/j5/wsRpc.test.ts | 13 ++-- .../src/j5/a2a/CrewWorktreeCleanupSection.tsx | 2 +- apps/web/src/j5/a2a/HumanInboxPage.tsx | 17 +++-- .../j5/a2a/crewWorktreeCleanup.logic.test.ts | 15 +++++ .../src/j5/a2a/crewWorktreeCleanup.logic.ts | 22 +++++++ .../client-runtime/src/j5/actions.test.ts | 9 ++- .../src/j5/clientRpcPermissions.test.ts | 5 ++ .../contracts/src/j5/clientRpcPermissions.ts | 3 +- 12 files changed, 130 insertions(+), 56 deletions(-) diff --git a/apps/server/src/j5/a2a/clientActionRpc.ts b/apps/server/src/j5/a2a/clientActionRpc.ts index 57769f348fb6c..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, @@ -46,7 +47,7 @@ export const CLIENT_ACTION_RPC_SCOPES = { [METHODS.archiveCrew]: AuthOrchestrationOperateScope, [METHODS.respondCrewRuntimeRequest]: AuthOrchestrationOperateScope, [METHODS.answerHumanExchange]: AuthOrchestrationOperateScope, - [METHODS.answerCrewWorktreeCleanup]: AuthOrchestrationOperateScope, + [METHODS.answerCrewWorktreeCleanup]: AuthSettingsWriteScope, [METHODS.issuePeerCredential]: AuthAccessWriteScope, [METHODS.addPeer]: AuthAccessWriteScope, [METHODS.removePeer]: AuthAccessWriteScope, diff --git a/apps/server/src/j5/a2a/clientReadRpc.test.ts b/apps/server/src/j5/a2a/clientReadRpc.test.ts index e9007effa5047..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, ), ), @@ -227,29 +228,40 @@ it.effect("keeps identity requests exact, ordered, and total, and drops an id th }), ); -it.effect("counts an open worktree cleanup the person reaches in the open Inbox count", () => +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( - Layer.mock(ClientReadsService)({ - openInboxCount: (personId) => - Effect.succeed({ personId: personId ?? ParticipantId.make("agent:none"), count: 3 }), - crewWorktreeCleanups: () => - Effect.succeed([ - { - 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 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: [], + }); }), ); diff --git a/apps/server/src/j5/a2a/clientReadRpc.ts b/apps/server/src/j5/a2a/clientReadRpc.ts index afe1cfdde179c..fc45989636b90 100644 --- a/apps/server/src/j5/a2a/clientReadRpc.ts +++ b/apps/server/src/j5/a2a/clientReadRpc.ts @@ -15,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"; @@ -80,17 +80,15 @@ export const makeClientReadRpcHandlers = Effect.fn("j5.makeClientReadRpcHandlers Effect.provideService(PersonAccess, people), Effect.provideService(SharedThreads, shared), ); - // Listed to whoever reaches the Crew's Captain, like its archive's worktrees. + // 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"], ) { - const listed = yield* clientReads + if (!(yield* isOwner(session).pipe(Effect.provideService(PersonAccess, people)))) return []; + return yield* clientReads .crewWorktreeCleanups(status) .pipe(Effect.catch(failed("Reading worktree cleanups failed."))); - const reachesCaptain = yield* reaches; - return yield* Effect.filter(listed, (item) => - reachesCaptain(Effect.succeed(item.captainThreadId)), - ); }); return { [METHODS.listHumanInbox]: (input: HumanInboxListRequest) => 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 2c483c408a289..7a24e07ab1d9e 100644 --- a/apps/server/src/j5/wsRpc.test.ts +++ b/apps/server/src/j5/wsRpc.test.ts @@ -424,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, }, @@ -478,9 +479,13 @@ 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* client[ACTIONS.answerCrewWorktreeCleanup]({ itemId: "cleanup:1", removePaths: [] })) - .item.status, + (yield* owner.client[ACTIONS.answerCrewWorktreeCleanup]({ + itemId: "cleanup:1", + removePaths: [], + })).item.status, "decided", ); assert.deepStrictEqual( @@ -504,11 +509,11 @@ describe("J5 client action RPC handlers", () => { "resolve", "stop", "archive", - "cleanup", "respond", "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 index 47abea2f14281..55fec56c9f837 100644 --- a/apps/web/src/j5/a2a/CrewWorktreeCleanupSection.tsx +++ b/apps/web/src/j5/a2a/CrewWorktreeCleanupSection.tsx @@ -107,7 +107,7 @@ export function useWorktreeCleanupInbox() { }; } -const unavailable = "This environment is unavailable or this connection is read-only."; +const unavailable = "This environment is unavailable, or only an Owner of this server can answer."; function ItemHeader({ item, diff --git a/apps/web/src/j5/a2a/HumanInboxPage.tsx b/apps/web/src/j5/a2a/HumanInboxPage.tsx index 80d2655eabd24..ed1e6ef515c22 100644 --- a/apps/web/src/j5/a2a/HumanInboxPage.tsx +++ b/apps/web/src/j5/a2a/HumanInboxPage.tsx @@ -60,7 +60,11 @@ import { useWorktreeCleanupInbox, } from "./CrewWorktreeCleanupSection"; import { refreshWorktreeCleanups } from "./crewWorktreeCleanupClient"; -import { worktreeCleanupKey, type ScopedWorktreeCleanup } from "./crewWorktreeCleanup.logic"; +import { + inboxSummary, + worktreeCleanupKey, + type ScopedWorktreeCleanup, +} from "./crewWorktreeCleanup.logic"; import { answeredInboxQueryAtom, answeredInboxSourcesAtom, @@ -617,11 +621,12 @@ export function HumanInboxPage() {

    {loading && items.length === 0 ? "Loading questions waiting on you…" - : `${items.length + cleanups.openCount} ${complete ? "open" : "loaded"} ${items.length + cleanups.openCount === 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, + })}