Files
PaperClipAI/server/src/services/headless-channels.ts
T
DottaandPaperclip ea56320e10 feat(board): add headless channels, fenced task queues, paperclipai/sdk, and pc CLI (#23330)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Multi-agent workflows and terminal scripts often need lightweight
shared channels, structured task queues, and scriptable CLI/SDK
primitives without building a full project UI first.
> - Today, Paperclip issues require board-oriented setup, lack lazy
hierarchical channels, lack fenced task claim leases, and lack a
zero-dependency TypeScript SDK and short CLI alias for fast script
coordination.
> - Without fenced leases, blocking queue claims, CAS key-value labels,
and race-free event streaming, multiple headless workers collide on
shared work or fall back to wasteful polling loops.
> - This pull request adds headless channels, versioned JSON schemas,
topological `plan.json` batch creation, fenced task queues with `FOR
UPDATE SKIP LOCKED` claims, CAS key-value labels, one-line ask/confirm
interactions, SSE event streaming, `paperclipai/sdk`, and the `pc` CLI
with `paperclipai up`.
> - The benefit is zero-ceremony, machine-readable, race-safe
coordination across terminal agents, CI scripts, and local Paperclip
servers while staying compatible with existing Web UI issue threads.

## Linked Issues or Issue Description

**Subsystem affected**

Cross-cutting (`packages/db`, `packages/shared`, `server/`, `cli/`,
`doc/`, `skills/`)

**Problem or motivation**

Agents and terminal workflows need a fast way to post updates, queue DAG
tasks, claim work without double-execution, ask humans for approval, and
wait on board events without browser setup or polling loops. Existing
Paperclip routes assume UI-driven projects, lack fenced claim leases for
pools of workers, and lack a minimal `pc` CLI and `paperclipai/sdk`
client.

**Proposed solution**

Build a headless coordination layer directly on top of Paperclip
`issues` and `issue_comments` using `issues.scope = 'channel'`:

- **Database & Contracts (`packages/db`, `packages/shared`)**: Add
`0511_pale_kronos.sql` (`issues.scope`) and `0512_stormy_the_hood.sql`
for lazy hierarchical `channels`, `channel_access_members`, immutable
`company_schemas`, monotonic `board_events`, `scheduled_board_posts`,
`issue_batch_idempotency_keys`, scoped `board_api_keys`,
`agent_identity_policy`, `kv_labels`, `schema_blocks`, and fenced claim
leases. Export Zod contracts, DAG sorting, KV CAS helpers, and the
zero-dependency `paperclip()` SDK (`packages/shared/src/sdk/`),
including an in-memory test backend.
- **Server APIs & Workers (`server/`)**: Add routes and services for
progressive `--as` actor resolution (`open_local_profiles`,
`delegated_profiles`, `strict_agent_keys`), `pc agent connect` auth
challenges, lazy channels, CAS `kv-labels`, versioned schemas,
topological batch creation, `FOR UPDATE SKIP LOCKED` pool claims with
fenced TTL renewal/release/complete/fail, one-line
`ask`/`confirm`/`approve`/`reject` interactions, SSE cursor streaming
(`events/wait`, `events/stream`), and sleep-aware lease expiry and
scheduled post workers.
- **CLI, Launcher & Docs (`cli/`, `doc/`, `skills/`)**: Expose the `pc`
binary alias and `paperclipai/sdk` export, add the zero-prompt
`paperclipai up` / `pc up` local launcher, add `pc` commands (`post`,
`reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`,
`approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent
connect/login`), add documentation (`doc/CHANNELS-AND-QUEUES.md`,
`doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`), and add
`skills/paperclip-lite/SKILL.md`.

**Alternatives considered**

- **Separate message and queue tables outside `issues`**: Rejected
because channel posts and queued tasks would lose Paperclip identifiers
(`PC-1`), comments, attachments, privacy ACLs, and direct Web UI issue
URLs (`/<prefix>/issues/PC-1`).
- **Advisory locks or polling loops for task workers**: Rejected because
advisory locks drop on reconnect across laptop sleep, and polling wastes
tokens and prevents database sleep. Fenced `(claimToken, claimEpoch)`
TTL leases with `events/wait` and `waitSec` solve both safely.

**Roadmap alignment**

Extends core Paperclip agent orchestration and CLI workflows with a
headless board, SDK, and queue primitive without altering existing Web
UI board behavior.

**Additional context**

This PR builds on the `issues.scope` surface visibility foundation from
#23329 (included as the base commit in this stacked branch so CI and
reviewers can test the full integration against `master`).

## What Changed

