diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index b447411dc3bbf..478cb55f9e61a 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -282,7 +282,7 @@ const WorkReadTool = Tool.make("work_read", { }).annotate(Tool.Readonly, true); const WorkCommandTool = Tool.make("work_command", { description: - "Manage durable T3 work using a typed action. GLaDOS can create-lead and lead-message; project leads manage only their own local tasks and use lead-context/lead-report. Create action requires type=create, taskId, projectId, title, outcome, criteria, verifyCommand, priority, dependencies, workspaceStrategy. create-lead, assign, and active lead-status may include runtimeMode='approval-required' or 'full-access'; it cannot exceed the calling thread's current mode, is saved for that launch, and omission uses the saved worker default. Include authorityGeneration from your role or lead record on management commands. Managers create/assign tasks, inspect and accept evidence, request rework, and acknowledge messages. Workers report questions/progress and submit candidate evidence. Retry an uncertain call with exactly the same commandId and payload. New decisions require the current snapshot revision. When the user asks in conversation, GLaDOS records brief, pause, resolve-decision, approve-verification, verification-profile and verification-recipe changes herself, including revising proof after an attempt. Only electing the role still requires the user.", + "Manage durable T3 work using a typed action. GLaDOS can create-lead and lead-message; project leads manage only their own local tasks and use lead-context/lead-report. Create action requires type=create, taskId, projectId, title, outcome, criteria, verifyCommand, priority, dependencies, workspaceStrategy. create-lead, assign, and active lead-status may include runtimeMode='approval-required' or 'full-access'; it cannot exceed the calling thread's current mode, is saved for that launch, and omission uses the saved worker default. Include authorityGeneration from your role or lead record on management commands. Managers create/assign tasks, inspect and accept evidence, request rework, and acknowledge messages. Workers report questions/progress and submit candidate evidence. Retry an uncertain call with exactly the same commandId and payload. New decisions require the current snapshot revision. At the user's direction, elected GLaDOS may use clear-board to archive the visible board after active writers drain; this retains the role, journal, threads and worktrees and grants no project scope. When the user asks in conversation, GLaDOS records brief, pause, resolve-decision, approve-verification, verification-profile and verification-recipe changes herself, including revising proof after an attempt. Only electing the role still requires the user.", parameters: PitbossCommand, success: PitbossSnapshot, failure: PitbossError, diff --git a/apps/server/src/pitboss/Work.test.ts b/apps/server/src/pitboss/Work.test.ts index 562591fbc524e..6c9c53f71b585 100644 --- a/apps/server/src/pitboss/Work.test.ts +++ b/apps/server/src/pitboss/Work.test.ts @@ -9,7 +9,15 @@ import { type PitbossBrief, type PitbossAction, } from "@t3tools/contracts"; -import { decide, emptyWork, observeAttempt, readyTasks, managerView, workContext } from "./Work.ts"; +import { + decide, + emptyWork, + finishBoardClear, + observeAttempt, + readyTasks, + managerView, + workContext, +} from "./Work.ts"; const projectId = ProjectId.make("project"); const threadId = ThreadId.make("boss"); @@ -73,6 +81,138 @@ describe("pitboss work", () => { }); }); +it("keeps the old board visible to an empty-scope coordinator without granting task authority", () => { + const f = fixture(); + f.run({ + type: "create", + taskId: "old-work", + projectId, + title: "Old work", + outcome: "Remain discoverable", + criteria: "Visible to GLaDOS", + verifyCommand: "", + priority: 1, + dependencies: [], + workspaceStrategy: { type: "root" }, + }); + f.run({ + type: "create-lead", + leadId: "old-lead", + projectId, + charter: "Retain visible portfolio context", + model: brief.workerModel, + maxWorkers: 1, + }); + f.run({ type: "brief", brief: { ...brief, projectIds: [] } }); + + expect(managerView(f.state).tasks.map((task) => task.id)).toEqual(["old-work"]); + expect(managerView(f.state).leads?.map((lead) => lead.id)).toEqual(["old-lead"]); + expect(() => + f.run( + { type: "cancel", taskId: "old-work", note: "Must not gain task authority" }, + { type: "agent", threadId }, + ), + ).toThrow(/outside the current GLaDOS brief/); + expect(readyTasks(f.state)).toEqual([]); +}); + +it("lets paused GLaDOS archive the board while fencing unauthorized and late writers", () => { + const f = fixture(); + f.run({ + type: "create", + taskId: "archive-me", + projectId, + title: "Archive me", + outcome: "Clear the board", + criteria: "The board is empty", + verifyCommand: "", + priority: 1, + dependencies: [], + workspaceStrategy: { type: "root" }, + }); + f.run({ type: "assign", taskId: "archive-me" }); + const attempt = f.state.tasks[0]!.attempts[0]!; + f.run({ type: "pause", paused: true }); + const oldGeneration = f.state.role!.generation; + + expect(() => + f.run({ type: "clear-board" }, { type: "agent", threadId: attempt.threadId }), + ).toThrow(/current GLaDOS/); + f.run({ type: "clear-board" }, { type: "agent", threadId }); + expect(f.state.role).toMatchObject({ threadId, paused: true }); + expect(f.state.role!.generation).toBeGreaterThan(oldGeneration); + expect(f.state.tasks[0]!.attempts[0]!.state).toBe("stop_requested"); + const cleared = finishBoardClear(f.state, f.state.boardClear!.operationId); + expect(cleared).toMatchObject({ tasks: [], messages: [], leads: [] }); + expect(cleared.role).toMatchObject({ threadId, paused: true }); + expect(observeAttempt(cleared, "archive-me", attempt.id, "running", "late result")).toBe(cleared); +}); + +it("archives only work visible to GLaDOS and preserves work outside its brief", () => { + const f = fixture(); + const hiddenProject = ProjectId.make("hidden-project"); + f.run({ type: "brief", brief: { ...brief, projectIds: [projectId, hiddenProject] } }); + for (const [taskId, taskProjectId] of [ + ["visible-work", projectId], + ["hidden-work", hiddenProject], + ] as const) { + f.run({ + type: "create", + taskId, + projectId: taskProjectId, + title: taskId, + outcome: "Keep authority aligned with visibility", + criteria: "Only visible work is archived", + verifyCommand: "", + priority: 1, + dependencies: [], + workspaceStrategy: { type: "root" }, + }); + f.run({ + type: "request-decision", + taskId, + question: `Keep ${taskId}?`, + options: ["Yes", "No"], + recommendation: "Yes", + }); + f.run({ + type: "create-lead", + leadId: `${taskId}-lead`, + projectId: taskProjectId, + charter: `Manage ${taskId}`, + model: brief.workerModel, + maxWorkers: 1, + }); + } + f.run({ type: "brief", brief }); + + expect(managerView(f.state).tasks.map((task) => task.id)).toEqual(["visible-work"]); + const hiddenStatus = f.state.tasks.find((task) => task.id === "hidden-work")!.status; + f.run({ type: "clear-board" }, { type: "agent", threadId }); + expect(f.state.boardClear).toMatchObject({ taskIds: ["visible-work"] }); + expect(f.state.tasks.find((task) => task.id === "visible-work")?.status).toBe("cancelled"); + expect(f.state.tasks.find((task) => task.id === "hidden-work")?.status).toBe(hiddenStatus); + expect(() => + f.run({ type: "report", taskId: "visible-work", kind: "progress", text: "too late" }), + ).toThrow(/affected work is already being cleared/); + f.run({ + type: "report", + taskId: "hidden-work", + kind: "progress", + text: "Hidden work continues while the scoped board drains", + }); + + const cleared = finishBoardClear(f.state, f.state.boardClear!.operationId); + expect(cleared.tasks.map((task) => task.id)).toEqual(["hidden-work"]); + expect(cleared.leads?.map((lead) => lead.id)).toEqual(["hidden-work-lead"]); + expect(cleared.leads?.[0]).toMatchObject({ + status: "active", + parentGeneration: cleared.role?.generation, + }); + expect(cleared.messages.map((message) => message.taskId)).toContain("hidden-work"); + expect(cleared.messages.map((message) => message.taskId)).not.toContain("visible-work"); +}); + it("keeps worker submission distinct from acceptance and rejects worker self-acceptance", () => { const f = fixture(); const run = f.run; diff --git a/apps/server/src/pitboss/Work.ts b/apps/server/src/pitboss/Work.ts index d3fe1f1f9532a..abab25d892be0 100644 --- a/apps/server/src/pitboss/Work.ts +++ b/apps/server/src/pitboss/Work.ts @@ -60,13 +60,18 @@ function peerInBrief(state: PitbossSnapshot, peerId: string | undefined): boolea } /** User views retain the portfolio; agent context follows the current brief. */ export function managerView(state: PitbossSnapshot): PitbossSnapshot { + // An empty brief grants no execution scope, but it must not make the existing board disappear + // from its elected coordinator. Visibility is needed to explain and archive old work; every + // mutating task path below still checks the explicit project list. + const portfolioOnly = state.role?.brief.projectIds.length === 0; const tasks = state.tasks.filter( (task) => - state.role?.brief.projectIds.includes(task.projectId) && - !(state.sourceAuthorities ?? []).some( - (authority) => - authority.scope === task.source?.scope && !peerInBrief(state, authority.peerId), - ), + portfolioOnly || + (state.role?.brief.projectIds.includes(task.projectId) && + !(state.sourceAuthorities ?? []).some( + (authority) => + authority.scope === task.source?.scope && !peerInBrief(state, authority.peerId), + )), ); const taskIds = new Set(tasks.map((task) => task.id)); const scopes = new Set(tasks.flatMap((task) => (task.source?.scope ? [task.source.scope] : []))); @@ -84,8 +89,8 @@ export function managerView(state: PitbossSnapshot): PitbossSnapshot { tasks, ...(state.leads ? { - leads: state.leads.filter((entry) => - state.role?.brief.projectIds.includes(entry.projectId), + leads: state.leads.filter( + (entry) => portfolioOnly || state.role?.brief.projectIds.includes(entry.projectId), ), } : {}), @@ -93,6 +98,7 @@ export function managerView(state: PitbossSnapshot): PitbossSnapshot { messages: state.messages .filter( (message) => + portfolioOnly || !state.leads?.some( (lead) => (lead.id === message.recipientLeadId || lead.threadId === message.threadId) && @@ -100,9 +106,11 @@ export function managerView(state: PitbossSnapshot): PitbossSnapshot { ), ) .filter((message) => - message.taskId !== null - ? taskIds.has(message.taskId) - : !message.sourcePeerId || peerIds.has(message.sourcePeerId), + portfolioOnly + ? true + : message.taskId !== null + ? taskIds.has(message.taskId) + : !message.sourcePeerId || peerIds.has(message.sourcePeerId), ), }; } @@ -242,6 +250,29 @@ export function decide( fail("Only the user can elect GLaDOS.", "forbidden"); if (!["report", "submit", "request-decision"].includes(action.type) && !manager) fail("Only the current GLaDOS or user can manage work.", "forbidden"); + if (state.boardClear) { + const referencedTaskIds = "taskId" in action ? [action.taskId] : []; + const referencedLeadIds = "leadId" in action && action.leadId !== null ? [action.leadId] : []; + const referencedMessageIds = action.type === "acknowledge" ? [action.messageId] : []; + const scopedReferences = [ + ...referencedTaskIds.map((id) => state.boardClear!.taskIds.includes(id)), + ...referencedLeadIds.map((id) => state.boardClear!.leadIds.includes(id)), + ...referencedMessageIds.map((id) => state.boardClear!.messageIds.includes(id)), + ]; + if (scopedReferences.length === 0 || scopedReferences.some(Boolean)) + fail( + "The affected work is already being cleared. Wait for its active writers to stop.", + "conflict", + ); + } + if ( + action.type === "clear-board" && + (!state.role || + actor.type === "peer" || + !!lead || + (actor.type === "agent" && state.role.threadId !== actor.threadId)) + ) + fail("Only the elected GLaDOS or user can clear this work board.", "forbidden"); if ( action.type === "submit" && actor.type === "agent" && @@ -587,6 +618,62 @@ export function decide( }, }; if (action.type === "dismiss") return { ...next, role: null }; + if (action.type === "clear-board") { + if (!state.role) return fail("Activate GLaDOS first."); + const visible = user ? state : managerView(state); + const taskIds = visible.tasks.map((task) => task.id); + const leadIds = (visible.leads ?? []).map((lead) => lead.id); + const messageIds = visible.messages.map((message) => message.id); + const taskIdSet = new Set(taskIds); + const leadIdSet = new Set(leadIds); + const messageIdSet = new Set(messageIds); + const attemptIds = new Set( + state.tasks + .filter((task) => taskIdSet.has(task.id)) + .flatMap((task) => task.attempts.map((attempt) => attempt.id)), + ); + return { + ...next, + boardClear: { + operationId: command.commandId, + generation: next.revision, + requestedAt: now, + taskIds, + leadIds, + messageIds, + }, + // Keep the same coordinator and brief. A new authority generation fences callbacks and + // commands captured before the archive request. + role: { ...state.role, generation: next.revision }, + tasks: state.tasks.map((task) => + taskIdSet.has(task.id) + ? { + ...task, + status: "cancelled" as const, + note: "Archived by GLaDOS at the user's direction", + closedAt: now, + closedReason: "Archived from the GLaDOS work board", + acceptedEvidenceId: null, + revision: task.revision + 1, + attempts: task.attempts.map((attempt) => + ["pending", "running", "submitted"].includes(attempt.state) + ? { ...attempt, state: "stop_requested" as const } + : attempt, + ), + } + : task, + ), + leads: state.leads?.map((entry) => + leadIdSet.has(entry.id) + ? { ...entry, status: "dormant" as const } + : { ...entry, parentGeneration: next.revision }, + ), + messages: state.messages.map((message) => + messageIdSet.has(message.id) ? { ...message, acknowledged: true } : message, + ), + awaitingApproval: (state.awaitingApproval ?? []).filter((id) => !attemptIds.has(id)), + }; + } // Reset clears this environment's work before the home re-elects a fresh thread. The role and // brief survive (with a new generation fencing the old coordinator) so a failed re-election // can be retried. Mirrored tasks belong to their peer home; sources and peers are configuration. @@ -766,7 +853,8 @@ export function decide( if (action.type === "create" || action.type === "edit") { if (!state.role?.brief.projectIds.includes(action.projectId)) fail("Project is outside the GLaDOS brief.", "forbidden"); - if (action.type === "create" && existing) fail("Task ID already exists.", "conflict"); + if (action.type === "create" && (existing || state.archivedTaskIds?.includes(action.taskId))) + fail("Task ID already exists.", "conflict"); if (action.type === "edit" && !existing) fail("Task not found."); if ( action.dependencies.some( @@ -1676,7 +1764,7 @@ function coordinatorContext(state: PitbossSnapshot, threadId: ThreadId) { "- Read the current revision before any mutation. Never claim a task or result exists until the command succeeds.", "- A finished turn is not an accepted outcome. Inspect evidence before accepting.", "- Acknowledge an inbox item only after handling its obligation.", - "- Record the brief, pause, permission, decision and verification changes the user asks for here. Only electing the role still requires the user.", + "- Record the brief, pause, permission, decision and verification changes the user asks for here. At the user's direction, clear-board archives visible tasks and messages after writers drain while retaining this role and audit history. Only electing the role still requires the user.", "- All delegation goes through work_command, so every piece of work keeps a task identity, evidence and acceptance. delegate_task, create_threads and t3_thread_start are refused for you.", "", "## Coordination", @@ -1854,3 +1942,28 @@ export function observeAttempt( ), }; } + +/** Completes one durable archive after the runtime has stopped its writers. */ +export function finishBoardClear(before: PitbossSnapshot, operationId: string): PitbossSnapshot { + if (before.boardClear?.operationId !== operationId) return before; + const taskIds = new Set(before.boardClear.taskIds); + const leadIds = new Set(before.boardClear.leadIds); + const messageIds = new Set(before.boardClear.messageIds); + const attemptIds = new Set( + before.tasks + .filter((task) => taskIds.has(task.id)) + .flatMap((task) => task.attempts.map((attempt) => attempt.id)), + ); + return { + ...before, + revision: before.revision + 1, + boardClear: undefined, + awaitingApproval: (before.awaitingApproval ?? []).filter((id) => !attemptIds.has(id)), + archivedTaskIds: [ + ...new Set([...(before.archivedTaskIds ?? []), ...before.boardClear.taskIds]), + ], + leads: (before.leads ?? []).filter((lead) => !leadIds.has(lead.id)), + tasks: before.tasks.filter((task) => !taskIds.has(task.id)), + messages: before.messages.filter((message) => !messageIds.has(message.id)), + }; +} diff --git a/apps/server/src/pitboss/WorkJournal.ts b/apps/server/src/pitboss/WorkJournal.ts index b07fbbc74f8a4..1cff031d56287 100644 --- a/apps/server/src/pitboss/WorkJournal.ts +++ b/apps/server/src/pitboss/WorkJournal.ts @@ -12,9 +12,10 @@ import { type PitbossSnapshot, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; -import { decide, emptyWork, observeAttempt } from "./Work.ts"; +import { decide, emptyWork, finishBoardClear, observeAttempt } from "./Work.ts"; const Entry = Schema.Union([ + Schema.Struct({ type: Schema.Literal("board-cleared"), operationId: Schema.String }), Schema.Struct({ type: Schema.Literal("verification"), taskId: Schema.String, @@ -61,7 +62,8 @@ export function replayJournal(entries: ReadonlyArray): PitbossSnapshot { let state = emptyWork; for (const raw of entries) { const entry = decode(raw); - if (entry.type === "command") + if (entry.type === "board-cleared") state = finishBoardClear(state, entry.operationId); + else if (entry.type === "command") state = decide(state, entry.input, entry.actor, entry.now, entry.version === undefined); else if (entry.type === "verification") state = recordVerification(state, entry.taskId, entry.run); diff --git a/apps/server/src/pitboss/WorkRuntime.test.ts b/apps/server/src/pitboss/WorkRuntime.test.ts index 9d453a58d5990..69474e3100bc8 100644 --- a/apps/server/src/pitboss/WorkRuntime.test.ts +++ b/apps/server/src/pitboss/WorkRuntime.test.ts @@ -168,6 +168,7 @@ const harness = Effect.gen(function* () { let failSettlement = false; let forbidHistoryReads = false; let deferInterrupt = false; + let interruptTimesOut = false; const failLaunch = new Set(); const command = (action: PitbossAction) => Effect.gen(function* () { @@ -280,12 +281,24 @@ const harness = Effect.gen(function* () { interruptThread: (input) => Effect.sync(() => { interrupted.push(input.threadId); + if (interruptTimesOut) + return { + type: "interrupt_requested" as const, + run: running(input.threadId), + dispatch: { sequence: 1, storedEvents: [] }, + }; if (!deferInterrupt) { const p = projections.get(input.threadId)!; projections.set(input.threadId, { ...p, runs: [] }); } return { type: "no_active_run" as const }; }), + waitForThread: (input) => + Effect.succeed({ + threadId: input.threadId, + run: running(input.threadId), + timedOut: interruptTimesOut, + }), getProjectThread: (input) => { if (forbidHistoryReads) return Effect.die("Runtime monitoring loaded full history"); const p = projections.get(input.threadId); @@ -386,6 +399,12 @@ const harness = Effect.gen(function* () { deferInterrupt: () => { deferInterrupt = true; }, + timeoutInterrupt: () => { + interruptTimesOut = true; + }, + allowInterrupt: () => { + interruptTimesOut = false; + }, failLaunch, command, drain, @@ -393,6 +412,188 @@ const harness = Effect.gen(function* () { }; }); const services = storeLayer.pipe(Layer.provideMerge(SqlitePersistenceMemory)); +it.effect("drains active writers before removing tasks and stale messages from the board", () => + Effect.gen(function* () { + const h = yield* harness; + yield* h.command({ + type: "create", + taskId: "active-clear", + projectId: a, + title: "Active clear", + outcome: "Stop safely", + criteria: "Writer drains", + verifyCommand: "", + priority: 1, + dependencies: [], + workspaceStrategy: { type: "root" }, + }); + yield* h.command({ type: "assign", taskId: "active-clear" }); + const worker = (yield* h.store.read()).tasks[0]!.attempts[0]!.threadId; + h.projections.set(worker, { ...projection(worker, a), runs: [running(worker)] }); + + yield* h.command({ type: "clear-board" }); + yield* h.drain(); + const archived = yield* h.store.read(); + expect(h.interrupted).toContain(worker); + expect(archived.tasks).toEqual([]); + expect(archived.messages).toEqual([]); + expect(archived.role?.threadId).toBe(boss); + }).pipe(Effect.provide(services)), +); + +it.effect("keeps a timed-out board clear pending and completes it on retry", () => + Effect.gen(function* () { + const h = yield* harness; + yield* h.command({ + type: "create", + taskId: "retry-clear", + projectId: a, + title: "Retry clear", + outcome: "Drain before archive", + criteria: "The archive retries after timeout", + verifyCommand: "", + priority: 1, + dependencies: [], + workspaceStrategy: { type: "root" }, + }); + yield* h.command({ type: "assign", taskId: "retry-clear" }); + const worker = (yield* h.store.read()).tasks[0]!.attempts[0]!.threadId; + h.projections.set(worker, { ...projection(worker, a), runs: [running(worker)] }); + h.timeoutInterrupt(); + + yield* h.command({ type: "clear-board" }); + yield* h.drain(); + expect((yield* h.store.read()).boardClear).toBeDefined(); + expect((yield* h.store.effects()).some((effect) => effect.kind === "clear-board")).toBe(true); + + h.allowInterrupt(); + yield* h.drain(); + expect((yield* h.store.read()).tasks).toEqual([]); + expect((yield* h.store.effects()).some((effect) => effect.kind === "clear-board")).toBe(false); + }).pipe(Effect.provide(services)), +); + +it.effect("does not drain or archive local work outside the coordinator's visible brief", () => + Effect.gen(function* () { + const h = yield* harness; + for (const [taskId, projectId] of [ + ["visible-local", a], + ["hidden-local", b], + ] as const) { + yield* h.command({ + type: "create", + taskId, + projectId, + title: taskId, + outcome: "Respect visible authority", + criteria: "Only visible writers stop", + verifyCommand: "", + priority: 1, + dependencies: [], + workspaceStrategy: { type: "root" }, + }); + yield* h.command({ type: "assign", taskId }); + const task = (yield* h.store.read()).tasks.find((entry) => entry.id === taskId)!; + const worker = task.attempts[0]!.threadId; + h.projections.set(worker, { ...projection(worker, projectId), runs: [running(worker)] }); + } + const before = yield* h.store.read(); + yield* h.command({ + type: "brief", + brief: { ...before.role!.brief, projectIds: [a] }, + }); + const scoped = yield* h.store.read(); + yield* h.store.command( + { + commandId: CommandId.make("scoped-board-clear"), + expectedRevision: scoped.revision, + authorityGeneration: scoped.role!.generation, + action: { type: "clear-board" }, + }, + { type: "agent", threadId: boss }, + ); + + yield* h.drain(); + const hidden = (yield* h.store.read()).tasks; + expect(hidden.map((task) => task.id)).toEqual(["hidden-local"]); + expect(hidden[0]?.attempts[0]?.state).toBe("running"); + expect(h.interrupted).toEqual([ + before.tasks.find((task) => task.id === "visible-local")!.attempts[0]!.threadId, + ]); + }).pipe(Effect.provide(services)), +); + +it.effect("archives a remote projection without interrupting its home writer", () => + Effect.gen(function* () { + const h = yield* harness; + const home = EnvironmentId.make("remote-home"); + const self = EnvironmentId.make("local-coordinator"); + yield* h.store.importSources( + { + id: "remote-source", + kind: "linear", + baseUrl: "https://tracker.invalid", + tenantId: "team", + remoteProjectId: "project", + projectId: a, + enabled: true, + }, + [ + { + title: "Remote writer", + outcome: "Keep remote ownership", + source: { + kind: "linear", + tenantId: "team", + itemId: "remote-writer", + scope: "remote-scope", + key: "REMOTE-2", + url: "https://tracker.invalid/REMOTE-2", + status: "Open", + priority: "1", + observedAt: "2026-09-11T00:00:00.000Z", + }, + }, + ], + ); + const imported = (yield* h.store.read()).tasks[0]!; + yield* h.store.setSourceAuthority({ + scope: imported.source!.scope!, + self, + coordinator: self, + homeEnvironmentId: home, + peerId: "remote-peer", + proposalId: "approved-remote-scope", + }); + const remoteThread = ThreadId.make("remote-writer-thread"); + yield* h.store.mirrorTask(home, { + ...imported, + revision: imported.revision + 1, + status: "active", + attempts: [ + { + id: "remote-attempt", + threadId: remoteThread, + generation: 1, + state: "running", + model, + createdAt: "2026-09-11T00:00:00.000Z", + detail: "Running at task home", + }, + ], + }); + h.projections.set(remoteThread, { + ...projection(remoteThread, a), + runs: [running(remoteThread)], + }); + + yield* h.command({ type: "clear-board" }); + yield* h.drain(); + expect(h.interrupted).not.toContain(remoteThread); + expect((yield* h.store.read()).tasks).toEqual([]); + }).pipe(Effect.provide(services)), +); + it.effect("settles handled worker attempts once without touching live or unresolved workers", () => Effect.gen(function* () { const h = yield* harness; diff --git a/apps/server/src/pitboss/WorkRuntime.ts b/apps/server/src/pitboss/WorkRuntime.ts index 1ad3089c01abf..3b11ec92f381b 100644 --- a/apps/server/src/pitboss/WorkRuntime.ts +++ b/apps/server/src/pitboss/WorkRuntime.ts @@ -728,6 +728,88 @@ export const layer = Layer.effectDiscard( } const action = yield* decodeAction(effect.payload_json); const state = yield* store.read(); + if (action.type === "clear-board") { + if (state.boardClear?.operationId !== effect.operation_id) return; + const taskIds = new Set(state.boardClear.taskIds); + const leadIds = new Set(state.boardClear.leadIds); + for (const task of state.tasks.filter((task) => taskIds.has(task.id))) { + const authority = state.sourceAuthorities?.find( + (entry) => entry.scope === task.source?.scope, + ); + // A mirrored writer belongs to its recorded home. Archiving this projection must + // never become an implicit remote cancellation. + if (task.homeEnvironmentId && authority?.self !== task.homeEnvironmentId) continue; + for (const attempt of task.attempts) { + if (attempt.state !== "stop_requested") continue; + const interrupted = yield* Effect.result( + threads.interruptThread({ + projectId: task.projectId, + threadId: attempt.threadId, + commandId: CommandId.make(`${effect.operation_id}:stop:${attempt.id}`), + reason: "GLaDOS archived the work board at the user's direction", + }), + ); + if (interrupted._tag === "Failure" && !isMissingThread(interrupted.failure)) + return yield* Effect.fail(interrupted.failure); + if ( + interrupted._tag === "Success" && + interrupted.success.type === "interrupt_requested" + ) { + const drained = yield* threads.waitForThread({ + projectId: task.projectId, + threadId: attempt.threadId, + runId: interrupted.success.run.id, + timeoutMs: 30_000, + }); + if (drained.timedOut) + return yield* new PitbossError({ + code: "unavailable", + message: `Worker ${attempt.id} did not stop before the board archive timed out.`, + }); + } + yield* store.updateAttempt( + task.id, + attempt.id, + "stopped", + "Board archived; evidence and workspace retained", + ); + } + } + for (const lead of (state.leads ?? []).filter((lead) => leadIds.has(lead.id))) { + const existing = yield* Effect.result( + threads.getProjectThread({ projectId: lead.projectId, threadId: lead.threadId }), + ); + if (existing._tag === "Failure") { + if (!isMissingThread(existing.failure)) + return yield* Effect.fail(existing.failure); + continue; + } + const run = latestActiveRun(existing.success); + if (!run) continue; + const interrupted = yield* threads.interruptThread({ + projectId: lead.projectId, + threadId: lead.threadId, + runId: run.id, + commandId: CommandId.make(`${effect.operation_id}:stop-lead:${lead.id}`), + reason: "GLaDOS archived the work board at the user's direction", + }); + if (interrupted.type === "interrupt_requested") { + const drained = yield* threads.waitForThread({ + projectId: lead.projectId, + threadId: lead.threadId, + runId: interrupted.run.id, + timeoutMs: 30_000, + }); + if (drained.timedOut) + return yield* new PitbossError({ + code: "unavailable", + message: `Project lead ${lead.id} did not stop before the board archive timed out.`, + }); + } + } + yield* store.finishBoardClear(effect.operation_id); + return; + } if (action.type === "send-peer") { const message = state.messages.find((entry) => entry.id === effect.operation_id); if (!message?.threadId) @@ -935,6 +1017,12 @@ export const layer = Layer.effectDiscard( ); if (result._tag === "Failure") { const detail = `${effect.kind} (${effect.operation_id}): ${String(result.failure)}`; + // A board archive must remain retryable until every writer drains. Replaying the same + // command republishes a store change, and thread terminal events also wake this drain. + if (effect.kind === "clear-board") { + yield* store.retryEffect(effect.operation_id, detail); + continue; + } const state = yield* store.read(); for (const task of state.tasks) { const attempt = task.attempts.find((attempt) => attempt.id === effect.operation_id); diff --git a/apps/server/src/pitboss/WorkStore.test.ts b/apps/server/src/pitboss/WorkStore.test.ts index 33c0f3e7c0832..e28c417d7e184 100644 --- a/apps/server/src/pitboss/WorkStore.test.ts +++ b/apps/server/src/pitboss/WorkStore.test.ts @@ -561,3 +561,125 @@ it.effect( expect((yield* store.effects()).filter((e) => e.kind === "create-lead")).toHaveLength(1); }).pipe(Effect.provide(services)), ); + +it.effect("archives a paused board idempotently and ignores late attempt observations", () => + Effect.gen(function* () { + const store = yield* WorkStore; + let state = yield* store.command(election, { type: "user" }); + state = yield* store.command( + { + commandId: CommandId.make("archive-create"), + expectedRevision: state.revision, + action: { + type: "create", + taskId: "archive-task", + projectId: election.action.projectId, + title: "Archive task", + outcome: "Clear visible work", + criteria: "Board is empty", + verifyCommand: "", + priority: 1, + dependencies: [], + workspaceStrategy: { type: "root" }, + }, + }, + { type: "user" }, + ); + state = yield* store.command( + { + commandId: CommandId.make("archive-assign"), + expectedRevision: state.revision, + action: { type: "assign", taskId: "archive-task" }, + }, + { type: "user" }, + ); + const attempt = state.tasks[0]!.attempts[0]!; + yield* store.updateAttempt( + "archive-task", + attempt.id, + "stopped", + "Stopped result retained for audit", + "/tmp/archive-task", + ); + yield* store.receiveMessage({ + id: "archive-stale-message", + taskId: "archive-task", + threadId: attempt.threadId, + kind: "progress", + text: "Stale result message", + createdAt: "2026-09-22T00:00:00Z", + acknowledged: false, + }); + state = yield* store.read(); + state = yield* store.command( + { + commandId: CommandId.make("archive-pause"), + expectedRevision: state.revision, + action: { type: "pause", paused: true }, + }, + { type: "user" }, + ); + const clear = { + commandId: CommandId.make("archive-board"), + expectedRevision: state.revision, + authorityGeneration: state.role!.generation, + action: { type: "clear-board" as const }, + }; + const pending = yield* store.command(clear, { + type: "agent", + threadId: election.action.threadId, + }); + expect(pending.boardClear?.operationId).toBe("archive-board"); + expect(pending.role).toMatchObject({ threadId: election.action.threadId, paused: true }); + expect((yield* store.effects()).filter((effect) => effect.kind === "clear-board")).toHaveLength( + 1, + ); + + yield* store.finishBoardClear("archive-board"); + const archived = yield* store.read(); + expect(archived.tasks).toEqual([]); + expect(archived.messages).toEqual([]); + expect(archived.role).toMatchObject({ threadId: election.action.threadId, paused: true }); + yield* store.receiveMessage({ + id: "archive-stale-message", + taskId: "archive-task", + threadId: attempt.threadId, + kind: "progress", + text: "Stale result message", + createdAt: "2026-09-22T00:00:00Z", + acknowledged: false, + }); + yield* store.receiveMessage({ + id: "archive-late-message", + taskId: "archive-task", + threadId: attempt.threadId, + kind: "result", + text: "Late result after archive", + createdAt: "2026-09-22T00:01:00Z", + acknowledged: false, + }); + expect((yield* store.read()).messages).toEqual([]); + yield* store.receiveMessage({ + id: "archive-fresh-message", + taskId: null, + threadId: election.action.threadId, + kind: "progress", + text: "Fresh coordinator message", + createdAt: "2026-09-22T00:02:00Z", + acknowledged: false, + }); + expect((yield* store.read()).messages.map((message) => message.id)).toEqual([ + "archive-fresh-message", + ]); + const revision = (yield* store.read()).revision; + yield* store.updateAttempt("archive-task", attempt.id, "running", "late callback"); + expect((yield* store.read()).revision).toBe(revision); + expect( + (yield* store.command(clear, { + type: "agent", + threadId: election.action.threadId, + })).revision, + ).toBe(revision); + expect(yield* store.rebuild()).toEqual(yield* store.read()); + }).pipe(Effect.provide(services)), +); diff --git a/apps/server/src/pitboss/WorkStore.ts b/apps/server/src/pitboss/WorkStore.ts index f1848dca6b812..bca2d3ff2831c 100644 --- a/apps/server/src/pitboss/WorkStore.ts +++ b/apps/server/src/pitboss/WorkStore.ts @@ -28,6 +28,7 @@ import * as Stream from "effect/Stream"; import * as SqlClient from "effect/unstable/sql/SqlClient"; import { decide, + finishBoardClear, remoteTaskAuthority, managerView, importedCriteria, @@ -80,6 +81,7 @@ export class WorkStore extends Context.Service< actor: WorkActor, authority?: WorkCommandAuthority, ) => Effect.Effect; + finishBoardClear: (operationId: string) => Effect.Effect; subscribe: () => Stream.Stream; changes: Stream.Stream; effects: () => Effect.Effect, PitbossError>; @@ -271,6 +273,7 @@ export const layer = Layer.effect( "cancel", "propose-coordination", "send-peer", + "clear-board", ].includes(action.type) || (action.type === "brief" && action.applyCoordinatorPermissions) ) { @@ -288,6 +291,23 @@ export const layer = Layer.effect( return WorkStore.of({ read, command, + finishBoardClear: (operationId) => + sql + .withTransaction( + Effect.gen(function* () { + const before = yield* readAll(); + const after = finishBoardClear(before, operationId); + if (after === before) return; + const now = DateTime.formatIso(yield* DateTime.now); + const eventId = `${operationId}:completed`; + yield* sql`INSERT INTO pitboss_events (operation_id, request_json, payload_json, created_at) VALUES (${eventId}, ${eventId}, ${encodeJson({ type: "board-cleared", operationId })}, ${now})`; + yield* persist(after); + }), + ) + .pipe( + Effect.tap(() => PubSub.publish(notifications, undefined)), + Effect.mapError(unavailable), + ), rebuild, resolveRemoteReceipt: (operationId, applied, detail) => sql @@ -392,8 +412,13 @@ export const layer = Layer.effect( .withTransaction( Effect.gen(function* () { const state = yield* readAll(); + const recorded = yield* sql<{ + readonly operation_id: string; + }>`SELECT operation_id FROM pitboss_events WHERE operation_id = ${message.id}`; + if (recorded[0]) return; const previous = state.messages.find((entry) => entry.id === message.id); if (previous) return; + if (message.taskId && state.archivedTaskIds?.includes(message.taskId)) return; yield* sql`INSERT INTO pitboss_events (operation_id, request_json, payload_json, created_at) VALUES (${message.id}, ${message.id}, ${encodeJson({ type: "message", message })}, ${message.createdAt})`; yield* persist({ ...state, diff --git a/apps/web/src/components/pitboss/workView.test.ts b/apps/web/src/components/pitboss/workView.test.ts index 864f7558536e5..eb019bf7d94a6 100644 --- a/apps/web/src/components/pitboss/workView.test.ts +++ b/apps/web/src/components/pitboss/workView.test.ts @@ -21,6 +21,12 @@ function task(title: string, status: PitbossTask["status"] = "queued", priority } describe("GLaDOS work discovery", () => { + it("shows no stale rows after the server archives the visible board", () => { + const before = { tasks: [task("Visible before archive")] }; + const after = { ...before, tasks: [] }; + expect(filterWork(before.tasks, "All", "", "")).toEqual(before.tasks); + expect(filterWork(after.tasks, "All", "", "")).toEqual([]); + }); it("keeps every outcome reachable, including beyond the tenth item", () => { const tasks = Array.from({ length: 24 }, (_, i) => task(`Outcome ${i}`)); expect(filterWork(tasks, "All", "", "")).toHaveLength(24); diff --git a/packages/contracts/src/pitboss.test.ts b/packages/contracts/src/pitboss.test.ts index d50c4c583ae90..9b93db773dbbd 100644 --- a/packages/contracts/src/pitboss.test.ts +++ b/packages/contracts/src/pitboss.test.ts @@ -1,13 +1,27 @@ import { expect, it } from "@effect/vitest"; +import * as Schema from "effect/Schema"; import { ProjectId, ThreadId } from "./baseSchemas.ts"; import { isUserWorkMessage, pitbossMessageHeadline, verificationProposalApprovalAction, verificationProposalSaveAction, + PitbossCommand, type PitbossMessage, type PitbossTask, } from "./pitboss.ts"; +const decodePitbossCommand = Schema.decodeUnknownSync(PitbossCommand); + +it("decodes the explicit board archive operation", () => { + expect( + decodePitbossCommand({ + commandId: "clear-board", + expectedRevision: 12, + authorityGeneration: 7, + action: { type: "clear-board" }, + }).action, + ).toEqual({ type: "clear-board" }); +}); const recipe = { projectId: ProjectId.make("project"), diff --git a/packages/contracts/src/pitboss.ts b/packages/contracts/src/pitboss.ts index 4a67bca014625..1087c3efc2cdd 100644 --- a/packages/contracts/src/pitboss.ts +++ b/packages/contracts/src/pitboss.ts @@ -350,6 +350,19 @@ export const PitbossSnapshot = Schema.Struct({ */ awaitingApproval: Schema.optional(Schema.Array(Id)), verificationRecipes: Schema.optional(Schema.Array(PitbossVerificationRecipe)), + /** A durable board archive is draining writers before its visible projection is removed. */ + boardClear: Schema.optional( + Schema.Struct({ + operationId: Id, + generation: Version, + requestedAt: Schema.String, + taskIds: Schema.Array(Id), + leadIds: Schema.Array(Id), + messageIds: Schema.Array(Id), + }), + ), + /** Durable task tombstones that fence messages and callbacks arriving after a board archive. */ + archivedTaskIds: Schema.optional(Schema.Array(Id)), leads: Schema.optional(Schema.Array(PitbossLead)), sourceAuthorities: Schema.optional(Schema.Array(PitbossSourceAuthority)), revision: Version, @@ -454,6 +467,8 @@ export const PitbossAction = Schema.Union([ brief: PitbossBrief, }), Schema.Struct({ type: Schema.Literal("dismiss") }), + /** Archives the visible board while retaining its journal, threads, worktrees and role. */ + Schema.Struct({ type: Schema.Literal("clear-board") }), /** Cancels open local work and gives GLaDOS a fresh home thread; the brief is kept. */ Schema.Struct({ type: Schema.Literal("reset") }), Schema.Struct({ type: Schema.Literal("pause"), paused: Schema.Boolean }),