mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Headless channels, fenced task queues, `@paperclipai/shared/sdk`, and the `pc` CLI landed in #23330 to coordinate multi-agent swarms and inbox/queue patterns. > - Real multi-stage workflows immediately hit gaps: there was no `assign` command to push existing channel posts to managed agents, no atomic `handoff`/`move` across channels with CAS labels and lease release, `claim --ready` could not opt into `backlog`/`in_review` or `--assignee me`, there was no `cancel`/`reopen` or mid-flight `--needs` dependency linking, and `pc channels` could not update queue config, manage private members, or bind event-driven managed pools. > - Without these primitives, operators had to drop back to raw `issue update` calls or non-atomic two-step scripts that race on crash. > - This pull request adds the complete workflow lifecycle across shared schemas, modular server services/routes, SDK methods, `pc` CLI commands, and the `.agents/skills/channels-queues-and-workflows` skill. > - The benefit is end-to-end single-command support for inbox triage, single-thread relays, chained channel assembly lines, mid-flight DAG dependencies, and Day-2 graduation to managed Paperclip agent pools. ## Linked Issues or Issue Description Refs #23330 **Subsystem affected** Cross-cutting (multiple of the above) **Problem or motivation** Building multi-agent queues and chained workflows on Paperclip channels required workarounds: assigning an existing post to a registered agent required raw `issue update --assignee-agent-id <uuid>`; moving an issue across stage channels with a label update and lease release required non-atomic multi-step calls; triage or review workers could not opt into claiming `backlog`, `in_review`, or their own assigned tasks (`--mine`); tasks could not be cancelled, reopened, or given mid-flight `--needs` blockers; and channels lacked CLI/API administration for `queueConfig`, private `channel_access_members`, and `managedPool` auto-dispatch. **Proposed solution** Add cohesive REST endpoints, modular services (`headless-task-workflows.ts`, `headless-channel-admin.ts`), SDK methods, `pc` CLI subcommands, and the `channels-queues-and-workflows` skill covering `assign`, `handoff`/`move`, `cancel`, `reopen`, `block --needs`/`deps`, opt-in `claim --status`/`--assignee`, and `channels update`/`members` with event-driven `managedPool` dispatch. **Alternatives considered** Leaving these operations to raw `PATCH /api/issues/:id` calls was rejected because it bypasses fenced claim tokens (`claimEpoch` + `claimToken`), lacks atomic channel+label+lease transactions, and does not enforce CAS preconditions or dependency cycle checks. **Roadmap alignment** Directly extends the headless channels and queues coordination primitive introduced in #23330. ## What Changed - **Shared schemas & SDK (`packages/shared/src/headless/`, `packages/shared/src/sdk/`):** - Added pure zero-zod constants `CLAIMABLE_TASK_STATUSES` and `TASK_CLAIM_ASSIGNEE_MODES` in `pure.ts`, upgraded `TaskClaimRequestSchema` (`status`/`statuses`, `assignee`) and `TaskReleaseSchema` (`status`, `channel`, `labels`, `unsetLabels`), and added `TaskAssignSchema`, `TaskHandoffSchema`, `TaskCancelSchema`, `TaskReopenSchema`, `TaskDependenciesMutationSchema`, `updateChannelInputSchema`, and `channelMemberInputSchema`. - Added `task.assigned`, `task.handed_off`, `task.cancelled`, `task.reopened`, and `task.dependencies_changed` to `BOARD_EVENT_TYPES`. - Exposed matching SDK methods on `paperclip().tasks`, `ClaimedTask`, and `paperclip().channels`. - **Server services & routes (`server/src/services/`, `server/src/routes/`):** - Upgraded `claimTask` and `releaseTaskClaim` in `headless-task-queue.ts` to support opt-in `status` (`todo`, `backlog`, `in_review` excluding pending interactions), `assignee` (`unassigned`, `me`, `any`), and atomic channel/label/status updates on release. - Added `server/src/services/headless-task-workflows.ts` implementing `assignTask`, `handoffTask`, `cancelTask`, `reopenTask`, `listTaskDependencies`, and `mutateTaskDependencies` (with BFS cycle detection and fenced lease release). - Added `server/src/services/headless-channel-admin.ts` implementing `updateChannel`, `listChannelMembers`, `addChannelMember`, `removeChannelMember`, and event-driven `dispatchManagedChannelPool` (zero idle polling). - Wired routes in `headless-queues-events.ts` and `headless-channels-schemas.ts`. - **CLI (`cli/src/commands/board/`):** - Added `cli/src/commands/board/tasks-workflows.ts` (`pc tasks assign`, `handoff`/`move`, `cancel`, `reopen`, `deps list|add|remove`). - Upgraded `pc tasks claim`/`run` (`--status`, `--assignee`, `--mine`), `pc tasks release` (`--channel`, `--label`, `--unset`, `--status`), `pc tasks block` (`--needs`), and `pc channels` (`update`/`config`, `members list|add|remove`). - **Skill & Tests:** - Added `.agents/skills/channels-queues-and-workflows/SKILL.md` and `examples.md`. - Added `server/src/__tests__/headless-task-workflows.test.ts` and updated `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/shared build && pnpm --filter @paperclipai/server typecheck && pnpm --filter paperclipai typecheck` — passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/headless-task-workflows.test.ts src/__tests__/headless-queues-leases-events.test.ts src/__tests__/headless-channels-schemas-batch.test.ts src/__tests__/headless-e2e-sdk-cli.test.ts` — 4 files, 27 tests passed. - `pnpm --filter @paperclipai/shared exec vitest run src/headless/headless.test.ts src/sdk/sdk.test.ts` — 2 files, 20 tests passed. - Live headless CLI test-drive (`pc up --port 3299` in isolated `PAPERCLIP_HOME`) verifying `agent connect`, `post`, `tasks assign`, `tasks claim --mine`, `tasks handoff`, `tasks release --status in_review`, `tasks claim --status in_review`, `tasks block --needs`, `tasks deps list`, blocker completion auto-unblock, `tasks cancel`, `tasks reopen`, `tasks claim --status backlog`, `channels members add/list/remove`, and `channels update --managed-pool` — all 11 scenarios passed. ## Risks - Low risk. No database migrations are required; existing `channels.queue_config`, `channel_access_members`, `issue_relations`, and `issues` lease columns are reused. - Default `claim --ready` behavior (`status = todo`, `assignee = unassigned`) is unchanged; `--status` and `--assignee` are strictly opt-in, and `--assignee me`/`any` never allows claiming tasks assigned to another agent or user. - Note on file size: `server/src/services/headless-task-queue.ts` and `cli/src/commands/board/tasks.ts` were already over 1,000 lines before this PR; all new workflow/admin operations were placed in dedicated sibling modules (`headless-task-workflows.ts`, `headless-channel-admin.ts`, `tasks-workflows.ts`) to keep existing files bounded. ## Model Used - Google Gemini (Antigravity agentic runtime, Gemini 4 Neon Medium, extended thinking with tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
571 lines
20 KiB
TypeScript
571 lines
20 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { createServer, type Server as HttpServer } from "node:http";
|
|
import express from "express";
|
|
import {
|
|
afterAll,
|
|
beforeAll,
|
|
describe,
|
|
expect,
|
|
it,
|
|
vi,
|
|
} from "vitest";
|
|
import { and, eq } from "drizzle-orm";
|
|
import {
|
|
activityLog,
|
|
agents,
|
|
companies,
|
|
companyMemberships,
|
|
createDb,
|
|
type Db,
|
|
} from "@paperclipai/db";
|
|
import { paperclip } from "@paperclipai/shared/sdk";
|
|
import { errorHandler } from "../middleware/error-handler.js";
|
|
import { headlessChannelsSchemasRoutes } from "../routes/headless-channels-schemas.js";
|
|
import { headlessQueuesEventsRoutes } from "../routes/headless-queues-events.js";
|
|
import type { heartbeatService } from "../services/heartbeat.js";
|
|
import {
|
|
getEmbeddedPostgresTestSupport,
|
|
startEmbeddedPostgresTestDatabase,
|
|
} from "./helpers/embedded-postgres.js";
|
|
|
|
vi.hoisted(() => {
|
|
process.env.PAPERCLIP_HOME = "/tmp/paperclip-test-home-workflows";
|
|
process.env.PAPERCLIP_INSTANCE_ID = "vitest-headless-workflows";
|
|
process.env.PAPERCLIP_LOG_DIR = "/tmp/paperclip-test-home-workflows/logs";
|
|
process.env.PAPERCLIP_IN_WORKTREE = "false";
|
|
});
|
|
|
|
const support = await getEmbeddedPostgresTestSupport();
|
|
const describeEmbeddedPostgres = support.supported ? describe : describe.skip;
|
|
|
|
function createTestServer(db: Db, wakeupSpy: ReturnType<typeof vi.fn>) {
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((req, _res, next) => {
|
|
const actorType = req.header("x-test-actor-type");
|
|
if (actorType === "agent") {
|
|
req.actor = {
|
|
type: "agent",
|
|
agentId: req.header("x-test-agent-id") ?? undefined,
|
|
companyId: req.header("x-test-company-id") ?? undefined,
|
|
source: "agent_key",
|
|
};
|
|
} else {
|
|
req.actor = {
|
|
type: "board",
|
|
userId: req.header("x-test-user-id") ?? "board-user",
|
|
source: "local_implicit",
|
|
isInstanceAdmin: true,
|
|
};
|
|
}
|
|
next();
|
|
});
|
|
|
|
const mockHeartbeat = {
|
|
wakeup: wakeupSpy,
|
|
} as unknown as ReturnType<typeof heartbeatService>;
|
|
|
|
app.use("/api", headlessChannelsSchemasRoutes(db, { heartbeat: mockHeartbeat }));
|
|
app.use("/api", headlessQueuesEventsRoutes(db, { heartbeat: mockHeartbeat }));
|
|
app.use(errorHandler);
|
|
return createServer(app);
|
|
}
|
|
|
|
describeEmbeddedPostgres("headless task workflows, claim filters, and channel admin", () => {
|
|
let stopDb: (() => Promise<void>) | undefined;
|
|
let db: Db;
|
|
let server: HttpServer;
|
|
let apiBase: string;
|
|
let companyId: string;
|
|
let agentAId: string;
|
|
let agentBId: string;
|
|
const wakeupSpy = vi.fn().mockResolvedValue(null);
|
|
|
|
const makeAgentClient = (agentId: string) =>
|
|
paperclip({
|
|
apiBase,
|
|
company: companyId,
|
|
fetch: (input, init) => {
|
|
const headers = new Headers(init?.headers);
|
|
headers.set("x-test-actor-type", "agent");
|
|
headers.set("x-test-agent-id", agentId);
|
|
headers.set("x-test-company-id", companyId);
|
|
return fetch(input, { ...init, headers });
|
|
},
|
|
});
|
|
|
|
const makeBoardClient = () =>
|
|
paperclip({
|
|
apiBase,
|
|
company: companyId,
|
|
});
|
|
|
|
beforeAll(async () => {
|
|
const started = await startEmbeddedPostgresTestDatabase(
|
|
"paperclip-headless-workflows",
|
|
);
|
|
stopDb = started.cleanup;
|
|
db = createDb(started.connectionString);
|
|
|
|
server = createTestServer(db, wakeupSpy);
|
|
await new Promise<void>((resolve) => {
|
|
server.listen(0, "127.0.0.1", () => resolve());
|
|
});
|
|
const addr = server.address();
|
|
if (!addr || typeof addr === "string") {
|
|
throw new Error("Failed to bind test server");
|
|
}
|
|
apiBase = `http://127.0.0.1:${addr.port}`;
|
|
|
|
companyId = randomUUID();
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Workflow Test Co",
|
|
issuePrefix: "WFL",
|
|
});
|
|
|
|
await db.insert(companyMemberships).values({
|
|
companyId,
|
|
principalType: "user",
|
|
principalId: "board-user",
|
|
membershipRole: "owner",
|
|
status: "active",
|
|
});
|
|
|
|
agentAId = randomUUID();
|
|
agentBId = randomUUID();
|
|
await db.insert(agents).values([
|
|
{
|
|
id: agentAId,
|
|
companyId,
|
|
name: "backend-eng",
|
|
role: "engineer",
|
|
status: "idle",
|
|
adapterType: "process",
|
|
},
|
|
{
|
|
id: agentBId,
|
|
companyId,
|
|
name: "qa-reviewer",
|
|
role: "qa",
|
|
status: "idle",
|
|
adapterType: "process",
|
|
},
|
|
]);
|
|
}, 60_000);
|
|
|
|
afterAll(async () => {
|
|
await new Promise<void>((resolve) => server?.close(() => resolve()));
|
|
await stopDb?.();
|
|
});
|
|
|
|
it("assigns passive posts (promoting backlog -> todo), enforces lease guard unless forced, and unassigns", async () => {
|
|
wakeupSpy.mockClear();
|
|
const board = makeBoardClient();
|
|
|
|
const post = await board.post("inbox/bugs", "500 on /api/checkout");
|
|
expect(post.status).toBe("backlog");
|
|
expect(post.assigneeAgentId).toBeNull();
|
|
|
|
const assigned = await board.tasks.assign(post.identifier, "@backend-eng", {
|
|
comment: "Routing to backend team",
|
|
});
|
|
expect(assigned.assigneeAgentId).toBe(agentAId);
|
|
expect(assigned.status).toBe("todo");
|
|
expect(wakeupSpy).toHaveBeenCalledWith(
|
|
agentAId,
|
|
expect.objectContaining({ reason: "issue_assigned" }),
|
|
);
|
|
|
|
// Unassign returns it to unassigned pool
|
|
const unassigned = await board.tasks.assign(post.identifier, null, {
|
|
unassign: true,
|
|
});
|
|
expect(unassigned.assigneeAgentId).toBeNull();
|
|
expect(unassigned.status).toBe("todo");
|
|
|
|
// Claim it, verify assign without force fails 409, then force succeeds & fences old claim
|
|
const claimed = await board.as("worker-1").tasks.claim(post.identifier);
|
|
expect(claimed).not.toBeNull();
|
|
|
|
await expect(
|
|
board.tasks.assign(post.identifier, "@qa-reviewer"),
|
|
).rejects.toMatchObject({ status: 409, code: "task_claimed" });
|
|
|
|
const forced = await board.tasks.assign(post.identifier, "@qa-reviewer", {
|
|
force: true,
|
|
});
|
|
expect(forced.assigneeAgentId).toBe(agentBId);
|
|
expect(forced.claimLeaseExpiresAt).toBeNull();
|
|
|
|
// Old worker's lease is fenced
|
|
await expect(claimed!.renew("5m")).rejects.toMatchObject({
|
|
status: 409,
|
|
code: "claim_lost",
|
|
});
|
|
});
|
|
|
|
it("supports claim --status (backlog, in_review excluding pending interactions) and --assignee me/any", async () => {
|
|
const board = makeBoardClient();
|
|
const agentA = makeAgentClient(agentAId);
|
|
const agentB = makeAgentClient(agentBId);
|
|
|
|
// 1. Backlog post: ignored by default claim, poppable with status: ["backlog"]
|
|
const rawPost = await board.post("triage/raw", "Raw customer alert");
|
|
const defaultPop = await board.tasks.claim({ channel: "triage/raw" });
|
|
expect(defaultPop).toBeNull();
|
|
|
|
const backlogPop = await board.tasks.claim({
|
|
channel: "triage/raw",
|
|
status: "backlog",
|
|
});
|
|
expect(backlogPop?.task.id).toBe(rawPost.id);
|
|
await backlogPop!.complete("Triaged");
|
|
|
|
// 2. in_review: excluded if pending human interaction exists, claimable if no pending interaction
|
|
const reviewWithCard = await board.tasks.create("review/queue", "Needs human confirm");
|
|
const reviewClean = await board.tasks.create("review/queue", "Ready for agent review");
|
|
|
|
const claimedCard = await board.tasks.claim(reviewWithCard.identifier);
|
|
await claimedCard!.confirm("Approve deploy?", { humanOnly: true });
|
|
|
|
const claimedClean = await board.tasks.claim(reviewClean.identifier);
|
|
await claimedClean!.release({ status: "in_review", comment: "Ready for peer review" });
|
|
|
|
const reviewPop = await agentB.tasks.claim({
|
|
channel: "review/queue",
|
|
status: "in_review",
|
|
});
|
|
expect(reviewPop?.task.id).toBe(reviewClean.id);
|
|
await reviewPop!.complete("LGTM");
|
|
|
|
// Second pop must be null because reviewWithCard has a pending human interaction
|
|
const reviewPop2 = await agentB.tasks.claim({
|
|
channel: "review/queue",
|
|
status: "in_review",
|
|
});
|
|
expect(reviewPop2).toBeNull();
|
|
|
|
// 3. --assignee me / any: agentA claims its own assigned task, never steals agentB's
|
|
const forA = await board.tasks.create("assigned/pool", "Task for A", { for: "@backend-eng" });
|
|
const forB = await board.tasks.create("assigned/pool", "Task for B", { for: "@qa-reviewer" });
|
|
const unassignedTask = await board.tasks.create("assigned/pool", "Unassigned task");
|
|
|
|
const aMine = await agentA.tasks.claim({
|
|
channel: "assigned/pool",
|
|
assignee: "me",
|
|
});
|
|
expect(aMine?.task.id).toBe(forA.id);
|
|
await aMine!.complete("Done A");
|
|
|
|
// Next --assignee me for agentA is empty (cannot steal forB)
|
|
const aMine2 = await agentA.tasks.claim({
|
|
channel: "assigned/pool",
|
|
assignee: "me",
|
|
});
|
|
expect(aMine2).toBeNull();
|
|
|
|
// --assignee any for agentA picks up unassignedTask, still never steals forB
|
|
const aAny = await agentA.tasks.claim({
|
|
channel: "assigned/pool",
|
|
assignee: "any",
|
|
});
|
|
expect(aAny?.task.id).toBe(unassignedTask.id);
|
|
await aAny!.complete("Done unassigned");
|
|
|
|
const aAny2 = await agentA.tasks.claim({
|
|
channel: "assigned/pool",
|
|
assignee: "any",
|
|
});
|
|
expect(aAny2).toBeNull();
|
|
|
|
// Verify forB is still untouched and claimable by agentB
|
|
const bMine = await agentB.tasks.claim({
|
|
channel: "assigned/pool",
|
|
assignee: "me",
|
|
});
|
|
expect(bMine?.task.id).toBe(forB.id);
|
|
await bMine!.complete("Done B");
|
|
});
|
|
|
|
it("performs atomic handoff across channels with CAS labels and fenced lease release", async () => {
|
|
const board = makeBoardClient();
|
|
const draft = await board.tasks.create("seo/drafts", "Write AEO guide", {
|
|
labels: { stage: "draft" },
|
|
});
|
|
|
|
const claimed = await board.as("writer-1").tasks.claim({ channel: "seo/drafts" });
|
|
expect(claimed?.task.id).toBe(draft.id);
|
|
|
|
// CAS mismatch rejects without releasing lease or moving channel
|
|
await expect(
|
|
claimed!.handoff({
|
|
channel: "seo/review",
|
|
labels: { stage: "review" },
|
|
ifLabels: { stage: "wrong" },
|
|
}),
|
|
).rejects.toMatchObject({ status: 409, code: "label_conflict" });
|
|
|
|
// Valid CAS handoff moves channel, updates label, and releases lease atomically
|
|
const handed = await claimed!.handoff({
|
|
channel: "seo/review",
|
|
labels: { stage: "review" },
|
|
ifLabels: { stage: "draft" },
|
|
comment: "Draft complete, ready for fact-check",
|
|
});
|
|
expect(handed.channel).toBe("seo/review");
|
|
expect(handed.status).toBe("todo");
|
|
expect(handed.kvLabels.stage).toBe("review");
|
|
expect(handed.claimLeaseExpiresAt).toBeNull();
|
|
|
|
// Old writer lease is fenced
|
|
await expect(claimed!.renew("5m")).rejects.toMatchObject({
|
|
status: 409,
|
|
code: "claim_lost",
|
|
});
|
|
|
|
// Reviewer pool can immediately pop from seo/review
|
|
const reviewClaim = await board.as("reviewer-1").tasks.claim({
|
|
channel: "seo/review",
|
|
label: "stage=review",
|
|
});
|
|
expect(reviewClaim?.task.id).toBe(draft.id);
|
|
await reviewClaim!.complete("Published");
|
|
});
|
|
|
|
it("supports cancel, reopen, and mid-flight dependencies with cycle detection", async () => {
|
|
const board = makeBoardClient();
|
|
const taskA = await board.tasks.create("ops/work", "Deploy service A");
|
|
const taskB = await board.tasks.create("ops/work", "Run DB migration B");
|
|
|
|
// Worker claims A, discovers it needs B, adds dependency and releases lease
|
|
const claimedA = await board.as("ops-1").tasks.claim(taskA.identifier);
|
|
expect(claimedA).not.toBeNull();
|
|
|
|
const deps = await board.tasks.updateDependencies(taskA.identifier, {
|
|
add: [taskB.identifier],
|
|
releaseLease: true,
|
|
claimToken: claimedA!.claimToken,
|
|
claimEpoch: claimedA!.claimEpoch,
|
|
comment: "Waiting on migration B",
|
|
});
|
|
expect(deps.status).toBe("todo");
|
|
expect(deps.blockedBy.map((d) => d.id)).toContain(taskB.id);
|
|
|
|
// Cycle detection: B cannot depend on A
|
|
await expect(
|
|
board.tasks.updateDependencies(taskB.identifier, { add: [taskA.identifier] }),
|
|
).rejects.toMatchObject({ status: 400, code: "cyclic_dependencies" });
|
|
|
|
// A cannot be claimed while B is incomplete
|
|
await expect(board.tasks.claim(taskA.identifier)).rejects.toMatchObject({
|
|
status: 409,
|
|
code: "task_not_claimable",
|
|
});
|
|
|
|
// Complete B -> A becomes claimable again
|
|
const claimedB = await board.as("ops-2").tasks.claim(taskB.identifier);
|
|
await claimedB!.complete("Migration B done");
|
|
|
|
const claimedA2 = await board.as("ops-1").tasks.claim(taskA.identifier);
|
|
expect(claimedA2?.task.id).toBe(taskA.id);
|
|
|
|
// Cancel A -> status=cancelled
|
|
const cancelled = await board.tasks.cancel(taskA.identifier, {
|
|
claimToken: claimedA2!.claimToken,
|
|
reason: "Superseded",
|
|
});
|
|
expect(cancelled.status).toBe("cancelled");
|
|
|
|
// Reopen A -> status=todo
|
|
const reopened = await board.tasks.reopen(taskA.identifier, {
|
|
comment: "Actually still needed",
|
|
});
|
|
expect(reopened.status).toBe("todo");
|
|
|
|
// Adding a dependency with releaseLease: true on an UNCLAIMED todo task succeeds (no-op release)
|
|
const taskC = await board.tasks.create("ops/work", "Unclaimed waiting task");
|
|
const unclaimedDeps = await board.tasks.updateDependencies(taskC.identifier, {
|
|
add: [taskA.identifier],
|
|
releaseLease: true,
|
|
});
|
|
expect(unclaimedDeps.blockedBy.map((d) => d.id)).toContain(taskA.id);
|
|
});
|
|
|
|
it("supports channel update, private channel members, and managedPool auto-dispatch", async () => {
|
|
wakeupSpy.mockClear();
|
|
const board = makeBoardClient();
|
|
const agentA = makeAgentClient(agentAId);
|
|
const agentB = makeAgentClient(agentBId);
|
|
|
|
// Private channel membership
|
|
await board.channels.create("sec/private", { visibility: "private" });
|
|
await expect(agentA.read("sec/private")).rejects.toMatchObject({ status: 404 });
|
|
|
|
const added = await board.channels.members.add("sec/private", {
|
|
agent: "@backend-eng",
|
|
});
|
|
expect(added.subjectId).toBe(agentAId);
|
|
|
|
const members = await board.channels.members.list("sec/private");
|
|
expect(members.some((m) => m.subjectId === agentAId)).toBe(true);
|
|
|
|
// Now agentA can read, agentB still cannot
|
|
const page = await agentA.read("sec/private");
|
|
expect(page.kind).toBe("channel");
|
|
await expect(agentB.read("sec/private")).rejects.toMatchObject({ status: 404 });
|
|
|
|
const removed = await board.channels.members.remove("sec/private", {
|
|
agent: "@backend-eng",
|
|
});
|
|
expect(removed.removed).toBe(true);
|
|
await expect(agentA.read("sec/private")).rejects.toMatchObject({ status: 404 });
|
|
|
|
// Channel update + managedPool auto-dispatch (maxConcurrency = 1)
|
|
await board.channels.create("auto/drain", { description: "Initial" });
|
|
const t1 = await board.tasks.create("auto/drain", "Task 1");
|
|
const t2 = await board.tasks.create("auto/drain", "Task 2");
|
|
|
|
const updatedCh = await board.channels.update("auto/drain", {
|
|
description: "Auto-drained by backend-eng",
|
|
queueConfig: { ordering: "strict_fifo" },
|
|
managedPool: { agent: "@backend-eng", maxConcurrency: 1 },
|
|
});
|
|
expect(updatedCh.description).toBe("Auto-drained by backend-eng");
|
|
expect(updatedCh.queueConfig.ordering).toBe("strict_fifo");
|
|
expect(updatedCh.queueConfig.managedPool).toEqual({
|
|
agentId: agentAId,
|
|
maxConcurrency: 1,
|
|
});
|
|
|
|
// Exactly 1 of the 2 ready tasks should have been auto-assigned to backend-eng and woken!
|
|
const t1View = await board.read(t1.identifier);
|
|
const t2View = await board.read(t2.identifier);
|
|
const assignedCount = [t1View, t2View].filter(
|
|
(v) => v.kind === "thread" && v.issue.assigneeAgentId === agentAId,
|
|
).length;
|
|
expect(assignedCount).toBe(1);
|
|
expect(wakeupSpy).toHaveBeenCalledWith(
|
|
agentAId,
|
|
expect.objectContaining({ reason: "issue_assigned" }),
|
|
);
|
|
|
|
// Completing task 1 frees the managedPool slot and automatically dispatches task 2!
|
|
const firstAssigned =
|
|
t1View.kind === "thread" && t1View.issue.assigneeAgentId === agentAId ? t1 : t2;
|
|
const secondTask = firstAssigned.id === t1.id ? t2 : t1;
|
|
const claimedFirst = await agentA.tasks.claim(firstAssigned.identifier);
|
|
await claimedFirst!.complete("Done 1");
|
|
|
|
const secondAfterComplete = await board.read(secondTask.identifier);
|
|
expect(secondAfterComplete.kind).toBe("thread");
|
|
if (secondAfterComplete.kind === "thread") {
|
|
expect(secondAfterComplete.issue.assigneeAgentId).toBe(agentAId);
|
|
}
|
|
|
|
// Automatic managedPool assignments must be recorded in activityLog
|
|
const autoAssignActivity = await db
|
|
.select()
|
|
.from(activityLog)
|
|
.where(
|
|
and(
|
|
eq(activityLog.companyId, companyId),
|
|
eq(activityLog.entityId, firstAssigned.id),
|
|
eq(activityLog.action, "issue.assigned"),
|
|
),
|
|
);
|
|
expect(autoAssignActivity.length).toBeGreaterThanOrEqual(1);
|
|
expect(autoAssignActivity[0]?.actorType).toBe("system");
|
|
|
|
// ManagedPool cannot target a non-member agent on a private channel
|
|
await expect(
|
|
board.channels.update("sec/private", {
|
|
managedPool: { agent: "@qa-reviewer", maxConcurrency: 1 },
|
|
}),
|
|
).rejects.toMatchObject({ status: 403 });
|
|
|
|
// ManagedPool cannot target a protected agent with blockAssignment
|
|
const protectedAgentId = randomUUID();
|
|
await db.insert(agents).values({
|
|
id: protectedAgentId,
|
|
companyId,
|
|
name: "Protected Bot",
|
|
role: "engineer",
|
|
status: "idle",
|
|
adapterType: "process",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {
|
|
authorizationPolicy: {
|
|
protectedAgent: { blockAssignment: true },
|
|
},
|
|
},
|
|
});
|
|
await expect(
|
|
board.channels.update("auto/drain", {
|
|
managedPool: { agent: protectedAgentId, maxConcurrency: 1 },
|
|
}),
|
|
).rejects.toMatchObject({ status: 403 });
|
|
});
|
|
|
|
it("enforces creator/admin auth on channel admin, blocks cross-channel private dependency leaks, and fences stale cancel tokens", async () => {
|
|
const board = makeBoardClient();
|
|
const agentA = makeAgentClient(agentAId);
|
|
const agentB = makeAgentClient(agentBId);
|
|
|
|
// 1. Non-creator member cannot update channel config or manage members
|
|
await board.channels.create("sec/locked", { visibility: "private" });
|
|
await board.channels.members.add("sec/locked", { agent: "@backend-eng" });
|
|
|
|
await expect(
|
|
agentA.channels.update("sec/locked", { description: "Hijacked" }),
|
|
).rejects.toMatchObject({ status: 403, code: "channel_manage_denied" });
|
|
await expect(
|
|
agentA.channels.members.add("sec/locked", { agent: "@qa-reviewer" }),
|
|
).rejects.toMatchObject({ status: 403, code: "channel_manage_denied" });
|
|
await expect(
|
|
agentA.channels.members.remove("sec/locked", { agent: "@backend-eng" }),
|
|
).rejects.toMatchObject({ status: 403, code: "channel_manage_denied" });
|
|
|
|
// 2. Agent without access to private channel cannot attach or view private issue via dependencies
|
|
const secretTask = await board.tasks.create("sec/locked", "Secret credential rotation");
|
|
const publicTask = await board.tasks.create("pub/work", "Public task");
|
|
|
|
await expect(
|
|
agentB.tasks.updateDependencies(publicTask.identifier, {
|
|
add: [secretTask.identifier],
|
|
}),
|
|
).rejects.toMatchObject({ status: 404 });
|
|
|
|
// Even if an admin links secretTask -> publicTask, agentB's dependencies list hides secretTask
|
|
await board.tasks.updateDependencies(publicTask.identifier, {
|
|
add: [secretTask.identifier],
|
|
});
|
|
const depsForB = await agentB.tasks.dependencies(publicTask.identifier);
|
|
expect(depsForB.blockedBy).toEqual([]);
|
|
|
|
// Valid public dependency can be added and read by an agent
|
|
const publicBlocker = await board.tasks.create("pub/work", "Public blocker");
|
|
const addedByAgent = await agentB.tasks.updateDependencies(publicTask.identifier, {
|
|
add: [publicBlocker.identifier],
|
|
});
|
|
expect(addedByAgent.blockedBy.map((d) => d.id)).toEqual([publicBlocker.id]);
|
|
const listedByAgent = await agentB.tasks.dependencies(publicTask.identifier);
|
|
expect(listedByAgent.blockedBy.map((d) => d.id)).toEqual([publicBlocker.id]);
|
|
|
|
// 3. Stale worker claim token cannot cancel an already-completed task
|
|
const raceTask = await board.tasks.create("pub/work", "Race cancel test");
|
|
const staleClaim = await board.as("stale-worker").tasks.claim(raceTask.identifier);
|
|
expect(staleClaim).not.toBeNull();
|
|
await staleClaim!.complete("Finished cleanly");
|
|
|
|
await expect(
|
|
board.tasks.cancel(raceTask.identifier, {
|
|
claimToken: staleClaim!.claimToken,
|
|
claimEpoch: staleClaim!.claimEpoch,
|
|
reason: "Delayed stale cancel",
|
|
}),
|
|
).rejects.toMatchObject({ status: 409, code: "claim_lost" });
|
|
});
|
|
});
|