- **Schema & Migrations (`packages/db`)**: Added online-compatible
migrations `0511_pale_kronos.sql` and `0512_stormy_the_hood.sql`, schema
definitions (`channels.ts`, `company_schemas.ts`, `headless_board.ts`),
and column extensions on `issues`, `issue_comments`, `companies`,
`board_api_keys`, and `cli_auth_challenges`.
- **Shared Contracts & SDK (`packages/shared`)**: Added
`packages/shared/src/headless/*` (channels, events, identity, labels,
leases, DAG plans, schemas) and `packages/shared/src/sdk/*`
(`paperclip()` client, env loader, SSE parser, and in-memory backend).
- **Server Routes & Services (`server/`)**: Added
`headless-channels-schemas.ts`, `headless-queues-events.ts`,
`headless-identity.ts` routes and supporting services
(`headless-channels.ts`, `headless-common.ts`,
`headless-events-schedules-interactions.ts`, `headless-identity.ts`,
`headless-labels-batch.ts`, `headless-schemas.ts`,
`headless-task-queue.ts`), plus `issues.scope` visibility isolation and
`board-auth.ts` extensions.
- **CLI & SDK Export (`cli/`, `scripts/`)**: Exposed `pc` bin alias and
`paperclipai/sdk` entrypoint, added `up.ts` zero-prompt launcher and
`cli/src/commands/board/*` commands (`post`, `reply`, `read`,
`channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`,
`schemas`, `schedule`, `tail`, `wait`, `agent`).
- **Docs, Skill & Runner Registry (`doc/`, `skills/`,
`tests/runner-e2e/`)**: Added `doc/CHANNELS-AND-QUEUES.md`,
`doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`, plan docs,
`skills/paperclip-lite/SKILL.md`, and synchronized
`tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `pnpm --filter @paperclipai/shared build` — passed.
- `pnpm --filter @paperclipai/db check:migrations` — passed
(`0511_pale_kronos.sql` and `0512_stormy_the_hood.sql` verified
online-compatible, 2 new migrations since `630cf0423024`, none blocked).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed (`598` inputs, `changed: false`).
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs` — 13/13 tests
passed.
- `node scripts/check-maps.mjs` — passed (`35` areas, `192` capability
IDs aligned).
- `pnpm exec vitest run packages/shared/src/headless/headless.test.ts
packages/shared/src/sdk/sdk.test.ts
cli/src/__tests__/headless-board-cli.test.ts` — 3 files, 22/22 tests
passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-scope-visibility.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-identity-auth.test.ts
src/__tests__/headless-queues-leases-events.test.ts
src/__tests__/headless-e2e-sdk-cli.test.ts` — 5 files, 25/25 tests
passed.
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck
&& pnpm --filter paperclipai typecheck` — all passed.
- `pnpm --filter paperclipai build` — passed.

## Risks

- **Two new migrations (`0511`, `0512`)**: Both migrations are marked
online-compatible (`NOT VALID` constraints validated afterwards,
`CONCURRENTLY` index creation, idempotent statements for
non-transactional execution) and checked by `check:migrations`. If
#23329 lands separately with `0511` modified or renumbered, this branch
will rebase on top cleanly.
- **Large surface area (91 files)**: Changes are primarily additive new
modules (`headless-*`, `cli/src/commands/board/*`,
`packages/shared/src/headless/*`, `packages/shared/src/sdk/*`); existing
Web UI board behavior remains isolated via `issues.scope`.
- **Full repository Vitest suite**: Only the targeted headless, SDK,
CLI, server, and runner-e2e pin suites ran locally after rebasing; full
cross-package CI checks will validate the remaining suite.

## Model Used

- Google DeepMind Antigravity (Gemini coding agent) 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 08:12:19 -06:00

1364 lines
39 KiB
TypeScript

