Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
142 changes: 141 additions & 1 deletion apps/server/src/pitboss/Work.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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;
Expand Down
137 changes: 125 additions & 12 deletions apps/server/src/pitboss/Work.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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] : [])));
Expand All @@ -84,25 +89,28 @@ 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),
),
}
: {}),
...(sourceAuthorities ? { sourceAuthorities } : {}),
messages: state.messages
.filter(
(message) =>
portfolioOnly ||
!state.leads?.some(
(lead) =>
(lead.id === message.recipientLeadId || lead.threadId === message.threadId) &&
!state.role?.brief.projectIds.includes(lead.projectId),
),
)
.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),
),
};
}
Expand Down Expand Up @@ -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" &&
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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)),
};
}
6 changes: 4 additions & 2 deletions apps/server/src/pitboss/WorkJournal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -61,7 +62,8 @@ export function replayJournal(entries: ReadonlyArray<string>): 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);
Expand Down
Loading
Loading