mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Headless channels, fenced task queues, `@paperclipai/shared/sdk`, and the `pc` CLI landed in #23330 to coordinate multi-agent swarms and inbox/queue patterns. > - Real multi-stage workflows immediately hit gaps: there was no `assign` command to push existing channel posts to managed agents, no atomic `handoff`/`move` across channels with CAS labels and lease release, `claim --ready` could not opt into `backlog`/`in_review` or `--assignee me`, there was no `cancel`/`reopen` or mid-flight `--needs` dependency linking, and `pc channels` could not update queue config, manage private members, or bind event-driven managed pools. > - Without these primitives, operators had to drop back to raw `issue update` calls or non-atomic two-step scripts that race on crash. > - This pull request adds the complete workflow lifecycle across shared schemas, modular server services/routes, SDK methods, `pc` CLI commands, and the `.agents/skills/channels-queues-and-workflows` skill. > - The benefit is end-to-end single-command support for inbox triage, single-thread relays, chained channel assembly lines, mid-flight DAG dependencies, and Day-2 graduation to managed Paperclip agent pools. ## Linked Issues or Issue Description Refs #23330 **Subsystem affected** Cross-cutting (multiple of the above) **Problem or motivation** Building multi-agent queues and chained workflows on Paperclip channels required workarounds: assigning an existing post to a registered agent required raw `issue update --assignee-agent-id <uuid>`; moving an issue across stage channels with a label update and lease release required non-atomic multi-step calls; triage or review workers could not opt into claiming `backlog`, `in_review`, or their own assigned tasks (`--mine`); tasks could not be cancelled, reopened, or given mid-flight `--needs` blockers; and channels lacked CLI/API administration for `queueConfig`, private `channel_access_members`, and `managedPool` auto-dispatch. **Proposed solution** Add cohesive REST endpoints, modular services (`headless-task-workflows.ts`, `headless-channel-admin.ts`), SDK methods, `pc` CLI subcommands, and the `channels-queues-and-workflows` skill covering `assign`, `handoff`/`move`, `cancel`, `reopen`, `block --needs`/`deps`, opt-in `claim --status`/`--assignee`, and `channels update`/`members` with event-driven `managedPool` dispatch. **Alternatives considered** Leaving these operations to raw `PATCH /api/issues/:id` calls was rejected because it bypasses fenced claim tokens (`claimEpoch` + `claimToken`), lacks atomic channel+label+lease transactions, and does not enforce CAS preconditions or dependency cycle checks. **Roadmap alignment** Directly extends the headless channels and queues coordination primitive introduced in #23330. ## What Changed - **Shared schemas & SDK (`packages/shared/src/headless/`, `packages/shared/src/sdk/`):** - Added pure zero-zod constants `CLAIMABLE_TASK_STATUSES` and `TASK_CLAIM_ASSIGNEE_MODES` in `pure.ts`, upgraded `TaskClaimRequestSchema` (`status`/`statuses`, `assignee`) and `TaskReleaseSchema` (`status`, `channel`, `labels`, `unsetLabels`), and added `TaskAssignSchema`, `TaskHandoffSchema`, `TaskCancelSchema`, `TaskReopenSchema`, `TaskDependenciesMutationSchema`, `updateChannelInputSchema`, and `channelMemberInputSchema`. - Added `task.assigned`, `task.handed_off`, `task.cancelled`, `task.reopened`, and `task.dependencies_changed` to `BOARD_EVENT_TYPES`. - Exposed matching SDK methods on `paperclip().tasks`, `ClaimedTask`, and `paperclip().channels`. - **Server services & routes (`server/src/services/`, `server/src/routes/`):** - Upgraded `claimTask` and `releaseTaskClaim` in `headless-task-queue.ts` to support opt-in `status` (`todo`, `backlog`, `in_review` excluding pending interactions), `assignee` (`unassigned`, `me`, `any`), and atomic channel/label/status updates on release. - Added `server/src/services/headless-task-workflows.ts` implementing `assignTask`, `handoffTask`, `cancelTask`, `reopenTask`, `listTaskDependencies`, and `mutateTaskDependencies` (with BFS cycle detection and fenced lease release). - Added `server/src/services/headless-channel-admin.ts` implementing `updateChannel`, `listChannelMembers`, `addChannelMember`, `removeChannelMember`, and event-driven `dispatchManagedChannelPool` (zero idle polling). - Wired routes in `headless-queues-events.ts` and `headless-channels-schemas.ts`. - **CLI (`cli/src/commands/board/`):** - Added `cli/src/commands/board/tasks-workflows.ts` (`pc tasks assign`, `handoff`/`move`, `cancel`, `reopen`, `deps list|add|remove`). - Upgraded `pc tasks claim`/`run` (`--status`, `--assignee`, `--mine`), `pc tasks release` (`--channel`, `--label`, `--unset`, `--status`), `pc tasks block` (`--needs`), and `pc channels` (`update`/`config`, `members list|add|remove`). - **Skill & Tests:** - Added `.agents/skills/channels-queues-and-workflows/SKILL.md` and `examples.md`. - Added `server/src/__tests__/headless-task-workflows.test.ts` and updated `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/shared build && pnpm --filter @paperclipai/server typecheck && pnpm --filter paperclipai typecheck` — passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/headless-task-workflows.test.ts src/__tests__/headless-queues-leases-events.test.ts src/__tests__/headless-channels-schemas-batch.test.ts src/__tests__/headless-e2e-sdk-cli.test.ts` — 4 files, 27 tests passed. - `pnpm --filter @paperclipai/shared exec vitest run src/headless/headless.test.ts src/sdk/sdk.test.ts` — 2 files, 20 tests passed. - Live headless CLI test-drive (`pc up --port 3299` in isolated `PAPERCLIP_HOME`) verifying `agent connect`, `post`, `tasks assign`, `tasks claim --mine`, `tasks handoff`, `tasks release --status in_review`, `tasks claim --status in_review`, `tasks block --needs`, `tasks deps list`, blocker completion auto-unblock, `tasks cancel`, `tasks reopen`, `tasks claim --status backlog`, `channels members add/list/remove`, and `channels update --managed-pool` — all 11 scenarios passed. ## Risks - Low risk. No database migrations are required; existing `channels.queue_config`, `channel_access_members`, `issue_relations`, and `issues` lease columns are reused. - Default `claim --ready` behavior (`status = todo`, `assignee = unassigned`) is unchanged; `--status` and `--assignee` are strictly opt-in, and `--assignee me`/`any` never allows claiming tasks assigned to another agent or user. - Note on file size: `server/src/services/headless-task-queue.ts` and `cli/src/commands/board/tasks.ts` were already over 1,000 lines before this PR; all new workflow/admin operations were placed in dedicated sibling modules (`headless-task-workflows.ts`, `headless-channel-admin.ts`, `tasks-workflows.ts`) to keep existing files bounded. ## Model Used - Google Gemini (Antigravity agentic runtime, Gemini 4 Neon Medium, extended thinking with tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
1447 lines
41 KiB
TypeScript
1447 lines
41 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 { assertCanConfigureManagedPool } from "./headless-managed-pool.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 assertChannelPathWritePreconditions(
|
|
dbOrTx: DbOrTx,
|
|
companyId: string,
|
|
actor: HeadlessActorContext,
|
|
rawPath: string,
|
|
): Promise<{
|
|
normalizedPath: string;
|
|
existingChannel: typeof channels.$inferSelect | null;
|
|
hasPrivateAncestor: boolean;
|
|
}> {
|
|
const normalized = normalizeChannelPathOrThrow(rawPath, {
|
|
allowSubtreePrefix: false,
|
|
});
|
|
enforceHeadlessScopes(actor, { channelPath: normalized.path });
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
|
|
const [existing] = await dbOrTx
|
|
.select()
|
|
.from(channels)
|
|
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
|
|
.limit(1);
|
|
if (existing) {
|
|
if (existing.archivedAt !== null) {
|
|
throw notFound(`Channel '${normalized.path}' not found`);
|
|
}
|
|
if (existing.visibility === "private") {
|
|
await assertChannelAccess(dbOrTx, existing, actor);
|
|
}
|
|
return {
|
|
normalizedPath: normalized.path,
|
|
existingChannel: existing,
|
|
hasPrivateAncestor,
|
|
};
|
|
}
|
|
|
|
return {
|
|
normalizedPath: normalized.path,
|
|
existingChannel: null,
|
|
hasPrivateAncestor,
|
|
};
|
|
}
|
|
|
|
export async function ensureChannel(
|
|
dbOrTx: DbOrTx,
|
|
companyId: string,
|
|
actor: HeadlessActorContext,
|
|
input: EnsureChannelInput | CreateChannelInput,
|
|
opts: { allowUpdateExisting?: boolean; publications?: ActivityPublication[] } = {},
|
|
): Promise<typeof channels.$inferSelect> {
|
|
const { normalizedPath, hasPrivateAncestor } =
|
|
await assertChannelPathWritePreconditions(dbOrTx, companyId, actor, input.path);
|
|
const normalized = { path: normalizedPath };
|
|
|
|
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",
|
|
});
|
|
}
|
|
|
|
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 [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") {
|
|
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");
|
|
}
|
|
|
|
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";
|
|
|
|
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,
|
|
};
|
|
}
|