import { createHash, randomUUID } from "node:crypto";
import {
and,
asc,
desc,
eq,
gt,
inArray,
isNull,
like,
ne,
or,
sql,
type SQL,
} from "drizzle-orm";
import { z } from "zod";
import type { Db } from "@paperclipai/db";
import {
agents,
boardEvents,
channelAccessMembers,
channels,
companies,
companyMemberships,
issueComments,
issueLabels,
issues,
labels,
projects,
} from "@paperclipai/db";
import {
channelQueueConfigSchema,
CHANNEL_VISIBILITIES,
deriveAgentUrlKey,
ISSUE_PRIORITIES,
isUuidLike,
matchesLabelFilter,
normalizeChannelPath,
parseEventCursor,
parseLabelFilterExpr,
parseSchemaRef,
SCHEMA_REF_REGEX,
schemaBlockSchema,
splitMessageIntoTitleAndDescription,
writableKvLabelsRecordSchema,
type BoardEventView,
type ChannelPage,
type ChannelQueueConfig,
type ChannelView,
type ChannelVisibility,
type CommentView,
type CreateChannelInput,
type HeadlessIssueView,
type IssuePriority,
type IssueScope,
type IssueStatus,
type SchemaBlock,
} from "@paperclipai/shared";
import { badRequest, conflict, forbidden, notFound } from "../errors.js";
import {
logActivity,
publishActivity,
type ActivityPublication,
} from "./activity-log.js";
import {
appendBoardEvent,
assertChannelAccess,
assertProjectReadAccess,
buildSqlIssueLabelFilterCondition,
canAccessChannel,
channelDescendantsCondition,
channelSubtreeCondition,
enforceHeadlessScopes,
getLatestCompanyEventCursor,
loadHeadlessIssueView,
loadHeadlessIssueViews,
publishCommittedBoardEvent,
resolveIssueByIdOrIdentifier,
resolveProjectReference,
serializeCommentView,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
import {
assertSchemaExists,
formatBlocksAsFencedJson,
validateSchemaBlocks,
} from "./headless-schemas.js";
import { listIssueDependencyReadinessMap } from "./issues.js";
const DEFAULT_TAG_LABEL_COLOR = "#64748b";
function isChannelAllowedByScopes(
actor: Pick<HeadlessActorContext, "scopes">,
channelPath: string,
): boolean {
try {
enforceHeadlessScopes(actor, { channelPath });
return true;
} catch {
return false;
}
}
export function normalizeChannelPathOrThrow(
rawPath: string,
opts?: { allowSubtreePrefix?: boolean },
) {
try {
return normalizeChannelPath(rawPath, opts);
} catch (err) {
throw badRequest(
err instanceof Error ? err.message : `Invalid channel path "${rawPath}"`,
{
error: "invalid_channel_path",
code: "invalid_channel_path",
},
);
}
}
export function validateWritableKvLabelsOrThrow(
rawLabels: Record<string, unknown>,
): Record<string, string> {
for (const key of Object.keys(rawLabels)) {
if (key.startsWith("paperclip.")) {
throw badRequest(
"Label keys starting with 'paperclip.' are reserved",
{
error: "reserved_label",
code: "reserved_label",
key,
},
);
}
}
const parsed = writableKvLabelsRecordSchema.safeParse(rawLabels);
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((issue) => `${issue.path.join(".") || "$"}: ${issue.message}`)
.join("; "),
{
error: "validation_error",
code: "validation_error",
issues: parsed.error.issues,
},
);
}
return parsed.data;
}
export async function resolveAssigneeAgent(
dbOrTx: DbOrTx,
companyId: string,
opts: { assigneeAgentId?: string | null; for?: string },
): Promise<string | null> {
if (opts.assigneeAgentId !== undefined) {
if (opts.assigneeAgentId === null) return null;
const [agent] = await dbOrTx
.select({ id: agents.id })
.from(agents)
.where(
and(
eq(agents.id, opts.assigneeAgentId),
eq(agents.companyId, companyId),
ne(agents.status, "terminated"),
),
)
.limit(1);
if (!agent) {
throw notFound(`Agent '${opts.assigneeAgentId}' not found`, {
error: "agent_not_found",
code: "agent_not_found",
});
}
return agent.id;
}
if (opts.for !== undefined && opts.for.trim().length > 0) {
const target = opts.for.trim().replace(/^@+/, "").toLowerCase();
if (isUuidLike(target)) {
const [agent] = await dbOrTx
.select({ id: agents.id })
.from(agents)
.where(
and(
eq(agents.id, target),
eq(agents.companyId, companyId),
ne(agents.status, "terminated"),
),
)
.limit(1);
if (!agent) {
throw notFound(`Agent '@${target}' not found`, {
error: "agent_not_found",
code: "agent_not_found",
});
}
return agent.id;
}
const companyAgents = await dbOrTx
.select({ id: agents.id, name: agents.name })
.from(agents)
.where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated")));
const match = companyAgents.find(
(a) =>
a.name.trim().toLowerCase() === target ||
deriveAgentUrlKey(a.name, a.id).toLowerCase() === target,
);
if (!match) {
throw notFound(`Agent '@${target}' not found`, {
error: "agent_not_found",
code: "agent_not_found",
});
}
return match.id;
}
return null;
}
export async function attachTagLabels(
tx: DbOrTx,
companyId: string,
issueId: string,
tagNames: string[],
): Promise<void> {
const uniqueNames = Array.from(
new Set(tagNames.map((t) => t.trim()).filter((t) => t.length > 0)),
);
if (uniqueNames.length === 0) return;
await tx
.insert(labels)
.values(
uniqueNames.map((name) => ({
companyId,
name,
color: DEFAULT_TAG_LABEL_COLOR,
})),
)
.onConflictDoNothing({
target: [labels.companyId, labels.name],
});
const labelRows = await tx
.select({ id: labels.id })
.from(labels)
.where(and(eq(labels.companyId, companyId), inArray(labels.name, uniqueNames)));
if (labelRows.length === 0) return;
await tx
.insert(issueLabels)
.values(
labelRows.map((l) => ({
issueId,
labelId: l.id,
companyId,
})),
)
.onConflictDoNothing({
target: [issueLabels.issueId, issueLabels.labelId],
});
}
async function addChannelCreatorMembership(
dbOrTx: DbOrTx,
companyId: string,
channelId: string,
actor: HeadlessActorContext,
): Promise<void> {
const member = actor.agentId
? { subjectType: "agent", subjectId: actor.agentId }
: actor.userId
? { subjectType: "user", subjectId: actor.userId }
: null;
if (!member) return;
await dbOrTx
.insert(channelAccessMembers)
.values({
companyId,
channelId,
subjectType: member.subjectType,
subjectId: member.subjectId,
})
.onConflictDoNothing({
target: [
channelAccessMembers.channelId,
channelAccessMembers.subjectType,
channelAccessMembers.subjectId,
],
});
}
export interface EnsureChannelInput {
path: string;
description?: string | null;
visibility?: ChannelVisibility;
defaultProjectId?: string | null;
queueConfig?: ChannelQueueConfig;
}
export async function ensureChannel(
dbOrTx: DbOrTx,
companyId: string,
actor: HeadlessActorContext,
input: EnsureChannelInput | CreateChannelInput,
opts: { allowUpdateExisting?: boolean; publications?: ActivityPublication[] } = {},
): Promise<typeof channels.$inferSelect> {
const normalized = normalizeChannelPathOrThrow(input.path, {
allowSubtreePrefix: false,
});
enforceHeadlessScopes(actor, { channelPath: normalized.path });
let resolvedDefaultProjectId: string | null | undefined;
if (input.defaultProjectId !== undefined) {
resolvedDefaultProjectId =
input.defaultProjectId === null
? null
: await resolveProjectReference(dbOrTx, companyId, input.defaultProjectId, actor);
}
let validatedQueueConfig: ChannelQueueConfig | undefined;
if (input.queueConfig !== undefined) {
const parsedQc = channelQueueConfigSchema.safeParse(input.queueConfig);
if (!parsedQc.success) {
throw badRequest(
parsedQc.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
{
error: "validation_error",
code: "validation_error",
issues: parsedQc.error.issues,
},
);
}
validatedQueueConfig = parsedQc.data;
}
let visibility: ChannelVisibility | undefined = input.visibility;
if (visibility !== undefined && !CHANNEL_VISIBILITIES.includes(visibility)) {
throw badRequest(`Invalid channel visibility '${visibility}'`, {
error: "validation_error",
code: "validation_error",
});
}
// Always check ancestor privacy and access so private parents cannot spawn open children
let hasPrivateAncestor = false;
const parts = normalized.path.split("/");
if (parts.length > 1) {
const ancestorPaths: string[] = [];
for (let i = 1; i < parts.length; i += 1) {
ancestorPaths.push(parts.slice(0, i).join("/"));
}
const ancestors = await dbOrTx
.select()
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
inArray(channels.path, ancestorPaths),
isNull(channels.archivedAt),
),
);
for (const anc of ancestors) {
if (anc.visibility === "private") {
await assertChannelAccess(dbOrTx, anc, actor);
hasPrivateAncestor = true;
}
}
}
if (hasPrivateAncestor) {
if (visibility === "open") {
throw forbidden("Cannot create or expose an open channel under a private ancestor", {
code: "private_ancestor_required",
});
}
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();
if (inserted) {
if (inserted.visibility === "private") {
await addChannelCreatorMembership(dbOrTx, companyId, inserted.id, actor);
}
if (opts.publications) {
await logActivity(
dbOrTx as unknown as Db,
{
companyId,
actorType: actor.principalType === "agent" ? "agent" : "user",
actorId:
actor.principalType === "agent"
? actor.agentId!
: (actor.userId ?? "local-board"),
agentId: actor.agentId,
responsibleUserIdOverride: actor.responsibleUserId,
action: "channel.created",
entityType: "channel",
entityId: inserted.id,
details: {
path: inserted.path,
visibility: inserted.visibility,
},
},
opts.publications,
);
}
return inserted;
}
const [existing] = await dbOrTx
.select()
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
.limit(1);
if (!existing) {
throw notFound(`Channel '${normalized.path}' not found`);
}
if (existing.visibility === "private") {
await assertChannelAccess(dbOrTx, existing, actor);
}
if (!opts.allowUpdateExisting) {
return existing;
}
const updates: Partial<typeof channels.$inferInsert> = {};
if (input.description !== undefined && input.description !== existing.description) {
updates.description = input.description;
}
if (input.visibility !== undefined && input.visibility !== existing.visibility) {
updates.visibility = input.visibility;
}
if (
resolvedDefaultProjectId !== undefined &&
resolvedDefaultProjectId !== existing.defaultProjectId
) {
updates.defaultProjectId = resolvedDefaultProjectId;
}
if (
validatedQueueConfig !== undefined &&
JSON.stringify(validatedQueueConfig) !== JSON.stringify(existing.queueConfig ?? {})
) {
updates.queueConfig = validatedQueueConfig;
}
if (Object.keys(updates).length > 0) {
enforceHeadlessScopes(actor, {
action: "channels.manage",
channelPath: existing.path,
});
const isOwnerOrCreator =
actor.isInstanceAdmin ||
actor.principalType === "local_trusted" ||
(Boolean(actor.userId) && existing.createdByUserId === actor.userId) ||
(Boolean(actor.agentId) && existing.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");
}
updates.updatedAt = new Date();
const privatizingTree =
updates.visibility === "private" && existing.visibility !== "private";
let childChannels: Array<{ id: string; visibility: string }> = [];
let affectedChannelIds: string[] = [];
if (privatizingTree) {
childChannels = await dbOrTx
.select({ id: channels.id, visibility: channels.visibility })
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
isNull(channels.archivedAt),
channelDescendantsCondition(existing.path),
),
);
affectedChannelIds = [existing.id, ...childChannels.map((c) => c.id)].sort();
// Lock issues BEFORE locking channels so all transactions share issues -> channels -> board_events lock order.
await dbOrTx.execute(
sql`SELECT id FROM issues WHERE company_id = ${companyId} AND channel_id IN (${sql.join(
affectedChannelIds.map((id) => sql`${id}`),
sql`, `,
)}) AND visibility <> 'private' ORDER BY id FOR UPDATE`,
);
await dbOrTx.execute(
sql`SELECT id FROM channels WHERE company_id = ${companyId} AND id IN (${sql.join(
affectedChannelIds.map((id) => sql`${id}`),
sql`, `,
)}) ORDER BY id FOR UPDATE`,
);
}
const [updated] = await dbOrTx
.update(channels)
.set(updates)
.where(eq(channels.id, existing.id))
.returning();
if (updated?.visibility === "private" && existing.visibility !== "private") {
await addChannelCreatorMembership(dbOrTx, companyId, updated.id, actor);
const newlyPrivatizedChildIds = childChannels
.filter((c) => c.visibility !== "private")
.map((c) => c.id)
.sort();
if (newlyPrivatizedChildIds.length > 0) {
await dbOrTx
.update(channels)
.set({ visibility: "private", updatedAt: updates.updatedAt })
.where(inArray(channels.id, newlyPrivatizedChildIds));
for (const childId of newlyPrivatizedChildIds) {
await addChannelCreatorMembership(dbOrTx, companyId, childId, actor);
}
}
await dbOrTx
.update(issues)
.set({
visibility: "private",
privacyRootIssueId: sql`coalesce(${issues.privacyRootIssueId}, ${issues.id})`,
updatedAt: updates.updatedAt,
})
.where(
and(
eq(issues.companyId, companyId),
inArray(issues.channelId, affectedChannelIds),
ne(issues.visibility, "private"),
),
);
}
if (updated && opts.publications) {
await logActivity(
dbOrTx as unknown as Db,
{
companyId,
actorType: actor.principalType === "agent" ? "agent" : "user",
actorId:
actor.principalType === "agent"
? actor.agentId!
: (actor.userId ?? "local-board"),
agentId: actor.agentId,
responsibleUserIdOverride: actor.responsibleUserId,
action: "channel.updated",
entityType: "channel",
entityId: updated.id,
details: {
path: updated.path,
visibility: updated.visibility,
},
},
opts.publications,
);
}
return updated ?? existing;
}
return existing;
}
export async function buildChannelViews(
dbOrTx: DbOrTx,
companyId: string,
channelRows: Array<typeof channels.$inferSelect>,
): Promise<ChannelView[]> {
if (channelRows.length === 0) return [];
const channelIds = channelRows.map((c) => c.id);
const channelIssues = await dbOrTx
.select({
id: issues.id,
channelId: issues.channelId,
status: issues.status,
assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId,
conversationAgentId: issues.conversationAgentId,
})
.from(issues)
.where(
and(
eq(issues.companyId, companyId),
inArray(issues.channelId, channelIds),
isNull(issues.hiddenAt),
),
);
const candidateReadyIds = channelIssues
.filter(
(i) =>
i.status === "todo" &&
!i.assigneeAgentId &&
!i.assigneeUserId &&
!i.conversationAgentId,
)
.map((i) => i.id);
const blockedIssueIds = new Set<string>();
if (candidateReadyIds.length > 0) {
const readinessMap = await listIssueDependencyReadinessMap(
dbOrTx as unknown as Db,
companyId,
candidateReadyIds,
false,
);
for (const [issueId, readiness] of readinessMap) {
if (!readiness.isDependencyReady) {
blockedIssueIds.add(issueId);
}
}
}
const counts = new Map<
string,
{ threadCount: number; openTaskCount: number; readyTaskCount: number }
>();
for (const chId of channelIds) {
counts.set(chId, { threadCount: 0, openTaskCount: 0, readyTaskCount: 0 });
}
for (const row of channelIssues) {
if (!row.channelId) continue;
const c = counts.get(row.channelId);
if (!c) continue;
c.threadCount += 1;
if (
row.status === "todo" ||
row.status === "in_progress" ||
row.status === "in_review" ||
row.status === "blocked"
) {
c.openTaskCount += 1;
}
if (
row.status === "todo" &&
!row.assigneeAgentId &&
!row.assigneeUserId &&
!row.conversationAgentId &&
!blockedIssueIds.has(row.id)
) {
c.readyTaskCount += 1;
}
}
return channelRows.map((ch) => {
const c = counts.get(ch.id) ?? {
threadCount: 0,
openTaskCount: 0,
readyTaskCount: 0,
};
return {
id: ch.id,
companyId: ch.companyId,
path: ch.path,
description: ch.description ?? null,
visibility: ch.visibility,
defaultProjectId: ch.defaultProjectId ?? null,
queueConfig: (ch.queueConfig ?? {}) as ChannelQueueConfig,
threadCount: c.threadCount,
openTaskCount: c.openTaskCount,
readyTaskCount: c.readyTaskCount,
lastActivityAt: ch.lastActivityAt.toISOString(),
createdAt: ch.createdAt.toISOString(),
updatedAt: ch.updatedAt.toISOString(),
};
});
}
export async function listChannels(
db: Db,
companyId: string,
actor: HeadlessActorContext,
prefix?: string,
): Promise<ChannelView[]> {
enforceHeadlessScopes(actor, { action: "read" });
const conditions = [
eq(channels.companyId, companyId),
isNull(channels.archivedAt),
];
if (prefix && prefix.trim().length > 0) {
const norm = normalizeChannelPathOrThrow(prefix, {
allowSubtreePrefix: true,
});
conditions.push(channelSubtreeCondition(norm.path));
}
const rows = await db
.select()
.from(channels)
.where(and(...conditions))
.orderBy(asc(channels.path));
const visibleRows: Array<typeof channels.$inferSelect> = [];
for (const row of rows) {
if (!isChannelAllowedByScopes(actor, row.path)) continue;
if (!(await canAccessChannel(db, row, actor))) continue;
visibleRows.push(row);
}
return buildChannelViews(db, companyId, visibleRows);
}
const createChannelPostInputSchema = z
.object({
channel: z.string().min(1),
status: z.enum(["backlog", "todo"]).optional(),
for: z.string().min(1).optional(),
assigneeAgentId: z.string().uuid().nullable().optional(),
resultSchema: z
.string()
.refine((v) => SCHEMA_REF_REGEX.test(v.trim()), {
message: "resultSchema must match <name>@<positive-integer>",
})
.optional(),
labels: z.record(z.string(), z.string()).optional(),
kvLabels: z.record(z.string(), z.string()).optional(),
tagLabels: z.array(z.string().min(1).max(64)).optional(),
blocks: z.array(schemaBlockSchema).optional(),
schema: z
.object({
ref: z.string().refine((v) => SCHEMA_REF_REGEX.test(v.trim()), {
message: "Invalid schema ref",
}),
data: z.record(z.string(), z.unknown()),
})
.strict()
.optional(),
priority: z.enum(ISSUE_PRIORITIES).optional(),
projectId: z.string().min(1).nullable().optional(),
board: z.boolean().optional(),
title: z.string().max(240).optional(),
text: z.string().optional(),
description: z.string().nullable().optional(),
idempotencyKey: z.string().min(1).max(255).optional(),
sourceTrust: z.string().min(1).max(64).optional(),
})
.passthrough();
export async function createChannelPost(
db: Db,
companyId: string,
actor: HeadlessActorContext,
rawBody: unknown,
): Promise<{ issue: HeadlessIssueView; created: boolean }> {
const parsedBody = createChannelPostInputSchema.safeParse(rawBody);
if (!parsedBody.success) {
throw badRequest(
parsedBody.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
{
error: "validation_error",
code: "validation_error",
issues: parsedBody.error.issues,
},
);
}
const input = parsedBody.data;
const normalizedChannel = normalizeChannelPathOrThrow(input.channel, {
allowSubtreePrefix: false,
});
const requestedStatus: IssueStatus = input.status ?? "backlog";
const requiredAction = requestedStatus === "todo" ? "tasks.create" : "post";
enforceHeadlessScopes(actor, {
action: requiredAction,
channelPath: normalizedChannel.path,
});
const mergedKvLabels = validateWritableKvLabelsOrThrow({
...(input.labels ?? {}),
...(input.kvLabels ?? {}),
});
const combinedBlocks: SchemaBlock[] = [...(input.blocks ?? [])];
if (input.schema) {
const parsedRef = parseSchemaRef(input.schema.ref);
combinedBlocks.push({
schema: parsedRef.name,
version: parsedRef.version,
data: input.schema.data,
});
}
const validatedBlocks = await validateSchemaBlocks(db, companyId, combinedBlocks);
const resolvedResultSchemaRef = input.resultSchema
? await assertSchemaExists(db, companyId, input.resultSchema)
: null;
const originId = input.idempotencyKey
? `headless:${input.idempotencyKey}`
: null;
let resolvedTitle: string;
let resolvedDescription: string | null;
const trimmedTitle = input.title?.trim();
if (trimmedTitle) {
resolvedTitle = trimmedTitle;
if (input.description !== undefined) {
resolvedDescription = input.description;
} else if (input.text !== undefined) {
resolvedDescription = input.text.trim() ? input.text : null;
} else if (validatedBlocks.length > 0) {
resolvedDescription = formatBlocksAsFencedJson(validatedBlocks);
} else {
resolvedDescription = null;
}
} else if (
(input.text && input.text.trim().length > 0) ||
(input.description && input.description.trim().length > 0)
) {
const rawText = input.text ?? input.description ?? "";
const split = splitMessageIntoTitleAndDescription(rawText);
resolvedTitle = split.title;
resolvedDescription = split.description;
} else if (validatedBlocks.length > 0) {
resolvedTitle = `[${validatedBlocks[0]!.schema}@${validatedBlocks[0]!.version}]`;
resolvedDescription = formatBlocksAsFencedJson(validatedBlocks);
} else {
throw badRequest("Post requires title, text, description, or blocks", {
error: "validation_error",
code: "validation_error",
});
}
const requestHash = originId
? createHash("sha256")
.update(
JSON.stringify({
channel: normalizedChannel.path,
status: requestedStatus,
title: resolvedTitle,
description: resolvedDescription,
projectId: input.projectId ?? null,
board: Boolean(input.board),
priority: input.priority ?? "medium",
for: input.for ?? null,
assigneeAgentId: input.assigneeAgentId ?? null,
kvLabels: mergedKvLabels,
tagLabels: input.tagLabels ?? [],
blocks: validatedBlocks,
resultSchema: resolvedResultSchemaRef,
}),
)
.digest("hex")
: null;
if (originId) {
const [existing] = await db
.select()
.from(issues)
.where(
and(
eq(issues.companyId, companyId),
eq(issues.originKind, "manual"),
eq(issues.originId, originId),
),
)
.limit(1);
if (existing) {
if (existing.channelId) {
const [ch] = await db
.select()
.from(channels)
.where(eq(channels.id, existing.channelId))
.limit(1);
if (ch) await assertChannelAccess(db, ch, actor);
}
if (existing.originFingerprint && existing.originFingerprint !== requestHash) {
throw conflict(
"Idempotency key has already been used for a different payload",
{
error: "idempotency_conflict",
code: "idempotency_conflict",
},
);
}
const view = await loadHeadlessIssueView(db, existing.id);
return { issue: view, created: false };
}
}
const publications: ActivityPublication[] = [];
const committedEvents: BoardEventView[] = [];
const txResult = await db.transaction(async (tx) => {
if (originId) {
await tx.execute(
sql`select pg_advisory_xact_lock(hashtext(${companyId}), hashtext(${"post:" + originId}))`,
);
const [existingInTx] = await tx
.select()
.from(issues)
.where(
and(
eq(issues.companyId, companyId),
eq(issues.originKind, "manual"),
eq(issues.originId, originId),
),
)
.limit(1);
if (existingInTx) {
if (existingInTx.channelId) {
const [ch] = await tx
.select()
.from(channels)
.where(eq(channels.id, existingInTx.channelId))
.limit(1);
if (ch) await assertChannelAccess(tx, ch, actor);
}
if (
existingInTx.originFingerprint &&
existingInTx.originFingerprint !== requestHash
) {
throw conflict(
"Idempotency key has already been used for a different payload",
{
error: "idempotency_conflict",
code: "idempotency_conflict",
},
);
}
const view = await loadHeadlessIssueView(tx, existingInTx.id);
return { issue: view, created: false };
}
}
const channel = await ensureChannel(tx, companyId, actor, {
path: normalizedChannel.path,
});
const now = new Date();
let projectId: string | null = channel.defaultProjectId ?? null;
if (input.projectId !== undefined) {
projectId =
input.projectId === null
? null
: await resolveProjectReference(tx, companyId, input.projectId, actor);
} else if (projectId) {
await assertProjectReadAccess(tx, companyId, projectId, actor);
}
const assigneeAgentId = await resolveAssigneeAgent(tx, companyId, {
assigneeAgentId: input.assigneeAgentId,
for: input.for,
});
const [maxRow] = await tx
.select({
maxNum: sql<number>`coalesce(max(${issues.issueNumber}), 0)`,
})
.from(issues)
.where(eq(issues.companyId, companyId));
const currentMax = Number(maxRow?.maxNum ?? 0);
const [companyRow] = await tx
.update(companies)
.set({
issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + 1`,
updatedAt: now,
})
.where(eq(companies.id, companyId))
.returning({
issueCounter: companies.issueCounter,
issuePrefix: companies.issuePrefix,
});
const issueNumber = companyRow!.issueCounter;
const identifier = `${companyRow!.issuePrefix}-${issueNumber}`;
const scope: IssueScope = input.board ? "board" : "channel";
const priority: IssuePriority = input.priority ?? "medium";
let issueVisibility: "open" | "private" =
channel.visibility === "private" ? "private" : "open";
if (projectId && issueVisibility !== "private") {
const [projRow] = await tx
.select({ visibility: projects.visibility })
.from(projects)
.where(and(eq(projects.id, projectId), eq(projects.companyId, companyId)))
.limit(1);
if (projRow?.visibility === "private") {
issueVisibility = "private";
}
}
const newIssueId = randomUUID();
const privacyRootIssueId = issueVisibility === "private" ? newIssueId : null;
const [inserted] = await tx
.insert(issues)
.values({
id: newIssueId,
companyId,
projectId,
channelId: channel.id,
visibility: issueVisibility,
privacyRootIssueId,
title: resolvedTitle,
description: resolvedDescription,
status: requestedStatus,
scope,
priority,
assigneeAgentId,
createdByAgentId: actor.agentId,
createdByUserId: actor.agentId ? null : actor.userId,
createdByProfile: actor.actorProfile,
responsibleUserId: actor.responsibleUserId,
kvLabels: mergedKvLabels,
schemaBlocks: validatedBlocks,
resultSchemaRef: resolvedResultSchemaRef,
issueNumber,
identifier,
originKind: "manual",
originId,
originFingerprint: requestHash ?? "default",
createdAt: now,
updatedAt: now,
})
.returning();
await tx
.update(channels)
.set({ lastActivityAt: now, updatedAt: now })
.where(eq(channels.id, channel.id));
if (input.tagLabels && input.tagLabels.length > 0) {
await attachTagLabels(tx, companyId, inserted!.id, input.tagLabels);
}
await logActivity(
tx as unknown as Db,
{
companyId,
actorType: actor.principalType === "agent" ? "agent" : "user",
actorId:
actor.principalType === "agent"
? actor.agentId!
: (actor.userId ?? "local-board"),
agentId: actor.agentId,
issueId: inserted!.id,
responsibleUserIdOverride: actor.responsibleUserId,
action:
requestedStatus === "todo" ? "issue.created" : "channel.post_created",
entityType: "issue",
entityId: inserted!.id,
details: {
identifier,
channel: channel.path,
status: requestedStatus,
scope,
},
},
publications,
);
const isReadyTask = requestedStatus === "todo" && assigneeAgentId === null;
const primaryEvent = await appendBoardEvent(tx, {
companyId,
type: requestedStatus === "todo" ? "task.created" : "thread.posted",
channelId: channel.id,
channelPath: channel.path,
issueId: inserted!.id,
identifier,
actor,
payload: {
title: resolvedTitle,
...(resolvedDescription ? { description: resolvedDescription.slice(0, 4000) } : {}),
blocks: validatedBlocks,
labels: mergedKvLabels,
...(isReadyTask ? { ready: true } : {}),
},
});
committedEvents.push(primaryEvent);
let lastCursor = primaryEvent.cursor;
if (isReadyTask) {
const readyEvent = await appendBoardEvent(tx, {
companyId,
type: "task.ready",
channelId: channel.id,
channelPath: channel.path,
issueId: inserted!.id,
identifier,
actor,
payload: {},
});
committedEvents.push(readyEvent);
lastCursor = readyEvent.cursor;
}
const view = await loadHeadlessIssueView(tx, inserted!.id, lastCursor);
return { issue: view, created: true };
});
for (const pub of publications) {
publishActivity(pub);
}
for (const evt of committedEvents) {
publishCommittedBoardEvent(evt);
}
return txResult;
}
export interface ListChannelThreadsQuery {
channel: string;
status?: string | string[];
label?: string | string[];
after?: string;
limit?: number;
readCondition?: SQL;
}
function toStringArray(val: string | string[] | undefined): string[] {
if (val === undefined) return [];
const arr = Array.isArray(val) ? val : [val];
return arr
.flatMap((item) => item.split(","))
.map((s) => s.trim())
.filter((s) => s.length > 0);
}
export async function listChannelThreads(
db: Db,
companyId: string,
actor: HeadlessActorContext,
query: ListChannelThreadsQuery,
): Promise<ChannelPage> {
const normalized = normalizeChannelPathOrThrow(query.channel, {
allowSubtreePrefix: true,
});
enforceHeadlessScopes(actor, {
action: "read",
channelPath: normalized.path,
});
const channelDisplay = normalized.isSubtreePrefix
? `${normalized.path}/`
: normalized.path;
const statusFilters = toStringArray(query.status);
const rawLabelFilters = toStringArray(query.label);
const parsedLabelFilters = rawLabelFilters.map((expr) => {
try {
return parseLabelFilterExpr(expr);
} catch (err) {
throw badRequest(
err instanceof Error ? err.message : `Invalid label filter "${expr}"`,
{ error: "invalid_label_filter", code: "invalid_label_filter" },
);
}
});
const rawLimit = query.limit ?? 50;
const limit = Math.max(1, Math.min(200, Math.floor(rawLimit)));
const matchedChannels = await db
.select()
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
isNull(channels.archivedAt),
normalized.isSubtreePrefix
? channelSubtreeCondition(normalized.path)
: eq(channels.path, normalized.path),
),
);
if (!normalized.isSubtreePrefix) {
const exact = matchedChannels[0];
if (!exact) {
return {
kind: "channel",
channel: channelDisplay,
items: [],
cursor: await getLatestCompanyEventCursor(db, companyId),
};
}
await assertChannelAccess(db, exact, actor);
}
const accessibleChannelIds: string[] = [];
for (const ch of matchedChannels) {
if (!isChannelAllowedByScopes(actor, ch.path)) continue;
if (!(await canAccessChannel(db, ch, actor))) continue;
accessibleChannelIds.push(ch.id);
}
if (accessibleChannelIds.length === 0) {
return {
kind: "channel",
channel: channelDisplay,
items: [],
cursor: await getLatestCompanyEventCursor(db, companyId),
};
}
const issueConditions = [
eq(issues.companyId, companyId),
inArray(issues.channelId, accessibleChannelIds),
isNull(issues.hiddenAt),
...(query.readCondition ? [query.readCondition] : []),
];
if (statusFilters.length > 0) {
issueConditions.push(inArray(issues.status, statusFilters));
}
for (const expr of parsedLabelFilters) {
issueConditions.push(buildSqlIssueLabelFilterCondition(expr));
}
if (query.after && query.after.trim().length > 0) {
const afterTrimmed = query.after.trim();
const afterSeq = parseEventCursor(afterTrimmed);
if (afterSeq !== null) {
const eventIssueRows = await db
.selectDistinct({ issueId: boardEvents.issueId })
.from(boardEvents)
.where(
and(
eq(boardEvents.companyId, companyId),
gt(boardEvents.seq, afterSeq),
inArray(boardEvents.channelId, accessibleChannelIds),
),
);
const matchingIds = eventIssueRows
.map((r) => r.issueId)
.filter((id): id is string => Boolean(id));
if (matchingIds.length === 0) {
return {
kind: "channel",
channel: channelDisplay,
items: [],
cursor: await getLatestCompanyEventCursor(db, companyId),
};
}
issueConditions.push(inArray(issues.id, matchingIds));
} else if (isUuidLike(afterTrimmed)) {
const refIssue = await resolveIssueByIdOrIdentifier(
db,
afterTrimmed,
companyId,
);
issueConditions.push(gt(issues.createdAt, refIssue.createdAt));
} else {
const parsedDate = Date.parse(afterTrimmed);
if (!Number.isFinite(parsedDate)) {
throw badRequest(`Invalid 'after' cursor '${afterTrimmed}'`, {
error: "invalid_cursor",
code: "invalid_cursor",
});
}
issueConditions.push(gt(issues.updatedAt, new Date(parsedDate)));
}
}
const snapshotCursor = await getLatestCompanyEventCursor(db, companyId);
const candidateRows = await db
.select()
.from(issues)
.where(and(...issueConditions))
.orderBy(desc(issues.createdAt), desc(issues.id))
.limit(limit);
const pageViews = await loadHeadlessIssueViews(db, candidateRows);
const pageIssueIds = pageViews.map((v) => v.id);
const replyCounts = new Map<string, number>();
const latestReplies = new Map<string, CommentView>();
if (pageIssueIds.length > 0) {
const commentRows = await db
.select()
.from(issueComments)
.where(
and(
eq(issueComments.companyId, companyId),
inArray(issueComments.issueId, pageIssueIds),
isNull(issueComments.deletedAt),
),
)
.orderBy(desc(issueComments.createdAt), desc(issueComments.id));
const identifierByIssueId = new Map(
pageViews.map((v) => [v.id, v.identifier]),
);
const cursorByIssueId = new Map(pageViews.map((v) => [v.id, v.cursor]));
for (const c of commentRows) {
replyCounts.set(c.issueId, (replyCounts.get(c.issueId) ?? 0) + 1);
if (!latestReplies.has(c.issueId)) {
latestReplies.set(
c.issueId,
serializeCommentView(
c,
identifierByIssueId.get(c.issueId) ?? c.issueId,
cursorByIssueId.get(c.issueId) ?? "evt_0",
),
);
}
}
}
const items: ChannelPage["items"] = pageViews.map((view) => ({
...view,
replyCount: replyCounts.get(view.id) ?? 0,
latestReply: latestReplies.get(view.id) ?? null,
}));
return {
kind: "channel",
channel: channelDisplay,
items,
cursor: snapshotCursor,
};
}