feat(board): add task assign, atomic handoff, claim filters, cancel/reopen, mid-flight deps, and channel admin (#23415)

## 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
This commit is contained in:
Dotta authored and GitHub committed 2026-12-01 23:54:54 +00:00
1 parent fcb8fc5deb
commit 0434e7f3aa
30 files changed
+5985 -67

No files matched your search

@@ -0,0 +1,133 @@
---
name: channels-queues-and-workflows
description: Design and run Paperclip channel queues, inboxes, and multi-agent workflows with leases, assign, handoff, CAS labels, DAG deps, and human gates.
---
# Channels, Queues, and Workflows
Use Paperclip's channel, queue, lease, handoff, label, and dependency primitives to coordinate multi-agent work without heavy setup or custom glue.
## Core Mental Model
Four primitives cover every queue and workflow pattern:
1. **Channel = lightweight folder / room of Issues.**
- Created lazily on first write (`pc post`, `pc tasks create`). Supports nested slash paths (`seo/briefs`, `factory/build`); trailing `/` queries the whole subtree (`seo/`).
- Separate from **Projects**: a Project binds execution infrastructure (Git repos, sandboxes, secrets); a Channel is just a stream/queue. They compose cleanly (`--project` is optional per task or channel default).
- Administer channel queue policy, archive state, private membership, or managed-pool auto-drain anytime with `pc channels update <path>` (alias `config`) and `pc channels members list|add|remove <path>`.
2. **Post vs. Task = the same `Issue` object.**
- `pc post <channel> "<text>"` creates an unassigned `status=backlog` issue (`scope=channel`). Default `claim --ready` ignores it.
- `pc tasks create <channel> "<text>"` creates an unassigned `status=todo` issue (`scope=channel`). Workers can claim it immediately.
- `pc tasks create <existing-id>` (or `pc tasks assign <id> @agent`) promotes a `backlog` post to `todo` in place, keeping its ID (`PAP-142`) and full thread history.
3. **Queue = pullable slice of ready issues (Pull vs. Push).**
- No separate Queue resource is required. Any channel with ready issues *is* a queue.
- **Pull (`pc tasks claim --ready <channel>`):** Pops the next matching task atomically (`FOR UPDATE SKIP LOCKED`), sets `status=in_progress`, and grants a 5-minute TTL lease + fenced `claimToken`.
- **Safe default:** `status=todo` + `unassigned`.
- **Opt-in filters:** Pass `--status backlog` (e.g., triage bot draining raw inbox posts) or `--status in_review` (review pool — automatically excludes tasks waiting on pending human interaction cards). Pass `--mine` (`--assignee me`) to claim tasks pushed to *you*, or `--assignee any` for unassigned + yours (never steals another agent's assigned task).
- **Push (`pc tasks assign <id> @agent`):** Assigns an existing post/task to a registered Paperclip agent (auto-promoting `backlog` → `todo` unless `--keep-status`) and wakes it via Paperclip's managed Runner. Use `--unassign` to return a task to the unassigned pool, or `--force` to fence an active worker lease.
- **Managed Pool Auto-Drain:** Bind a managed agent directly to a channel (`pc channels update factory/build --managed-pool @coder --max-concurrency 4`) so Paperclip's control plane automatically assigns and wakes up to `N` concurrent tasks without an external bash loop.
4. **Key-Value Labels (`kv_labels`) = routing and lock-free state.**
- Slice any queue with `--label key=value` (`--label role=reviewer`, `--label stage=draft`).
- Guard state transitions with atomic Compare-And-Swap (`--if` / `--if-unset`): `pc label PAP-50 stage=draft --if stage=new` returns `409 label_conflict` if another agent already transitioned it.
---
## Queue & Inbox Patterns
### 1. Direct Work Queue (Drop & Drain)
Use when every dropped item is immediately actionable by a pool of fungible workers.
```bash
# Producers drop work in (human, cron, webhook, or lead agent)
pc tasks create triage/bugs "Fix 500 on /api/checkout" --priority high --label role=fixer
# Pool of workers drains in parallel (auto-renews lease, releases on Ctrl-C)
pc tasks run --ready triage/bugs --label role=fixer --wait 10m --as worker-1 \
-- claude -p 'Read $PAPERCLIP_TASK_ID with pc read, fix it, verify, and reply.'
```
### 2. Two-Step Inbox (Passive Drop → Triage → Promote or Assign)
Use when raw signals are noisy (alerts, external requests, ideas) and should not burn worker tokens until triaged.
```bash
# 1. Drop raw signal as passive backlog post (zero worker wakeups)
pc post errors/web "500 spike on /api/checkout (14 occurrences in 5m)"
# 2. Optional: a lightweight triage bot pops raw backlog posts with --status backlog
pc tasks claim --ready errors/web --status backlog --as triage-bot
# 3. Promote to a worker pool OR push-assign directly to a managed agent:
pc tasks create PAP-142 --priority high --label role=fixer
# ...or push to a named Paperclip agent (auto-promotes backlog -> todo and wakes @backend-eng):
pc tasks assign PAP-142 @backend-eng --comment "Confirmed nil stripeCustomerId"
```
---
## Multi-Agent Workflow Patterns
Choose one of three patterns (or combine them) based on the shape of the work:
### Pattern A: Single-Thread Relay (Atomic `handoff` Across Stages or Channels)
**Use when:** One unit of work (a support ticket, PR, or article) moves sequentially through specialists and every specialist needs the **entire conversation history in one thread**.
Use **`pc tasks handoff`** (alias **`move`**) to atomically move channels, update labels (with optional `--if` CAS), change status/assignee, and release the active lease in **one transaction**:
```bash
# Writer finishes draft and atomically hands off PAP-50 to #seo/review with CAS guard
pc tasks handoff PAP-50 --channel seo/review \
--label stage=review --if stage=draft \
--comment "Draft ready for fact-check" --as writer-1
```
You can also keep the issue in a single channel and omit `--channel`, or push-assign the next stage directly (`--assignee @qa-reviewer`).
### Pattern B: Assembly Line (Chained Channels with 1-to-Many Fan-Out)
**Use when:** Stages produce **distinct artifacts**, have **1-to-many fan-out** (1 audit → 5 fix tasks, 1 topic → 3 briefs), or need **separate queue policies/permissions** per stage.
- Give each stage its own channel: `#seo/topics` → `#seo/briefs` → `#seo/drafts` → `#seo/publish`.
- A worker pops from Stage $N$, produces its artifact, creates one or more `todo` tasks in Stage $N+1$ (linking back to the source ID), and marks its Stage $N$ task `done`.
- `pc channels --prefix seo/` surfaces queue depth and bottlenecks at every stage.
### Pattern C: DAG Fan-Out / Fan-In (`plan.json` + Mid-Flight `--needs`)
**Use when:** The dependency graph is known up front (feature launches, multi-repo refactors) OR a worker discovers a new prerequisite mid-flight.
- **Up-front DAG:** `pc tasks create <channel> --file plan.json --idempotency-key <key>`. Tasks with `"needs": ["keyA", "keyB"]` sit in `Waiting` until every dependency reaches `done`, then flip `Ready` automatically.
- **Mid-flight prerequisite:** If a worker claims `PAP-142` and discovers it needs `PAP-150` done first, park it without losing auto-wakeup:
```bash
pc tasks block PAP-142 --needs PAP-150 "Waiting on schema migration" --as worker-1
# Releases lease and parks PAP-142 in todo (Waiting). Auto-becomes Ready when PAP-150 completes!
```
- Inspect or edit dependencies anytime with `pc tasks deps list|add|remove <id>`.
---
## Lifecycle & Workflow Glue
- **Non-Blocking Human Gates (`pc ask` / `pc confirm`):** Posts a typed interactive card, moves the task to `in_review`, and **releases the worker's lease**. When the human answers or clicks Approve (`--human`), Paperclip automatically flips the task back to `todo` (`Ready`) for the pool.
- **Cancel & Reopen:** Cancel duplicate/obsolete tasks with `pc tasks cancel <id> "Duplicate of PAP-110"` (use `--force` to fence another worker's lease), and reopen `done`/`cancelled`/`blocked` tasks with `pc tasks reopen <id>`.
- **Typed Stage Contracts (`--schema` & `--result-schema`):** Attach `--schema finding@1` on posts/replies for validated JSON alongside Markdown prose, or `--result-schema content-brief@1` on tasks so `pc tasks complete <id> --data '{...}'` enforces the JSON contract before `done`.
---
## Decision Cheat Sheet
| Goal | Primitive / Command | Example |
| :--- | :--- | :--- |
| Group a stream or create a distinct stage queue | **Channel** | `#seo/drafts`, `#factory/build` |
| Log/discuss before deciding whether to run agents | **Passive Post (`pc post`)** | `#errors/web` → promote or `--status backlog` |
| Pull next ready task from a pool (or your own assigned) | **`pc tasks claim`** | `pc tasks claim --ready build/ --mine` |
| Push an existing post/task to a managed Paperclip agent | **`pc tasks assign`** | `pc tasks assign PAP-142 @backend-eng` |
| Atomically move channel + update labels + drop lease | **`pc tasks handoff` (`move`)** | `pc tasks handoff PAP-50 --channel seo/review --label stage=review` |
| Park a task waiting on a newly discovered blocker | **`pc tasks block --needs`** | `pc tasks block PAP-142 --needs PAP-150` |
| Cancel or reopen a task | **`pc tasks cancel` / `reopen`** | `pc tasks cancel PAP-9 "Duplicate"` |
| Auto-drain a channel with a managed Paperclip agent | **`pc channels update`** | `pc channels update build --managed-pool @coder --max-concurrency 4` |
| Manage `--private` channel access | **`pc channels members`** | `pc channels members add sec/private @sec-bot` |
| Pause for human decision without blocking a worker | **`pc ask` / `pc confirm`** | Drops lease → human resolves → auto-requeues |
| Bind a Git repo, sandbox, and secrets | **Project (`--project`)** | `#factory/build` + `--project web-app` |
---
## Additional Resources
- For complete end-to-end recipes (Software Factory, Customer Service Review, SEO/AEO Content Engine, and Feature Launch Campaign), see [examples.md](examples.md).
@@ -0,0 +1,206 @@
# Channel Queue & Workflow Examples
End-to-end recipes combining Paperclip channels, pull leases, push `assign`, atomic `handoff`, `kv_labels` (with CAS), DAG `plan.json` + mid-flight `--needs`, human gates, `--result-schema` contracts, and managed pools.
---
## 1. Software Factory (Inbox → Plan DAG → Mid-Flight Blocker → Review)
**Patterns combined:** Two-step Inbox + DAG (`needs`) + `--project` binding + Mid-flight `block --needs` + Human Gate + Managed Pool.
**Channels:**
- `#factory/inbox` — passive bug reports and feature requests (`pc post`)
- `#factory/build` — active coding and review queue (`--project web-app`)
- `#deploys/prod` — passive release breadcrumbs (`pc post`)
### Step 1: Signal arrives in passive inbox & triage pops `--status backlog`
```bash
id=$(pc post factory/inbox "Checkout returns 500 when guest cart has promo code" --label source=sentry -q)
# Option A: Triage bot drains raw backlog posts directly
pc tasks claim --ready factory/inbox --status backlog --as triage-bot
# Option B: Human or triage bot push-assigns directly to a managed agent
pc tasks assign "$id" @backend-eng --comment "Reproduced on staging"
```
### Step 2: Or triage submits a 2-step DAG into `#factory/build`
```bash
cat <<'EOF' > /tmp/factory-plan.json
{
"channel": "factory/build",
"projectId": "web-app",
"idempotencyKey": "fix-guest-promo-500",
"tasks": [
{
"key": "fix",
"title": "Fix nil customer check on guest promo checkout",
"description": "Origin thread: PAP-142. Add regression test and open PR.",
"labels": { "role": "coder", "origin": "PAP-142" },
"resultSchema": "pull-request@1"
},
{
"key": "review",
"title": "Adversarial review of guest promo fix PR",
"description": "Verify diff, tests, and migration safety. Merge if clean.",
"labels": { "role": "reviewer", "origin": "PAP-142" },
"needs": ["fix"],
"resultSchema": "review-verdict@1"
}
]
}
EOF
pc tasks create factory/build --file /tmp/factory-plan.json --as triage-bot
```
### Step 3: Mid-flight dependency discovery + Human gate
If the coder discovers a prerequisite migration while working `PAP-143`:
```bash
mig=$(pc tasks create factory/build "Backfill null customer_id rows" --label role=coder -q)
pc tasks block PAP-143 --needs "$mig" "Needs backfill before constraint" --as coder-1
# PAP-143 releases its lease and automatically flips Ready when $mig completes!
```
If the reviewer hits a risky migration:
```bash
pc confirm PAP-144 "PR #418 adds a NOT NULL column on orders. Approve merge?" --human --as reviewer-1
# Lease is dropped immediately; once a human clicks Approve, PAP-144 flips back to `todo`.
```
---
## 2. Customer Service Review Flow (Single-Thread Relay with Atomic `handoff`)
**Patterns combined:** Single-thread relay via atomic `pc tasks handoff` + CAS `--if` + Human Gate for high-value refunds.
**Channel:** `#support/tickets`
**State machine (`kv_labels`):** `stage=new` → `stage=drafted` → `stage=approved` → `done`
### Step 1: Ticket lands in the queue
```bash
pc tasks create support/tickets "Customer #8821 requests $120 refund for double charge" \
--priority high \
--label stage=new \
--label tier=enterprise
```
### Step 2: Drafter pops `stage=new` and atomically hands off in one call
```bash
# Drafter claims: pc tasks claim --ready support/tickets --label stage=new --as drafter-1
pc tasks handoff "$PAPERCLIP_TASK_ID" \
--label stage=drafted --label refund_amount=120 \
--if stage=new \
--comment "Verified duplicate Stripe charge ch_3Q9x. Drafted apology + $120 refund." \
--as drafter-1
```
### Step 3: Policy/QA agent pops `stage=drafted`
```bash
# Routine ticket (<= $50): atomic handoff to sender
pc tasks handoff "$PAPERCLIP_TASK_ID" --label stage=approved --if stage=drafted --as qa-1
# High-value refund (> $50): ask a human without holding the worker slot
pc confirm "$PAPERCLIP_TASK_ID" "Approve $120 refund and send drafted reply to Customer #8821?" --human --as qa-1
```
Once the human approves, the ticket requeues and the **Sender agent** (`--ready support/tickets --label stage=approved`) executes the refund + email and calls `pc tasks complete`.
---
## 3. SEO / AEO Content Engine (Chained Channels with Single-Thread `handoff`)
**Patterns combined:** Multi-channel pipeline (`#aeo/gaps` → `#aeo/briefs` → `#aeo/drafts` → `#aeo/fact-check` → `#aeo/publish`) + atomic `pc tasks handoff --channel` + `--result-schema` + managed pool auto-drain.
### Step 1: Configure channels & optional managed pool
```bash
pc schemas create content-brief@1 --file ./schemas/content-brief.schema.json
pc schemas create fact-check@1 --file ./schemas/fact-check.schema.json
# Optional: let Paperclip auto-drain #aeo/fact-check using a managed agent
pc channels create aeo/fact-check --description "Independent fact verification"
pc channels update aeo/fact-check --ordering strict_fifo --managed-pool @fact-checker --max-concurrency 2
```
### Step 2: Scheduled monitor drops passive findings into `#aeo/gaps`
```bash
pc post aeo/gaps "Paperclip not cited for 'open source ai agent control plane' on ChatGPT" \
--schema aeo-gap@1 '{"query":"open source ai agent control plane","engine":"chatgpt","share":0.0}'
```
### Step 3: Move the same thread across stage channels with `handoff` (or spawn 1-to-many)
```bash
# Brief writer finishes and moves the same thread into #aeo/drafts
pc tasks handoff PAP-202 --channel aeo/drafts --label stage=draft \
--comment "Brief finalized with target citations" --as strategist-1
# Writer finishes and moves into #aeo/fact-check (requiring fact-check@1)
pc tasks handoff PAP-202 --channel aeo/fact-check --label stage=verify \
--result-schema fact-check@1 --comment "Draft complete" --as writer-1
```
Check pipeline health and queue depths at any time:
```bash
pc channels list --prefix aeo/
```
---
## 4. Feature Launch Campaign (Parallel Fan-Out / Fan-In DAG)
**Patterns combined:** Single `plan.json` DAG with parallel specialist tracks and a synchronized final human launch gate.
**Channel:** `#launch/channels-v1`
```json
{
"channel": "launch/channels-v1",
"idempotencyKey": "launch-channels-v1",
"tasks": [
{
"key": "changelog",
"title": "Draft release changelog entry for Channels & Queues",
"labels": { "role": "eng" }
},
{
"key": "docs",
"title": "Publish CHANNELS-AND-QUEUES.md and CLI reference updates",
"labels": { "role": "docs" }
},
{
"key": "blog",
"title": "Write launch blog post with tutorial walkthrough",
"labels": { "role": "marketing" }
},
{
"key": "social",
"title": "Draft launch thread and short demo captions from blog post",
"labels": { "role": "marketing" },
"needs": ["blog"]
},
{
"key": "demo",
"title": "Record 60-second terminal demo of pc up + worker pool",
"labels": { "role": "design" }
},
{
"key": "go-live",
"title": "Compile launch checklist and request final human go-live approval",
"labels": { "role": "launch-lead" },
"needs": ["changelog", "docs", "blog", "social", "demo"]
}
]
}
```
```bash
# Load the entire campaign in one atomic call
pc tasks create launch/channels-v1 --file launch-plan.json --as launch-lead
# Specialists work in parallel; `social` waits for `blog`, and `go-live` waits for all 5.
pc tasks run --ready launch/channels-v1 --label role=eng --as eng-agent -- ...
pc tasks run --ready launch/channels-v1 --label role=docs --as docs-agent -- ...
pc tasks run --ready launch/channels-v1 --label role=marketing --as mktg-agent -- ...
pc tasks run --ready launch/channels-v1 --label role=design --as design-agent -- ...
```
When the 5th deliverable completes, `go-live` flips from `Waiting` to `Ready`; the launch lead pops it, posts links to all artifacts, and calls `pc confirm --human "All 5 launch assets ready. Publish?"`.
+204 -1
View File
@@ -1,6 +1,6 @@
import pc from "picocolors";
import type { Command } from "commander";
import type { ChannelPage, ChannelView, ThreadDetailView } from "@paperclipai/shared/sdk";
import { parseDurationMs, type ChannelPage, type ChannelView, type ThreadDetailView } from "@paperclipai/shared/sdk";
import { channelsCommand } from "../channels.js";
import {
addBoardClientOptions,
@@ -350,6 +350,209 @@ function configureChannelsSubtree(cmd: Command, opts: { forceBoard: boolean }):
}
}),
);
addBoardClientOptions(
cmd
.command("update")
.alias("config")
.description("Update channel description, default project, archive state, or queue/managed-pool config")
.argument("<path>", "Channel path (e.g. build/auth)")
.option("--description <text>", "Channel description")
.option("--project <id-or-slug>", "Default project ID or slug")
.option("--clear-project", "Clear default project")
.option("--archive", "Archive channel")
.option("--unarchive", "Unarchive channel")
.option("--lease <dur>", "Default lease duration (e.g. 5m)")
.option("--max-lease <dur>", "Maximum lease duration (e.g. 1h)")
.option("--max-attempts <n>", "Max claim attempts before poison-pill block", (v) => Number.parseInt(v, 10))
.option("--ordering <mode>", "Queue ordering (priority_fifo or strict_fifo)")
.option("--managed-pool <agent>", "Bind a managed Paperclip agent to auto-drain this channel")
.option("--max-concurrency <n>", "Max concurrent tasks for --managed-pool (default: 1)", (v) => Number.parseInt(v, 10))
.option("--clear-managed-pool", "Remove managed pool binding from this channel")
.action(
async (
channelPath: string,
updateOpts: BoardCommonOptions & {
description?: string;
project?: string;
clearProject?: boolean;
archive?: boolean;
unarchive?: boolean;
lease?: string;
maxLease?: string;
maxAttempts?: number;
ordering?: string;
managedPool?: string;
maxConcurrency?: number;
clearManagedPool?: boolean;
},
) => {
try {
const resolved = resolveBoardClient(updateOpts);
const queueConfig: Record<string, unknown> = {};
if (updateOpts.lease) {
queueConfig.defaultLeaseSec = Math.max(
30,
Math.round(parseDurationMs(updateOpts.lease) / 1000),
);
}
if (updateOpts.maxLease) {
queueConfig.maxLeaseSec = Math.max(
30,
Math.round(parseDurationMs(updateOpts.maxLease) / 1000),
);
}
if (updateOpts.maxAttempts !== undefined && Number.isFinite(updateOpts.maxAttempts)) {
queueConfig.maxClaimAttempts = updateOpts.maxAttempts;
}
if (updateOpts.ordering) {
if (updateOpts.ordering !== "priority_fifo" && updateOpts.ordering !== "strict_fifo") {
throw new Error('Invalid --ordering: expected "priority_fifo" or "strict_fifo"');
}
queueConfig.ordering = updateOpts.ordering;
}
const updated = await resolved.client.channels.update(channelPath, {
...(updateOpts.description !== undefined
? { description: updateOpts.description }
: {}),
...(updateOpts.clearProject
? { defaultProjectId: null }
: updateOpts.project
? { defaultProjectId: updateOpts.project }
: {}),
...(updateOpts.archive
? { archived: true }
: updateOpts.unarchive
? { archived: false }
: {}),
...(Object.keys(queueConfig).length > 0 ? { queueConfig } : {}),
...(updateOpts.clearManagedPool
? { managedPool: null }
: updateOpts.managedPool
? {
managedPool: {
agent: updateOpts.managedPool,
maxConcurrency: updateOpts.maxConcurrency ?? 1,
},
}
: {}),
});
if (resolved.json) {
console.log(JSON.stringify(updated, null, 2));
return;
}
if (isScriptOutput(resolved)) {
console.log(updated.path);
return;
}
console.log(pc.green(`Updated channel #${updated.path}.`));
} catch (err) {
handleBoardError(err, updateOpts);
}
},
),
);
const membersCmd = cmd
.command("members")
.description("Manage access members on a channel (e.g. --private channels)");
addBoardClientOptions(
membersCmd
.command("list")
.description("List explicit access members on a channel")
.argument("<path>", "Channel path")
.action(async (channelPath: string, listOpts: BoardCommonOptions) => {
try {
const resolved = resolveBoardClient(listOpts);
const members = await resolved.client.channels.members.list(channelPath);
if (resolved.json) {
console.log(JSON.stringify({ items: members }, null, 2));
return;
}
if (members.length === 0) {
console.log(pc.dim(`No explicit members on #${channelPath}.`));
return;
}
for (const m of members) {
const label = m.displayName ? `${m.displayName} (${m.subjectId})` : m.subjectId;
console.log(` [${m.subjectType}] ${label}`);
}
} catch (err) {
handleBoardError(err, listOpts);
}
}),
);
addBoardClientOptions(
membersCmd
.command("add")
.description("Grant an agent or user access to a private channel")
.argument("<path>", "Channel path")
.argument("<target>", "Agent (@name, slug, or UUID) or user ID (with --user)")
.option("--user", "Treat <target> as a user ID instead of an agent")
.action(
async (
channelPath: string,
target: string,
addOpts: BoardCommonOptions & { user?: boolean },
) => {
try {
const resolved = resolveBoardClient(addOpts);
const added = await resolved.client.channels.members.add(
channelPath,
addOpts.user ? { userId: target } : { agent: target },
);
if (resolved.json) {
console.log(JSON.stringify(added, null, 2));
return;
}
console.log(
pc.green(`Added ${added.subjectType} ${added.displayName ?? added.subjectId} to #${channelPath}.`),
);
} catch (err) {
handleBoardError(err, addOpts);
}
},
),
);
addBoardClientOptions(
membersCmd
.command("remove")
.description("Revoke an agent or user's access to a private channel")
.argument("<path>", "Channel path")
.argument("<target>", "Agent (@name, slug, or UUID) or user ID (with --user)")
.option("--user", "Treat <target> as a user ID instead of an agent")
.action(
async (
channelPath: string,
target: string,
rmOpts: BoardCommonOptions & { user?: boolean },
) => {
try {
const resolved = resolveBoardClient(rmOpts);
const res = await resolved.client.channels.members.remove(
channelPath,
rmOpts.user ? { userId: target } : { agent: target },
);
if (resolved.json) {
console.log(JSON.stringify(res, null, 2));
return;
}
console.log(
res.removed
? pc.yellow(`Removed ${target} from #${channelPath}.`)
: pc.dim(`${target} was not a member of #${channelPath}.`),
);
} catch (err) {
handleBoardError(err, rmOpts);
}
},
),
);
}
export function registerBoardChannelCommands(program: Command): void {
+446
View File
@@ -0,0 +1,446 @@
import type { Command } from "commander";
import pc from "picocolors";
import { ISSUE_PRIORITIES, type IssuePriority } from "@paperclipai/shared";
import {
CLAIMABLE_TASK_STATUSES,
type ClaimableTaskStatus,
type HeadlessIssueView,
type TaskDependenciesView,
} from "@paperclipai/shared/sdk";
import {
addBoardClientOptions,
collectOption,
handleBoardError,
isScriptOutput,
parseLabelsList,
resolveBoardClient,
splitCsvValues,
type BoardCommonOptions,
} from "./client.js";
import { deleteClaimRecord, resolveClaimCredentials } from "./store.js";
interface TasksAssignOptions extends BoardCommonOptions {
unassign?: boolean;
keepStatus?: boolean;
force?: boolean;
comment?: string;
message?: string;
}
interface TasksHandoffOptions extends BoardCommonOptions {
channel?: string;
label?: string[];
unset?: string[];
if?: string[];
status?: string;
assignee?: string;
unassign?: boolean;
priority?: string;
resultSchema?: string;
clearResultSchema?: boolean;
comment?: string;
message?: string;
}
interface TasksCancelOptions extends BoardCommonOptions {
reason?: string;
message?: string;
force?: boolean;
}
interface TasksReopenOptions extends BoardCommonOptions {
status?: string;
comment?: string;
message?: string;
}
interface TasksDepsMutateOptions extends BoardCommonOptions {
needs?: string[];
release?: boolean;
comment?: string;
message?: string;
}
function parseOptionalClaimableStatus(raw?: string): ClaimableTaskStatus | undefined {
if (!raw) return undefined;
const trimmed = raw.trim().toLowerCase();
if (!CLAIMABLE_TASK_STATUSES.includes(trimmed as ClaimableTaskStatus)) {
throw new Error(
`Invalid status "${raw}": expected one of ${CLAIMABLE_TASK_STATUSES.join(", ")}`,
);
}
return trimmed as ClaimableTaskStatus;
}
function parseIfPairs(rawPairs: string[] | undefined): Record<string, string | null> | undefined {
if (!rawPairs || rawPairs.length === 0) return undefined;
const out: Record<string, string | null> = {};
for (const expr of rawPairs) {
const idx = expr.indexOf("=");
if (idx <= 0) {
throw new Error(`Invalid --if expression "${expr}": expected key=value or key=null`);
}
const key = expr.slice(0, idx).trim();
const val = expr.slice(idx + 1).trim();
out[key] = val === "" || val === "null" ? null : val;
}
return out;
}
function formatDependencies(deps: TaskDependenciesView): void {
console.log(`${pc.cyan(deps.identifier)} (status=${deps.status})`);
if (deps.blockedBy.length === 0) {
console.log(` blocked by: ${pc.dim("(none)")}`);
} else {
console.log(" blocked by:");
for (const item of deps.blockedBy) {
console.log(` - ${pc.cyan(item.identifier)} [${item.status}] ${item.title}`);
}
}
if (deps.blocks.length === 0) {
console.log(` blocks: ${pc.dim("(none)")}`);
} else {
console.log(" blocks:");
for (const item of deps.blocks) {
console.log(` - ${pc.cyan(item.identifier)} [${item.status}] ${item.title}`);
}
}
}
export function registerTaskWorkflowCommands(tasksCmd: Command): void {
addBoardClientOptions(
tasksCmd
.command("assign")
.description("Assign an existing task or channel post to a registered agent (or --unassign)")
.argument("<id>", "Issue identifier or UUID")
.argument("[agent]", "Target agent (@name, slug, or UUID)")
.option("--unassign", "Clear assignee and return task to the unassigned pool")
.option("--keep-status", "Do not auto-promote a passive backlog post to todo")
.option("--force", "Fence and clear an active worker lease if currently claimed")
.option("--comment <text>", "Optional handoff note")
.option("-m, --message <text>", "Alias for --comment")
.action(async (id: string, agent: string | undefined, opts: TasksAssignOptions) => {
try {
const resolved = resolveBoardClient(opts);
if (!opts.unassign && !agent) {
throw new Error("Specify an <agent> or pass --unassign.");
}
const comment = opts.comment ?? opts.message;
const updated: HeadlessIssueView = await resolved.client.tasks.assign(
id,
opts.unassign ? null : agent!,
{
...(opts.unassign ? { unassign: true } : {}),
...(opts.keepStatus ? { keepStatus: true } : {}),
...(opts.force ? { force: true } : {}),
...(comment !== undefined ? { comment } : {}),
},
);
const companyId = await resolved.resolveCompanyId();
if (opts.force) {
deleteClaimRecord(companyId, id);
}
if (resolved.json) {
console.log(JSON.stringify(updated, null, 2));
return;
}
if (isScriptOutput(resolved)) {
console.log(updated.identifier);
return;
}
const targetDesc = opts.unassign
? "unassigned pool"
: pc.bold(agent!);
console.log(
`${pc.green("Assigned")} ${pc.cyan(updated.identifier)} -> ${targetDesc} (status=${updated.status}, ${updated.cursor})`,
);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
addBoardClientOptions(
tasksCmd
.command("handoff")
.alias("move")
.description("Atomically move channel, update labels/assignee/status, and release any active lease")
.argument("<id>", "Issue identifier or UUID")
.argument("[channel]", "Optional target channel path")
.option("--channel <path>", "Target channel path")
.option("--label <k=v>", "Set key=value label(s) (repeatable)", collectOption, [])
.option("--unset <key>", "Unset label key(s) (repeatable)", collectOption, [])
.option("--if <k=v>", "CAS precondition (key=value or key=null, repeatable)", collectOption, [])
.option("--status <status>", "Target status (todo, backlog, in_review; default: todo)")
.option("--assignee <agent>", "Push-assign to a registered agent (@name, slug, or UUID)")
.option("--unassign", "Clear assignee so the target queue pool can claim it")
.option("--priority <level>", "Update priority (critical, high, medium, low)")
.option("--result-schema <ref>", "Require structured result schema (<name>@<version>)")
.option("--clear-result-schema", "Clear required result schema")
.option("--comment <text>", "Handoff note")
.option("-m, --message <text>", "Alias for --comment")
.action(async (id: string, channelArg: string | undefined, opts: TasksHandoffOptions) => {
try {
const resolved = resolveBoardClient(opts);
const companyId = await resolved.resolveCompanyId();
const claim = resolveClaimCredentials({
companyId,
issueRef: id,
activeProfile: resolved.profile,
requireClaim: false,
});
const { kvLabels: labels } = parseLabelsList(opts.label);
const ifLabels = parseIfPairs(opts.if);
const status = parseOptionalClaimableStatus(opts.status);
let priority: IssuePriority | undefined;
if (opts.priority) {
if (!ISSUE_PRIORITIES.includes(opts.priority as IssuePriority)) {
throw new Error(
`Invalid priority "${opts.priority}": expected one of ${ISSUE_PRIORITIES.join(", ")}`,
);
}
priority = opts.priority as IssuePriority;
}
const targetChannel = opts.channel ?? channelArg;
const comment = opts.comment ?? opts.message;
const updated = await resolved.client.tasks.handoff(id, {
...(claim ? { claimToken: claim.claimToken } : {}),
...(claim?.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}),
...(targetChannel ? { channel: targetChannel } : {}),
...(status ? { status } : {}),
...(Object.keys(labels).length > 0 ? { labels } : {}),
...(opts.unset && opts.unset.length > 0 ? { unsetLabels: opts.unset } : {}),
...(ifLabels ? { ifLabels } : {}),
...(opts.unassign
? { unassign: true }
: opts.assignee !== undefined
? { assignee: opts.assignee }
: {}),
...(priority ? { priority } : {}),
...(opts.clearResultSchema
? { resultSchema: null }
: opts.resultSchema !== undefined
? { resultSchema: opts.resultSchema }
: {}),
...(comment !== undefined ? { comment } : {}),
});
if (claim) {
deleteClaimRecord(companyId, id);
}
if (resolved.json) {
console.log(JSON.stringify(updated, null, 2));
return;
}
if (isScriptOutput(resolved)) {
console.log(updated.identifier);
return;
}
const chLabel = updated.channel ? `#${updated.channel}` : "board";
console.log(
`${pc.green("Handed off")} ${pc.cyan(updated.identifier)} -> ${chLabel} (status=${updated.status}, ${updated.cursor})`,
);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
addBoardClientOptions(
tasksCmd
.command("cancel")
.description("Cancel a task (status=cancelled), releasing any active lease")
.argument("<id>", "Issue identifier or UUID")
.argument("[reason...]", "Optional cancellation reason")
.option("--reason <text>", "Cancellation reason")
.option("-m, --message <text>", "Alias for --reason")
.option("--force", "Force-cancel even if another worker currently holds a lease")
.action(async (id: string, reasonParts: string[], opts: TasksCancelOptions) => {
try {
const resolved = resolveBoardClient(opts);
const companyId = await resolved.resolveCompanyId();
const claim = resolveClaimCredentials({
companyId,
issueRef: id,
activeProfile: resolved.profile,
requireClaim: false,
});
const positional = reasonParts.length > 0 ? reasonParts.join(" ") : undefined;
const reason = opts.reason ?? opts.message ?? positional;
const updated = await resolved.client.tasks.cancel(id, {
...(claim ? { claimToken: claim.claimToken } : {}),
...(claim?.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}),
...(reason !== undefined ? { reason } : {}),
...(opts.force ? { force: true } : {}),
});
if (claim || opts.force) {
deleteClaimRecord(companyId, id);
}
if (resolved.json) {
console.log(JSON.stringify(updated, null, 2));
return;
}
if (isScriptOutput(resolved)) {
console.log(updated.identifier);
return;
}
console.log(
`${pc.yellow("Cancelled")} ${pc.cyan(updated.identifier)} (${updated.cursor})`,
);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
addBoardClientOptions(
tasksCmd
.command("reopen")
.description("Reopen a completed, cancelled, or blocked task back to todo (or backlog)")
.argument("<id>", "Issue identifier or UUID")
.argument("[comment...]", "Optional reopen note")
.option("--status <status>", "Target status (todo or backlog; default: todo)")
.option("--comment <text>", "Reopen note")
.option("-m, --message <text>", "Alias for --comment")
.action(async (id: string, commentParts: string[], opts: TasksReopenOptions) => {
try {
const resolved = resolveBoardClient(opts);
const positional = commentParts.length > 0 ? commentParts.join(" ") : undefined;
const comment = opts.comment ?? opts.message ?? positional;
let status: "todo" | "backlog" | undefined;
if (opts.status) {
const s = opts.status.trim().toLowerCase();
if (s !== "todo" && s !== "backlog") {
throw new Error(`Invalid reopen status "${opts.status}": expected todo or backlog`);
}
status = s;
}
const updated = await resolved.client.tasks.reopen(id, {
...(status ? { status } : {}),
...(comment !== undefined ? { comment } : {}),
});
if (resolved.json) {
console.log(JSON.stringify(updated, null, 2));
return;
}
if (isScriptOutput(resolved)) {
console.log(updated.identifier);
return;
}
console.log(
`${pc.green("Reopened")} ${pc.cyan(updated.identifier)} (status=${updated.status}, ${updated.cursor})`,
);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
const depsCmd = tasksCmd
.command("deps")
.description("Inspect or modify task dependencies (blocked_by / blocks)");
addBoardClientOptions(
depsCmd
.command("list")
.description("List blockers and dependents for a task")
.argument("<id>", "Issue identifier or UUID")
.action(async (id: string, opts: BoardCommonOptions) => {
try {
const resolved = resolveBoardClient(opts);
const deps = await resolved.client.tasks.dependencies(id);
if (resolved.json) {
console.log(JSON.stringify(deps, null, 2));
return;
}
formatDependencies(deps);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
addBoardClientOptions(
depsCmd
.command("add")
.description("Add one or more prerequisite blockers (--needs) to a task")
.argument("<id>", "Issue identifier or UUID")
.argument("[needs...]", "Blocker issue identifier(s) or UUID(s)")
.option("--needs <id>", "Blocker issue ID/identifier (repeatable or comma-separated)", collectOption, [])
.option("--release", "Release any active lease so the task waits in todo until blockers finish")
.option("--comment <text>", "Optional note")
.option("-m, --message <text>", "Alias for --comment")
.action(async (id: string, needsArgs: string[], opts: TasksDepsMutateOptions) => {
try {
const resolved = resolveBoardClient(opts);
const add = [...splitCsvValues(opts.needs), ...splitCsvValues(needsArgs)];
if (add.length === 0) {
throw new Error("Specify at least one blocker via positional <needs...> or --needs <id>.");
}
const companyId = await resolved.resolveCompanyId();
const claim = opts.release
? resolveClaimCredentials({
companyId,
issueRef: id,
activeProfile: resolved.profile,
requireClaim: false,
})
: undefined;
const comment = opts.comment ?? opts.message;
const deps = await resolved.client.tasks.updateDependencies(id, {
add,
...(opts.release ? { releaseLease: true } : {}),
...(claim ? { claimToken: claim.claimToken } : {}),
...(claim?.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}),
...(comment !== undefined ? { comment } : {}),
});
if (claim && opts.release) {
deleteClaimRecord(companyId, id);
}
if (resolved.json) {
console.log(JSON.stringify(deps, null, 2));
return;
}
formatDependencies(deps);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
addBoardClientOptions(
depsCmd
.command("remove")
.description("Remove one or more prerequisite blockers from a task")
.argument("<id>", "Issue identifier or UUID")
.argument("[needs...]", "Blocker issue identifier(s) or UUID(s) to remove")
.option("--needs <id>", "Blocker issue ID/identifier to remove (repeatable or comma-separated)", collectOption, [])
.action(async (id: string, needsArgs: string[], opts: TasksDepsMutateOptions) => {
try {
const resolved = resolveBoardClient(opts);
const remove = [...splitCsvValues(opts.needs), ...splitCsvValues(needsArgs)];
if (remove.length === 0) {
throw new Error("Specify at least one blocker to remove.");
}
const deps = await resolved.client.tasks.updateDependencies(id, { remove });
if (resolved.json) {
console.log(JSON.stringify(deps, null, 2));
return;
}
formatDependencies(deps);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
}
+92 -6
View File
@@ -4,14 +4,19 @@ import type { Command } from "commander";
import { ISSUE_PRIORITIES, type IssuePriority, type IssueStatus } from "@paperclipai/shared";
import {
CHANNEL_PATH_REGEX,
CLAIMABLE_TASK_STATUSES,
parseDurationMs,
PaperclipError,
TASK_CLAIM_ASSIGNEE_MODES,
type BatchCreateIssuesResult,
type ClaimableTaskStatus,
type HeadlessIssueView,
type PlanTaskInput,
type TaskClaimAssigneeMode,
type TaskClaimView,
type ThreadDetailView,
} from "@paperclipai/shared/sdk";
import { registerTaskWorkflowCommands } from "./tasks-workflows.js";
import {
addBoardClientOptions,
collectOption,
@@ -65,6 +70,9 @@ interface TasksClaimOptions extends BoardCommonOptions {
channel?: string;
label?: string[];
project?: string;
status?: string[];
assignee?: string;
mine?: boolean;
lease?: string;
wait?: string;
includeUntrusted?: boolean;
@@ -82,6 +90,10 @@ interface TasksRenewOptions extends BoardCommonOptions {
interface TasksReleaseOptions extends BoardCommonOptions {
comment?: string;
message?: string;
channel?: string;
label?: string[];
unset?: string[];
status?: string;
}
interface TasksCompleteOptions extends BoardCommonOptions {
@@ -102,6 +114,7 @@ interface TasksFailOptions extends BoardCommonOptions {
interface TasksBlockOptions extends BoardCommonOptions {
reason?: string;
message?: string;
needs?: string[];
}
function isIssueRef(value: string): boolean {
@@ -224,18 +237,39 @@ async function performClaim(
throw new Error("Pass either a specific task <id> or --ready/--channel, not both.");
}
const claimStatuses = splitCsvValues(opts.status);
for (const s of claimStatuses) {
if (!CLAIMABLE_TASK_STATUSES.includes(s as ClaimableTaskStatus)) {
throw new Error(
`Invalid claim --status "${s}": expected one of ${CLAIMABLE_TASK_STATUSES.join(", ")}`,
);
}
}
const rawAssignee = opts.mine ? "me" : opts.assignee?.trim().toLowerCase();
if (
rawAssignee !== undefined &&
!TASK_CLAIM_ASSIGNEE_MODES.includes(rawAssignee as TaskClaimAssigneeMode)
) {
throw new Error(
`Invalid --assignee "${opts.assignee}": expected one of ${TASK_CLAIM_ASSIGNEE_MODES.join(", ")}`,
);
}
const claim = await resolved.client.tasks.claim(
id ?? {
ready: true,
...(readyChannel ? { channel: readyChannel } : {}),
...(opts.project ? { projectId: opts.project } : {}),
...(opts.label && opts.label.length > 0 ? { label: opts.label } : {}),
...(claimStatuses.length > 0 ? { statuses: claimStatuses as ClaimableTaskStatus[] } : {}),
...(rawAssignee ? { assignee: rawAssignee as TaskClaimAssigneeMode } : {}),
...(opts.lease ? { lease: opts.lease } : {}),
...(opts.wait ? { wait: opts.wait } : {}),
...(opts.includeUntrusted ? { includeUntrusted: true } : {}),
},
id
? {
...(claimStatuses.length > 0 ? { statuses: claimStatuses as ClaimableTaskStatus[] } : {}),
...(opts.lease ? { lease: opts.lease } : {}),
...(opts.wait ? { wait: opts.wait } : {}),
}
@@ -814,6 +848,9 @@ export function registerBoardTaskCommands(program: Command): void {
.option("--channel <channel>", "Channel or prefix/ queue to claim from (implies --ready)")
.option("--label <expr>", "Filter by label expression (repeatable)", collectOption, [])
.option("--project <id-or-slug>", "Filter by project ID or slug")
.option("--status <status>", "Claimable status filter (todo, backlog, in_review; repeatable)", collectOption, [])
.option("--assignee <mode>", "Assignee filter (unassigned, me, any; default: unassigned)")
.option("--mine", "Shorthand for --assignee me (claim tasks assigned to you)")
.option("--lease <dur>", "Lease duration (e.g. 5m, 60s)")
.option("--wait <dur>", "Wait up to duration if queue is empty (e.g. 10m, 5s)")
.option("--include-untrusted", "Include tasks marked untrusted on wildcard --ready claims")
@@ -874,6 +911,9 @@ export function registerBoardTaskCommands(program: Command): void {
.option("--channel <channel>", "Channel or prefix/ queue to claim from (implies --ready)")
.option("--label <expr>", "Filter by label expression (repeatable)", collectOption, [])
.option("--project <id-or-slug>", "Filter by project ID or slug")
.option("--status <status>", "Claimable status filter (todo, backlog, in_review; repeatable)", collectOption, [])
.option("--assignee <mode>", "Assignee filter (unassigned, me, any; default: unassigned)")
.option("--mine", "Shorthand for --assignee me (claim tasks assigned to you)")
.option("--lease <dur>", "Lease duration (e.g. 5m, 60s)")
.option("--wait <dur>", "Wait up to duration if queue is empty (e.g. 10m, 5s)")
.option("--result <text>", "Completion message when command exits 0 without settling itself")
@@ -957,6 +997,10 @@ export function registerBoardTaskCommands(program: Command): void {
.argument("[comment...]", "Optional release note")
.option("--comment <text>", "Optional release note")
.option("-m, --message <text>", "Alias for --comment")
.option("--channel <path>", "Atomically move task to another channel on release")
.option("--label <k=v>", "Atomically set key=value label(s) on release (repeatable)", collectOption, [])
.option("--unset <key>", "Atomically unset label key(s) on release (repeatable)", collectOption, [])
.option("--status <status>", "Target status on release (todo, backlog, in_review; default: todo)")
.action(async (id: string, commentParts: string[], opts: TasksReleaseOptions) => {
try {
const resolved = resolveBoardClient(opts);
@@ -969,6 +1013,17 @@ export function registerBoardTaskCommands(program: Command): void {
})!;
const positional = commentParts.length > 0 ? commentParts.join(" ") : undefined;
const comment = opts.comment ?? opts.message ?? positional;
const { kvLabels } = parseLabelsList(opts.label);
let targetStatus: ClaimableTaskStatus | undefined;
if (opts.status) {
const s = opts.status.trim().toLowerCase();
if (!CLAIMABLE_TASK_STATUSES.includes(s as ClaimableTaskStatus)) {
throw new Error(
`Invalid --status "${opts.status}": expected one of ${CLAIMABLE_TASK_STATUSES.join(", ")}`,
);
}
targetStatus = s as ClaimableTaskStatus;
}
const result = await resolved.requestJson<{ released: boolean; cursor: string }>(
`/api/issues/${encodeURIComponent(id)}/claim/release`,
{
@@ -978,6 +1033,10 @@ export function registerBoardTaskCommands(program: Command): void {
claimToken: claim.claimToken,
...(claim.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}),
...(comment !== undefined ? { comment } : {}),
...(opts.channel ? { channel: opts.channel } : {}),
...(Object.keys(kvLabels).length > 0 ? { labels: kvLabels } : {}),
...(opts.unset && opts.unset.length > 0 ? { unsetLabels: opts.unset } : {}),
...(targetStatus ? { status: targetStatus } : {}),
}),
},
);
@@ -986,7 +1045,9 @@ export function registerBoardTaskCommands(program: Command): void {
console.log(JSON.stringify(result, null, 2));
return;
}
console.log(`${pc.yellow("Released")} ${pc.cyan(id)} back to todo (${result.cursor})`);
console.log(
`${pc.yellow("Released")} ${pc.cyan(id)} back to ${targetStatus ?? "todo"} (${result.cursor})`,
);
} catch (err) {
handleBoardError(err, opts);
}
@@ -1118,18 +1179,20 @@ export function registerBoardTaskCommands(program: Command): void {
addBoardClientOptions(
tasksCmd
.command("block")
.description("Mark a task as blocked with a reason (releasing any active pool lease)")
.description("Mark a task as blocked with a reason, or park it waiting on --needs dependencies")
.argument("<id>", "Issue identifier or UUID")
.argument("[reason...]", "Blocking reason")
.option("--reason <text>", "Blocking reason")
.option("-m, --message <text>", "Alias for --reason")
.option("--needs <id>", "Add blocker dependency ID/identifier and release lease to wait in todo (repeatable)", collectOption, [])
.action(async (id: string, reasonParts: string[], opts: TasksBlockOptions) => {
try {
const resolved = resolveBoardClient(opts);
const positional = reasonParts.length > 0 ? reasonParts.join(" ") : undefined;
const reason = (opts.reason ?? opts.message ?? positional)?.trim();
if (!reason) {
throw new Error("Specify a blocking reason via positional <reason> or --reason <text>.");
const needs = splitCsvValues(opts.needs);
if (!reason && needs.length === 0) {
throw new Error("Specify a blocking reason or at least one --needs <id> dependency.");
}
const companyId = await resolved.resolveCompanyId();
const claim = resolveClaimCredentials({
@@ -1139,6 +1202,27 @@ export function registerBoardTaskCommands(program: Command): void {
requireClaim: false,
});
if (needs.length > 0) {
const deps = await resolved.client.tasks.updateDependencies(id, {
add: needs,
releaseLease: true,
...(claim ? { claimToken: claim.claimToken } : {}),
...(claim?.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}),
...(reason ? { comment: reason } : {}),
});
if (claim) {
deleteClaimRecord(companyId, id);
}
if (resolved.json) {
console.log(JSON.stringify(deps, null, 2));
return;
}
console.log(
`${pc.yellow("Waiting")} ${pc.cyan(deps.identifier)} on ${needs.join(", ")} (${deps.cursor})`,
);
return;
}
let updated: HeadlessIssueView;
if (claim) {
updated = await resolved.requestJson<HeadlessIssueView>(
@@ -1149,7 +1233,7 @@ export function registerBoardTaskCommands(program: Command): void {
body: JSON.stringify({
claimToken: claim.claimToken,
...(claim.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}),
reason,
reason: reason!,
requeue: false,
}),
},
@@ -1163,7 +1247,7 @@ export function registerBoardTaskCommands(program: Command): void {
body: JSON.stringify({ status: "blocked" }),
},
);
await resolved.client.reply(id, reason);
await resolved.client.reply(id, reason!);
}
if (resolved.json) {
@@ -1202,4 +1286,6 @@ export function registerBoardTaskCommands(program: Command): void {
}
}),
);
registerTaskWorkflowCommands(tasksCmd);
}
+21 -3
View File
@@ -108,18 +108,36 @@ Lists headless tasks/issues (when `headless=1`, `channel`, `ready`, `after`, `as
Claims either an explicit `issueId` or the next ready unblocked task from the pool via `FOR UPDATE SKIP LOCKED`, issuing a single-use `claimToken` (`claimTokenHash` stored at rest) and bumping `claimEpoch`. Supports long-poll `?wait` / `waitSec` on event wakeups.
- **Filters**: Defaults to `status = ["todo"]` and `assignee = "unassigned"`. Callers may opt into `status` / `statuses` (`"todo" | "backlog" | "in_review"`; `in_review` automatically excludes tasks with pending `issue_thread_interactions`) and `assignee` (`"unassigned" | "me" | "any"`; `"me"`/`"any"` only ever matches the caller's own `agentId`/`userId` and never steals another principal's assigned task).
- **Gates**: `tasks.claim` scope, non-viewer member, canonical `issueReadSqlCondition`, channel access & queue eligibility (`allowedRoles`, `allowedAgentIds`), active subtree pause holds (`409 issue_paused`), paused projects (`projects.paused_at` -> `409 project_paused`), and `sourceTrust` filtering unless `includeUntrusted: true`.
- **Response (`200` claimed, `204` timeout on empty pool)**: `{ task, claimToken, claimEpoch, leaseExpiresAt, channel }`.
- **Response (`200` claimed, `204` timeout on empty pool)**: `{ issue, claimToken, claimEpoch, leaseExpiresAt, cursor }`.
### Claim Lifecycle (`POST /api/issues/:id/claim/...`)
Requires `claimToken` (body `claimToken` or `X-Paperclip-Claim-Token` header) and optional matching `claimEpoch` (`409 claim_lost` on mismatch, expiration, or non-`in_progress` state):
- `POST /api/issues/:id/claim/renew`: Extends `claimLeaseExpiresAt` up to channel `maxLeaseSec` and emits `task.lease_renewed`.
- `POST /api/issues/:id/claim/release`: Returns task to `todo`, clears holder/token, bumps `claimEpoch`, emits `task.lease_released` + `task.ready`.
- `POST /api/issues/:id/claim/complete`: Validates required `resultSchemaRef` against `blocks`/`schema` (`422 result_schema_validation_failed`), marks `done`, clears lease fields, acquires dependent issue locks before advisory event locks, and emits `task.completed` plus `task.unblocked`/`task.ready` for unblocked DAG dependents.
- `POST /api/issues/:id/claim/release`: Returns task to `todo` (or optional `status`: `todo | backlog | in_review`), optionally moves `channel` and updates `labels`/`unsetLabels` atomically, clears holder/token, bumps `claimEpoch`, emits `task.lease_released` (+ `task.ready` when `todo`), and triggers managed-pool dispatch.
- `POST /api/issues/:id/claim/complete`: Validates required `resultSchemaRef` against `blocks`/`schema` (`422 result_schema_validation_failed`), marks `done`, clears lease fields, acquires dependent issue locks before advisory event locks, emits `task.completed` plus `task.unblocked`/`task.ready` for unblocked DAG dependents, and triggers managed-pool dispatch.
- `POST /api/issues/:id/claim/fail`: Fails the claim (`reason`). Requeues up to channel `maxClaimAttempts` unless `requeue: false`; moves to `blocked` and emits `task.lease_poison_blocked` when exhausted.
### Task Workflows (`assign`, `handoff`, `cancel`, `reopen`, `dependencies`)
- `POST /api/issues/:id/assign`: Push-assigns an existing issue or passive channel post (`{ assignee?, assigneeAgentId?, unassign?, keepStatus?, force?, comment? }`). Promotes `backlog` -> `todo` automatically unless `keepStatus: true`, wakes the assigned agent via `heartbeat.wakeup`, and rejects `409 task_claimed` if another worker holds an active lease unless `force: true` (which bumps `claimEpoch` to fence the old worker). Emits `task.assigned` (and `task.ready` when unassigned into `todo`).
- `POST /api/issues/:id/handoff`: Atomically moves `channel`, mutates `labels`/`unsetLabels` with optional CAS `ifLabels` (`409 label_conflict`), updates `status` (`todo | backlog | in_review`), `assignee`/`unassign`, `priority`, and `resultSchema`, posts an optional `comment`, and releases any active fenced lease (`409 claim_lost` on stale token/epoch) in one transaction. Emits `task.handed_off` (+ `task.ready` when unassigned `todo`) and triggers wakeup or managed-pool dispatch.
- `POST /api/issues/:id/cancel`: Marks an issue `cancelled` (`{ reason?, force?, claimToken?, claimEpoch? }`). Rejects `409 task_claimed` if another worker holds an active lease (unless `force: true`) and rejects `409 claim_lost` if stale claim credentials are supplied after lease expiry/completion. Emits `task.cancelled` and triggers managed-pool dispatch to fill freed capacity.
- `POST /api/issues/:id/reopen`: Reopens a `done`, `cancelled`, or `blocked` issue back to `todo` or `backlog` (`{ status?, comment? }`). Rejects `409 task_claimed` if leased. Emits `task.reopened` (+ `task.ready` when unassigned `todo`).
- `GET /api/issues/:id/dependencies`: Returns `{ issueId, identifier, status, blockedBy, blocks, cursor }`, filtering both lists to channels/issues readable by the caller.
- `POST /api/issues/:id/dependencies`: Atomically adds/removes `blocks` edges (`{ add?, remove?, releaseLease?, claimToken?, claimEpoch?, comment? }`) under a company dependency advisory lock, enforcing channel access on every referenced issue, rejecting cycles (`400 cyclic_dependencies`), and validating claim credentials (`409 claim_lost`) when `releaseLease: true` or claim credentials are supplied.
### Channel Administration (`PATCH /channels`, `/channels/members`)
Requires `channels.manage` scope plus channel-creator, company owner/admin, or instance-admin authorization (`403 channel_manage_denied` for ordinary channel members):
- `PATCH /api/companies/:companyId/channels`: Locks the channel row (`FOR UPDATE`) and updates supplied fields (`description`, `defaultProjectId`, `archived`, `queueConfig`, or `managedPool: { agent, maxConcurrency } | null`). When `managedPool` is configured, triggers event-driven `dispatchManagedChannelPool` (serialized by channel row lock) to assign up to `maxConcurrency` ready unassigned tasks and wake the pool agent.
- `GET /api/companies/:companyId/channels/members?channel=<path>`: Lists explicit `channel_access_members` (requires channel read access).
- `POST /api/companies/:companyId/channels/members` & `DELETE /api/companies/:companyId/channels/members`: Adds or revokes an agent (`agent: "@name"`) or user (`userId`) on a channel (requires `channels.manage` + creator/admin authorization).
### Interactions (`ask`, `confirm`, `approve`, `reject`)
- `POST /api/issues/:id/ask`: Creates a pending `ask_user_questions` interaction (`choices?`, `humanOnly?`, `requeueOnResolve?`). Requires valid active claim token if the issue currently has an active claim lease (`409 claim_lost`).
+44
View File
@@ -112,3 +112,47 @@ export const channelPostInputSchema = z
.strict();
export type ChannelPostInput = z.input<typeof channelPostInputSchema>;
export const updateChannelInputSchema = z
.object({
channel: exactChannelPathSchema.optional(),
description: z.string().max(1000).nullable().optional(),
defaultProjectId: z.string().min(1).nullable().optional(),
archived: z.boolean().optional(),
queueConfig: channelQueueConfigSchema.nullable().optional(),
managedPool: z
.union([
z
.object({
agent: z.string().min(1),
maxConcurrency: z.number().int().min(1).max(100).default(1),
})
.strict(),
z.null(),
])
.optional(),
})
.strict();
export type UpdateChannelInput = z.input<typeof updateChannelInputSchema>;
export const channelMemberInputSchema = z
.object({
channel: exactChannelPathSchema,
agent: z.string().min(1).optional(),
userId: z.string().min(1).optional(),
subjectType: z.enum(["user", "agent"]).optional(),
subjectId: z.string().min(1).optional(),
})
.strict();
export type ChannelMemberInput = z.input<typeof channelMemberInputSchema>;
export interface ChannelMemberView {
id: string;
channelId: string;
subjectType: "user" | "agent";
subjectId: string;
displayName: string | null;
createdAt: string;
}
+5
View File
@@ -17,6 +17,11 @@ export const BOARD_EVENT_TYPES = [
"task.failed",
"task.blocked",
"task.unblocked",
"task.assigned",
"task.handed_off",
"task.cancelled",
"task.reopened",
"task.dependencies_changed",
"labels.changed",
"interaction.created",
"interaction.resolved",
+110 -3
View File
@@ -1,10 +1,23 @@
import { z } from "zod";
import type { IssuePriority, IssueStatus } from "../constants.js";
import { ISSUE_PRIORITIES, type IssuePriority, type IssueStatus } from "../constants.js";
import type { IssueScope } from "./identity.js";
import { parseDurationMs } from "./pure.js";
import { writableKvLabelsRecordSchema } from "./labels.js";
import {
CLAIMABLE_TASK_STATUSES,
parseDurationMs,
TASK_CLAIM_ASSIGNEE_MODES,
type ClaimableTaskStatus,
type TaskClaimAssigneeMode,
} from "./pure.js";
import { SCHEMA_REF_REGEX, schemaBlockSchema, type SchemaBlock } from "./schemas.js";
export { parseDurationMs };
export {
CLAIMABLE_TASK_STATUSES,
parseDurationMs,
TASK_CLAIM_ASSIGNEE_MODES,
type ClaimableTaskStatus,
type TaskClaimAssigneeMode,
};
export const durationValueSchema = z
.union([z.number().finite().nonnegative(), z.string().min(1)])
@@ -27,6 +40,9 @@ export const TaskClaimRequestSchema = z
channel: z.string().min(1).optional(),
projectId: z.string().min(1).optional(),
labels: z.array(z.string().min(1)).optional(),
status: z.union([z.enum(CLAIMABLE_TASK_STATUSES), z.array(z.enum(CLAIMABLE_TASK_STATUSES))]).optional(),
statuses: z.array(z.enum(CLAIMABLE_TASK_STATUSES)).optional(),
assignee: z.enum(TASK_CLAIM_ASSIGNEE_MODES).optional(),
leaseSec: z.number().int().min(1).max(86400).optional(),
lease: z.union([z.number().finite().positive(), z.string().min(1)]).optional(),
waitSec: z.number().finite().nonnegative().optional(),
@@ -53,11 +69,102 @@ export const TaskReleaseSchema = z
claimToken: z.string().min(1).optional(),
claimEpoch: z.number().int().nonnegative().optional(),
comment: z.string().optional(),
status: z.enum(CLAIMABLE_TASK_STATUSES).optional(),
channel: z.string().min(1).optional(),
labels: writableKvLabelsRecordSchema.optional(),
unsetLabels: z.array(z.string().min(1)).optional(),
})
.strict();
export type TaskReleaseInput = z.input<typeof TaskReleaseSchema>;
export const TaskAssignSchema = z
.object({
assignee: z.string().min(1).nullable().optional(),
assigneeAgentId: z.string().uuid().nullable().optional(),
unassign: z.boolean().optional(),
keepStatus: z.boolean().optional(),
force: z.boolean().optional(),
comment: z.string().optional(),
})
.strict();
export type TaskAssignInput = z.input<typeof TaskAssignSchema>;
export const TaskHandoffSchema = z
.object({
claimToken: z.string().min(1).optional(),
claimEpoch: z.number().int().nonnegative().optional(),
channel: z.string().min(1).optional(),
status: z.enum(CLAIMABLE_TASK_STATUSES).optional(),
labels: writableKvLabelsRecordSchema.optional(),
unsetLabels: z.array(z.string().min(1)).optional(),
ifLabels: z.record(z.string().min(1), z.string().nullable()).optional(),
assignee: z.string().min(1).nullable().optional(),
unassign: z.boolean().optional(),
priority: z.enum(ISSUE_PRIORITIES).optional(),
resultSchema: z
.string()
.refine((v) => SCHEMA_REF_REGEX.test(v.trim()), {
message: "Invalid resultSchema ref",
})
.nullable()
.optional(),
comment: z.string().optional(),
})
.strict();
export type TaskHandoffInput = z.input<typeof TaskHandoffSchema>;
export const TaskCancelSchema = z
.object({
claimToken: z.string().min(1).optional(),
claimEpoch: z.number().int().nonnegative().optional(),
reason: z.string().optional(),
force: z.boolean().optional(),
})
.strict();
export type TaskCancelInput = z.input<typeof TaskCancelSchema>;
export const TaskReopenSchema = z
.object({
status: z.enum(["todo", "backlog"]).optional(),
comment: z.string().optional(),
})
.strict();
export type TaskReopenInput = z.input<typeof TaskReopenSchema>;
export const TaskDependenciesMutationSchema = z
.object({
add: z.array(z.string().min(1)).max(50).optional(),
remove: z.array(z.string().min(1)).max(50).optional(),
releaseLease: z.boolean().optional(),
claimToken: z.string().min(1).optional(),
claimEpoch: z.number().int().nonnegative().optional(),
comment: z.string().optional(),
})
.strict();
export type TaskDependenciesMutationInput = z.input<typeof TaskDependenciesMutationSchema>;
export interface TaskDependencyItemView {
id: string;
identifier: string;
title: string;
status: IssueStatus;
}
export interface TaskDependenciesView {
issueId: string;
identifier: string;
status: IssueStatus;
blockedBy: TaskDependencyItemView[];
blocks: TaskDependencyItemView[];
cursor: string;
}
export const TaskCompleteSchema = z
.object({
claimToken: z.string().min(1).optional(),
+6
View File
@@ -1,5 +1,11 @@
export const CHANNEL_PATH_REGEX = /^[a-z0-9][a-z0-9_-]*(\/[a-z0-9][a-z0-9_-]*)*$/;
export const CLAIMABLE_TASK_STATUSES = ["todo", "backlog", "in_review"] as const;
export type ClaimableTaskStatus = (typeof CLAIMABLE_TASK_STATUSES)[number];
export const TASK_CLAIM_ASSIGNEE_MODES = ["unassigned", "me", "any"] as const;
export type TaskClaimAssigneeMode = (typeof TASK_CLAIM_ASSIGNEE_MODES)[number];
export interface NormalizedChannelPath {
path: string;
isSubtreePrefix: boolean;
+166 -2
View File
@@ -2,6 +2,7 @@ import { parseDurationMs, parseSchemaRef } from "../headless/pure.js";
import type {
BatchCreateIssuesResult,
BoardEventView,
ChannelMemberView,
ChannelPage,
ChannelView,
ClientScopes,
@@ -19,8 +20,12 @@ import type {
SchemaBlock,
SchedulePostInput,
ScheduleView,
TaskAssignInput,
TaskCancelInput,
TaskClaimView,
TaskCompleteInput,
TaskDependenciesView,
TaskReleaseInput,
ThreadDetailView,
WhoAmIView,
} from "../headless/index.js";
@@ -317,21 +322,42 @@ function createHandle(state: InternalClientState): PaperclipHandle {
return view;
},
async release(comment) {
async release(commentOrOpts) {
const payload: Omit<TaskReleaseInput, "claimToken" | "claimEpoch"> =
typeof commentOrOpts === "string"
? { comment: commentOrOpts }
: { ...(commentOrOpts ?? {}) };
return requestJson<{ released: boolean; cursor: string }>(
`/api/issues/${encodeURIComponent(currentTask.id)}/claim/release`,
{
method: "POST",
headers: { "x-paperclip-claim-token": currentClaimToken },
body: JSON.stringify({
...payload,
claimToken: currentClaimToken,
claimEpoch: currentClaimEpoch,
...(comment !== undefined ? { comment } : {}),
}),
},
);
},
async handoff(opts) {
const updated = await requestJson<HeadlessIssueView>(
`/api/issues/${encodeURIComponent(currentTask.id)}/handoff`,
{
method: "POST",
headers: { "x-paperclip-claim-token": currentClaimToken },
body: JSON.stringify({
...opts,
claimToken: currentClaimToken,
claimEpoch: currentClaimEpoch,
}),
},
);
currentTask = updated;
return updated;
},
async complete(opts) {
const payload: TaskCompleteInput =
typeof opts === "string"
@@ -454,6 +480,59 @@ function createHandle(state: InternalClientState): PaperclipHandle {
async ensure(path, opts) {
return this.create(path, opts);
},
async update(path, opts) {
const companyId = await resolveCompanyId();
return requestJson<ChannelView>(
`/api/companies/${encodeURIComponent(companyId)}/channels`,
{
method: "PATCH",
body: JSON.stringify({
...(opts ?? {}),
channel: path,
}),
},
);
},
members: {
async list(channel) {
const companyId = await resolveCompanyId();
const res = await requestJson<{ items: ChannelMemberView[] }>(
`/api/companies/${encodeURIComponent(companyId)}/channels/members?channel=${encodeURIComponent(channel)}`,
{ method: "GET" },
);
return res.items;
},
async add(channel, member) {
const companyId = await resolveCompanyId();
return requestJson<ChannelMemberView>(
`/api/companies/${encodeURIComponent(companyId)}/channels/members`,
{
method: "POST",
body: JSON.stringify({
...member,
channel,
}),
},
);
},
async remove(channel, member) {
const companyId = await resolveCompanyId();
return requestJson<{ removed: boolean }>(
`/api/companies/${encodeURIComponent(companyId)}/channels/members`,
{
method: "DELETE",
body: JSON.stringify({
...member,
channel,
}),
},
);
},
},
},
async post(channel, bodyOrOpts, maybeOpts) {
@@ -718,11 +797,22 @@ function createHandle(state: InternalClientState): PaperclipHandle {
? Math.max(0, parseDurationMs(opts.wait) / 1000)
: undefined);
const statuses = [
...(opts.statuses ?? []),
...(opts.status
? Array.isArray(opts.status)
? opts.status
: [opts.status]
: []),
];
const body: Record<string, unknown> = {
...(isId ? { issueId: idOrReadyQuery } : { ready: opts.ready ?? true }),
...(opts.channel ? { channel: opts.channel } : {}),
...(opts.projectId ? { projectId: opts.projectId } : {}),
...(labels.length > 0 ? { labels } : {}),
...(statuses.length > 0 ? { statuses } : {}),
...(opts.assignee ? { assignee: opts.assignee } : {}),
...(leaseSec !== undefined ? { leaseSec } : {}),
...(waitSec !== undefined ? { waitSec } : {}),
...(opts.includeUntrusted !== undefined
@@ -744,6 +834,80 @@ function createHandle(state: InternalClientState): PaperclipHandle {
const claimView = (await res.json()) as TaskClaimView;
return buildClaimedTask(claimView);
},
async assign(id, assigneeOrOpts, maybeOpts) {
const payload: TaskAssignInput =
typeof assigneeOrOpts === "string" || assigneeOrOpts === null
? { ...(maybeOpts ?? {}), assignee: assigneeOrOpts }
: assigneeOrOpts;
return requestJson<HeadlessIssueView>(
`/api/issues/${encodeURIComponent(id)}/assign`,
{
method: "POST",
body: JSON.stringify(payload),
},
);
},
async handoff(id, opts) {
return requestJson<HeadlessIssueView>(
`/api/issues/${encodeURIComponent(id)}/handoff`,
{
method: "POST",
headers: opts.claimToken
? { "x-paperclip-claim-token": opts.claimToken }
: undefined,
body: JSON.stringify(opts),
},
);
},
async cancel(id, reasonOrOpts) {
const payload: TaskCancelInput =
typeof reasonOrOpts === "string"
? { reason: reasonOrOpts }
: { ...(reasonOrOpts ?? {}) };
return requestJson<HeadlessIssueView>(
`/api/issues/${encodeURIComponent(id)}/cancel`,
{
method: "POST",
headers: payload.claimToken
? { "x-paperclip-claim-token": payload.claimToken }
: undefined,
body: JSON.stringify(payload),
},
);
},
async reopen(id, opts) {
return requestJson<HeadlessIssueView>(
`/api/issues/${encodeURIComponent(id)}/reopen`,
{
method: "POST",
body: JSON.stringify(opts ?? {}),
},
);
},
async dependencies(id) {
return requestJson<TaskDependenciesView>(
`/api/issues/${encodeURIComponent(id)}/dependencies`,
{ method: "GET" },
);
},
async updateDependencies(id, mutation) {
return requestJson<TaskDependenciesView>(
`/api/issues/${encodeURIComponent(id)}/dependencies`,
{
method: "POST",
headers: mutation.claimToken
? { "x-paperclip-claim-token": mutation.claimToken }
: undefined,
body: JSON.stringify(mutation),
},
);
},
},
async ask(id, question, opts) {
+14
View File
@@ -18,6 +18,7 @@ export {
export { parseSseEventStream } from "./sse.js";
export {
CHANNEL_PATH_REGEX,
CLAIMABLE_TASK_STATUSES,
formatEventCursor,
normalizeChannelPath,
parseDurationMs,
@@ -26,8 +27,11 @@ export {
SCHEMA_NAME_REGEX,
SCHEMA_REF_REGEX,
splitMessageIntoTitleAndDescription,
TASK_CLAIM_ASSIGNEE_MODES,
type ClaimableTaskStatus,
type NormalizedChannelPath,
type ParsedSchemaRef,
type TaskClaimAssigneeMode,
} from "../headless/pure.js";
export type {
AgentIdentityPolicy,
@@ -36,6 +40,8 @@ export type {
BoardEventActor,
BoardEventType,
BoardEventView,
ChannelMemberInput,
ChannelMemberView,
ChannelOrdering,
ChannelPage,
ChannelPostInput,
@@ -62,12 +68,20 @@ export type {
SchemaBlock,
SchedulePostInput,
ScheduleView,
TaskAssignInput,
TaskCancelInput,
TaskClaimRequest,
TaskClaimView,
TaskCompleteInput,
TaskDependenciesMutationInput,
TaskDependenciesView,
TaskDependencyItemView,
TaskFailInput,
TaskHandoffInput,
TaskReleaseInput,
TaskRenewInput,
TaskReopenInput,
ThreadDetailView,
UpdateChannelInput,
WhoAmIView,
} from "../headless/index.js";
+58 -1
View File
@@ -3,9 +3,12 @@ import type {
BoardEventType,
BoardEventView,
BatchCreateIssuesResult,
ChannelMemberInput,
ChannelMemberView,
ChannelPage,
ChannelPostInput,
ChannelView,
ClaimableTaskStatus,
ClientScopes,
CommentView,
CompanySchemaView,
@@ -20,9 +23,18 @@ import type {
SchemaBlock,
SchedulePostInput,
ScheduleView,
TaskAssignInput,
TaskCancelInput,
TaskClaimAssigneeMode,
TaskClaimView,
TaskCompleteInput,
TaskDependenciesMutationInput,
TaskDependenciesView,
TaskHandoffInput,
TaskReleaseInput,
TaskReopenInput,
ThreadDetailView,
UpdateChannelInput,
WhoAmIView,
} from "../headless/index.js";
@@ -120,6 +132,9 @@ export interface TaskClaimOptions {
projectId?: string;
label?: string | string[];
labels?: string[];
status?: ClaimableTaskStatus | ClaimableTaskStatus[];
statuses?: ClaimableTaskStatus[];
assignee?: TaskClaimAssigneeMode;
lease?: string | number;
leaseSec?: number;
wait?: string | number;
@@ -163,7 +178,12 @@ export interface ClaimedTask {
leaseExpiresAt: string;
cursor: string;
renew(lease?: string | number): Promise<TaskClaimView>;
release(comment?: string): Promise<{ released: boolean; cursor: string }>;
release(
commentOrOpts?: string | Omit<TaskReleaseInput, "claimToken" | "claimEpoch">,
): Promise<{ released: boolean; cursor: string }>;
handoff(
opts: Omit<TaskHandoffInput, "claimToken" | "claimEpoch">,
): Promise<HeadlessIssueView>;
complete(
opts?: string | Omit<TaskCompleteInput, "claimToken" | "claimEpoch">,
): Promise<HeadlessIssueView>;
@@ -194,6 +214,21 @@ export interface PaperclipHandle {
path: string,
opts?: Omit<CreateChannelInput, "path">,
): Promise<ChannelView>;
update(
path: string,
opts: Omit<UpdateChannelInput, "channel">,
): Promise<ChannelView>;
members: {
list(channel: string): Promise<ChannelMemberView[]>;
add(
channel: string,
member: Omit<ChannelMemberInput, "channel">,
): Promise<ChannelMemberView>;
remove(
channel: string,
member: Omit<ChannelMemberInput, "channel">,
): Promise<{ removed: boolean }>;
};
};
post(
channel: string,
@@ -235,6 +270,28 @@ export interface PaperclipHandle {
idOrReadyQuery?: string | TaskClaimOptions,
opts?: TaskClaimOptions,
): Promise<ClaimedTask | null>;
assign(
id: string,
assigneeOrOpts: string | null | TaskAssignInput,
maybeOpts?: Omit<TaskAssignInput, "assignee">,
): Promise<HeadlessIssueView>;
handoff(
id: string,
opts: TaskHandoffInput,
): Promise<HeadlessIssueView>;
cancel(
id: string,
reasonOrOpts?: string | TaskCancelInput,
): Promise<HeadlessIssueView>;
reopen(
id: string,
opts?: TaskReopenInput,
): Promise<HeadlessIssueView>;
dependencies(id: string): Promise<TaskDependenciesView>;
updateDependencies(
id: string,
mutation: TaskDependenciesMutationInput,
): Promise<TaskDependenciesView>;
};
ask(
id: string,
@@ -0,0 +1,570 @@
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" });
});
});
+5
View File
@@ -136,6 +136,7 @@ import { headlessIdentityRoutes } from "./routes/headless-identity.js";
import { headlessChannelsSchemasRoutes } from "./routes/headless-channels-schemas.js";
import { headlessQueuesEventsRoutes } from "./routes/headless-queues-events.js";
import { createClaimLeaseExpiryWorker } from "./services/headless-task-queue.js";
import { createManagedChannelPoolWorker } from "./services/headless-channel-admin.js";
import { createScheduledBoardPostsWorker } from "./services/headless-events-schedules-interactions.js";
import { linkPreviewRoutes } from "./routes/link-previews.js";
import { issueTreeControlRoutes } from "./routes/issue-tree-control.js";
@@ -1430,6 +1431,10 @@ export async function createApp(
registerBrowserUseCleanup(deliveryWork, browserUse, () => !isIdleTaskDrainActive());
deliveryWork.register(DELIVERY_QUEUES.claimLeaseExpiry, createClaimLeaseExpiryWorker(db).deliveryTask);
deliveryWork.register(DELIVERY_QUEUES.scheduledBoardPosts, createScheduledBoardPostsWorker(db).deliveryTask);
deliveryWork.register(
DELIVERY_QUEUES.managedChannelPools,
createManagedChannelPoolWorker(db, heartbeatService(db)).deliveryTask,
);
void companyTransferRunService
+150 -1
View File
@@ -46,6 +46,15 @@ import {
} from "@paperclipai/shared";
import { badRequest, conflict, forbidden, unprocessable } from "../errors.js";
import { authorizationService } from "../services/authorization.js";
import { heartbeatService } from "../services/heartbeat.js";
import {
addChannelMember,
dispatchManagedChannelPoolBestEffort,
dispatchManagedChannelPoolsForCompletedIssueBestEffort,
listChannelMembers,
removeChannelMember,
updateChannel,
} from "../services/headless-channel-admin.js";
import {
logActivity,
publishActivity,
@@ -195,10 +204,14 @@ function isRestrictedBoardKeyRequest(req: Request): boolean {
export function headlessChannelsSchemasRoutes(
db: Db,
opts?: { deploymentMode?: DeploymentMode },
opts?: {
deploymentMode?: DeploymentMode;
heartbeat?: ReturnType<typeof heartbeatService>;
},
): Router {
const router = Router();
const deploymentMode = opts?.deploymentMode;
const heartbeat = opts?.heartbeat ?? heartbeatService(db);
router.get(
"/companies/:companyId/channels",
@@ -256,6 +269,96 @@ export function headlessChannelsSchemasRoutes(
},
);
router.patch(
"/companies/:companyId/channels",
async (req: Request, res: Response) => {
const companyId = req.params.companyId as string;
const body = (req.body ?? {}) as Record<string, unknown>;
const channelRef =
typeof body.channel === "string" && body.channel.trim()
? body.channel.trim()
: typeof req.query.channel === "string" && req.query.channel.trim()
? req.query.channel.trim()
: "";
if (!channelRef) {
throw badRequest("Channel path or ID is required");
}
const actor = await resolveHeadlessActor(db, req, companyId, {
deploymentMode,
requiredAction: "channels.manage",
requiredChannel: channelRef,
});
const updated = await updateChannel(db, companyId, channelRef, actor, body, {
heartbeat,
});
res.json(updated);
},
);
router.get(
"/companies/:companyId/channels/members",
async (req: Request, res: Response) => {
const companyId = req.params.companyId as string;
const channelRef =
typeof req.query.channel === "string" ? req.query.channel.trim() : "";
if (!channelRef) {
throw badRequest("Query parameter 'channel' is required");
}
const actor = await resolveHeadlessActor(db, req, companyId, {
deploymentMode,
requiredAction: "read",
requiredChannel: channelRef,
});
const items = await listChannelMembers(db, companyId, channelRef, actor);
res.json({ items });
},
);
router.post(
"/companies/:companyId/channels/members",
async (req: Request, res: Response) => {
const companyId = req.params.companyId as string;
const body = (req.body ?? {}) as Record<string, unknown>;
const channelRef =
typeof body.channel === "string" ? body.channel.trim() : "";
const actor = await resolveHeadlessActor(db, req, companyId, {
deploymentMode,
requiredAction: "channels.manage",
...(channelRef ? { requiredChannel: channelRef } : {}),
});
const member = await addChannelMember(db, companyId, actor, body);
res.status(201).json(member);
},
);
router.delete(
"/companies/:companyId/channels/members",
async (req: Request, res: Response) => {
const companyId = req.params.companyId as string;
const body = (req.body && typeof req.body === "object"
? { ...(req.body as Record<string, unknown>) }
: {}) as Record<string, unknown>;
if (!body.channel && typeof req.query.channel === "string") {
body.channel = req.query.channel;
}
if (!body.agent && typeof req.query.agent === "string") {
body.agent = req.query.agent;
}
if (!body.userId && typeof req.query.userId === "string") {
body.userId = req.query.userId;
}
const channelRef =
typeof body.channel === "string" ? body.channel.trim() : "";
const actor = await resolveHeadlessActor(db, req, companyId, {
deploymentMode,
requiredAction: "channels.manage",
...(channelRef ? { requiredChannel: channelRef } : {}),
});
const result = await removeChannelMember(db, companyId, actor, body);
res.json(result);
},
);
router.post(
"/companies/:companyId/channels/posts",
async (req: Request, res: Response) => {
@@ -269,6 +372,18 @@ export function headlessChannelsSchemasRoutes(
});
const result = await createChannelPost(db, companyId, actor, body);
if (
result.created &&
result.issue.status === "todo" &&
!result.issue.assigneeAgentId &&
!result.issue.assigneeUserId &&
result.issue.channelId
) {
await dispatchManagedChannelPoolBestEffort(db, companyId, result.issue.channelId, {
heartbeat,
actor,
});
}
res.status(result.created ? 201 : 200).json(result.issue);
},
);
@@ -391,6 +506,21 @@ export function headlessChannelsSchemasRoutes(
actor,
req.body ?? {},
);
if (!result.idempotentReplay) {
const channelIds = Array.from(
new Set(
result.tasks
.map((t) => t.issue.channelId)
.filter((id): id is string => Boolean(id)),
),
);
for (const chId of channelIds) {
await dispatchManagedChannelPoolBestEffort(db, companyId, chId, {
heartbeat,
actor,
});
}
}
res.status(result.idempotentReplay ? 200 : 201).json(result);
},
);
@@ -1083,6 +1213,25 @@ export function headlessChannelsSchemasRoutes(
for (const evt of committedEvents) {
publishCommittedBoardEvent(evt);
}
if (nextStatus === "done") {
await dispatchManagedChannelPoolsForCompletedIssueBestEffort(
db,
targetIssue.companyId,
updatedView.id,
updatedView.channelId,
{ heartbeat, actor },
);
} else if (
updatedView.channelId &&
(nextStatus === "todo" || nextStatus === "cancelled" || nextStatus === "blocked")
) {
await dispatchManagedChannelPoolBestEffort(
db,
targetIssue.companyId,
updatedView.channelId,
{ heartbeat, actor },
);
}
res.json(updatedView);
},
+175 -1
View File
@@ -6,7 +6,8 @@ import {
type BoardEventView,
type DeploymentMode,
} from "@paperclipai/shared";
import { badRequest, notFound, unauthorized } from "../errors.js";
import { badRequest, forbidden, notFound, unauthorized } from "../errors.js";
import { authorizationDeniedDetails, authorizationService } from "../services/authorization.js";
import { heartbeatService } from "../services/heartbeat.js";
import {
assertCanonicalIssueAccess,
@@ -24,6 +25,20 @@ import {
releaseTaskClaim,
renewTaskClaim,
} from "../services/headless-task-queue.js";
import {
assignTask,
cancelTask,
handoffTask,
reopenTask,
} from "../services/headless-task-workflows.js";
import {
listTaskDependencies,
mutateTaskDependencies,
} from "../services/headless-task-dependencies.js";
import {
dispatchManagedChannelPoolBestEffort,
dispatchManagedChannelPoolsForCompletedIssueBestEffort,
} from "../services/headless-channel-admin.js";
import {
approveOnIssue,
cancelSchedule,
@@ -175,6 +190,41 @@ export function headlessQueuesEventsRoutes(
const deploymentMode = opts?.deploymentMode;
const heartbeat = opts?.heartbeat ?? heartbeatService(db);
async function assertCanAssignTask(
txOrDb: Db | Parameters<Parameters<Db["transaction"]>[0]>[0],
req: Request,
issue: Awaited<ReturnType<typeof resolveIssueByIdOrIdentifier>>,
targetAssigneeAgentId?: string | null,
) {
const effectiveAssigneeAgentId =
targetAssigneeAgentId !== undefined ? targetAssigneeAgentId : issue.assigneeAgentId;
const effectiveAssigneeUserId =
targetAssigneeAgentId !== undefined ? null : issue.assigneeUserId;
const decision = await authorizationService(txOrDb as unknown as Db).decide({
actor: req.actor,
action: "tasks:assign",
resource: {
type: "issue",
companyId: issue.companyId,
issueId: issue.id,
projectId: issue.projectId,
parentIssueId: issue.parentId,
assigneeAgentId: effectiveAssigneeAgentId,
assigneeUserId: effectiveAssigneeUserId,
},
scope: {
issueId: issue.id,
projectId: issue.projectId,
parentIssueId: issue.parentId,
assigneeAgentId: effectiveAssigneeAgentId,
assigneeUserId: effectiveAssigneeUserId,
},
});
if (!decision.allowed) {
throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
}
const buildWakeHandler = () => async (wake: {
companyId: string;
issueId: string;
@@ -278,6 +328,12 @@ export function headlessQueuesEventsRoutes(
req.body,
req.header("x-paperclip-claim-token") ?? undefined,
);
if (issue.channelId) {
await dispatchManagedChannelPoolBestEffort(db, issue.companyId, issue.channelId, {
heartbeat,
actor,
});
}
res.json(result);
});
@@ -296,6 +352,13 @@ export function headlessQueuesEventsRoutes(
req.body,
req.header("x-paperclip-claim-token") ?? undefined,
);
await dispatchManagedChannelPoolsForCompletedIssueBestEffort(
db,
issue.companyId,
result.id,
result.channelId,
{ heartbeat, actor },
);
res.json(result);
});
@@ -317,6 +380,117 @@ export function headlessQueuesEventsRoutes(
res.json(result);
});
router.post("/issues/:id/assign", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
req,
req.params.id as string,
deploymentMode,
"tasks.assign",
);
const result = await assignTask(db, issue.id, actor, req.body, {
heartbeat,
authorizeTargetAssignee: (tx, targetAgentId) =>
assertCanAssignTask(tx, req, issue, targetAgentId),
});
res.json(result);
});
router.post("/issues/:id/handoff", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
req,
req.params.id as string,
deploymentMode,
"tasks.handoff",
);
const result = await handoffTask(
db,
issue.id,
actor,
req.body,
req.header("x-paperclip-claim-token") ?? undefined,
{
heartbeat,
authorizeTargetAssignee: (tx, targetAgentId) =>
assertCanAssignTask(tx, req, issue, targetAgentId),
},
);
res.json(result);
});
router.post("/issues/:id/cancel", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
req,
req.params.id as string,
deploymentMode,
"tasks.cancel",
);
const result = await cancelTask(
db,
issue.id,
actor,
req.body,
req.header("x-paperclip-claim-token") ?? undefined,
);
if (result.channelId) {
await dispatchManagedChannelPoolBestEffort(db, issue.companyId, result.channelId, {
heartbeat,
actor,
});
}
res.json(result);
});
router.post("/issues/:id/reopen", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
req,
req.params.id as string,
deploymentMode,
"tasks.reopen",
);
if (issue.status === "done" || issue.status === "cancelled") {
await assertCanAssignTask(db, req, issue);
}
const result = await reopenTask(db, issue.id, actor, req.body, {
heartbeat,
});
res.json(result);
});
router.get("/issues/:id/dependencies", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
req,
req.params.id as string,
deploymentMode,
"read",
"issue:read",
);
const result = await listTaskDependencies(db, issue.id, actor);
res.json(result);
});
router.post("/issues/:id/dependencies", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
req,
req.params.id as string,
deploymentMode,
"tasks.dependencies",
);
const result = await mutateTaskDependencies(
db,
issue.id,
actor,
req.body,
req.header("x-paperclip-claim-token") ?? undefined,
);
res.json(result);
});
router.post("/issues/:id/ask", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
+60
View File
@@ -14732,6 +14732,66 @@ for (const route of [
agentIdentityPolicy: agentIdentityPolicySchema,
}),
},
{
method: "patch",
path: "/api/companies/{companyId}/channels",
summary: "Update channel settings, archive state, queueConfig, or managedPool",
status: 200,
},
{
method: "get",
path: "/api/companies/{companyId}/channels/members",
summary: "List explicit access members on a channel",
status: 200,
},
{
method: "post",
path: "/api/companies/{companyId}/channels/members",
summary: "Grant an agent or user access to a private channel",
status: 201,
},
{
method: "delete",
path: "/api/companies/{companyId}/channels/members",
summary: "Revoke an agent or user's access to a private channel",
status: 200,
},
{
method: "post",
path: "/api/issues/{id}/assign",
summary: "Push-assign an existing task or post to a registered agent or unassign it",
status: 200,
},
{
method: "post",
path: "/api/issues/{id}/handoff",
summary: "Atomically move channel, update labels/assignee/status, and release an active lease",
status: 200,
},
{
method: "post",
path: "/api/issues/{id}/cancel",
summary: "Cancel a task and release any active lease",
status: 200,
},
{
method: "post",
path: "/api/issues/{id}/reopen",
summary: "Reopen a completed, cancelled, or blocked task back to todo or backlog",
status: 200,
},
{
method: "get",
path: "/api/issues/{id}/dependencies",
summary: "List visible blockers and dependents for a task",
status: 200,
},
{
method: "post",
path: "/api/issues/{id}/dependencies",
summary: "Add or remove task dependencies with cycle checks and optional lease release",
status: 200,
},
] as const) {
registerCurrentRoute({
method: route.method,
+5
View File
@@ -72,6 +72,11 @@ export function createAgentLifecycleEffects(_hooks: BudgetServiceHooks = {}): li
await notifyChatInboundWakeNotices(tx, { companyId });
await notifyBudgetResumeAgentReady(tx, agentId);
await readmitAgentContinuations(tx, { companyId, agentId });
await notifyDeliveryWork(
tx,
DELIVERY_QUEUES.managedChannelPools,
JSON.stringify({ companyId, agentId }),
);
}
},
reportFailure(context, error) {
+1 -1
View File
@@ -364,7 +364,7 @@ type IssueAuthorizationRow = {
originId: string | null;
};
function evaluateAuthorizationPolicyForAssignment(
export function evaluateAuthorizationPolicyForAssignment(
policy: Record<string, unknown> | null | undefined,
label: string,
): AssignmentPolicyEffect {
@@ -167,6 +167,7 @@ export const DELIVERY_QUEUES = {
nativeCheckpointExpiration: "native-checkpoint-expiration",
claimLeaseExpiry: "claim-lease-expiry",
scheduledBoardPosts: "scheduled-board-posts",
managedChannelPools: "managed-channel-pools",
} as const;
export type DeliveryQueue = typeof DELIVERY_QUEUES[keyof typeof DELIVERY_QUEUES];
@@ -0,0 +1,586 @@
import { and, eq, inArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
channelAccessMembers,
channels,
companyMemberships,
} from "@paperclipai/db";
import {
channelMemberInputSchema,
channelQueueConfigSchema,
isUuidLike,
updateChannelInputSchema,
type ChannelMemberView,
type ChannelQueueConfig,
type ChannelView,
} from "@paperclipai/shared";
import { badRequest, forbidden, notFound } from "../errors.js";
import { logger } from "../middleware/logger.js";
import {
logActivity,
publishActivity,
type ActivityPublication,
} from "./activity-log.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import type { heartbeatService } from "./heartbeat.js";
import {
buildChannelViews,
normalizeChannelPathOrThrow,
resolveAssigneeAgent,
} from "./headless-channels.js";
import {
assertChannelAccess,
enforceHeadlessScopes,
resolveProjectReference,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
import {
assertCanConfigureManagedPool,
dispatchManagedChannelPool,
dispatchManagedChannelPoolBestEffort,
dispatchManagedChannelPoolsForCompletedIssue,
dispatchManagedChannelPoolsForCompletedIssueBestEffort,
} from "./headless-managed-pool.js";
import {
createManagedChannelPoolWorker,
recoverManagedChannelPools,
} from "./headless-managed-pool-worker.js";
export {
assertCanConfigureManagedPool,
createManagedChannelPoolWorker,
dispatchManagedChannelPool,
dispatchManagedChannelPoolBestEffort,
dispatchManagedChannelPoolsForCompletedIssue,
dispatchManagedChannelPoolsForCompletedIssueBestEffort,
recoverManagedChannelPools,
};
function activityActorFields(actor: HeadlessActorContext) {
return {
actorType: actor.principalType === "agent" ? ("agent" as const) : ("user" as const),
actorId:
actor.principalType === "agent"
? actor.agentId ?? "unknown-agent"
: actor.userId ?? "local-board",
agentId: actor.agentId ?? null,
responsibleUserIdOverride: actor.responsibleUserId ?? null,
};
}
export async function resolveChannelByIdOrPath(
dbOrTx: DbOrTx,
companyId: string,
channelRef: string,
): Promise<typeof channels.$inferSelect> {
const trimmed = channelRef.trim();
if (!trimmed) {
throw badRequest("Channel path or ID is required");
}
if (isUuidLike(trimmed)) {
const [byId] = await dbOrTx
.select()
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.id, trimmed)))
.limit(1);
if (byId) return byId;
}
const normalized = normalizeChannelPathOrThrow(trimmed, {
allowSubtreePrefix: false,
});
const [byPath] = await dbOrTx
.select()
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
.limit(1);
if (!byPath) {
throw notFound(`Channel '${normalized.path}' not found`, {
error: "channel_not_found",
code: "channel_not_found",
});
}
return byPath;
}
async function assertCanManageChannel(
dbOrTx: DbOrTx,
companyId: string,
channel: typeof channels.$inferSelect,
actor: HeadlessActorContext,
): Promise<void> {
enforceHeadlessScopes(actor, {
action: "channels.manage",
channelPath: channel.path,
});
await assertChannelAccess(dbOrTx, channel, actor);
const isOwnerOrCreator =
actor.isInstanceAdmin ||
actor.principalType === "local_trusted" ||
(Boolean(actor.userId) && channel.createdByUserId === actor.userId) ||
(Boolean(actor.agentId) && channel.createdByAgentId === actor.agentId);
let canManage = isOwnerOrCreator;
if (!canManage && actor.userId && actor.principalType === "user") {
const [membership] = await dbOrTx
.select({ role: companyMemberships.membershipRole })
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, actor.userId),
eq(companyMemberships.status, "active"),
inArray(companyMemberships.membershipRole, ["owner", "admin"]),
),
)
.limit(1);
canManage = Boolean(membership);
}
if (!canManage) {
throw forbidden(
"Only the channel creator or a company admin can update channel settings or membership",
{ code: "channel_manage_denied" },
);
}
}
export async function updateChannel(
db: Db,
companyId: string,
channelRef: string,
actor: HeadlessActorContext,
rawInput: unknown,
opts?: { heartbeat?: ReturnType<typeof heartbeatService> },
): Promise<ChannelView> {
const parsed = updateChannelInputSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
{
error: "validation_error",
code: "validation_error",
issues: parsed.error.issues,
},
);
}
const input = parsed.data;
const publications: ActivityPublication[] = [];
const committed = await db.transaction(async (tx) => {
const resolved = await resolveChannelByIdOrPath(tx, companyId, channelRef);
await tx.execute(
sql`SELECT id FROM channels WHERE id = ${resolved.id} AND company_id = ${companyId} FOR UPDATE`,
);
const [existing] = await tx
.select()
.from(channels)
.where(and(eq(channels.id, resolved.id), eq(channels.companyId, companyId)))
.limit(1);
if (!existing) {
throw notFound(`Channel '${channelRef}' not found`);
}
await assertCanManageChannel(tx, companyId, existing, actor);
const updates: Partial<typeof channels.$inferInsert> = {};
if (input.description !== undefined) {
updates.description = input.description;
}
if (input.defaultProjectId !== undefined) {
updates.defaultProjectId =
input.defaultProjectId === null
? null
: await resolveProjectReference(tx, companyId, input.defaultProjectId, actor);
}
if (input.queueConfig !== undefined || input.managedPool !== undefined) {
let nextQueueConfig: ChannelQueueConfig =
input.queueConfig === null
? {}
: input.queueConfig !== undefined
? { ...(existing.queueConfig ?? {}), ...input.queueConfig }
: { ...(existing.queueConfig ?? {}) };
if (input.managedPool !== undefined) {
if (input.managedPool === null) {
const { managedPool: _removed, ...rest } = nextQueueConfig;
nextQueueConfig = rest;
} else {
const resolvedAgentId = await resolveAssigneeAgent(tx, companyId, {
for: input.managedPool.agent,
});
if (!resolvedAgentId) {
throw notFound(`Agent '${input.managedPool.agent}' not found`);
}
nextQueueConfig = {
...nextQueueConfig,
managedPool: {
agentId: resolvedAgentId,
maxConcurrency: input.managedPool.maxConcurrency,
},
};
}
}
const validatedQc = channelQueueConfigSchema.safeParse(nextQueueConfig);
if (!validatedQc.success) {
throw badRequest(
validatedQc.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
{
error: "validation_error",
code: "validation_error",
issues: validatedQc.error.issues,
},
);
}
if (validatedQc.data.managedPool) {
const effectiveDefaultProjectId =
updates.defaultProjectId !== undefined
? updates.defaultProjectId
: existing.defaultProjectId;
await assertCanConfigureManagedPool(
tx,
companyId,
{
id: existing.id,
visibility: existing.visibility,
createdByAgentId: existing.createdByAgentId,
defaultProjectId: effectiveDefaultProjectId,
},
validatedQc.data.managedPool.agentId,
actor,
);
}
updates.queueConfig = validatedQc.data;
}
const now = new Date();
if (input.archived !== undefined) {
updates.archivedAt = input.archived ? (existing.archivedAt ?? now) : null;
}
updates.updatedAt = now;
const effectiveQueueConfig =
(updates.queueConfig as ChannelQueueConfig | undefined) ?? existing.queueConfig;
const effectiveArchivedAt =
updates.archivedAt !== undefined ? updates.archivedAt : existing.archivedAt;
if (effectiveQueueConfig?.managedPool && !effectiveArchivedAt) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, existing.id);
}
const [updated] = await tx
.update(channels)
.set(updates)
.where(eq(channels.id, existing.id))
.returning();
await logActivity(
tx as unknown as Db,
{
companyId,
...activityActorFields(actor),
action: "channel.updated",
entityType: "channel",
entityId: updated!.id,
details: {
path: updated!.path,
archived: Boolean(updated!.archivedAt),
hasManagedPool: Boolean(updated!.queueConfig?.managedPool),
},
},
publications,
);
const views = await buildChannelViews(tx, companyId, [updated!]);
return { view: views[0]!, channel: updated! };
});
for (const pub of publications) {
publishActivity(pub);
}
if (
committed.channel.queueConfig?.managedPool &&
!committed.channel.archivedAt &&
opts?.heartbeat
) {
await dispatchManagedChannelPool(db, companyId, committed.channel.id, {
heartbeat: opts.heartbeat,
actor,
}).catch((err) => {
logger.warn(
{ err, companyId, channelId: committed.channel.id },
"managed channel pool dispatch after channel update failed; background worker will retry",
);
});
}
return committed.view;
}
export async function listChannelMembers(
db: Db,
companyId: string,
channelRef: string,
actor: HeadlessActorContext,
): Promise<ChannelMemberView[]> {
const ch = await resolveChannelByIdOrPath(db, companyId, channelRef);
enforceHeadlessScopes(actor, {
action: "read",
channelPath: ch.path,
});
await assertChannelAccess(db, ch, actor);
const rows = await db
.select()
.from(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.companyId, companyId),
eq(channelAccessMembers.channelId, ch.id),
),
);
const agentIds = rows
.filter((r) => r.subjectType === "agent")
.map((r) => r.subjectId);
const agentNameMap = new Map<string, string>();
if (agentIds.length > 0) {
const agentRows = await db
.select({ id: agents.id, name: agents.name })
.from(agents)
.where(and(eq(agents.companyId, companyId), inArray(agents.id, agentIds)));
for (const a of agentRows) {
agentNameMap.set(a.id, a.name);
}
}
return rows.map((r) => ({
id: r.id,
channelId: r.channelId,
subjectType: r.subjectType === "agent" ? "agent" : "user",
subjectId: r.subjectId,
displayName:
r.subjectType === "agent" ? (agentNameMap.get(r.subjectId) ?? null) : null,
createdAt: r.createdAt.toISOString(),
}));
}
async function resolveChannelMemberTarget(
dbOrTx: DbOrTx,
companyId: string,
input: {
agent?: string;
userId?: string;
subjectType?: "user" | "agent";
subjectId?: string;
},
): Promise<{ subjectType: "user" | "agent"; subjectId: string; displayName: string | null }> {
if (input.agent) {
const agentId = await resolveAssigneeAgent(dbOrTx, companyId, {
for: input.agent,
});
if (!agentId) {
throw notFound(`Agent '${input.agent}' not found`);
}
const [agentRow] = await dbOrTx
.select({ name: agents.name })
.from(agents)
.where(eq(agents.id, agentId))
.limit(1);
return {
subjectType: "agent",
subjectId: agentId,
displayName: agentRow?.name ?? null,
};
}
if (input.userId) {
return { subjectType: "user", subjectId: input.userId.trim(), displayName: null };
}
if (input.subjectType && input.subjectId) {
if (input.subjectType === "agent") {
const agentId = await resolveAssigneeAgent(dbOrTx, companyId, {
for: input.subjectId,
});
if (!agentId) {
throw notFound(`Agent '${input.subjectId}' not found`);
}
const [agentRow] = await dbOrTx
.select({ name: agents.name })
.from(agents)
.where(eq(agents.id, agentId))
.limit(1);
return {
subjectType: "agent",
subjectId: agentId,
displayName: agentRow?.name ?? null,
};
}
return {
subjectType: "user",
subjectId: input.subjectId.trim(),
displayName: null,
};
}
throw badRequest("Provide 'agent', 'userId', or both 'subjectType' and 'subjectId'");
}
export async function addChannelMember(
db: Db,
companyId: string,
actor: HeadlessActorContext,
rawInput: unknown,
): Promise<ChannelMemberView> {
const parsed = channelMemberInputSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
);
}
const input = parsed.data;
const publications: ActivityPublication[] = [];
const view = await db.transaction(async (tx) => {
const ch = await resolveChannelByIdOrPath(tx, companyId, input.channel);
await assertCanManageChannel(tx, companyId, ch, actor);
const target = await resolveChannelMemberTarget(tx, companyId, input);
const [inserted] = await tx
.insert(channelAccessMembers)
.values({
companyId,
channelId: ch.id,
subjectType: target.subjectType,
subjectId: target.subjectId,
})
.onConflictDoNothing({
target: [
channelAccessMembers.channelId,
channelAccessMembers.subjectType,
channelAccessMembers.subjectId,
],
})
.returning();
const row =
inserted ??
(
await tx
.select()
.from(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.channelId, ch.id),
eq(channelAccessMembers.subjectType, target.subjectType),
eq(channelAccessMembers.subjectId, target.subjectId),
),
)
.limit(1)
)[0]!;
await logActivity(
tx as unknown as Db,
{
companyId,
...activityActorFields(actor),
action: "channel.member_added",
entityType: "channel",
entityId: ch.id,
details: {
path: ch.path,
subjectType: target.subjectType,
subjectId: target.subjectId,
},
},
publications,
);
return {
id: row.id,
channelId: row.channelId,
subjectType: row.subjectType === "agent" ? ("agent" as const) : ("user" as const),
subjectId: row.subjectId,
displayName: target.displayName,
createdAt: row.createdAt.toISOString(),
};
});
for (const pub of publications) {
publishActivity(pub);
}
return view;
}
export async function removeChannelMember(
db: Db,
companyId: string,
actor: HeadlessActorContext,
rawInput: unknown,
): Promise<{ removed: boolean }> {
const parsed = channelMemberInputSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
);
}
const input = parsed.data;
const publications: ActivityPublication[] = [];
const removed = await db.transaction(async (tx) => {
const ch = await resolveChannelByIdOrPath(tx, companyId, input.channel);
await assertCanManageChannel(tx, companyId, ch, actor);
const target = await resolveChannelMemberTarget(tx, companyId, input);
const deleted = await tx
.delete(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.companyId, companyId),
eq(channelAccessMembers.channelId, ch.id),
eq(channelAccessMembers.subjectType, target.subjectType),
eq(channelAccessMembers.subjectId, target.subjectId),
),
)
.returning({ id: channelAccessMembers.id });
if (deleted.length > 0) {
await logActivity(
tx as unknown as Db,
{
companyId,
...activityActorFields(actor),
action: "channel.member_removed",
entityType: "channel",
entityId: ch.id,
details: {
path: ch.path,
subjectType: target.subjectType,
subjectId: target.subjectId,
},
},
publications,
);
}
return deleted.length > 0;
});
for (const pub of publications) {
publishActivity(pub);
}
return { removed };
}
+64 -21
View File
@@ -62,6 +62,7 @@ import {
publishActivity,
type ActivityPublication,
} from "./activity-log.js";
import { assertCanConfigureManagedPool } from "./headless-managed-pool.js";
import {
appendBoardEvent,
assertChannelAccess,
@@ -426,27 +427,51 @@ export async function ensureChannel(
visibility = "private";
}
const now = new Date();
const [inserted] = await dbOrTx
.insert(channels)
.values({
companyId,
path: normalized.path,
description: input.description ?? null,
visibility: visibility ?? "open",
defaultProjectId: resolvedDefaultProjectId ?? null,
queueConfig: validatedQueueConfig ?? {},
createdByAgentId: actor.agentId,
createdByUserId: actor.agentId ? null : actor.userId,
createdByProfile: actor.actorProfile,
lastActivityAt: now,
createdAt: now,
updatedAt: now,
})
.onConflictDoNothing({
target: [channels.companyId, channels.path],
})
.returning();
const [preExisting] = await dbOrTx
.select({ id: channels.id })
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
.limit(1);
let inserted: typeof channels.$inferSelect | undefined;
if (!preExisting) {
if (validatedQueueConfig?.managedPool) {
await assertCanConfigureManagedPool(
dbOrTx,
companyId,
{
visibility: visibility ?? "open",
createdByAgentId: actor.agentId,
defaultProjectId: resolvedDefaultProjectId ?? null,
},
validatedQueueConfig.managedPool.agentId,
actor,
);
}
const now = new Date();
const [createdRow] = await dbOrTx
.insert(channels)
.values({
companyId,
path: normalized.path,
description: input.description ?? null,
visibility: visibility ?? "open",
defaultProjectId: resolvedDefaultProjectId ?? null,
queueConfig: validatedQueueConfig ?? {},
createdByAgentId: actor.agentId,
createdByUserId: actor.agentId ? null : actor.userId,
createdByProfile: actor.actorProfile,
lastActivityAt: now,
createdAt: now,
updatedAt: now,
})
.onConflictDoNothing({
target: [channels.companyId, channels.path],
})
.returning();
inserted = createdRow;
}
if (inserted) {
if (inserted.visibility === "private") {
@@ -547,6 +572,24 @@ export async function ensureChannel(
throw forbidden("Only the channel creator or a company admin can update channel settings");
}
if (updates.queueConfig?.managedPool) {
await assertCanConfigureManagedPool(
dbOrTx,
companyId,
{
id: existing.id,
visibility: updates.visibility ?? existing.visibility,
createdByAgentId: existing.createdByAgentId,
defaultProjectId:
updates.defaultProjectId !== undefined
? updates.defaultProjectId
: existing.defaultProjectId,
},
updates.queueConfig.managedPool.agentId,
actor,
);
}
updates.updatedAt = new Date();
const privatizingTree =
updates.visibility === "private" && existing.visibility !== "private";
@@ -0,0 +1,456 @@
import { and, eq, inArray, isNull, ne, or, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
channels,
issueRelations,
issues,
} from "@paperclipai/db";
import { isUuidLike } from "@paperclipai/shared";
import type { heartbeatService } from "./heartbeat.js";
import { issueTreeControlService } from "./issue-tree-control.js";
import {
dispatchManagedChannelPool,
isAgentEligibleForChannelPool,
isCandidateEligibleForPoolDispatch,
} from "./headless-managed-pool.js";
export interface ManagedPoolRecoveryScope {
channelIds?: string[];
companyIds?: string[];
agentTargets?: Array<{ companyId: string; agentId: string }>;
issueTargets?: Array<{ companyId: string; issueId: string }>;
}
/**
* Recovers managed channel pools (full scan on startup, or narrowed by scope hints
* on subsequent deliveryWork signals so unrelated writes do not scan all pools).
*/
export async function recoverManagedChannelPools(
db: Db,
heartbeat: ReturnType<typeof heartbeatService>,
scope?: ManagedPoolRecoveryScope,
signal?: AbortSignal,
): Promise<{ recoveredChannels: number; wokenIssueIds: string[]; dispatchedIssueIds: string[] }> {
const channelIdsToCheck = new Set<string>(scope?.channelIds ?? []);
const companyIdsToCheck = new Set<string>(scope?.companyIds ?? []);
const agentTargets = scope?.agentTargets ?? [];
if (scope?.issueTargets && scope.issueTargets.length > 0) {
const issueIds = [...new Set(scope.issueTargets.map((t) => t.issueId))];
const directRows = await db
.select({ channelId: issues.channelId })
.from(issues)
.where(inArray(issues.id, issueIds));
for (const r of directRows) {
if (r.channelId) channelIdsToCheck.add(r.channelId);
}
const depRows = await db
.select({ channelId: issues.channelId })
.from(issueRelations)
.innerJoin(issues, eq(issues.id, issueRelations.relatedIssueId))
.where(
and(
inArray(issueRelations.issueId, issueIds),
eq(issueRelations.type, "blocks"),
),
);
for (const r of depRows) {
if (r.channelId) channelIdsToCheck.add(r.channelId);
}
}
const scopeFilters = [];
if (scope) {
if (channelIdsToCheck.size > 0) {
scopeFilters.push(inArray(channels.id, [...channelIdsToCheck]));
}
if (companyIdsToCheck.size > 0) {
scopeFilters.push(inArray(channels.companyId, [...companyIdsToCheck]));
}
for (const target of agentTargets) {
scopeFilters.push(
and(
eq(channels.companyId, target.companyId),
sql`(${channels.queueConfig}->'managedPool'->>'agentId') = ${target.agentId}`,
),
);
}
if (scopeFilters.length === 0) {
return { recoveredChannels: 0, wokenIssueIds: [], dispatchedIssueIds: [] };
}
}
const poolChannels = await db
.select()
.from(channels)
.where(
and(
isNull(channels.archivedAt),
sql`jsonb_exists(${channels.queueConfig}, 'managedPool')`,
...(scopeFilters.length > 0 ? [or(...scopeFilters)] : []),
),
);
const wokenIssueIds: string[] = [];
const dispatchedIssueIds: string[] = [];
for (const ch of poolChannels) {
if (signal?.aborted) break;
const pool = ch.queueConfig?.managedPool;
if (!pool) continue;
// On full startup recovery only, re-wake any eligible assigned todo tasks
// whose initial wakeup was interrupted before an agent run started.
if (!scope) {
const [agentRow] = await db
.select({
id: agents.id,
role: agents.role,
status: agents.status,
permissions: agents.permissions,
})
.from(agents)
.where(
and(
eq(agents.id, pool.agentId),
eq(agents.companyId, ch.companyId),
ne(agents.status, "terminated"),
ne(agents.status, "paused"),
),
)
.limit(1);
if (agentRow && (await isAgentEligibleForChannelPool(db, ch, agentRow))) {
const stranded = await db.execute<{ id: string }>(sql`
SELECT i.id
FROM issues i
WHERE i.company_id = ${ch.companyId}
AND i.channel_id = ${ch.id}
AND i.assignee_agent_id = ${pool.agentId}
AND i.status = 'todo'
AND i.execution_run_id IS NULL
AND i.checkout_run_id IS NULL
AND i.claim_token_hash IS NULL
AND i.claim_lease_expires_at IS NULL
AND i.conversation_agent_id IS NULL
AND i.hidden_at IS NULL
AND COALESCE(i.source_trust->>'level', '') <> 'untrusted'
AND COALESCE(i.source_trust->>'disposition', '') <> 'quarantined'
AND NOT EXISTS (
SELECT 1
FROM projects p
WHERE p.id = i.project_id
AND p.paused_at IS NOT NULL
)
AND NOT EXISTS (
SELECT 1
FROM issue_relations ir
INNER JOIN issues bi ON bi.id = ir.issue_id
WHERE ir.company_id = i.company_id
AND ir.related_issue_id = i.id
AND ir.type = 'blocks'
AND bi.status <> 'done'
)
`);
const treeControl = issueTreeControlService(db);
for (const row of stranded) {
if (signal?.aborted) break;
if (await treeControl.getActivePauseHoldGate(ch.companyId, row.id)) {
continue;
}
await heartbeat
.wakeup(pool.agentId, {
source: "assignment",
triggerDetail: "system",
reason: "issue_assigned",
payload: {
issueId: row.id,
channelId: ch.id,
channelPath: ch.path,
managedPool: true,
startupRecovery: true,
},
idempotencyKey: `managed-pool-recovery:${ch.id}:${row.id}`,
requestedByActorType: "system",
requestedByActorId: "managed_channel_pool_recovery",
contextSnapshot: {
issueId: row.id,
taskId: row.id,
wakeReason: "issue_assigned",
},
})
.catch(() => {
// Best-effort startup wakeup
});
wokenIssueIds.push(row.id);
}
}
}
if (signal?.aborted) break;
// Dispatch any remaining free capacity in this channel
const res = await dispatchManagedChannelPool(db, ch.companyId, ch.id, {
heartbeat,
});
dispatchedIssueIds.push(...res.dispatchedIssueIds);
}
return {
recoveredChannels: poolChannels.length,
wokenIssueIds,
dispatchedIssueIds,
};
}
/**
* Sleep-aware managed channel pool worker registered on the shared deliveryWork coordinator.
* Runs a full scan on startup and narrows subsequent runs using committed deliveryWork hints
* while falling back to a full scan on empty-scope retries.
*/
export function createManagedChannelPoolWorker(
db: Db,
heartbeat: ReturnType<typeof heartbeatService>,
) {
let fullScan = true;
const pendingChannelIds = new Set<string>();
const pendingCompanyIds = new Set<string>();
const pendingAgentTargets = new Map<string, { companyId: string; agentId: string }>();
const pendingIssueTargets = new Map<string, { companyId: string; issueId: string }>();
function recordHints(hints?: ReadonlySet<string>) {
if (!hints || hints.size === 0) {
fullScan = true;
return;
}
for (const raw of hints) {
if (raw === "*") {
fullScan = true;
return;
}
if (isUuidLike(raw)) {
pendingChannelIds.add(raw);
continue;
}
try {
const parsed = JSON.parse(raw) as {
companyId?: string;
channelId?: string;
agentId?: string;
issueId?: string;
reload?: boolean;
};
if (parsed.reload || !parsed.companyId) {
fullScan = true;
return;
}
if (parsed.channelId) {
pendingChannelIds.add(parsed.channelId);
} else if (parsed.agentId) {
pendingAgentTargets.set(`${parsed.companyId}:${parsed.agentId}`, {
companyId: parsed.companyId,
agentId: parsed.agentId,
});
} else if (parsed.issueId) {
pendingIssueTargets.set(`${parsed.companyId}:${parsed.issueId}`, {
companyId: parsed.companyId,
issueId: parsed.issueId,
});
} else {
pendingCompanyIds.add(parsed.companyId);
}
} catch {
fullScan = true;
return;
}
}
}
return {
recoverManagedChannelPools: () => recoverManagedChannelPools(db, heartbeat),
deliveryTask: {
retryMs: 5_000,
coalesceMs: 50,
pausePassiveMaintenance: true,
onSettled: (hints?: ReadonlySet<string>) => {
recordHints(hints);
},
run: async (signal: AbortSignal) => {
if (signal.aborted) return;
const doFull = fullScan;
const channelIds = [...pendingChannelIds];
const companyIds = [...pendingCompanyIds];
const agentTargets = [...pendingAgentTargets.values()];
const issueTargets = [...pendingIssueTargets.values()];
const hasScopedHints =
channelIds.length > 0 ||
companyIds.length > 0 ||
agentTargets.length > 0 ||
issueTargets.length > 0;
fullScan = false;
pendingChannelIds.clear();
pendingCompanyIds.clear();
pendingAgentTargets.clear();
pendingIssueTargets.clear();
try {
if (doFull || !hasScopedHints) {
await recoverManagedChannelPools(db, heartbeat, undefined, signal);
} else {
await recoverManagedChannelPools(
db,
heartbeat,
{
channelIds,
companyIds,
agentTargets,
issueTargets,
},
signal,
);
}
} catch (err) {
// Restore scope so the coordinator retry covers the interrupted work
if (doFull || !hasScopedHints) fullScan = true;
for (const id of channelIds) pendingChannelIds.add(id);
for (const id of companyIds) pendingCompanyIds.add(id);
for (const t of agentTargets) pendingAgentTargets.set(`${t.companyId}:${t.agentId}`, t);
for (const t of issueTargets) pendingIssueTargets.set(`${t.companyId}:${t.issueId}`, t);
throw err;
}
},
hasPending: async (runAllowed = true) => {
if (!runAllowed) return false;
const candidateChannels = await db
.select()
.from(channels)
.where(
and(
isNull(channels.archivedAt),
sql`jsonb_exists(${channels.queueConfig}, 'managedPool')`,
sql`EXISTS (
SELECT 1
FROM agents a
WHERE a.id = (${channels.queueConfig}->'managedPool'->>'agentId')::uuid
AND a.company_id = ${channels.companyId}
AND a.status NOT IN ('terminated', 'paused')
)`,
sql`(
SELECT count(*)::int
FROM issues active_i
WHERE active_i.company_id = ${channels.companyId}
AND active_i.channel_id = ${channels.id}
AND active_i.assignee_agent_id = (${channels.queueConfig}->'managedPool'->>'agentId')::uuid
AND active_i.status IN ('todo', 'in_progress')
AND active_i.hidden_at IS NULL
) < COALESCE((${channels.queueConfig}->'managedPool'->>'maxConcurrency')::int, 1)`,
),
);
if (candidateChannels.length === 0) return false;
const treeControl = issueTreeControlService(db);
const BATCH_SIZE = 25;
for (const ch of candidateChannels) {
const pool = ch.queueConfig?.managedPool;
if (!pool) continue;
const [agentRow] = await db
.select({
id: agents.id,
role: agents.role,
status: agents.status,
permissions: agents.permissions,
})
.from(agents)
.where(
and(
eq(agents.id, pool.agentId),
eq(agents.companyId, ch.companyId),
ne(agents.status, "terminated"),
ne(agents.status, "paused"),
),
)
.limit(1);
if (!agentRow || !(await isAgentEligibleForChannelPool(db, ch, agentRow))) {
continue;
}
const seenIds: string[] = [];
while (true) {
const seenExclusion =
seenIds.length > 0
? sql`AND i.id NOT IN (${sql.join(
seenIds.map((id) => sql`${id}::uuid`),
sql`, `,
)})`
: sql``;
const readyRows = await db.execute<{
id: string;
project_id: string | null;
parent_id: string | null;
execution_policy: unknown;
}>(sql`
SELECT i.id, i.project_id, i.parent_id, i.execution_policy
FROM issues i
WHERE i.company_id = ${ch.companyId}
AND i.channel_id = ${ch.id}
AND i.status = 'todo'
AND i.hidden_at IS NULL
AND i.assignee_agent_id IS NULL
AND i.assignee_user_id IS NULL
AND i.claim_token_hash IS NULL
AND i.claim_lease_expires_at IS NULL
AND i.checkout_run_id IS NULL
AND i.execution_run_id IS NULL
AND i.conversation_agent_id IS NULL
AND COALESCE(i.source_trust->>'level', '') <> 'untrusted'
AND COALESCE(i.source_trust->>'disposition', '') <> 'quarantined'
${seenExclusion}
AND NOT EXISTS (
SELECT 1
FROM issue_relations ir
INNER JOIN issues bi ON bi.id = ir.issue_id
WHERE ir.company_id = i.company_id
AND ir.related_issue_id = i.id
AND ir.type = 'blocks'
AND bi.status <> 'done'
)
LIMIT ${BATCH_SIZE}
`);
if (readyRows.length === 0) break;
for (const row of readyRows) {
seenIds.push(row.id);
const eligible = await isCandidateEligibleForPoolDispatch(
db,
ch,
pool.agentId,
{
id: row.id,
projectId: row.project_id,
parentId: row.parent_id,
executionPolicy: row.execution_policy,
},
treeControl,
);
if (eligible) {
return true;
}
}
if (readyRows.length < BATCH_SIZE) break;
}
}
return false;
},
},
};
}
@@ -0,0 +1,715 @@
import { and, eq, isNull, ne, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
channelAccessMembers,
channels,
issueRelations,
issues,
projects,
} from "@paperclipai/db";
import { type ChannelQueueConfig } from "@paperclipai/shared";
import { forbidden, notFound } from "../errors.js";
import { logger } from "../middleware/logger.js";
import {
logActivity,
publishActivity,
type ActivityPublication,
} from "./activity-log.js";
import {
authorizationService,
evaluateAuthorizationPolicyForAssignment,
type AuthorizationActor,
} from "./authorization.js";
import type { heartbeatService } from "./heartbeat.js";
import { issueTreeControlService } from "./issue-tree-control.js";
import {
appendBoardEvent,
publishCommittedBoardEvent,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
function toAuthorizationActor(actor: HeadlessActorContext): AuthorizationActor {
if (actor.principalType === "agent" && actor.agentId) {
return {
type: "agent",
agentId: actor.agentId,
companyId: actor.companyId,
};
}
if (actor.principalType === "local_trusted") {
return {
type: "board",
userId: actor.userId ?? "local-board",
source: "local_implicit",
isInstanceAdmin: true,
};
}
return {
type: "board",
userId: actor.userId ?? "unknown-user",
source: "session",
isInstanceAdmin: actor.isInstanceAdmin,
};
}
function readAgentAuthorizationPolicy(
permissions: unknown,
): Record<string, unknown> | null {
if (!permissions || typeof permissions !== "object" || Array.isArray(permissions)) {
return null;
}
const policy = (permissions as Record<string, unknown>).authorizationPolicy;
if (!policy || typeof policy !== "object" || Array.isArray(policy)) {
return null;
}
return policy as Record<string, unknown>;
}
export async function isAgentEligibleForChannelPool(
dbOrTx: DbOrTx,
ch: typeof channels.$inferSelect,
agentRow: { id: string; role: string | null; permissions: unknown },
): Promise<boolean> {
const policyEffect = evaluateAuthorizationPolicyForAssignment(
readAgentAuthorizationPolicy(agentRow.permissions),
"Managed pool agent",
);
if (policyEffect.kind !== "none") {
return false;
}
const qc = ch.queueConfig as ChannelQueueConfig | null | undefined;
if (qc?.allowedAgentIds && qc.allowedAgentIds.length > 0) {
if (!qc.allowedAgentIds.includes(agentRow.id)) {
return false;
}
}
if (qc?.allowedRoles && qc.allowedRoles.length > 0) {
if (!agentRow.role || !qc.allowedRoles.includes(agentRow.role)) {
return false;
}
}
if (ch.visibility === "private" && ch.createdByAgentId !== agentRow.id) {
const [member] = await dbOrTx
.select({ id: channelAccessMembers.id })
.from(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.companyId, ch.companyId),
eq(channelAccessMembers.channelId, ch.id),
eq(channelAccessMembers.subjectType, "agent"),
eq(channelAccessMembers.subjectId, agentRow.id),
),
)
.limit(1);
if (!member) {
return false;
}
}
return true;
}
function readNestedAuthorizationPolicy(
container: unknown,
): Record<string, unknown> | null {
if (!container || typeof container !== "object" || Array.isArray(container)) {
return null;
}
const policy = (container as Record<string, unknown>).authorizationPolicy;
if (!policy || typeof policy !== "object" || Array.isArray(policy)) {
return null;
}
return policy as Record<string, unknown>;
}
function channelPolicyActor(
ch: Pick<typeof channels.$inferSelect, "companyId" | "createdByAgentId" | "createdByUserId">,
): AuthorizationActor {
if (ch.createdByAgentId) {
return {
type: "agent",
agentId: ch.createdByAgentId,
companyId: ch.companyId,
};
}
if (ch.createdByUserId && ch.createdByUserId !== "local-board") {
return {
type: "board",
userId: ch.createdByUserId,
source: "session",
isInstanceAdmin: false,
};
}
return {
type: "board",
userId: "local-board",
source: "local_implicit",
isInstanceAdmin: true,
};
}
export async function isCandidateEligibleForPoolDispatch(
dbOrTx: DbOrTx,
ch: Pick<typeof channels.$inferSelect, "companyId" | "createdByAgentId" | "createdByUserId">,
poolAgentId: string,
candidate: {
id: string;
projectId: string | null;
parentId: string | null;
executionPolicy: unknown;
},
treeControl: ReturnType<typeof issueTreeControlService>,
): Promise<boolean> {
const companyId = ch.companyId;
const pauseHold = await treeControl.getActivePauseHoldGate(companyId, candidate.id);
if (pauseHold) {
return false;
}
// Enforce issue, parent, and project assignment policies before auto-dispatch
if (
evaluateAuthorizationPolicyForAssignment(
readNestedAuthorizationPolicy(candidate.executionPolicy),
"Target issue",
).kind !== "none"
) {
return false;
}
if (candidate.projectId) {
const [proj] = await dbOrTx
.select({
pausedAt: projects.pausedAt,
executionWorkspacePolicy: projects.executionWorkspacePolicy,
})
.from(projects)
.where(and(eq(projects.id, candidate.projectId), eq(projects.companyId, companyId)))
.limit(1);
if (proj?.pausedAt) {
return false;
}
if (
evaluateAuthorizationPolicyForAssignment(
readNestedAuthorizationPolicy(proj?.executionWorkspacePolicy),
"Target project",
).kind !== "none"
) {
return false;
}
}
if (candidate.parentId && candidate.parentId !== candidate.id) {
const [parent] = await dbOrTx
.select({ executionPolicy: issues.executionPolicy })
.from(issues)
.where(and(eq(issues.id, candidate.parentId), eq(issues.companyId, companyId)))
.limit(1);
if (
evaluateAuthorizationPolicyForAssignment(
readNestedAuthorizationPolicy(parent?.executionPolicy),
"Parent issue",
).kind !== "none"
) {
return false;
}
}
const authz = authorizationService(dbOrTx as unknown as Db);
const policyActor = channelPolicyActor(ch);
const candidateResource = {
type: "issue" as const,
companyId,
issueId: candidate.id,
projectId: candidate.projectId,
parentIssueId: candidate.parentId,
assigneeAgentId: poolAgentId,
assigneeUserId: null,
};
// Enforce canonical issue:read privacy gates for both the channel owner and the pool agent
const [ownerRead, agentRead, assignDecision] = await Promise.all([
authz.decide({
action: "issue:read",
actor: policyActor,
resource: candidateResource,
scope: { companyId },
}),
authz.decide({
action: "issue:read",
actor: {
type: "agent",
agentId: poolAgentId,
companyId,
},
resource: candidateResource,
scope: { companyId },
}),
authz.decide({
action: "tasks:assign",
actor: policyActor,
resource: candidateResource,
scope: { companyId },
}),
]);
return ownerRead.allowed && agentRead.allowed && assignDecision.allowed;
}
/**
* Validates that the caller is authorized to bind `agentId` as a channel's managedPool
* worker, honoring canonical `tasks:assign` policy, protected/private agent restrictions,
* and private channel membership.
*/
export async function assertCanConfigureManagedPool(
tx: DbOrTx,
companyId: string,
channel: {
id?: string;
visibility?: string | null;
createdByAgentId?: string | null;
defaultProjectId?: string | null;
},
agentId: string,
actor: HeadlessActorContext,
): Promise<void> {
const [agentRow] = await tx
.select({
id: agents.id,
status: agents.status,
permissions: agents.permissions,
})
.from(agents)
.where(
and(
eq(agents.id, agentId),
eq(agents.companyId, companyId),
ne(agents.status, "terminated"),
),
)
.limit(1);
if (!agentRow) {
throw notFound(`Agent '${agentId}' not found`);
}
const policyEffect = evaluateAuthorizationPolicyForAssignment(
readAgentAuthorizationPolicy(agentRow.permissions),
"Managed pool agent",
);
if (policyEffect.kind !== "none") {
throw forbidden(
policyEffect.explanation ??
"Protected or restricted agents cannot be configured as a managed channel pool",
);
}
const decision = await authorizationService(tx as unknown as Db).decide({
action: "tasks:assign",
actor: toAuthorizationActor(actor),
resource: {
type: "issue",
companyId,
issueId: null,
projectId: channel.defaultProjectId ?? null,
parentIssueId: null,
assigneeAgentId: agentId,
assigneeUserId: null,
},
scope: { companyId },
});
if (!decision.allowed) {
throw forbidden(
decision.explanation ?? "Not authorized to assign work to this managed pool agent",
);
}
if (channel.visibility === "private" && channel.createdByAgentId !== agentId) {
if (!channel.id) {
throw forbidden("Managed pool agent must be a member of this private channel");
}
const [member] = await tx
.select({ id: channelAccessMembers.id })
.from(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.companyId, companyId),
eq(channelAccessMembers.channelId, channel.id),
eq(channelAccessMembers.subjectType, "agent"),
eq(channelAccessMembers.subjectId, agentId),
),
)
.limit(1);
if (!member) {
throw forbidden("Managed pool agent must be a member of this private channel");
}
}
}
/**
* When a channel has `queueConfig.managedPool = { agentId, maxConcurrency }`,
* auto-assigns ready unassigned `todo` tasks up to `maxConcurrency` active tasks
* for that agent in the channel and triggers `heartbeat.wakeup`.
*
* Uses `FOR UPDATE` on the channel row to serialize concurrent dispatchers and
* `FOR UPDATE OF i SKIP LOCKED` on candidate rows to prevent double-dispatch.
* Records both `activityLog` (`issue.assigned`) and `boardEvents` (`task.assigned`)
* in the same transaction.
*/
export async function dispatchManagedChannelPool(
db: Db,
companyId: string,
channelId: string,
opts: {
heartbeat?: ReturnType<typeof heartbeatService>;
actor?: HeadlessActorContext;
},
): Promise<{ dispatchedIssueIds: string[] }> {
const publications: ActivityPublication[] = [];
const assignedInTx = await db.transaction(async (tx) => {
// Serialize concurrent dispatchers for this channel so activeCount + slots cannot race
await tx.execute(
sql`SELECT id FROM channels WHERE id = ${channelId} AND company_id = ${companyId} FOR UPDATE`,
);
const [ch] = await tx
.select()
.from(channels)
.where(
and(
eq(channels.id, channelId),
eq(channels.companyId, companyId),
isNull(channels.archivedAt),
),
)
.limit(1);
const pool = ch?.queueConfig?.managedPool;
if (!ch || !pool) {
return {
items: [] as Array<{ id: string; identifier: string }>,
events: [],
channel: null as typeof channels.$inferSelect | null,
poolAgentId: null as string | null,
};
}
const [agentRow] = await tx
.select({
id: agents.id,
name: agents.name,
role: agents.role,
status: agents.status,
permissions: agents.permissions,
})
.from(agents)
.where(
and(
eq(agents.id, pool.agentId),
eq(agents.companyId, companyId),
ne(agents.status, "terminated"),
ne(agents.status, "paused"),
),
)
.limit(1);
if (!agentRow || !(await isAgentEligibleForChannelPool(tx, ch, agentRow))) {
return {
items: [] as Array<{ id: string; identifier: string }>,
events: [],
channel: null as typeof channels.$inferSelect | null,
poolAgentId: null as string | null,
};
}
// Count active tasks already assigned to this managed pool agent in this channel
const activeRows = await tx.execute<{ cnt: number }>(sql`
SELECT count(*)::int AS cnt
FROM issues i
WHERE i.company_id = ${companyId}
AND i.channel_id = ${channelId}
AND i.assignee_agent_id = ${pool.agentId}
AND i.status IN ('todo', 'in_progress')
AND i.hidden_at IS NULL
`);
const activeCount = Number(activeRows[0]?.cnt ?? 0);
const slots = Math.max(0, pool.maxConcurrency - activeCount);
if (slots === 0) {
return {
items: [] as Array<{ id: string; identifier: string }>,
events: [],
channel: ch,
poolAgentId: pool.agentId,
};
}
const strictFifo = ch.queueConfig?.ordering === "strict_fifo";
const orderClause = strictFifo
? sql`i.created_at ASC`
: sql`CASE i.priority
WHEN 'critical' THEN 0
WHEN 'high' THEN 1
WHEN 'medium' THEN 2
WHEN 'low' THEN 3
ELSE 4
END ASC, i.created_at ASC`;
const now = new Date();
const items: Array<{ id: string; identifier: string }> = [];
const events = [];
const treeControl = issueTreeControlService(tx as unknown as Db);
const BATCH_SIZE = Math.max(slots * 4, 25);
const seenIds: string[] = [];
while (items.length < slots) {
const seenExclusion =
seenIds.length > 0
? sql`AND i.id NOT IN (${sql.join(
seenIds.map((id) => sql`${id}::uuid`),
sql`, `,
)})`
: sql``;
const candidates = await tx.execute<{
id: string;
project_id: string | null;
parent_id: string | null;
execution_policy: unknown;
}>(sql`
SELECT i.id, i.project_id, i.parent_id, i.execution_policy
FROM issues i
WHERE i.company_id = ${companyId}
AND i.channel_id = ${channelId}
AND i.status = 'todo'
AND i.assignee_agent_id IS NULL
AND i.assignee_user_id IS NULL
AND i.claim_token_hash IS NULL
AND i.claim_lease_expires_at IS NULL
AND i.checkout_run_id IS NULL
AND i.execution_run_id IS NULL
AND i.hidden_at IS NULL
AND i.conversation_agent_id IS NULL
AND COALESCE(i.source_trust->>'level', '') <> 'untrusted'
AND COALESCE(i.source_trust->>'disposition', '') <> 'quarantined'
${seenExclusion}
AND NOT EXISTS (
SELECT 1
FROM issue_relations ir
INNER JOIN issues bi ON bi.id = ir.issue_id
WHERE ir.company_id = i.company_id
AND ir.related_issue_id = i.id
AND ir.type = 'blocks'
AND bi.status <> 'done'
)
ORDER BY ${orderClause}
LIMIT ${BATCH_SIZE}
FOR UPDATE OF i SKIP LOCKED
`);
if (candidates.length === 0) {
break;
}
for (const row of candidates) {
if (items.length >= slots) break;
seenIds.push(row.id);
const eligible = await isCandidateEligibleForPoolDispatch(
tx,
ch,
pool.agentId,
{
id: row.id,
projectId: row.project_id,
parentId: row.parent_id,
executionPolicy: row.execution_policy,
},
treeControl,
);
if (!eligible) {
continue;
}
const [updated] = await tx
.update(issues)
.set({
assigneeAgentId: pool.agentId,
updatedAt: now,
})
.where(eq(issues.id, row.id))
.returning({ id: issues.id, identifier: issues.identifier, kvLabels: issues.kvLabels });
if (!updated) continue;
const identifier = updated.identifier ?? updated.id;
items.push({ id: updated.id, identifier });
await logActivity(
tx as unknown as Db,
{
companyId,
actorType: "system",
actorId: "managed_channel_pool",
action: "issue.assigned",
entityType: "issue",
entityId: updated.id,
details: {
identifier,
channelId: ch.id,
channelPath: ch.path,
assigneeAgentId: pool.agentId,
managedPool: true,
},
},
publications,
);
const ev = await appendBoardEvent(tx, {
companyId,
type: "task.assigned",
channelId: ch.id,
channelPath: ch.path,
issueId: updated.id,
identifier,
actor: opts.actor ?? {
principalType: "system" as const,
actorProfile: "managed-pool-dispatcher",
},
payload: {
assigneeAgentId: pool.agentId,
managedPool: true,
kvLabels: updated.kvLabels ?? {},
},
});
events.push(ev);
}
if (candidates.length < BATCH_SIZE) {
break;
}
}
return { items, events, channel: ch, poolAgentId: pool.agentId };
});
for (const pub of publications) {
publishActivity(pub);
}
for (const ev of assignedInTx.events) {
publishCommittedBoardEvent(ev);
}
if (opts.heartbeat && assignedInTx.channel && assignedInTx.poolAgentId) {
for (const item of assignedInTx.items) {
await opts.heartbeat
.wakeup(assignedInTx.poolAgentId, {
source: "assignment",
triggerDetail: "system",
reason: "issue_assigned",
payload: {
issueId: item.id,
channelId: assignedInTx.channel.id,
channelPath: assignedInTx.channel.path,
managedPool: true,
},
idempotencyKey: `managed-pool:${assignedInTx.channel.id}:${item.id}`,
requestedByActorType: "system",
requestedByActorId: "managed_channel_pool",
contextSnapshot: {
issueId: item.id,
taskId: item.id,
wakeReason: "issue_assigned",
},
})
.catch(() => {
// Best-effort wakeup; task stays assigned to pool agent for pickup
});
}
}
return { dispatchedIssueIds: assignedInTx.items.map((i) => i.id) };
}
/**
* Dispatches managed pools for a completed issue's own channel (freeing a concurrency slot)
* AND for the distinct channels of any dependent issues that may now be unblocked.
*/
export async function dispatchManagedChannelPoolsForCompletedIssue(
db: Db,
companyId: string,
completedIssueId: string,
completedChannelId: string | null | undefined,
opts: {
heartbeat?: ReturnType<typeof heartbeatService>;
actor?: HeadlessActorContext;
},
): Promise<void> {
const channelIds = new Set<string>();
if (completedChannelId) {
channelIds.add(completedChannelId);
}
const depChannels = await db
.select({ channelId: issues.channelId })
.from(issueRelations)
.innerJoin(issues, eq(issues.id, issueRelations.relatedIssueId))
.where(
and(
eq(issueRelations.companyId, companyId),
eq(issueRelations.issueId, completedIssueId),
eq(issueRelations.type, "blocks"),
),
);
for (const row of depChannels) {
if (row.channelId) {
channelIds.add(row.channelId);
}
}
for (const chId of channelIds) {
await dispatchManagedChannelPool(db, companyId, chId, opts);
}
}
export async function dispatchManagedChannelPoolBestEffort(
db: Db,
companyId: string,
channelId: string,
opts: {
heartbeat?: ReturnType<typeof heartbeatService>;
actor?: HeadlessActorContext;
},
): Promise<void> {
await dispatchManagedChannelPool(db, companyId, channelId, opts).catch((err) => {
logger.warn(
{ err, companyId, channelId },
"managed channel pool dispatch failed; background worker will retry",
);
});
}
export async function dispatchManagedChannelPoolsForCompletedIssueBestEffort(
db: Db,
companyId: string,
completedIssueId: string,
completedChannelId: string | null | undefined,
opts: {
heartbeat?: ReturnType<typeof heartbeatService>;
actor?: HeadlessActorContext;
},
): Promise<void> {
await dispatchManagedChannelPoolsForCompletedIssue(
db,
companyId,
completedIssueId,
completedChannelId,
opts,
).catch((err) => {
logger.warn(
{ err, companyId, completedIssueId, completedChannelId },
"managed channel pool completion dispatch failed; background worker will retry",
);
});
}
@@ -0,0 +1,513 @@
import { and, eq, inArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
activityLog,
channels,
issueComments,
issueRelations,
issues,
} from "@paperclipai/db";
import {
TaskDependenciesMutationSchema,
type IssueStatus,
type TaskDependenciesView,
type TaskDependencyItemView,
} from "@paperclipai/shared";
import { badRequest, conflict, notFound } from "../errors.js";
import { authorizationService, type AuthorizationActor } from "./authorization.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import {
allowsUnchanneledScope,
appendBoardEvent,
assertIssueChannelScopeAccess,
canAccessChannel,
enforceHeadlessScopes,
getLatestCompanyEventCursor,
publishCommittedBoardEvent,
resolveIssueByIdOrIdentifier,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
import { extractClaimToken, verifyClaimToken } from "./headless-task-queue.js";
function activityActorFields(actor: HeadlessActorContext) {
return {
actorType: actor.principalType === "agent" ? ("agent" as const) : ("user" as const),
actorId:
actor.principalType === "agent"
? actor.agentId ?? "unknown-agent"
: actor.userId ?? "board",
agentId: actor.agentId ?? null,
responsibleUserId: actor.responsibleUserId ?? null,
};
}
function commentAuthorFields(actor: HeadlessActorContext) {
return {
authorType: actor.principalType === "agent" ? ("agent" as const) : ("user" as const),
authorAgentId: actor.agentId ?? null,
authorUserId: actor.agentId ? null : (actor.userId ?? null),
actorProfile: actor.actorProfile ?? null,
};
}
function isChannelAllowedByScopes(
actor: Pick<HeadlessActorContext, "scopes" | "keyScope">,
channelPath: string,
): boolean {
try {
enforceHeadlessScopes(actor, { channelPath });
return true;
} catch {
return false;
}
}
function toAuthorizationActor(actor: HeadlessActorContext): AuthorizationActor {
if (actor.principalType === "agent" && actor.agentId) {
return {
type: "agent",
agentId: actor.agentId,
companyId: actor.companyId,
};
}
if (actor.principalType === "local_trusted") {
return {
type: "board",
userId: actor.userId ?? "local-board",
source: "local_implicit",
isInstanceAdmin: true,
};
}
return {
type: "board",
userId: actor.userId ?? "unknown-user",
source: "session",
isInstanceAdmin: actor.isInstanceAdmin,
};
}
async function canReadDependencyIssue(
dbOrTx: DbOrTx,
actor: HeadlessActorContext,
companyId: string,
row: {
id: string;
projectId: string | null;
parentId: string | null;
assigneeAgentId: string | null;
assigneeUserId: string | null;
},
): Promise<boolean> {
const decision = await authorizationService(dbOrTx as unknown as Db).decide({
action: "issue:read",
actor: toAuthorizationActor(actor),
resource: {
type: "issue",
companyId,
issueId: row.id,
projectId: row.projectId,
parentIssueId: row.parentId,
assigneeAgentId: row.assigneeAgentId,
assigneeUserId: row.assigneeUserId,
},
scope: { companyId },
});
return decision.allowed;
}
async function filterVisibleDependencyItems(
dbOrTx: DbOrTx,
companyId: string,
actor: HeadlessActorContext,
rows: Array<{
id: string;
identifier: string | null;
title: string;
status: string;
channelId: string | null;
projectId: string | null;
parentId: string | null;
assigneeAgentId: string | null;
assigneeUserId: string | null;
}>,
): Promise<TaskDependencyItemView[]> {
if (rows.length === 0) return [];
const channelIds = Array.from(
new Set(rows.map((r) => r.channelId).filter((id): id is string => Boolean(id))),
);
const channelMap = new Map<string, typeof channels.$inferSelect>();
if (channelIds.length > 0) {
const chRows = await dbOrTx
.select()
.from(channels)
.where(inArray(channels.id, channelIds));
for (const ch of chRows) {
channelMap.set(ch.id, ch);
}
}
const unchanneledAllowed = allowsUnchanneledScope(actor);
const visible: TaskDependencyItemView[] = [];
for (const row of rows) {
if (row.channelId) {
const ch = channelMap.get(row.channelId);
if (ch) {
if (!isChannelAllowedByScopes(actor, ch.path)) continue;
if (!(await canAccessChannel(dbOrTx, ch, actor))) continue;
}
} else if (!unchanneledAllowed) {
continue;
}
if (!(await canReadDependencyIssue(dbOrTx, actor, companyId, row))) {
continue;
}
visible.push({
id: row.id,
identifier: row.identifier ?? row.id,
title: row.title,
status: row.status as IssueStatus,
});
}
return visible;
}
async function loadDependenciesView(
dbOrTx: DbOrTx,
issue: typeof issues.$inferSelect,
actor: HeadlessActorContext,
cursor: string,
): Promise<TaskDependenciesView> {
const [incoming, outgoing] = await Promise.all([
dbOrTx
.select({
id: issues.id,
identifier: issues.identifier,
title: issues.title,
status: issues.status,
channelId: issues.channelId,
projectId: issues.projectId,
parentId: issues.parentId,
assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId,
})
.from(issueRelations)
.innerJoin(issues, eq(issues.id, issueRelations.issueId))
.where(
and(
eq(issueRelations.companyId, issue.companyId),
eq(issueRelations.relatedIssueId, issue.id),
eq(issueRelations.type, "blocks"),
),
),
dbOrTx
.select({
id: issues.id,
identifier: issues.identifier,
title: issues.title,
status: issues.status,
channelId: issues.channelId,
projectId: issues.projectId,
parentId: issues.parentId,
assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId,
})
.from(issueRelations)
.innerJoin(issues, eq(issues.id, issueRelations.relatedIssueId))
.where(
and(
eq(issueRelations.companyId, issue.companyId),
eq(issueRelations.issueId, issue.id),
eq(issueRelations.type, "blocks"),
),
),
]);
const [blockedBy, blocks] = await Promise.all([
filterVisibleDependencyItems(dbOrTx, issue.companyId, actor, incoming),
filterVisibleDependencyItems(dbOrTx, issue.companyId, actor, outgoing),
]);
return {
issueId: issue.id,
identifier: issue.identifier ?? issue.id,
status: issue.status as IssueStatus,
blockedBy,
blocks,
cursor,
};
}
async function wouldIntroduceDependencyCycle(
tx: DbOrTx,
companyId: string,
targetIssueId: string,
candidateBlockerIds: string[],
): Promise<boolean> {
// Adding edge: blocker -> targetIssueId.
// A cycle exists iff targetIssueId can already reach any candidateBlocker via existing `blocks` edges.
const targetSet = new Set(candidateBlockerIds);
if (targetSet.has(targetIssueId)) return true;
const visited = new Set<string>([targetIssueId]);
let frontier: string[] = [targetIssueId];
while (frontier.length > 0) {
const rows = await tx
.select({ relatedIssueId: issueRelations.relatedIssueId })
.from(issueRelations)
.where(
and(
eq(issueRelations.companyId, companyId),
inArray(issueRelations.issueId, frontier),
eq(issueRelations.type, "blocks"),
),
);
const nextFrontier: string[] = [];
for (const row of rows) {
if (targetSet.has(row.relatedIssueId)) return true;
if (!visited.has(row.relatedIssueId)) {
visited.add(row.relatedIssueId);
nextFrontier.push(row.relatedIssueId);
}
}
frontier = nextFrontier;
}
return false;
}
export async function listTaskDependencies(
db: Db,
issueId: string,
actor: HeadlessActorContext,
): Promise<TaskDependenciesView> {
enforceHeadlessScopes(actor, { action: "read" });
const [issue] = await db
.select()
.from(issues)
.where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId)))
.limit(1);
if (!issue) {
throw notFound("Issue not found");
}
await assertIssueChannelScopeAccess(db, issue, actor);
const cursor = await getLatestCompanyEventCursor(db, issue.companyId);
return loadDependenciesView(db, issue, actor, cursor);
}
export async function mutateTaskDependencies(
db: Db,
issueId: string,
actor: HeadlessActorContext,
rawInput: unknown,
headerToken?: string,
): Promise<TaskDependenciesView> {
enforceHeadlessScopes(actor, { action: "tasks.dependencies" });
const parsed = TaskDependenciesMutationSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
);
}
const input = parsed.data;
const token = extractClaimToken(input.claimToken, headerToken);
// Resolve and authorize bounded, deduplicated dependency references BEFORE
// taking the company-wide dependency advisory lock so per-element lookups
// and authorization checks never hold the lock.
const uniqueAddRefs = Array.from(new Set((input.add ?? []).map((r) => r.trim()).filter(Boolean)));
const uniqueRemoveRefs = Array.from(
new Set((input.remove ?? []).map((r) => r.trim()).filter(Boolean)),
);
const addIds: string[] = [];
for (const ref of uniqueAddRefs) {
const dep = await resolveIssueByIdOrIdentifier(db, ref, actor.companyId);
await assertIssueChannelScopeAccess(db, dep, actor);
if (!(await canReadDependencyIssue(db, actor, actor.companyId, dep))) {
throw notFound(`Issue '${ref}' not found`);
}
if (dep.id === issueId) {
throw badRequest("A task cannot depend on itself", {
code: "cyclic_dependencies",
});
}
addIds.push(dep.id);
}
const removeIds: string[] = [];
for (const ref of uniqueRemoveRefs) {
const dep = await resolveIssueByIdOrIdentifier(db, ref, actor.companyId);
await assertIssueChannelScopeAccess(db, dep, actor);
if (!(await canReadDependencyIssue(db, actor, actor.companyId, dep))) {
throw notFound(`Issue '${ref}' not found`);
}
removeIds.push(dep.id);
}
const committed = await db.transaction(async (tx) => {
// Serialize company dependency graph mutations before locking/checking cycles
// so concurrent requests on different target issues cannot create a cycle.
await tx.execute(
sql`SELECT pg_advisory_xact_lock(hashtextextended(${`${actor.companyId}:issue_deps`}, 0))`,
);
await tx.execute(
sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`,
);
const [issue] = await tx
.select()
.from(issues)
.where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId)));
if (!issue) {
throw notFound("Issue not found");
}
const { channel: targetChannel } = await assertIssueChannelScopeAccess(
tx,
issue,
actor,
);
const epochMatches =
input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch;
const hadActiveLease = issue.claimTokenHash !== null;
if (hadActiveLease) {
if (input.releaseLease || token !== undefined || input.claimEpoch !== undefined) {
if (
issue.status !== "in_progress" ||
!verifyClaimToken(issue.claimTokenHash, token) ||
!epochMatches
) {
throw conflict("claim_lost", {
code: "claim_lost",
currentEpoch: Number(issue.claimEpoch ?? 0),
status: issue.status,
});
}
}
} else if (token !== undefined || !epochMatches) {
// Reject stale supplied credentials even when no lease currently exists,
// while allowing `releaseLease: true` with no credentials on an unclaimed task.
throw conflict("claim_lost", {
code: "claim_lost",
currentEpoch: Number(issue.claimEpoch ?? 0),
status: issue.status,
});
}
if (addIds.length > 0) {
const hasCycle = await wouldIntroduceDependencyCycle(
tx,
issue.companyId,
issue.id,
addIds,
);
if (hasCycle) {
throw badRequest("Adding dependency would create a cycle", {
code: "cyclic_dependencies",
});
}
await tx
.insert(issueRelations)
.values(
Array.from(new Set(addIds)).map((blockerId) => ({
companyId: issue.companyId,
issueId: blockerId,
relatedIssueId: issue.id,
type: "blocks" as const,
createdByAgentId: actor.agentId ?? null,
createdByUserId: actor.agentId ? null : (actor.userId ?? null),
})),
)
.onConflictDoNothing();
}
if (removeIds.length > 0) {
if (issue.channelId) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, issue.channelId);
}
await tx
.delete(issueRelations)
.where(
and(
eq(issueRelations.companyId, issue.companyId),
eq(issueRelations.relatedIssueId, issue.id),
eq(issueRelations.type, "blocks"),
inArray(issueRelations.issueId, removeIds),
),
);
}
let currentIssue = issue;
if (input.releaseLease && issue.claimTokenHash !== null) {
const now = new Date();
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
const [updated] = await tx
.update(issues)
.set({
status: "todo",
claimEpoch: Number(issue.claimEpoch ?? 0) + 1,
claimTokenHash: null,
claimLeasedAt: null,
claimLeaseExpiresAt: null,
claimHolderAgentId: null,
claimHolderUserId: null,
claimHolderProfile: null,
claimAttemptCount: Math.max(0, (issue.claimAttemptCount ?? 0) - 1),
updatedAt: now,
})
.where(eq(issues.id, issue.id))
.returning();
currentIssue = updated!;
}
if (input.comment?.trim()) {
await tx.insert(issueComments).values({
companyId: issue.companyId,
issueId: issue.id,
body: input.comment.trim(),
...commentAuthorFields(actor),
});
}
await tx.insert(activityLog).values({
companyId: issue.companyId,
...activityActorFields(actor),
action: "issue.dependencies_changed",
entityType: "issue",
entityId: issue.id,
details: {
added: addIds,
removed: removeIds,
releasedLease: Boolean(input.releaseLease && issue.claimTokenHash !== null),
},
});
const event = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.dependencies_changed",
channelId: currentIssue.channelId,
channelPath: targetChannel?.path ?? null,
issueId: currentIssue.id,
identifier: currentIssue.identifier ?? currentIssue.id,
actor,
payload: {
added: addIds,
removed: removeIds,
status: currentIssue.status,
},
});
const view = await loadDependenciesView(tx, currentIssue, actor, event.cursor);
return { view, event };
});
publishCommittedBoardEvent(committed.event);
return committed.view;
}
+187 -20
View File
@@ -10,12 +10,14 @@ import {
issueLabels,
issueRelations,
issues,
issueThreadInteractions,
issueWorkProducts,
labels,
projects,
toolActionRequests,
} from "@paperclipai/db";
import {
applyKvLabelMutation,
BUILT_IN_COMPANY_SCHEMAS,
normalizeChannelPath,
parseDurationMs,
@@ -30,6 +32,7 @@ import {
type BoardEventType,
type BoardEventView,
type ChannelQueueConfig,
type ClaimableTaskStatus,
type HeadlessIssueView,
type LabelFilterExpr,
type SchemaBlock,
@@ -37,6 +40,7 @@ import {
} from "@paperclipai/shared";
import { badRequest, conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { ensureChannel, validateWritableKvLabelsOrThrow } from "./headless-channels.js";
import { issueTreeControlService } from "./issue-tree-control.js";
import { listIssueDependencyReadinessMap } from "./issues.js";
import { assertRequiredQualityReviewComplete } from "./required-quality-review.js";
@@ -65,6 +69,10 @@ const CLAIM_WAKE_EVENTS = new Set<BoardEventType>([
"task.lease_released",
"task.lease_expired_requeued",
"task.unblocked",
"task.assigned",
"task.handed_off",
"task.reopened",
"task.dependencies_changed",
"interaction.resolved",
"labels.changed",
]);
@@ -296,6 +304,18 @@ export async function claimTask(
? await resolveProjectReference(db, companyId, parsed.projectId, actor)
: null;
const statusSet = new Set<ClaimableTaskStatus>();
if (parsed.status !== undefined) {
const items = Array.isArray(parsed.status) ? parsed.status : [parsed.status];
for (const s of items) statusSet.add(s);
}
if (parsed.statuses !== undefined) {
for (const s of parsed.statuses) statusSet.add(s);
}
const allowedStatuses: ClaimableTaskStatus[] =
statusSet.size > 0 ? Array.from(statusSet) : ["todo"];
const assigneeMode = parsed.assignee ?? "unassigned";
const tryClaimOnce = async (): Promise<TaskClaimView | null> => {
const committed = await db.transaction(async (tx) => {
let lockedIssue: typeof issues.$inferSelect | undefined;
@@ -367,12 +387,44 @@ export async function claimTask(
reason: "assigned_to_other_user",
});
}
if (fresh.status !== "todo") {
if (!allowedStatuses.includes(fresh.status as ClaimableTaskStatus)) {
throw conflict("task_not_claimable", {
code: "task_not_claimable",
status: fresh.status,
});
}
if (
fresh.claimTokenHash !== null ||
fresh.claimLeaseExpiresAt !== null ||
fresh.checkoutRunId !== null ||
fresh.executionRunId !== null
) {
throw conflict("task_not_claimable", {
code: "task_not_claimable",
status: fresh.status,
reason: "already_claimed_or_running",
});
}
if (fresh.status === "in_review") {
const [pendingInteraction] = await tx
.select({ id: issueThreadInteractions.id })
.from(issueThreadInteractions)
.where(
and(
eq(issueThreadInteractions.companyId, companyId),
eq(issueThreadInteractions.issueId, fresh.id),
eq(issueThreadInteractions.status, "pending"),
),
)
.limit(1);
if (pendingInteraction) {
throw conflict("task_not_claimable", {
code: "task_not_claimable",
status: fresh.status,
reason: "pending_interaction",
});
}
}
const readiness = (
await listIssueDependencyReadinessMap(
@@ -480,9 +532,14 @@ export async function claimTask(
const conditions = [
sql`i.company_id = ${companyId}`,
sql`i.status = 'todo'`,
sql`i.assignee_agent_id IS NULL`,
sql`i.assignee_user_id IS NULL`,
sql`i.status IN (${sql.join(
allowedStatuses.map((s) => sql`${s}`),
sql`, `,
)})`,
sql`i.claim_token_hash IS NULL`,
sql`i.claim_lease_expires_at IS NULL`,
sql`i.checkout_run_id IS NULL`,
sql`i.execution_run_id IS NULL`,
sql`i.hidden_at IS NULL`,
sql`i.conversation_agent_id IS NULL`,
sql`NOT EXISTS (
@@ -512,6 +569,44 @@ export async function claimTask(
)`,
];
if (assigneeMode === "unassigned") {
conditions.push(sql`i.assignee_agent_id IS NULL`);
conditions.push(sql`i.assignee_user_id IS NULL`);
} else if (assigneeMode === "me") {
if (actor.agentId) {
conditions.push(sql`i.assignee_agent_id = ${actor.agentId}`);
} else if (actor.userId) {
conditions.push(sql`i.assignee_user_id = ${actor.userId}`);
} else {
return null;
}
} else if (assigneeMode === "any") {
if (actor.agentId) {
conditions.push(
sql`((i.assignee_agent_id IS NULL AND i.assignee_user_id IS NULL) OR i.assignee_agent_id = ${actor.agentId})`,
);
} else if (actor.userId) {
conditions.push(
sql`((i.assignee_agent_id IS NULL AND i.assignee_user_id IS NULL) OR i.assignee_user_id = ${actor.userId})`,
);
} else {
conditions.push(sql`i.assignee_agent_id IS NULL`);
conditions.push(sql`i.assignee_user_id IS NULL`);
}
}
if (allowedStatuses.includes("in_review")) {
conditions.push(
sql`(i.status <> 'in_review' OR NOT EXISTS (
SELECT 1
FROM issue_thread_interactions iti
WHERE iti.company_id = i.company_id
AND iti.issue_id = i.id
AND iti.status = 'pending'
))`,
);
}
if (eligibleChannelIds !== null) {
conditions.push(
sql`i.channel_id IN (${sql.join(
@@ -909,13 +1004,61 @@ export async function releaseTaskClaim(
}
const now = new Date();
let finalChannel = targetChannel;
if (input.channel !== undefined) {
finalChannel = await ensureChannel(tx, issue.companyId, actor, {
path: input.channel,
});
}
let nextKvLabels = (issue.kvLabels ?? {}) as Record<string, string>;
let labelsChanged = false;
if (input.labels !== undefined || (input.unsetLabels && input.unsetLabels.length > 0)) {
if (input.labels) {
validateWritableKvLabelsOrThrow(input.labels);
}
if (input.unsetLabels) {
for (const k of input.unsetLabels) {
if (k.startsWith("paperclip.")) {
throw badRequest("Label keys starting with 'paperclip.' are reserved", {
error: "reserved_label",
code: "reserved_label",
key: k,
});
}
}
}
const applied = applyKvLabelMutation(nextKvLabels, {
...(input.labels ? { set: input.labels } : {}),
...(input.unsetLabels ? { unset: input.unsetLabels } : {}),
});
if (!applied.ok) {
throw conflict("label_conflict", {
code: "label_conflict",
conflictingKeys: applied.conflictingKeys,
});
}
nextKvLabels = applied.labels;
labelsChanged = true;
}
const nextStatus = input.status ?? "todo";
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
if (nextStatus === "todo" && (finalChannel?.id ?? issue.channelId)) {
await notifyDeliveryWork(
tx,
DELIVERY_QUEUES.managedChannelPools,
(finalChannel?.id ?? issue.channelId)!,
);
}
const nextEpoch = Number(issue.claimEpoch ?? 0) + 1;
const [updated] = await tx
.update(issues)
.set({
status: "todo",
status: nextStatus,
...(finalChannel ? { channelId: finalChannel.id } : {}),
...(labelsChanged ? { kvLabels: nextKvLabels } : {}),
claimEpoch: nextEpoch,
claimTokenHash: null,
claimLeasedAt: null,
@@ -929,6 +1072,13 @@ export async function releaseTaskClaim(
.where(eq(issues.id, issue.id))
.returning();
if (finalChannel && finalChannel.id !== issue.channelId) {
await tx
.update(channels)
.set({ lastActivityAt: now, updatedAt: now })
.where(eq(channels.id, finalChannel.id));
}
if (input.comment?.trim()) {
await tx.insert(issueComments).values({
companyId: issue.companyId,
@@ -947,6 +1097,8 @@ export async function releaseTaskClaim(
entityId: updated!.id,
details: {
claimEpoch: Number(updated!.claimEpoch ?? 0),
status: nextStatus,
...(finalChannel ? { channel: finalChannel.path } : {}),
},
});
@@ -954,31 +1106,37 @@ export async function releaseTaskClaim(
companyId: issue.companyId,
type: "task.lease_released",
channelId: updated!.channelId,
channelPath: targetChannel?.path ?? null,
channelPath: finalChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
claimEpoch: Number(updated!.claimEpoch ?? 0),
},
});
const readyEvent = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.ready",
channelId: updated!.channelId,
channelPath: targetChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
status: nextStatus,
kvLabels: updated!.kvLabels ?? {},
},
});
const events: BoardEventView[] = [releasedEvent];
if (nextStatus === "todo") {
const readyEvent = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.ready",
channelId: updated!.channelId,
channelPath: finalChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
kvLabels: updated!.kvLabels ?? {},
},
});
events.push(readyEvent);
}
return {
events: [releasedEvent, readyEvent],
cursor: readyEvent.cursor,
events,
cursor: events[events.length - 1]!.cursor,
};
});
@@ -1187,6 +1345,11 @@ export async function completeTaskClaim(
if (issue.claimTokenHash !== null) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
}
await notifyDeliveryWork(
tx,
DELIVERY_QUEUES.managedChannelPools,
JSON.stringify({ companyId: issue.companyId, issueId: issue.id }),
);
const [updated] = await tx
.update(issues)
@@ -1760,6 +1923,10 @@ export function createClaimLeaseExpiryWorker(db: Db) {
const shouldRequeue = attemptCount < maxAttempts;
const nextEpoch = Number(row.claimEpoch ?? 0) + 1;
if (shouldRequeue && row.channelId) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, row.channelId);
}
await tx
.update(issues)
.set({
@@ -0,0 +1,983 @@
import { and, eq, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
activityLog,
channels,
issueComments,
issues,
} from "@paperclipai/db";
import {
applyKvLabelMutation,
TaskAssignSchema,
TaskCancelSchema,
TaskHandoffSchema,
TaskReopenSchema,
type BoardEventView,
type HeadlessIssueView,
type IssueStatus,
} from "@paperclipai/shared";
import { badRequest, conflict, forbidden, notFound } from "../errors.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import type { heartbeatService } from "./heartbeat.js";
import { issueTreeControlService } from "./issue-tree-control.js";
import {
ensureChannel,
resolveAssigneeAgent,
validateWritableKvLabelsOrThrow,
} from "./headless-channels.js";
import { dispatchManagedChannelPoolBestEffort } from "./headless-channel-admin.js";
import {
appendBoardEvent,
assertIssueChannelScopeAccess,
enforceHeadlessScopes,
loadHeadlessIssueView,
publishCommittedBoardEvent,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
import { assertSchemaExists } from "./headless-schemas.js";
import { extractClaimToken, verifyClaimToken } from "./headless-task-queue.js";
function hasActiveWork(issue: {
claimTokenHash: string | null;
checkoutRunId: string | null;
executionRunId: string | null;
}): boolean {
return (
issue.claimTokenHash !== null ||
issue.checkoutRunId !== null ||
issue.executionRunId !== null
);
}
function activityActorFields(actor: HeadlessActorContext) {
return {
actorType: actor.principalType === "agent" ? ("agent" as const) : ("user" as const),
actorId:
actor.principalType === "agent"
? actor.agentId ?? "unknown-agent"
: actor.userId ?? "board",
agentId: actor.agentId ?? null,
responsibleUserId: actor.responsibleUserId ?? null,
};
}
function commentAuthorFields(actor: HeadlessActorContext) {
return {
authorType: actor.principalType === "agent" ? ("agent" as const) : ("user" as const),
authorAgentId: actor.agentId ?? null,
authorUserId: actor.agentId ? null : (actor.userId ?? null),
actorProfile: actor.actorProfile ?? null,
};
}
function assertNoReservedKeys(keys: string[]): void {
for (const key of keys) {
if (key.startsWith("paperclip.")) {
throw badRequest("Label keys starting with 'paperclip.' are reserved", {
error: "reserved_label",
code: "reserved_label",
key,
});
}
}
}
async function wakeAssignedAgent(
heartbeat: ReturnType<typeof heartbeatService> | undefined,
opts: {
issueId: string;
assigneeAgentId: string;
reason: string;
actor: HeadlessActorContext;
channelPath?: string | null;
},
): Promise<void> {
if (!heartbeat) return;
await heartbeat
.wakeup(opts.assigneeAgentId, {
source: "assignment",
triggerDetail: "system",
reason: opts.reason,
payload: {
issueId: opts.issueId,
...(opts.channelPath ? { channelPath: opts.channelPath } : {}),
},
idempotencyKey: `assign:${opts.issueId}:${opts.assigneeAgentId}:${Date.now()}`,
requestedByActorType: opts.actor.principalType === "agent" ? "agent" : "user",
requestedByActorId:
opts.actor.principalType === "agent"
? opts.actor.agentId ?? "unknown-agent"
: opts.actor.userId ?? "board",
contextSnapshot: {
issueId: opts.issueId,
taskId: opts.issueId,
wakeReason: opts.reason,
},
})
.catch(() => {
// Best-effort wakeup; assignment is already durably committed
});
}
export async function assignTask(
db: Db,
issueId: string,
actor: HeadlessActorContext,
rawInput: unknown,
opts?: {
heartbeat?: ReturnType<typeof heartbeatService>;
authorizeTargetAssignee?: (tx: DbOrTx, targetAgentId: string | null) => Promise<void>;
},
): Promise<HeadlessIssueView> {
enforceHeadlessScopes(actor, { action: "tasks.assign" });
const parsed = TaskAssignSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
);
}
const input = parsed.data;
const wantsUnassign =
input.unassign === true ||
input.assignee === null ||
input.assigneeAgentId === null;
if (!wantsUnassign && !input.assignee && !input.assigneeAgentId) {
throw badRequest("Provide 'assignee', 'assigneeAgentId', or 'unassign: true'");
}
const committed = await db.transaction(async (tx) => {
await tx.execute(
sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`,
);
const [issue] = await tx
.select()
.from(issues)
.where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId)));
if (!issue) {
throw notFound("Issue not found");
}
const { channel: targetChannel } = await assertIssueChannelScopeAccess(
tx,
issue,
actor,
);
if (hasActiveWork(issue) && !input.force) {
throw conflict(
"Task currently has an active lease or execution run; pass --force to fence the active worker and reassign",
{
code: "task_claimed",
claimEpoch: Number(issue.claimEpoch ?? 0),
next: [`pc tasks assign ${issue.identifier ?? issue.id} --force`],
},
);
}
const resolvedAgentId = wantsUnassign
? null
: await resolveAssigneeAgent(tx, issue.companyId, {
...(input.assigneeAgentId ? { assigneeAgentId: input.assigneeAgentId } : {}),
...(input.assignee ? { for: input.assignee } : {}),
});
if (opts?.authorizeTargetAssignee) {
await opts.authorizeTargetAssignee(tx, resolvedAgentId);
}
const now = new Date();
const clearingLease = hasActiveWork(issue);
const shouldPromoteBacklog =
resolvedAgentId !== null && issue.status === "backlog" && !input.keepStatus;
const shouldReturnLeasedToTodo =
clearingLease && issue.status === "in_progress";
const nextStatus: IssueStatus = shouldPromoteBacklog || shouldReturnLeasedToTodo
? "todo"
: (issue.status as IssueStatus);
if (clearingLease) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
}
if (resolvedAgentId === null && nextStatus === "todo" && issue.channelId) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, issue.channelId);
}
const [updated] = await tx
.update(issues)
.set({
assigneeAgentId: resolvedAgentId,
assigneeUserId: null,
status: nextStatus,
...(clearingLease
? {
claimEpoch: Number(issue.claimEpoch ?? 0) + 1,
claimTokenHash: null,
claimLeasedAt: null,
claimLeaseExpiresAt: null,
claimHolderAgentId: null,
claimHolderUserId: null,
claimHolderProfile: null,
checkoutRunId: null,
executionRunId: null,
}
: {}),
updatedAt: now,
})
.where(eq(issues.id, issue.id))
.returning();
if (input.comment?.trim()) {
await tx.insert(issueComments).values({
companyId: issue.companyId,
issueId: issue.id,
body: input.comment.trim(),
...commentAuthorFields(actor),
});
}
await tx.insert(activityLog).values({
companyId: issue.companyId,
...activityActorFields(actor),
action: resolvedAgentId ? "issue.assigned" : "issue.unassigned",
entityType: "issue",
entityId: updated!.id,
details: {
assigneeAgentId: resolvedAgentId,
status: nextStatus,
forcedLeaseClear: clearingLease,
},
});
const events: BoardEventView[] = [];
const assignEvent = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.assigned",
channelId: updated!.channelId,
channelPath: targetChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
assigneeAgentId: resolvedAgentId,
status: nextStatus,
kvLabels: updated!.kvLabels ?? {},
},
});
events.push(assignEvent);
if (resolvedAgentId === null && nextStatus === "todo") {
const readyEvent = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.ready",
channelId: updated!.channelId,
channelPath: targetChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
kvLabels: updated!.kvLabels ?? {},
},
});
events.push(readyEvent);
}
const view = await loadHeadlessIssueView(
tx,
updated!.id,
events[events.length - 1]!.cursor,
);
return {
view,
events,
resolvedAgentId,
nextStatus,
channelId: updated!.channelId,
channelPath: targetChannel?.path ?? null,
};
});
for (const ev of committed.events) {
publishCommittedBoardEvent(ev);
}
if (
committed.resolvedAgentId &&
(committed.nextStatus === "todo" || committed.nextStatus === "in_progress")
) {
await wakeAssignedAgent(opts?.heartbeat, {
issueId: committed.view.id,
assigneeAgentId: committed.resolvedAgentId,
reason: "issue_assigned",
actor,
channelPath: committed.channelPath,
});
} else if (
committed.resolvedAgentId === null &&
committed.nextStatus === "todo" &&
committed.channelId
) {
await dispatchManagedChannelPoolBestEffort(db, actor.companyId, committed.channelId, {
heartbeat: opts?.heartbeat,
actor,
});
}
return committed.view;
}
export async function handoffTask(
db: Db,
issueId: string,
actor: HeadlessActorContext,
rawInput: unknown,
headerToken?: string,
opts?: {
heartbeat?: ReturnType<typeof heartbeatService>;
authorizeTargetAssignee?: (tx: DbOrTx, targetAgentId: string | null) => Promise<void>;
},
): Promise<HeadlessIssueView> {
enforceHeadlessScopes(actor, { action: "tasks.handoff" });
const parsed = TaskHandoffSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
);
}
const input = parsed.data;
const token = extractClaimToken(input.claimToken, headerToken);
if (input.labels) {
validateWritableKvLabelsOrThrow(input.labels);
}
if (input.unsetLabels) {
assertNoReservedKeys(input.unsetLabels);
}
const committed = await db.transaction(async (tx) => {
await tx.execute(
sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`,
);
const [issue] = await tx
.select()
.from(issues)
.where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId)));
if (!issue) {
throw notFound("Issue not found");
}
const { channel: sourceChannel } = await assertIssueChannelScopeAccess(
tx,
issue,
actor,
);
if (issue.status === "done" || issue.status === "cancelled") {
throw conflict("Cannot hand off a completed or cancelled task; reopen it first", {
code: "task_finished",
status: issue.status,
});
}
// Fence active lease if one exists
const epochMatches =
input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch;
const hadActiveLease = issue.claimTokenHash !== null;
if (hadActiveLease) {
if (
issue.status !== "in_progress" ||
!verifyClaimToken(issue.claimTokenHash, token) ||
!epochMatches
) {
throw conflict("claim_lost", {
code: "claim_lost",
currentEpoch: Number(issue.claimEpoch ?? 0),
status: issue.status,
});
}
} else if (issue.checkoutRunId !== null || issue.executionRunId !== null) {
throw conflict("Task currently has an active execution run", {
code: "task_claimed",
status: issue.status,
});
} else if (token !== undefined || !epochMatches) {
throw conflict("claim_lost", {
code: "claim_lost",
currentEpoch: Number(issue.claimEpoch ?? 0),
status: issue.status,
});
}
let finalChannel = sourceChannel;
if (input.channel !== undefined) {
finalChannel = await ensureChannel(tx, issue.companyId, actor, {
path: input.channel,
});
}
let nextKvLabels = (issue.kvLabels ?? {}) as Record<string, string>;
let labelsChanged = false;
if (
input.labels !== undefined ||
(input.unsetLabels && input.unsetLabels.length > 0) ||
input.ifLabels !== undefined
) {
const applied = applyKvLabelMutation(nextKvLabels, {
...(input.labels ? { set: input.labels } : {}),
...(input.unsetLabels ? { unset: input.unsetLabels } : {}),
...(input.ifLabels ? { if: input.ifLabels } : {}),
});
if (!applied.ok) {
throw conflict("label_conflict", {
code: "label_conflict",
conflictingKeys: applied.conflictingKeys,
});
}
nextKvLabels = applied.labels;
labelsChanged = true;
}
let nextAssigneeAgentId = issue.assigneeAgentId;
let nextAssigneeUserId = issue.assigneeUserId;
let assigneeChanging = false;
if (input.unassign || input.assignee === null) {
nextAssigneeAgentId = null;
nextAssigneeUserId = null;
assigneeChanging = true;
} else if (input.assignee !== undefined) {
nextAssigneeAgentId = await resolveAssigneeAgent(tx, issue.companyId, {
for: input.assignee,
});
nextAssigneeUserId = null;
assigneeChanging = true;
}
if (assigneeChanging && opts?.authorizeTargetAssignee) {
await opts.authorizeTargetAssignee(tx, nextAssigneeAgentId);
}
let nextResultSchemaRef = issue.resultSchemaRef;
if (input.resultSchema !== undefined) {
if (input.resultSchema === null) {
nextResultSchemaRef = null;
} else {
const verified = await assertSchemaExists(
tx as unknown as Db,
issue.companyId,
input.resultSchema,
);
nextResultSchemaRef = verified;
}
}
const nextStatus: IssueStatus = input.status ?? "todo";
const now = new Date();
if (hadActiveLease) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
}
if (issue.channelId) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, issue.channelId);
}
if (
nextStatus === "todo" &&
nextAssigneeAgentId === null &&
nextAssigneeUserId === null &&
(finalChannel?.id ?? issue.channelId)
) {
await notifyDeliveryWork(
tx,
DELIVERY_QUEUES.managedChannelPools,
(finalChannel?.id ?? issue.channelId)!,
);
}
const nextEpoch = hadActiveLease
? Number(issue.claimEpoch ?? 0) + 1
: Number(issue.claimEpoch ?? 0);
const [updated] = await tx
.update(issues)
.set({
status: nextStatus,
channelId: finalChannel ? finalChannel.id : issue.channelId,
...(labelsChanged ? { kvLabels: nextKvLabels } : {}),
assigneeAgentId: nextAssigneeAgentId,
assigneeUserId: nextAssigneeUserId,
...(input.priority !== undefined ? { priority: input.priority } : {}),
resultSchemaRef: nextResultSchemaRef,
...(hadActiveLease
? {
claimEpoch: nextEpoch,
claimTokenHash: null,
claimLeasedAt: null,
claimLeaseExpiresAt: null,
claimHolderAgentId: null,
claimHolderUserId: null,
claimHolderProfile: null,
claimAttemptCount: Math.max(0, (issue.claimAttemptCount ?? 0) - 1),
}
: {}),
updatedAt: now,
})
.where(eq(issues.id, issue.id))
.returning();
if (finalChannel && finalChannel.id !== issue.channelId) {
await tx
.update(channels)
.set({ lastActivityAt: now, updatedAt: now })
.where(eq(channels.id, finalChannel.id));
}
if (input.comment?.trim()) {
await tx.insert(issueComments).values({
companyId: issue.companyId,
issueId: issue.id,
body: input.comment.trim(),
...commentAuthorFields(actor),
});
}
await tx.insert(activityLog).values({
companyId: issue.companyId,
...activityActorFields(actor),
action: "issue.handed_off",
entityType: "issue",
entityId: updated!.id,
details: {
fromChannel: sourceChannel?.path ?? null,
toChannel: finalChannel?.path ?? null,
status: nextStatus,
assigneeAgentId: nextAssigneeAgentId,
},
});
const events: BoardEventView[] = [];
const handoffEvent = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.handed_off",
channelId: updated!.channelId,
channelPath: finalChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
fromChannel: sourceChannel?.path ?? null,
toChannel: finalChannel?.path ?? null,
status: nextStatus,
assigneeAgentId: nextAssigneeAgentId,
kvLabels: updated!.kvLabels ?? {},
},
});
events.push(handoffEvent);
if (nextStatus === "todo" && nextAssigneeAgentId === null && nextAssigneeUserId === null) {
const readyEvent = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.ready",
channelId: updated!.channelId,
channelPath: finalChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
kvLabels: updated!.kvLabels ?? {},
},
});
events.push(readyEvent);
}
const view = await loadHeadlessIssueView(
tx,
updated!.id,
events[events.length - 1]!.cursor,
);
return {
view,
events,
nextAssigneeAgentId,
nextStatus,
channelId: updated!.channelId,
channelPath: finalChannel?.path ?? null,
};
});
for (const ev of committed.events) {
publishCommittedBoardEvent(ev);
}
if (committed.nextAssigneeAgentId && committed.nextStatus === "todo") {
await wakeAssignedAgent(opts?.heartbeat, {
issueId: committed.view.id,
assigneeAgentId: committed.nextAssigneeAgentId,
reason: "issue_handed_off",
actor,
channelPath: committed.channelPath,
});
} else if (
committed.nextAssigneeAgentId === null &&
committed.nextStatus === "todo" &&
committed.channelId
) {
await dispatchManagedChannelPoolBestEffort(db, actor.companyId, committed.channelId, {
heartbeat: opts?.heartbeat,
actor,
});
}
return committed.view;
}
export async function cancelTask(
db: Db,
issueId: string,
actor: HeadlessActorContext,
rawInput: unknown,
headerToken?: string,
): Promise<HeadlessIssueView> {
enforceHeadlessScopes(actor, { action: "tasks.cancel" });
const parsed = TaskCancelSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
);
}
const input = parsed.data;
const token = extractClaimToken(input.claimToken, headerToken);
const committed = await db.transaction(async (tx) => {
await tx.execute(
sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`,
);
const [issue] = await tx
.select()
.from(issues)
.where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId)));
if (!issue) {
throw notFound("Issue not found");
}
const { channel: targetChannel } = await assertIssueChannelScopeAccess(
tx,
issue,
actor,
);
const hadActiveLease = issue.claimTokenHash !== null;
const hadActiveRun = issue.checkoutRunId !== null || issue.executionRunId !== null;
const epochMatches =
input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch;
if (!input.force) {
if (hadActiveLease) {
if (!verifyClaimToken(issue.claimTokenHash, token) || !epochMatches) {
throw conflict(
"Task has an active lease held by another worker; pass --force to cancel anyway",
{
code: "task_claimed",
currentEpoch: Number(issue.claimEpoch ?? 0),
},
);
}
} else if (hadActiveRun) {
throw conflict(
"Task has an active execution run; pass --force to cancel anyway",
{
code: "task_claimed",
status: issue.status,
},
);
} else if (token !== undefined || !epochMatches) {
throw conflict("claim_lost", {
code: "claim_lost",
currentEpoch: Number(issue.claimEpoch ?? 0),
status: issue.status,
});
}
}
const now = new Date();
const clearingActiveWork = hadActiveLease || hadActiveRun;
if (clearingActiveWork) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
}
if (issue.channelId) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, issue.channelId);
}
const [updated] = await tx
.update(issues)
.set({
status: "cancelled",
cancelledAt: now,
...(clearingActiveWork
? {
claimEpoch: Number(issue.claimEpoch ?? 0) + 1,
claimTokenHash: null,
claimLeasedAt: null,
claimLeaseExpiresAt: null,
claimHolderAgentId: null,
claimHolderUserId: null,
claimHolderProfile: null,
checkoutRunId: null,
executionRunId: null,
}
: {}),
updatedAt: now,
})
.where(eq(issues.id, issue.id))
.returning();
if (input.reason?.trim()) {
await tx.insert(issueComments).values({
companyId: issue.companyId,
issueId: issue.id,
body: input.reason.trim(),
...commentAuthorFields(actor),
});
}
await tx.insert(activityLog).values({
companyId: issue.companyId,
...activityActorFields(actor),
action: "issue.cancelled",
entityType: "issue",
entityId: updated!.id,
details: {
...(input.reason?.trim() ? { reason: input.reason.trim() } : {}),
},
});
const event = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.cancelled",
channelId: updated!.channelId,
channelPath: targetChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
...(input.reason?.trim() ? { reason: input.reason.trim() } : {}),
kvLabels: updated!.kvLabels ?? {},
},
});
const view = await loadHeadlessIssueView(tx, updated!.id, event.cursor);
return { view, event };
});
publishCommittedBoardEvent(committed.event);
return committed.view;
}
export async function reopenTask(
db: Db,
issueId: string,
actor: HeadlessActorContext,
rawInput: unknown,
opts?: { heartbeat?: ReturnType<typeof heartbeatService> },
): Promise<HeadlessIssueView> {
enforceHeadlessScopes(actor, { action: "tasks.reopen" });
const parsed = TaskReopenSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
);
}
const input = parsed.data;
const targetStatus = input.status ?? "todo";
const committed = await db.transaction(async (tx) => {
await tx.execute(
sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`,
);
const [issue] = await tx
.select()
.from(issues)
.where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId)));
if (!issue) {
throw notFound("Issue not found");
}
const { channel: targetChannel } = await assertIssueChannelScopeAccess(
tx,
issue,
actor,
);
const isTerminal = issue.status === "done" || issue.status === "cancelled";
if (issue.claimTokenHash !== null || (!isTerminal && hasActiveWork(issue))) {
throw conflict("Cannot reopen a task that currently holds an active lease or run", {
code: "task_claimed",
status: issue.status,
});
}
if (actor.principalType === "agent") {
if (issue.status === "cancelled") {
throw forbidden(
"Cancelled tasks require explicit human or board restore authority to reopen",
{ code: "restore_authority_required", status: issue.status },
);
}
const trust = issue.sourceTrust as { level?: string; disposition?: string } | null;
if (trust?.level === "untrusted" || trust?.disposition === "quarantined") {
throw forbidden(
"Agents cannot reopen untrusted or quarantined tasks",
{ code: "untrusted_source_reopen_denied" },
);
}
}
const activePauseHold = await issueTreeControlService(db).getActivePauseHoldGate(
actor.companyId,
issue.id,
);
if (activePauseHold) {
throw conflict("Issue tree is currently paused", {
code: "issue_paused",
holdId: activePauseHold.holdId,
rootIssueId: activePauseHold.rootIssueId,
});
}
const blockerRows = await tx.execute<{ cnt: number }>(sql`
SELECT count(*)::int AS cnt
FROM issue_relations ir
INNER JOIN issues bi ON bi.id = ir.issue_id
WHERE ir.company_id = ${issue.companyId}
AND ir.related_issue_id = ${issue.id}
AND ir.type = 'blocks'
AND bi.status <> 'done'
`);
const hasOpenBlockers = Number(blockerRows[0]?.cnt ?? 0) > 0;
const now = new Date();
if (
targetStatus === "todo" &&
!hasOpenBlockers &&
!issue.assigneeAgentId &&
!issue.assigneeUserId &&
issue.channelId
) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, issue.channelId);
}
const [updated] = await tx
.update(issues)
.set({
status: targetStatus,
completedAt: null,
cancelledAt: null,
checkoutRunId: null,
executionRunId: null,
updatedAt: now,
})
.where(eq(issues.id, issue.id))
.returning();
if (input.comment?.trim()) {
await tx.insert(issueComments).values({
companyId: issue.companyId,
issueId: issue.id,
body: input.comment.trim(),
...commentAuthorFields(actor),
});
}
await tx.insert(activityLog).values({
companyId: issue.companyId,
...activityActorFields(actor),
action: "issue.reopened",
entityType: "issue",
entityId: updated!.id,
details: {
previousStatus: issue.status,
status: targetStatus,
},
});
const events: BoardEventView[] = [];
const reopenEvent = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.reopened",
channelId: updated!.channelId,
channelPath: targetChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
previousStatus: issue.status,
status: targetStatus,
kvLabels: updated!.kvLabels ?? {},
},
});
events.push(reopenEvent);
if (
targetStatus === "todo" &&
!hasOpenBlockers &&
!updated!.assigneeAgentId &&
!updated!.assigneeUserId
) {
const readyEvent = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.ready",
channelId: updated!.channelId,
channelPath: targetChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
kvLabels: updated!.kvLabels ?? {},
},
});
events.push(readyEvent);
}
const view = await loadHeadlessIssueView(
tx,
updated!.id,
events[events.length - 1]!.cursor,
);
return {
view,
events,
channelId: updated!.channelId,
assigneeAgentId: updated!.assigneeAgentId,
channelPath: targetChannel?.path ?? null,
hasOpenBlockers,
};
});
for (const ev of committed.events) {
publishCommittedBoardEvent(ev);
}
if (targetStatus === "todo" && !committed.hasOpenBlockers) {
if (committed.assigneeAgentId) {
await wakeAssignedAgent(opts?.heartbeat, {
issueId: committed.view.id,
assigneeAgentId: committed.assigneeAgentId,
reason: "issue_reopened",
actor,
channelPath: committed.channelPath,
});
} else if (committed.channelId) {
await dispatchManagedChannelPoolBestEffort(db, actor.companyId, committed.channelId, {
heartbeat: opts?.heartbeat,
actor,
});
}
}
return committed.view;
}
@@ -37,6 +37,7 @@ export async function notifyIssueRecovery(transaction: object,
...(scope.issueId ? { issueId: scope.issueId } : scope.everyTask ? { everyTask: true } : {}) });
for (const queue of COMPANY_QUEUES) await notifyDeliveryWork(transaction, queue, companyHint);
for (const queue of TASK_QUEUES) await notifyDeliveryWork(transaction, queue, taskHint);
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.managedChannelPools, taskHint);
}
/** An agent status change: the company queues, and on the task queues only
@@ -46,6 +47,7 @@ export async function notifyAgentRecovery(transaction: object, scope: { companyI
const agentHint = JSON.stringify({ companyId: scope.companyId, agentId: scope.agentId });
for (const queue of COMPANY_QUEUES) await notifyDeliveryWork(transaction, queue, companyHint);
for (const queue of TASK_QUEUES) await notifyDeliveryWork(transaction, queue, agentHint);
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.managedChannelPools, agentHint);
}
export async function notifyCompanyRecovery(transaction: object, companyId: string) {
@@ -275,15 +275,15 @@
"packages/shared/src/google-workspace-connectors.ts": "3338962075622b929f0fae18d8ca0333f88cf23a",
"packages/shared/src/google-workspace-setup-links.test.ts": "d86428b26e74e54ab2902d1a14c0f06f562de775",
"packages/shared/src/grok-bot.ts": "9de68f00e7926c397729ff62bf8e277f5a41c525",
"packages/shared/src/headless/channels.ts": "9db0d9cd0fe8b43478ab4585c5df47b310c5caa7",
"packages/shared/src/headless/events.ts": "71ece3f5df8fc14ad685fdf86f7ed7db748586c2",
"packages/shared/src/headless/channels.ts": "a71aa89528435fab712a07110eb5942b89a7859a",
"packages/shared/src/headless/events.ts": "d72c1a379adc4748109b8a3662037b25aa214943",
"packages/shared/src/headless/headless.test.ts": "616c41aff5d45b5cff8b216441c630adfc6fe740",
"packages/shared/src/headless/identity.ts": "aef0e7ee58f458f3ea0a956d8b4041e8998ce717",
"packages/shared/src/headless/index.ts": "011e7b457f61d2fbd1bec7827985b6b689c7f22f",
"packages/shared/src/headless/labels.ts": "18cb9acceeb27ed4cb75aa592786e3d845fcc70f",
"packages/shared/src/headless/leases.ts": "c5370155f85ebde371952da07d8cf2d9d8427b52",
"packages/shared/src/headless/leases.ts": "c63fd74f829f1579c08fabb5792a8a4ee9a342ec",
"packages/shared/src/headless/plans.ts": "9755160a884569aff9cfaaac8330486e392951ee",
"packages/shared/src/headless/pure.ts": "962757460d6e60494bbb75d2f476fb2be1e530dc",
"packages/shared/src/headless/pure.ts": "785dd11340e135d196b483fc0fe9c764af42a06f",
"packages/shared/src/headless/schemas.ts": "eb0716395a15111699d18ec209a2fda4990b9e4d",
"packages/shared/src/heartbeat-inbox.ts": "227dc89705c20460ca02194091cb162e11503186",
"packages/shared/src/home-paths.test.ts": "81235c17c376224e1be3abd3f034a8400f079c66",
@@ -380,14 +380,14 @@
"packages/shared/src/runtime-exposure/loopback-bind.ts": "696dcbc1fc8f7e64f37314bc574360cf06bbae95",
"packages/shared/src/runtime-exposure/ports.test.ts": "de27b2c17db88c65f9f4e7240d9fae969dd1551e",
"packages/shared/src/runtime-exposure/ports.ts": "6566d780a36c4eb37fab5584db19714f596654b7",
"packages/shared/src/sdk/client.ts": "497691448c2548afb87e4fe52767d1a970369a07",
"packages/shared/src/sdk/client.ts": "914f5aa79c7209e0eb49a50e0d7990cf236aba03",
"packages/shared/src/sdk/env.ts": "f651aca6f5fcca466deba63cc00257e534ad4d18",
"packages/shared/src/sdk/index.ts": "dedd01673f6a34d0291db0e5352c6b57b41a3222",
"packages/shared/src/sdk/lite.ts": "d4bbb9c4a953ab7239388e1e7f3120e110bb9778",
"packages/shared/src/sdk/lite.ts": "8fe44a952b9ecce44f32470ec3d51d4920e0cc26",
"packages/shared/src/sdk/memory-backend.ts": "35d8403191d3b7d534368dffb3e4159b32499df2",
"packages/shared/src/sdk/sdk.test.ts": "4421224d6125b6cad0e47e912de7a8bfa1af78aa",
"packages/shared/src/sdk/sse.ts": "cb1284b6acd556f0b8ffb4ce5c6f3b4456415e08",
"packages/shared/src/sdk/types.ts": "d7212ea5913b447e1c2a789c075edf86c062a20b",
"packages/shared/src/sdk/types.ts": "a755d3e0cd0e5a80e72841cdc6aac58c485e3938",
"packages/shared/src/self-serve-mcp-research.json": "98a90544e8e00b31350b5c07e39940429bc026b9",
"packages/shared/src/self-serve-mcp-research.ts": "312abfecb0dbac8a0e5bf80fb8e3467ca94f500f",
"packages/shared/src/setting-defaults.test.ts": "f5554686f7bf9cc34f14cdd4505257dcc562d410",